Skip to content

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

feat(sheet): add facade api (#4279)

Univer50db7a3e1f23
diff --git a/packages/engine-formula/src/basics/common.ts b/packages/engine-formula/src/basics/common.ts
index 45f404e819..79d6cb90ca 100644
--- a/packages/engine-formula/src/basics/common.ts
+++ b/packages/engine-formula/src/basics/common.ts
@@ -190,6 +190,7 @@ export interface IFormulaDatasetConfig {
allUnitData?: IUnitData;
unitStylesData?: IUnitStylesData;
unitSheetNameMap?: IUnitSheetNameMap;
+ maxIteration?: number;
}
export enum ConcatenateType {
diff --git a/packages/engine-formula/src/controller/calculate.controller.ts b/packages/engine-formula/src/controller/calculate.controller.ts
index 4fea92d069..b945fcdfea 100644
--- a/packages/engine-formula/src/controller/calculate.controller.ts
+++ b/packages/engine-formula/src/controller/calculate.controller.ts
@@ -31,6 +31,7 @@ import {
import { FormulaDataModel } from '../models/formula-data.model';
import { ICalculateFormulaService } from '../services/calculate-formula.service';
import { FormulaExecutedStateType, type IAllRuntimeData } from '../services/runtime.service';
+import { DEFAULT_CYCLE_REFERENCE_COUNT } from './config.schema';
export class CalculateController extends Disposable {
constructor(
@@ -76,7 +77,7 @@ export class CalculateController extends Disposable {
private async _calculate(
formulaDirtyData: Partial<IFormulaDirtyData>
) {
- const { forceCalculation: forceCalculate = false, dirtyRanges = [], dirtyNameMap = {}, dirtyDefinedNameMap = {}, dirtyUnitFeatureMap = {}, dirtyUnitOtherFormulaMap = {}, clearDependencyTreeCache = {} } = formulaDirtyData;
+ const { forceCalculation: forceCalculate = false, dirtyRanges = [], dirtyNameMap = {}, dirtyDefinedNameMap = {}, dirtyUnitFeatureMap = {}, dirtyUnitOtherFormulaMap = {}, clearDependencyTreeCache = {}, maxIteration = DEFAULT_CYCLE_REFERENCE_COUNT } = formulaDirtyData;
const formulaData = this._formulaDataModel.getFormulaData();
@@ -96,6 +97,7 @@ export class CalculateController extends Disposable {
dirtyUnitFeatureMap,
dirtyUnitOtherFormulaMap,
clearDependencyTreeCache,
+ maxIteration,
});
}
diff --git a/packages/engine-formula/src/controller/config.schema.ts b/packages/engine-formula/src/controller/config.schema.ts
index 2ae45fa331..29c1ab6086 100644
--- a/packages/engine-formula/src/controller/config.schema.ts
+++ b/packages/engine-formula/src/controller/config.schema.ts
@@ -20,6 +20,10 @@ import type { BaseFunction } from '../functions/base-function';
export const ENGINE_FORMULA_PLUGIN_CONFIG_KEY = 'engine-formula.config';
+export const DEFAULT_CYCLE_REFERENCE_COUNT = 1;
+
+export const ENGINE_FORMULA_CYCLE_REFERENCE_COUNT = 'CYCLE_REFERENCE_COUNT';
+
export const configSymbol = Symbol(ENGINE_FORMULA_PLUGIN_CONFIG_KEY);
export interface IUniverEngineFormulaConfig {
diff --git a/packages/engine-formula/src/facade/f-formula.ts b/packages/engine-formula/src/facade/f-formula.ts
index be42a26754..c9e3735580 100644
--- a/packages/engine-formula/src/facade/f-formula.ts
+++ b/packages/engine-formula/src/facade/f-formula.ts
@@ -16,8 +16,8 @@
import type { ICommandInfo, IDisposable } from '@univerjs/core';
import type { FormulaExecutedStateType, IExecutionInProgressParams, ISetFormulaCalculationNotificationMutation, ISetFormulaCalculationStartMutation } from '@univerjs/engine-formula';
-import { FBase, ICommandService, Inject, Injector } from '@univerjs/core';
-import { SetFormulaCalculationNotificationMutation, SetFormulaCalculationStartMutation, SetFormulaCalculationStopMutation } from '@univerjs/engine-formula';
+import { FBase, ICommandService, IConfigService, Inject, Injector } from '@univerjs/core';
+import { ENGINE_FORMULA_CYCLE_REFERENCE_COUNT, SetFormulaCalculationNotificationMutation, SetFormulaCalculationStartMutation, SetFormulaCalculationStopMutation } from '@univerjs/engine-formula';
/**
* This interface class provides methods to modify the behavior of the operation formula.
@@ -25,7 +25,8 @@ import { SetFormulaCalculationNotificationMutation, SetFormulaCalculationStartMu
export class FFormula extends FBase {
constructor(
@Inject(ICommandService) private readonly _commandService: ICommandService,
- @Inject(Injector) protected readonly _injector: Injector
+ @Inject(Injector) protected readonly _injector: Injector,
+ @IConfigService protected readonly _configService: IConfigService
) {
super();
}
@@ -104,4 +105,19 @@ export class FFormula extends FBase {
}
});
}
+
+ /**
+ * 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
+ * const formulaEngine = univerAPI.getFormula();
+ * formulaEngine.maxIteration(5);
+ * ```
+ */
+ setMaxIteration(maxIteration: number): void {
+ this._configService.setConfig(ENGINE_FORMULA_CYCLE_REFERENCE_COUNT, maxIteration);
+ }
}
diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.ts
index ee4094350b..187ac8893d 100644
--- a/packages/engine-formula/src/index.ts
+++ b/packages/engine-formula/src/index.ts
@@ -164,7 +164,7 @@ export { FormulaDependencyTreeVirtual } from './engine/dependency/dependency-tre
export { generateAstNode } from './engine/utils/generate-ast-node';
export { type IFeatureCalculationManagerParam } from './services/feature-calculation-manager.service';
export { DEFAULT_INTERVAL_COUNT } from './services/calculate-formula.service';
-export { ENGINE_FORMULA_PLUGIN_CONFIG_KEY, type IUniverEngineFormulaConfig } from './controller/config.schema';
+export { ENGINE_FORMULA_CYCLE_REFERENCE_COUNT, ENGINE_FORMULA_PLUGIN_CONFIG_KEY, type IUniverEngineFormulaConfig } from './controller/config.schema';
export { generateRandomDependencyTreeId } from './engine/dependency/formula-dependency';
export { DependencyManagerBaseService } from './services/dependency-manager.service';
diff --git a/packages/engine-formula/src/services/calculate-formula.service.ts b/packages/engine-formula/src/services/calculate-formula.service.ts
index 7df8dd71a5..1f66490ea7 100644
--- a/packages/engine-formula/src/services/calculate-formula.service.ts
+++ b/packages/engine-formula/src/services/calculate-formula.service.ts
@@ -38,7 +38,7 @@ import {
import { Subject } from 'rxjs';
import { ErrorType } from '../basics/error-type';
import { CELL_INVERTED_INDEX_CACHE } from '../basics/inverted-index-cache';
-import { ENGINE_FORMULA_PLUGIN_CONFIG_KEY } from '../controller/config.schema';
+import { DEFAULT_CYCLE_REFERENCE_COUNT, ENGINE_FORMULA_PLUGIN_CONFIG_KEY } from '../controller/config.schema';
import { Lexer } from '../engine/analysis/lexer';
import { AstTreeBuilder } from '../engine/analysis/parser';
import { ErrorNode } from '../engine/ast-node/base-ast-node';
@@ -48,8 +48,6 @@ import { FORMULA_REF_TO_ARRAY_CACHE, type FunctionVariantType } from '../engine/
import { IFormulaCurrentConfigService } from './current-data.service';
import { FormulaExecuteStageType, IFormulaRuntimeService } from './runtime.service';
-export const DEFAULT_CYCLE_REFERENCE_COUNT = 1;
-
export const DEFAULT_INTERVAL_COUNT = 500;
export const CYCLE_REFERENCE_COUNT = 'cycleReferenceCount';
@@ -124,8 +122,7 @@ export class CalculateFormulaService extends Disposable {
this._runtimeService.reset();
- const cycleReferenceCount = (this._configService.getConfig('CYCLE_REFERENCE_COUNT') ||
- DEFAULT_CYCLE_REFERENCE_COUNT) as number;
+ const cycleReferenceCount = (formulaDatasetConfig.maxIteration || DEFAULT_CYCLE_REFERENCE_COUNT) as number;
for (let i = 0; i < cycleReferenceCount; i++) {
this._runtimeService.setFormulaCycleIndex(i);
diff --git a/packages/engine-formula/src/services/current-data.service.ts b/packages/engine-formula/src/services/current-data.service.ts
index 30e02a616c..4fb7297044 100644
--- a/packages/engine-formula/src/services/current-data.service.ts
+++ b/packages/engine-formula/src/services/current-data.service.ts
@@ -43,6 +43,7 @@ export interface IFormulaDirtyData {
dirtyUnitFeatureMap: IDirtyUnitFeatureMap;
dirtyUnitOtherFormulaMap: IDirtyUnitOtherFormulaMap;
clearDependencyTreeCache: IDirtyUnitSheetNameMap; // unitId -> sheetId
+ maxIteration?: number;
}
export interface IFormulaCurrentConfigService {
diff --git a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
index 7b2fb49b7a..a1b13f2dfc 100644
--- a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
+++ b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts
@@ -28,6 +28,7 @@ import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
import type { IUniverSheetsFormulaBaseConfig } from './config.schema';
import { Disposable, ICommandService, IConfigService, ILogService, Inject, LocaleService } from '@univerjs/core';
import {
+ ENGINE_FORMULA_CYCLE_REFERENCE_COUNT,
FormulaDataModel,
FormulaExecutedStateType,
FormulaExecuteStageType,
@@ -258,6 +259,7 @@ export class TriggerCalculationController extends Disposable {
dirtyUnitOtherFormulaMap: allDirtyUnitOtherFormulaMap,
forceCalculation: false,
clearDependencyTreeCache: allClearDependencyTreeCache,
+ maxIteration: (this._configService.getConfig(ENGINE_FORMULA_CYCLE_REFERENCE_COUNT)) as number | undefined,
// numfmtItemMap,
};
}
@@ -276,6 +278,8 @@ export class TriggerCalculationController extends Disposable {
this._mergeDirtyUnitFeatureOrOtherFormulaMap(allDirtyUnitOtherFormulaMap, dirtyData2.dirtyUnitOtherFormulaMap);
this._mergeDirtyNameMap(allClearDependencyTreeCache, dirtyData2.clearDependencyTreeCache);
+ const maxIteration = dirtyData1.maxIteration || dirtyData2.maxIteration;
+
return {
dirtyRanges: allDirtyRanges,
dirtyNameMap: allDirtyNameMap,
@@ -284,6 +288,7 @@ export class TriggerCalculationController extends Disposable {
dirtyUnitOtherFormulaMap: allDirtyUnitOtherFormulaMap,
forceCalculation: !!this._forceCalculating,
clearDependencyTreeCache: allClearDependencyTreeCache,
+ maxIteration,
};
}
@@ -512,13 +517,13 @@ export class TriggerCalculationController extends Disposable {
}
private _initialExecuteFormula() {
- const params = this._getDiryDataByCalculationMode(this._calculationMode);
+ const params = this._getDirtyDataByCalculationMode(this._calculationMode);
this._commandService.executeCommand(SetFormulaCalculationStartMutation.id, params, lo);
this._registerOtherFormulaService.calculateStarted$.next(true);
}
- private _getDiryDataByCalculationMode(calculationMode: CalculationMode): IFormulaDirtyData {
+ private _getDirtyDataByCalculationMode(calculationMode: CalculationMode): IFormulaDirtyData {
const forceCalculation = calculationMode === CalculationMode.FORCED;
// loop all sheets cell data, and get the dirty data
@@ -538,6 +543,7 @@ export class TriggerCalculationController extends Disposable {
dirtyUnitFeatureMap,
dirtyUnitOtherFormulaMap,
clearDependencyTreeCache,
+ maxIteration: this._configService.getConfig(ENGINE_FORMULA_CYCLE_REFERENCE_COUNT) as number | undefined,
};
}
}
diff --git a/packages/sheets/src/facade/f-workbook.ts b/packages/sheets/src/facade/f-workbook.ts
index 6f0631c383..ceee1d8923 100644
--- a/packages/sheets/src/facade/f-workbook.ts
+++ b/packages/sheets/src/facade/f-workbook.ts
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-import type { CommandListener, ICommandInfo, IDisposable, IRange, IWorkbookData, Workbook } from '@univerjs/core';
+import type { CommandListener, ICommandInfo, IDisposable, IRange, IWorkbookData, LocaleType, Workbook } from '@univerjs/core';
import type { ISetSelectionsOperationParams, ISheetCommandSharedParams } from '@univerjs/sheets';
-import { FBase, ICommandService, ILogService, Inject, Injector, IPermissionService, IResourceLoaderService, IUniverInstanceService, mergeWorksheetSnapshotWithDefault, RedoCommand, toDisposable, UndoCommand, UniverInstanceType } from '@univerjs/core';
-import { getPrimaryForRange, InsertSheetCommand, RemoveSheetCommand, SetSelectionsOperation, SetWorksheetActiveOperation, SheetsSelectionsService, WorkbookEditablePermission } 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 { FRange } from './f-range';
import { FWorksheet } from './f-worksheet';
@@ -32,23 +32,65 @@ export class FWorkbook extends FBase {
@IUniverInstanceService protected readonly _univerInstanceService: IUniverInstanceService,
@ICommandService protected readonly _commandService: ICommandService,
@IPermissionService protected readonly _permissionService: IPermissionService,
- @ILogService protected readonly _logService: ILogService
+ @ILogService protected readonly _logService: ILogService,
+ @Inject(LocaleService) protected readonly _localeService: LocaleService
) {
super();
this.id = this._workbook.getUnitId();
}
+ /**
+ * Get the id of the workbook.
+ * @returns {string} The id of the workbook.
+ * @example
+ * ```ts
+ * // The code below gets the id of the workbook
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const id = activeSpreadsheet.getId();
+ * ```
+ */
getId(): string {
return this.id;
}
+ /**
+ * Get the name of the workbook.
+ * @returns {string} The name of the workbook.
+ * @example
+ * ```ts
+ * // The code below gets the name of the workbook
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const name = activeSpreadsheet.getName();
+ * ```
+ */
getName(): string {
- return this._workbook.getName();
+ return this._workbook.name;
+ }
+
+ /**
+ * Set the name of the workbook.
+ * @param {string} name The new name of the workbook.
+ * @example
+ * ```ts
+ * // The code below sets the name of the workbook
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * activeSpreadsheet.setName('MyWorkbook');
+ * ```
+ */
+ setName(name: string) {
+ this._workbook.setName(name);
}
/**
* save workbook snapshot data, including conditional formatting, data validation, and other plugin data.
+ * @return Workbook snapshot data
+ * @example
+ * ```ts
+ * // The code below saves the workbook snapshot data
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const snapshot = activeSpreadsheet.save();
+ * ```
*/
save(): IWorkbookData {
const snapshot = this._resourceLoaderService.saveUnit<IWorkbookData>(this._workbook.getUnitId())!;
@@ -57,7 +99,7 @@ export class FWorkbook extends FBase {
/**
* @deprecated use 'save' instead.
- * @return {*} {IWorkbookData}
+ * @return {*} {IWorkbookData} Workbook snapshot data
* @memberof FWorkbook
*/
getSnapshot(): IWorkbookData {
@@ -68,6 +110,12 @@ export class FWorkbook extends FBase {
/**
* Get the active sheet of the workbook.
* @returns The active sheet of the workbook
+ * @example
+ * ```ts
+ * // The code below gets the active sheet of the workbook
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const activeSheet = activeSpreadsheet.getActiveSheet();
+ * ```
*/
getActiveSheet(): FWorksheet {
const activeSheet = this._workbook.getActiveSheet();
@@ -77,6 +125,12 @@ export class FWorkbook extends FBase {
/**
* Gets all the worksheets in this workbook
* @returns An array of all the worksheets in the workbook
+ * @example
+ * ```ts
+ * // The code below gets all the worksheets in the workbook
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const sheets = activeSpreadsheet.getSheets();
+ * ```
*/
getSheets(): FWorksheet[] {
return this._workbook.getSheets().map((sheet) => {
@@ -90,6 +144,12 @@ export class FWorkbook extends FBase {
* @param rows How may rows would the new sheet have
* @param column How many columns would the new sheet have
* @returns The new created sheet
+ * @example
+ * ```ts
+ * // The code below creates a new sheet
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const newSheet = activeSpreadsheet.create('MyNewSheet', 10, 10);
+ * ```
*/
create(name: string, rows: number, column: number): FWorksheet {
const newSheet = mergeWorksheetSnapshotWithDefault({});
@@ -121,6 +181,12 @@ export class FWorkbook extends FBase {
* Get a worksheet by sheet id.
* @param sheetId The id of the sheet to get.
* @return The worksheet with given sheet id
+ * @example
+ * ```ts
+ * // The code below gets a worksheet by sheet id
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const sheet = activeSpreadsheet.getSheetBySheetId('sheetId');
+ * ```
*/
getSheetBySheetId(sheetId: string): FWorksheet | null {
const worksheet = this._workbook.getSheetBySheetId(sheetId);
@@ -135,6 +201,12 @@ export class FWorkbook extends FBase {
* Get a worksheet by sheet name.
* @param name The name of the sheet to get.
* @returns The worksheet with given sheet name
+ * @example
+ * ```ts
+ * // The code below gets a worksheet by sheet name
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const sheet = activeSpreadsheet.getSheetByName('Sheet1');
+ * ```
*/
getSheetByName(name: string): FWorksheet | null {
const worksheet = this._workbook.getSheetBySheetName(name);
@@ -149,6 +221,13 @@ export class FWorkbook extends FBase {
* Sets the given worksheet to be the active worksheet in the workbook.
* @param sheet The worksheet to set as the active worksheet.
* @returns The active worksheet
+ * @example
+ * ```ts
+ * // The code below sets the given worksheet to be the active worksheet
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const sheet = activeSpreadsheet.getSheetByName('Sheet1');
+ * activeSpreadsheet.setActiveSheet(sheet);
+ * ```
*/
setActiveSheet(sheet: FWorksheet): FWorksheet {
this._commandService.syncExecuteCommand(SetWorksheetActiveOperation.id, {
@@ -162,10 +241,25 @@ export class FWorkbook extends FBase {
/**
* Inserts a new worksheet into the workbook.
* Using a default sheet name. The new sheet becomes the active sheet
+ * @param sheetName - (optional) The name of the new sheet
* @returns The new sheet
+ * @example
+ * ```ts
+ * // The code below inserts a new sheet into the workbook
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * activeSpreadsheet.insertSheet();
+ *
+ * // The code below inserts a new sheet into the workbook, using a custom name
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * activeSpreadsheet.insertSheet('MyNewSheet');
+ * ```
*/
- insertSheet(): FWorksheet {
- this._commandService.syncExecuteCommand(InsertSheetCommand.id);
+ insertSheet(sheetName?: string): FWorksheet {
+ if (sheetName != null) {
+ this._commandService.syncExecuteCommand(InsertSheetCommand.id, { sheet: { name: sheetName } });
+ } else {
+ this._commandService.syncExecuteCommand(InsertSheetCommand.id);
+ }
const unitId = this.id;
const subUnitId = this._workbook.getSheets()[this._workbook.getSheets().length - 1].getSheetId();
@@ -185,6 +279,13 @@ export class FWorkbook extends FBase {
/**
* Deletes the specified worksheet.
* @param sheet The worksheet to delete.
+ * @example
+ * ```ts
+ * // The code below deletes the specified worksheet
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const sheet = activeSpreadsheet.getSheetByName('Sheet1');
+ * activeSpreadsheet.deleteSheet(sheet);
+ * ```
*/
deleteSheet(sheet: FWorksheet): void {
const unitId = this.id;
@@ -196,21 +297,54 @@ export class FWorkbook extends FBase {
}
// #region editing
-
+ /**
+ * Undo the last action.
+ * @returns A promise that resolves to true if the undo was successful, false otherwise.
+ * @example
+ * ```ts
+ * // The code below undoes the last action
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * activeSpreadsheet.undo();
+ * ```
+ */
undo(): Promise<boolean> {
this._univerInstanceService.focusUnit(this.id);
return this._commandService.executeCommand(UndoCommand.id);
}
+ /**
+ * Redo the last undone action.
+ * @returns A promise that resolves to true if the redo was successful, false otherwise.
+ * @example
+ * ```ts
+ * // The code below redoes the last undone action
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * activeSpreadsheet.redo();
+ * ```
+ */
redo(): Promise<boolean> {
this._univerInstanceService.focusUnit(this.id);
return this._commandService.executeCommand(RedoCommand.id);
}
+ /**
+ * Callback for command execution.
+ * @callback onBeforeCommandExecuteCallback
+ * @param {ICommandInfo<ISheetCommandSharedParams>} command The command that was executed.
+ */
+
/**
* Register a callback that will be triggered before invoking a command targeting the Univer sheet.
- * @param callback the callback.
+ * @param {onBeforeCommandExecuteCallback} callback the callback.
* @returns A function to dispose the listening.
+ * @example
+ * ```ts
+ * // The code below registers a callback that will be triggered before invoking a command targeting the Univer sheet
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * activeSpreadsheet.onBeforeCommandExecute((command) => {
+ * console.log('Command executed:', command);
+ * });
+ * ```
*/
onBeforeCommandExecute(callback: CommandListener): IDisposable {
return this._commandService.beforeCommandExecuted((command) => {
@@ -222,10 +356,23 @@ export class FWorkbook extends FBase {
});
}
+ /**
+ * Callback for command execution.
+ * @callback onCommandExecutedCallback
+ * @param {ICommandInfo<ISheetCommandSharedParams>} command The command that was executed
+ */
+
/**
* Register a callback that will be triggered when a command is invoked targeting the Univer sheet.
- * @param callback the callback.
+ * @param {onCommandExecutedCallback} callback the callback.
* @returns A function to dispose the listening.
+ * @example
+ * ```ts
+ * // The code below registers a callback that will be triggered when a command is invoked targeting the Univer sheet
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * activeSpreadsheet.onCommandExecuted((command) => {
+ * console.log('Command executed:', command);
+ * });
*/
onCommandExecuted(callback: CommandListener): IDisposable {
return this._commandService.onCommandExecuted((command) => {
@@ -237,6 +384,18 @@ export class FWorkbook extends FBase {
});
}
+ /**
+ * Callback for selection changes.
+ *
+ * @callback onSelectionChangeCallback
+ * @param {IRange[]} selections The new selection.
+ */
+
+ /**
+ * Register a callback that will be triggered when the selection changes.
+ * @param {onSelectionChangeCallback} callback The callback.
+ * @returns A function to dispose the listening
+ */
onSelectionChange(callback: (selections: IRange[]) => void): IDisposable {
return toDisposable(
this._selectionManagerService.selectionMoveEnd$.subscribe((selections) => {
@@ -310,4 +469,150 @@ export class FWorkbook extends FBase {
return this._injector.createInstance(FRange, this._workbook, activeSheet, active.range);
}
+
+ /**
+ * Deletes the currently active sheet.
+ * @example
+ * ```ts
+ * // The code below deletes the currently active sheet and stores the new active
+ * // sheet in a variable
+ * const sheet = univerAPI.getActiveWorkbook().deleteActiveSheet();
+ * ```
+ */
+ deleteActiveSheet(): void {
+ const sheet = this.getActiveSheet();
+ this.deleteSheet(sheet);
+ }
+
+ /**
+ * Duplicates the given worksheet.
+ * @param {FWorksheet} sheet The worksheet to duplicate.
+ * @example
+ * ```ts
+ * // The code below duplicates the given worksheet
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const activeSheet = activeSpreadsheet.getActiveSheet();
+ * activeSpreadsheet.duplicateSheet(activeSheet);
+ * ```
+ */
+ duplicateSheet(sheet: FWorksheet) {
+ this._commandService.syncExecuteCommand(CopySheetCommand.id, {
+ unitId: sheet.getWorkbook().getUnitId(),
+ subUnitId: sheet.getSheetId(),
+ });
+ }
+
+ /**
+ * Duplicates the active sheet.
+ * @example
+ * ```ts
+ * // The code below duplicates the active sheet
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * activeSpreadsheet.duplicateActiveSheet();
+ * ```
+ */
+ duplicateActiveSheet(): void {
+ const sheet = this.getActiveSheet();
+ this.duplicateSheet(sheet);
+ }
+
+ /**
+ * Get the number of sheets in the workbook.
+ * @returns The number of sheets in the workbook
+ * @example
+ * ```ts
+ * // The code below gets the number of sheets in the workbook
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const numSheets = activeSpreadsheet.getNumSheets();
+ * ```
+ */
+ getNumSheets(): number {
+ return this._workbook.getSheets().length;
+ }
+
+ /**
+ * Get the locale of the workbook.
+ * @returns {LocaleType} The locale of the workbook
+ * @example
+ * ```ts
+ * // The code below gets the locale of the workbook
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const locale = activeSpreadsheet.getLocale();
+ * ```
+ */
+ getLocale(): LocaleType {
+ return this._localeService.getCurrentLocale();
+ }
+
+ /**
+ * Set the locale of the workbook.
+ * @param {LocaleType} locale The locale to set
+ * @example
+ * ```ts
+ * // The code below sets the locale of the workbook
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * activeSpreadsheet.setLocale(LocaleType.EN_US);
+ * ```
+ */
+
+ setLocale(locale: LocaleType): void {
+ this._localeService.setLocale(locale);
+ }
+
+ /**
+ * Get the URL of the workbook.
+ * @returns {string} The URL of the workbook
+ * @example
+ * ```ts
+ * // The code below gets the URL of the workbook
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const url = activeSpreadsheet.getUrl();
+ * ```
+ */
+ getUrl(): string {
+ return location.href;
+ }
+
+ /**
+ * Move the sheet to the specified index.
+ * @param {FWorksheet} sheet The sheet to move
+ * @param {number} index The index to move the sheet to
+ * @returns {Promise<boolean>} true if the sheet was moved, false otherwise
+ * @example
+ * ```ts
+ * // The code below moves the sheet to the specified index
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * const sheet = activeSpreadsheet.getActiveSheet();
+ * activeSpreadsheet.moveSheet(sheet, 1);
+ * ```
+ */
+ async moveSheet(sheet: FWorksheet, index: number): Promise<boolean> {
+ let sheetIndexVal = index;
+ if (sheetIndexVal < 0) {
+ sheetIndexVal = 0;
+ } else if (sheetIndexVal > this._workbook.getSheets().length - 1) {
+ sheetIndexVal = this._workbook.getSheets().length - 1;
+ }
+ return this._commandService.executeCommand(SetWorksheetOrderCommand.id, {
+ unitId: sheet.getWorkbook().getUnitId(),
+ order: sheetIndexVal,
+ subUnitId: sheet.getSheetId(),
+ });
+ }
+
+ /**
+ * Move the active sheet to the specified index.
+ * @param {number} index The index to move the active sheet to
+ * @returns {Promise<boolean>} true if the sheet was moved, false otherwise
+ * @example
+ * ```ts
+ * // The code below moves the active sheet to the specified index
+ * const activeSpreadsheet = univerAPI.getActiveWorkbook();
+ * activeSpreadsheet.moveActiveSheet(1);
+ * ```
+ */
+ async moveActiveSheet(index: number) {
+ const sheet = this.getActiveSheet();
+ return this.moveSheet(sheet, index);
+ }
}