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(sheet): add defined name api (#4282)
Univerfb9bfcda25d3
diff --git a/packages/engine-formula/src/commands/mutations/set-defined-name.mutation.ts b/packages/engine-formula/src/commands/mutations/set-defined-name.mutation.tsindex fa20a3051a..cac4ba3679 100644--- a/packages/engine-formula/src/commands/mutations/set-defined-name.mutation.ts+++ b/packages/engine-formula/src/commands/mutations/set-defined-name.mutation.ts@@ -59,11 +59,37 @@ export const SetDefinedNameMutationFactory = (export const SetDefinedNameMutation: IMutation<ISetDefinedNameMutationParam> = {id: 'formula.mutation.set-defined-name',type: CommandType.MUTATION,- handler: () => true,+ handler: (accessor, params) => {+ if (params == null) {+ return false;+ }++ const definedNamesService = accessor.get(IDefinedNamesService);+ const { id, unitId, name, formulaOrRefString, comment, hidden, localSheetId } = params as ISetDefinedNameMutationParam;+ definedNamesService.registerDefinedName(unitId, {+ id,+ name: name.trim(),+ formulaOrRefString: formulaOrRefString.trim(),+ comment: comment?.trim(),+ hidden,+ localSheetId,+ });++ return true;+ },};export const RemoveDefinedNameMutation: IMutation<ISetDefinedNameMutationParam> = {id: 'formula.mutation.remove-defined-name',type: CommandType.MUTATION,- handler: () => true,+ handler: (accessor, params) => {+ if (params == null) {+ return false;+ }+ const definedNamesService = accessor.get(IDefinedNamesService);+ const { unitId, id } = params as ISetDefinedNameMutationSearchParam;+ definedNamesService.removeDefinedName(unitId, id);++ return true;+ },};diff --git a/packages/engine-formula/src/controller/set-defined-name.controller.ts b/packages/engine-formula/src/controller/set-defined-name.controller.tsdeleted file mode 100644index 9ce75b9a1b..0000000000--- a/packages/engine-formula/src/controller/set-defined-name.controller.ts+++ /dev/null@@ -1,69 +0,0 @@-/**- * 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 { ICommandInfo } from '@univerjs/core';-import type {- ISetDefinedNameMutationParam,- ISetDefinedNameMutationSearchParam,-} from '../commands/mutations/set-defined-name.mutation';--import { Disposable, ICommandService } from '@univerjs/core';-import { RemoveDefinedNameMutation, SetDefinedNameMutation } from '../commands/mutations/set-defined-name.mutation';-import { IDefinedNamesService } from '../services/defined-names.service';--export class SetDefinedNameController extends Disposable {- constructor(- @ICommandService private readonly _commandService: ICommandService,- @IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService- ) {- super();-- this._initialize();- }-- private _initialize(): void {- this._commandExecutedListener();- }-- private _commandExecutedListener() {- this.disposeWithMe(- this._commandService.onCommandExecuted((command: ICommandInfo) => {- if (command.id === SetDefinedNameMutation.id) {- const params = command.params as ISetDefinedNameMutationParam;- if (params == null) {- return;- }- const { id, unitId, name, formulaOrRefString, comment, hidden, localSheetId } = params;- this._definedNamesService.registerDefinedName(unitId, {- id,- name: name.trim(),- formulaOrRefString: formulaOrRefString.trim(),- comment: comment?.trim(),- hidden,- localSheetId,- });- } else if (command.id === RemoveDefinedNameMutation.id) {- const params = command.params as ISetDefinedNameMutationSearchParam;- if (params == null) {- return;- }- const { unitId, id } = params;- this._definedNamesService.removeDefinedName(unitId, id);- }- })- );- }-}diff --git a/packages/engine-formula/src/facade/f-formula.ts b/packages/engine-formula/src/facade/f-formula.tsindex c9e3735580..c1bcc57d5c 100644--- a/packages/engine-formula/src/facade/f-formula.ts+++ b/packages/engine-formula/src/facade/f-formula.ts@@ -107,14 +107,14 @@ export class FFormula extends FBase {}/**- * Set the maximum number of iterations for the formula calculation.+ * When a formula contains a circular reference, set the maximum number of iterations for the formula calculation.* @param maxIteration The maximum number of iterations. The default value is 1.* @example- * @example* ```ts- * // The code below moves the active sheet to the specified index+ * // Set the maximum number of iterations for the formula calculation to 5.+ * // The default value is 1.* const formulaEngine = univerAPI.getFormula();- * formulaEngine.maxIteration(5);+ * formulaEngine.setMaxIteration(5);* ```*/setMaxIteration(maxIteration: number): void {diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.tsindex 187ac8893d..466e41f355 100644--- a/packages/engine-formula/src/index.ts+++ b/packages/engine-formula/src/index.ts@@ -59,7 +59,6 @@ export { type ISetFormulaDataMutationParams, SetFormulaDataMutation } from './coexport { type IRemoveOtherFormulaMutationParams, type ISetOtherFormulaMutationParams, RemoveOtherFormulaMutation, SetOtherFormulaMutation } from './commands/mutations/set-other-formula.mutation';export { RemoveSuperTableMutation, SetSuperTableMutation, SetSuperTableOptionMutation } from './commands/mutations/set-super-table.mutation';export { CalculateController } from './controller/calculate.controller';-export { SetDefinedNameController } from './controller/set-defined-name.controller';export { Lexer } from './engine/analysis/lexer';export { LexerNode } from './engine/analysis/lexer-node';export { LexerTreeBuilder } from './engine/analysis/lexer-tree-builder';diff --git a/packages/engine-formula/src/plugin.ts b/packages/engine-formula/src/plugin.tsindex d09ac79f85..1a4bf792ff 100644--- a/packages/engine-formula/src/plugin.ts+++ b/packages/engine-formula/src/plugin.ts@@ -20,7 +20,6 @@ import { IConfigService, Inject, Injector, Plugin, touchDependencies } from '@unimport { CalculateController } from './controller/calculate.controller';import { defaultPluginConfig, ENGINE_FORMULA_PLUGIN_CONFIG_KEY } from './controller/config.schema';import { FormulaController } from './controller/formula.controller';-import { SetDefinedNameController } from './controller/set-defined-name.controller';import { SetDependencyController } from './controller/set-dependency.controller';import { SetFeatureCalculationController } from './controller/set-feature-calculation.controller';import { SetOtherFormulaController } from './controller/set-other-formula.controller';@@ -80,7 +79,6 @@ export class UniverFormulaEnginePlugin extends Plugin {override onReady(): void {touchDependencies(this._injector, [[FormulaController],- [SetDefinedNameController],[SetSuperTableController],]);@@ -120,7 +118,6 @@ export class UniverFormulaEnginePlugin extends Plugin {//Controllers[FormulaController],- [SetDefinedNameController],[SetSuperTableController],];diff --git a/packages/facade/src/apis/__tests__/create-test-bed.ts b/packages/facade/src/apis/__tests__/create-test-bed.tsindex 4ec397ae9a..97ee8fcb46 100644--- a/packages/facade/src/apis/__tests__/create-test-bed.ts+++ b/packages/facade/src/apis/__tests__/create-test-bed.ts@@ -32,7 +32,7 @@ import {UniverInstanceType,} from '@univerjs/core';import { UniverDataValidationPlugin } from '@univerjs/data-validation';-import { ActiveDirtyManagerService, FormulaDataModel, FunctionService, IActiveDirtyManagerService, IFunctionService, LexerTreeBuilder } from '@univerjs/engine-formula';+import { ActiveDirtyManagerService, DefinedNamesService, FormulaDataModel, FunctionService, IActiveDirtyManagerService, IDefinedNamesService, IFunctionService, LexerTreeBuilder } from '@univerjs/engine-formula';import { Engine, IRenderingEngine, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import { ISocketService, WebSocketService } from '@univerjs/network';import {@@ -175,6 +175,7 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:injector.add([WorksheetProtectionPointModel]);injector.add([RangeProtectionRuleModel]);injector.add([WorksheetProtectionRuleModel]);+ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);const renderManagerService = injector.get(IRenderManagerService);renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, [SheetSkeletonManagerService] as Dependency);diff --git a/packages/facade/src/apis/sheets/__tests__/create-worksheet-test-bed.ts b/packages/facade/src/apis/sheets/__tests__/create-worksheet-test-bed.tsindex 2fd756ddeb..d95e471c0b 100644--- a/packages/facade/src/apis/sheets/__tests__/create-worksheet-test-bed.ts+++ b/packages/facade/src/apis/sheets/__tests__/create-worksheet-test-bed.ts@@ -32,7 +32,7 @@ import {UniverInstanceType,} from '@univerjs/core';import { UniverDataValidationPlugin } from '@univerjs/data-validation';-import { ActiveDirtyManagerService, FormulaDataModel, FunctionService, IActiveDirtyManagerService, IFunctionService, LexerTreeBuilder } from '@univerjs/engine-formula';+import { ActiveDirtyManagerService, DefinedNamesService, FormulaDataModel, FunctionService, IActiveDirtyManagerService, IDefinedNamesService, IFunctionService, LexerTreeBuilder } from '@univerjs/engine-formula';import { Engine, IRenderingEngine, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import { ISocketService, WebSocketService } from '@univerjs/network';import {@@ -168,6 +168,7 @@ export function createWorksheetTestBed(workbookData?: IWorkbookData, dependencieinjector.add([WorksheetProtectionPointModel]);injector.add([RangeProtectionRuleModel]);injector.add([WorksheetProtectionRuleModel]);+ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);const renderManagerService = injector.get(IRenderManagerService);renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, [SheetSkeletonManagerService] as Dependency);diff --git a/packages/facade/src/apis/sheets/__tests__/f-defined-name.spec.ts b/packages/facade/src/apis/sheets/__tests__/f-defined-name.spec.tsnew file mode 100644index 0000000000..a0f118f2b3--- /dev/null+++ b/packages/facade/src/apis/sheets/__tests__/f-defined-name.spec.ts@@ -0,0 +1,104 @@+/**+ * 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 { ICellData, Injector, Nullable } from '@univerjs/core';+import type { FUniver } from '../../everything';+import { ICommandService, IUniverInstanceService } from '@univerjs/core';+import { RemoveDefinedNameMutation, SetDefinedNameMutation } from '@univerjs/engine-formula';+import { RemoveDefinedNameCommand, SetDefinedNameCommand } from '@univerjs/sheets';+import { beforeEach, describe, expect, it } from 'vitest';+import { createFacadeTestBed } from '../../__tests__/create-test-bed';++describe('Test FDefinedName', () => {+ let get: Injector['get'];+ let commandService: ICommandService;+ let univerAPI: FUniver;+ let getValueByPosition: (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ) => Nullable<ICellData>;++ beforeEach(() => {+ const testBed = createFacadeTestBed();+ get = testBed.get;+ univerAPI = testBed.univerAPI;++ commandService = get(ICommandService);+ commandService.registerCommand(RemoveDefinedNameCommand);+ commandService.registerCommand(SetDefinedNameMutation);+ commandService.registerCommand(RemoveDefinedNameMutation);+ commandService.registerCommand(SetDefinedNameCommand);++ getValueByPosition = (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ): Nullable<ICellData> =>+ get(IUniverInstanceService)+ .getUniverSheetInstance('test')+ ?.getSheetBySheetId('sheet1')+ ?.getRange(startRow, startColumn, endRow, endColumn)+ .getValue();+ });++ it('defined name insertDefinedName', () => {+ const activeSpreadsheet = univerAPI.getActiveWorkbook()!;+ activeSpreadsheet.insertDefinedName('test1', 'A1');+ const definedName = activeSpreadsheet.getDefinedName('test1');+ expect(definedName?.getName()).eq('test1');+ });++ it('defined name getDefinedNames', () => {+ const activeSpreadsheet = univerAPI.getActiveWorkbook()!;+ activeSpreadsheet.insertDefinedName('test', 'A1');+ activeSpreadsheet.insertDefinedName('test1', '=SUM(A1)');+ activeSpreadsheet.insertDefinedName('test2', '=A1');+ activeSpreadsheet.insertDefinedName('test3', 'A1:B10');+ expect(activeSpreadsheet.getDefinedNames().length).toBe(4);+ });++ it('defined name deleteDefinedName', () => {+ const activeSpreadsheet = univerAPI.getActiveWorkbook()!;+ activeSpreadsheet.insertDefinedName('test', 'A1');+ activeSpreadsheet.insertDefinedName('test1', '=SUM(A1)');+ activeSpreadsheet.insertDefinedName('test2', '=A1');+ activeSpreadsheet.insertDefinedName('test3', 'A1:B10');++ activeSpreadsheet.deleteDefinedName('test2');+ activeSpreadsheet.deleteDefinedName('test3');++ expect(activeSpreadsheet.getDefinedNames().length).toBe(2);+ });++ it('defined name insertDefinedNameBuilder', () => {+ const builder = univerAPI.newDefinedName();+ const param = builder.setName('test').setFormula('A1').setComment('test comment').setHidden(true).build();+ const activeSpreadsheet = univerAPI.getActiveWorkbook()!;+ activeSpreadsheet.insertDefinedNameBuilder(param);+ const definedName = activeSpreadsheet.getDefinedName('test');+ expect(definedName?.getComment()).eq('test comment');+ });++ it('defined name updateDefinedName', () => {+ const activeSpreadsheet = univerAPI.getActiveWorkbook()!;+ const sheet = activeSpreadsheet.getActiveSheet();+ sheet.insertDefinedName('test11', 'A1');+ expect(activeSpreadsheet.getDefinedName('test11')?.getLocalSheetId()).eq(sheet.getSheetId());+ });+});diff --git a/packages/facade/src/apis/sheets/__tests__/f-workbook.spec.ts b/packages/facade/src/apis/sheets/__tests__/f-workbook.spec.tsindex 35b189ec84..fc8d785025 100644--- a/packages/facade/src/apis/sheets/__tests__/f-workbook.spec.ts+++ b/packages/facade/src/apis/sheets/__tests__/f-workbook.spec.ts@@ -16,8 +16,8 @@import type { ICellData, Injector, Nullable } from '@univerjs/core';import type { FUniver } from '../../everything';-import { ICommandService, IUniverInstanceService } from '@univerjs/core';-import { InsertSheetCommand, InsertSheetMutation, RemoveSheetCommand, RemoveSheetMutation, SetHorizontalTextAlignCommand, SetRangeValuesCommand, SetRangeValuesMutation, SetStyleCommand, SetTextWrapCommand, SetVerticalTextAlignCommand, SetWorksheetActiveOperation } from '@univerjs/sheets';+import { ICommandService, IUniverInstanceService, LocaleType } from '@univerjs/core';+import { CopySheetCommand, InsertSheetCommand, InsertSheetMutation, RemoveSheetCommand, RemoveSheetMutation, SetHorizontalTextAlignCommand, SetRangeValuesCommand, SetRangeValuesMutation, SetStyleCommand, SetTextWrapCommand, SetVerticalTextAlignCommand, SetWorksheetActiveOperation, SetWorksheetOrderCommand, SetWorksheetOrderMutation } from '@univerjs/sheets';import { beforeEach, describe, expect, it } from 'vitest';import { createFacadeTestBed } from '../../__tests__/create-test-bed';@@ -49,6 +49,9 @@ describe('Test FWorkbook', () => {commandService.registerCommand(SetWorksheetActiveOperation);commandService.registerCommand(RemoveSheetCommand);commandService.registerCommand(RemoveSheetMutation);+ commandService.registerCommand(CopySheetCommand);+ commandService.registerCommand(SetWorksheetOrderCommand);+ commandService.registerCommand(SetWorksheetOrderMutation);getValueByPosition = (startRow: number,@@ -74,7 +77,7 @@ describe('Test FWorkbook', () => {expect(activeSheet).not.toBeNull();});- it('Workbook insertSheet, deleteSheet, and setActiveSheet', () => {+ it('Workbook insertSheet, deleteSheet, and setActiveSheet', async () => {const workbook = univerAPI.getActiveWorkbook();// insert a new sheet@@ -93,7 +96,24 @@ describe('Test FWorkbook', () => {expect(activeSheet?.getSheetName()).toBe('sheet1');// delete the active sheet- workbook?.deleteSheet(activeSheet!);+ await workbook?.deleteSheet(activeSheet!);expect(workbook?.getSheets().length).toBe(1);});++ it('Workbook deleteActiveSheet', async () => {+ const activeSpreadsheet = univerAPI.getActiveWorkbook()!;+ activeSpreadsheet.insertSheet();+ expect(activeSpreadsheet.getNumSheets()).toBe(2);+ await activeSpreadsheet.deleteActiveSheet();+ expect(activeSpreadsheet.getNumSheets()).toBe(1);+ activeSpreadsheet.setActiveSheet(activeSpreadsheet.getSheets()[0]);+ await activeSpreadsheet.duplicateActiveSheet();+ expect(activeSpreadsheet.getNumSheets()).toBe(2);+ activeSpreadsheet.setLocale(LocaleType.RU_RU);+ expect(activeSpreadsheet.getLocale()).toBe(LocaleType.RU_RU);+ const worksheet = activeSpreadsheet.getActiveSheet();+ expect(worksheet.getIndex()).toBe(0);+ await activeSpreadsheet.moveActiveSheet(1);+ expect(worksheet.getIndex()).toBe(1);+ });});diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/update-defined-name.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/update-defined-name.controller.spec.tsindex 6e41e8478f..ac0c060356 100644--- a/packages/sheets-formula-ui/src/controllers/__tests__/update-defined-name.controller.spec.ts+++ b/packages/sheets-formula-ui/src/controllers/__tests__/update-defined-name.controller.spec.ts@@ -17,7 +17,7 @@import type { ICellData, Injector, IWorkbookData, Nullable, Univer } from '@univerjs/core';import type { IDeleteRangeMoveLeftCommandParams, IDeleteRangeMoveUpCommandParams, IInsertColCommandParams, IInsertRowCommandParams, IMoveColsCommandParams, IMoveRangeCommandParams, IMoveRowsCommandParams, InsertRangeMoveDownCommandParams, InsertRangeMoveRightCommandParams, IRemoveRowColCommandParams, IRemoveSheetCommandParams, ISetWorksheetNameCommandParams } from '@univerjs/sheets';import { Direction, ICommandService, IUniverInstanceService, LocaleType, RANGE_TYPE, RedoCommand, UndoCommand } from '@univerjs/core';-import { IDefinedNamesService, RemoveDefinedNameMutation, SetArrayFormulaDataMutation, SetDefinedNameController, SetDefinedNameMutation, SetFormulaDataMutation } from '@univerjs/engine-formula';+import { IDefinedNamesService, RemoveDefinedNameMutation, SetArrayFormulaDataMutation, SetDefinedNameMutation, SetFormulaDataMutation } from '@univerjs/engine-formula';import { DeleteRangeMoveLeftCommand, DeleteRangeMoveUpCommand, InsertColCommand, InsertColMutation, InsertRangeMoveDownCommand, InsertRangeMoveRightCommand, InsertRowCommand, InsertRowMutation, MoveColsCommand, MoveColsMutation, MoveRangeCommand, MoveRangeMutation, MoveRowsCommand, MoveRowsMutation, RemoveColCommand, RemoveColMutation, RemoveRowCommand, RemoveRowMutation, RemoveSheetCommand, RemoveSheetMutation, SetDefinedNameCommand, SetRangeValuesCommand, SetRangeValuesMutation, SetSelectionsOperation, SetWorksheetNameCommand, SetWorksheetNameMutation, SheetsSelectionsService } from '@univerjs/sheets';import { UpdateDefinedNameController } from '@univerjs/sheets-formula';@@ -67,13 +67,11 @@ describe('Test update defined name', () => {beforeEach(() => {const testBed = createCommandTestBed(TEST_WORKBOOK_DATA_DEMO(), [[UpdateDefinedNameController],- [SetDefinedNameController],]);univer = testBed.univer;get = testBed.get;get(UpdateDefinedNameController);- get(SetDefinedNameController);commandService = get(ICommandService);commandService.registerCommand(MoveRangeCommand);diff --git a/packages/sheets-formula/src/controllers/defined-name.controller.ts b/packages/sheets-formula/src/controllers/defined-name.controller.tsindex e8132ec995..4931d96a29 100644--- a/packages/sheets-formula/src/controllers/defined-name.controller.ts+++ b/packages/sheets-formula/src/controllers/defined-name.controller.ts@@ -24,12 +24,10 @@ import {UniverInstanceType,} from '@univerjs/core';import { FunctionType, IDefinedNamesService, RemoveDefinedNameMutation, SetDefinedNameMutation } from '@univerjs/engine-formula';-import { SetWorksheetActiveOperation } from '@univerjs/sheets';+import { SCOPE_WORKBOOK_VALUE_DEFINED_NAME, SetWorksheetActiveOperation } from '@univerjs/sheets';import { IDescriptionService } from '../services/description.service';-export const SCOPE_WORKBOOK_VALUE = 'AllDefaultWorkbook';-/*** header highlight* column menu: show, hover and mousedown event@@ -106,7 +104,7 @@ export class DefinedNameController extends Disposable {}const { name, comment, formulaOrRefString, localSheetId } = param;- if (!this._descriptionService.hasDescription(name) && (localSheetId == null || localSheetId === SCOPE_WORKBOOK_VALUE || localSheetId === sheetId)) {+ if (!this._descriptionService.hasDescription(name) && (localSheetId == null || localSheetId === SCOPE_WORKBOOK_VALUE_DEFINED_NAME || localSheetId === sheetId)) {this._descriptionService.registerDescriptions([{functionName: name,description: formulaOrRefString + (comment || ''),@@ -178,7 +176,7 @@ export class DefinedNameController extends Disposable {Array.from(Object.values(definedNames)).forEach((value) => {const { name, comment, formulaOrRefString, localSheetId } = value;- if (!this._descriptionService.hasDescription(name) && (localSheetId == null || localSheetId === SCOPE_WORKBOOK_VALUE || localSheetId === sheetId)) {+ if (!this._descriptionService.hasDescription(name) && (localSheetId == null || localSheetId === SCOPE_WORKBOOK_VALUE_DEFINED_NAME || localSheetId === sheetId)) {functionList.push({functionName: name,description: formulaOrRefString + (comment || ''),@@ -208,7 +206,7 @@ export class DefinedNameController extends Disposable {Array.from(Object.values(definedNames)).forEach((value) => {const { name, localSheetId } = value;- if (localSheetId !== SCOPE_WORKBOOK_VALUE && localSheetId !== sheetId) {+ if (localSheetId !== SCOPE_WORKBOOK_VALUE_DEFINED_NAME && localSheetId !== sheetId) {functionList.push(name);}});diff --git a/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx b/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsxindex 06c877020e..b3bb63f266 100644--- a/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx+++ b/packages/sheets-ui/src/views/defined-name/DefinedNameContainer.tsx@@ -21,10 +21,9 @@ import { ICommandService, IUniverInstanceService, LocaleService, Tools, UniverInimport { Confirm, Tooltip } from '@univerjs/design';import { IDefinedNamesService, serializeRangeWithSheet } from '@univerjs/engine-formula';import { CheckMarkSingle, DeleteSingle, IncreaseSingle } from '@univerjs/icons';-import { InsertDefinedNameCommand, RemoveDefinedNameCommand, SetDefinedNameCommand, SetWorksheetShowCommand, SheetsSelectionsService } from '@univerjs/sheets';+import { InsertDefinedNameCommand, RemoveDefinedNameCommand, SCOPE_WORKBOOK_VALUE_DEFINED_NAME, SetDefinedNameCommand, SetWorksheetShowCommand, SheetsSelectionsService } from '@univerjs/sheets';import clsx from 'clsx';import React, { useEffect, useState } from 'react';-import { SCOPE_WORKBOOK_VALUE } from './component-name';import { DefinedNameInput } from './DefinedNameInput';import styles from './index.module.less';@@ -188,7 +187,7 @@ export const DefinedNameContainer = () => {<div className={styles.definedNameContainerItemName}>{definedName.name}<span className={styles.definedNameContainerItemNameForSheet}>- {(definedName.localSheetId === SCOPE_WORKBOOK_VALUE || definedName.localSheetId == null) ? '' : getSheetNameBySheetId(definedName.localSheetId)}+ {(definedName.localSheetId === SCOPE_WORKBOOK_VALUE_DEFINED_NAME || definedName.localSheetId == null) ? '' : getSheetNameBySheetId(definedName.localSheetId)}</span></div><div className={styles.definedNameContainerItemFormulaOrRefString}>{definedName.formulaOrRefString}</div>diff --git a/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx b/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsxindex 7d920212df..ac09efe87d 100644--- a/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx+++ b/packages/sheets-ui/src/views/defined-name/DefinedNameInput.tsx@@ -21,11 +21,11 @@ import { Button, Input, Radio, RadioGroup, Select } from '@univerjs/design';import { IDefinedNamesService, type IDefinedNamesServiceParam, IFunctionService, isReferenceStrings, isReferenceStringWithEffectiveColumn, LexerTreeBuilder, operatorToken } from '@univerjs/engine-formula';import { hasCJKText } from '@univerjs/engine-render';import { ErrorSingle } from '@univerjs/icons';+import { SCOPE_WORKBOOK_VALUE_DEFINED_NAME } from '@univerjs/sheets';import { ComponentManager, useSidebarClick } from '@univerjs/ui';import React, { useEffect, useMemo, useRef, useState } from 'react';-import { EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, RANGE_SELECTOR_COMPONENT_KEY } from '../../common/keys';-import { SCOPE_WORKBOOK_VALUE } from './component-name';+import { EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, RANGE_SELECTOR_COMPONENT_KEY } from '../../common/keys';import styles from './index.module.less';export interface IDefinedNameInputProps extends Omit<IDefinedNamesServiceParam, 'id'> {@@ -51,7 +51,7 @@ export const DefinedNameInput = (props: IDefinedNameInputProps) => {name,formulaOrRefString,comment = '',- localSheetId = SCOPE_WORKBOOK_VALUE,+ localSheetId = SCOPE_WORKBOOK_VALUE_DEFINED_NAME,hidden = false, // 是否对用户隐藏,与excel兼容,暂时用不上。id,@@ -93,7 +93,7 @@ export const DefinedNameInput = (props: IDefinedNameInputProps) => {const options = [{label: localeService.t('definedName.scopeWorkbook'),- value: SCOPE_WORKBOOK_VALUE,+ value: SCOPE_WORKBOOK_VALUE_DEFINED_NAME,}];const isFormula = (token: string) => {diff --git a/packages/sheets-ui/src/views/defined-name/component-name.ts b/packages/sheets-ui/src/views/defined-name/component-name.tsindex 8595f8e23f..313f6a7672 100644--- a/packages/sheets-ui/src/views/defined-name/component-name.ts+++ b/packages/sheets-ui/src/views/defined-name/component-name.ts@@ -15,5 +15,3 @@*/export const DEFINED_NAME_CONTAINER = 'DefinedNameContainer';--export const SCOPE_WORKBOOK_VALUE = 'AllDefaultWorkbook';diff --git a/packages/sheets/src/controllers/defined-name-data.controller.ts b/packages/sheets/src/controllers/defined-name-data.controller.tsindex 59a9bbcd78..de28c481e7 100644--- a/packages/sheets/src/controllers/defined-name-data.controller.ts+++ b/packages/sheets/src/controllers/defined-name-data.controller.ts@@ -24,6 +24,8 @@ import { IDefinedNamesService } from '@univerjs/engine-formula';const SHEET_DEFINED_NAME_PLUGIN = 'SHEET_DEFINED_NAME_PLUGIN';+export const SCOPE_WORKBOOK_VALUE_DEFINED_NAME = 'AllDefaultWorkbook';+export class DefinedNameDataController extends Disposable {constructor(@IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService,diff --git a/packages/sheets/src/facade/f-defined-name.ts b/packages/sheets/src/facade/f-defined-name.tsnew file mode 100644index 0000000000..5305e11d93--- /dev/null+++ b/packages/sheets/src/facade/f-defined-name.ts@@ -0,0 +1,446 @@+/**+ * 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 { FWorksheet } from './f-worksheet';+import { FBase, generateRandomId, IAuthzIoService, ICommandService, Inject, Injector, IPermissionService, LocaleService } from '@univerjs/core';+import { IDefinedNamesService, type ISetDefinedNameMutationParam, serializeRange } from '@univerjs/engine-formula';+import { RangeProtectionRuleModel, RemoveDefinedNameCommand, SCOPE_WORKBOOK_VALUE_DEFINED_NAME, SetDefinedNameCommand, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';++function getDefinedNameFieldName(unitId: string, localeService: LocaleService, definedNamesService: IDefinedNamesService): string {+ const definedNameMap = definedNamesService.getDefinedNameMap(unitId);+ if (definedNameMap == null) {+ return localeService.t('definedName.defaultName') + 1;+ }+ const definedNames = Array.from(Object.values(definedNameMap));+ const count = definedNames.length + 1;+ const name = localeService.t('definedName.defaultName') + count;+ if (definedNamesService.getValueByName(unitId, name) == null) {+ return name;+ }++ let i = count + 1;+ while (true) {+ const newName = localeService.t('definedName.defaultName') + i;+ if (definedNamesService.getValueByName(unitId, newName) == null) {+ return newName;+ }+ i++;+ }+}++export class FDefinedNameBuilder {+ private _definedNameParam: ISetDefinedNameMutationParam;+ constructor() {+ this._definedNameParam = {+ id: generateRandomId(10),+ unitId: '',+ name: '',+ formulaOrRefString: '',+ };+ }++ /**+ * Sets the name of the defined name builder.+ * @param name The name of the defined name.+ * @returns The defined name builder.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedNameBuilder = UniverAPI.newDefinedName()+ * .setName('MyDefinedName')+ * .build();+ * workbook.insertDefinedNameBuilder(definedNameBuilder);+ * ```+ */+ setName(name: string): FDefinedNameBuilder {+ this._definedNameParam.name = name;+ return this;+ }++ /**+ * Sets the formula of the defined name builder.+ * @param formula The formula of the defined name.+ * @returns The defined name builder.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedNameBuilder = UniverAPI.newDefinedName()+ * .setFormula('SUM(Sheet1!$A$1)')+ * .setName('MyDefinedName')+ * .build();+ * workbook.insertDefinedNameBuilder(definedNameBuilder);+ * ```+ */+ setFormula(formula: string): FDefinedNameBuilder {+ this._definedNameParam.formulaOrRefString = `=${formula}`;+ return this;+ }++ /**+ * Sets the reference of the defined name builder.+ * @param refString The reference of the defined name.+ * @returns The defined name builder.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedNameBuilder = UniverAPI.newDefinedName()+ * .setRef('Sheet1!$A$1')+ * .build();+ * workbook.insertDefinedNameBuilder(definedNameBuilder);+ * ```+ */+ setRef(a1Notation: string): FDefinedNameBuilder {+ this._definedNameParam.formulaOrRefString = a1Notation;+ return this;+ }++ /**+ * Sets the reference of the defined name builder by range .+ * @param row The start row of the range.+ * @param column The start column of the range.+ * @param numRows The number of rows in the range.+ * @param numColumns The number of columns in the range.+ * @returns The defined name builder.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedNameBuilder = UniverAPI.newDefinedName()+ * .setRefByRange(1, 3, 2, 5)+ * .build();+ * workbook.insertDefinedNameBuilder(definedNameBuilder);+ * ```+ */+ setRefByRange(row: number, column: number, numRows: number, numColumns: number): FDefinedNameBuilder {+ this._definedNameParam.formulaOrRefString = serializeRange({+ startRow: row,+ endRow: row + (numRows ?? 1) - 1,+ startColumn: column,+ endColumn: column + (numColumns ?? 1) - 1,+ });+ return this;+ }++ /**+ * Sets the comment of the defined name builder.+ * @param comment The comment of the defined name.+ * @returns The defined name builder.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedNameBuilder = UniverAPI.newDefinedName()+ * .setComment('This is a comment')+ * .build();+ * workbook.insertDefinedNameBuilder(definedNameBuilder);+ * ```+ */+ setComment(comment: string): FDefinedNameBuilder {+ this._definedNameParam.comment = comment;+ return this;+ }++ /**+ * Sets the hidden status of the defined name builder.+ * @param hidden The hidden status of the defined name.+ * @returns The defined name builder.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedNameBuilder = UniverAPI.newDefinedName()+ * .setHidden(true)+ * .build();+ * workbook.insertDefinedNameBuilder(definedNameBuilder);+ * ```+ */+ setHidden(hidden: boolean): FDefinedNameBuilder {+ this._definedNameParam.hidden = hidden;+ return this;+ }++ /**+ * Builds the defined name.+ * @returns The defined name mutation parameter.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedNameBuilder = UniverAPI.newDefinedName()+ * .setRef('Sheet1!$A$1')+ * .setName('MyDefinedName')+ * .build();+ * workbook.insertDefinedNameBuilder(definedNameBuilder);+ * ```+ */+ build(): ISetDefinedNameMutationParam {+ return this._definedNameParam;+ }++ load(param: ISetDefinedNameMutationParam): FDefinedNameBuilder {+ this._definedNameParam = param;+ return this;+ }+}++export class FDefinedName extends FBase {+ constructor(+ protected _definedNameParam: ISetDefinedNameMutationParam,+ @Inject(Injector) protected readonly _injector: Injector,+ @ICommandService protected readonly _commandService: ICommandService,+ @IPermissionService protected readonly _permissionService: IPermissionService,+ @Inject(WorksheetProtectionRuleModel) protected readonly _worksheetProtectionRuleModel: WorksheetProtectionRuleModel,+ @Inject(RangeProtectionRuleModel) protected readonly _rangeProtectionRuleModel: RangeProtectionRuleModel,+ @Inject(WorksheetProtectionPointModel) protected readonly _worksheetProtectionPointRuleModel: WorksheetProtectionPointModel,+ @Inject(IAuthzIoService) protected readonly _authzIoService: IAuthzIoService,+ @Inject(LocaleService) protected readonly _localeService: LocaleService,+ @IDefinedNamesService protected readonly _definedNamesService: IDefinedNamesService+ ) {+ super();+ }++ private _apply(): void {+ if (this._definedNameParam.name === '') {+ this._definedNameParam.name = getDefinedNameFieldName(this._definedNameParam.unitId, this._localeService, this._definedNamesService);+ }+ this._commandService.syncExecuteCommand(SetDefinedNameCommand.id, this._definedNameParam);+ }++ /**+ * Gets the name of the defined name.+ * @returns The name of the defined name.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedName = workbook.getDefinedNames[0];+ * console.log(definedName.getName());+ * ```+ */+ getName(): string {+ return this._definedNameParam.name;+ }++ /**+ * Sets the name of the defined name.+ * @param name The name of the defined name.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedName = workbook.getDefinedName('MyDefinedName');+ * definedName.setName('NewDefinedName');+ * ```+ */+ setName(name: string): void {+ this._definedNameParam.name = name;+ this._apply();+ }++ /**+ * Sets the formula of the defined name.+ * @param formula The formula of the defined name.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedName = workbook.getDefinedName('MyDefinedName');+ * definedName.setFormula('SUM(Sheet1!$A$1)');+ * ```+ */+ setFormula(formula: string): void {+ this._definedNameParam.formulaOrRefString = `=${formula}`;+ this._apply();+ }++ /**+ * Sets the reference of the defined name.+ * @param refString The reference of the defined name.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedName = workbook.getDefinedNames[0];+ * definedName.setRef('Sheet1!$A$1');+ * ```+ */+ setRef(refString: string): void {+ this._definedNameParam.formulaOrRefString = refString;+ this._apply();+ }++ /**+ * Gets the reference of the defined name.+ * @returns The reference of the defined name.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedName = workbook.getDefinedNames[0];+ * console.log(definedName.getFormulaOrRefString());+ * ```+ */+ getFormulaOrRefString(): string {+ return this._definedNameParam.formulaOrRefString;+ }++ /**+ * Sets the reference of the defined name by range.+ * @param row The start row of the range.+ * @param column The start column of the range.+ * @param numRows The number of rows in the range.+ * @param numColumns The number of columns in the range.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedName = workbook.getDefinedNames[0];+ * definedName.setRefByRange(1, 3, 2, 5);+ * ```+ */+ setRefByRange(row: number, column: number, numRows: number, numColumns: number): void {+ this._definedNameParam.formulaOrRefString = serializeRange({+ startRow: row,+ endRow: row + (numRows ?? 1) - 1,+ startColumn: column,+ endColumn: column + (numColumns ?? 1) - 1,+ });+ this._apply();+ }++ /**+ * Gets the comment of the defined name.+ * @returns The comment of the defined name.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedName = workbook.getDefinedNames[0];+ * console.log(definedName.getComment());+ * ```+ */+ getComment(): string | undefined {+ return this._definedNameParam.comment;+ }++ /**+ * Sets the comment of the defined name.+ * @param comment The comment of the defined name.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedName = workbook.getDefinedNames[0];+ * definedName.setComment('This is a comment');+ * ```+ */+ setComment(comment: string): void {+ this._definedNameParam.comment = comment;+ this._apply();+ }++ /**+ * Sets the scope of the defined name to the worksheet.+ * @param worksheet The worksheet to set the scope to.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const worksheet = workbook.getWorksheets[0];+ * const definedName = workbook.getDefinedNames[0];+ * definedName.setScopeToWorksheet(worksheet);+ * ```+ */+ setScopeToWorksheet(worksheet: FWorksheet): void {+ this._definedNameParam.localSheetId = worksheet.getSheetId();+ this._apply();+ }++ /**+ * Sets the scope of the defined name to the workbook.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedName = workbook.getDefinedNames[0];+ * definedName.setScopeToWorkbook();+ * ```+ */+ setScopeToWorkbook(): void {+ this._definedNameParam.localSheetId = SCOPE_WORKBOOK_VALUE_DEFINED_NAME;+ this._apply();+ }++ /**+ * Sets the hidden status of the defined name.+ * @param hidden The hidden status of the defined name.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedName = workbook.getDefinedNames[0];+ * definedName.setHidden(true);+ * ```+ */+ setHidden(hidden: boolean): void {+ this._definedNameParam.hidden = hidden;+ this._apply();+ }++ /**+ * Deletes the defined name.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedName = workbook.getDefinedNames[0];+ * definedName.delete();+ * ```+ */+ delete(): void {+ this._commandService.syncExecuteCommand(RemoveDefinedNameCommand.id, this._definedNameParam);+ }++ /**+ * Gets the local sheet id of the defined name.+ * @returns The local sheet id of the defined name.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedName = workbook.getDefinedNames[0];+ * console.log(definedName.getLocalSheetId());+ * ```+ */+ getLocalSheetId(): string | undefined {+ return this._definedNameParam.localSheetId;+ }++ /**+ * Checks if the defined name is in the workbook scope.+ * @returns True if the defined name is in the workbook scope, false otherwise.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedName = workbook.getDefinedNames[0];+ * console.log(definedName.isWorkbookScope());+ * ```+ */+ isWorkbookScope(): boolean {+ return this._definedNameParam.localSheetId === SCOPE_WORKBOOK_VALUE_DEFINED_NAME;+ }++ /**+ * Converts the defined name to a defined name builder.+ * @returns The defined name builder.+ * @example+ * ```ts+ * const workbook = UniverAPI.getActiveWorkbook();+ * const definedName = workbook.getDefinedNames[0];+ * const definedNameBuilder = definedName.toBuilder();+ * const param definedNameBuilder.setName('NewDefinedName').setFormula('SUM(Sheet1!$A$1)').build();+ * workbook.updateDefinedNameBuilder(param);+ * ```+ */+ toBuilder(): FDefinedNameBuilder {+ const builder = this._injector.createInstance(FDefinedNameBuilder);+ builder.load(this._definedNameParam);+ return builder;+ }+}diff --git a/packages/sheets/src/facade/f-univer.ts b/packages/sheets/src/facade/f-univer.tsindex 587576e173..483e3166f1 100644--- a/packages/sheets/src/facade/f-univer.ts+++ b/packages/sheets/src/facade/f-univer.ts@@ -16,6 +16,7 @@import type { IDisposable, IWorkbookData, Workbook } from '@univerjs/core';import { FUniver, IUniverInstanceService, toDisposable, UniverInstanceType } from '@univerjs/core';+import { FDefinedNameBuilder } from './f-defined-name';import { FPermission } from './f-permission';import { FWorkbook } from './f-workbook';@@ -51,6 +52,12 @@ export interface IFUniverSheetsMixin {* Register a callback that will be triggered when a Univer Sheet is created.*/onUniverSheetCreated(callback: (workbook: FWorkbook) => void): IDisposable;++ /**+ * Create a new defined name builder.+ * @returns {FDefinedNameBuilder} - The defined name builder.+ */+ newDefinedName(): FDefinedNameBuilder;}export class FUniverSheetsMixin extends FUniver implements IFUniverSheetsMixin {@@ -90,6 +97,10 @@ export class FUniverSheetsMixin extends FUniver implements IFUniverSheetsMixin {return toDisposable(subscription);}++ override newDefinedName(): FDefinedNameBuilder {+ return this._injector.createInstance(FDefinedNameBuilder);+ }}FUniver.extend(FUniverSheetsMixin);diff --git a/packages/sheets/src/facade/f-workbook.ts b/packages/sheets/src/facade/f-workbook.tsindex cd21d9be9c..2330c07e3c 100644--- a/packages/sheets/src/facade/f-workbook.ts+++ b/packages/sheets/src/facade/f-workbook.ts@@ -15,9 +15,12 @@*/import type { CommandListener, ICommandInfo, IDisposable, IRange, IWorkbookData, LocaleType, Workbook } from '@univerjs/core';+import type { ISetDefinedNameMutationParam } from '@univerjs/engine-formula';import type { ISetSelectionsOperationParams, ISheetCommandSharedParams } from '@univerjs/sheets';import { FBase, ICommandService, ILogService, Inject, Injector, IPermissionService, IResourceLoaderService, IUniverInstanceService, LocaleService, mergeWorksheetSnapshotWithDefault, RedoCommand, toDisposable, UndoCommand, UniverInstanceType } from '@univerjs/core';-import { CopySheetCommand, getPrimaryForRange, InsertSheetCommand, RemoveSheetCommand, SetSelectionsOperation, SetWorksheetActiveOperation, SetWorksheetOrderCommand, SheetsSelectionsService, WorkbookEditablePermission } from '@univerjs/sheets';+import { IDefinedNamesService } from '@univerjs/engine-formula';+import { CopySheetCommand, getPrimaryForRange, InsertSheetCommand, RemoveSheetCommand, SCOPE_WORKBOOK_VALUE_DEFINED_NAME, SetDefinedNameCommand, SetSelectionsOperation, SetWorksheetActiveOperation, SetWorksheetOrderCommand, SheetsSelectionsService, WorkbookEditablePermission } from '@univerjs/sheets';+import { FDefinedName, FDefinedNameBuilder } from './f-defined-name';import { FPermission } from './f-permission';import { FRange } from './f-range';import { FWorksheet } from './f-worksheet';@@ -34,7 +37,8 @@ export class FWorkbook extends FBase {@ICommandService protected readonly _commandService: ICommandService,@IPermissionService protected readonly _permissionService: IPermissionService,@ILogService protected readonly _logService: ILogService,- @Inject(LocaleService) protected readonly _localeService: LocaleService+ @Inject(LocaleService) protected readonly _localeService: LocaleService,+ @IDefinedNamesService protected readonly _definedNamesService: IDefinedNamesService) {super();@@ -288,10 +292,10 @@ export class FWorkbook extends FBase {* activeSpreadsheet.deleteSheet(sheet);* ```*/- deleteSheet(sheet: FWorksheet): void {+ deleteSheet(sheet: FWorksheet): Promise<boolean> {const unitId = this.id;const subUnitId = sheet.getSheetId();- this._commandService.executeCommand(RemoveSheetCommand.id, {+ return this._commandService.executeCommand(RemoveSheetCommand.id, {unitId,subUnitId,});@@ -480,14 +484,15 @@ export class FWorkbook extends FBase {* const sheet = univerAPI.getActiveWorkbook().deleteActiveSheet();* ```*/- deleteActiveSheet(): void {+ deleteActiveSheet(): Promise<boolean> {const sheet = this.getActiveSheet();- this.deleteSheet(sheet);+ return this.deleteSheet(sheet);}/*** Duplicates the given worksheet.* @param {FWorksheet} sheet The worksheet to duplicate.+ * @returns {Promise<boolean>} true if the sheet was duplicated, false otherwise* @example* ```ts* // The code below duplicates the given worksheet@@ -496,8 +501,8 @@ export class FWorkbook extends FBase {* activeSpreadsheet.duplicateSheet(activeSheet);* ```*/- duplicateSheet(sheet: FWorksheet): void {- this._commandService.syncExecuteCommand(CopySheetCommand.id, {+ duplicateSheet(sheet: FWorksheet): Promise<boolean> {+ return this._commandService.executeCommand(CopySheetCommand.id, {unitId: sheet.getWorkbook().getUnitId(),subUnitId: sheet.getSheetId(),});@@ -505,6 +510,7 @@ export class FWorkbook extends FBase {/*** Duplicates the active sheet.+ * @returns {Promise<boolean>} true if the sheet was duplicated, false otherwise* @example* ```ts* // The code below duplicates the active sheet@@ -512,9 +518,9 @@ export class FWorkbook extends FBase {* activeSpreadsheet.duplicateActiveSheet();* ```*/- duplicateActiveSheet(): void {+ duplicateActiveSheet(): Promise<boolean> {const sheet = this.getActiveSheet();- this.duplicateSheet(sheet);+ return this.duplicateSheet(sheet);}/**@@ -587,7 +593,7 @@ export class FWorkbook extends FBase {* activeSpreadsheet.moveSheet(sheet, 1);* ```*/- async moveSheet(sheet: FWorksheet, index: number): Promise<boolean> {+ moveSheet(sheet: FWorksheet, index: number): Promise<boolean> {let sheetIndexVal = index;if (sheetIndexVal < 0) {sheetIndexVal = 0;@@ -612,7 +618,7 @@ export class FWorkbook extends FBase {* activeSpreadsheet.moveActiveSheet(1);* ```*/- async moveActiveSheet(index: number): Promise<boolean> {+ moveActiveSheet(index: number): Promise<boolean> {const sheet = this.getActiveSheet();return this.moveSheet(sheet, index);}@@ -625,4 +631,117 @@ export class FWorkbook extends FBase {getPermission(): FPermission {return this._injector.createInstance(FPermission);}++ /**+ * Get the defined name by name.+ * @param {string} name The name of the defined name to get+ * @returns {FDefinedName | null} The defined name with the given name+ * @example+ * ```ts+ * // The code below gets the defined name by name+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();+ * const definedName = activeSpreadsheet.getDefinedName('MyDefinedName');+ * ```+ */+ getDefinedName(name: string): FDefinedName | null {+ const definedName = this._definedNamesService.getValueByName(this.id, name);+ if (!definedName) {+ return null;+ }++ return this._injector.createInstance(FDefinedName, { ...definedName, unitId: this.id });+ }++ /**+ * Get all the defined names in the workbook.+ * @returns {FDefinedName[]} All the defined names in the workbook+ * @example+ * ```ts+ * // The code below gets all the defined names in the workbook+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();+ * const definedNames = activeSpreadsheet.getDefinedNames();+ * ```+ */+ getDefinedNames(): FDefinedName[] {+ const definedNames = this._definedNamesService.getDefinedNameMap(this.id);+ if (!definedNames) {+ return [];+ }+ return Object.values(definedNames).map((definedName) => {+ return this._injector.createInstance(FDefinedName, { ...definedName, unitId: this.id });+ });+ }++ /**+ * Insert a defined name.+ * @param {string} name The name of the defined name to insert+ * @param {string} formulaOrRefString The formula(=sum(A2:b10)) or reference(A1) string of the defined name to insert+ * @example+ * ```ts+ * // The code below inserts a defined name+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();+ * activeSpreadsheet.insertDefinedName('MyDefinedName', 'Sheet1!A1');+ * ```+ */+ insertDefinedName(name: string, formulaOrRefString: string): void {+ const definedNameBuilder = this._injector.createInstance(FDefinedNameBuilder);+ const param = definedNameBuilder.setName(name).setRef(formulaOrRefString).build();+ param.localSheetId = SCOPE_WORKBOOK_VALUE_DEFINED_NAME;+ this.insertDefinedNameBuilder(param);+ }++ /**+ * Delete the defined name with the given name.+ * @param {string} name The name of the defined name to delete+ * @returns {boolean} true if the defined name was deleted, false otherwise+ * @example+ * ```ts+ * // The code below deletes the defined name with the given name+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();+ * const deleted = activeSpreadsheet.deleteDefinedName('MyDefinedName');+ * ```+ */+ deleteDefinedName(name: string): boolean {+ const definedName = this.getDefinedName(name);+ if (definedName) {+ definedName.delete();+ return true;+ }++ return false;+ }++ /**+ * insert a defined name by builder param+ * @param {ISetDefinedNameMutationParam} param The param to insert the defined name+ * @example+ * ```ts+ * // The code below inserts a defined name by builder param+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();+ * const builder = univerAPI.newDefinedName();+ * const param = builder.setName('MyDefinedName').setRef('Sheet1!A1').build();+ * activeSpreadsheet.insertDefinedNameBuilder(param);+ * ```+ */+ insertDefinedNameBuilder(param: ISetDefinedNameMutationParam): void {+ param.unitId = this.getId();+ this._commandService.syncExecuteCommand(SetDefinedNameCommand.id, param);+ }++ /**+ * Update the defined name with the given name.+ * @param {ISetDefinedNameMutationParam} param The param to insert the defined name+ * @example+ * ```ts+ * // The code below updates the defined name with the given name+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();+ * const builder = activeSpreadsheet.getDefinedName('MyDefinedName').toBuilder();+ * builder.setRef('Sheet1!A2').setName('MyDefinedName1').build();+ * activeSpreadsheet.updateDefinedNameBuilder(param);+ *+ * ```+ */+ updateDefinedNameBuilder(param: ISetDefinedNameMutationParam): void {+ this._commandService.syncExecuteCommand(SetDefinedNameCommand.id, param);+ }}diff --git a/packages/sheets/src/facade/f-worksheet.ts b/packages/sheets/src/facade/f-worksheet.tsindex 01a3a2428e..80e118e785 100644--- a/packages/sheets/src/facade/f-worksheet.ts+++ b/packages/sheets/src/facade/f-worksheet.ts@@ -16,10 +16,12 @@import type { CustomData, ICellData, IColumnData, IDisposable, IFreeze, IObjectArrayPrimitiveType, IRange, IRowData, IStyleData, Nullable, Workbook, Worksheet } from '@univerjs/core';import type { ISetColDataCommandParams, ISetGridlinesColorCommandParams, ISetRangeValuesMutationParams, ISetRowDataCommandParams, IToggleGridlinesCommandParams } from '@univerjs/sheets';+import type { FDefinedName } from './f-defined-name';import type { FWorkbook } from './f-workbook';import { BooleanNumber, Direction, FBase, ICommandService, Inject, Injector, ObjectMatrix, RANGE_TYPE } from '@univerjs/core';import { deserializeRangeWithSheet } from '@univerjs/engine-formula';import { CancelFrozenCommand, ClearSelectionAllCommand, ClearSelectionContentCommand, ClearSelectionFormatCommand, copyRangeStyles, InsertColCommand, InsertRowCommand, MoveColsCommand, MoveRowsCommand, RemoveColCommand, RemoveRowCommand, SetColDataCommand, SetColHiddenCommand, SetColWidthCommand, SetFrozenCommand, SetGridlinesColorCommand, SetRangeValuesMutation, SetRowDataCommand, SetRowHeightCommand, SetRowHiddenCommand, SetSpecificColsVisibleCommand, SetSpecificRowsVisibleCommand, SetTabColorCommand, SetWorksheetDefaultStyleMutation, SetWorksheetHideCommand, SetWorksheetNameCommand, SetWorksheetRowIsAutoHeightCommand, SetWorksheetShowCommand, SheetsSelectionsService, ToggleGridlinesCommand } from '@univerjs/sheets';+import { FDefinedNameBuilder } from './f-defined-name';import { FRange } from './f-range';import { FSelection } from './f-selection';import { covertToColRange, covertToRowRange } from './utils';@@ -1532,4 +1534,39 @@ export class FWorksheet extends FBase {}return false;}++ /*+ * Insert a defined name for worksheet.+ * @param {string} name The name of the defined name to insert+ * @param {string} formulaOrRefString The formula(=sum(A2:b10)) or reference(A1) string of the defined name to insert+ * @example+ * ```ts+ * // The code below inserts a defined name+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();+ * const sheet1 = activeSpreadsheet.getSheetByName('Sheet1');+ * sheet1.insertDefinedName('MyDefinedName', 'Sheet1!A1');+ * ```+ */+ insertDefinedName(name: string, formulaOrRefString: string): void {+ const definedNameBuilder = this._injector.createInstance(FDefinedNameBuilder);+ const param = definedNameBuilder.setName(name).setRef(formulaOrRefString).build();+ param.localSheetId = this.getSheetId();+ this._fWorkbook.insertDefinedNameBuilder(param);+ }++ /**+ * Get all the defined names in the worksheet.+ * @returns {FDefinedName[]} All the defined names in the worksheet+ * @example+ * ```ts+ * // The code below gets all the defined names in the worksheet+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();+ * const sheet1 = activeSpreadsheet.getSheetByName('Sheet1');+ * const definedNames = sheet1.getDefinedNames();+ * ```+ */+ getDefinedNames(): FDefinedName[] {+ const names = this._fWorkbook.getDefinedNames();+ return names.filter((name) => name.getLocalSheetId() === this.getSheetId());+ }}diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.tsindex bf59d8e19b..faba482646 100644--- a/packages/sheets/src/index.ts+++ b/packages/sheets/src/index.ts@@ -420,5 +420,5 @@ export { ScrollToCellOperation } from './commands/operations/scroll-to-cell.operexport { type ISetSelectionsOperationParams, SetSelectionsOperation } from './commands/operations/selection.operation';export { type ISetWorksheetActiveOperationParams, SetWorksheetActiveOperation } from './commands/operations/set-worksheet-active.operation';export { type IToggleCellCheckboxCommandParams, ToggleCellCheckboxCommand } from './commands/commands/toggle-checkbox.command';-+export { SCOPE_WORKBOOK_VALUE_DEFINED_NAME } from './controllers/defined-name-data.controller';// #endregion