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(facade): add clipboard hooks and selection api (#3216)

#FF0000e2fbf0e4bd01
diff --git a/examples/src/docs/main.ts b/examples/src/docs/main.ts
index 0f02189a76..c74a5dea60 100644
--- a/examples/src/docs/main.ts
+++ b/examples/src/docs/main.ts
@@ -27,6 +27,7 @@ import { UniverDocsDrawingUIPlugin } from '@univerjs/docs-drawing-ui';
import { UniverDocsThreadCommentUIPlugin } from '@univerjs/docs-thread-comment-ui';
import { UniverDocsHyperLinkUIPlugin } from '@univerjs/docs-hyper-link-ui';
import { UniverDocsMentionUIPlugin } from '@univerjs/docs-mention-ui';
+import { FUniver } from '@univerjs/facade';
import { DEFAULT_DOCUMENT_DATA_CN } from '../data';
import { enUS, ruRU, zhCN } from '../locales';
@@ -101,3 +102,4 @@ const mockUser = {
canBindAnonymous: false,
};
userManagerService.setCurrentUser(mockUser);
+window.univerAPI = FUniver.newAPI(univer);
diff --git a/packages/facade/src/apis/docs/f-document.ts b/packages/facade/src/apis/docs/f-document.ts
index 369e2dab33..a26bcbee67 100644
--- a/packages/facade/src/apis/docs/f-document.ts
+++ b/packages/facade/src/apis/docs/f-document.ts
@@ -15,8 +15,9 @@
*/
import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
-import {
- ICommandService,
+import { ICommandService,
+ Inject,
+ Injector,
IResourceManagerService,
IUniverInstanceService,
RedoCommand,
@@ -24,12 +25,14 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import { InsertCommand } from '@univerjs/docs';
+import { DOC_RANGE_TYPE, ITextSelectionRenderManager } from '@univerjs/engine-render';
export class FDocument {
readonly id: string;
constructor(
private readonly _documentDataModel: DocumentDataModel,
+ @Inject(Injector) protected readonly _injector: Injector,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@ICommandService private readonly _commandService: ICommandService,
@IResourceManagerService private readonly _resourceManagerService: IResourceManagerService
@@ -95,4 +98,30 @@ export class FDocument {
segmentId,
});
}
+
+ /**
+ * Sets the selection to a specified text range in the document.
+ *
+ * @param startOffset - The starting offset of the selection in the document.
+ * @param endOffset - The ending offset of the selection in the document.
+ *
+ * @example
+ * ```typescript
+ * document.setSelection(10, 20);
+ * ```
+ */
+ setSelection(startOffset: number, endOffset: number): void {
+ const textSelectionRenderManager = this._injector.get(ITextSelectionRenderManager);
+ textSelectionRenderManager.removeAllRanges();
+ textSelectionRenderManager.addDocRanges(
+ [
+ {
+ startOffset,
+ endOffset,
+ rangeType: DOC_RANGE_TYPE.TEXT,
+ },
+ ]
+ , true
+ );
+ }
}
diff --git a/packages/facade/src/apis/f-hooks.ts b/packages/facade/src/apis/f-hooks.ts
index e57c130bee..89f6fa80eb 100644
--- a/packages/facade/src/apis/f-hooks.ts
+++ b/packages/facade/src/apis/f-hooks.ts
@@ -17,6 +17,7 @@
import { Inject, Injector, LifecycleService, LifecycleStages, toDisposable } from '@univerjs/core';
import type { IDisposable } from '@univerjs/core';
import { filter } from 'rxjs';
+import { FClipboardHooks } from './hooks/f-clipboard-hooks';
import { FUndoRedoHooks } from './hooks/f-undoredo-hooks';
export class FHooks {
@@ -90,4 +91,32 @@ export class FHooks {
* @returns A disposable object that can be used to unsubscribe from the event
*/
onRedo = FUndoRedoHooks.afterRedo.bind(this);
+
+ /**
+ * The onBeforeCopy event is fired before a copy operation is performed.
+ * @param callback Callback function that will be called when the event is fired
+ * @returns A disposable object that can be used to unsubscribe from the event
+ */
+ onBeforeCopy = FClipboardHooks.onBeforeCopy.bind(this);
+
+ /**
+ * The onCopy event is fired after a copy operation is performed.
+ * @param callback Callback function that will be called when the event is fired
+ * @returns A disposable object that can be used to unsubscribe from the event
+ */
+ onCopy = FClipboardHooks.onCopy.bind(this);
+
+ /**
+ * The onBeforePaste event is fired before a paste operation is performed.
+ * @param callback Callback function that will be called when the event is fired
+ * @returns A disposable object that can be used to unsubscribe from the event
+ */
+ onBeforePaste = FClipboardHooks.onBeforePaste.bind(this);
+
+ /**
+ * The onPaste event is fired after a paste operation is performed.
+ * @param callback Callback function that will be called when the event is fired
+ * @returns A disposable object that can be used to unsubscribe from the event
+ */
+ onPaste = FClipboardHooks.onPaste.bind(this);
}
diff --git a/packages/facade/src/apis/facade.ts b/packages/facade/src/apis/facade.ts
index 80b7e8e01f..8c854fd202 100644
--- a/packages/facade/src/apis/facade.ts
+++ b/packages/facade/src/apis/facade.ts
@@ -58,6 +58,7 @@ import { SHEET_VIEW_KEY } from '@univerjs/sheets-ui';
import { SetFormulaCalculationStartMutation } from '@univerjs/engine-formula';
import type { ISetCrosshairHighlightColorOperationParams } from '@univerjs/sheets-crosshair-highlight';
import { DisableCrosshairHighlightOperation, EnableCrosshairHighlightOperation, SetCrosshairHighlightColorOperation } from '@univerjs/sheets-crosshair-highlight';
+import { CopyCommand, PasteCommand } from '@univerjs/ui';
import { FDocument } from './docs/f-document';
import { FWorkbook } from './sheets/f-workbook';
import { FSheetHooks } from './sheets/f-sheet-hooks';
@@ -225,7 +226,7 @@ export class FUniver {
* @returns {FDocument | null} The currently focused Univer document.
*/
getActiveDocument(): FDocument | null {
- const document = this._univerInstanceService.getCurrentUniverDocInstance();
+ const document = this._univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
if (!document) {
return null;
}
@@ -332,6 +333,14 @@ export class FUniver {
return this._commandService.executeCommand(RedoCommand.id);
}
+ copy(): Promise<boolean> {
+ return this._commandService.executeCommand(CopyCommand.id);
+ }
+
+ paste(): Promise<boolean> {
+ return this._commandService.executeCommand(PasteCommand.id);
+ }
+
// #endregion
// #region listeners
diff --git a/packages/facade/src/apis/hooks/__tests__/f-clipboard-hooks.spec.ts b/packages/facade/src/apis/hooks/__tests__/f-clipboard-hooks.spec.ts
new file mode 100644
index 0000000000..ff905cc305
--- /dev/null
+++ b/packages/facade/src/apis/hooks/__tests__/f-clipboard-hooks.spec.ts
@@ -0,0 +1,88 @@
+/**
+ * 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 { ICommandService, type Injector, IUniverInstanceService, Univer, UniverInstanceType } from '@univerjs/core';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { UniverSheetsPlugin } from '@univerjs/sheets';
+import { UniverRenderEnginePlugin } from '@univerjs/engine-render';
+import { CopyCommand, PasteCommand } from '@univerjs/ui';
+import { FUniver } from '../../facade';
+import type { FWorksheet } from '../../sheets/f-worksheet';
+import type { FWorkbook } from '../../sheets/f-workbook';
+
+function createUnitTestBed(): {
+ univer: Univer;
+ get: Injector['get'];
+ univerAPI: FUniver;
+ injector: Injector;
+} {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ univer.registerPlugin(UniverSheetsPlugin);
+ univer.registerPlugin(UniverRenderEnginePlugin);
+
+ const commandService = injector.get(ICommandService);
+ commandService.registerCommand(PasteCommand);
+ commandService.registerCommand(CopyCommand);
+
+ const sheet = univer.createUnit(UniverInstanceType.UNIVER_SHEET, {});
+ const univerInstanceService = injector.get(IUniverInstanceService);
+ univerInstanceService.focusUnit(sheet.getUnitId());
+ const univerAPI = FUniver.newAPI(univer);
+
+ return {
+ univer,
+ get: injector.get.bind(injector),
+ univerAPI,
+ injector,
+ };
+}
+
+describe('Test Clipboard Hooks', () => {
+ let get: Injector['get'];
+ let univerAPI: FUniver;
+
+ beforeEach(() => {
+ const testBed = createUnitTestBed();
+ get = testBed.get;
+ univerAPI = testBed.univerAPI;
+ });
+
+ it('clipboard normal case', async () => {
+ const workbook = univerAPI.getActiveWorkbook() as FWorkbook;
+ const sheet = workbook.getActiveSheet() as FWorksheet;
+ expect(sheet).not.toBeUndefined();
+
+ const beforeCopyFn = vi.fn();
+ const afterCopyFn = vi.fn();
+ const beforePasteFn = vi.fn();
+ const afterPasteFn = vi.fn();
+
+ univerAPI.getHooks().onBeforeCopy(beforeCopyFn);
+ univerAPI.getHooks().onCopy(afterCopyFn);
+ univerAPI.getHooks().onBeforePaste(beforePasteFn);
+ univerAPI.getHooks().onPaste(afterPasteFn);
+
+ await univerAPI.copy();
+ await univerAPI.paste();
+
+ expect(beforeCopyFn).toHaveBeenCalledTimes(1);
+ expect(afterCopyFn).toHaveBeenCalledTimes(1);
+ expect(beforePasteFn).toHaveBeenCalledTimes(1);
+ expect(afterPasteFn).toHaveBeenCalledTimes(1);
+ });
+});
+
diff --git a/packages/facade/src/apis/hooks/f-clipboard-hooks.ts b/packages/facade/src/apis/hooks/f-clipboard-hooks.ts
new file mode 100644
index 0000000000..f5d6defc95
--- /dev/null
+++ b/packages/facade/src/apis/hooks/f-clipboard-hooks.ts
@@ -0,0 +1,61 @@
+/**
+ * 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 { IDisposable } from '@univerjs/core';
+import { ICommandService } from '@univerjs/core';
+import { CopyCommand, PasteCommand } from '@univerjs/ui';
+import type { FHooks } from '../f-hooks';
+
+export const FClipboardHooks = {
+
+ onBeforeCopy(this: FHooks, callback: () => void): IDisposable {
+ const commandService = this._injector.get(ICommandService);
+
+ return commandService.beforeCommandExecuted((command) => {
+ if (command.id === CopyCommand.id) {
+ callback();
+ }
+ });
+ },
+ onCopy(this: FHooks, callback: () => void): IDisposable {
+ const commandService = this._injector.get(ICommandService);
+
+ return commandService.onCommandExecuted((command) => {
+ if (command.id === CopyCommand.id) {
+ callback();
+ }
+ });
+ },
+
+ onBeforePaste(this: FHooks, callback: () => void): IDisposable {
+ const commandService = this._injector.get(ICommandService);
+
+ return commandService.beforeCommandExecuted((command) => {
+ if (command.id === PasteCommand.id) {
+ callback();
+ }
+ });
+ },
+ onPaste(this: FHooks, callback: () => void): IDisposable {
+ const commandService = this._injector.get(ICommandService);
+
+ return commandService.onCommandExecuted((command) => {
+ if (command.id === PasteCommand.id) {
+ callback();
+ }
+ });
+ },
+};
diff --git a/packages/facade/src/apis/sheets/__tests__/f-active-range.spec.ts b/packages/facade/src/apis/sheets/__tests__/f-active-range.spec.ts
new file mode 100644
index 0000000000..f2adf228f9
--- /dev/null
+++ b/packages/facade/src/apis/sheets/__tests__/f-active-range.spec.ts
@@ -0,0 +1,99 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Injector } from '@univerjs/core';
+import { ICommandService } from '@univerjs/core';
+import { InsertSheetCommand, InsertSheetMutation, RemoveSheetCommand, RemoveSheetMutation, SetSelectionsOperation, SetWorksheetActiveOperation } from '@univerjs/sheets';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import type { FUniver } from '../../facade';
+import { createFacadeTestBed } from '../../__tests__/create-test-bed';
+
+describe('Test Active Range', () => {
+ let get: Injector['get'];
+ let commandService: ICommandService;
+ let univerAPI: FUniver;
+
+ beforeEach(() => {
+ const testBed = createFacadeTestBed();
+ get = testBed.get;
+ univerAPI = testBed.univerAPI;
+
+ commandService = get(ICommandService);
+ commandService.registerCommand(InsertSheetCommand);
+ commandService.registerCommand(InsertSheetMutation);
+ commandService.registerCommand(SetWorksheetActiveOperation);
+ commandService.registerCommand(RemoveSheetCommand);
+ commandService.registerCommand(RemoveSheetMutation);
+ commandService.registerCommand(SetSelectionsOperation);
+ });
+
+ it('Workbook setActiveRange', () => {
+ const workbook = univerAPI.getActiveWorkbook()!;
+ expect(workbook.getSheets().length).toBe(1);
+
+ const sheet = workbook.getSheets()[0];
+
+ expect(sheet.getActiveRange()).toBeDefined();
+
+ sheet.setActiveRange(sheet.getRange(0, 0, 2, 2));
+
+ let activeRange = workbook.getActiveRange();
+ expect(activeRange?.getRange().startRow).toBe(0);
+ expect(activeRange?.getRange().startColumn).toBe(0);
+ expect(activeRange?.getRange().endColumn).toBe(1);
+ expect(activeRange?.getRange().endRow).toBe(1);
+
+ const sheet2 = workbook.insertSheet();
+ expect(workbook.getSheets().length).toBe(2);
+
+ sheet2.setActiveRange(sheet2.getRange(0, 0, 3, 3));
+ activeRange = workbook.getActiveRange();
+ expect(activeRange?.getRange().startRow).toBe(0);
+ expect(activeRange?.getRange().startColumn).toBe(0);
+ expect(activeRange?.getRange().endColumn).toBe(2);
+ expect(activeRange?.getRange().endRow).toBe(2);
+
+ workbook.setActiveSheet(sheet);
+ activeRange = workbook.getActiveRange();
+ expect(activeRange?.getRange().startRow).toBe(0);
+ expect(activeRange?.getRange().startColumn).toBe(0);
+ expect(activeRange?.getRange().endColumn).toBe(1);
+ expect(activeRange?.getRange().endRow).toBe(1);
+
+ workbook.setActiveRange(sheet2.getRange(0, 0, 1, 1));
+ expect(workbook.getActiveSheet().getSheetId()).toBe(sheet2.getSheetId());
+ });
+
+ it('Worksheet setActiveRange', () => {
+ const workbook = univerAPI.getActiveWorkbook()!;
+ const sheet1 = workbook.getSheets()[0];
+ const sheet2 = workbook.insertSheet();
+
+ const range1 = sheet1.getRange(0, 0, 10, 10);
+ const range2 = sheet2.getRange(0, 0, 10, 10);
+
+ sheet1.setActiveRange(range1);
+ expect(workbook.getActiveRange()?.getRange()).toEqual(range1.getRange());
+
+ sheet2.setActiveRange(range2);
+ expect(workbook.getActiveRange()?.getRange()).toEqual(range2.getRange());
+
+ expect(() => {
+ sheet1.setActiveRange(range2);
+ }).toThrow('Specified range must be part of the sheet.');
+ });
+});
diff --git a/packages/facade/src/apis/sheets/__tests__/f-range.spec.ts b/packages/facade/src/apis/sheets/__tests__/f-range.spec.ts
index 75e452f1e6..a696e033e2 100644
--- a/packages/facade/src/apis/sheets/__tests__/f-range.spec.ts
+++ b/packages/facade/src/apis/sheets/__tests__/f-range.spec.ts
@@ -568,6 +568,8 @@ describe('Test FRange', () => {
expect(range.getDataValidation()).toBeTruthy();
expect(range.getDataValidation()?.rule.ranges).toEqual([{
+ unitId: univerAPI.getActiveWorkbook()?.getId(),
+ sheetId: activeSheet.getSheetId(),
startRow: 0,
endRow: 9,
startColumn: 0,
@@ -601,7 +603,14 @@ describe('Test FRange', () => {
expect(filter).not.toBeNull();
expect(activeSheet.getFilter()).not.toBeNull();
expect(activeSheet.getRange(0, 0, 1, 1).getFilter()).not.toBeNull();
- expect(filter.getRange().getRange()).toStrictEqual({ startColumn: 0, startRow: 0, endColumn: 9, endRow: 9 } as IRange);
+ expect(filter.getRange().getRange()).toStrictEqual({
+ unitId: univerAPI.getActiveWorkbook()?.getId(),
+ sheetId: activeSheet.getSheetId(),
+ startColumn: 0,
+ startRow: 0,
+ endColumn: 9,
+ endRow: 9,
+ } as IRange);
expect(await filter.setColumnFilterCriteria(1, { colId: 1, filters: { blank: true } })).toBeTruthy();
expect(filter.getColumnFilterCriteria(1)).toEqual({ colId: 1, filters: { blank: true } });
diff --git a/packages/facade/src/apis/sheets/f-workbook.ts b/packages/facade/src/apis/sheets/f-workbook.ts
index e47eea35bd..2d30fcb7c7 100644
--- a/packages/facade/src/apis/sheets/f-workbook.ts
+++ b/packages/facade/src/apis/sheets/f-workbook.ts
@@ -30,9 +30,10 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import type {
+ ISetSelectionsOperationParams,
ISheetCommandSharedParams,
} from '@univerjs/sheets';
-import { InsertSheetCommand, RemoveSheetCommand, SetWorksheetActiveOperation, SheetsSelectionsService, WorkbookEditablePermission } from '@univerjs/sheets';
+import { getPrimaryForRange, InsertSheetCommand, RemoveSheetCommand, SetSelectionsOperation, SetWorksheetActiveOperation, SheetsSelectionsService, WorkbookEditablePermission } from '@univerjs/sheets';
import type { ICanvasFloatDom } from '@univerjs/sheets-drawing-ui';
import type { IAddSheetDataValidationCommandParams, IDataValidationResCache, IRemoveSheetAllDataValidationCommandParams, IRemoveSheetDataValidationCommandParams, IUpdateSheetDataValidationOptionsCommandParams, IUpdateSheetDataValidationRangeCommandParams, IUpdateSheetDataValidationSettingCommandParams } from '@univerjs/sheets-data-validation';
import { AddSheetDataValidationCommand, DataValidationModel, RemoveSheetAllDataValidationCommand, RemoveSheetDataValidationCommand, SheetsDataValidationValidatorService, UpdateSheetDataValidationOptionsCommand, UpdateSheetDataValidationRangeCommand, UpdateSheetDataValidationSettingCommand } from '@univerjs/sheets-data-validation';
@@ -43,6 +44,7 @@ import { AddCommentCommand, DeleteCommentCommand, DeleteCommentTreeCommand, Thre
import { filter } from 'rxjs';
import type { IFComponentKey } from './utils';
import { FWorksheet } from './f-worksheet';
+import { FRange } from './f-range';
export interface IFICanvasFloatDom extends Omit<ICanvasFloatDom, 'componentKey' | 'unitId' | 'subUnitId'>, IFComponentKey {
@@ -105,7 +107,7 @@ export class FWorkbook {
*/
getActiveSheet(): FWorksheet {
const activeSheet = this._workbook.getActiveSheet();
- return this._injector.createInstance(FWorksheet, this._workbook, activeSheet);
+ return this._injector.createInstance(FWorksheet, this, this._workbook, activeSheet);
}
/**
@@ -114,7 +116,7 @@ export class FWorkbook {
*/
getSheets(): FWorksheet[] {
return this._workbook.getSheets().map((sheet) => {
- return this._injector.createInstance(FWorksheet, this._workbook, sheet);
+ return this._injector.createInstance(FWorksheet, this, this._workbook, sheet);
});
}
@@ -146,7 +148,7 @@ export class FWorkbook {
throw new Error('No active sheet found');
}
- return this._injector.createInstance(FWorksheet, this._workbook, worksheet);
+ return this._injector.createInstance(FWorksheet, this, this._workbook, worksheet);
}
/**
@@ -160,7 +162,7 @@ export class FWorkbook {
return null;
}
- return this._injector.createInstance(FWorksheet, this._workbook, worksheet);
+ return this._injector.createInstance(FWorksheet, this, this._workbook, worksheet);
}
/**
@@ -174,7 +176,7 @@ export class FWorkbook {
return null;
}
- return this._injector.createInstance(FWorksheet, this._workbook, worksheet);
+ return this._injector.createInstance(FWorksheet, this, this._workbook, worksheet);
}
/**
@@ -211,7 +213,7 @@ export class FWorkbook {
throw new Error('No active sheet found');
}
- return this._injector.createInstance(FWorksheet, this._workbook, worksheet);
+ return this._injector.createInstance(FWorksheet, this, this._workbook, worksheet);
}
/**
@@ -316,6 +318,50 @@ export class FWorkbook {
);
}
+ /**
+ * Sets the active selection region for this sheet.
+ * @param range The range to set as the active selection.
+ */
+ setActiveRange(range: FRange): void {
+ // In theory, FRange should belong to a specific context, rather than getting the currently active sheet
+ const sheet = this.getActiveSheet();
+ const sheetId = range.getRange().sheetId || sheet.getSheetId();
+
+ const worksheet = sheetId ? this._workbook.getSheetBySheetId(sheetId) : this._workbook.getActiveSheet(true);
+ if (!worksheet) {
+ throw new Error('No active sheet found');
+ }
+
+ // if the range is not in the current sheet, set the active sheet to the range's sheet
+ if (worksheet.getSheetId() !== sheet.getSheetId()) {
+ this.setActiveSheet(this._injector.createInstance(FWorksheet, this, this._workbook, worksheet));
+ }
+
+ const setSelectionOperationParams: ISetSelectionsOperationParams = {
+ unitId: this.getId(),
+ subUnitId: sheetId,
+
+ selections: [range].map((r) => ({ range: r.getRange(), primary: getPrimaryForRange(r.getRange(), worksheet), style: null })),
+ };
+
+ this._commandService.syncExecuteCommand(SetSelectionsOperation.id, setSelectionOperationParams);
+ }
+
+ /**
+ * Returns the selected range in the active sheet, or null if there is no active range.
+ * @returns the active range
+ */
+ getActiveRange(): FRange | null {
+ const activeSheet = this._workbook.getActiveSheet();
+ const selections = this._selectionManagerService.getCurrentSelections();
+ const active = selections.find((selection) => !!selection.primary);
+ if (!active) {
+ return null;
+ }
+
+ return this._injector.createInstance(FRange, this._workbook, activeSheet, active.range);
+ }
+
// region DataValidationHooks
/**
* The onDataValidationChange event is fired when the data validation rule of this sheet is changed.
diff --git a/packages/facade/src/apis/sheets/f-worksheet.ts b/packages/facade/src/apis/sheets/f-worksheet.ts
index 5f4fb471b8..983b96ca32 100644
--- a/packages/facade/src/apis/sheets/f-worksheet.ts
+++ b/packages/facade/src/apis/sheets/f-worksheet.ts
@@ -30,11 +30,12 @@ import { FSelection } from './f-selection';
import { FDataValidation } from './f-data-validation';
import { FFilter } from './f-filter';
import { FThreadComment } from './f-thread-comment';
-import type { IFICanvasFloatDom } from './f-workbook';
+import type { FWorkbook, IFICanvasFloatDom } from './f-workbook';
import { covertToColRange, covertToRowRange, transformComponentKey } from './utils';
export class FWorksheet {
constructor(
+ private readonly _fWorkbook: FWorkbook,
private readonly _workbook: Workbook,
private readonly _worksheet: Worksheet,
@Inject(Injector) private readonly _injector: Injector,
@@ -91,6 +92,8 @@ export class FWorksheet {
endRow: row + (height ?? 1) - 1,
startColumn: col,
endColumn: col + (width ?? 1) - 1,
+ unitId: this._workbook.getUnitId(),
+ sheetId: this._worksheet.getSheetId(),
};
return this._injector.createInstance(FRange, this._workbook, this._worksheet, range);
@@ -836,4 +839,32 @@ export class FWorksheet {
}
// #endregion
+
+ /**
+ * Returns the selected range in the active sheet, or null if there is no active range.
+ * @returns the active range
+ */
+ getActiveRange(): FRange | null {
+ return this._fWorkbook.getActiveRange();
+ }
+
+ /**
+ * Sets the active selection region for this sheet.
+ * @param range The range to set as the active selection.
+ */
+ setActiveRange(range: FRange): void {
+ const { unitId, sheetId } = range.getRange();
+
+ if (unitId !== this._workbook.getUnitId() || sheetId !== this._worksheet.getSheetId()) {
+ throw new Error('Specified range must be part of the sheet.');
+ }
+
+ this._fWorkbook.setActiveRange(range);
+ }
+
+ /**
+ * Sets the active selection region for this sheet.
+ * @param range The range to set as the active selection.
+ */
+ setActiveSelection = this.setActiveRange;
}