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.

refactor(permission): refactor and fix some permission API-related issues (#6804)

wpxp123456b10809c9c127
diff --git a/packages/sheets-ui/src/facade/f-permission.ts b/packages/sheets-ui/src/facade/f-workbook-permission.ts
similarity index 73%
rename from packages/sheets-ui/src/facade/f-permission.ts
rename to packages/sheets-ui/src/facade/f-workbook-permission.ts
index c77ce28be5..15c0e4bb54 100644
--- a/packages/sheets-ui/src/facade/f-permission.ts
+++ b/packages/sheets-ui/src/facade/f-workbook-permission.ts
@@ -14,33 +14,33 @@
* limitations under the License.
*/
-import { FPermission } from '@univerjs/sheets/facade';
+import { FWorkbookPermission } from '@univerjs/sheets/facade';
/**
* @ignore
*/
-export interface IFPermissionSheetsUIMixin {
+export interface IFWorkbookPermissionSheetsUIMixin {
/**
* Set visibility of unauthorized pop-up window
* @param {boolean} visible - visibility of unauthorized pop-up window
* @example
* ```ts
* const fWorkbook = univerAPI.getActiveWorkbook();
- * const permission = fWorkbook.getPermission();
+ * const permission = fWorkbook.getWorkbookPermission();
* permission.setPermissionDialogVisible(false);
* ```
*/
setPermissionDialogVisible(visible: boolean): void;
}
-export class FPermissionSheetsUIMixin extends FPermission implements IFPermissionSheetsUIMixin {
+export class FWorkbookPermissionSheetsUIMixin extends FWorkbookPermission implements IFWorkbookPermissionSheetsUIMixin {
override setPermissionDialogVisible(visible: boolean): void {
this._permissionService.setShowComponents(visible);
}
}
-FPermission.extend(FPermissionSheetsUIMixin);
+FWorkbookPermission.extend(FWorkbookPermissionSheetsUIMixin);
declare module '@univerjs/sheets/facade' {
// eslint-disable-next-line ts/naming-convention
- interface FPermission extends IFPermissionSheetsUIMixin {}
+ interface FWorkbookPermission extends IFWorkbookPermissionSheetsUIMixin {}
}
diff --git a/packages/sheets-ui/src/facade/index.ts b/packages/sheets-ui/src/facade/index.ts
index 5cd763d6fc..bb22bd9795 100644
--- a/packages/sheets-ui/src/facade/index.ts
+++ b/packages/sheets-ui/src/facade/index.ts
@@ -17,16 +17,16 @@
import './f-univer';
import './f-workbook';
import './f-worksheet';
-import './f-permission';
+import './f-workbook-permission';
import './f-sheet-hooks';
import './f-event';
export * from './f-enum';
export type * from './f-event';
-export type * from './f-permission';
export { type IFComponentKey, transformComponentKey } from './f-range';
export type * from './f-sheet-hooks';
export type * from './f-univer';
export type * from './f-workbook';
+export type * from './f-workbook-permission';
export type * from './f-worksheet';
diff --git a/packages/sheets/src/facade/__tests__/f-permission.spec.ts b/packages/sheets/src/facade/__tests__/f-permission.spec.ts
deleted file mode 100644
index bcf34fff72..0000000000
--- a/packages/sheets/src/facade/__tests__/f-permission.spec.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * 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 type { FUniver } from '@univerjs/core/facade';
-import { ICommandService, IPermissionService } from '@univerjs/core';
-import { AddRangeProtectionMutation, AddWorksheetProtectionMutation, DeleteRangeProtectionMutation, DeleteWorksheetProtectionMutation, RangeProtectionPermissionEditPoint, RangeProtectionRuleModel, SetRangeProtectionMutation, WorkbookEditablePermission, WorksheetEditPermission } from '@univerjs/sheets';
-import { beforeEach, describe, expect, it } from 'vitest';
-import { createFacadeTestBed } from './create-test-bed';
-
-describe('Test FPermission', () => {
- let get: Injector['get'];
- let commandService: ICommandService;
- let univerAPI: FUniver;
- let permissionService: IPermissionService;
- let rangeProtectionRuleModel: RangeProtectionRuleModel;
-
- beforeEach(() => {
- const testBed = createFacadeTestBed();
- get = testBed.get;
- univerAPI = testBed.univerAPI;
-
- commandService = get(ICommandService);
- commandService.registerCommand(AddWorksheetProtectionMutation);
- commandService.registerCommand(DeleteWorksheetProtectionMutation);
- commandService.registerCommand(AddRangeProtectionMutation);
- commandService.registerCommand(SetRangeProtectionMutation);
- commandService.registerCommand(DeleteRangeProtectionMutation);
-
- permissionService = get(IPermissionService);
- rangeProtectionRuleModel = get(RangeProtectionRuleModel);
- });
-
- it('set workbook edit point false', () => {
- const permission = univerAPI.getPermission();
- const unitId = univerAPI.getActiveWorkbook()?.getId();
- if (unitId) {
- permission.setWorkbookEditPermission(unitId, false);
- let editValue = permissionService.getPermissionPoint(new WorkbookEditablePermission(unitId).id)?.value;
- expect(editValue).toBe(false);
- permission.setWorkbookEditPermission(unitId, true);
- editValue = permissionService.getPermissionPoint(new WorkbookEditablePermission(unitId).id)?.value;
- expect(editValue).toBe(true);
- }
- });
-
- it('set worksheet edit point false', async () => {
- const permission = univerAPI.getPermission();
- const unitId = univerAPI.getActiveWorkbook()?.getId();
- const subUnitId = univerAPI.getActiveWorkbook()?.getActiveSheet().getSheetId();
- if (unitId && subUnitId) {
- await permission.addWorksheetBasePermission(unitId, subUnitId);
- await permission.setWorksheetPermissionPoint(unitId, subUnitId, WorksheetEditPermission, false);
- let editValue = permissionService.getPermissionPoint(new WorksheetEditPermission(unitId, subUnitId).id)?.value;
- expect(editValue).toBe(false);
- await permission.setWorksheetPermissionPoint(unitId, subUnitId, WorksheetEditPermission, true);
- editValue = permissionService.getPermissionPoint(new WorksheetEditPermission(unitId, subUnitId).id)?.value;
- expect(editValue).toBe(true);
- await permission.setWorksheetPermissionPoint(unitId, subUnitId, WorksheetEditPermission, false);
- editValue = permissionService.getPermissionPoint(new WorksheetEditPermission(unitId, subUnitId).id)?.value;
- expect(editValue).toBe(false);
- permission.removeWorksheetPermission(unitId, subUnitId);
- editValue = permissionService.getPermissionPoint(new WorksheetEditPermission(unitId, subUnitId).id)?.value;
- expect(editValue).toBe(true);
- }
- });
-
- it('set range protection point false', async () => {
- const permission = univerAPI.getPermission();
- const workbook = univerAPI.getActiveWorkbook();
- const worksheet = workbook?.getActiveSheet();
- const unitId = workbook?.getId();
- const subUnitId = worksheet?.getSheetId();
- const rangeFirst = worksheet?.getRange(0, 0, 2, 2);
- const rangeSecond = worksheet?.getRange(0, 0, 3, 3);
-
- if (unitId && subUnitId && rangeFirst && rangeSecond) {
- const res = await permission.addRangeBaseProtection(unitId, subUnitId, [rangeFirst]);
- if (!res?.permissionId || !res?.ruleId) {
- return;
- }
- permission.setRangeProtectionPermissionPoint(unitId, subUnitId, res.permissionId, RangeProtectionPermissionEditPoint, false);
- let editValue = permissionService.getPermissionPoint(new RangeProtectionPermissionEditPoint(unitId, subUnitId, res.permissionId).id)?.value;
- expect(editValue).toBe(false);
- permission.setRangeProtectionPermissionPoint(unitId, subUnitId, res.permissionId, RangeProtectionPermissionEditPoint, true);
- editValue = permissionService.getPermissionPoint(new RangeProtectionPermissionEditPoint(unitId, subUnitId, res.permissionId).id)?.value;
- expect(editValue).toBe(true);
- let catchErr = false;
- try {
- await permission.addWorksheetBasePermission(unitId, subUnitId);
- } catch (e) {
- catchErr = true;
- }
- // expect(catchErr).toBe(true);
- permission.setRangeProtectionRanges(unitId, subUnitId, res.ruleId, [rangeSecond]);
- let rule = rangeProtectionRuleModel.getRule(unitId, subUnitId, res.ruleId);
- expect(rule?.ranges).toStrictEqual([rangeSecond].map((range) => range.getRange()));
- permission.removeRangeProtection(unitId, subUnitId, [res.ruleId]);
- rule = rangeProtectionRuleModel.getRule(unitId, subUnitId, res.ruleId);
- expect(rule).toBeUndefined();
- }
- });
-});
diff --git a/packages/sheets/src/facade/f-permission.ts b/packages/sheets/src/facade/f-permission.ts
deleted file mode 100644
index bbb4a078bb..0000000000
--- a/packages/sheets/src/facade/f-permission.ts
+++ /dev/null
@@ -1,725 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * 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 { RangePermissionPointConstructor, WorkbookPermissionPointConstructor, WorkSheetPermissionPointConstructor } from '@univerjs/core';
-import type { ICollaborator } from '@univerjs/protocol';
-import type { IAddRangeProtectionMutationParams, ISetWorksheetPermissionPointsMutationParams } from '@univerjs/sheets';
-import type { Observable } from 'rxjs';
-import type { FRange } from './f-range';
-import type { IRangeProtectionOptions, IWorksheetProtectionOptions } from './permission/permission-types';
-import { cellToRange, generateRandomId, IAuthzIoService, ICommandService, Inject, Injector, IPermissionService, Rectangle } from '@univerjs/core';
-import { FBase } from '@univerjs/core/facade';
-import { AddRangeProtectionMutation, AddWorksheetProtectionMutation, DeleteRangeProtectionMutation, DeleteWorksheetProtectionMutation, EditStateEnum, getAllWorksheetPermissionPoint, getAllWorksheetPermissionPointByPointPanel, PermissionPointsDefinitions, RangeProtectionRuleModel, SetRangeProtectionMutation, SetWorksheetPermissionPointsMutation, UnitObject, ViewStateEnum, WorkbookEditablePermission, WorkbookPermissionService, WorksheetEditPermission, WorksheetProtectionPointModel, WorksheetProtectionRuleModel, WorksheetViewPermission } from '@univerjs/sheets';
-import { UnitRole } from './permission/permission-types';
-
-/**
- * @description Used to generate permission instances to control permissions for the entire workbook
- * @deprecated This class is deprecated. Use the new permission API instead:
- * - For workbook-level permissions, use `workbook.getWorkbookPermission()`
- * - For worksheet-level permissions, use `worksheet.getWorksheetPermission()`
- * - For range-level permissions, use `range.getRangePermission()`
- *
- * The new API provides:
- * - More intuitive and type-safe interfaces
- * - Better support for RxJS Observable streams
- * - Enum-based permission points instead of class constructors
- * - Simplified collaborator management
- * - Mode-based permission settings (viewer, editor, owner, etc.)
- *
- * Migration examples:
- * ```ts
- * // Old API
- * const permission = workbook.getPermission();
- * await permission.addRangeBaseProtection(unitId, subUnitId, ranges);
- *
- * // New API
- * const worksheet = workbook.getSheetBySheetId(subUnitId);
- * const permission = worksheet.getWorksheetPermission();
- * await permission.protectRanges([{ ranges, options: { name: 'Protected', allowEdit: false } }]);
- * ```
- * @hideconstructor
- */
-export class FPermission extends FBase {
- /**
- * Permission point definition, can read the point constructor want to modify from here
- */
- public permissionPointsDefinition = PermissionPointsDefinitions;
- /**
- * An observable object used to monitor permission change events within a range, thereby triggering corresponding subsequent processing.
- */
- public rangeRuleChangedAfterAuth$: Observable<string>;
- /**
- * An observable object used to monitor permission change events within a worksheet, thereby triggering corresponding subsequent processing.
- */
- public sheetRuleChangedAfterAuth$: Observable<string>;
-
- /**
- * An observable object used to monitor the initialization state changes of unit permissions.
- */
- public unitPermissionInitStateChange$: Observable<boolean>;
-
- constructor(
- @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(WorkbookPermissionService) protected readonly _workbookPermissionService: WorkbookPermissionService,
- @Inject(IAuthzIoService) protected readonly _authzIoService: IAuthzIoService
- ) {
- super();
- this.rangeRuleChangedAfterAuth$ = this._rangeProtectionRuleModel.ruleRefresh$;
- this.sheetRuleChangedAfterAuth$ = this._worksheetProtectionRuleModel.ruleRefresh$;
- this.unitPermissionInitStateChange$ = this._workbookPermissionService.unitPermissionInitStateChange$;
- }
-
- /**
- * Configures a specific permission point for a workbook.
- * This function sets or updates a permission point for a workbook identified by `unitId`.
- * It creates a new permission point if it does not already exist, and updates the point with the provided value.
- * @param {string} unitId - The unique identifier of the workbook for which the permission is being set.
- * @param {WorkbookPermissionPointConstructor} FPointClass - The constructor function for creating a permission point instance. Other point constructors can See the [permission-point documentation](https://github.com/dream-num/univer/tree/dev/packages/sheets/src/services/permission/permission-point) for more details.
- * @param {boolean} value - The boolean value to determine whether the permission point is enabled or disabled.
- *
- * @example
- * ```typescript
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook.getPermission();
- * const unitId = workbook.getId();
- * permission.setWorkbookPermissionPoint(unitId, permission.permissionPointsDefinition.WorkbookEditablePermission, false)
- * ```
- */
- setWorkbookPermissionPoint(unitId: string, FPointClass: WorkbookPermissionPointConstructor, value: boolean): void {
- const instance = new FPointClass(unitId);
- const permissionPoint = this._permissionService.getPermissionPoint(instance.id);
- if (!permissionPoint) {
- this._permissionService.addPermissionPoint(instance);
- }
- this._permissionService.updatePermissionPoint(instance.id, value);
- }
-
- /**
- * Check if a specific permission point is enabled for a workbook.
- * @param unitId - The unique identifier of the workbook.
- * @param FPointClass - The constructor for the permission point class.
- * See the [permission-point documentation](https://github.com/dream-num/univer/tree/dev/packages/sheets/src/services/permission/permission-point) for more details.
- * @example
- * ```typescript
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook.getPermission();
- * const unitId = workbook.getId();
- * // Check if the workbook is editable
- * const isEditable = permission.checkWorkbookPermissionPoint(unitId, permission.permissionPointsDefinition.WorkbookEditablePermission);
- * console.log('Workbook is editable:', isEditable);
- * ```
- */
- checkWorkbookPermissionPoint(unitId: string, FPointClass: WorkbookPermissionPointConstructor): boolean | undefined {
- const instance = new FPointClass(unitId);
- const permissionPoint = this._permissionService.getPermissionPoint(instance.id);
- if (permissionPoint) {
- return permissionPoint.value;
- }
- return undefined;
- }
-
- /**
- * This function is used to set whether the workbook can be edited
- * @param {string} unitId - The unique identifier of the workbook for which the permission is being set.
- * @param {boolean} value - A value that controls whether the workbook can be edited
- *
- * @example
- * ```typescript
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook.getPermission();
- * const unitId = workbook.getId();
- * permission.setWorkbookEditPermission(unitId, false);
- * ```
- */
- setWorkbookEditPermission(unitId: string, value: boolean): void {
- this.setWorkbookPermissionPoint(unitId, WorkbookEditablePermission, value);
- }
-
- /**
- * This function is used to add a base permission for a worksheet.
- * Note that after adding, only the background mask of the permission module will be rendered. If you want to modify the function permissions,
- * you need to modify the permission points with the permissionId returned by this function.
- * @param {string} unitId - The unique identifier of the workbook for which the permission is being set.
- * @param {string} subUnitId - The unique identifier of the worksheet for which the permission is being set.
- * @param {IWorksheetProtectionOptions} options - Optional protection options including allowed users and name.
- * @returns {Promise<string | undefined>} - Returns the `permissionId` if the permission is successfully added. If the operation fails or no result is returned, it resolves to `undefined`.
- *
- * @example
- * ```typescript
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook.getPermission();
- * const unitId = workbook.getId();
- * const worksheet = workbook.getActiveSheet();
- * const subUnitId = worksheet.getSheetId();
- * // Note that there will be no permission changes after this step is completed. It only returns an ID for subsequent permission changes.
- * // For details, please see the example of the **`setWorksheetPermissionPoint`** API.
- * const permissionId = await permission.addWorksheetBasePermission(unitId, subUnitId, {
- * allowedUsers: ['user1', 'user2'],
- * name: 'My Protection'
- * })
- * // Can still edit and read it.
- * console.log('debugger', permissionId)
- * ```
- */
- async addWorksheetBasePermission(unitId: string, subUnitId: string, options?: IWorksheetProtectionOptions): Promise<string | undefined> {
- // const hasRangeProtection = this._rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId).length > 0;
- // if (hasRangeProtection) {
- // throw new Error('sheet protection cannot intersect with range protection');
- // }
- let collaborators: ICollaborator[] = [];
- if (options?.allowedUsers) {
- // Fetch existing collaborators first
- const existingCollaborators = await this._authzIoService.listCollaborators({
- objectID: unitId,
- unitID: unitId,
- });
-
- // Create a map of allowed user IDs for easy lookup
- const allowedUserIds = new Set(options.allowedUsers);
-
- // Filter and include only the allowed users with complete information
- collaborators = existingCollaborators
- .filter((c) => allowedUserIds.has(c.subject?.userID || c.id))
- .map((c) => ({
- id: c.id,
- role: UnitRole.Editor,
- subject: c.subject,
- }));
-
- // Check for any user IDs that weren't found in existing collaborators
- const foundUserIds = new Set(collaborators.map((c) => c.subject?.userID || c.id));
- options.allowedUsers.forEach((userId) => {
- if (!foundUserIds.has(userId)) {
- console.error(`User ${userId} not found in collaborators list`);
- }
- });
- }
-
- const permissionId = await this._authzIoService.create({
- objectType: UnitObject.Worksheet,
- worksheetObject: {
- collaborators,
- unitID: unitId,
- strategies: [],
- name: options?.name || '',
- scope: undefined,
- },
- });
- const res = this._commandService.syncExecuteCommand(AddWorksheetProtectionMutation.id, {
- unitId,
- subUnitId,
- rule: {
- permissionId,
- unitType: UnitObject.Worksheet,
- unitId,
- subUnitId,
- },
- });
- if (res) {
- return permissionId;
- }
- }
-
- /**
- * Delete the entire table protection set for the worksheet and reset the point permissions of the worksheet to true
- * @param {string} unitId - The unique identifier of the workbook for which the permission is being set.
- * @param {string} subUnitId - The unique identifier of the worksheet for which the permission is being set.
- *
- * @example
- * ```typescript
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook.getPermission();
- * const unitId = workbook.getId();
- * const worksheet = workbook.getActiveSheet();
- * const subUnitId = worksheet.getSheetId();
- * permission.removeWorksheetPermission(unitId, subUnitId);
- * ```
- */
- removeWorksheetPermission(unitId: string, subUnitId: string): void {
- this._commandService.syncExecuteCommand(DeleteWorksheetProtectionMutation.id, {
- unitId,
- subUnitId,
- });
-
- [...getAllWorksheetPermissionPoint(), ...getAllWorksheetPermissionPointByPointPanel()].forEach((F) => {
- const instance = new F(unitId, subUnitId);
- this._permissionService.updatePermissionPoint(instance.id, true);
- });
- this._worksheetProtectionPointRuleModel.deleteRule(unitId, subUnitId);
- }
-
- /**
- * Sets the worksheet permission point by updating or adding the permission point for the worksheet.
- * If the worksheet doesn't have a base permission, it creates one to used render
- * @param {string} unitId - The unique identifier of the workbook.
- * @param {string} subUnitId - The unique identifier of the worksheet.
- * @param {WorkSheetPermissionPointConstructor} FPointClass - The constructor for the permission point class.
- * See the [permission-point documentation](https://github.com/dream-num/univer/tree/dev/packages/sheets/src/services/permission/permission-point) for more details.
- * @param {boolean} value - The new permission value to be set for the worksheet.
- * @returns {Promise<string | undefined>} - Returns the `permissionId` if the permission point is successfully set or created. If no permission is set, it resolves to `undefined`.
- *
- * @example
- * ```typescript
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook.getPermission();
- * const unitId = workbook.getId();
- * const worksheet = workbook.getActiveSheet();
- * const subUnitId = worksheet.getSheetId();
- * const permissionId = await permission.addWorksheetBasePermission(unitId, subUnitId)
- * // After this line of code , the worksheet will no longer be editable
- * permission.setWorksheetPermissionPoint(unitId, subUnitId, permission.permissionPointsDefinition.WorksheetEditPermission, false);
- * ```
- */
- async setWorksheetPermissionPoint(unitId: string, subUnitId: string, FPointClass: WorkSheetPermissionPointConstructor, value: boolean): Promise<string | undefined> {
- const hasBasePermission = this._worksheetProtectionRuleModel.getRule(unitId, subUnitId);
- let permissionId;
- const isBasePoint = FPointClass === WorksheetEditPermission || FPointClass === WorksheetViewPermission;
- if (isBasePoint) {
- if (!hasBasePermission) {
- // const hasRangeProtection = this._rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId).length > 0;
- // if (hasRangeProtection) {
- // throw new Error('sheet protection cannot intersect with range protection');
- // }
- permissionId = await this.addWorksheetBasePermission(unitId, subUnitId);
- } else {
- permissionId = hasBasePermission.permissionId;
- }
- } else {
- const rule = this._worksheetProtectionPointRuleModel.getRule(unitId, subUnitId);
- if (!rule) {
- permissionId = await this._authzIoService.create({
- objectType: UnitObject.Worksheet,
- worksheetObject: {
- collaborators: [],
- unitID: unitId,
- strategies: [],
- name: '',
- scope: undefined,
- },
- });
- this._commandService.syncExecuteCommand<ISetWorksheetPermissionPointsMutationParams>(SetWorksheetPermissionPointsMutation.id, { unitId, subUnitId, rule: { unitId, subUnitId, permissionId } });
- } else {
- permissionId = rule.permissionId;
- }
- }
-
- const instance = new FPointClass(unitId, subUnitId);
- const permissionPoint = this._permissionService.getPermissionPoint(instance.id);
- if (!permissionPoint) {
- this._permissionService.addPermissionPoint(instance);
- }
-
- // IMPORTANT: Update authzIoService FIRST to set override before triggering pointChange$
- if (permissionId) {
- const actionNumber = instance.subType;
- // Set strategy: Reader role = deny, Owner role = allow
- await this._authzIoService.update({
- objectType: UnitObject.Worksheet,
- objectID: permissionId,
- strategies: [{
- action: actionNumber,
- role: value ? UnitRole.Owner : UnitRole.Reader,
- }],
- unitID: unitId,
- share: undefined,
- name: '',
- scope: undefined,
- collaborators: undefined,
- });
- }
- // Now update permissionPoint, which triggers pointChange$ and _initWorksheetPermissionPointsChange()
- // At this point, authzIoService.allowed() will find the override and return the correct value
- this._permissionService.updatePermissionPoint(instance.id, value);
-
- return permissionId;
- }
-
- /**
- * Check if a specific permission point is enabled for a worksheet.
- * @param unitId - The unique identifier of the workbook.
- * @param subUnitId - The unique identifier of the worksheet.
- * @param FPointClass - The constructor for the permission point class.
- * See the [permission-point documentation](https://github.com/dream-num/univer/tree/dev/packages/sheets/src/services/permission/permission-point) for more details.
- * @returns {boolean | undefined} - Returns true if the permission point is enabled, false if it is disabled, or undefined if the permission point does not exist.
- * @example
- * ```typescript
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook.getPermission();
- * const unitId = workbook.getId();
- * const worksheet = workbook.getActiveSheet();
- * const subUnitId = worksheet.getSheetId();
- * // Check if the worksheet is editable
- * const isEditable = permission.checkWorksheetPermissionPoint(unitId, subUnitId, permission.permissionPointsDefinition.WorksheetEditPermission);
- * console.log('Worksheet is editable:', isEditable);
- * ```
- */
- checkWorksheetPermissionPoint(unitId: string, subUnitId: string, FPointClass: WorkSheetPermissionPointConstructor): boolean | undefined {
- const instance = new FPointClass(unitId, subUnitId);
- const permissionPoint = this._permissionService.getPermissionPoint(instance.id);
- if (permissionPoint) {
- return permissionPoint.value;
- }
- return undefined;
- }
-
- /**
- * Adds a range protection to the worksheet.
- * Note that after adding, only the background mask of the permission module will be rendered. If you want to modify the function permissions,
- * you need to modify the permission points with the permissionId returned by this function.
- * @deprecated Use `worksheet.getWorksheetPermission().protectRanges()` instead
- * @param {string} unitId - The unique identifier of the workbook.
- * @param {string} subUnitId - The unique identifier of the worksheet.
- * @param {FRange[]} ranges - The ranges to be protected.
- * @param {IRangeProtectionOptions} options - Optional protection options including allowed users and name.
- * @returns {Promise<{ permissionId: string, ruleId: string } | undefined>} - Returns an object containing the `permissionId` and `ruleId` if the range protection is successfully added. If the operation fails or no result is returned, it resolves to `undefined`. permissionId is used to stitch permission point ID,ruleId is used to store permission rules
- *
- * @example
- * ```typescript
- * // Old API
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook.getPermission();
- * const unitId = workbook.getId();
- * const worksheet = workbook.getActiveSheet();
- * const subUnitId = worksheet.getSheetId();
- * const range = worksheet.getRange('A1:B2');
- * const ranges = [];
- * ranges.push(range);
- * const res = await permission.addRangeBaseProtection(unitId, subUnitId, ranges, {
- * name: 'Protected Area',
- * allowEdit: false
- * });
- * const {permissionId, ruleId} = res;
- * console.log('debugger', permissionId, ruleId);
- *
- * // New API (recommended)
- * const worksheet = univerAPI.getActiveWorkbook().getActiveSheet();
- * const permission = worksheet.getWorksheetPermission();
- * const range = worksheet.getRange('A1:B2');
- * await permission.protectRanges([{
- * ranges: [range],
- * options: { name: 'Protected Area', allowEdit: false }
- * }]);
- * ```
- */
- // eslint-disable-next-line max-lines-per-function
- async addRangeBaseProtection(unitId: string, subUnitId: string, ranges: FRange[], options?: IRangeProtectionOptions): Promise<{
- permissionId: string;
- ruleId: string;
- } | undefined> {
- // Fetch existing collaborators if allowedUsers is provided
- let collaborators: ICollaborator[] = [];
- if (options?.allowedUsers) {
- // Fetch existing collaborators first
- const existingCollaborators = await this._authzIoService.listCollaborators({
- objectID: unitId,
- unitID: unitId,
- });
-
- // Create a map of allowed user IDs for easy lookup
- const allowedUserIds = new Set(options.allowedUsers);
-
- // Filter and include only the allowed users with complete information
- collaborators = existingCollaborators
- .filter((c) => allowedUserIds.has(c.subject?.userID || c.id))
- .map((c) => ({
- id: c.id,
- role: UnitRole.Editor,
- subject: c.subject,
- }));
-
- // Check for any user IDs that weren't found in existing collaborators
- const foundUserIds = new Set(collaborators.map((c) => c.subject?.userID || c.id));
- options.allowedUsers.forEach((userId) => {
- if (!foundUserIds.has(userId)) {
- console.error(`User ${userId} not found in collaborators list`);
- }
- });
- }
-
- // Create permission ID with collaborators support
- const permissionId = await this._authzIoService.create({
- objectType: UnitObject.SelectRange,
- selectRangeObject: {
- collaborators,
- unitID: unitId,
- name: options?.name || '',
- scope: undefined,
- },
- });
- const ruleId = `ruleId_${generateRandomId(6)}`;
- // const worksheetProtection = this._worksheetProtectionRuleModel.getRule(unitId, subUnitId);
- // if (worksheetProtection) {
- // throw new Error('sheet protection cannot intersect with range protection');
- // }
- const subunitRuleList = this._rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId);
- const overlap = subunitRuleList.some((rule) => {
- return rule.ranges.some((range) => {
- return ranges.some((newRange) => {
- return Rectangle.intersects(newRange.getRange(), range);
- });
- });
- });
- if (overlap) {
- throw new Error('range protection cannot intersect');
- }
-
- // Determine view and edit states
- const viewState = this._determineRangeViewState(options);
- const editState = this._determineRangeEditState(options);
- const params: IAddRangeProtectionMutationParams = {
- unitId,
- subUnitId,
- rules: [{
- permissionId,
- unitType: UnitObject.SelectRange,
- unitId,
- subUnitId,
- ranges: ranges.map((range) => range.getRange()),
- id: ruleId,
- description: options?.name,
- viewState,
- editState,
- }],
- };
-
- const res = this._commandService.syncExecuteCommand(AddRangeProtectionMutation.id, params);
- if (res) {
- return {
- permissionId,
- ruleId,
- };
- }
- }
-
- /**
- * Determine view state from range protection options
- * @private
- */
- private _determineRangeViewState(options?: IRangeProtectionOptions): ViewStateEnum {
- if (options?.allowViewByOthers === false) {
- return ViewStateEnum.NoOneElseCanView; // ViewStateEnum.NoOneElseCanView
- }
- return ViewStateEnum.OthersCanView; // ViewStateEnum.OthersCanView
- }
-
- /**
- * Determine edit state from range protection options
- * @private
- */
- private _determineRangeEditState(options?: IRangeProtectionOptions): EditStateEnum {
- if (options?.allowEdit === true && options?.allowedUsers?.length) {
- return EditStateEnum.DesignedUserCanEdit;
- }
- return EditStateEnum.OnlyMe;
- }
-
- /**
- * Removes the range protection from the worksheet.
- * @deprecated Use `worksheet.getWorksheetPermission().unprotectRules()` instead
- * @param {string} unitId - The unique identifier of the workbook.
- * @param {string} subUnitId - The unique identifier of the worksheet.
- * @param {string[]} ruleIds - The rule IDs of the range protection to be removed.
- *
- * @example
- * ```typescript
- * // Old API
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook.getPermission();
- * const unitId = workbook.getId();
- * const worksheet = workbook.getActiveSheet();
- * const subUnitId = worksheet.getSheetId();
- * const range = worksheet.getRange('A1:B2');
- * const ranges = [];
- * ranges.push(range);
- * const res = await permission.addRangeBaseProtection(unitId, subUnitId, ranges);
- * const ruleId = res.ruleId;
- * permission.removeRangeProtection(unitId, subUnitId, [ruleId]);
- *
- * // New API (recommended)
- * const worksheet = univerAPI.getActiveWorkbook().getActiveSheet();
- * const permission = worksheet.getWorksheetPermission();
- * await permission.unprotectRules([ruleId]);
- * ```
- */
- removeRangeProtection(unitId: string, subUnitId: string, ruleIds: string[]): void {
- const res = this._commandService.syncExecuteCommand(DeleteRangeProtectionMutation.id, {
- unitId,
- subUnitId,
- ruleIds,
- });
- if (res) {
- const ruleList = this._rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId);
- if (ruleList.length === 0) {
- // because this rule is attached to other protection, if other protection is deleted, this rule should be deleted.
- this._worksheetProtectionPointRuleModel.deleteRule(unitId, subUnitId);
- [...getAllWorksheetPermissionPointByPointPanel()].forEach((F) => {
- const instance = new F(unitId, subUnitId);
- this._permissionService.updatePermissionPoint(instance.id, instance.value);
- });
- }
- }
- }
-
- /**
- * Modify the permission points of a custom area
- * @param {string} unitId - The unique identifier of the workbook.
- * @param {string} subUnitId - The unique identifier of the worksheet within the workbook.
- * @param {string} permissionId - The unique identifier of the permission that controls access to the range.
- * @param {RangePermissionPointConstructor} FPointClass - The constructor for the range permission point class.
- * See the [permission-point documentation](https://github.com/dream-num/univer/tree/dev/packages/sheets/src/services/permission/permission-point) for more details.
- * @param {boolean} value - The new permission value to be set for the range (e.g., true for allowing access, false for restricting access).
- *
- * @example
- * ```typescript
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook.getPermission();
- * const unitId = workbook.getId();
- * const worksheet = workbook.getActiveSheet();
- * const subUnitId = worksheet.getSheetId();
- * const range = worksheet.getRange('A1:B2');
- * const ranges = [];
- * ranges.push(range);
- * // Note that there will be no permission changes after this step is completed. It only returns an ID for subsequent permission changes.
- * // For details, please see the example of the **`setRangeProtectionPermissionPoint`** API.
- * const res = await permission.addRangeBaseProtection(unitId, subUnitId, ranges);
- * const {permissionId, ruleId} = res;
- * // After passing the following line of code, the range set above will become uneditable
- * permission.setRangeProtectionPermissionPoint(unitId,subUnitId,permissionId, permission.permissionPointsDefinition.RangeProtectionPermissionEditPoint, false);
- * ```
- */
- setRangeProtectionPermissionPoint(unitId: string, subUnitId: string, permissionId: string, FPointClass: RangePermissionPointConstructor, value: boolean): void {
- const instance = new FPointClass(unitId, subUnitId, permissionId);
- const permissionPoint = this._permissionService.getPermissionPoint(instance.id);
- if (!permissionPoint) {
- this._permissionService.addPermissionPoint(instance);
- }
- this._permissionService.updatePermissionPoint(instance.id, value);
- }
-
- /**
- * Sets the ranges for range protection in a worksheet.
- *
- * This method finds the rule by unitId, subUnitId, and ruleId, and updates the rule with the provided ranges.
- * It checks for overlaps with existing ranges in the same subunit and shows an error message if any overlap is detected.
- * If no overlap is found, it executes the command to update the range protection with the new ranges.
- * @param {string} unitId - The unique identifier of the workbook.
- * @param {string} subUnitId - The unique identifier of the worksheet within the workbook.
- * @param {string} ruleId - The ruleId of the range protection rule that is being updated.
- * @param {FRange[]} ranges - The array of new ranges to be set for the range protection rule.
- *
- * @example
- * ```typescript
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook.getPermission();
- * const unitId = workbook.getId();
- * const worksheet = workbook.getActiveSheet();
- * const subUnitId = worksheet.getSheetId();
- * const range = worksheet.getRange('A1:B2');
- * const ranges = [];
- * ranges.push(range);
- * const res = await permission.addRangeBaseProtection(unitId, subUnitId, ranges);
- * const {permissionId, ruleId} = res;
- * const newRange = worksheet.getRange('C1:D2');
- * permission.setRangeProtectionRanges(unitId, subUnitId, ruleId, [newRange]);
- * ```
- */
- setRangeProtectionRanges(unitId: string, subUnitId: string, ruleId: string, ranges: FRange[]): void {
- const rule = this._rangeProtectionRuleModel.getRule(unitId, subUnitId, ruleId);
- if (rule) {
- const subunitRuleList = this._rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId).filter((r) => r.id !== ruleId);
- const overlap = subunitRuleList.some((rule) => {
- return rule.ranges.some((range) => {
- return ranges.some((newRange) => {
- return Rectangle.intersects(newRange.getRange(), range);
- });
- });
- });
- if (overlap) {
- throw new Error('range protection cannot intersect');
- }
- this._commandService.syncExecuteCommand(SetRangeProtectionMutation.id, {
- unitId,
- subUnitId,
- ruleId,
- rule: {
- ...rule,
- ranges: ranges.map((range) => range.getRange()),
- },
- });
- }
- }
-
- /**
- * Get the permission information for a specific cell in a worksheet.
- * @param {string} unitId - The unique identifier of the workbook.
- * @param {string} subUnitId - The unique identifier of the worksheet within the workbook.
- * @param {number} row - The row index of the cell.
- * @param {number} column - The column index of the cell.
- * @returns {{ permissionId: string, ruleId: string } | undefined} - Returns an object containing the `permissionId` and `ruleId` if the cell is protected by a range protection rule. If no protection is found, it returns `undefined`.
- *
- * @example
- * ```typescript
- * const fWorkbook = univerAPI.getActiveWorkbook();
- * const fWorksheet = fWorkbook.getActiveSheet();
- * const permission = fWorkbook.getPermission();
- * const unitId = fWorkbook.getId();
- * const subUnitId = fWorksheet.getSheetId();
- *
- * // Get the permission information for cell C3
- * const cell = fWorksheet.getRange('C3');
- * const permissionInfo = permission.getPermissionInfoWithCell(
- * unitId,
- * subUnitId,
- * cell.getRow(),
- * cell.getColumn()
- * );
- * console.log(permissionInfo);
- *
- * // If the cell is protected, you can remove the protection like this:
- * if (permissionInfo) {
- * const { ruleId } = permissionInfo;
- *
- * // After 2 seconds, remove the protection for the cell
- * setTimeout(() => {
- * permission.removeRangeProtection(unitId, subUnitId, [ruleId]);
- * }, 2000);
- * }
- * ```
- */
- getPermissionInfoWithCell(unitId: string, subUnitId: string, row: number, column: number): {
- permissionId: string;
- ruleId: string;
- } | undefined {
- const cellRange = cellToRange(row, column);
- const overlapRule = this._rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId).find((rule) => {
- const ranges = rule.ranges;
- return ranges.some((range) => {
- return Rectangle.intersects(cellRange, range);
- });
- });
- if (overlapRule) {
- return {
- permissionId: overlapRule.permissionId,
- ruleId: overlapRule.id,
- };
- }
- }
-}
diff --git a/packages/sheets/src/facade/f-univer.ts b/packages/sheets/src/facade/f-univer.ts
index d900f8acfa..a9efacf02b 100644
--- a/packages/sheets/src/facade/f-univer.ts
+++ b/packages/sheets/src/facade/f-univer.ts
@@ -68,7 +68,6 @@ import {
ToggleGridlinesCommand,
} from '@univerjs/sheets';
import { FDefinedNameBuilder } from './f-defined-name';
-import { FPermission } from './f-permission';
import { FWorkbook } from './f-workbook';
/**
@@ -133,12 +132,6 @@ export interface IFUniverSheetsMixin {
getWorkbook(id: string): FWorkbook | null;
- /**
- * Get the PermissionInstance.
- * @deprecated This function is deprecated and will be removed in version 0.6.0. Please use the function with the same name on the `FWorkbook` instance instead.
- */
- getPermission(): FPermission;
-
/**
* @deprecated Use `univerAPI.addEvent(univerAPI.Event.UnitCreated, () => {})`
*/
@@ -734,10 +727,6 @@ export class FUniverSheetsMixin extends FUniver implements IFUniverSheetsMixin {
return this.getUniverSheet(id);
}
- override getPermission(): FPermission {
- return this._injector.createInstance(FPermission);
- }
-
override onUniverSheetCreated(callback: (workbook: FWorkbook) => void): IDisposable {
const subscription = this._univerInstanceService.getTypeOfUnitAdded$<Workbook>(UniverInstanceType.UNIVER_SHEET).subscribe((workbook) => {
const fworkbook = this._injector.createInstance(FWorkbook, workbook);
diff --git a/packages/sheets/src/facade/f-workbook.ts b/packages/sheets/src/facade/f-workbook.ts
index 6a32ec9df1..9cea944c3e 100644
--- a/packages/sheets/src/facade/f-workbook.ts
+++ b/packages/sheets/src/facade/f-workbook.ts
@@ -23,7 +23,6 @@ import { FBaseInitialable } from '@univerjs/core/facade';
import { IDefinedNamesService } from '@univerjs/engine-formula';
import { CopySheetCommand, getPrimaryForRange, InsertSheetCommand, RangeThemeStyle, RegisterWorksheetRangeThemeStyleCommand, RemoveSheetCommand, SCOPE_WORKBOOK_VALUE_DEFINED_NAME, SetDefinedNameCommand, SetSelectionsOperation, SetWorkbookNameCommand, SetWorksheetActiveOperation, SetWorksheetOrderCommand, SheetRangeThemeService, SheetsSelectionsService, UnregisterWorksheetRangeThemeStyleCommand, 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';
import { FWorkbookPermission } from './permission/f-workbook-permission';
@@ -800,21 +799,6 @@ export class FWorkbook extends FBaseInitialable {
return this.moveSheet(sheet, index);
}
- /**
- * Get the PermissionInstance.
- * @returns {FPermission} - The PermissionInstance.
- * @deprecated Use `getWorkbookPermission()` instead for the new permission API
- * @example
- * ```ts
- * const fWorkbook = univerAPI.getActiveWorkbook();
- * const permission = fWorkbook.getPermission();
- * console.log(permission);
- * ```
- */
- getPermission(): FPermission {
- return this._injector.createInstance(FPermission);
- }
-
/**
* Get the WorkbookPermission instance for managing workbook-level permissions.
* This is the new permission API that provides a more intuitive and type-safe interface.
diff --git a/packages/sheets/src/facade/index.ts b/packages/sheets/src/facade/index.ts
index ef874f072d..4ff6866a70 100644
--- a/packages/sheets/src/facade/index.ts
+++ b/packages/sheets/src/facade/index.ts
@@ -19,12 +19,12 @@ import './f-enum';
export * from './f-enum';
export * from './f-event';
-export { FPermission } from './f-permission';
export { FRange } from './f-range';
export { FSelection } from './f-selection';
export { FSheetHooks } from './f-sheet-hooks';
export { FWorkbook } from './f-workbook';
+export { FWorksheet } from './f-worksheet';
+export { FWorkbookPermission } from './permission/f-workbook-permission';
// eslint-disable-next-line perfectionist/sort-exports
export type * from './f-univer';
-export { FWorksheet } from './f-worksheet';
diff --git a/packages/sheets/src/facade/permission/f-range-permission.ts b/packages/sheets/src/facade/permission/f-range-permission.ts
index 731dfdab0d..f8440e776d 100644
--- a/packages/sheets/src/facade/permission/f-range-permission.ts
+++ b/packages/sheets/src/facade/permission/f-range-permission.ts
@@ -14,24 +14,17 @@
* limitations under the License.
*/
-import type { Nullable } from '@univerjs/core';
-import type { IRangeProtectionRule } from '@univerjs/sheets';
-import type { Observable, Subscription } from 'rxjs';
+import type { ICollaborator } from '@univerjs/protocol';
+import type { IAddRangeProtectionMutationParams } from '@univerjs/sheets';
import type { FRange } from '../f-range';
import type { FWorksheet } from '../f-worksheet';
-import type {
- IRangeProtectionOptions,
- RangePermissionSnapshot,
-} from './permission-types';
-import { IAuthzIoService, ICommandService, Inject, Injector, IPermissionService } from '@univerjs/core';
-import { UnitRole } from '@univerjs/protocol';
-import { EditStateEnum, RangeProtectionRuleModel, ViewStateEnum } from '@univerjs/sheets';
-import { BehaviorSubject } from 'rxjs';
-import { distinctUntilChanged, filter, map, shareReplay } from 'rxjs/operators';
-import { FPermission } from '../f-permission';
+import type { IRangeProtectionOptions } from './permission-types';
+import { generateRandomId, IAuthzIoService, ICommandService, Inject, Injector, Rectangle } from '@univerjs/core';
+import { FBase } from '@univerjs/core/facade';
+import { UnitObject, UnitRole } from '@univerjs/protocol';
+import { AddRangeProtectionMutation, EditStateEnum, RangeProtectionRuleModel } from '@univerjs/sheets';
import { FRangeProtectionRule } from './f-range-protection-rule';
-import { RANGE_PERMISSION_POINT_MAP } from './permission-point-map';
-import { RangePermissionPoint } from './permission-types';
+import { determineEditState, determineScope, determineViewState, getListRangeProtectionRules } from './util';
/**
* Implementation class for RangePermission
@@ -39,361 +32,42 @@ import { RangePermissionPoint } from './permission-types';
*
* @hideconstructor
*/
-export class FRangePermission {
- private readonly _permissionSubject: BehaviorSubject<RangePermissionSnapshot>;
- private readonly _subscriptions: Subscription[] = [];
- private readonly _fPermission: FPermission;
-
- /**
- * Observable stream of permission snapshot changes
- * @returns Observable that emits when permission snapshot changes
- */
- readonly permission$: Observable<RangePermissionSnapshot>;
-
- /**
- * Observable stream of protection state changes
- * @returns Observable that emits when protection state changes
- */
- readonly protectionChange$: Observable<{
- type: 'protected';
- rule: FRangeProtectionRule;
- } | {
- type: 'unprotected';
- ruleId: string;
- }>;
-
+export class FRangePermission extends FBase {
constructor(
private readonly _unitId: string,
private readonly _subUnitId: string,
private readonly _range: FRange,
private readonly _worksheet: FWorksheet,
@Inject(Injector) private readonly _injector: Injector,
- @Inject(IPermissionService) private readonly _permissionService: IPermissionService,
@Inject(IAuthzIoService) private readonly _authzIoService: IAuthzIoService,
@Inject(ICommandService) private readonly _commandService: ICommandService,
@Inject(RangeProtectionRuleModel) private readonly _rangeProtectionRuleModel: RangeProtectionRuleModel
) {
- // Initialize FPermission instance
- this._fPermission = this._injector.createInstance(FPermission);
-
- this._permissionSubject = new BehaviorSubject<RangePermissionSnapshot>(this._buildSnapshot());
-
- // Create permission$ stream from IPermissionService
- this.permission$ = this._createPermissionStream();
-
- // Create protectionChange$ stream from RangeProtectionRuleModel
- this.protectionChange$ = this._createProtectionChangeStream();
- }
-
- /**
- * Create permission snapshot stream from IPermissionService
- * @private
- */
- private _createPermissionStream(): Observable<RangePermissionSnapshot> {
- // Listen to permission point changes from IPermissionService
- const sub = this._permissionService.permissionPointUpdate$.pipe(
- filter((point) => {
- // Filter for permission points related to this range
- const pointId = point.id;
- return pointId.includes(this._unitId) && pointId.includes(this._subUnitId);
- })
- ).subscribe(() => {
- this._permissionSubject.next(this._buildSnapshot());
- });
-
- // Store subscription for cleanup
- this._subscriptions.push(sub);
-
- return this._permissionSubject.asObservable().pipe(
- distinctUntilChanged((prev, curr) => JSON.stringify(prev) === JSON.stringify(curr)),
- shareReplay({ bufferSize: 1, refCount: true })
- );
- }
-
- /**
- * Create protection change stream from RangeProtectionRuleModel
- * @private
- */
- private _createProtectionChangeStream(): Observable<{
- type: 'protected';
- rule: FRangeProtectionRule;
- } | {
- type: 'unprotected';
- ruleId: string;
- }> {
- return this._rangeProtectionRuleModel.ruleChange$.pipe(
- filter((change) => {
- // Only process changes for this worksheet
- if (change.unitId !== this._unitId || change.subUnitId !== this._subUnitId) {
- return false;
- }
-
- // Only emit for changes that affect this specific range
- if (change.type === 'delete') {
- // Check if the deleted rule was protecting this range
- return this._rangeMatches(change.rule);
- } else if (change.type === 'add') {
- // Check if the new rule protects this range
- return this._rangeMatches(change.rule);
- }
- return false;
- }),
- map((change) => {
- // Also update permission snapshot
- this._permissionSubject.next(this._buildSnapshot());
-
- if (change.type === 'delete') {
- return {
- type: 'unprotected' as const,
- ruleId: change.rule.id,
- };
- } else {
- // change.type === 'add'
- const rule = this._createFacadeRule(change.rule);
- return {
- type: 'protected' as const,
- rule,
- };
- }
- }),
- shareReplay({ bufferSize: 1, refCount: true })
- );
- }
-
- /**
- * Check if a protection rule matches this range
- */
- private _rangeMatches(rule: IRangeProtectionRule): boolean {
- const range = this._range.getRange();
- return rule.ranges.some((ruleRange) =>
- range.startRow === ruleRange.startRow &&
- range.startColumn === ruleRange.startColumn &&
- range.endRow === ruleRange.endRow &&
- range.endColumn === ruleRange.endColumn
- );
- }
-
- /**
- * Create a Facade rule from internal rule
- */
- private _createFacadeRule(rule: IRangeProtectionRule): FRangeProtectionRule {
- const ranges = rule.ranges.map((range) =>
- this._worksheet.getRange(
- range.startRow,
- range.startColumn,
- range.endRow - range.startRow + 1,
- range.endColumn - range.startColumn + 1
- )
- );
-
- const options: IRangeProtectionOptions = {
- name: rule.description || '',
- allowViewByOthers: rule.viewState !== ViewStateEnum.NoOneElseCanView,
- allowEdit: rule.editState === EditStateEnum.DesignedUserCanEdit,
- };
-
- return this._injector.createInstance(
- FRangeProtectionRule,
- this._unitId,
- this._subUnitId,
- rule.id,
- rule.permissionId,
- ranges,
- options
- );
- }
-
- /**
- * Get the value of a specific permission point.
- * @param {RangePermissionPoint} point The permission point to query.
- * @returns {boolean} true if allowed, false if denied.
- * @example
- * ```ts
- * const range = univerAPI.getActiveWorkbook()?.getActiveSheet()?.getRange('A1:B2');
- * const permission = range?.getRangePermission();
- * const canEdit = permission?.getPoint(univerAPI.Enum.RangePermissionPoint.Edit);
- * console.log(canEdit);
- * ```
- */
- getPoint(point: RangePermissionPoint): boolean {
- const PermissionPointClass = RANGE_PERMISSION_POINT_MAP[point];
- if (!PermissionPointClass) {
- console.warn(`Unknown permission point: ${point}`);
- return false;
- }
-
- // Try to get permission from protection rule
- const rule = this._getProtectionRule();
- if (rule) {
- const permissionPoint = new PermissionPointClass(this._unitId, this._subUnitId, rule.permissionId);
- const permission = this._permissionService.getPermissionPoint(permissionPoint.id);
- if (permission) {
- return permission.value;
- }
- }
-
- // Default to true (allowed) when no permission point is set
- // This aligns with worksheet-level permission behavior
- // If a range is not explicitly protected, it should be accessible
- return true;
- }
-
- /**
- * Get the current permission snapshot.
- * @returns {RangePermissionSnapshot} Snapshot of all permission points.
- * @example
- * ```ts
- * const range = univerAPI.getActiveWorkbook()?.getActiveSheet()?.getRange('A1:B2');
- * const permission = range?.getRangePermission();
- * const snapshot = permission?.getSnapshot();
- * console.log(snapshot);
- * ```
- */
- getSnapshot(): RangePermissionSnapshot {
- return this._buildSnapshot();
+ super();
}
/**
* Check if the current range is protected.
- * @returns {boolean} true if protected, false otherwise.
+ * @returns {boolean} True if the range is protected, false otherwise.
* @example
* ```ts
- * const range = univerAPI.getActiveWorkbook()?.getActiveSheet()?.getRange('A1:B2');
- * const permission = range?.getRangePermission();
- * const isProtected = permission?.isProtected();
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * // Check if the A1:B2 range is protected
+ * const isProtected = fRange.getRangePermission().isProtected();
* console.log(isProtected);
* ```
*/
isProtected(): boolean {
- return this._getProtectionRule() !== null;
- }
-
- /**
- * Check if the current user can edit this range.
- * @returns {boolean} true if editable, false otherwise.
- * @example
- * ```ts
- * const range = univerAPI.getActiveWorkbook()?.getActiveSheet()?.getRange('A1:B2');
- * const permission = range?.getRangePermission();
- * if (permission?.canEdit()) {
- * console.log('You can edit this range');
- * }
- * ```
- */
- canEdit(): boolean {
- // Always check the permission point value first
- // This handles cases where setPoint() was called without protect()
- return this.getPoint(RangePermissionPoint.Edit);
- }
-
- /**
- * Check if the current user can view this range.
- * @returns {boolean} true if viewable, false otherwise.
- * @example
- * ```ts
- * const range = univerAPI.getActiveWorkbook()?.getActiveSheet()?.getRange('A1:B2');
- * const permission = range?.getRangePermission();
- * if (permission?.canView()) {
- * console.log('You can view this range');
- * }
- * ```
- */
- canView(): boolean {
- // Always check the permission point value first
- // This handles cases where setPoint() was called without protect()
- return this.getPoint(RangePermissionPoint.View);
- }
-
- /**
- * Check if the current user can manage collaborators for this range.
- * @returns {boolean} true if can manage collaborators, false otherwise.
- * @example
- * ```ts
- * const range = univerAPI.getActiveWorkbook()?.getActiveSheet()?.getRange('A1:B2');
- * const permission = range?.getRangePermission();
- * if (permission?.canManageCollaborator()) {
- * console.log('You can manage collaborators for this range');
- * }
- * ```
- */
- canManageCollaborator(): boolean {
- // Always check the permission point value first
- // This handles cases where setPoint() was called without protect()
- return this.getPoint(RangePermissionPoint.ManageCollaborator);
- }
-
- /**
- * Check if the current user can delete this protection rule.
- * @returns {boolean} true if can delete rule, false otherwise.
- * @example
- * ```ts
- * const range = univerAPI.getActiveWorkbook()?.getActiveSheet()?.getRange('A1:B2');
- * const permission = range?.getRangePermission();
- * if (permission?.canDelete()) {
- * console.log('You can delete this protection rule');
- * }
- * ```
- */
- canDelete(): boolean {
- // Always check the permission point value first
- // This handles cases where setPoint() was called without protect()
- return this.getPoint(RangePermissionPoint.Delete);
- }
-
- /**
- * Set a specific permission point for the range (low-level API).
- *
- * **Important:** This method only updates the permission point value for an existing protection rule.
- * It does NOT create permission checks that will block actual editing operations.
- * You must call `protect()` first to create a protection rule before using this method.
- *
- * This method is useful for:
- * - Fine-tuning permissions after creating a protection rule with `protect()`
- * - Dynamically adjusting permissions based on runtime conditions
- * - Advanced permission management scenarios
- *
- * @param {RangePermissionPoint} point The permission point to set.
- * @param {boolean} value The value to set (true = allowed, false = denied).
- * @returns {Promise<void>} A promise that resolves when the point is set.
- * @throws {Error} If no protection rule exists for this range.
- *
- * @example
- * ```ts
- * const range = univerAPI.getActiveWorkbook()?.getActiveSheet()?.getRange('A1:B2');
- * const permission = range?.getRangePermission();
- *
- * // First, create a protection rule
- * await permission?.protect({ name: 'My Range', allowEdit: true });
- *
- * // Then you can dynamically update permission points
- * await permission?.setPoint(univerAPI.Enum.RangePermissionPoint.Edit, false); // Now disable edit
- * await permission?.setPoint(univerAPI.Enum.RangePermissionPoint.View, true); // Ensure view is enabled
- * ```
- */
- async setPoint(point: RangePermissionPoint, value: boolean): Promise<void> {
- const PermissionPointClass = RANGE_PERMISSION_POINT_MAP[point];
- if (!PermissionPointClass) {
- throw new Error(`Unknown permission point: ${point}`);
- }
-
- // Must have a protection rule to set permission points
- const rule = this._getProtectionRule();
- if (!rule) {
- throw new Error('Cannot set permission point: No protection rule exists for this range. Call protect() first.');
- }
-
- const oldValue = this.getPoint(point);
- if (oldValue === value) {
- return; // Value unchanged, no update needed
- }
-
- const permissionId = rule.permissionId;
+ const rules = this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId, this._subUnitId);
- // Use FPermission's setRangeProtectionPermissionPoint method
- this._fPermission.setRangeProtectionPermissionPoint(this._unitId, this._subUnitId, permissionId, PermissionPointClass, value);
+ // Filter rules that intersect with the current range
+ const matchingRules = rules.filter((rule) =>
+ rule.ranges.some((ruleRange) => Rectangle.intersects(ruleRange, this._range.getRange()))
+ );
- // Update snapshot (the Observable stream will automatically emit the change)
- this._permissionSubject.next(this._buildSnapshot());
+ return matchingRules.length > 0;
}
/**
@@ -402,38 +76,81 @@ export class FRangePermission {
* @returns {Promise<FRangeProtectionRule>} The created protection rule.
* @example
* ```ts
- * const range = univerAPI.getActiveWorkbook()?.getActiveSheet()?.getRange('A1:B2');
- * const permission = range?.getRangePermission();
- * const rule = await permission?.protect({
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * const rule = await fRange.getRangePermission().protect({
* name: 'My protected range',
- * allowEdit: true,
* allowedUsers: ['user1', 'user2'],
* allowViewByOthers: false,
* });
* console.log(rule);
* ```
*/
+
async protect(options?: IRangeProtectionOptions): Promise<FRangeProtectionRule> {
if (this.isProtected()) {
throw new Error('Range is already protected');
}
- // Use FPermission's addRangeBaseProtection method
- const result = await this._fPermission.addRangeBaseProtection(
- this._unitId,
- this._subUnitId,
- [this._range],
- options
- );
+ const editState = determineEditState(options?.allowedUsers);
+ const viewState = determineViewState(options?.allowViewByOthers);
+ const scope = determineScope(editState, viewState);
+
+ // Fetch existing collaborators if allowedUsers is provided
+ const collaborators: ICollaborator[] = [];
+ if (editState === EditStateEnum.DesignedUserCanEdit) {
+ const existingCollaborators = await this._authzIoService.listCollaborators({
+ objectID: this._unitId,
+ unitID: this._unitId,
+ });
+
+ options!.allowedUsers!.forEach((userId) => {
+ const existingCollaborator = existingCollaborators.find((c) => c.subject?.userID === userId || c.id === userId);
+ if (!existingCollaborator) {
+ console.error(`User ${userId} not found in existing collaborators`);
+ return;
+ }
- if (!result) {
- throw new Error('Failed to create range protection');
+ collaborators.push({
+ id: existingCollaborator.id,
+ role: UnitRole.Editor,
+ subject: existingCollaborator.subject,
+ });
+ });
}
- const { permissionId, ruleId } = result;
+ // Create permission ID with collaborators support
+ const permissionId = await this._authzIoService.create({
+ objectType: UnitObject.SelectRange,
+ selectRangeObject: {
+ collaborators,
+ unitID: this._unitId,
+ name: options?.name || '',
+ scope,
+ },
+ });
+ const ruleId = `ruleId_${generateRandomId(6)}`;
+
+ const result = this._commandService.syncExecuteCommand<IAddRangeProtectionMutationParams>(AddRangeProtectionMutation.id, {
+ unitId: this._unitId,
+ subUnitId: this._subUnitId,
+ rules: [{
+ ranges: [this._range.getRange()],
+ permissionId,
+ id: ruleId,
+ description: options?.name,
+ unitType: UnitObject.SelectRange,
+ unitId: this._unitId,
+ subUnitId: this._subUnitId,
+ viewState,
+ editState,
+ }],
+ });
- // Set permission points for local runtime control
- await this._setPermissionPoints(permissionId, options);
+ if (!result) {
+ throw new Error('Failed to add range protection');
+ }
// Create and return FRangeProtectionRule instance
const rule = this._injector.createInstance(
@@ -446,287 +163,63 @@ export class FRangePermission {
options || {}
);
- // The Observable stream will automatically emit the change
return rule;
}
/**
- * Determine view state from options
- * @private
- */
- private _determineViewState(options?: IRangeProtectionOptions): ViewStateEnum {
- if (options?.allowViewByOthers === false) {
- return ViewStateEnum.NoOneElseCanView; // Only owner can view
- }
- // For true, undefined, or string[], default to OthersCanView
- return ViewStateEnum.OthersCanView;
- }
-
- /**
- * Determine edit state from options
- * @private
- */
- private _determineEditState(options?: IRangeProtectionOptions): EditStateEnum {
- if (options?.allowEdit === true && options?.allowedUsers?.length) {
- return EditStateEnum.DesignedUserCanEdit; // Designed users can edit
- }
- // For false or undefined, default to OnlyMe
- return EditStateEnum.OnlyMe;
- }
-
- /**
- * Set permission points based on options (for local runtime control)
- * @private
- */
- private async _setPermissionPoints(permissionId: string, options?: IRangeProtectionOptions): Promise<void> {
- if (!options) {
- return;
- }
-
- // Helper function to determine permission value
- const getPermissionValue = (option: boolean | string[] | undefined, defaultValue: boolean): boolean => {
- if (option === undefined) {
- return defaultValue;
- }
- if (typeof option === 'boolean') {
- return option;
- }
- // For string[] (whitelist), we default to true and let the collaboration system handle it
- return true;
- };
-
- // Set permission points
- await this._setPermissionPoint(permissionId, RangePermissionPoint.Edit, getPermissionValue(options.allowEdit, false));
- await this._setPermissionPoint(permissionId, RangePermissionPoint.View, getPermissionValue(options.allowViewByOthers, true));
- }
-
- /**
- * Set a single permission point
- * @private
- */
- private async _setPermissionPoint(permissionId: string, point: RangePermissionPoint, value: boolean): Promise<void> {
- const PermissionPointClass = RANGE_PERMISSION_POINT_MAP[point];
- if (!PermissionPointClass) {
- return;
- }
-
- // Use FPermission's setRangeProtectionPermissionPoint method
- this._fPermission.setRangeProtectionPermissionPoint(this._unitId, this._subUnitId, permissionId, PermissionPointClass, value);
- }
-
- /**
- * Unprotect the current range.
- * @returns {Promise<void>} A promise that resolves when the range is unprotected.
+ * Cancel all protection rules that intersect with the current range.
+ * @returns {Promise<boolean>} True if all rules were successfully removed, false otherwise.
* @example
* ```ts
- * const range = univerAPI.getActiveWorkbook()?.getActiveSheet()?.getRange('A1:B2');
- * const permission = range?.getRangePermission();
- * await permission?.unprotect();
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * const result = await fRange.getRangePermission().unprotect();
+ * console.log(result);
* ```
*/
- async unprotect(): Promise<void> {
- const rule = this._getProtectionRule();
- if (!rule) {
- // Silently handle unprotecting a non-protected range
- return;
- }
+ async unprotect(): Promise<boolean> {
+ const rules = await this.listRules({ ignoreCollaborators: true });
+ if (rules.length === 0) return true;
+
+ const results = await Promise.all(rules.map((rule) => rule.remove()));
- const ruleId = rule.id;
+ for (const result of results) {
+ if (!result) {
+ console.error('Failed to remove some range protection rules');
+ return false;
+ }
+ }
- // Use FPermission's removeRangeProtection method
- this._fPermission.removeRangeProtection(this._unitId, this._subUnitId, [ruleId]);
+ return true;
}
/**
- * List all protection rules.
+ * List all protection rules that intersect with the current range.
* @returns {Promise<FRangeProtectionRule[]>} Array of protection rules.
* @example
* ```ts
- * const range = univerAPI.getActiveWorkbook()?.getActiveSheet()?.getRange('A1:B2');
- * const permission = range?.getRangePermission();
- * const rules = await permission?.listRules();
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * const rules = await fRange.getRangePermission().listRules();
* console.log(rules);
* ```
*/
- async listRules(): Promise<FRangeProtectionRule[]> {
- return await this._buildProtectionRulesAsync();
- }
-
- /**
- * Subscribe to permission changes (simplified interface).
- * @param {Function} listener Callback function to be called when permissions change.
- * @returns {Function} Unsubscribe function.
- * @example
- * ```ts
- * const range = univerAPI.getActiveWorkbook()?.getActiveSheet()?.getRange('A1:B2');
- * const permission = range?.getRangePermission();
- * const unsubscribe = permission?.subscribe((snapshot) => {
- * console.log('Permission changed:', snapshot);
- * });
- * // Later, to stop listening:
- * unsubscribe?.();
- * ```
- */
- subscribe(listener: (snapshot: RangePermissionSnapshot) => void): (() => void) {
- const subscription = this.permission$.subscribe(listener);
- return () => subscription.unsubscribe();
- }
-
- /**
- * Get the protection rule for the current range
- */
- private _getProtectionRule(): Nullable<IRangeProtectionRule> {
- const rules = this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId, this._subUnitId);
- const range = this._range.getRange();
-
- for (const rule of rules) {
- for (const ruleRange of rule.ranges) {
- if (
- range.startRow === ruleRange.startRow &&
- range.startColumn === ruleRange.startColumn &&
- range.endRow === ruleRange.endRow &&
- range.endColumn === ruleRange.endColumn
- ) {
- return rule;
- }
- }
+ async listRules(
+ options?: {
+ ignoreCollaborators?: boolean; // Option to ignore fetching collaborators for performance
}
-
- return null;
- }
-
- /**
- * Build Facade objects for all protection rules
- */
- private _buildProtectionRules(): FRangeProtectionRule[] {
- const rules = this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId, this._subUnitId);
-
- return rules.map((rule) => {
- const ranges = rule.ranges.map((range) =>
- this._worksheet.getRange(
- range.startRow,
- range.startColumn,
- range.endRow - range.startRow + 1,
- range.endColumn - range.startColumn + 1
- )
- );
-
- // Build options from rule state
- const options: IRangeProtectionOptions = {
- name: rule.description || '',
- allowViewByOthers: rule.viewState !== ViewStateEnum.NoOneElseCanView,
- };
-
- // Handle allowEdit based on editState
- if (rule.editState === EditStateEnum.DesignedUserCanEdit) {
- // Get collaborators list synchronously for this rule
- // Note: This is a synchronous context, but we need async data
- // We'll use a placeholder here and expect the caller to handle async properly
- // For now, we set it to an empty array as a fallback
- options.allowEdit = true;
- } else {
- options.allowEdit = false;
+ ): Promise<FRangeProtectionRule[]> {
+ return getListRangeProtectionRules(
+ this._injector,
+ this._unitId,
+ this._subUnitId,
+ {
+ worksheet: this._worksheet,
+ specificRange: this._range,
+ ignoreCollaborators: options?.ignoreCollaborators,
}
-
- return this._injector.createInstance(
- FRangeProtectionRule,
- this._unitId,
- this._subUnitId,
- rule.id,
- rule.permissionId,
- ranges,
- options
- );
- });
- }
-
- /**
- * Build Facade objects for all protection rules (async version with collaborator data)
- * @private
- */
- private async _buildProtectionRulesAsync(): Promise<FRangeProtectionRule[]> {
- const rules = this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId, this._subUnitId);
-
- // Use Promise.all to fetch collaborators for all rules in parallel
- const rulesWithOptions = await Promise.all(
- rules.map(async (rule) => {
- const ranges = rule.ranges.map((range) =>
- this._worksheet.getRange(
- range.startRow,
- range.startColumn,
- range.endRow - range.startRow + 1,
- range.endColumn - range.startColumn + 1
- )
- );
-
- // Build options from rule state
- const options: IRangeProtectionOptions = {
- name: rule.description || '',
- allowViewByOthers: rule.viewState !== ViewStateEnum.NoOneElseCanView,
- };
-
- // Handle allowEdit based on editState
- if (rule.editState === EditStateEnum.DesignedUserCanEdit) {
- try {
- // Fetch collaborators for this rule
- const collaborators = await this._authzIoService.listCollaborators({
- objectID: rule.permissionId,
- unitID: this._unitId,
- });
- // Extract collaborator IDs with Editor role
- const editorIds = collaborators
- .filter((c) => c.role === UnitRole.Editor)
- .map((c) => c.subject?.userID || c.id);
- options.allowEdit = editorIds.length > 0;
- } catch (error) {
- // If fetching collaborators fails, fall back to empty array
- console.warn(`Failed to fetch collaborators for rule ${rule.id}:`, error);
- options.allowEdit = false;
- }
- } else {
- options.allowEdit = false;
- }
-
- return {
- rule,
- ranges,
- options,
- };
- })
);
-
- // Create FRangeProtectionRule instances
- return rulesWithOptions.map(({ rule, ranges, options }) =>
- this._injector.createInstance(
- FRangeProtectionRule,
- this._unitId,
- this._subUnitId,
- rule.id,
- rule.permissionId,
- ranges,
- options
- )
- );
- }
-
- /**
- * Build permission snapshot
- */
- private _buildSnapshot(): RangePermissionSnapshot {
- const snapshot: RangePermissionSnapshot = {} as RangePermissionSnapshot;
-
- Object.values(RangePermissionPoint).forEach((point) => {
- snapshot[point] = this.getPoint(point);
- });
-
- return snapshot;
- }
-
- /**
- * Clean up resources
- */
- dispose(): void {
- this._subscriptions.forEach((sub) => sub.unsubscribe());
- this._permissionSubject.complete();
}
}
diff --git a/packages/sheets/src/facade/permission/f-range-protection-rule.ts b/packages/sheets/src/facade/permission/f-range-protection-rule.ts
index cecad5dd69..86821f1568 100644
--- a/packages/sheets/src/facade/permission/f-range-protection-rule.ts
+++ b/packages/sheets/src/facade/permission/f-range-protection-rule.ts
@@ -14,10 +14,15 @@
* limitations under the License.
*/
+import type { IDeleteRangeProtectionMutationParams, ISetRangeProtectionMutationParams } from '@univerjs/sheets';
import type { FRange } from '../f-range';
-import type { IRangeProtectionOptions } from './permission-types';
-import { ICommandService, Inject, Injector } from '@univerjs/core';
-import { DeleteRangeProtectionMutation, RangeProtectionRuleModel, SetRangeProtectionMutation } from '@univerjs/sheets';
+import type { IRangeProtectionOptions, RangePermissionSnapshot } from './permission-types';
+import { IAuthzIoService, ICommandService, Inject, Injector, IPermissionService, Rectangle } from '@univerjs/core';
+import { UnitRole } from '@univerjs/protocol';
+import { DeleteRangeProtectionMutation, RangeProtectionRuleModel, SetRangeProtectionMutation, UnitObject } from '@univerjs/sheets';
+import { RANGE_PERMISSION_POINT_MAP } from './permission-point-map';
+import { RangePermissionPoint } from './permission-types';
+import { handleWorksheetRangePermissionIsEmpty } from './util';
/**
* Implementation class for range protection rules
@@ -35,36 +40,27 @@ export class FRangeProtectionRule {
private readonly _options: IRangeProtectionOptions,
@Inject(Injector) private readonly _injector: Injector,
@Inject(ICommandService) private readonly _commandService: ICommandService,
+ @Inject(IPermissionService) private readonly _permissionService: IPermissionService,
+ @Inject(IAuthzIoService) private readonly _authzIoService: IAuthzIoService,
@Inject(RangeProtectionRuleModel) private readonly _rangeProtectionRuleModel: RangeProtectionRuleModel
) {}
/**
* Get the rule ID.
- * @returns {string} The unique identifier of this protection rule.
- * @example
- * ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * const rules = await permission?.listRangeProtectionRules();
- * const ruleId = rules?.[0]?.id;
- * console.log(ruleId);
- * ```
*/
get id(): string {
return this._ruleId;
}
+ /**
+ * Get the permission ID associated with this rule.
+ */
+ get permissionId(): string {
+ return this._permissionId;
+ }
+
/**
* Get the protected ranges.
- * @returns {FRange[]} Array of protected ranges.
- * @example
- * ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * const rules = await permission?.listRangeProtectionRules();
- * const ranges = rules?.[0]?.ranges;
- * console.log(ranges);
- * ```
*/
get ranges(): FRange[] {
return this._ranges;
@@ -72,15 +68,6 @@ export class FRangeProtectionRule {
/**
* Get the protection options.
- * @returns {IRangeProtectionOptions} Copy of the protection options.
- * @example
- * ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * const rules = await permission?.listRangeProtectionRules();
- * const options = rules?.[0]?.options;
- * console.log(options);
- * ```
*/
get options(): IRangeProtectionOptions {
return { ...this._options };
@@ -92,14 +79,18 @@ export class FRangeProtectionRule {
* @returns {Promise<void>} A promise that resolves when the ranges are updated.
* @example
* ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * const rules = await permission?.listRangeProtectionRules();
- * const rule = rules?.[0];
- * await rule?.updateRanges([worksheet.getRange('A1:C3')]);
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const rules = await fWorksheet.getWorksheetPermission().listRangeProtectionRules();
+ * // Update the ranges to A1:C3 for the first rule
+ * if (rules.length > 0) {
+ * const rule = rules[0];
+ * const result = await rule.updateRanges([fWorksheet.getRange('A1:C3')]);
+ * console.log(result);
+ * }
* ```
*/
- async updateRanges(ranges: FRange[]): Promise<void> {
+ async updateRanges(ranges: FRange[]): Promise<boolean> {
if (!ranges || ranges.length === 0) {
throw new Error('Ranges cannot be empty');
}
@@ -110,16 +101,13 @@ export class FRangeProtectionRule {
}
// Check for overlap with other rules
- const subunitRuleList = this._rangeProtectionRuleModel
+ const subUnitRuleList = this._rangeProtectionRuleModel
.getSubunitRuleList(this._unitId, this._subUnitId)
.filter((r) => r.id !== this._ruleId);
- const hasOverlap = subunitRuleList.some((otherRule) =>
+ const hasOverlap = subUnitRuleList.some((otherRule) =>
otherRule.ranges.some((otherRange) =>
- ranges.some((newRange) => {
- const newRangeData = newRange.getRange();
- return this._rangesIntersect(newRangeData, otherRange);
- })
+ ranges.some((newRange) => Rectangle.intersects(otherRange, newRange.getRange()))
)
);
@@ -128,7 +116,7 @@ export class FRangeProtectionRule {
}
// Execute update
- await this._commandService.executeCommand(SetRangeProtectionMutation.id, {
+ const result = await this._commandService.executeCommand<ISetRangeProtectionMutationParams>(SetRangeProtectionMutation.id, {
unitId: this._unitId,
subUnitId: this._subUnitId,
ruleId: this._ruleId,
@@ -138,9 +126,13 @@ export class FRangeProtectionRule {
},
});
- // Update local reference
- (this._ranges as FRange[]).length = 0;
- this._ranges.push(...ranges);
+ if (result) {
+ // Update local reference
+ this._ranges.length = 0;
+ this._ranges.push(...ranges);
+ }
+
+ return result;
}
/**
@@ -148,35 +140,234 @@ export class FRangeProtectionRule {
* @returns {Promise<void>} A promise that resolves when the rule is removed.
* @example
* ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * const rules = await permission?.listRangeProtectionRules();
- * const rule = rules?.[0];
- * await rule?.remove();
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const rules = await fWorksheet.getWorksheetPermission().listRangeProtectionRules();
+ * // Remove the first protection rule
+ * if (rules.length > 0) {
+ * const rule = rules[0];
+ * const result = await rule.remove();
+ * console.log(result);
+ * }
* ```
*/
- async remove(): Promise<void> {
- await this._commandService.executeCommand(DeleteRangeProtectionMutation.id, {
+ async remove(): Promise<boolean> {
+ const result = await this._commandService.executeCommand<IDeleteRangeProtectionMutationParams>(DeleteRangeProtectionMutation.id, {
unitId: this._unitId,
subUnitId: this._subUnitId,
ruleIds: [this._ruleId],
});
+
+ if (result) {
+ handleWorksheetRangePermissionIsEmpty(this._injector, this._unitId, this._subUnitId);
+ }
+
+ return result;
+ }
+
+ /**
+ * Set a specific permission point for the range rule (low-level API).
+ *
+ * **Important:** This method only updates the permission point value for an existing protection rule.
+ * It does NOT create permission checks that will block actual editing operations.
+ * You must call `protect()` first to create a protection rule before using this method.
+ *
+ * This method is useful for:
+ * - Fine-tuning permissions after creating a protection rule with `protect()`
+ * - Dynamically adjusting permissions based on runtime conditions
+ * - Advanced permission management scenarios
+ *
+ * @param {RangePermissionPoint} point The permission point to set.
+ * @param {boolean} value The value to set (true = allowed, false = denied).
+ * @returns {Promise<void>} A promise that resolves when the point is set.
+ * @throws {Error} If no protection rule exists for this range.
+ *
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const fRange = fWorksheet.getRange('A1:B2');
+ * // First, create a protection rule
+ * const rule = await fRange.getRangePermission().protect({ name: 'My Range', allowEdit: true });
+ * // Then you can dynamically update permission points
+ * await rule.setPoint(univerAPI.Enum.RangePermissionPoint.Edit, false); // Now disable edit
+ * await rule.setPoint(univerAPI.Enum.RangePermissionPoint.View, true); // Ensure view is enabled
+ * ```
+ */
+ async setPoint(point: RangePermissionPoint, value: boolean): Promise<void> {
+ const PermissionPointClass = RANGE_PERMISSION_POINT_MAP[point];
+ if (!PermissionPointClass) {
+ throw new Error(`Unknown range permission point: ${point}`);
+ }
+
+ const instance = new PermissionPointClass(this._unitId, this._subUnitId, this._permissionId);
+ const permissionPoint = this._permissionService.getPermissionPoint(instance.id);
+
+ if (permissionPoint && permissionPoint.value === value) {
+ return; // Value unchanged, no update needed
+ }
+
+ if (!permissionPoint) {
+ this._permissionService.addPermissionPoint(instance);
+ }
+
+ await this._authzIoService.update({
+ objectType: UnitObject.SelectRange,
+ objectID: this._permissionId,
+ unitID: this._unitId,
+ share: undefined,
+ name: this._options.name || '',
+ strategies: [{
+ action: instance.subType,
+ role: value ? UnitRole.Editor : UnitRole.Owner,
+ }],
+ scope: undefined,
+ collaborators: undefined,
+ });
+
+ this._permissionService.updatePermissionPoint(instance.id, value);
}
/**
- * Check if two ranges intersect
- * @returns true if ranges intersect, false otherwise
- * @private
+ * Get the value of a specific permission point.
+ * @param {RangePermissionPoint} point The range permission point to query.
+ * @returns {boolean} true if allowed, false if denied.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const rules = await fWorksheet.getWorksheetPermission().listRangeProtectionRules();
+ * // Check if the first rule allows editing
+ * if (rules.length > 0) {
+ * const rule = rules[0];
+ * const canEdit = rule.getPoint(univerAPI.Enum.RangePermissionPoint.Edit);
+ * console.log(canEdit);
+ * }
+ * ```
*/
- private _rangesIntersect(
- range1: { startRow: number; startColumn: number; endRow: number; endColumn: number },
- range2: { startRow: number; startColumn: number; endRow: number; endColumn: number }
- ): boolean {
- return !(
- range1.endRow < range2.startRow ||
- range1.startRow > range2.endRow ||
- range1.endColumn < range2.startColumn ||
- range1.startColumn > range2.endColumn
- );
+ getPoint(point: RangePermissionPoint): boolean {
+ const PermissionPointClass = RANGE_PERMISSION_POINT_MAP[point];
+ if (!PermissionPointClass) {
+ console.warn(`Unknown permission point: ${point}`);
+ return false;
+ }
+
+ const permissionPoint = new PermissionPointClass(this._unitId, this._subUnitId, this._permissionId);
+ const permission = this._permissionService.getPermissionPoint(permissionPoint.id);
+ if (permission) {
+ return permission.value;
+ }
+
+ return true;
+ }
+
+ /**
+ * Check if the current user can edit this range.
+ * @returns {boolean} true if editable, false otherwise.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const rules = await fWorksheet.getWorksheetPermission().listRangeProtectionRules();
+ * // Check if the first rule allows editing
+ * const rule = rules[0];
+ * if (rule?.canEdit()) {
+ * console.log(`You can edit this range ${rule.ranges.map(r => r.getA1Notation()).join(', ')}`);
+ * }
+ * ```
+ */
+ canEdit(): boolean {
+ // Always check the permission point value first
+ // This handles cases where setPoint() was called without protect()
+ return this.getPoint(RangePermissionPoint.Edit);
+ }
+
+ /**
+ * Check if the current user can view this range.
+ * @returns {boolean} true if viewable, false otherwise.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const rules = await fWorksheet.getWorksheetPermission().listRangeProtectionRules();
+ * // Check if the first rule allows viewing
+ * const rule = rules[0];
+ * if (rule?.canView()) {
+ * console.log(`You can view this range ${rule.ranges.map(r => r.getA1Notation()).join(', ')}`);
+ * }
+ * ```
+ */
+ canView(): boolean {
+ // Always check the permission point value first
+ // This handles cases where setPoint() was called without protect()
+ return this.getPoint(RangePermissionPoint.View);
+ }
+
+ /**
+ * Check if the current user can manage collaborators for this range.
+ * @returns {boolean} true if can manage collaborators, false otherwise.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const rules = await fWorksheet.getWorksheetPermission().listRangeProtectionRules();
+ * // Check if the first rule allows managing collaborators
+ * const rule = rules[0];
+ * if (rule?.canManageCollaborator()) {
+ * console.log(`You can manage collaborators for this range ${rule.ranges.map(r => r.getA1Notation()).join(', ')}`);
+ * }
+ * ```
+ */
+ canManageCollaborator(): boolean {
+ // Always check the permission point value first
+ // This handles cases where setPoint() was called without protect()
+ return this.getPoint(RangePermissionPoint.ManageCollaborator);
+ }
+
+ /**
+ * Check if the current user can delete this protection rule.
+ * @returns {boolean} true if can delete rule, false otherwise.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const rules = await fWorksheet.getWorksheetPermission().listRangeProtectionRules();
+ * // Check if the first rule allows deleting the rule
+ * const rule = rules[0];
+ * if (rule?.canDelete()) {
+ * console.log(`You can delete this protection rule for this range ${rule.ranges.map(r => r.getA1Notation()).join(', ')}`);
+ * }
+ * ```
+ */
+ canDelete(): boolean {
+ // Always check the permission point value first
+ // This handles cases where setPoint() was called without protect()
+ return this.getPoint(RangePermissionPoint.Delete);
+ }
+
+ /**
+ * Get the current permission snapshot.
+ * @returns {RangePermissionSnapshot} Snapshot of all permission points.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const rules = await fWorksheet.getWorksheetPermission().listRangeProtectionRules();
+ * // Get the permission snapshot of the first rule
+ * if (rules.length > 0) {
+ * const rule = rules[0];
+ * const snapshot = rule.getSnapshot();
+ * console.log(snapshot);
+ * }
+ * ```
+ */
+ getSnapshot(): RangePermissionSnapshot {
+ const snapshot: RangePermissionSnapshot = {} as RangePermissionSnapshot;
+
+ Object.values(RangePermissionPoint).forEach((point) => {
+ snapshot[point] = this.getPoint(point);
+ });
+
+ return snapshot;
}
}
diff --git a/packages/sheets/src/facade/permission/f-workbook-permission.ts b/packages/sheets/src/facade/permission/f-workbook-permission.ts
index 8365497f1a..04edb968f7 100644
--- a/packages/sheets/src/facade/permission/f-workbook-permission.ts
+++ b/packages/sheets/src/facade/permission/f-workbook-permission.ts
@@ -14,13 +14,11 @@
* limitations under the License.
*/
-import type { ICollaborator as IProtocolCollaborator, IUser } from '@univerjs/protocol';
-import type { Observable, Subscription } from 'rxjs';
-import type { ICollaborator, IWorkbookPermission, UnsubscribeFn, WorkbookMode, WorkbookPermissionSnapshot } from './permission-types';
+import type { ICollaborator as IProtocolCollaborator } from '@univerjs/protocol';
+import type { ICollaborator, ICollaboratorUser, WorkbookMode, WorkbookPermissionSnapshot } from './permission-types';
import { IAuthzIoService, Inject, Injector, IPermissionService } from '@univerjs/core';
-import { BehaviorSubject, Subject } from 'rxjs';
-import { distinctUntilChanged, filter, map, shareReplay } from 'rxjs/operators';
-import { FPermission } from '../f-permission';
+import { FBase } from '@univerjs/core/facade';
+import { UnitObject } from '@univerjs/protocol';
import { WORKBOOK_PERMISSION_POINT_MAP } from './permission-point-map';
import { UnitRole, WorkbookPermissionPoint } from './permission-types';
@@ -30,168 +28,32 @@ import { UnitRole, WorkbookPermissionPoint } from './permission-types';
*
* @hideconstructor
*/
-export class FWorkbookPermission implements IWorkbookPermission {
- private readonly _permissionSubject: BehaviorSubject<WorkbookPermissionSnapshot>;
-
- // Collaborator changes are tracked manually since IAuthzIoService doesn't provide an observable
- // TODO: If IAuthzIoService adds an observable in the future, migrate to use that
- private readonly _collaboratorChangeSubject = new Subject<{
- type: 'add' | 'update' | 'delete';
- collaborator: ICollaborator;
- }>();
-
- /**
- * Observable stream of permission snapshot changes (BehaviorSubject)
- * Emits immediately on subscription with current state, then on any permission point change
- */
- readonly permission$: Observable<WorkbookPermissionSnapshot>;
-
- /**
- * Observable stream of individual permission point changes
- * Emits when a specific permission point value changes
- */
- readonly pointChange$: Observable<{
- point: WorkbookPermissionPoint;
- value: boolean;
- oldValue: boolean;
- }>;
-
- /**
- * Observable stream of collaborator changes
- * Emits when collaborators are added, updated, or removed
- */
- readonly collaboratorChange$: Observable<{
- type: 'add' | 'update' | 'delete';
- collaborator: ICollaborator;
- }>;
-
- private _subscriptions: Subscription[] = [];
- private readonly _fPermission: FPermission;
-
+export class FWorkbookPermission extends FBase {
constructor(
private readonly _unitId: string,
@Inject(Injector) private readonly _injector: Injector,
- @IPermissionService private readonly _permissionService: IPermissionService,
+ @IPermissionService protected readonly _permissionService: IPermissionService,
@IAuthzIoService private readonly _authzIoService: IAuthzIoService
) {
- // Initialize FPermission instance
- this._fPermission = this._injector.createInstance(FPermission);
-
- // Initialize BehaviorSubject (with initial value)
- this._permissionSubject = new BehaviorSubject(this._buildSnapshot());
-
- // Setup observables from internal services
- this.permission$ = this._createPermissionStream();
- this.pointChange$ = this._createPointChangeStream();
-
- // Collaborator changes are tracked manually since IAuthzIoService doesn't provide an observable
- this.collaboratorChange$ = this._collaboratorChangeSubject.asObservable().pipe(
- shareReplay({ bufferSize: 1, refCount: true })
- );
- }
-
- /**
- * Create permission snapshot stream from IPermissionService
- * @private
- */
- private _createPermissionStream(): Observable<WorkbookPermissionSnapshot> {
- const permissionSub = this._permissionService.permissionPointUpdate$.pipe(
- filter((point) => point.id.includes(this._unitId))
- ).subscribe(() => {
- this._permissionSubject.next(this._buildSnapshot());
- });
- this._subscriptions.push(permissionSub);
-
- return this._permissionSubject.asObservable().pipe(
- distinctUntilChanged((prev, curr) => JSON.stringify(prev) === JSON.stringify(curr)),
- shareReplay({ bufferSize: 1, refCount: true })
- );
- }
-
- /**
- * Create point change stream from IPermissionService
- * @private
- */
- private _createPointChangeStream(): Observable<{ point: WorkbookPermissionPoint; value: boolean; oldValue: boolean }> {
- // Cache to store previous values for comparison
- const valueCache = new Map<WorkbookPermissionPoint, boolean>();
-
- // Initialize cache with current values for all permission points
- for (const point in WorkbookPermissionPoint) {
- const pointKey = WorkbookPermissionPoint[point as keyof typeof WorkbookPermissionPoint];
- valueCache.set(pointKey, this.getPoint(pointKey));
- }
-
- return this._permissionService.permissionPointUpdate$.pipe(
- filter((point) => point.id.includes(this._unitId)),
- map((permissionPoint) => {
- // Find which WorkbookPermissionPoint this corresponds to
- const pointType = this._extractWorkbookPointType(permissionPoint.id);
- if (!pointType) return null;
-
- const newValue: boolean = Boolean(permissionPoint.value);
-
- // Get old value from cache
- const oldValue: boolean = valueCache.get(pointType)!;
-
- // Update cache for next time
- valueCache.set(pointType, newValue);
-
- if (oldValue === newValue) return null;
-
- return { point: pointType, value: newValue, oldValue };
- }),
- filter((change): change is { point: WorkbookPermissionPoint; value: boolean; oldValue: boolean } => change !== null),
- shareReplay({ bufferSize: 1, refCount: true })
- );
- }
-
- /**
- * Extract WorkbookPermissionPoint type from permission point ID
- * @private
- */
- private _extractWorkbookPointType(pointId: string): WorkbookPermissionPoint | null {
- for (const point in WorkbookPermissionPoint) {
- const pointKey = WorkbookPermissionPoint[point as keyof typeof WorkbookPermissionPoint];
- const PointClass = WORKBOOK_PERMISSION_POINT_MAP[pointKey];
- if (!PointClass) continue;
-
- const instance = new PointClass(this._unitId);
- if (instance.id === pointId) {
- return pointKey;
- }
- }
- return null;
- }
-
- /**
- * Build permission snapshot
- */
- private _buildSnapshot(): WorkbookPermissionSnapshot {
- const snapshot = {} as WorkbookPermissionSnapshot;
- for (const point in WorkbookPermissionPoint) {
- const pointKey = WorkbookPermissionPoint[point as keyof typeof WorkbookPermissionPoint];
- snapshot[pointKey] = this.getPoint(pointKey);
- }
- return snapshot;
+ super();
}
- /**
- * Listen to permission point changes
/**
* Set permission mode for the workbook.
* @param {WorkbookMode} mode The permission mode to set ('owner' | 'editor' | 'viewer' | 'commenter').
* @returns {Promise<void>} A promise that resolves when the mode is set.
* @example
* ```ts
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook?.getWorkbookPermission();
- * await permission?.setMode('editor');
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * await fWorkbook.getWorkbookPermission().setMode('editor');
* ```
*/
async setMode(mode: WorkbookMode): Promise<void> {
const pointsToSet = this._getModePermissions(mode);
- await this._batchSetPermissionPoints(pointsToSet);
+
+ await Promise.all(
+ Object.entries(pointsToSet).map(([point, value]) => this.setPoint(point as WorkbookPermissionPoint, value))
+ );
}
/**
@@ -251,47 +113,13 @@ export class FWorkbookPermission implements IWorkbookPermission {
return pointsToSet;
}
- /**
- * Batch set multiple permission points efficiently
- * @private
- */
- private async _batchSetPermissionPoints(pointsToSet: Record<WorkbookPermissionPoint, boolean>): Promise<void> {
- // Note: IPermissionService doesn't have a batch update API, so we update individually
- // but we optimize by only updating the snapshot once at the end
- const pointsChanged: Array<{ point: WorkbookPermissionPoint; value: boolean; oldValue: boolean }> = [];
-
- for (const [point, value] of Object.entries(pointsToSet)) {
- const pointKey = point as WorkbookPermissionPoint;
- const PointClass = WORKBOOK_PERMISSION_POINT_MAP[pointKey];
- if (!PointClass) {
- throw new Error(`Unknown workbook permission point: ${pointKey}`);
- }
-
- const oldValue = this.getPoint(pointKey);
- if (oldValue === value) {
- continue; // Skip unchanged values
- }
-
- // Use FPermission's setWorkbookPermissionPoint method
- this._fPermission.setWorkbookPermissionPoint(this._unitId, PointClass, value);
- pointsChanged.push({ point: pointKey, value, oldValue });
- }
-
- // Update snapshot once at the end (the Observable stream will pick up the changes automatically)
- if (pointsChanged.length > 0) {
- const newSnapshot = this._buildSnapshot();
- this._permissionSubject.next(newSnapshot);
- }
- }
-
/**
* Set the workbook to read-only mode (viewer mode).
* @returns {Promise<void>} A promise that resolves when the mode is set.
* @example
* ```ts
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook?.getWorkbookPermission();
- * await permission?.setReadOnly();
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * await fWorkbook.getWorkbookPermission().setReadOnly();
* ```
*/
async setReadOnly(): Promise<void> {
@@ -303,31 +131,14 @@ export class FWorkbookPermission implements IWorkbookPermission {
* @returns {Promise<void>} A promise that resolves when the mode is set.
* @example
* ```ts
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook?.getWorkbookPermission();
- * await permission?.setEditable();
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * await fWorkbook.getWorkbookPermission().setEditable();
* ```
*/
async setEditable(): Promise<void> {
await this.setMode('editor');
}
- /**
- * Check if the workbook is editable.
- * @returns {boolean} true if the workbook can be edited, false otherwise.
- * @example
- * ```ts
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook?.getWorkbookPermission();
- * if (permission?.canEdit()) {
- * console.log('Workbook is editable');
- * }
- * ```
- */
- canEdit(): boolean {
- return this.getPoint(WorkbookPermissionPoint.Edit);
- }
-
/**
* Set a specific permission point.
* @param {WorkbookPermissionPoint} point The permission point to set.
@@ -335,28 +146,57 @@ export class FWorkbookPermission implements IWorkbookPermission {
* @returns {Promise<void>} A promise that resolves when the point is set.
* @example
* ```ts
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook?.getWorkbookPermission();
- * await permission?.setPoint(univerAPI.Enum.WorkbookPermissionPoint.Print, false);
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const permission = fWorkbook.getWorkbookPermission();
+ * await permission.setPoint(univerAPI.Enum.WorkbookPermissionPoint.Print, false);
* ```
*/
async setPoint(point: WorkbookPermissionPoint, value: boolean): Promise<void> {
- const PointClass = WORKBOOK_PERMISSION_POINT_MAP[point];
- if (!PointClass) {
+ const PermissionPointClass = WORKBOOK_PERMISSION_POINT_MAP[point];
+ if (!PermissionPointClass) {
throw new Error(`Unknown workbook permission point: ${point}`);
}
- const oldValue = this.getPoint(point);
- if (oldValue === value) {
+ const instance = new PermissionPointClass(this._unitId);
+ const permissionPoint = this._permissionService.getPermissionPoint(instance.id);
+ if (permissionPoint && permissionPoint.value === value) {
return; // Value unchanged, no update needed
}
- // Use FPermission's setWorkbookPermissionPoint method
- this._fPermission.setWorkbookPermissionPoint(this._unitId, PointClass, value);
+ if (!permissionPoint) {
+ this._permissionService.addPermissionPoint(instance);
+ }
+
+ await this._authzIoService.update({
+ objectType: UnitObject.Workbook,
+ objectID: this._unitId,
+ unitID: this._unitId,
+ share: undefined,
+ name: '',
+ strategies: [{
+ action: instance.subType,
+ role: value ? UnitRole.Editor : UnitRole.Owner,
+ }],
+ scope: undefined,
+ collaborators: undefined,
+ });
- // Update snapshot (the Observable stream will automatically emit the change)
- const newSnapshot = this._buildSnapshot();
- this._permissionSubject.next(newSnapshot);
+ this._permissionService.updatePermissionPoint(instance.id, value);
+ }
+
+ /**
+ * Check if the workbook is editable.
+ * @returns {boolean} true if the workbook can be edited, false otherwise.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * if (fWorkbook.getWorkbookPermission().canEdit()) {
+ * console.log('Workbook is editable');
+ * }
+ * ```
+ */
+ canEdit(): boolean {
+ return this.getPoint(WorkbookPermissionPoint.Edit);
}
/**
@@ -365,9 +205,9 @@ export class FWorkbookPermission implements IWorkbookPermission {
* @returns {boolean} true if allowed, false if denied.
* @example
* ```ts
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook?.getWorkbookPermission();
- * const canPrint = permission?.getPoint(univerAPI.Enum.WorkbookPermissionPoint.Print);
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const permission = fWorkbook.getWorkbookPermission();
+ * const canPrint = permission.getPoint(univerAPI.Enum.WorkbookPermissionPoint.Print);
* console.log(canPrint);
* ```
*/
@@ -388,14 +228,18 @@ export class FWorkbookPermission implements IWorkbookPermission {
* @returns {WorkbookPermissionSnapshot} An object containing all permission point values.
* @example
* ```ts
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook?.getWorkbookPermission();
- * const snapshot = permission?.getSnapshot();
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const snapshot = fWorkbook.getWorkbookPermission().getSnapshot();
* console.log(snapshot);
* ```
*/
getSnapshot(): WorkbookPermissionSnapshot {
- return this._buildSnapshot();
+ const snapshot = {} as WorkbookPermissionSnapshot;
+ for (const point in WorkbookPermissionPoint) {
+ const pointKey = WorkbookPermissionPoint[point as keyof typeof WorkbookPermissionPoint];
+ snapshot[pointKey] = this.getPoint(pointKey);
+ }
+ return snapshot;
}
/**
@@ -404,9 +248,9 @@ export class FWorkbookPermission implements IWorkbookPermission {
* @returns {Promise<void>} A promise that resolves when the collaborators are set.
* @example
* ```ts
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook?.getWorkbookPermission();
- * await permission?.setCollaborators([
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const permission = fWorkbook.getWorkbookPermission();
+ * await permission.setCollaborators([
* {
* user: { userID: 'user1', name: 'John Doe', avatar: 'https://...' },
* role: univerAPI.Enum.UnitRole.Editor
@@ -418,7 +262,7 @@ export class FWorkbookPermission implements IWorkbookPermission {
* ]);
* ```
*/
- async setCollaborators(collaborators: Array<{ user: IUser; role: UnitRole }>): Promise<void> {
+ async setCollaborators(collaborators: Array<{ user: ICollaboratorUser; role: UnitRole }>): Promise<void> {
// Convert to protocol format
const protocolCollaborators: IProtocolCollaborator[] = collaborators.map((c) => ({
id: c.user.userID,
@@ -432,17 +276,6 @@ export class FWorkbookPermission implements IWorkbookPermission {
unitID: this._unitId,
collaborators: protocolCollaborators,
});
-
- // Trigger change events
- collaborators.forEach((c) => {
- this._collaboratorChangeSubject.next({
- type: 'add',
- collaborator: {
- user: { id: c.user.userID },
- role: c.role,
- },
- });
- });
}
/**
@@ -452,15 +285,15 @@ export class FWorkbookPermission implements IWorkbookPermission {
* @returns {Promise<void>} A promise that resolves when the collaborator is added.
* @example
* ```ts
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook?.getWorkbookPermission();
- * await permission?.addCollaborator(
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const permission = fWorkbook.getWorkbookPermission();
+ * await permission.addCollaborator(
* { userID: 'user1', name: 'John Doe', avatar: 'https://...' },
* univerAPI.Enum.UnitRole.Editor
* );
* ```
*/
- async addCollaborator(user: IUser, role: UnitRole): Promise<void> {
+ async addCollaborator(user: ICollaboratorUser, role: UnitRole): Promise<void> {
await this._authzIoService.createCollaborator({
objectID: this._unitId,
unitID: this._unitId,
@@ -470,14 +303,6 @@ export class FWorkbookPermission implements IWorkbookPermission {
role,
}],
});
-
- this._collaboratorChangeSubject.next({
- type: 'add',
- collaborator: {
- user: { id: user.userID },
- role,
- },
- });
}
/**
@@ -487,15 +312,15 @@ export class FWorkbookPermission implements IWorkbookPermission {
* @returns {Promise<void>} A promise that resolves when the collaborator is updated.
* @example
* ```ts
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook?.getWorkbookPermission();
- * await permission?.updateCollaborator(
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const permission = fWorkbook.getWorkbookPermission();
+ * await permission.updateCollaborator(
* { userID: 'user1', name: 'John Doe Updated', avatar: 'https://...' },
* univerAPI.Enum.UnitRole.Reader
* );
* ```
*/
- async updateCollaborator(user: IUser, role: UnitRole): Promise<void> {
+ async updateCollaborator(user: ICollaboratorUser, role: UnitRole): Promise<void> {
await this._authzIoService.updateCollaborator({
objectID: this._unitId,
unitID: this._unitId,
@@ -505,14 +330,6 @@ export class FWorkbookPermission implements IWorkbookPermission {
role,
},
});
-
- this._collaboratorChangeSubject.next({
- type: 'update',
- collaborator: {
- user: { id: user.userID },
- role,
- },
- });
}
/**
@@ -521,9 +338,9 @@ export class FWorkbookPermission implements IWorkbookPermission {
* @returns {Promise<void>} A promise that resolves when the collaborator is removed.
* @example
* ```ts
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook?.getWorkbookPermission();
- * await permission?.removeCollaborator('user1');
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const permission = fWorkbook.getWorkbookPermission();
+ * await permission.removeCollaborator('user1');
* ```
*/
async removeCollaborator(userId: string): Promise<void> {
@@ -532,14 +349,6 @@ export class FWorkbookPermission implements IWorkbookPermission {
unitID: this._unitId,
collaboratorID: userId,
});
-
- this._collaboratorChangeSubject.next({
- type: 'delete',
- collaborator: {
- user: { id: userId },
- role: UnitRole.Reader, // Placeholder value
- },
- });
}
/**
@@ -548,15 +357,15 @@ export class FWorkbookPermission implements IWorkbookPermission {
* @returns {Promise<void>} A promise that resolves when the collaborators are removed.
* @example
* ```ts
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook?.getWorkbookPermission();
- * await permission?.removeCollaborators(['user1', 'user2']);
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const permission = fWorkbook.getWorkbookPermission();
+ * await permission.removeCollaborators(['user1', 'user2']);
* ```
*/
async removeCollaborators(userIds: string[]): Promise<void> {
- for (const userId of userIds) {
- await this.removeCollaborator(userId);
- }
+ await Promise.all(
+ userIds.map((userId) => this.removeCollaborator(userId))
+ );
}
/**
@@ -564,9 +373,9 @@ export class FWorkbookPermission implements IWorkbookPermission {
* @returns {Promise<ICollaborator[]>} Array of collaborators with their roles.
* @example
* ```ts
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook?.getWorkbookPermission();
- * const collaborators = await permission?.listCollaborators();
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const permission = fWorkbook.getWorkbookPermission();
+ * const collaborators = await permission.listCollaborators();
* console.log(collaborators);
* ```
*/
@@ -578,39 +387,11 @@ export class FWorkbookPermission implements IWorkbookPermission {
return protocolCollaborators.map((c) => ({
user: {
- id: c.subject?.userID || c.id,
- displayName: c.subject?.name || '',
+ userID: c.subject?.userID || c.id,
+ name: c.subject?.name || '',
+ avatar: c.subject?.avatar || '',
},
- role: c.role as UnitRole, // Type conversion: protocol UnitRole to our UnitRole
+ role: c.role as UnitRole,
}));
}
-
- /**
- * Subscribe to permission changes (simplified interface for users not familiar with RxJS).
- * @param {Function} listener Callback function to be called when permissions change.
- * @returns {UnsubscribeFn} Unsubscribe function.
- * @example
- * ```ts
- * const workbook = univerAPI.getActiveWorkbook();
- * const permission = workbook?.getWorkbookPermission();
- * const unsubscribe = permission?.subscribe((snapshot) => {
- * console.log('Permission changed:', snapshot);
- * });
- * // Later, to stop listening:
- * unsubscribe?.();
- * ```
- */
- subscribe(listener: (snapshot: WorkbookPermissionSnapshot) => void): UnsubscribeFn {
- const subscription = this.permission$.subscribe(listener);
- return () => subscription.unsubscribe();
- }
-
- /**
- * Clean up resources
- */
- dispose(): void {
- this._subscriptions.forEach((s) => s.unsubscribe());
- this._permissionSubject.complete();
- this._collaboratorChangeSubject.complete();
- }
}
diff --git a/packages/sheets/src/facade/permission/f-worksheet-permission.ts b/packages/sheets/src/facade/permission/f-worksheet-permission.ts
index 429ecd215a..1d5c4ca797 100644
--- a/packages/sheets/src/facade/permission/f-worksheet-permission.ts
+++ b/packages/sheets/src/facade/permission/f-worksheet-permission.ts
@@ -16,39 +16,43 @@
import type { ICollaborator } from '@univerjs/protocol';
import type {
+ IAddRangeProtectionMutationParams,
+ IAddWorksheetProtectionParams,
+ IDeleteWorksheetProtectionParams,
IRangeProtectionRule,
} from '@univerjs/sheets';
-import type { Observable, Subscription } from 'rxjs';
import type { FRange } from '../f-range';
import type { FWorksheet } from '../f-worksheet';
import type {
IRangeProtectionOptions,
IWorksheetPermissionConfig,
IWorksheetProtectionOptions,
- UnsubscribeFn,
WorksheetMode,
WorksheetPermissionSnapshot,
} from './permission-types';
-import { IAuthzIoService, ICommandService, Inject, Injector, IPermissionService } from '@univerjs/core';
-import { UnitRole } from '@univerjs/protocol';
+import { cellToRange, generateRandomId, IAuthzIoService, ICommandService, Inject, Injector, IPermissionService, Rectangle } from '@univerjs/core';
+import { FBase } from '@univerjs/core/facade';
+import { UnitAction, UnitRole } from '@univerjs/protocol';
import {
AddRangeProtectionMutation,
+ AddWorksheetProtectionMutation,
+ DeleteRangeProtectionMutation,
+ DeleteWorksheetProtectionMutation,
EditStateEnum,
+ getAllWorksheetPermissionPoint,
+ getAllWorksheetPermissionPointByPointPanel,
+ RangeProtectionPermissionEditPoint,
+ RangeProtectionPermissionViewPoint,
RangeProtectionRuleModel,
UnitObject,
ViewStateEnum,
WorksheetProtectionPointModel,
WorksheetProtectionRuleModel,
} from '@univerjs/sheets';
-import { BehaviorSubject } from 'rxjs';
-import { distinctUntilChanged, filter, map, shareReplay } from 'rxjs/operators';
-import { FPermission } from '../f-permission';
import { FRangeProtectionRule } from './f-range-protection-rule';
-import { RANGE_PERMISSION_POINT_MAP, WORKSHEET_PERMISSION_POINT_MAP } from './permission-point-map';
-import {
- RangePermissionPoint,
- WorksheetPermissionPoint,
-} from './permission-types';
+import { WORKSHEET_PERMISSION_POINT_MAP } from './permission-point-map';
+import { WorksheetPermissionPoint } from './permission-types';
+import { determineEditState, determineScope, determineViewState, getListRangeProtectionRules, handleWorksheetRangePermissionIsEmpty } from './util';
/**
* Implementation class for WorksheetPermission
@@ -56,45 +60,9 @@ import {
*
* @hideconstructor
*/
-export class FWorksheetPermission {
- private readonly _permissionSubject: BehaviorSubject<WorksheetPermissionSnapshot>;
- private readonly _rangeRulesSubject: BehaviorSubject<FRangeProtectionRule[]>;
-
- /**
- * Observable stream of permission snapshot changes (BehaviorSubject)
- * Emits immediately on subscription with current state, then on any permission point change
- */
- readonly permission$: Observable<WorksheetPermissionSnapshot>;
-
- /**
- * Observable stream of individual permission point changes
- * Emits when a specific permission point value changes
- */
- readonly pointChange$: Observable<{
- point: WorksheetPermissionPoint;
- value: boolean;
- oldValue: boolean;
- }>;
-
- /**
- * Observable stream of range protection rule changes
- * Emits when protection rules are added, updated, or deleted
- */
- readonly rangeProtectionChange$: Observable<{
- type: 'add' | 'update' | 'delete';
- rules: FRangeProtectionRule[];
- }>;
-
- /**
- * Observable stream of current range protection rules list (BehaviorSubject)
- * Emits immediately on subscription with current rules, then auto-updates when rules change
- */
- readonly rangeProtectionRules$: Observable<FRangeProtectionRule[]>;
-
+export class FWorksheetPermission extends FBase {
private readonly _unitId: string;
private readonly _subUnitId: string;
- private readonly _subscriptions: Subscription[] = [];
- private readonly _fPermission: FPermission;
constructor(
private readonly _worksheet: FWorksheet,
@@ -106,238 +74,28 @@ export class FWorksheetPermission {
@Inject(WorksheetProtectionPointModel) private readonly _worksheetProtectionPointModel: WorksheetProtectionPointModel,
@Inject(WorksheetProtectionRuleModel) private readonly _worksheetProtectionRuleModel: WorksheetProtectionRuleModel
) {
+ super();
+
// Get unitId and subUnitId from worksheet
this._unitId = this._worksheet.getWorkbook().getUnitId();
this._subUnitId = this._worksheet.getSheetId();
-
- // Initialize FPermission instance
- this._fPermission = this._injector.createInstance(FPermission);
-
- // Initialize BehaviorSubject
- this._permissionSubject = new BehaviorSubject(this._buildSnapshot());
- this._rangeRulesSubject = new BehaviorSubject<FRangeProtectionRule[]>(this._buildRangeProtectionRules());
-
- // Setup observables from internal services
- this.permission$ = this._createPermissionStream();
- this.pointChange$ = this._createPointChangeStream();
- this.rangeProtectionChange$ = this._createRangeProtectionChangeStream();
- this.rangeProtectionRules$ = this._createRangeProtectionRulesStream();
- }
-
- /**
- * Create permission snapshot stream from IPermissionService
- * @private
- */
- private _createPermissionStream(): Observable<WorksheetPermissionSnapshot> {
- // Listen to permission point changes from IPermissionService
- const permissionSub = this._permissionService.permissionPointUpdate$.pipe(
- filter((point) => point.id.includes(this._unitId) && point.id.includes(this._subUnitId))
- ).subscribe(() => {
- this._permissionSubject.next(this._buildSnapshot());
- });
- this._subscriptions.push(permissionSub);
-
- return this._permissionSubject.asObservable().pipe(
- distinctUntilChanged((prev, curr) => JSON.stringify(prev) === JSON.stringify(curr)),
- shareReplay({ bufferSize: 1, refCount: true })
- );
- }
-
- /**
- * Create point change stream from IPermissionService
- * @private
- */
- private _createPointChangeStream(): Observable<{ point: WorksheetPermissionPoint; value: boolean; oldValue: boolean }> {
- return this._permissionService.permissionPointUpdate$.pipe(
- filter((point) => point.id.includes(this._unitId) && point.id.includes(this._subUnitId)),
- map((point) => {
- const pointType = this._extractWorksheetPointType(point.id);
- if (!pointType) return null;
- return {
- point: pointType,
- value: point.value ?? false,
- oldValue: !(point.value ?? false),
- };
- }),
- filter((change): change is { point: WorksheetPermissionPoint; value: boolean; oldValue: boolean } => change !== null),
- shareReplay({ bufferSize: 1, refCount: true })
- );
- }
-
- /**
- * Create range protection change stream from RangeProtectionRuleModel
- * @private
- */
- private _createRangeProtectionChangeStream(): Observable<{ type: 'add' | 'update' | 'delete'; rules: FRangeProtectionRule[] }> {
- return this._rangeProtectionRuleModel.ruleChange$.pipe(
- filter((change) => change.unitId === this._unitId && change.subUnitId === this._subUnitId),
- map((change) => {
- const rules = this._buildRangeProtectionRules();
- const type: 'add' | 'update' | 'delete' = change.type === 'delete' ? 'delete' : (change.type === 'set' ? 'update' : 'add');
- return { type, rules };
- }),
- shareReplay({ bufferSize: 1, refCount: true })
- );
- }
-
- /**
- * Create range protection rules list stream from RangeProtectionRuleModel
- * @private
- */
- private _createRangeProtectionRulesStream(): Observable<FRangeProtectionRule[]> {
- const ruleChangeSub = this._rangeProtectionRuleModel.ruleChange$.pipe(
- filter((change) => change.unitId === this._unitId && change.subUnitId === this._subUnitId)
- ).subscribe(() => {
- this._rangeRulesSubject.next(this._buildRangeProtectionRules());
- });
- this._subscriptions.push(ruleChangeSub);
-
- return this._rangeRulesSubject.asObservable().pipe(
- distinctUntilChanged((prev, curr) => {
- if (prev.length !== curr.length) return false;
- return prev.every((p, i) => p.id === curr[i].id);
- }),
- shareReplay({ bufferSize: 1, refCount: true })
- );
- }
-
- /**
- * Extract WorksheetPermissionPoint type from permission point ID
- * @private
- */
- private _extractWorksheetPointType(pointId: string): WorksheetPermissionPoint | null {
- // Try to match against known worksheet permission points
- for (const [pointName, PointClass] of Object.entries(WORKSHEET_PERMISSION_POINT_MAP)) {
- const testPoint = new PointClass(this._unitId, this._subUnitId);
- if (testPoint.id === pointId) {
- return pointName as WorksheetPermissionPoint;
- }
- }
- return null;
}
/**
- * Read the actual edit permission from a rule's permissionId
- */
- private _getRuleEditPermission(rule: { permissionId: string }): boolean {
- const PermissionPointClass = RANGE_PERMISSION_POINT_MAP[RangePermissionPoint.Edit];
- if (!PermissionPointClass) {
- return false;
- }
-
- const permissionPoint = new PermissionPointClass(
- this._unitId,
- this._subUnitId,
- rule.permissionId
- );
-
- const permission = this._permissionService.getPermissionPoint(permissionPoint.id);
- return permission?.value ?? false;
- }
-
- /**
- * Build permission snapshot
- */
- private _buildSnapshot(): WorksheetPermissionSnapshot {
- const snapshot = {} as WorksheetPermissionSnapshot;
- for (const point in WorksheetPermissionPoint) {
- const pointKey = WorksheetPermissionPoint[point as keyof typeof WorksheetPermissionPoint];
- snapshot[pointKey] = this.getPoint(pointKey);
- }
- return snapshot;
- }
-
- /**
- * Build range protection rules list
- */
- private _buildRangeProtectionRules(): FRangeProtectionRule[] {
- const rules = this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId, this._subUnitId);
- return rules.map((rule) => {
- // Convert IRange to FRange using worksheet
- const ranges = rule.ranges.map((range) =>
- this._worksheet.getRange(
- range.startRow,
- range.startColumn,
- range.endRow - range.startRow + 1,
- range.endColumn - range.startColumn + 1
- )
- );
-
- return this._injector.createInstance(
- FRangeProtectionRule,
- this._unitId,
- this._subUnitId,
- rule.id,
- rule.permissionId,
- ranges,
- {
- name: rule.description || '',
- allowEdit: this._getRuleEditPermission(rule),
- }
- );
- });
- }
-
- /**
- * Build Facade objects for all protection rules
- */
- private _buildProtectionRule(rule: IRangeProtectionRule): FRangeProtectionRule {
- const ranges = rule.ranges.map((range) =>
- this._worksheet.getRange(range)
- );
-
- // Build options from rule state
- const options: IRangeProtectionOptions = {
- name: rule.description || '',
- allowViewByOthers: rule.viewState !== ViewStateEnum.NoOneElseCanView,
- };
-
- // Handle allowEdit based on editState
- if (rule.editState === EditStateEnum.DesignedUserCanEdit) {
- // Get collaborators list synchronously for this rule
- // Note: This is a synchronous context, but we need async data
- // We'll use a placeholder here and expect the caller to handle async properly
- // For now, we set it to an empty array as a fallback
- options.allowEdit = true;
- } else {
- options.allowEdit = false;
- }
-
- return this._injector.createInstance(
- FRangeProtectionRule,
- this._unitId,
- this._subUnitId,
- rule.id,
- rule.permissionId,
- ranges,
- options
- );
- }
-
- /**
- * Debug cell permission information.
- * @param {number} row Row index.
- * @param {number} col Column index.
- * @returns {ICellPermissionDebugInfo | null} Debug information about which rules affect this cell, or null if no rules apply.
+ * Check if worksheet is currently protected.
+ * @returns {boolean} true if protected, false otherwise.
* @example
* ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * const debugInfo = permission?.debugCellPermission(0, 0);
- * console.log(debugInfo);
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * if (fWorksheet.getWorksheetPermission().isProtected()) {
+ * console.log('Worksheet is protected');
+ * }
* ```
*/
- debugCellPermission(row: number, col: number): FRangeProtectionRule | undefined {
- const info = this._fPermission.getPermissionInfoWithCell(this._unitId, this._subUnitId, row, col);
- if (!info) {
- return undefined;
- }
- const { ruleId } = info;
- const rule = this._rangeProtectionRuleModel.getRule(this._unitId, this._subUnitId, ruleId);
- if (!rule) {
- return undefined;
- }
- return this._buildProtectionRule(rule);
+ isProtected(): boolean {
+ const rule = this._worksheetProtectionRuleModel.getRule(this._unitId, this._subUnitId);
+ return !!rule;
}
/**
@@ -347,11 +105,12 @@ export class FWorksheetPermission {
* @returns {Promise<string>} The permissionId for the created protection.
* @example
* ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const permission = fWorksheet.getWorksheetPermission();
*
* // Create worksheet protection with collaborators
- * const permissionId = await permission?.protect({
+ * const permissionId = await permission.protect({
* allowedUsers: ['user1', 'user2'],
* name: 'My Worksheet Protection'
* });
@@ -366,10 +125,62 @@ export class FWorksheetPermission {
throw new Error('Worksheet is already protected. Call unprotect() first.');
}
- // Use FPermission's addWorksheetBasePermission method
- const permissionId = await this._fPermission.addWorksheetBasePermission(this._unitId, this._subUnitId, options);
+ const editState = determineEditState(options?.allowedUsers);
+ const viewState = determineViewState(options?.allowViewByOthers);
+ const scope = determineScope(editState, viewState);
+
+ // Fetch existing collaborators if allowedUsers is provided
+ const collaborators: ICollaborator[] = [];
+ if (editState === EditStateEnum.DesignedUserCanEdit) {
+ const existingCollaborators = await this._authzIoService.listCollaborators({
+ objectID: this._unitId,
+ unitID: this._unitId,
+ });
+
+ options!.allowedUsers!.forEach((userId) => {
+ const existingCollaborator = existingCollaborators.find((c) => c.subject?.userID === userId || c.id === userId);
+ if (!existingCollaborator) {
+ console.error(`User ${userId} not found in existing collaborators`);
+ return;
+ }
+
+ collaborators.push({
+ id: existingCollaborator.id,
+ role: UnitRole.Editor,
+ subject: existingCollaborator.subject,
+ });
+ });
+ }
+
+ const permissionId = await this._authzIoService.create({
+ objectType: UnitObject.Worksheet,
+ worksheetObject: {
+ collaborators,
+ unitID: this._unitId,
+ strategies: [
+ { role: UnitRole.Editor, action: UnitAction.Edit },
+ { role: UnitRole.Reader, action: UnitAction.View },
+ ],
+ name: options?.name || '',
+ scope,
+ },
+ });
- if (!permissionId) {
+ const result = this._commandService.syncExecuteCommand<IAddWorksheetProtectionParams>(AddWorksheetProtectionMutation.id, {
+ unitId: this._unitId,
+ subUnitId: this._subUnitId,
+ rule: {
+ permissionId,
+ description: options?.name,
+ unitType: UnitObject.Worksheet,
+ unitId: this._unitId,
+ subUnitId: this._subUnitId,
+ viewState,
+ editState,
+ },
+ });
+
+ if (!result) {
throw new Error('Failed to create worksheet protection');
}
@@ -382,39 +193,28 @@ export class FWorksheetPermission {
* @returns {Promise<void>} A promise that resolves when protection is removed.
* @example
* ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * await permission?.unprotect();
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * await fWorksheet.getWorksheetPermission().unprotect();
* ```
*/
- async unprotect(): Promise<void> {
+ async unprotect(): Promise<boolean> {
if (!this.isProtected()) {
- return; // Already unprotected
+ return true; // Already unprotected
}
- // Use FPermission's removeWorksheetPermission method
- this._fPermission.removeWorksheetPermission(this._unitId, this._subUnitId);
+ const result = this._commandService.syncExecuteCommand<IDeleteWorksheetProtectionParams>(DeleteWorksheetProtectionMutation.id, {
+ unitId: this._unitId,
+ subUnitId: this._subUnitId,
+ });
- // Update snapshot
- const newSnapshot = this._buildSnapshot();
- this._permissionSubject.next(newSnapshot);
- }
+ [...getAllWorksheetPermissionPoint(), ...getAllWorksheetPermissionPointByPointPanel()].forEach((F) => {
+ const instance = new F(this._unitId, this._subUnitId);
+ this._permissionService.updatePermissionPoint(instance.id, true);
+ });
+ this._worksheetProtectionPointModel.deleteRule(this._unitId, this._subUnitId);
- /**
- * Check if worksheet is currently protected.
- * @returns {boolean} true if protected, false otherwise.
- * @example
- * ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * if (permission?.isProtected()) {
- * console.log('Worksheet is protected');
- * }
- * ```
- */
- isProtected(): boolean {
- const rule = this._worksheetProtectionRuleModel.getRule(this._unitId, this._subUnitId);
- return !!rule;
+ return result;
}
/**
@@ -424,16 +224,19 @@ export class FWorksheetPermission {
* @returns {Promise<void>} A promise that resolves when the mode is set.
* @example
* ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * await permission?.setMode('readOnly');
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * await fWorksheet.getWorksheetPermission().setMode('readOnly');
* ```
*/
async setMode(mode: WorksheetMode): Promise<void> {
// Ensure worksheet protection exists before setting permission points
const pointsToSet = this._getModePermissions(mode);
- await this._batchSetPermissionPoints(pointsToSet);
+
+ await Promise.all(
+ Object.entries(pointsToSet).map(([point, value]) => this.setPoint(point as WorksheetPermissionPoint, value))
+ );
}
/**
@@ -457,61 +260,26 @@ export class FWorksheetPermission {
case 'readOnly':
// Fully read-only - only View is allowed
pointsToSet[WorksheetPermissionPoint.View] = true;
- // All other permissions remain false
break;
case 'filterOnly':
// Can only filter/sort
pointsToSet[WorksheetPermissionPoint.View] = true;
pointsToSet[WorksheetPermissionPoint.Sort] = true;
pointsToSet[WorksheetPermissionPoint.Filter] = true;
- // All other permissions remain false
break;
}
return pointsToSet;
}
- /**
- * Batch set multiple permission points efficiently
- * @private
- */
- private async _batchSetPermissionPoints(pointsToSet: Record<WorksheetPermissionPoint, boolean>): Promise<void> {
- // Note: IPermissionService doesn't have a batch update API, so we update individually
- // but we optimize by only updating the snapshot once at the end
- const pointsChanged: Array<{ point: WorksheetPermissionPoint; value: boolean; oldValue: boolean }> = [];
-
- for (const [point, value] of Object.entries(pointsToSet)) {
- const pointKey = point as WorksheetPermissionPoint;
- const PointClass = WORKSHEET_PERMISSION_POINT_MAP[pointKey];
- if (!PointClass) {
- throw new Error(`Unknown worksheet permission point: ${pointKey}`);
- }
-
- const oldValue = this.getPoint(pointKey);
- if (oldValue === value) {
- continue; // Skip unchanged values
- }
-
- // Use FPermission's setWorksheetPermissionPoint method
- await this._fPermission.setWorksheetPermissionPoint(this._unitId, this._subUnitId, PointClass, value);
- pointsChanged.push({ point: pointKey, value, oldValue });
- }
-
- // Update snapshot once at the end (the Observable stream will pick up the changes automatically)
- if (pointsChanged.length > 0) {
- const newSnapshot = this._buildSnapshot();
- this._permissionSubject.next(newSnapshot);
- }
- }
-
/**
* Set the worksheet to read-only mode.
* @returns {Promise<void>} A promise that resolves when the mode is set.
* @example
* ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * await permission?.setReadOnly();
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * await fWorksheet.getWorksheetPermission().setReadOnly();
* ```
*/
async setReadOnly(): Promise<void> {
@@ -523,23 +291,76 @@ export class FWorksheetPermission {
* @returns {Promise<void>} A promise that resolves when the mode is set.
* @example
* ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * await permission?.setEditable();
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * await fWorksheet.getWorksheetPermission().setEditable();
* ```
*/
async setEditable(): Promise<void> {
await this.setMode('editable');
}
+ /**
+ * Set a specific permission point for the worksheet.
+ * Automatically creates worksheet protection if not already protected.
+ * @param {WorksheetPermissionPoint} point The permission point to set.
+ * @param {boolean} value The value to set (true = allowed, false = denied).
+ * @returns {Promise<void>} A promise that resolves when the point is set.
+ * @example
+ * ```ts
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const permission = fWorksheet.getWorksheetPermission();
+ * await permission.setPoint(univerAPI.Enum.WorksheetPermissionPoint.InsertRow, false);
+ * ```
+ */
+ async setPoint(point: WorksheetPermissionPoint, value: boolean): Promise<void> {
+ const PermissionPointClass = WORKSHEET_PERMISSION_POINT_MAP[point];
+ if (!PermissionPointClass) {
+ throw new Error(`Unknown worksheet permission point: ${point}`);
+ }
+
+ // Set worksheet permission points require worksheet protection to exist first
+ const worksheetProtectionRule = this._worksheetProtectionRuleModel.getRule(this._unitId, this._subUnitId);
+ if (!worksheetProtectionRule) {
+ throw new Error(`Cannot set ${point} permission point because worksheet protection does not exist. Call protect() first.`);
+ }
+
+ const instance = new PermissionPointClass(this._unitId, this._subUnitId);
+ const permissionPoint = this._permissionService.getPermissionPoint(instance.id);
+ if (permissionPoint && permissionPoint.value === value) {
+ return; // Value unchanged, no update needed
+ }
+
+ if (!permissionPoint) {
+ this._permissionService.addPermissionPoint(instance);
+ }
+
+ await this._authzIoService.update({
+ objectType: UnitObject.Worksheet,
+ objectID: worksheetProtectionRule.permissionId,
+ unitID: this._unitId,
+ share: undefined,
+ name: worksheetProtectionRule.description || '',
+ strategies: [{
+ action: instance.subType,
+ role: value ? UnitRole.Editor : UnitRole.Owner,
+ }],
+ scope: undefined,
+ collaborators: undefined,
+ });
+
+ this._permissionService.updatePermissionPoint(instance.id, value);
+ }
+
/**
* Check if the worksheet is editable.
* @returns {boolean} true if the worksheet can be edited, false otherwise.
* @example
* ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * if (permission?.canEdit()) {
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * if (fWorksheet.getWorksheetPermission().canEdit()) {
* console.log('Worksheet is editable');
* }
* ```
@@ -555,9 +376,11 @@ export class FWorksheetPermission {
* @returns {boolean} true if the cell can be edited, false otherwise.
* @example
* ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * const canEdit = permission?.canEditCell(0, 0);
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * // Check if cell C3 can be edited
+ * const fRange = fWorksheet.getRange('C3');
+ * const canEdit = fWorksheet.getWorksheetPermission().canEditCell(fRange.getRow(), fRange.getColumn());
* console.log(canEdit);
* ```
*/
@@ -578,7 +401,13 @@ export class FWorksheetPermission {
col <= range.endColumn
) {
// Cell is within protected range, check the rule's edit permission
- return this._getRuleEditPermission(rule);
+ const permissionPoint = new RangeProtectionPermissionEditPoint(
+ this._unitId,
+ this._subUnitId,
+ rule.permissionId
+ );
+ const permission = this._permissionService.getPermissionPoint(permissionPoint.id);
+ return permission?.value ?? false;
}
}
}
@@ -587,55 +416,64 @@ export class FWorksheetPermission {
}
/**
- * Check if a specific cell can be viewed.
- * @param {number} _row Row index (unused, for API consistency).
- * @param {number} _col Column index (unused, for API consistency).
- * @returns {boolean} true if the cell can be viewed, false otherwise.
+ * Check if the worksheet is viewable.
+ * @returns {boolean} true if the worksheet can be viewed, false otherwise.
* @example
* ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * const canView = permission?.canViewCell(0, 0);
- * console.log(canView);
- * ```
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * if (fWorksheet.getWorksheetPermission().canView()) {
+ * console.log('Worksheet is viewable');
+ * }
*/
- canViewCell(_row: number, _col: number): boolean {
- // View permission is usually true by default
+ canView(): boolean {
return this.getPoint(WorksheetPermissionPoint.View);
}
/**
- * Set a specific permission point for the worksheet.
- * Automatically creates worksheet protection if not already protected.
- * @param {WorksheetPermissionPoint} point The permission point to set.
- * @param {boolean} value The value to set (true = allowed, false = denied).
- * @returns {Promise<void>} A promise that resolves when the point is set.
+ * Check if a specific cell can be viewed.
+ * @param {number} row Row index.
+ * @param {number} col Column index.
+ * @returns {boolean} true if the cell can be viewed, false otherwise.
* @example
* ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * await permission?.setPoint(univerAPI.Enum.WorksheetPermissionPoint.InsertRow, false);
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * // Check if cell C3 can be viewed
+ * const fRange = fWorksheet.getRange('C3');
+ * const canView = fWorksheet.getWorksheetPermission().canViewCell(fRange.getRow(), fRange.getColumn());
+ * console.log(canView);
* ```
*/
- async setPoint(point: WorksheetPermissionPoint, value: boolean): Promise<void> {
- // Ensure worksheet protection exists before setting permission points
-
- const PointClass = WORKSHEET_PERMISSION_POINT_MAP[point];
- if (!PointClass) {
- throw new Error(`Unknown worksheet permission point: ${point}`);
+ canViewCell(row: number, col: number): boolean {
+ // First check worksheet-level view permission
+ if (!this.canView()) {
+ return false;
}
- const oldValue = this.getPoint(point);
- if (oldValue === value) {
- return; // Value unchanged, no update needed
+ // Check if there are range protection rules covering this cell that deny view permission
+ const rules = this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId, this._subUnitId);
+ for (const rule of rules) {
+ for (const range of rule.ranges) {
+ if (
+ row >= range.startRow &&
+ row <= range.endRow &&
+ col >= range.startColumn &&
+ col <= range.endColumn
+ ) {
+ // Cell is within protected range, check the rule's view permission
+ const permissionPoint = new RangeProtectionPermissionViewPoint(
+ this._unitId,
+ this._subUnitId,
+ rule.permissionId
+ );
+ const permission = this._permissionService.getPermissionPoint(permissionPoint.id);
+ return permission?.value ?? false;
+ }
+ }
}
- // Use FPermission's setWorksheetPermissionPoint method
- await this._fPermission.setWorksheetPermissionPoint(this._unitId, this._subUnitId, PointClass, value);
-
- // Update snapshot (the Observable stream will automatically emit the change)
- const newSnapshot = this._buildSnapshot();
- this._permissionSubject.next(newSnapshot);
+ return true;
}
/**
@@ -644,9 +482,10 @@ export class FWorksheetPermission {
* @returns {boolean} true if allowed, false if denied.
* @example
* ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * const canInsertRow = permission?.getPoint(univerAPI.Enum.WorksheetPermissionPoint.InsertRow);
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const permission = fWorksheet.getWorksheetPermission();
+ * const canInsertRow = permission.getPoint(univerAPI.Enum.WorksheetPermissionPoint.InsertRow);
* console.log(canInsertRow);
* ```
*/
@@ -667,14 +506,19 @@ export class FWorksheetPermission {
* @returns {WorksheetPermissionSnapshot} An object containing all permission point values.
* @example
* ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * const snapshot = permission?.getSnapshot();
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const snapshot = fWorksheet.getWorksheetPermission().getSnapshot();
* console.log(snapshot);
* ```
*/
getSnapshot(): WorksheetPermissionSnapshot {
- return this._buildSnapshot();
+ const snapshot = {} as WorksheetPermissionSnapshot;
+ for (const point in WorksheetPermissionPoint) {
+ const pointKey = WorksheetPermissionPoint[point as keyof typeof WorksheetPermissionPoint];
+ snapshot[pointKey] = this.getPoint(pointKey);
+ }
+ return snapshot;
}
/**
@@ -725,16 +569,16 @@ export class FWorksheetPermission {
* @returns {Promise<FRangeProtectionRule[]>} Array of created protection rules.
* @example
* ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * const rules = await permission?.protectRanges([
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const rules = await fWorksheet.getWorksheetPermission().protectRanges([
* {
- * ranges: [worksheet.getRange('A1:B2')],
- * options: { name: 'Protected Area 1', allowEdit: false, allowViewByOthers: true }
+ * ranges: [fWorksheet.getRange('A1:B2')],
+ * options: { name: 'Protected Area 1', allowedUsers: ['user1', 'user2'], allowViewByOthers: true }
* },
* {
- * ranges: [worksheet.getRange('C3:D4')],
- * options: { name: 'Protected Area 2', allowEdit: true, allowViewByOthers: false }
+ * ranges: [fWorksheet.getRange('C3:D4')],
+ * options: { name: 'Protected Area 2', allowViewByOthers: false }
* }
* ]);
* console.log(rules);
@@ -751,163 +595,110 @@ export class FWorksheetPermission {
throw new Error('Configs cannot be empty');
}
+ const rules = this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId, this._subUnitId);
+
// Fetch existing collaborators once if any config has allowedUsers
let existingCollaborators: ICollaborator[] = [];
- const hasAllowedUsers = configs.some((c) => c.options?.allowedUsers?.length);
- if (hasAllowedUsers) {
- existingCollaborators = await this._authzIoService.listCollaborators({
- objectID: this._unitId,
- unitID: this._unitId,
- });
- }
+ let fetchCollaborators = false;
+
+ const addRules: IRangeProtectionRule[] = [];
+
+ for (let i = 0; i < configs.length; i++) {
+ const { ranges, options } = configs[i];
- // 1. Create permissionId in parallel
- const permissionIds = await Promise.all(
- configs.map((c) => {
- let collaborators: ICollaborator[] = [];
- if (c.options?.allowedUsers) {
- // Create a map of allowed user IDs for easy lookup
- const allowedUserIds = new Set(c.options.allowedUsers);
-
- // Filter and include only the allowed users with complete information
- collaborators = existingCollaborators
- .filter((collab) => allowedUserIds.has(collab.subject?.userID || collab.id))
- .map((collab) => ({
- id: collab.id,
- role: UnitRole.Editor,
- subject: collab.subject,
- }));
-
- // Check for any user IDs that weren't found in existing collaborators
- const foundUserIds = new Set(collaborators.map((collab) => collab.subject?.userID || collab.id));
- c.options.allowedUsers.forEach((userId) => {
- if (!foundUserIds.has(userId)) {
- console.error(`User ${userId} not found in collaborators list`);
- }
+ if (
+ ranges.some((range) =>
+ rules.some((rule) =>
+ rule.ranges.some((ruleRange) => Rectangle.intersects(ruleRange, range.getRange()))
+ )
+ )
+ ) {
+ throw new Error(`The specified ranges overlap with existing protected ranges: ${ranges.map((r) => r.getA1Notation()).join(', ')}`);
+ }
+
+ const editState = determineEditState(options?.allowedUsers);
+ const viewState = determineViewState(options?.allowViewByOthers);
+ const scope = determineScope(editState, viewState);
+
+ const collaborators: ICollaborator[] = [];
+ if (editState === EditStateEnum.DesignedUserCanEdit) {
+ if (!fetchCollaborators) {
+ existingCollaborators = await this._authzIoService.listCollaborators({
+ objectID: this._unitId,
+ unitID: this._unitId,
});
+ fetchCollaborators = true;
}
- return this._authzIoService.create({
- objectType: UnitObject.SelectRange,
- selectRangeObject: {
- collaborators,
- unitID: this._unitId,
- name: c.options?.name || '',
- scope: undefined,
- },
+ options!.allowedUsers!.forEach((userId) => {
+ const existingCollaborator = existingCollaborators.find((c) => c.subject?.userID === userId || c.id === userId);
+ if (!existingCollaborator) {
+ console.error(`User ${userId} not found in existing collaborators`);
+ return;
+ }
+
+ collaborators.push({
+ id: existingCollaborator.id,
+ role: UnitRole.Editor,
+ subject: existingCollaborator.subject,
+ });
});
- })
- );
+ }
- // 2. Build rule parameters with proper viewState and editState
- const ruleParams = configs.map((c, i) => {
- const viewState = this._determineViewState(c.options);
- const editState = this._determineEditState(c.options);
+ // Create permission ID with collaborators support
+ const permissionId = await this._authzIoService.create({
+ objectType: UnitObject.SelectRange,
+ selectRangeObject: {
+ collaborators,
+ unitID: this._unitId,
+ name: options?.name || '',
+ scope,
+ },
+ });
+ const ruleId = `ruleId_${generateRandomId(6)}`;
- return {
- permissionId: permissionIds[i],
+ addRules.push({
+ ranges: ranges.map((r) => r.getRange()),
+ permissionId,
+ id: ruleId,
+ description: options?.name,
unitType: UnitObject.SelectRange,
unitId: this._unitId,
subUnitId: this._subUnitId,
- ranges: c.ranges.map((r) => r.getRange()),
- id: this._rangeProtectionRuleModel.createRuleId(this._unitId, this._subUnitId),
- description: c.options?.name || '',
viewState,
editState,
- };
- });
+ });
+ }
- // 3. Execute command to add multiple rules at once
- const result = await this._commandService.executeCommand(AddRangeProtectionMutation.id, {
+ const result = this._commandService.syncExecuteCommand<IAddRangeProtectionMutationParams>(AddRangeProtectionMutation.id, {
unitId: this._unitId,
subUnitId: this._subUnitId,
- rules: ruleParams,
+ rules: addRules,
});
if (!result) {
throw new Error('Failed to create range protection rules');
}
- // 4. Set permission points for each rule
- await Promise.all(
- configs.map((c, i) => this._setPermissionPoints(permissionIds[i], c.options))
- );
-
- // 5. Create RangeProtectionRule objects
- const rules = ruleParams.map((param, i) =>
- this._injector.createInstance(
+ const rangeProtectionRules = addRules.map((item, i) => {
+ const rule = this._injector.createInstance(
FRangeProtectionRule,
this._unitId,
this._subUnitId,
- param.id,
- param.permissionId,
+ item.id,
+ item.permissionId,
configs[i].ranges,
configs[i].options || {}
- )
- );
-
- // The Observable stream will automatically emit the change event
- return rules;
- }
-
- /**
- * Determine view state from options
- * @private
- */
- private _determineViewState(options?: IRangeProtectionOptions): ViewStateEnum {
- if (options?.allowViewByOthers === false) {
- return ViewStateEnum.NoOneElseCanView; // Only owner can view
- }
- return ViewStateEnum.OthersCanView;
- }
-
- /**
- * Determine edit state from options
- * @private
- */
- private _determineEditState(options?: IRangeProtectionOptions): EditStateEnum {
- if (options?.allowEdit === true && options?.allowedUsers?.length) {
- return EditStateEnum.DesignedUserCanEdit; // Designed users can edit
- }
- return EditStateEnum.OnlyMe;
- }
-
- /**
- * Set permission points based on options (for local runtime control)
- * @private
- */
- private async _setPermissionPoints(permissionId: string, options?: IRangeProtectionOptions): Promise<void> {
- if (!options) {
- return;
- }
-
- const getPermissionValue = (option: boolean | string[] | undefined, defaultValue: boolean): boolean => {
- if (option === undefined) {
- return defaultValue;
- }
- if (typeof option === 'boolean') {
- return option;
- }
- return true; // For string[] whitelist
- };
+ );
- // Set permission points
- await this._setPermissionPoint(permissionId, RangePermissionPoint.Edit, getPermissionValue(options.allowEdit, false));
- await this._setPermissionPoint(permissionId, RangePermissionPoint.View, getPermissionValue(options.allowViewByOthers, true));
- }
+ // Set permission points based on options (for local runtime control)
+ // rule.setPoint(RangePermissionPoint.Edit, configs[i].options?.allowEdit ?? false);
+ // rule.setPoint(RangePermissionPoint.View, configs[i].options?.allowViewByOthers ?? true);
- /**
- * Set a single permission point
- * @private
- */
- private async _setPermissionPoint(permissionId: string, point: RangePermissionPoint, value: boolean): Promise<void> {
- const PermissionPointClass = RANGE_PERMISSION_POINT_MAP[point];
- if (!PermissionPointClass) {
- return;
- }
+ return rule;
+ });
- // Use FPermission's setRangeProtectionPermissionPoint method
- this._fPermission.setRangeProtectionPermissionPoint(this._unitId, this._subUnitId, permissionId, PermissionPointClass, value);
+ return rangeProtectionRules;
}
/**
@@ -916,20 +707,33 @@ export class FWorksheetPermission {
* @returns {Promise<void>} A promise that resolves when the rules are removed.
* @example
* ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * await permission?.unprotectRules(['rule1', 'rule2']);
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const worksheetPermission = fWorksheet.getWorksheetPermission();
+ * const rules = await worksheetPermission.listRangeProtectionRules();
+ * // Unprotect the first rule as an example
+ * if (rules.length > 0) {
+ * const result = await worksheetPermission.unprotectRules([rules[0].id]);
+ * console.log(result);
+ * }
* ```
*/
- async unprotectRules(ruleIds: string[]): Promise<void> {
+ async unprotectRules(ruleIds: string[]): Promise<boolean> {
if (!ruleIds || ruleIds.length === 0) {
- return;
+ return true;
}
- // Use FPermission's removeRangeProtection method
- this._fPermission.removeRangeProtection(this._unitId, this._subUnitId, ruleIds);
+ const result = await this._commandService.executeCommand(DeleteRangeProtectionMutation.id, {
+ unitId: this._unitId,
+ subUnitId: this._subUnitId,
+ ruleIds,
+ });
+
+ if (result) {
+ handleWorksheetRangePermissionIsEmpty(this._injector, this._unitId, this._subUnitId);
+ }
- // The Observable stream will automatically emit the change event
+ return result;
}
/**
@@ -937,42 +741,83 @@ export class FWorksheetPermission {
* @returns {Promise<FRangeProtectionRule[]>} Array of protection rules.
* @example
* ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * const rules = await permission?.listRangeProtectionRules();
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * const rules = await fWorksheet.getWorksheetPermission().listRangeProtectionRules();
* console.log(rules);
* ```
*/
- async listRangeProtectionRules(): Promise<FRangeProtectionRule[]> {
- return this._buildRangeProtectionRules();
+ async listRangeProtectionRules(
+ options?: {
+ ignoreCollaborators?: boolean; // Option to ignore fetching collaborators for performance
+ }
+ ): Promise<FRangeProtectionRule[]> {
+ return getListRangeProtectionRules(
+ this._injector,
+ this._unitId,
+ this._subUnitId,
+ {
+ worksheet: this._worksheet,
+ ignoreCollaborators: options?.ignoreCollaborators,
+ }
+ );
}
/**
- * Subscribe to permission changes (simplified interface for users not familiar with RxJS).
- * @param {Function} listener Callback function to be called when permissions change.
- * @returns {UnsubscribeFn} Unsubscribe function.
+ * Debug cell permission information.
+ * @param {number} row Row index.
+ * @param {number} col Column index.
+ * @returns {FRangeProtectionRule | undefined} Debug information about which rules affect this cell, or null if no rules apply.
* @example
* ```ts
- * const worksheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
- * const permission = worksheet?.getWorksheetPermission();
- * const unsubscribe = permission?.subscribe((snapshot) => {
- * console.log('Permission changed:', snapshot);
- * });
- * // Later, to stop listening:
- * unsubscribe?.();
+ * const fWorkbook = univerAPI.getActiveWorkbook();
+ * const fWorksheet = fWorkbook.getActiveSheet();
+ * // Get debug info for cell C3
+ * const fRange = fWorksheet.getRange('C3');
+ * const debugInfo = await fWorksheet.getWorksheetPermission().debugCellPermission(fRange.getRow(), fRange.getColumn());
+ * console.log(debugInfo);
* ```
*/
- subscribe(listener: (snapshot: WorksheetPermissionSnapshot) => void): UnsubscribeFn {
- const subscription = this.permission$.subscribe(listener);
- return () => subscription.unsubscribe();
- }
+ async debugCellPermission(row: number, col: number): Promise<FRangeProtectionRule | undefined> {
+ const rules = this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId, this._subUnitId);
+ const cellRange = cellToRange(row, col);
+ const rule = rules.find((rule) =>
+ rule.ranges.some((range) => Rectangle.intersects(cellRange, range))
+ );
- /**
- * Clean up resources
- */
- dispose(): void {
- this._subscriptions.forEach((sub) => sub.unsubscribe());
- this._permissionSubject.complete();
- this._rangeRulesSubject.complete();
+ if (!rule) {
+ return;
+ }
+
+ const ranges = rule.ranges.map((range) => this._worksheet.getRange(range));
+ const options: IRangeProtectionOptions = {
+ name: rule.description || '',
+ allowViewByOthers: rule.viewState !== ViewStateEnum.NoOneElseCanView,
+ };
+
+ if (rule.editState === EditStateEnum.DesignedUserCanEdit) {
+ options.allowedUsers = [];
+
+ try {
+ // Fetch collaborators for this rule
+ const collaborators = await this._authzIoService.listCollaborators({
+ objectID: rule.permissionId,
+ unitID: this._unitId,
+ });
+ options.allowedUsers = collaborators.map((c) => c.subject?.userID || c.id);
+ } catch (error) {
+ console.error(`Failed to fetch collaborators for rule ${rule.id}:`, error);
+ }
+ }
+
+ return this._injector.createInstance(
+ FRangeProtectionRule,
+ this._unitId,
+ this._subUnitId,
+ rule.id,
+ rule.permissionId,
+ ranges,
+ options
+ );
}
}
diff --git a/packages/sheets/src/facade/permission/permission-types.ts b/packages/sheets/src/facade/permission/permission-types.ts
index a801a56092..9f4b4e4016 100644
--- a/packages/sheets/src/facade/permission/permission-types.ts
+++ b/packages/sheets/src/facade/permission/permission-types.ts
@@ -14,9 +14,6 @@
* limitations under the License.
*/
-import type { IUser } from '@univerjs/protocol';
-import type { Observable } from 'rxjs';
-
/**
* ========================
* Basic Types / Enums
@@ -32,24 +29,15 @@ export enum UnitRole {
Owner = 2,
}
-/**
- * User reference information
- */
-export interface IUserRef {
- /** User ID (defined by host system) */
- id: string;
- /** Display name */
- displayName?: string;
- /** Email address */
- email?: string;
+export interface ICollaboratorUser {
+ userID: string;
+ name: string;
+ avatar: string;
}
-/**
- * Collaborator information
- */
export interface ICollaborator {
/** User information */
- user: IUserRef;
+ user: ICollaboratorUser;
/** Role */
role: UnitRole;
}
@@ -190,11 +178,6 @@ export type WorksheetPermissionSnapshot = Record<WorksheetPermissionPoint, boole
*/
export type RangePermissionSnapshot = Record<RangePermissionPoint, boolean>;
-/**
- * Unsubscribe function type
- */
-export type UnsubscribeFn = () => void;
-
/**
* ========================
* Worksheet Protection Configuration
@@ -205,9 +188,17 @@ export type UnsubscribeFn = () => void;
* Worksheet protection options configuration
*/
export interface IWorksheetProtectionOptions {
- /** Whitelist of users allowed to edit; empty means only owner */
+ /**
+ * Specifies users allowed to edit this worksheet; if not specified, defaults to only the owner having edit permission.
+ */
allowedUsers?: string[];
+ /**
+ * Whether to allow others to view this range.
+ * @default true
+ */
+ allowViewByOthers?: boolean;
+
/** Protection name for UI display */
name?: string;
@@ -225,12 +216,15 @@ export interface IWorksheetProtectionOptions {
* Range protection options configuration
*/
export interface IRangeProtectionOptions {
- /** Whether to allow current user to edit (default false = protected, not editable) */
- allowEdit?: boolean;
-
- /** Whitelist of users allowed to edit; empty means determined by role or global policy */
+ /**
+ * Specifies users allowed to edit this range; if not specified, defaults to only the owner having edit permission.
+ */
allowedUsers?: string[];
+ /**
+ * Whether to allow others to view this range.
+ * @default true
+ */
allowViewByOthers?: boolean;
/** Rule name for UI display and management */
@@ -240,117 +234,6 @@ export interface IRangeProtectionOptions {
metadata?: Record<string, unknown>;
}
-/**
- * Cell permission debug rule information
- */
-export interface ICellPermissionDebugRuleInfo {
- ruleId: string;
- /** Range reference string list, e.g., ['A1:B10', 'D1:D5'] */
- rangeRefs: string[];
- options: IRangeProtectionOptions;
-}
-
-/**
- * ========================
- * Facade: WorkbookPermission
- * ========================
- */
-
-/**
- * Workbook-level permission Facade interface
- */
-export interface IWorkbookPermission {
- /**
- * High-level mode setting: By Owner / Editor / Viewer / Commenter semantics
- * Internally automatically combines multiple WorkbookPermissionPoints
- */
- setMode(mode: WorkbookMode): Promise<void>;
-
- /** Shortcut: Set workbook to read-only (equivalent to setMode('viewer')) */
- setReadOnly(): Promise<void>;
-
- /** Shortcut: Set workbook to editable (equivalent to setMode('editor') or owner subset) */
- setEditable(): Promise<void>;
-
- /** Whether current user can edit this workbook (calculated from combined permissions) */
- canEdit(): boolean;
-
- /**
- * Collaborator management (wraps IAuthzIoService)
- */
-
- /** Batch set collaborators (replace mode, overwrites existing collaborator list) */
- setCollaborators(collaborators: Array<{ user: IUser; role: UnitRole }>): Promise<void>;
-
- /** Add a single collaborator */
- addCollaborator(user: IUser, role: UnitRole): Promise<void>;
-
- /** Update collaborator role and information */
- updateCollaborator(user: IUser, role: UnitRole): Promise<void>;
-
- /** Remove collaborator */
- removeCollaborator(userId: string): Promise<void>;
-
- /** Batch remove collaborators */
- removeCollaborators(userIds: string[]): Promise<void>;
-
- /** List all collaborators */
- listCollaborators(): Promise<ICollaborator[]>;
-
- /**
- * Low-level point operations: Directly set boolean value of a WorkbookPermissionPoint
- */
- setPoint(point: WorkbookPermissionPoint, value: boolean): Promise<void>;
-
- /** Read current value of a point (synchronous, reads from local state) */
- getPoint(point: WorkbookPermissionPoint): boolean;
-
- /** Get snapshot of all current points */
- getSnapshot(): WorkbookPermissionSnapshot;
-
- /**
- * ========================
- * RxJS Observable Reactive Interface
- * ========================
- */
-
- /**
- * Permission snapshot change stream (BehaviorSubject, immediately provides current state on subscription)
- * Triggers when any permission point changes
- */
- readonly permission$: Observable<WorkbookPermissionSnapshot>;
-
- /**
- * Single permission point change stream
- * For scenarios that only care about specific permission point changes
- */
- readonly pointChange$: Observable<{
- point: WorkbookPermissionPoint;
- value: boolean;
- oldValue: boolean;
- }>;
-
- /**
- * Collaborator change stream
- */
- readonly collaboratorChange$: Observable<{
- type: 'add' | 'update' | 'delete';
- collaborator: ICollaborator;
- }>;
-
- /**
- * Compatibility method: Simplified subscription (for users unfamiliar with RxJS)
- * Internally implemented based on permission$ Observable
- */
- subscribe(listener: (snapshot: WorkbookPermissionSnapshot) => void): UnsubscribeFn;
-}
-
-/**
- * ========================
- * Facade: WorksheetPermission
- * ========================
- */
-
/**
* Worksheet permission configuration
*/
@@ -367,14 +250,3 @@ export interface IWorksheetPermissionConfig {
options?: IRangeProtectionOptions; // If not provided, defaults to "protected, not editable"
}>;
}
-
-/**
- * ========================
- * Facade: RangePermission
- * ========================
- */
-
-export interface ICellPermissionDebugInfo {
- permissionId: string;
- ruleId: string;
-}
diff --git a/packages/sheets/src/facade/permission/util.ts b/packages/sheets/src/facade/permission/util.ts
new file mode 100644
index 0000000000..e49c4cc211
--- /dev/null
+++ b/packages/sheets/src/facade/permission/util.ts
@@ -0,0 +1,143 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * 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 type { FRange } from '../f-range';
+import type { FWorksheet } from '../f-worksheet';
+import type { IRangeProtectionOptions } from './permission-types';
+import { IAuthzIoService, PermissionService, Rectangle } from '@univerjs/core';
+import { ObjectScope } from '@univerjs/protocol';
+import { EditStateEnum, getAllWorksheetPermissionPointByPointPanel, RangeProtectionRuleModel, ViewStateEnum, WorksheetProtectionPointModel } from '@univerjs/sheets';
+import { FRangeProtectionRule } from './f-range-protection-rule';
+
+export function determineViewState(allowViewByOthers?: boolean): ViewStateEnum {
+ if (allowViewByOthers === false) {
+ return ViewStateEnum.NoOneElseCanView;
+ }
+ return ViewStateEnum.OthersCanView;
+}
+
+export function determineEditState(allowedUsers?: string[]): EditStateEnum {
+ if (allowedUsers?.length) {
+ return EditStateEnum.DesignedUserCanEdit;
+ }
+ return EditStateEnum.OnlyMe;
+}
+
+export function determineScope(editState: EditStateEnum, viewState: ViewStateEnum): {
+ edit: ObjectScope;
+ read: ObjectScope;
+} {
+ return {
+ edit: editState === EditStateEnum.DesignedUserCanEdit ? ObjectScope.SomeCollaborator : ObjectScope.OneSelf,
+ read: viewState === ViewStateEnum.OthersCanView ? ObjectScope.AllCollaborator : ObjectScope.SomeCollaborator,
+ };
+}
+
+/**
+ * Check if there are no range protection rules for the given unit and subunit when removing a range protection rule.
+ * If there are no rules left, also remove the associated worksheet protection and update the permission points accordingly.
+ */
+export function handleWorksheetRangePermissionIsEmpty(injector: Injector, unitId: string, subUnitId: string): void {
+ const rangeProtectionRuleModel = injector.get(RangeProtectionRuleModel);
+ const worksheetProtectionPointModel = injector.get(WorksheetProtectionPointModel);
+ const permissionService = injector.get(PermissionService);
+
+ const rules = rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId);
+ if (rules.length > 0) {
+ return;
+ }
+
+ // Because this rule is attached to other protection, if other protection is deleted, this rule should be deleted.
+ worksheetProtectionPointModel.deleteRule(unitId, subUnitId);
+
+ [...getAllWorksheetPermissionPointByPointPanel()].forEach((F) => {
+ const instance = new F(unitId, subUnitId);
+ permissionService.updatePermissionPoint(instance.id, instance.value);
+ });
+}
+
+/**
+ * Get the list of range protection rules for a specific worksheet or range, and convert them to FRangeProtectionRule instances.
+ */
+export async function getListRangeProtectionRules(
+ injector: Injector,
+ unitId: string,
+ subUnitId: string,
+ options: {
+ worksheet: FWorksheet; // Pass the worksheet to convert IRange to FRange
+ specificRange?: FRange; // Option to specify a particular range to filter rules
+ ignoreCollaborators?: boolean; // Option to ignore fetching collaborators for performance
+ }
+): Promise<FRangeProtectionRule[]> {
+ const rangeProtectionRuleModel = injector.get(RangeProtectionRuleModel);
+ const authzIoService = injector.get(IAuthzIoService);
+
+ const { worksheet, specificRange, ignoreCollaborators = false } = options;
+
+ let rules = rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId);
+ if (specificRange) {
+ rules = rules.filter((rule) =>
+ rule.ranges.some((ruleRange) => Rectangle.intersects(ruleRange, specificRange.getRange()))
+ );
+ }
+
+ const rulesWithOptions = await Promise.all(
+ rules.map(async (rule) => {
+ const ranges = rule.ranges.map((range) => worksheet.getRange(range));
+ const options: IRangeProtectionOptions = {
+ name: rule.description || '',
+ allowViewByOthers: rule.viewState !== ViewStateEnum.NoOneElseCanView,
+ };
+
+ if (rule.editState === EditStateEnum.DesignedUserCanEdit) {
+ options.allowedUsers = [];
+
+ if (!ignoreCollaborators) {
+ try {
+ // Fetch collaborators for this rule
+ const collaborators = await authzIoService.listCollaborators({
+ objectID: rule.permissionId,
+ unitID: unitId,
+ });
+ options.allowedUsers = collaborators.map((c) => c.subject?.userID || c.id);
+ } catch (error) {
+ console.warn(`Failed to fetch collaborators for rule ${rule.id}:`, error);
+ }
+ }
+ }
+
+ return {
+ id: rule.id,
+ permissionId: rule.permissionId,
+ ranges,
+ options,
+ };
+ })
+ );
+
+ return rulesWithOptions.map(({ id, permissionId, ranges, options }) =>
+ injector.createInstance(
+ FRangeProtectionRule,
+ unitId,
+ subUnitId,
+ id,
+ permissionId,
+ ranges,
+ options
+ )
+ );
+}