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(facade): workbook and worksheet operation (#2076)
Dushusir2daefd7f82b6
diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.tsindex c8d24ccc0b..a66b35a453 100644--- a/examples/src/sheets/main.ts+++ b/examples/src/sheets/main.ts@@ -35,8 +35,9 @@ import { UniverDataValidationPlugin } from '@univerjs/data-validation';import { UniverSheetsDataValidationPlugin } from '@univerjs/sheets-data-validation';import { UniverSheetsConditionalFormattingUIPlugin } from '@univerjs/sheets-conditional-formatting-ui';-import { DEFAULT_WORKBOOK_DATA_DEMO } from '../data/sheets/demo/default-workbook-data-demo';+import { FUniver } from '@univerjs/facade';import { DebuggerPlugin } from '../plugins/debugger';+import { DEFAULT_WORKBOOK_DATA_DEMO } from '../data/sheets/demo/default-workbook-data-demo';import { locales } from './locales';/* eslint-disable-next-line node/prefer-global/process */@@ -114,6 +115,7 @@ univer.registerPlugin(DebuggerPlugin);declare global {interface Window {univer?: Univer;+ univerAPI?: ReturnType<typeof FUniver.newAPI>;}}@@ -125,3 +127,4 @@ setTimeout(() => {}, LOAD_LAZY_PLUGINS_TIMEOUT);window.univer = univer;+window.univerAPI = FUniver.newAPI(univer);diff --git a/packages/facade/src/apis/__tests__/facade.spec.ts b/packages/facade/src/apis/__tests__/facade.spec.tsindex 54dcd01ba6..e164199f96 100644--- a/packages/facade/src/apis/__tests__/facade.spec.ts+++ b/packages/facade/src/apis/__tests__/facade.spec.ts@@ -162,6 +162,7 @@ describe('Test FUniver', () => {expect(() => univerAPI.createSocket('URL')).toThrowError();});+it('Function registerSheetRowHeaderExtension and unregisterSheetRowHeaderExtension', () => {const rowHeader = univerAPI.registerSheetRowHeaderExtension('test', new RowHeaderCustomExtension());diff --git a/packages/facade/src/apis/facade.ts b/packages/facade/src/apis/facade.tsindex 66639b3422..4064c8d5fb 100644--- a/packages/facade/src/apis/facade.ts+++ b/packages/facade/src/apis/facade.ts@@ -67,7 +67,7 @@ export class FUniver {/*** Create a new spreadsheet and get the API handler of that spreadsheet.- * @param data the snapshot of the spreadsheet.+ * @param data The snapshot of the spreadsheet.* @returns Spreadsheet API instance.*/createUniverSheet(data: Partial<IWorkbookData>): FWorkbook {@@ -77,7 +77,7 @@ export class FUniver {/*** Create a new document and get the API handler of that document.- * @param data the snapshot of the document.+ * @param data The snapshot of the document.* @returns Document API instance.*/createUniverDoc(data: Partial<IDocumentData>): FDocument {@@ -87,7 +87,7 @@ export class FUniver {/*** Get the spreadsheet API handler by the spreadsheet id.- * @param id the spreadsheet id.+ * @param id The spreadsheet id.* @returns Spreadsheet API instance.*/getUniverSheet(id: string): FWorkbook | null {@@ -101,7 +101,7 @@ export class FUniver {/*** Get the document API handler by the document id.- * @param id the document id.+ * @param id The document id.* @returns Document API instance.*/getUniverDoc(id: string): FDocument | null {diff --git a/packages/facade/src/apis/sheets/__tests__/f-workbook.spec.ts b/packages/facade/src/apis/sheets/__tests__/f-workbook.spec.tsnew file mode 100644index 0000000000..d26808b32e--- /dev/null+++ b/packages/facade/src/apis/sheets/__tests__/f-workbook.spec.ts@@ -0,0 +1,120 @@+/**+ * 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, IStyleData, Nullable } from '@univerjs/core';+import { ICommandService, IUniverInstanceService } from '@univerjs/core';+import { InsertSheetCommand, InsertSheetMutation, RemoveSheetCommand, RemoveSheetMutation, SetHorizontalTextAlignCommand, SetRangeValuesCommand, SetRangeValuesMutation, SetStyleCommand, SetTextWrapCommand, SetVerticalTextAlignCommand, SetWorksheetActiveOperation } from '@univerjs/sheets';+import type { Injector } from '@wendellhu/redi';+import { beforeEach, describe, expect, it } from 'vitest';++import type { FUniver } from '../../facade';+import { createTestBed } from '../../__tests__/create-test-bed';++describe('Test FWorkbook', () => {+ let get: Injector['get'];+ let commandService: ICommandService;+ let univerAPI: FUniver;+ let getValueByPosition: (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ) => Nullable<ICellData>;+ let getStyleByPosition: (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ) => Nullable<IStyleData>;++ beforeEach(() => {+ const testBed = createTestBed();+ get = testBed.get;+ univerAPI = testBed.univerAPI;++ commandService = get(ICommandService);+ commandService.registerCommand(SetRangeValuesCommand);+ commandService.registerCommand(SetRangeValuesMutation);+ commandService.registerCommand(SetStyleCommand);+ commandService.registerCommand(SetVerticalTextAlignCommand);+ commandService.registerCommand(SetHorizontalTextAlignCommand);+ commandService.registerCommand(SetTextWrapCommand);+ commandService.registerCommand(InsertSheetCommand);+ commandService.registerCommand(InsertSheetMutation);+ commandService.registerCommand(SetWorksheetActiveOperation);+ commandService.registerCommand(RemoveSheetCommand);+ commandService.registerCommand(RemoveSheetMutation);++ getValueByPosition = (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ): Nullable<ICellData> =>+ get(IUniverInstanceService)+ .getUniverSheetInstance('test')+ ?.getSheetBySheetId('sheet1')+ ?.getRange(startRow, startColumn, endRow, endColumn)+ .getValue();++ getStyleByPosition = (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ): Nullable<IStyleData> => {+ const value = getValueByPosition(startRow, startColumn, endRow, endColumn);+ const styles = get(IUniverInstanceService).getUniverSheetInstance('test')?.getStyles();+ if (value && styles) {+ return styles.getStyleByCell(value);+ }+ };+ });++ it('Workbook getSheets', () => {+ const sheets = univerAPI.getActiveWorkbook()?.getSheets();+ expect(sheets).not.toBeNull();+ expect(sheets?.length).toBe(1);+ });++ it('Workbook getSheetByName', () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');+ expect(activeSheet).not.toBeNull();+ });++ it('Workbook insertSheet, deleteSheet, and setActiveSheet', () => {+ const workbook = univerAPI.getActiveWorkbook();++ // insert a new sheet+ let activeSheet = workbook?.insertSheet();+ expect(activeSheet).not.toBeNull();+ expect(workbook?.getSheets().length).toBe(2);++ const sheets = workbook?.getSheets();++ if (!sheets) {+ throw new Error('sheets is null');+ }++ // set the first sheet as active sheet+ activeSheet = workbook?.setActiveSheet(sheets[0]);+ expect(activeSheet?.getSheetName()).toBe('sheet1');++ // delete the active sheet+ workbook?.deleteSheet(activeSheet!);+ expect(workbook?.getSheets().length).toBe(1);+ });+});diff --git a/packages/facade/src/apis/sheets/__tests__/f-worksheet.spec.ts b/packages/facade/src/apis/sheets/__tests__/f-worksheet.spec.tsnew file mode 100644index 0000000000..961cfd1117--- /dev/null+++ b/packages/facade/src/apis/sheets/__tests__/f-worksheet.spec.ts@@ -0,0 +1,86 @@+/**+ * 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, IStyleData, Nullable } from '@univerjs/core';+import { ICommandService, IUniverInstanceService } from '@univerjs/core';+import { SetHorizontalTextAlignCommand, SetRangeValuesCommand, SetRangeValuesMutation, SetStyleCommand, SetTextWrapCommand, SetVerticalTextAlignCommand } from '@univerjs/sheets';+import type { Injector } from '@wendellhu/redi';+import { beforeEach, describe, expect, it } from 'vitest';++import type { FUniver } from '../../facade';+import { createTestBed } from '../../__tests__/create-test-bed';++describe('Test FWorksheet', () => {+ let get: Injector['get'];+ let commandService: ICommandService;+ let univerAPI: FUniver;+ let getValueByPosition: (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ) => Nullable<ICellData>;+ let getStyleByPosition: (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ) => Nullable<IStyleData>;++ beforeEach(() => {+ const testBed = createTestBed();+ get = testBed.get;+ univerAPI = testBed.univerAPI;++ commandService = get(ICommandService);+ commandService.registerCommand(SetRangeValuesCommand);+ commandService.registerCommand(SetRangeValuesMutation);+ commandService.registerCommand(SetStyleCommand);+ commandService.registerCommand(SetVerticalTextAlignCommand);+ commandService.registerCommand(SetHorizontalTextAlignCommand);+ commandService.registerCommand(SetTextWrapCommand);++ getValueByPosition = (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ): Nullable<ICellData> =>+ get(IUniverInstanceService)+ .getUniverSheetInstance('test')+ ?.getSheetBySheetId('sheet1')+ ?.getRange(startRow, startColumn, endRow, endColumn)+ .getValue();++ getStyleByPosition = (+ startRow: number,+ startColumn: number,+ endRow: number,+ endColumn: number+ ): Nullable<IStyleData> => {+ const value = getValueByPosition(startRow, startColumn, endRow, endColumn);+ const styles = get(IUniverInstanceService).getUniverSheetInstance('test')?.getStyles();+ if (value && styles) {+ return styles.getStyleByCell(value);+ }+ };+ });++ it('Worksheet getSheetName', () => {+ const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');+ expect(activeSheet?.getSheetName()).toBe('sheet1');+ });+});diff --git a/packages/facade/src/apis/sheets/f-workbook.ts b/packages/facade/src/apis/sheets/f-workbook.tsindex 9e0e468a82..551adc65d3 100644--- a/packages/facade/src/apis/sheets/f-workbook.ts+++ b/packages/facade/src/apis/sheets/f-workbook.ts@@ -28,7 +28,7 @@ import {import type {ISheetCommandSharedParams,} from '@univerjs/sheets';-import { InsertSheetCommand, SelectionManagerService, SetWorksheetActiveOperation } from '@univerjs/sheets';+import { InsertSheetCommand, RemoveSheetCommand, SelectionManagerService, SetWorksheetActiveOperation } from '@univerjs/sheets';import type { IDisposable } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';@@ -50,7 +50,7 @@ export class FWorkbook {}getId(): string {- return this._workbook.getUnitId();+ return this.id;}getName(): string {@@ -58,7 +58,7 @@ export class FWorkbook {}/**- * Returns workbook snapshot data, including conditional formatting, data validation, and other plugin data."+ * Returns workbook snapshot data, including conditional formatting, data validation, and other plugin data.*/getSnapshot(): IWorkbookData {const snapshot = this._resourceLoaderService.saveWorkbook(this._workbook);@@ -78,6 +78,16 @@ export class FWorkbook {return this._injector.createInstance(FWorksheet, this._workbook, activeSheet);}+ /**+ * Gets all the worksheets in this workbook+ * @returns An array of all the worksheets in the workbook+ */+ getSheets() {+ return this._workbook.getSheets().map((sheet) => {+ return this._injector.createInstance(FWorksheet, this._workbook, sheet);+ });+ }+/*** Create a new worksheet and returns a handle to it.* @param name Name of the new sheet@@ -93,12 +103,12 @@ export class FWorkbook {newSheet.id = name.toLowerCase().replace(/ /g, '-');this._commandService.syncExecuteCommand(InsertSheetCommand.id, {- unitId: this._workbook.getUnitId(),+ unitId: this.id,index: this._workbook.getSheets().length,sheet: newSheet,});this._commandService.syncExecuteCommand(SetWorksheetActiveOperation.id, {- unitId: this._workbook.getUnitId(),+ unitId: this.id,subUnitId: this._workbook.getSheets()[this._workbook.getSheets().length - 1].getSheetId(),});@@ -107,8 +117,8 @@ export class FWorkbook {/*** Get a worksheet by sheet id.- * @param sheetId id of the worksheet- * @return the worksheet with given sheet id+ * @param sheetId The id of the sheet to get.+ * @return The worksheet with given sheet id*/getSheetBySheetId(sheetId: string): FWorksheet | null {const worksheet = this._workbook.getSheetBySheetId(sheetId);@@ -119,6 +129,67 @@ export class FWorkbook {return this._injector.createInstance(FWorksheet, this._workbook, worksheet);}+ /**+ * Get a worksheet by sheet name.+ * @param name The name of the sheet to get.+ * @returns The worksheet with given sheet name+ */+ getSheetByName(name: string): FWorksheet | null {+ const worksheet = this._workbook.getSheetBySheetName(name);+ if (!worksheet) {+ return null;+ }++ return this._injector.createInstance(FWorksheet, this._workbook, worksheet);+ }+++ /**+ * 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+ */+ setActiveSheet(sheet: FWorksheet) {+ this._commandService.syncExecuteCommand(SetWorksheetActiveOperation.id, {+ unitId: this.id,+ subUnitId: sheet.getSheetId(),+ });++ return sheet;+ }++ /**+ * Inserts a new worksheet into the workbook.+ * Using a default sheet name. The new sheet becomes the active sheet+ * @returns The new sheet+ */+ insertSheet() {+ this._commandService.syncExecuteCommand(InsertSheetCommand.id);++ const unitId = this.id;+ const subUnitId = this._workbook.getSheets()[this._workbook.getSheets().length - 1].getSheetId();++ this._commandService.syncExecuteCommand(SetWorksheetActiveOperation.id, {+ unitId,+ subUnitId,+ });++ return this._injector.createInstance(FWorksheet, this._workbook, this._workbook.getActiveSheet());+ }++ /**+ * Deletes the specified worksheet.+ * @param sheet The worksheet to delete.+ */+ deleteSheet(sheet: FWorksheet) {+ const unitId = this.id;+ const subUnitId = sheet.getSheetId();+ this._commandService.executeCommand(RemoveSheetCommand.id, {+ unitId,+ subUnitId,+ });+ }+// #region editingundo(): Promise<boolean> {diff --git a/packages/facade/src/apis/sheets/f-worksheet.ts b/packages/facade/src/apis/sheets/f-worksheet.tsindex 8ed95d34a2..89af947c65 100644--- a/packages/facade/src/apis/sheets/f-worksheet.ts+++ b/packages/facade/src/apis/sheets/f-worksheet.ts@@ -33,17 +33,17 @@ export class FWorksheet {/*** Returns the worksheet id- * @returns sheet id+ * @returns The id of the worksheet*/getSheetId(): string {return this._worksheet.getSheetId();}/**- * Returns the name of the worksheet.- * @returns name of the worksheet+ * Returns the worksheet name+ * @returns The name of the worksheet*/- getName(): string {+ getSheetName(): string {return this._worksheet.getName();}