Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
refactor(permission-ui): refactor permission-ui & user part can be customized (#3945)
ybzky9ae72d090fb7
diff --git a/packages-experimental/action-recorder/src/controllers/action-recorder.controller.tsx b/packages-experimental/action-recorder/src/controllers/action-recorder.controller.tsxindex d20ec2176e..73243829de 100644--- a/packages-experimental/action-recorder/src/controllers/action-recorder.controller.tsx+++ b/packages-experimental/action-recorder/src/controllers/action-recorder.controller.tsx@@ -35,7 +35,6 @@ import { AddWorksheetMergeAllCommand,SetFrozenCommand,SetHorizontalTextAlignCommand,SetOverlineCommand,- SetRangeProtectionCommand,SetRangeValuesCommand,SetSelectionsOperation,SetStrikeThroughCommand,@@ -151,7 +150,6 @@ export class ActionRecorderController extends Disposable {SetRangeFontFamilyCommand,SetRangeFontSizeCommand,SetRangeItalicCommand,- SetRangeProtectionCommand,SetRangeStrickThroughCommand,SetRangeSubscriptCommand,SetRangeSuperscriptCommand,diff --git a/packages/core/src/services/command/command.service.ts b/packages/core/src/services/command/command.service.tsindex 120c2c86f9..471a5b2105 100644--- a/packages/core/src/services/command/command.service.ts+++ b/packages/core/src/services/command/command.service.ts@@ -373,8 +373,6 @@ export class CommandService extends Disposable implements ICommandService {throw new Error(`[CommandService]: command "${id}" is not registered.`);} catch (error) {- this._logService.error(error);-if (error instanceof CustomCommandExecutionError) {// If need custom logic, can add it herereturn false as R;@@ -428,7 +426,6 @@ export class CommandService extends Disposable implements ICommandService {if (error instanceof CustomCommandExecutionError) {return false as R;} else {- this._logService.error(error);throw error;}}diff --git a/packages/sheets-ui/src/commands/commands/range-protection.command.ts b/packages/sheets-ui/src/commands/commands/range-protection.command.tsindex 0b76b01470..5716808b86 100644--- a/packages/sheets-ui/src/commands/commands/range-protection.command.ts+++ b/packages/sheets-ui/src/commands/commands/range-protection.command.ts@@ -16,13 +16,9 @@import type { ICommand, Workbook } from '@univerjs/core';import type { IRangeProtectionRule } from '@univerjs/sheets';-import type { IPermissionPanelRule } from '../../services/permission/sheet-permission-panel.model';-import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, Rectangle, sequenceExecute, UniverInstanceType } from '@univerjs/core';-import { UnitObject } from '@univerjs/protocol';-import { AddRangeProtectionMutation, AddWorksheetProtectionMutation, DeleteRangeProtectionMutation, DeleteWorksheetProtectionMutation, RangeProtectionRuleModel, SetRangeProtectionMutation, SetWorksheetProtectionMutation, SheetsSelectionsService, WorksheetProtectionRuleModel } from '@univerjs/sheets';-import { SheetPermissionPanelModel } from '../../services/permission/sheet-permission-panel.model';+import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, Rectangle, Tools, UniverInstanceType } from '@univerjs/core';+import { AddRangeProtectionMutation, DeleteRangeProtectionMutation, DeleteWorksheetProtectionCommand, RangeProtectionRuleModel, SheetsSelectionsService, WorksheetProtectionRuleModel } from '@univerjs/sheets';import { SheetPermissionOpenPanelOperation } from '../operations/sheet-permission-open-panel.operation';-import { DeleteWorksheetProtectionCommand } from './worksheet-protection.command';export interface IAddRangeProtectionParams {permissionId: string;@@ -37,17 +33,11 @@ export interface IDeleteRangeProtectionParams {rule: IRangeProtectionRule;}-export interface ISetProtectionParams {- rule: IPermissionPanelRule;-}-export const AddRangeProtectionFromToolbarCommand: ICommand = {type: CommandType.COMMAND,id: 'sheet.command.add-range-protection-from-toolbar',async handler(accessor) {const commandService = accessor.get(ICommandService);- const sheetPermissionPanelModel = accessor.get(SheetPermissionPanelModel);- sheetPermissionPanelModel.resetRule();await commandService.executeCommand(SheetPermissionOpenPanelOperation.id, { showDetail: true });return true;},@@ -58,8 +48,6 @@ export const AddRangeProtectionFromContextMenuCommand: ICommand = {id: 'sheet.command.add-range-protection-from-context-menu',async handler(accessor) {const commandService = accessor.get(ICommandService);- const sheetPermissionPanelModel = accessor.get(SheetPermissionPanelModel);- sheetPermissionPanelModel.resetRule();await commandService.executeCommand(SheetPermissionOpenPanelOperation.id, { showDetail: true });return true;},@@ -80,8 +68,6 @@ export const AddRangeProtectionFromSheetBarCommand: ICommand = {id: 'sheet.command.add-range-protection-from-sheet-bar',async handler(accessor) {const commandService = accessor.get(ICommandService);- const sheetPermissionPanelModel = accessor.get(SheetPermissionPanelModel);- sheetPermissionPanelModel.resetRule();await commandService.executeCommand(SheetPermissionOpenPanelOperation.id, { fromSheetBar: true, showDetail: true });return true;},@@ -97,130 +83,6 @@ export const ViewSheetPermissionFromSheetBarCommand: ICommand = {},};-export const AddRangeProtectionCommand: ICommand<IAddRangeProtectionParams> = {- type: CommandType.COMMAND,- id: 'sheet.command.add-range-protection',- async handler(accessor, params) {- if (!params) {- return false;- }- const commandService = accessor.get(ICommandService);- const undoRedoService = accessor.get(IUndoRedoService);- const selectionProtectionModel = accessor.get(RangeProtectionRuleModel);- const { rule, permissionId } = params;-- const { unitId, subUnitId, ranges, name, description } = rule;- const rules = [{- ranges,- permissionId,- id: selectionProtectionModel.createRuleId(unitId, subUnitId),- name,- description,- }];-- const result = await commandService.executeCommand(AddRangeProtectionMutation.id, {- unitId,- subUnitId,- rules,- });-- if (result) {- const redoMutations = [{ id: AddRangeProtectionMutation.id, params: { unitId, subUnitId, rules } }];- const undoMutations = [{ id: DeleteRangeProtectionMutation.id, params: { unitId, subUnitId, ruleIds: rules.map((rule) => rule.id) } }];- undoRedoService.pushUndoRedo({- unitID: unitId,- redoMutations,- undoMutations,- });- }-- return true;- },-};--export const DeleteRangeSelectionCommand: ICommand<IDeleteRangeProtectionParams> = {- type: CommandType.COMMAND,- id: 'sheet.command.delete-range-protection',- async handler(accessor, params) {- if (!params) {- return false;- }- const commandService = accessor.get(ICommandService);- const undoRedoService = accessor.get(IUndoRedoService);- const { unitId, subUnitId, rule } = params;-- const redoMutationParam = {- unitId,- subUnitId,- ruleIds: [rule.id],- };- const result = await commandService.executeCommand(DeleteRangeProtectionMutation.id, redoMutationParam);-- if (result) {- undoRedoService.pushUndoRedo({- unitID: unitId,- redoMutations: [{ id: DeleteRangeProtectionMutation.id, params: redoMutationParam }],- undoMutations: [{ id: AddRangeProtectionMutation.id, params: { unitId, subUnitId, rules: [rule] } }],- });- }-- return true;- },-};--export const SetRangeProtectionCommand: ICommand<ISetRangeProtectionParams> = {- type: CommandType.COMMAND,- id: 'sheet.command.set-range-protection',- async handler(accessor, params) {- if (!params) {- return false;- }- const commandService = accessor.get(ICommandService);- const selectionProtectionModel = accessor.get(RangeProtectionRuleModel);- const sheetPermissionPanelModel = accessor.get(SheetPermissionPanelModel);- const undoRedoService = accessor.get(IUndoRedoService);- const { rule, permissionId } = params;-- const { unitId, subUnitId, ranges, name, description } = rule;-- if (rule.id) {- const redoMutationParam = {- unitId,- subUnitId,- ruleId: rule.id,- rule: {- ranges,- permissionId,- id: selectionProtectionModel.createRuleId(unitId, subUnitId),- name,- description,- },- };- const result = await commandService.executeCommand(SetRangeProtectionMutation.id, redoMutationParam);-- if (result) {- const redoMutations = [{- id: SetRangeProtectionMutation.id, params: redoMutationParam,- }];- const undoMutations = [{- id: SetRangeProtectionMutation.id, params: {- unitId,- subUnitId,- ruleId: rule.id,- rule: sheetPermissionPanelModel.oldRule,- },- }];- undoRedoService.pushUndoRedo({- unitID: unitId,- redoMutations,- undoMutations,- });- }- }- return true;- },-};-export const DeleteRangeProtectionFromContextMenuCommand: ICommand = {type: CommandType.COMMAND,id: 'sheet.command.delete-range-protection-from-context-menu',@@ -287,7 +149,6 @@ export const SetRangeProtectionFromContextMenuCommand: ICommand = {const unitId = workbook.getUnitId();const subUnitId = worksheet.getSheetId();const worksheetRule = worksheetRuleModel.getRule(unitId, subUnitId);- const sheetPermissionPanelModel = accessor.get(SheetPermissionPanelModel);if (worksheetRule?.permissionId) {const oldRule = {...worksheetRule,@@ -295,9 +156,7 @@ export const SetRangeProtectionFromContextMenuCommand: ICommand = {subUnitId,ranges: [],};- sheetPermissionPanelModel.setRule(oldRule);- sheetPermissionPanelModel.setOldRule(oldRule);- await commandService.executeCommand(SheetPermissionOpenPanelOperation.id, { showDetail: true });+ await commandService.executeCommand(SheetPermissionOpenPanelOperation.id, { showDetail: true, rule: Tools.deepClone(oldRule), oldRule: Tools.deepClone(oldRule) });return true;} else {const selectRange = selectionManagerService.getCurrentLastSelection()?.range;@@ -316,9 +175,7 @@ export const SetRangeProtectionFromContextMenuCommand: ICommand = {unitId,subUnitId,};- sheetPermissionPanelModel.setRule(oldRule);- sheetPermissionPanelModel.setOldRule(oldRule);- await commandService.executeCommand(SheetPermissionOpenPanelOperation.id, { showDetail: true });+ await commandService.executeCommand(SheetPermissionOpenPanelOperation.id, { showDetail: true, rule: Tools.deepClone(oldRule), oldRule: Tools.deepClone(oldRule) });return true;} else {return false;@@ -327,64 +184,3 @@ export const SetRangeProtectionFromContextMenuCommand: ICommand = {},};-export const SetProtectionCommand: ICommand<ISetProtectionParams> = {- type: CommandType.COMMAND,- id: 'sheet.command.set-protection',- async handler(accessor, params) {- if (!params) {- return false;- }- const commandService = accessor.get(ICommandService);- const undoRedoService = accessor.get(IUndoRedoService);- const sheetPermissionPanelModel = accessor.get(SheetPermissionPanelModel);- const rangeProtectionRuleModel = accessor.get(RangeProtectionRuleModel);- const { rule } = params;- const { unitId, subUnitId } = rule;-- const redoMutations = [];- const undoMutations = [];-- const oldRule = sheetPermissionPanelModel.oldRule;-- if (oldRule?.unitType === rule.unitType) {- if (rule.unitType === UnitObject.Worksheet) {- redoMutations.push({ id: SetWorksheetProtectionMutation.id, params: { unitId, subUnitId, rule } });- undoMutations.push({ id: SetWorksheetProtectionMutation.id, params: { unitId, subUnitId, rule: oldRule } });- } else {- redoMutations.push({ id: SetRangeProtectionMutation.id, params: { unitId, subUnitId, rule, ruleId: (rule as IRangeProtectionRule).id } });- undoMutations.push({ id: SetRangeProtectionMutation.id, params: { unitId, subUnitId, ruleId: (oldRule as IRangeProtectionRule).id, rule: oldRule } });- }- } else {- if (oldRule) {- if (oldRule.unitType === UnitObject.Worksheet) {- redoMutations.push({ id: DeleteWorksheetProtectionMutation.id, params: { unitId, subUnitId } });- undoMutations.push({ id: AddWorksheetProtectionMutation.id, params: { unitId, rule: oldRule, subUnitId: oldRule.subUnitId } });- } else if (oldRule.unitType === UnitObject.SelectRange) {- redoMutations.push({ id: DeleteRangeProtectionMutation.id, params: { unitId, subUnitId, ruleIds: [(oldRule as IRangeProtectionRule).id] } });- undoMutations.push({ id: AddRangeProtectionMutation.id, params: { unitId, subUnitId, rules: [oldRule] } });- }- }-- if (rule.unitType === UnitObject.Worksheet) {- redoMutations.push({ id: AddWorksheetProtectionMutation.id, params: { unitId, rule, subUnitId: rule.subUnitId } });- undoMutations.unshift({ id: DeleteWorksheetProtectionMutation.id, params: { unitId, subUnitId } });- } else if (rule.unitType === UnitObject.SelectRange) {- (rule as IRangeProtectionRule).id = rangeProtectionRuleModel.createRuleId(unitId, subUnitId);- redoMutations.push({ id: AddRangeProtectionMutation.id, params: { unitId, subUnitId, rules: [rule] } });- undoMutations.unshift({ id: DeleteRangeProtectionMutation.id, params: { unitId, subUnitId, ruleIds: [(rule as IRangeProtectionRule).id] } });- }- }-- const result = sequenceExecute(redoMutations, commandService);-- if (result) {- undoRedoService.pushUndoRedo({- unitID: unitId,- undoMutations,- redoMutations,- });- }-- return true;- },-};diff --git a/packages/sheets-ui/src/commands/commands/worksheet-protection.command.ts b/packages/sheets-ui/src/commands/commands/worksheet-protection.command.tsindex f81ef7ec83..173d31ed44 100644--- a/packages/sheets-ui/src/commands/commands/worksheet-protection.command.ts+++ b/packages/sheets-ui/src/commands/commands/worksheet-protection.command.ts@@ -15,126 +15,11 @@*/import type { ICommand, Workbook } from '@univerjs/core';+import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';import { UniverType } from '@univerjs/protocol';--import { AddWorksheetProtectionMutation, DeleteWorksheetProtectionMutation, SetWorksheetProtectionMutation, WorksheetProtectionRuleModel } from '@univerjs/sheets';-import type { IWorksheetProtectionRule } from '@univerjs/sheets';-import { SheetPermissionPanelModel } from '../../services/permission/sheet-permission-panel.model';--export interface IAddWorksheetProtectionParams {- unitId: string;- rule: IWorksheetProtectionRule;-}--export interface IDeleteWorksheetProtectionParams {- unitId: string;- subUnitId: string;- rule: IWorksheetProtectionRule;-}--export interface ISetWorksheetProtectionParams {- permissionId: string;- rule: IWorksheetProtectionRule;-}--export const AddWorksheetProtectionCommand: ICommand<IAddWorksheetProtectionParams> = {- type: CommandType.COMMAND,- id: 'sheet.command.add-worksheet-protection',- async handler(accessor, params) {- if (!params) {- return false;- }- const commandService = accessor.get(ICommandService);- const undoRedoService = accessor.get(IUndoRedoService);- const { rule, unitId } = params;- const subUnitId = rule.subUnitId;-- const result = await commandService.executeCommand(AddWorksheetProtectionMutation.id, {- unitId,- rule,- subUnitId: rule.subUnitId,- });-- if (result) {- const redoMutations = [{ id: AddWorksheetProtectionMutation.id, params: { unitId, rule, subUnitId: rule.subUnitId } }];- const undoMutations = [{ id: DeleteWorksheetProtectionMutation.id, params: { unitId, subUnitId } }];- undoRedoService.pushUndoRedo({- unitID: unitId,- redoMutations,- undoMutations,- });- }-- return true;- },-};--export const DeleteWorksheetProtectionCommand: ICommand<IDeleteWorksheetProtectionParams> = {- type: CommandType.COMMAND,- id: 'sheet.command.delete-worksheet-protection',- handler(accessor, params) {- if (!params) {- return false;- }- const commandService = accessor.get(ICommandService);- const undoRedoService = accessor.get(IUndoRedoService);- const { rule, unitId, subUnitId } = params;-- commandService.executeCommand(DeleteWorksheetProtectionMutation.id, {- unitId,- subUnitId,- });-- const redoMutations = [{ id: DeleteWorksheetProtectionMutation.id, params: { unitId, subUnitId } }];- const undoMutations = [{ id: AddWorksheetProtectionMutation.id, params: { unitId, rule, subUnitId } }];- undoRedoService.pushUndoRedo({- unitID: unitId,- redoMutations,- undoMutations,- });-- return true;- },-};--export const SetWorksheetProtectionCommand: ICommand<ISetWorksheetProtectionParams> = {- type: CommandType.COMMAND,- id: 'sheet.command.set-worksheet-protection',- async handler(accessor, params) {- if (!params) {- return false;- }- const commandService = accessor.get(ICommandService);- const sheetPermissionPanelModel = accessor.get(SheetPermissionPanelModel);- const undoRedoService = accessor.get(IUndoRedoService);-- const { rule, permissionId } = params;- const { unitId, subUnitId } = rule;-- const newRule = { ...rule, permissionId };- const oldRule = sheetPermissionPanelModel.oldRule;-- const result = await commandService.executeCommand(SetWorksheetProtectionMutation.id, {- unitId,- subUnitId,- newRule,- });-- if (result) {- const redoMutations = [{ id: SetWorksheetProtectionMutation.id, params: { unitId, subUnitId, newRule } }];- const undoMutations = [{ id: SetWorksheetProtectionMutation.id, params: { unitId, subUnitId, rule: oldRule } }];- undoRedoService.pushUndoRedo({- unitID: unitId,- redoMutations,- undoMutations,- });- }-- return true;- },-};+import { AddWorksheetProtectionCommand, DeleteWorksheetProtectionCommand, WorksheetProtectionRuleModel } from '@univerjs/sheets';export const DeleteWorksheetProtectionFormSheetBarCommand: ICommand = {type: CommandType.COMMAND,diff --git a/packages/sheets-ui/src/commands/operations/sheet-permission-open-panel.operation.ts b/packages/sheets-ui/src/commands/operations/sheet-permission-open-panel.operation.tsindex 0f5f0bcf97..0456170d55 100644--- a/packages/sheets-ui/src/commands/operations/sheet-permission-open-panel.operation.ts+++ b/packages/sheets-ui/src/commands/operations/sheet-permission-open-panel.operation.ts@@ -15,15 +15,18 @@*/import type { ICommand } from '@univerjs/core';+import type { IPermissionPanelRule } from '../../services/permission/sheet-permission-panel.model';import { CommandType } from '@univerjs/core';import { ISidebarService } from '@univerjs/ui';+import { UNIVER_SHEET_PERMISSION_PANEL } from '../../consts/permission';import { SheetPermissionPanelModel } from '../../services/permission/sheet-permission-panel.model';import { SheetPermissionUserManagerService } from '../../services/permission/sheet-permission-user-list.service';-import { UNIVER_SHEET_PERMISSION_PANEL, UNIVER_SHEET_PERMISSION_PANEL_FOOTER } from '../../consts/permission';export interface IPermissionOpenPanelParam {fromSheetBar?: boolean;showDetail?: boolean;+ rule?: IPermissionPanelRule;+ oldRule?: IPermissionPanelRule;}export const SheetPermissionOpenPanelOperation: ICommand<IPermissionOpenPanelParam> = {@@ -34,7 +37,7 @@ export const SheetPermissionOpenPanelOperation: ICommand<IPermissionOpenPanelParconst sheetPermissionPanelModel = accessor.get(SheetPermissionPanelModel);const sheetPermissionUserManagerService = accessor.get(SheetPermissionUserManagerService);- const { showDetail = true, fromSheetBar = false } = _params;+ const { showDetail = true, fromSheetBar = false, rule, oldRule } = _params;const sidebarProps = {header: { title: 'permission.panel.title' },@@ -42,12 +45,10 @@ export const SheetPermissionOpenPanelOperation: ICommand<IPermissionOpenPanelParlabel: UNIVER_SHEET_PERMISSION_PANEL,showDetail,fromSheetBar,+ rule,+ oldRule,},width: 330,- footer: {- label: UNIVER_SHEET_PERMISSION_PANEL_FOOTER,- showDetail,- },onClose: () => {sheetPermissionPanelModel.reset();sheetPermissionUserManagerService.reset();diff --git a/packages/sheets-ui/src/consts/permission.ts b/packages/sheets-ui/src/consts/permission.tsindex 7f0a2818de..4341b93fc7 100644--- a/packages/sheets-ui/src/consts/permission.ts+++ b/packages/sheets-ui/src/consts/permission.ts@@ -18,6 +18,7 @@ import { UnitAction } from '@univerjs/protocol';export const UNIVER_SHEET_PERMISSION_PLUGIN_NAME = 'UNIVER_SHEET_PERMISSION_PLUGIN';export const UNIVER_SHEET_PERMISSION_PANEL = 'UNIVER_SHEET_PERMISSION_PANEL';+export const UNIVER_SHEET_PERMISSION_USER_PART = 'UNIVER_SHEET_PERMISSION_USER_PART';export const UNIVER_SHEET_PERMISSION_PANEL_FOOTER = 'UNIVER_SHEET_PERMISSION_PANEL_FOOTER';export const UNIVER_SHEET_PERMISSION_USER_DIALOG = 'UNIVER_SHEET_PERMISSION_USER_DIALOG';export const UNIVER_SHEET_PERMISSION_DIALOG = 'UNIVER_SHEET_PERMISSION_DIALOG';diff --git a/packages/sheets-ui/src/controllers/menu/permission-menu-util.ts b/packages/sheets-ui/src/controllers/menu/permission-menu-util.tsindex 25d7bfbcd4..68b9cfcb89 100644--- a/packages/sheets-ui/src/controllers/menu/permission-menu-util.ts+++ b/packages/sheets-ui/src/controllers/menu/permission-menu-util.ts@@ -105,6 +105,7 @@ export function getEditPermissionHidden$(accessor: IAccessor) {const subUnitRuleList = rangeRuleModel.getSubunitRuleList(unitId, subUnitId);const selectionRanges = selectionManagerService.getCurrentSelections()?.map((selection) => selection.range);+ const ruleRanges = subUnitRuleList.map((rule) => rule.ranges).flat();if (!selectionRanges?.length) {return true;}@@ -216,7 +217,7 @@ export function getAddPermissionDisableBase$(accessor: IAccessor) {const editorVisible$ = editorBridgeService?.visible$ ?? of(null);return combineLatest([workbook$, userManagerService.currentUser$, editorVisible$, formulaEditorFocus$]).pipe(- switchMap(([workbook, __, visible, formulaEditorFocus]) => {+ switchMap(([workbook, _, visible, formulaEditorFocus]) => {if (!workbook || (visible?.visible && visible.unitId === workbook.getUnitId()) || formulaEditorFocus) {return of(true);}@@ -306,7 +307,7 @@ export function getAddPermissionFromSheetBarDisable$(accessor: IAccessor) {if (!permission) return true;const worksheetRule = worksheetProtectionRuleModel.getRule(unitId, subUnitId);if (worksheetRule?.permissionId) return true;- const subUnitRuleList = selectionProtectionRuleModel.getSubunitRuleList(unitId, subUnitId)?.filter((item) => item?.permissionId && item?.name);+ const subUnitRuleList = selectionProtectionRuleModel.getSubunitRuleList(unitId, subUnitId)?.filter((item) => item?.permissionId);return subUnitRuleList.length > 0;}));@@ -416,13 +417,14 @@ export function getRemovePermissionDisable$(accessor: IAccessor) {const sheetSelectionsService = accessor.get(SheetsSelectionsService);const selectionProtectionRuleModel = accessor.get(RangeProtectionRuleModel);const worksheetProtectionRuleModel = accessor.get(WorksheetProtectionRuleModel);- // const permission$ = permissionService.composePermission$([new WorkbookEditablePermission(unitId).id]).pipe(map((permissions) => permissions.every((permission) => permission.value))) ?? of(false);- return merge(++ const changes$ = merge(selectionProtectionRuleModel.ruleChange$,worksheetProtectionRuleModel.ruleChange$,sheetSelectionsService.selectionMoveEnd$- ).pipe(startWith(null)).pipe(- map(() => {+ ).pipe(startWith(null));+ return combineLatest([changes$]).pipe(+ map(([_]) => {const selections = accessor.get(SheetsSelectionsService).getCurrentSelections();const selectionRanges = selections?.map((selection) => selection.range);if (!selectionRanges?.length || selectionRanges.length > 1) {@@ -480,7 +482,7 @@ export function getViewPermissionDisable$(accessor: IAccessor) {const editorVisible$ = editorBridgeService?.visible$ ?? of(null);return combineLatest([workbook$, userManagerService.currentUser$, editorVisible$, formulaEditorFocus$]).pipe(- switchMap(([workbook, __, visible, formulaEditorFocus]) => {+ switchMap(([workbook, _, visible, formulaEditorFocus]) => {if (!workbook || (visible?.visible && visible.unitId === workbook.getUnitId()) || formulaEditorFocus) {return of(true);}diff --git a/packages/sheets-ui/src/controllers/mobile/mobile-sheet-ui.controller.ts b/packages/sheets-ui/src/controllers/mobile/mobile-sheet-ui.controller.tsindex 61ef1e385f..22938f7a5a 100644--- a/packages/sheets-ui/src/controllers/mobile/mobile-sheet-ui.controller.ts+++ b/packages/sheets-ui/src/controllers/mobile/mobile-sheet-ui.controller.ts@@ -48,7 +48,7 @@ import {} from '../../commands/commands/inline-format.command';import { InsertRangeMoveDownConfirmCommand } from '../../commands/commands/insert-range-move-down-confirm.command';import { InsertRangeMoveRightConfirmCommand } from '../../commands/commands/insert-range-move-right-confirm.command';-import { AddRangeProtectionFromContextMenuCommand, AddRangeProtectionFromSheetBarCommand, AddRangeProtectionFromToolbarCommand, DeleteRangeProtectionFromContextMenuCommand, SetProtectionCommand, SetRangeProtectionFromContextMenuCommand, ViewSheetPermissionFromContextMenuCommand, ViewSheetPermissionFromSheetBarCommand } from '../../commands/commands/range-protection.command';+import { AddRangeProtectionFromContextMenuCommand, AddRangeProtectionFromSheetBarCommand, AddRangeProtectionFromToolbarCommand, DeleteRangeProtectionFromContextMenuCommand, SetRangeProtectionFromContextMenuCommand, ViewSheetPermissionFromContextMenuCommand, ViewSheetPermissionFromSheetBarCommand } from '../../commands/commands/range-protection.command';import { RefillCommand } from '../../commands/commands/refill.command';import { RemoveColConfirmCommand, RemoveRowConfirmCommand } from '../../commands/commands/remove-row-col-confirm.command';import { RemoveSheetConfirmCommand } from '../../commands/commands/remove-sheet-confirm.command';@@ -71,7 +71,7 @@ import {} from '../../commands/commands/set-selection.command';import { ChangeZoomRatioCommand, SetZoomRatioCommand } from '../../commands/commands/set-zoom-ratio.command';import { ShowMenuListCommand } from '../../commands/commands/unhide.command';-import { AddWorksheetProtectionCommand, ChangeSheetProtectionFromSheetBarCommand, DeleteWorksheetProtectionCommand, DeleteWorksheetProtectionFormSheetBarCommand, SetWorksheetProtectionCommand } from '../../commands/commands/worksheet-protection.command';+import { ChangeSheetProtectionFromSheetBarCommand, DeleteWorksheetProtectionFormSheetBarCommand } from '../../commands/commands/worksheet-protection.command';import { SetActivateCellEditOperation } from '../../commands/operations/activate-cell-edit.operation';import {SetCellEditVisibleArrowOperation,@@ -258,11 +258,7 @@ export class SheetUIMobileController extends Disposable {ChangeSheetProtectionFromSheetBarCommand,DeleteRangeProtectionFromContextMenuCommand,SetRangeProtectionFromContextMenuCommand,- AddWorksheetProtectionCommand,- DeleteWorksheetProtectionCommand,- SetWorksheetProtectionCommand,DeleteWorksheetProtectionFormSheetBarCommand,- SetProtectionCommand,].forEach((c) => {this.disposeWithMe(this._commandService.registerCommand(c));});diff --git a/packages/sheets-ui/src/controllers/permission/sheet-permission-render.controller.ts b/packages/sheets-ui/src/controllers/permission/sheet-permission-render.controller.tsindex 7597913660..ffd3aa569b 100644--- a/packages/sheets-ui/src/controllers/permission/sheet-permission-render.controller.ts+++ b/packages/sheets-ui/src/controllers/permission/sheet-permission-render.controller.ts@@ -16,32 +16,38 @@import type { IRenderContext, IRenderModule, Spreadsheet } from '@univerjs/engine-render';import type { MenuConfig } from '@univerjs/ui';-import { Disposable, Inject, IPermissionService, IUniverInstanceService } from '@univerjs/core';+import { connectInjector, Disposable, Inject, Injector, IPermissionService, IUniverInstanceService } from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';import { CheckMarkSingle, DeleteSingle, LockSingle, ProtectSingle, WriteSingle } from '@univerjs/icons';import { RangeProtectionRuleModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';-import { ComponentManager } from '@univerjs/ui';+import { ComponentManager, IUIPartsService } from '@univerjs/ui';import { merge, throttleTime } from 'rxjs';-import { permissionCheckIconKey, permissionDeleteIconKey, permissionEditIconKey, permissionLockIconKey, permissionMenuIconKey, UNIVER_SHEET_PERMISSION_DIALOG, UNIVER_SHEET_PERMISSION_PANEL, UNIVER_SHEET_PERMISSION_PANEL_FOOTER, UNIVER_SHEET_PERMISSION_USER_DIALOG } from '../../consts/permission';+import { permissionCheckIconKey, permissionDeleteIconKey, permissionEditIconKey, permissionLockIconKey, permissionMenuIconKey, UNIVER_SHEET_PERMISSION_DIALOG, UNIVER_SHEET_PERMISSION_PANEL, UNIVER_SHEET_PERMISSION_USER_DIALOG, UNIVER_SHEET_PERMISSION_USER_PART } from '../../consts/permission';import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';-import { SheetPermissionDialog, SheetPermissionPanel, SheetPermissionPanelFooter, SheetPermissionUserDialog } from '../../views/permission';+import { SheetPermissionDialog, SheetPermissionPanel, SheetPermissionUserDialog } from '../../views/permission';import { AlertDialog } from '../../views/permission/error-msg-dialog';import { UNIVER_SHEET_PERMISSION_ALERT_DIALOG } from '../../views/permission/error-msg-dialog/interface';import { RANGE_PROTECTION_CAN_NOT_VIEW_RENDER_EXTENSION_KEY, RANGE_PROTECTION_CAN_VIEW_RENDER_EXTENSION_KEY, RangeProtectionCanNotViewRenderExtension, RangeProtectionCanViewRenderExtension } from '../../views/permission/extensions/range-protection.render';import { worksheetProtectionKey, WorksheetProtectionRenderExtension } from '../../views/permission/extensions/worksheet-permission.render';+import { PermissionDetailUserPart } from '../../views/permission/panel-detail/PermissionDetailUserPart';export interface IUniverSheetsPermissionMenuConfig {menu: MenuConfig;}export class SheetPermissionRenderManagerController extends Disposable {- constructor(@Inject(ComponentManager) private _componentManager: ComponentManager) {+ constructor(+ @Inject(Injector) private _injector: Injector,+ @Inject(ComponentManager) private _componentManager: ComponentManager,+ @Inject(IUIPartsService) private _uiPartsService: IUIPartsService+ ) {super();this._init();}private _init(): void {this._initComponents();+ this._initUiPartComponents();}private _initComponents(): void {@@ -52,7 +58,6 @@ export class SheetPermissionRenderManagerController extends Disposable {[permissionCheckIconKey, CheckMarkSingle],[permissionLockIconKey, LockSingle],[UNIVER_SHEET_PERMISSION_PANEL, SheetPermissionPanel],- [UNIVER_SHEET_PERMISSION_PANEL_FOOTER, SheetPermissionPanelFooter],[UNIVER_SHEET_PERMISSION_USER_DIALOG, SheetPermissionUserDialog],[UNIVER_SHEET_PERMISSION_DIALOG, SheetPermissionDialog],[UNIVER_SHEET_PERMISSION_ALERT_DIALOG, AlertDialog],@@ -63,6 +68,10 @@ export class SheetPermissionRenderManagerController extends Disposable {));});}++ private _initUiPartComponents(): void {+ this.disposeWithMe(this._uiPartsService.registerComponent(UNIVER_SHEET_PERMISSION_USER_PART, () => connectInjector(PermissionDetailUserPart, this._injector)));+ }}export class SheetPermissionRenderController extends Disposable implements IRenderModule {diff --git a/packages/sheets-ui/src/controllers/sheet-ui.controller.ts b/packages/sheets-ui/src/controllers/sheet-ui.controller.tsindex 90cfd46310..6eddc85e31 100644--- a/packages/sheets-ui/src/controllers/sheet-ui.controller.ts+++ b/packages/sheets-ui/src/controllers/sheet-ui.controller.ts@@ -53,7 +53,7 @@ import {} from '../commands/commands/inline-format.command';import { InsertRangeMoveDownConfirmCommand } from '../commands/commands/insert-range-move-down-confirm.command';import { InsertRangeMoveRightConfirmCommand } from '../commands/commands/insert-range-move-right-confirm.command';-import { AddRangeProtectionFromContextMenuCommand, AddRangeProtectionFromSheetBarCommand, AddRangeProtectionFromToolbarCommand, DeleteRangeProtectionFromContextMenuCommand, SetProtectionCommand, SetRangeProtectionFromContextMenuCommand, ViewSheetPermissionFromContextMenuCommand, ViewSheetPermissionFromSheetBarCommand } from '../commands/commands/range-protection.command';+import { AddRangeProtectionFromContextMenuCommand, AddRangeProtectionFromSheetBarCommand, AddRangeProtectionFromToolbarCommand, DeleteRangeProtectionFromContextMenuCommand, SetRangeProtectionFromContextMenuCommand, ViewSheetPermissionFromContextMenuCommand, ViewSheetPermissionFromSheetBarCommand } from '../commands/commands/range-protection.command';import { RefillCommand } from '../commands/commands/refill.command';import { RemoveColConfirmCommand, RemoveRowConfirmCommand } from '../commands/commands/remove-row-col-confirm.command';import { RemoveSheetConfirmCommand } from '../commands/commands/remove-sheet-confirm.command';@@ -77,7 +77,7 @@ import {import { SetWorksheetColAutoWidthCommand } from '../commands/commands/set-worksheet-auto-col-width.command';import { ChangeZoomRatioCommand, SetZoomRatioCommand } from '../commands/commands/set-zoom-ratio.command';import { ShowMenuListCommand } from '../commands/commands/unhide.command';-import { AddWorksheetProtectionCommand, ChangeSheetProtectionFromSheetBarCommand, DeleteWorksheetProtectionCommand, DeleteWorksheetProtectionFormSheetBarCommand, SetWorksheetProtectionCommand } from '../commands/commands/worksheet-protection.command';+import { ChangeSheetProtectionFromSheetBarCommand, DeleteWorksheetProtectionFormSheetBarCommand } from '../commands/commands/worksheet-protection.command';import { SetActivateCellEditOperation } from '../commands/operations/activate-cell-edit.operation';import {SetCellEditVisibleArrowOperation,@@ -273,11 +273,7 @@ export class SheetUIController extends Disposable {ChangeSheetProtectionFromSheetBarCommand,DeleteRangeProtectionFromContextMenuCommand,SetRangeProtectionFromContextMenuCommand,- AddWorksheetProtectionCommand,- DeleteWorksheetProtectionCommand,- SetWorksheetProtectionCommand,DeleteWorksheetProtectionFormSheetBarCommand,- SetProtectionCommand,SetWorksheetColAutoWidthCommand,].forEach((c) => {this.disposeWithMe(this._commandService.registerCommand(c));diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.tsindex ba7fb36e67..6d6c1c16b4 100644--- a/packages/sheets-ui/src/index.ts+++ b/packages/sheets-ui/src/index.ts@@ -145,14 +145,10 @@ export {export { InsertRangeMoveDownConfirmCommand } from './commands/commands/insert-range-move-down-confirm.command';export { InsertRangeMoveRightConfirmCommand } from './commands/commands/insert-range-move-right-confirm.command';export {- AddRangeProtectionCommand,AddRangeProtectionFromContextMenuCommand,AddRangeProtectionFromSheetBarCommand,AddRangeProtectionFromToolbarCommand,DeleteRangeProtectionFromContextMenuCommand,- DeleteRangeSelectionCommand,- SetProtectionCommand,- SetRangeProtectionCommand,SetRangeProtectionFromContextMenuCommand,ViewSheetPermissionFromContextMenuCommand,ViewSheetPermissionFromSheetBarCommand,@@ -175,11 +171,8 @@ export { ExpandSelectionCommand, JumpOver, MoveSelectionCommand, MoveSelectionEnexport { ChangeZoomRatioCommand, SetZoomRatioCommand } from './commands/commands/set-zoom-ratio.command';export { ShowMenuListCommand } from './commands/commands/unhide.command';export {- AddWorksheetProtectionCommand,ChangeSheetProtectionFromSheetBarCommand,- DeleteWorksheetProtectionCommand,DeleteWorksheetProtectionFormSheetBarCommand,- SetWorksheetProtectionCommand,} from './commands/commands/worksheet-protection.command';export { SetActivateCellEditOperation } from './commands/operations/activate-cell-edit.operation';diff --git a/packages/sheets-ui/src/locale/en-US.ts b/packages/sheets-ui/src/locale/en-US.tsindex 287ecd7518..3581cd8e0b 100644--- a/packages/sheets-ui/src/locale/en-US.ts+++ b/packages/sheets-ui/src/locale/en-US.ts@@ -605,6 +605,7 @@ const locale: typeof zhCN = {setCellStyle: 'Set cell style',copy: 'Copy',alert: 'Alert',+ search: 'Search',alertContent: 'This range has been protected and no editing permissions are currently available. If you need to edit, please contact the creator.',userEmpty: 'no designated person , Share link to invite specific people.',listEmpty: 'You haven\'t set up any ranges or sheets as protected.',diff --git a/packages/sheets-ui/src/locale/fa-IR.ts b/packages/sheets-ui/src/locale/fa-IR.tsindex f7f9f46197..d17c2f8adc 100644--- a/packages/sheets-ui/src/locale/fa-IR.ts+++ b/packages/sheets-ui/src/locale/fa-IR.ts@@ -605,6 +605,7 @@ const locale: typeof zhCN = {setCellStyle: 'تنظیم سبک سلول',copy: 'کپی',alert: 'هشدار',+ search: 'جستجو',alertContent: 'این محدوده محافظت شده است و در حال حاضر هیچ مجوز ویرایشی در دسترس نیست. اگر نیاز به ویرایش دارید، لطفا با سازنده تماس بگیرید.',userEmpty: 'هیچ شخص تعیین شدهای وجود ندارد، لینک اشتراک را برای دعوت افراد خاص ارسال کنید.',listEmpty: 'شما هیچ محدوده یا برگهای را به عنوان محافظت شده تنظیم نکردهاید.',diff --git a/packages/sheets-ui/src/locale/ru-RU.ts b/packages/sheets-ui/src/locale/ru-RU.tsindex ab04d7f540..dad30a39a4 100644--- a/packages/sheets-ui/src/locale/ru-RU.ts+++ b/packages/sheets-ui/src/locale/ru-RU.ts@@ -605,6 +605,7 @@ const locale: typeof zhCN = {setCellStyle: 'Установить стиль ячейки',copy: 'Копировать',alert: 'Предупреждение',+ search: 'Поиск',alertContent: 'Этот диапазон защищен и в настоящее время недоступен для редактирования. Если вам нужно редактировать, пожалуйста, свяжитесь с создателем.',userEmpty: 'нет назначенных лиц, поделитесь ссылкой, чтобы пригласить конкретных людей.',listEmpty: 'Вы не установили ни одного защищенного диапазона или листа.',diff --git a/packages/sheets-ui/src/locale/vi-VN.ts b/packages/sheets-ui/src/locale/vi-VN.tsindex e9f901cf13..5703de128f 100644--- a/packages/sheets-ui/src/locale/vi-VN.ts+++ b/packages/sheets-ui/src/locale/vi-VN.ts@@ -601,6 +601,7 @@ const locale: typeof zhCN = {setCellStyle: 'Thiết lập kiểu ô',copy: 'Sao chép',alert: 'Thông báo',+ search: 'Tìm kiếm',alertContent: 'Phạm vi này đã được bảo vệ, hiện không có quyền chỉnh sửa. Nếu cần chỉnh sửa, vui lòng liên hệ với người tạo.',userEmpty: 'Không có người chỉ định, chia sẻ liên kết để mời người cụ thể.',listEmpty: 'Bạn chưa thiết lập bất kỳ phạm vi hoặc bảng tính nào ở trạng thái được bảo vệ.',diff --git a/packages/sheets-ui/src/locale/zh-CN.ts b/packages/sheets-ui/src/locale/zh-CN.tsindex 7a7eb4164b..2baa832739 100644--- a/packages/sheets-ui/src/locale/zh-CN.ts+++ b/packages/sheets-ui/src/locale/zh-CN.ts@@ -600,6 +600,7 @@ const locale = {setCellStyle: '设置单元格样式',copy: '复制',alert: '提示',+ search: '搜索',alertContent: '该范围已被保护,目前无编辑权限。如需编辑,请联系创建者。',userEmpty: '没有指定的人员,分享链接以邀请特定的人。',listEmpty: '你还没有设置任何范围或工作表为受保护状态。',diff --git a/packages/sheets-ui/src/locale/zh-TW.ts b/packages/sheets-ui/src/locale/zh-TW.tsindex e49fdee8a8..cd82720eba 100644--- a/packages/sheets-ui/src/locale/zh-TW.ts+++ b/packages/sheets-ui/src/locale/zh-TW.ts@@ -602,6 +602,7 @@ const locale: typeof zhCN = {setCellStyle: '設定儲存格樣式',copy: '複製',alert: '提示',+ search: '搜索',alertContent: '該範圍已被保護,目前無編輯權限。如需編輯,請聯絡創建者。 ',userEmpty: '沒有指定的人員,分享連結以邀請特定的人。 ',listEmpty: '你還沒有設定任何範圍或工作表為受保護狀態。 ',diff --git a/packages/sheets-ui/src/services/permission/sheet-permission-panel.model.ts b/packages/sheets-ui/src/services/permission/sheet-permission-panel.model.tsindex 0e035670e0..d4066d1e56 100644--- a/packages/sheets-ui/src/services/permission/sheet-permission-panel.model.ts+++ b/packages/sheets-ui/src/services/permission/sheet-permission-panel.model.ts@@ -14,40 +14,24 @@* limitations under the License.*/-import type { IRange, Nullable } from '@univerjs/core';-import type { IRangeProtectionRule, IWorksheetProtectionRule } from '@univerjs/sheets';-import { UnitObject } from '@univerjs/protocol';-import { BehaviorSubject } from 'rxjs';+import type { IRange } from '@univerjs/core';+import { EditStateEnum, type IRangeProtectionRule, type IWorksheetProtectionRule, UnitObject, ViewStateEnum } from '@univerjs/sheets';-const DEFAULT_RANGE_RULE: IRangeProtectionRule = {- name: '',+export const DEFAULT_RANGE_RULE: IRangeProtectionRule = {unitId: '',subUnitId: '',permissionId: '',- unitType: UnitObject.Unkonwn,+ unitType: UnitObject.SelectRange,id: '',ranges: [],+ viewState: ViewStateEnum.OthersCanView,+ editState: EditStateEnum.OnlyMe,};-export enum viewState {- othersCanView = 'othersCanView',- noOneElseCanView = 'noOneElseCanView',-}--export enum editState {- designedUserCanEdit = 'designedUserCanEdit',- onlyMe = 'onlyMe',-}--type IPermissionPanelBaseRule = IRangeProtectionRule | IWorksheetProtectionRule;--export type IPermissionPanelRule = IPermissionPanelBaseRule & { viewStatus?: viewState; editStatus?: editState; ranges: IRange[] };+export type IPermissionPanelRule = (IRangeProtectionRule | IWorksheetProtectionRule) & { ranges: IRange[]; id: string };export class SheetPermissionPanelModel {private _rule: IPermissionPanelRule = DEFAULT_RANGE_RULE;- private _rule$ = new BehaviorSubject(this._rule);- private _oldRule: Nullable<IPermissionPanelRule>;- private _rangeErrorMsg$ = new BehaviorSubject<string | undefined>(undefined);private _visible = false;@@ -59,40 +43,7 @@ export class SheetPermissionPanelModel {return this._visible;}- rangeErrorMsg$ = this._rangeErrorMsg$.asObservable();-- setRangeErrorMsg(msg: string | undefined) {- this._rangeErrorMsg$.next(msg);- }-- rule$ = this._rule$.asObservable();-- get rule() {- return this._rule;- }-- setRule(ruleObj: Partial<IPermissionPanelRule>) {- this._rule = { ...this._rule, ...ruleObj };- this._rule$.next(this._rule);- }-- resetRule() {- this._rule = DEFAULT_RANGE_RULE;- this._rule$.next(this._rule);- }-reset() {this.setVisible(false);- this.resetRule();- this.setRangeErrorMsg('');- this.setOldRule(null);- }-- get oldRule() {- return this._oldRule;- }-- setOldRule(ruleObj: Nullable<IPermissionPanelRule>) {- this._oldRule = ruleObj;}}diff --git a/packages/sheets-ui/src/services/permission/sheet-permission-user-list.service.ts b/packages/sheets-ui/src/services/permission/sheet-permission-user-list.service.tsindex 99cd406282..241376d312 100644--- a/packages/sheets-ui/src/services/permission/sheet-permission-user-list.service.ts+++ b/packages/sheets-ui/src/services/permission/sheet-permission-user-list.service.ts@@ -14,32 +14,23 @@* limitations under the License.*/-import { BehaviorSubject } from 'rxjs';import type { ICollaborator } from '@univerjs/protocol';+import { BehaviorSubject } from 'rxjs';export class SheetPermissionUserManagerService {private _userList: ICollaborator[] = [];private _oldCollaboratorList: ICollaborator[] = [];- private _selectUserList: ICollaborator[] = [];- private _allUserList: ICollaborator[] = [];+ private _selectUserList: ICollaborator[] = [];private _selectUserList$ = new BehaviorSubject<ICollaborator[]>(this._selectUserList);-selectUserList$ = this._selectUserList$.asObservable();get userList() {return this._userList;}- get allUserList() {- return this._allUserList;- }-- setAllUserList(userList: ICollaborator[]) {- this._allUserList = userList;- }-- setUserList(userList: ICollaborator[]) {+ // Set all editable users of this unit+ setCanEditUserList(userList: ICollaborator[]) {this._userList = userList;}@@ -48,7 +39,6 @@ export class SheetPermissionUserManagerService {this._oldCollaboratorList = [];this._selectUserList = [];this._selectUserList$.next([]);- this._allUserList = [];}get oldCollaboratorList() {@@ -63,6 +53,7 @@ export class SheetPermissionUserManagerService {return this._selectUserList;}+ // The results of the user dialog selection panel should be rendered in the permission panelsetSelectUserList(userList: ICollaborator[]) {this._selectUserList = userList;this._selectUserList$.next(userList);diff --git a/packages/sheets-ui/src/views/permission/footer/index.module.less b/packages/sheets-ui/src/views/permission/footer/index.module.lessdeleted file mode 100644index 225bb4ad4a..0000000000--- a/packages/sheets-ui/src/views/permission/footer/index.module.less+++ /dev/null@@ -1,19 +0,0 @@-.sheet-permission-panel-footer {- display: flex;- flex-direction: row-reverse;-- &-cancel {- margin-right: 12px;- }-}--.sheet-permission-panel-add-button {- width: 100%;- display: flex;- align-items: center;- justify-content: center;-- div {- margin-right: 4px;- }-}diff --git a/packages/sheets-ui/src/views/permission/footer/index.tsx b/packages/sheets-ui/src/views/permission/footer/index.tsxdeleted file mode 100644index 0530d99450..0000000000--- a/packages/sheets-ui/src/views/permission/footer/index.tsx+++ /dev/null@@ -1,25 +0,0 @@-/**- * Copyright 2023-present DreamNum Inc.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import React from 'react';-import { SheetPermissionPanelAddFooter } from './permission-list-footer';-import { SheetPermissionPanelDetailFooter } from './permission-detail-footer';--export const SheetPermissionPanelFooter = ({ showDetail }: { showDetail: boolean }) => {- return (- showDetail ? <SheetPermissionPanelDetailFooter /> : <SheetPermissionPanelAddFooter />- );-};diff --git a/packages/sheets-ui/src/views/permission/footer/permission-list-footer.tsx b/packages/sheets-ui/src/views/permission/footer/permission-list-footer.tsxdeleted file mode 100644index b7f6d5c4e3..0000000000--- a/packages/sheets-ui/src/views/permission/footer/permission-list-footer.tsx+++ /dev/null@@ -1,78 +0,0 @@-/**- * Copyright 2023-present DreamNum Inc.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import type { Workbook } from '@univerjs/core';-import { IPermissionService, IUniverInstanceService, LocaleService, UniverInstanceType, useDependency } from '@univerjs/core';-import { Button } from '@univerjs/design';-import { WorkbookCreateProtectPermission, WorksheetProtectionRuleModel } from '@univerjs/sheets';-import { ISidebarService, useObservable } from '@univerjs/ui';-import React from 'react';-import { UNIVER_SHEET_PERMISSION_PANEL, UNIVER_SHEET_PERMISSION_PANEL_FOOTER } from '../../../consts/permission';-import { SheetPermissionPanelModel } from '../../../services/permission/sheet-permission-panel.model';-import styles from './index.module.less';--export const SheetPermissionPanelAddFooter = () => {- const sidebarService = useDependency(ISidebarService);- const localeService = useDependency(LocaleService);-- const univerInstanceService = useDependency(IUniverInstanceService);- const permissionService = useDependency(IPermissionService);- const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;- const unitId = workbook.getUnitId();- const activeSheet$ = useObservable(workbook.activeSheet$);-- const hasSetProtectPermission = permissionService.getPermissionPoint(new WorkbookCreateProtectPermission(unitId).id)?.value ?? false;- const sheetPermissionPanelModel = useDependency(SheetPermissionPanelModel);- const worksheetProtectionRuleModel = useDependency(WorksheetProtectionRuleModel);-- const subUnitId = activeSheet$?.getSheetId();- if (!subUnitId) {- return null;- }-- const worksheetRule = worksheetProtectionRuleModel.getRule(unitId, subUnitId);-- if (!hasSetProtectPermission || worksheetRule) {- return null;- }- return (- <div>- <Button- className={styles.sheetPermissionPanelAddButton}- type="primary"- onClick={() => {- sheetPermissionPanelModel.resetRule();- const sidebarProps = {- header: { title: `${localeService.t('permission.panel.title')}` },- children: {- label: UNIVER_SHEET_PERMISSION_PANEL,- showDetail: true,- },- width: 330,- footer: {- label: UNIVER_SHEET_PERMISSION_PANEL_FOOTER,- showDetail: true,- },- };- sidebarService.open(sidebarProps);- }}- >- <div>+ </div>- {localeService.t('permission.button.addNewPermission')}- </Button>- </div>- );-};diff --git a/packages/sheets-ui/src/views/permission/index.ts b/packages/sheets-ui/src/views/permission/index.tsindex ef547dcdab..5670677e59 100644--- a/packages/sheets-ui/src/views/permission/index.ts+++ b/packages/sheets-ui/src/views/permission/index.ts@@ -14,8 +14,6 @@* limitations under the License.*/-export { SheetPermissionPanelFooter } from './footer';-export { SheetPermissionPanelAddFooter } from './footer/permission-list-footer';export { SheetPermissionPanel } from './panel';export { SheetPermissionPanelList } from './panel-list';export { SheetPermissionDialog } from './permission-dialog';diff --git a/packages/sheets-ui/src/views/permission/footer/permission-detail-footer.tsx b/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailFooterPart.tsxsimilarity index 71%rename from packages/sheets-ui/src/views/permission/footer/permission-detail-footer.tsxrename to packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailFooterPart.tsxindex 9ed6ad243e..83d02a2809 100644--- a/packages/sheets-ui/src/views/permission/footer/permission-detail-footer.tsx+++ b/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailFooterPart.tsx@@ -14,58 +14,97 @@* limitations under the License.*/-import { IAuthzIoService, ICommandService, LocaleService, useDependency } from '@univerjs/core';+import type { IRange, Workbook } from '@univerjs/core';+import type { IRangeProtectionRule } from '@univerjs/sheets';+import type { IPermissionPanelRule } from '../../../services/permission/sheet-permission-panel.model';+import { IAuthzIoService, ICommandService, IUniverInstanceService, LocaleService, UniverInstanceType, useDependency } from '@univerjs/core';import { Button } from '@univerjs/design';-import { ObjectScope, UnitAction, UnitObject, UnitRole } from '@univerjs/protocol';-import { AddRangeProtectionCommand } from '@univerjs/sheets';-import { ISidebarService, useObservable } from '@univerjs/ui';+import { ObjectScope, UnitAction, UnitRole } from '@univerjs/protocol';+import { AddRangeProtectionCommand, AddWorksheetProtectionCommand, EditStateEnum, SetProtectionCommand, UnitObject, ViewStateEnum } from '@univerjs/sheets';+import { ISidebarService } from '@univerjs/ui';import React from 'react';-import { SetProtectionCommand } from '../../../commands/commands/range-protection.command';-import { AddWorksheetProtectionCommand } from '../../../commands/commands/worksheet-protection.command';import { getUserListEqual } from '../../../common/utils';-import { UNIVER_SHEET_PERMISSION_PANEL, UNIVER_SHEET_PERMISSION_PANEL_FOOTER } from '../../../consts/permission';-import { editState, SheetPermissionPanelModel, viewState } from '../../../services/permission/sheet-permission-panel.model';+import { UNIVER_SHEET_PERMISSION_PANEL } from '../../../consts/permission';+import { SheetPermissionPanelModel } from '../../../services/permission/sheet-permission-panel.model';import { SheetPermissionUserManagerService } from '../../../services/permission/sheet-permission-user-list.service';+import { checkRangesIsWholeSheet } from '../util';import styles from './index.module.less';-export const SheetPermissionPanelDetailFooter = () => {+interface IPermissionDetailFooterPartProps {+ permissionId: string;+ id: string;+ ranges: IRange[];+ rangesErrMsg?: string;+ desc?: string;+ editState: EditStateEnum;+ viewState: ViewStateEnum;+ oldRule?: IPermissionPanelRule;+}++export const PermissionDetailFooterPart = (props: IPermissionDetailFooterPartProps) => {+ const { viewState, editState, permissionId, ranges, rangesErrMsg, desc, oldRule, id } = props;const sheetPermissionPanelModel = useDependency(SheetPermissionPanelModel);- const activeRule = useObservable(sheetPermissionPanelModel.rule$, sheetPermissionPanelModel.rule);const sidebarService = useDependency(ISidebarService);const authzIoService = useDependency(IAuthzIoService);const localeService = useDependency(LocaleService);const commandService = useDependency(ICommandService);const sheetPermissionUserManagerService = useDependency(SheetPermissionUserManagerService);- const rangeErrMsg = useObservable(sheetPermissionPanelModel.rangeErrorMsg$);+ const univerInstanceService = useDependency(IUniverInstanceService);++ const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ const worksheet = workbook?.getActiveSheet();+ if (!workbook || !worksheet) {+ return null;+ }+ const unitId = workbook.getUnitId();+ const subUnitId = worksheet.getSheetId();return (<div className={styles.sheetPermissionPanelFooter}><Buttontype="primary"onClick={async () => {- if (rangeErrMsg) return;+ if (rangesErrMsg) return;++ const activeRule: IPermissionPanelRule = {+ unitId,+ subUnitId,+ permissionId,+ id,+ viewState,+ editState,+ unitType: UnitObject.SelectRange,+ ranges,+ description: desc,+ };++ const isSelectWholeSheet = checkRangesIsWholeSheet(ranges, worksheet);+ if (isSelectWholeSheet) {+ activeRule.unitType = UnitObject.Worksheet;+ activeRule.ranges = [];+ }+let collaborators = sheetPermissionUserManagerService.selectUserList;- if (activeRule.editStatus === editState.onlyMe) {+ if (activeRule.editState === EditStateEnum.OnlyMe) {collaborators = [];sheetPermissionUserManagerService.setSelectUserList([]);}const scopeObj = {- read: activeRule.viewStatus === viewState.othersCanView ? ObjectScope.AllCollaborator : ObjectScope.SomeCollaborator,- edit: activeRule.editStatus === editState.designedUserCanEdit ? ObjectScope.SomeCollaborator : ObjectScope.OneSelf,+ read: activeRule.viewState === ViewStateEnum.OthersCanView ? ObjectScope.AllCollaborator : ObjectScope.SomeCollaborator,+ edit: activeRule.editState === EditStateEnum.DesignedUserCanEdit ? ObjectScope.SomeCollaborator : ObjectScope.OneSelf,};- if (activeRule.editStatus === editState.designedUserCanEdit && collaborators.length === 0) {+ if (activeRule.editState === EditStateEnum.DesignedUserCanEdit && collaborators.length === 0) {collaborators = [];scopeObj.edit = ObjectScope.OneSelf;}// Editing existing permission rulesif (activeRule.permissionId) {- const oldRule = sheetPermissionPanelModel.oldRule;// Collaborators only need to consider people with editing permissionsconst isSameCollaborators = getUserListEqual(collaborators.filter((user) => user.role === UnitRole.Editor), sheetPermissionUserManagerService.oldCollaboratorList.filter((user) => user.role === UnitRole.Editor));- const isSameReadStatus = oldRule?.viewStatus === activeRule.viewStatus;- const isSameEditStatus = oldRule?.editStatus === activeRule.editStatus;- const ruleConfigIsOrigin = activeRule.unitType === oldRule?.unitType && activeRule.name === oldRule.name && activeRule.description === oldRule.description && activeRule.ranges === oldRule.ranges;+ const isSameReadStatus = oldRule?.viewState === activeRule.viewState;+ const isSameEditStatus = oldRule?.editState === activeRule.editState;+ const ruleConfigIsOrigin = activeRule.unitType === oldRule?.unitType && activeRule.description === oldRule.description && activeRule.ranges === (oldRule as IRangeProtectionRule).ranges;const collaboratorsIsChange = !isSameCollaborators || !isSameReadStatus || !isSameEditStatus;if (ruleConfigIsOrigin && collaboratorsIsChange) {@@ -93,7 +132,7 @@ export const SheetPermissionPanelDetailFooter = () => {worksheetObject: {collaborators,unitID: activeRule.unitId,- name: activeRule.name,+ name: '',strategies: [{ role: UnitRole.Editor, action: UnitAction.Edit }, { role: UnitRole.Reader, action: UnitAction.View }],scope: scopeObj,},@@ -104,7 +143,7 @@ export const SheetPermissionPanelDetailFooter = () => {selectRangeObject: {collaborators,unitID: activeRule.unitId,- name: activeRule.name,+ name: '',scope: scopeObj,},objectType: UnitObject.SelectRange,@@ -117,6 +156,7 @@ export const SheetPermissionPanelDetailFooter = () => {...activeRule,permissionId: newPermissionId,},+ oldRule,});}} else {@@ -127,7 +167,7 @@ export const SheetPermissionPanelDetailFooter = () => {worksheetObject: {collaborators,unitID: activeRule.unitId,- name: activeRule.name,+ name: '',strategies: [{ role: UnitRole.Editor, action: UnitAction.Edit }, { role: UnitRole.Reader, action: UnitAction.View }],scope: scopeObj,},@@ -144,7 +184,7 @@ export const SheetPermissionPanelDetailFooter = () => {selectRangeObject: {collaborators,unitID: activeRule.unitId,- name: activeRule.name,+ name: '',scope: scopeObj,},objectType: UnitObject.SelectRange,@@ -155,8 +195,6 @@ export const SheetPermissionPanelDetailFooter = () => {});}}- sheetPermissionPanelModel.resetRule();- sheetPermissionUserManagerService.reset();const sidebarProps = {header: { title: `${localeService.t('permission.panel.title')}` },children: {@@ -164,10 +202,6 @@ export const SheetPermissionPanelDetailFooter = () => {showDetail: false,},width: 330,- footer: {- label: UNIVER_SHEET_PERMISSION_PANEL_FOOTER,- showDetail: false,- },};sidebarService.open(sidebarProps);}}diff --git a/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailMainPart.tsx b/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailMainPart.tsxnew file mode 100644index 0000000000..0c223cfc44--- /dev/null+++ b/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailMainPart.tsx@@ -0,0 +1,102 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IRange, Workbook } from '@univerjs/core';+import { Injector, isValidRange, IUniverInstanceService, LocaleService, UniverInstanceType, useDependency } from '@univerjs/core';+import { FormLayout, Input } from '@univerjs/design';+import { deserializeRangeWithSheet, serializeRange } from '@univerjs/engine-formula';+import { setEndForRange } from '@univerjs/sheets';+import { ComponentManager } from '@univerjs/ui';+import React, { useMemo } from 'react';+import { RANGE_SELECTOR_COMPONENT_KEY } from '../../../common/keys';+import { checkRangeValid } from '../util';+import styles from './index.module.less';++interface IPermissionDetailMainPartProps {+ permissionId: string;+ ranges: IRange[];+ onRangesChange: (ranges: IRange[], err?: string) => void;+ isFocusRangeSelector: boolean;+ rangesErrMsg?: string;+ desc?: string;+ onDescChange: (desc: string) => void;+ rangeSelectorRef: React.MutableRefObject<any>;+}++export const PermissionDetailMainPart = (props: IPermissionDetailMainPartProps) => {+ const { ranges, onRangesChange, rangeSelectorRef, desc, onDescChange, rangesErrMsg, isFocusRangeSelector, permissionId } = props;+ const componentManager = useDependency(ComponentManager);+ const RangeSelector = useMemo(() => componentManager.get(RANGE_SELECTOR_COMPONENT_KEY), []);+ const univerInstanceService = useDependency(IUniverInstanceService);+ const localeService = useDependency(LocaleService);+ const injector = useDependency(Injector);++ const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ const worksheet = workbook?.getActiveSheet();+ if (!workbook || !worksheet) {+ return null;+ }+ const unitId = workbook.getUnitId();+ const subUnitId = worksheet.getSheetId();++ const handleRangeChange = (rangeText: string) => {+ const newRange = rangeText.split(',').map(deserializeRangeWithSheet).map((item) => item.range);+ if (newRange.some((i) => !isValidRange(i) || i.endColumn < i.startColumn || i.endRow < i.startRow)) {+ return;+ }++ const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ const worksheet = workbook?.getActiveSheet();+ if (!workbook || !worksheet) {+ return;+ }+ const unitId = workbook.getUnitId();+ const subUnitId = worksheet.getSheetId();+ const transformedRange = newRange.map((range) => {+ const rowCount = worksheet.getRowCount();+ const colCount = worksheet.getColumnCount();+ setEndForRange(range, rowCount, colCount);+ return range;+ });+ const rangeErrorString = checkRangeValid(injector, transformedRange, permissionId, unitId, subUnitId);+ onRangesChange(transformedRange, rangeErrorString);+ };++ return (+ <>+ <FormLayout className={styles.sheetPermissionPanelTitle} label={localeService.t('permission.panel.protectedRange')}>+ {RangeSelector && (+ <RangeSelector+ unitId={unitId}+ errorText={rangesErrMsg}+ subUnitId={subUnitId}+ initValue={ranges?.map((i) => serializeRange(i)).join(',')}+ onChange={handleRangeChange}+ isFocus={isFocusRangeSelector}+ actions={rangeSelectorRef.current}+ />+ )}+ </FormLayout>+ <FormLayout className={styles.sheetPermissionPanelTitle} label={localeService.t('permission.panel.permissionDirection')}>+ <Input+ value={desc}+ onChange={(v) => onDescChange(v)}+ placeholder={localeService.t('permission.panel.permissionDirectionPlaceholder')}+ />+ </FormLayout>+ </>+ );+};diff --git a/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailPanel.tsx b/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailPanel.tsxnew file mode 100644index 0000000000..57752048f3--- /dev/null+++ b/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailPanel.tsx@@ -0,0 +1,111 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IRange, Workbook } from '@univerjs/core';+import type { IPermissionPanelRule } from '../../../services/permission/sheet-permission-panel.model';+import { Injector, IUniverInstanceService, UniverInstanceType, useDependency } from '@univerjs/core';+import { EditStateEnum, ViewStateEnum } from '@univerjs/sheets';+import { ComponentContainer, ISidebarService, useComponentsOfPart } from '@univerjs/ui';+import React, { useEffect, useRef, useState } from 'react';+import { UNIVER_SHEET_PERMISSION_USER_PART } from '../../../consts/permission';+import { checkRangeValid, generateDefaultRule, generateRuleByUnitType } from '../util';+import styles from './index.module.less';+import { PermissionDetailFooterPart } from './PermissionDetailFooterPart';+import { PermissionDetailMainPart } from './PermissionDetailMainPart';++interface ISheetPermissionPanelDetailProps {+ fromSheetBar: boolean;+ rule?: IPermissionPanelRule;+ oldRule?: IPermissionPanelRule;+}++export const SheetPermissionPanelDetail = (props: ISheetPermissionPanelDetailProps) => {+ const { fromSheetBar, rule, oldRule } = props;+ const injector = useDependency(Injector);+ const activeRule: IPermissionPanelRule = rule ? generateRuleByUnitType(injector, rule) : generateDefaultRule(injector, fromSheetBar);++ const [ranges, setRanges] = useState<IRange[]>(activeRule.ranges);+ const [rangesErrMsg, setRangesErrMsg] = useState<string | undefined>(() => {+ return checkRangeValid(injector, activeRule.ranges, activeRule.permissionId, activeRule.unitId, activeRule.subUnitId);+ });+ const [desc, setDesc] = useState<string | undefined>(activeRule.description);+ const [editState, setEditState] = useState<EditStateEnum>(activeRule.editState ?? EditStateEnum.OnlyMe);+ const [viewState, setViewState] = useState<ViewStateEnum>(activeRule.viewState ?? ViewStateEnum.OthersCanView);+ const rangeSelectorActionsRef = useRef<any>({});+ const [isFocusRangeSelector, isFocusRangeSelectorSet] = useState(false);++ const handlePanelClick = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {+ const handleOutClick = rangeSelectorActionsRef.current?.handleOutClick;+ handleOutClick && handleOutClick(e, isFocusRangeSelectorSet);+ };++ const PermissionDetailUserPart = useComponentsOfPart(UNIVER_SHEET_PERMISSION_USER_PART);++ useEffect(() => {+ const univerInstanceService = injector.get(IUniverInstanceService);+ const sidebarService = injector.get(ISidebarService);+ const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ if (!workbook) return;+ const subUnitId = workbook.getActiveSheet().getSheetId();+ const activeSheetSubscribe = workbook.activeSheet$.subscribe((sheet) => {+ if (sheet?.getSheetId() !== subUnitId) {+ sidebarService.close();+ }+ });+ return () => {+ activeSheetSubscribe.unsubscribe();+ };+ }, []);++ return (+ <div className={styles.permissionPanelDetailWrapper} onClick={handlePanelClick}>+ <PermissionDetailMainPart+ permissionId={activeRule.permissionId}+ ranges={ranges}+ onRangesChange={(v: IRange[], err?: string) => {+ setRanges(v);+ setRangesErrMsg(err);+ }}+ isFocusRangeSelector={isFocusRangeSelector}+ rangesErrMsg={rangesErrMsg}+ desc={desc}+ onDescChange={(v) => setDesc(v)}+ rangeSelectorRef={rangeSelectorActionsRef}+ />+ <ComponentContainer+ key="user-part"+ components={PermissionDetailUserPart}+ sharedProps={{+ editState,+ onEditStateChange: (v: EditStateEnum) => setEditState(v),+ viewState,+ onViewStateChange: (v: ViewStateEnum) => setViewState(v),+ permissionId: activeRule.permissionId,+ }}+ />+ <PermissionDetailFooterPart+ permissionId={activeRule.permissionId}+ id={activeRule.id}+ ranges={ranges}+ rangesErrMsg={rangesErrMsg}+ desc={desc}+ viewState={viewState}+ editState={editState}+ oldRule={oldRule}+ />+ </div>+ );+};diff --git a/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailUserPart.tsx b/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailUserPart.tsxnew file mode 100644index 0000000000..54e7dc056b--- /dev/null+++ b/packages/sheets-ui/src/views/permission/panel-detail/PermissionDetailUserPart.tsx@@ -0,0 +1,169 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { Workbook } from '@univerjs/core';+import type { ICollaborator } from '@univerjs/protocol';+import { IAuthzIoService, IUniverInstanceService, LocaleService, UniverInstanceType, useDependency, useObservable, UserManagerService } from '@univerjs/core';+import { Avatar, FormLayout, Radio, RadioGroup, Select } from '@univerjs/design';+import { UnitRole } from '@univerjs/protocol';+import { EditStateEnum, ViewStateEnum } from '@univerjs/sheets';+import { IDialogService } from '@univerjs/ui';+import React, { useEffect } from 'react';+import { UNIVER_SHEET_PERMISSION_USER_DIALOG, UNIVER_SHEET_PERMISSION_USER_DIALOG_ID } from '../../../consts/permission';+import { SheetPermissionUserManagerService } from '../../../services/permission/sheet-permission-user-list.service';+import { UserEmptyBase64 } from '../user-dialog/constant';+import styles from './index.module.less';++interface IPermissionDetailUserPartProps {+ editState: EditStateEnum;+ onEditStateChange: (v: EditStateEnum) => void;+ viewState: ViewStateEnum;+ onViewStateChange: (v: ViewStateEnum) => void;+ permissionId: string;+}++export const PermissionDetailUserPart = (props: IPermissionDetailUserPartProps) => {+ const { editState, onEditStateChange, viewState, onViewStateChange, permissionId } = props;+ const localeService = useDependency(LocaleService);+ const dialogService = useDependency(IDialogService);+ const authzIoService = useDependency(IAuthzIoService);+ const sheetPermissionUserManagerService = useDependency(SheetPermissionUserManagerService);+ const userManagerService = useDependency(UserManagerService);+ const univerInstanceService = useDependency(IUniverInstanceService);+ const selectUserList = useObservable(sheetPermissionUserManagerService.selectUserList$, sheetPermissionUserManagerService.selectUserList);++ const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ const worksheet = workbook?.getActiveSheet();+ if (!workbook || !worksheet) {+ return null;+ }+ const unitId = workbook.getUnitId();++ const handleAddPerson = async () => {+ const userList = await authzIoService.listCollaborators({+ objectID: unitId,+ unitID: unitId,+ });++ const currentUser = userManagerService.getCurrentUser();+ sheetPermissionUserManagerService.setCanEditUserList(userList.filter((user) => user.subject?.userID !== currentUser.userID));+ dialogService.open({+ id: UNIVER_SHEET_PERMISSION_USER_DIALOG_ID,+ title: { title: '' },+ children: { label: UNIVER_SHEET_PERMISSION_USER_DIALOG },+ width: 280,+ destroyOnClose: true,+ onClose: () => dialogService.close(UNIVER_SHEET_PERMISSION_USER_DIALOG_ID),+ className: 'sheet-permission-user-dialog',+ });+ };++ useEffect(() => {+ const getSelectUserList = async () => {+ const collaborators = await authzIoService.listCollaborators({+ objectID: permissionId!,+ unitID: unitId,+ });+ const selectUserList: ICollaborator[] = collaborators.filter((user) => {+ return user.role === UnitRole.Editor;+ });+ if (selectUserList.length > 0) {+ onEditStateChange(EditStateEnum.DesignedUserCanEdit);+ }+ sheetPermissionUserManagerService.setSelectUserList(selectUserList);+ sheetPermissionUserManagerService.setOldCollaboratorList(selectUserList);+ };+ if (permissionId) {+ getSelectUserList();+ } else {+ sheetPermissionUserManagerService.setSelectUserList([]);+ sheetPermissionUserManagerService.setOldCollaboratorList([]);+ }+ }, []);++ return (+ <>+ <FormLayout className={styles.sheetPermissionPanelTitle} label={localeService.t('permission.panel.editPermission')}>+ <RadioGroup+ value={editState}+ onChange={(v) => onEditStateChange(v as EditStateEnum)}+ className={styles.radioGroupVertical}+ >+ <Radio value={EditStateEnum.OnlyMe}>+ <span className={styles.text}>{localeService.t('permission.panel.onlyICanEdit')}</span>+ </Radio>+ <Radio value={EditStateEnum.DesignedUserCanEdit}>+ <span className={styles.text}>{localeService.t('permission.panel.designedUserCanEdit')}</span>+ </Radio>+ </RadioGroup>+ </FormLayout>+ {editState === EditStateEnum.DesignedUserCanEdit && (+ <div className={styles.sheetPermissionDesignPersonPanel}>+ <div className={styles.sheetPermissionDesignPersonPanelHeader}>+ <span>{localeService.t('permission.panel.designedPerson')}</span>+ <span className={styles.sheetPermissionDesignPersonPanelHeaderAdd} onClick={handleAddPerson}>{localeService.t('permission.panel.addPerson')}</span>+ </div>+ <div className={styles.sheetPermissionDesignPersonPanelSplit}></div>+ <div className={styles.sheetPermissionDesignPersonPanelContent}>+ {selectUserList?.length > 0+ ? selectUserList.map((item) => {+ return (+ <div key={item.subject?.userID} className={styles.sheetPermissionDesignPersonPanelContentItem}>+ <Avatar size={24} src={item.subject?.avatar} />+ <span className={styles.sheetPermissionDesignPersonPanelContentItemName}>{item.subject?.name}</span>+ <Select+ className={styles.sheetPermissionDesignPersonPanelContentItemSelect}+ value="edit"+ onChange={(v) => {+ if (v === 'delete') {+ sheetPermissionUserManagerService.setSelectUserList(selectUserList.filter((i) => i.subject?.userID !== item.subject?.userID));+ }+ }}+ options={[+ { label: `${localeService.t('permission.panel.canEdit')}`, value: 'edit' },+ { label: `${localeService.t('permission.panel.delete')}`, value: 'delete' },+ ]}+ />+ </div>+ );+ })+ : (+ <div className={styles.sheetPermissionUserListEmpty}>+ <img width={240} height={120} src={UserEmptyBase64} alt="" />+ <p className={styles.sheetPermissionUserListEmptyText}>{localeService.t('permission.dialog.userEmpty')}</p>+ </div>+ )}+ </div>++ </div>+ )}+ <FormLayout className={styles.sheetPermissionPanelTitle} label={localeService.t('permission.panel.viewPermission')}>+ <RadioGroup+ value={viewState}+ onChange={(v) => onViewStateChange(v as ViewStateEnum)}+ className={styles.radioGroupVertical}+ >+ <Radio value={ViewStateEnum.OthersCanView}>+ <span className={styles.text}>{localeService.t('permission.panel.othersCanView')}</span>+ </Radio>+ <Radio value={ViewStateEnum.NoOneElseCanView}>+ <span className={styles.text}>{localeService.t('permission.panel.noOneElseCanView')}</span>+ </Radio>+ </RadioGroup>+ </FormLayout>+ </>+ );+};diff --git a/packages/sheets-ui/src/views/permission/panel-detail/index.module.less b/packages/sheets-ui/src/views/permission/panel-detail/index.module.lessindex e9c547e5a1..76d54ef9c4 100644--- a/packages/sheets-ui/src/views/permission/panel-detail/index.module.less+++ b/packages/sheets-ui/src/views/permission/panel-detail/index.module.less@@ -1,6 +1,8 @@.permission-panel-detail-wrapper {margin-top: 16px;- height: 100%;+ height: calc(100% - 16px);+ display: flex;+ flex-direction: column;}.radio-group-vertical {@@ -10,7 +12,7 @@}.sheet-permission-design-person-panel {- height: 300px;+ height: 270px;border: 1px solid rgb(var(--grey-200));border-radius: var(--border-radius-lg);padding: var(--padding-base);@@ -105,6 +107,19 @@font-weight: 500;}+.sheet-permission-panel-footer {+ display: flex;+ flex-direction: row-reverse;+ padding: 20px 0;+ margin-top: auto;++ button {+ &:first-child {+ margin-left: 8px;+ }+ }+}+.permission-range-selector {font-weight: 400;}diff --git a/packages/sheets-ui/src/views/permission/panel-detail/index.tsx b/packages/sheets-ui/src/views/permission/panel-detail/index.tsxdeleted file mode 100644index 42b1fee57d..0000000000--- a/packages/sheets-ui/src/views/permission/panel-detail/index.tsx+++ /dev/null@@ -1,454 +0,0 @@-/**- * Copyright 2023-present DreamNum Inc.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import type { IRange, Workbook } from '@univerjs/core';-import type { ICollaborator, IUser } from '@univerjs/protocol';-import { IAuthzIoService, isValidRange, IUniverInstanceService, LocaleService, RANGE_TYPE, Rectangle, UniverInstanceType, useDependency, UserManagerService } from '@univerjs/core';-import { Avatar, FormLayout, Input, Radio, RadioGroup, Select } from '@univerjs/design';-import { deserializeRangeWithSheet, serializeRange } from '@univerjs/engine-formula';--import { ObjectScope, UnitAction, UnitObject, UnitRole } from '@univerjs/protocol';-import { RangeProtectionRuleModel, setEndForRange, SheetsSelectionsService, WorksheetProtectionRuleModel } from '@univerjs/sheets';-import { ComponentManager, IDialogService, ISidebarService, useObservable } from '@univerjs/ui';-import React, { useEffect, useMemo, useRef, useState } from 'react';-import { RANGE_SELECTOR_COMPONENT_KEY } from '../../../common/keys';-import { UNIVER_SHEET_PERMISSION_USER_DIALOG, UNIVER_SHEET_PERMISSION_USER_DIALOG_ID } from '../../../consts/permission';-import { editState, SheetPermissionPanelModel, viewState } from '../../../services/permission/sheet-permission-panel.model';-import { SheetPermissionUserManagerService } from '../../../services/permission/sheet-permission-user-list.service';-import Spin from '../spin';-import { UserEmptyBase64 } from '../user-dialog/constant';-import styles from './index.module.less';--export const SheetPermissionPanelDetail = ({ fromSheetBar }: { fromSheetBar: boolean }) => {- const localeService = useDependency(LocaleService);- const dialogService = useDependency(IDialogService);- const univerInstanceService = useDependency(IUniverInstanceService);- const selectionManagerService = useDependency(SheetsSelectionsService);- const sheetPermissionPanelModel = useDependency(SheetPermissionPanelModel);- const activeRule = useObservable(sheetPermissionPanelModel.rule$, sheetPermissionPanelModel.rule);- const userManagerService = useDependency(UserManagerService);- const sheetPermissionUserManagerService = useDependency(SheetPermissionUserManagerService);- const authzIoService = useDependency(IAuthzIoService);- const sidebarService = useDependency(ISidebarService);- const rangeProtectionRuleModel = useDependency(RangeProtectionRuleModel);- const worksheetRuleModel = useDependency(WorksheetProtectionRuleModel);- const componentManager = useDependency(ComponentManager);- const RangeSelector = useMemo(() => componentManager.get(RANGE_SELECTOR_COMPONENT_KEY), []);-- const rangeErrorMsg = useObservable(sheetPermissionPanelModel.rangeErrorMsg$);-- const rangeSelectorActionsRef = useRef<any>({});- const [isFocusRangeSelector, isFocusRangeSelectorSet] = useState(false);- const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;- const worksheet = workbook.getActiveSheet()!;- const unitId = workbook.getUnitId();- const subUnitId = worksheet.getSheetId();-- const selectUserList = useObservable(sheetPermissionUserManagerService.selectUserList$, sheetPermissionUserManagerService.selectUserList);-- // The status of these two collaborators is updated directly by calling the interface, and will not be written to the snapshot or undoredo, so they are pulled in real time when they need to be displayed.- const [editorGroupValue, setEditorGroupValue] = React.useState<editState>(selectUserList.length ? editState.designedUserCanEdit : editState.onlyMe);- const [viewGroupValue, setViewGroupValue] = React.useState(viewState.othersCanView);- const [loading, setLoading] = useState(!!activeRule?.permissionId);-- const [rangeInitialization, setRangeInitialization] = useState(false);-- const handleAddPerson = async () => {- const userList = await authzIoService.listCollaborators({- objectID: unitId,- unitID: unitId,- });- userList.forEach((user) => {- if (user?.subject) {- userManagerService.addUser(user.subject as IUser);- }- });-- const currentUser = userManagerService.getCurrentUser();- sheetPermissionUserManagerService.setUserList(userList.filter((user) => user.subject?.userID !== currentUser.userID));-- dialogService.open({- id: UNIVER_SHEET_PERMISSION_USER_DIALOG_ID,- title: { title: '' },- children: { label: UNIVER_SHEET_PERMISSION_USER_DIALOG },- width: 280,- destroyOnClose: true,- onClose: () => dialogService.close(UNIVER_SHEET_PERMISSION_USER_DIALOG_ID),- className: 'sheet-permission-user-dialog',- });- };-- const checkRangeValid = (permissionRanges: IRange[]) => {- let rangeErrorString = '';- if (permissionRanges.length === 0) {- rangeErrorString = localeService.t('permission.panel.emptyRangeError');- } else if (permissionRanges.length > 1) {- let hasLap = false;- for (let i = 0; i < permissionRanges.length; i++) {- for (let j = i + 1; j < permissionRanges.length; j++) {- if (Rectangle.intersects(permissionRanges[i], permissionRanges[j])) {- hasLap = true;- break;- }- }- if (hasLap) {- break;- }- }- if (hasLap) {- rangeErrorString = localeService.t('permission.panel.rangeOverlapError');- }- }- if (!rangeErrorString) {- const worksheetRule = worksheetRuleModel.getRule(unitId, subUnitId);- if (worksheetRule && !activeRule?.permissionId) {- rangeErrorString = localeService.t('permission.panel.rangeOverlapOverPermissionError');- return rangeErrorString;- }- const lapRule = rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId).filter((rule) => {- return rule.permissionId !== activeRule?.permissionId;- }).find((rule) => {- return rule.ranges.some((ruleRange) => {- return permissionRanges.some((r) => Rectangle.intersects(ruleRange, r));- });- });- const lapRange = lapRule?.ranges.find((range) => {- return permissionRanges.some((r) => Rectangle.intersects(range, r));- });- if (lapRange) {- rangeErrorString = localeService.t('permission.panel.rangeOverlapOverPermissionError');- }- }- return rangeErrorString === '' ? undefined : rangeErrorString;- };-- useEffect(() => {- const isEdit = activeRule?.permissionId;- setRangeInitialization(true);- if (isEdit) {- if (activeRule.unitType === UnitObject.Worksheet) {- sheetPermissionPanelModel.setRule({- ranges: [{- startRow: 0,- startColumn: 0,- endRow: worksheet.getRowCount() - 1,- endColumn: worksheet.getColumnCount() - 1,- rangeType: RANGE_TYPE.ALL,- }],- });- }- return;- }- if (fromSheetBar) {- selectionManagerService.clearCurrentSelections();- selectionManagerService.addSelections([- {- primary: null,- style: null,- range: {- startRow: 0,- startColumn: 0,- endRow: worksheet.getRowCount() - 1,- endColumn: worksheet.getColumnCount() - 1,- rangeType: RANGE_TYPE.ALL,- },- },- ]);- }- const ranges = selectionManagerService.getCurrentSelections()?.map((s) => s.range) ?? [];- const rangeErrorString = checkRangeValid(ranges);- sheetPermissionPanelModel.setRangeErrorMsg(rangeErrorString);- const rangeStr = ranges?.length- ? ranges.map((range) => {- const v = serializeRange(range);- return v === 'NaN' ? '' : v;- }).filter((r) => !!r).join(',')- : '';- const sheetName = worksheet.getName();- sheetPermissionPanelModel.setRule({- ranges,- name: fromSheetBar ? `${sheetName}` : `${sheetName}(${rangeStr})`,- unitId,- subUnitId,- unitType: fromSheetBar ? UnitObject.Worksheet : UnitObject.SelectRange,-- });- }, [activeRule?.permissionId, fromSheetBar, selectionManagerService, sheetPermissionPanelModel, subUnitId, unitId, worksheet]);-- useEffect(() => {- const getSelectUserList = async () => {- const permissionId = activeRule?.permissionId;-- const collaborators = await authzIoService.listCollaborators({- objectID: permissionId!,- unitID: unitId,- });- const selectUserList: ICollaborator[] = collaborators.filter((user) => {- return user.role === UnitRole.Editor;- });- sheetPermissionUserManagerService.setSelectUserList(selectUserList);- sheetPermissionUserManagerService.setOldCollaboratorList(selectUserList);- };- if (activeRule?.permissionId) {- getSelectUserList();- } else {- sheetPermissionUserManagerService.setSelectUserList([]);- sheetPermissionUserManagerService.setOldCollaboratorList([]);- }- }, [activeRule?.permissionId]);-- useEffect(() => {- if (!activeRule.permissionId) {- sheetPermissionPanelModel.setRule({- viewStatus: viewState.othersCanView,- });- return;- }- const getCollaboratorInit = async () => {- try {- const res = await authzIoService.list({- unitID: unitId,- objectIDs: [activeRule?.permissionId],- actions: [UnitAction.View, UnitAction.Edit],- });- if (!res.length) {- setViewGroupValue(viewState.othersCanView);- setEditorGroupValue(editState.onlyMe);- sheetPermissionPanelModel.setRule({- viewStatus: viewState.othersCanView,- editStatus: editState.onlyMe,- });- } else {- const isAllCanView = res[0].scope?.read === ObjectScope.AllCollaborator;- const isSomeCanEdit = res[0].scope?.edit === ObjectScope.SomeCollaborator;- const viewValue = isAllCanView ? viewState.othersCanView : viewState.noOneElseCanView;- const editValue = isSomeCanEdit ? editState.designedUserCanEdit : editState.onlyMe;- setViewGroupValue(viewValue);- setEditorGroupValue(editValue);- sheetPermissionPanelModel.setRule({- viewStatus: viewValue,- editStatus: editValue,- });- }- } catch (error) {- console.error(error);- } finally {- setTimeout(() => {- setLoading(false);- }, 100);- }- };- getCollaboratorInit();- }, [activeRule.permissionId]);-- useEffect(() => {- const getListCollaborators = async () => {- const userList = await authzIoService.listCollaborators({- objectID: unitId,- unitID: unitId,- });- userList.forEach((user) => {- if (user?.subject) {- userManagerService.addUser(user.subject as IUser);- }- });-- sheetPermissionUserManagerService.setUserList(userList.filter((user) => user.role === UnitRole.Editor));- sheetPermissionUserManagerService.setAllUserList(userList.filter((user) => user.role === UnitRole.Editor || user.role === UnitRole.Reader));- };- getListCollaborators();- }, []);-- useEffect(() => {- const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);- if (!workbook) return;- const activeSheetSubscribe = workbook.activeSheet$.subscribe((sheet) => {- if (sheet?.getSheetId() !== subUnitId) {- sidebarService.close();- }- });- return () => {- activeSheetSubscribe.unsubscribe();- };- }, [sidebarService, subUnitId, univerInstanceService]);-- const handleRangeChange = (rangeText: string) => {- const newRange = rangeText.split(',').map(deserializeRangeWithSheet).map((item) => item.range);- if (newRange.some((i) => !isValidRange(i) || i.endColumn < i.startColumn || i.endRow < i.startRow)) {- return;- }-- const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;- const worksheet = workbook.getActiveSheet()!;- const unitId = workbook.getUnitId();- const subUnitId = worksheet.getSheetId();- const transformedRange = newRange.map((range) => {- const rowCount = worksheet.getRowCount();- const colCount = worksheet.getColumnCount();- setEndForRange(range, rowCount, colCount);- return range;- });- const rangeErrorString = checkRangeValid(transformedRange);- sheetPermissionPanelModel.setRangeErrorMsg(rangeErrorString);- if (rangeErrorString) return;-- const sheetName = worksheet.getName();- const rangeStr = transformedRange.map((range) => {- const v = serializeRange(range);- return v === 'NaN' ? '' : v;- }).filter((r) => !!r).join(',');-- const rule = {- ranges: transformedRange,- unitId,- subUnitId,- unitType: UnitObject.SelectRange,- name: `${sheetName}(${rangeStr})`,- };- if (rule.ranges.length === 1) {- const { startRow, endRow, startColumn, endColumn } = rule.ranges[0];- if (startRow === 0 && endRow === worksheet.getRowCount() - 1 && startColumn === 0 && worksheet.getColumnCount() - 1 === endColumn) {- rule.unitType = UnitObject.Worksheet;- rule.name = `${sheetName}`;- }- }-- sheetPermissionPanelModel.setRule(rule);- };-- const handlePanelClick = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {- const handleOutClick = rangeSelectorActionsRef.current?.handleOutClick;- handleOutClick && handleOutClick(e, isFocusRangeSelectorSet);- };-- const rangeStr = activeRule?.ranges?.map((i) => serializeRange(i)).join(',');-- return (- <div className={styles.permissionPanelDetailWrapper} onClick={handlePanelClick}>- {/* <FormLayout className={styles.sheetPermissionPanelTitle} label={localeService.t('permission.panel.name')}>- <Input- value={activeRule?.name ?? ''}- onChange={(v) => sheetPermissionPanelModel.setRule({ name: v.replace(/\s+/g, '') })}- className={clsx({ [styles.sheetPermissionPanelNameInputError]: !activeRule?.name })}- />- {!activeRule?.name && <span className={styles.sheetPermissionPanelNameInputErrorText}>{localeService.t('permission.panel.nameError')}</span>}- </FormLayout> */}- <Spin loading={loading}>- <FormLayout className={styles.sheetPermissionPanelTitle} label={localeService.t('permission.panel.protectedRange')}>- {RangeSelector && rangeInitialization && (- <RangeSelector- unitId={unitId}- errorText={rangeErrorMsg}- subUnitId={subUnitId}- initValue={rangeStr}- onChange={handleRangeChange}- onFocus={() => isFocusRangeSelectorSet(true)}- // onVerify={handleVerify}- isFocus={isFocusRangeSelector}- actions={rangeSelectorActionsRef.current}- />- )}- </FormLayout>- <FormLayout className={styles.sheetPermissionPanelTitle} label={localeService.t('permission.panel.permissionDirection')}>- <Input- value={activeRule?.description ?? ''}- onChange={(v) => sheetPermissionPanelModel.setRule({ description: v })}- placeholder={localeService.t('permission.panel.permissionDirectionPlaceholder')}- />- </FormLayout>- <FormLayout className={styles.sheetPermissionPanelTitle} label={localeService.t('permission.panel.editPermission')}>- <RadioGroup- value={editorGroupValue}- onChange={(v) => {- setEditorGroupValue(v as editState);- sheetPermissionPanelModel.setRule({- editStatus: v as editState,- });- }}- className={styles.radioGroupVertical}- >- <Radio value={editState.onlyMe}>- <span className={styles.text}>{localeService.t('permission.panel.onlyICanEdit')}</span>- </Radio>- <Radio value={editState.designedUserCanEdit}>- <span className={styles.text}>{localeService.t('permission.panel.designedUserCanEdit')}</span>- </Radio>- </RadioGroup>- </FormLayout>- {editorGroupValue === 'designedUserCanEdit' && (- <div className={styles.sheetPermissionDesignPersonPanel}>-- <div className={styles.sheetPermissionDesignPersonPanelHeader}>- <span>{localeService.t('permission.panel.designedPerson')}</span>- <span className={styles.sheetPermissionDesignPersonPanelHeaderAdd} onClick={handleAddPerson}>{localeService.t('permission.panel.addPerson')}</span>- </div>- <div className={styles.sheetPermissionDesignPersonPanelSplit}></div>- <div className={styles.sheetPermissionDesignPersonPanelContent}>- {selectUserList?.length > 0- ? selectUserList.map((item) => {- return (- <div key={item.subject?.userID} className={styles.sheetPermissionDesignPersonPanelContentItem}>- <Avatar size={24} src={item.subject?.avatar} />- <span className={styles.sheetPermissionDesignPersonPanelContentItemName}>{item.subject?.name}</span>- <Select- className={styles.sheetPermissionDesignPersonPanelContentItemSelect}- value="edit"- onChange={(v) => {- if (v === 'delete') {- sheetPermissionUserManagerService.setSelectUserList(selectUserList.filter((i) => i.subject?.userID !== item.subject?.userID));- }- }}- options={[- { label: `${localeService.t('permission.panel.canEdit')}`, value: 'edit' },- { label: `${localeService.t('permission.panel.delete')}`, value: 'delete' },- ]}- />- </div>- );- })- : (- <div className={styles.sheetPermissionUserListEmpty}>- <img width={240} height={120} src={UserEmptyBase64} alt="" />- <p className={styles.sheetPermissionUserListEmptyText}>{localeService.t('permission.dialog.userEmpty')}</p>- </div>- )}- </div>-- </div>- )}- <FormLayout className={styles.sheetPermissionPanelTitle} label={localeService.t('permission.panel.viewPermission')}>- <RadioGroup- value={viewGroupValue}- onChange={(v) => {- setViewGroupValue(v as viewState);- sheetPermissionPanelModel.setRule({- viewStatus: v as viewState,- });- }}- className={styles.radioGroupVertical}- >- <Radio value={viewState.othersCanView}>- <span className={styles.text}>{localeService.t('permission.panel.othersCanView')}</span>- </Radio>- <Radio value={viewState.noOneElseCanView}>- <span className={styles.text}>{localeService.t('permission.panel.noOneElseCanView')}</span>- </Radio>- </RadioGroup>- </FormLayout>- </Spin>- </div>- );-};diff --git a/packages/sheets-ui/src/views/permission/panel-list/index.module.less b/packages/sheets-ui/src/views/permission/panel-list/index.module.lessindex ab8063b25e..027b56062c 100644--- a/packages/sheets-ui/src/views/permission/panel-list/index.module.less+++ b/packages/sheets-ui/src/views/permission/panel-list/index.module.less@@ -1,6 +1,8 @@.sheet-permission-list-panel-wrapper {margin-top: var(--margin-xs);- height: 100%;+ height: calc(100% - 8px);+ display: flex;+ flex-direction: column;}.sheet-permission-list-panel-header {@@ -39,9 +41,11 @@.sheet-permission-list-item-header-icon {border-radius: var(--border-radius-base);+&:hover {background-color: rgb(var(--grey-200));}+height: 24px;padding: 4px;box-sizing: border-box;@@ -117,7 +121,7 @@flex-direction: column;align-items: center;justify-content: center;- height: 100%;+ flex: 1;}.sheet-permission-list-empty-text {@@ -141,3 +145,19 @@line-height: 16px;color: rgb(var(--grey-600));}++.sheet-permission-panel-add-wrapper {+ padding: 20px 0;+ margin-top: auto;+}++.sheet-permission-panel-add-button {+ width: 100%;+ display: flex;+ align-items: center;+ justify-content: center;++ div {+ margin-right: 4px;+ }+}diff --git a/packages/sheets-ui/src/views/permission/panel-list/index.tsx b/packages/sheets-ui/src/views/permission/panel-list/index.tsxindex 3eaa1896d8..c440dcfd5d 100644--- a/packages/sheets-ui/src/views/permission/panel-list/index.tsx+++ b/packages/sheets-ui/src/views/permission/panel-list/index.tsx@@ -18,22 +18,21 @@ import type { IRange, Workbook } from '@univerjs/core';import type { IPermissionPoint } from '@univerjs/protocol';import type { IRangeProtectionRule, IWorksheetProtectionRule } from '@univerjs/sheets';import type { IPermissionPanelRule } from '../../../services/permission/sheet-permission-panel.model';-import { IAuthzIoService, ICommandService, IPermissionService, IUniverInstanceService, LocaleService, UniverInstanceType, useDependency, UserManagerService } from '@univerjs/core';-import { Avatar, Tooltip } from '@univerjs/design';+import { IAuthzIoService, ICommandService, IPermissionService, IUniverInstanceService, LocaleService, Tools, UniverInstanceType, useDependency, UserManagerService } from '@univerjs/core';+import { Avatar, Button, Tooltip } from '@univerjs/design';import { serializeRange } from '@univerjs/engine-formula';import { DeleteSingle, WriteSingle } from '@univerjs/icons';import { UnitAction, UnitObject } from '@univerjs/protocol';-import { baseProtectionActions, DeleteRangeProtectionCommand, RangeProtectionRuleModel, SetWorksheetActiveOperation, WorksheetProtectionRuleModel } from '@univerjs/sheets';+import { baseProtectionActions, DeleteRangeProtectionCommand, DeleteWorksheetProtectionCommand, RangeProtectionRuleModel, SetWorksheetActiveOperation, WorkbookCreateProtectPermission, WorksheetProtectionRuleModel } from '@univerjs/sheets';import { ISidebarService, useObservable } from '@univerjs/ui';import clsx from 'clsx';import React, { useCallback, useEffect, useState } from 'react';-import { merge } from 'rxjs';-import { DeleteWorksheetProtectionCommand } from '../../../commands/commands/worksheet-protection.command';-import { UNIVER_SHEET_PERMISSION_PANEL, UNIVER_SHEET_PERMISSION_PANEL_FOOTER } from '../../../consts/permission';+import { distinctUntilChanged, merge } from 'rxjs';+import { UNIVER_SHEET_PERMISSION_PANEL } from '../../../consts/permission';import { useHighlightRange } from '../../../hooks/useHighlightRange';-import { SheetPermissionPanelModel } from '../../../services/permission/sheet-permission-panel.model';+import { SheetPermissionUserManagerService } from '../../../services/permission/sheet-permission-user-list.service';import { panelListEmptyBase64 } from './constant';import styles from './index.module.less';@@ -41,14 +40,10 @@ type IRuleItem = IRangeProtectionRule | IWorksheetProtectionRule;export const SheetPermissionPanelList = () => {const [isCurrentSheet, setIsCurrentSheet] = useState(true);const [forceUpdateFlag, setForceUpdateFlag] = useState(false);- const sheetPermissionPanelModel = useDependency(SheetPermissionPanelModel);const localeService = useDependency(LocaleService);const rangeProtectionRuleModel = useDependency(RangeProtectionRuleModel);const worksheetProtectionModel = useDependency(WorksheetProtectionRuleModel);const univerInstanceService = useDependency(IUniverInstanceService);- const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;-- const unitId = workbook.getUnitId();const commandService = useDependency(ICommandService);const sidebarService = useDependency(ISidebarService);const authzIoService = useDependency(IAuthzIoService);@@ -56,10 +51,19 @@ export const SheetPermissionPanelList = () => {const usesManagerService = useDependency(UserManagerService);const currentUser = usesManagerService.getCurrentUser();const [currentRuleRanges, currentRuleRangesSet] = useState<IRange[]>([]);+ const sheetPermissionUserManagerService = useDependency(SheetPermissionUserManagerService);const _sheetRuleRefresh = useObservable(worksheetProtectionModel.ruleRefresh$, '');const _rangeRuleRefresh = useObservable(rangeProtectionRuleModel.ruleRefresh$, '');+ const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);++ if (!workbook) {+ return null;+ }++ const unitId = workbook?.getUnitId();+const getRuleList = useCallback(async (isCurrentSheet: boolean) => {const worksheet = workbook.getActiveSheet()!;const unitId = workbook.getUnitId();@@ -118,7 +122,9 @@ export const SheetPermissionPanelList = () => {}, [isCurrentSheet]);useEffect(() => {- const subscribe = workbook.activeSheet$.subscribe(async () => {+ const subscribe = workbook.activeSheet$.pipe(+ distinctUntilChanged((prevSheet, currSheet) => prevSheet?.getSheetId() === currSheet?.getSheetId())+ ).subscribe(async () => {const ruleList = await getRuleList(isCurrentSheet);setRuleList(ruleList);});@@ -154,6 +160,10 @@ export const SheetPermissionPanelList = () => {}};+ useEffect(() => {+ sheetPermissionUserManagerService.reset();+ }, []);+useHighlightRange(currentRuleRanges);const allRuleMap = new Map<string, IRangeProtectionRule | IWorksheetProtectionRule>();@@ -171,9 +181,6 @@ export const SheetPermissionPanelList = () => {});const handleEdit = (rule: IPermissionPanelRule) => {- sheetPermissionPanelModel.setRule(rule);- sheetPermissionPanelModel.setOldRule(rule);-if (rule.subUnitId !== workbook.getActiveSheet().getSheetId()) {commandService.executeCommand(SetWorksheetActiveOperation.id, {unitId: rule.unitId,@@ -186,23 +193,21 @@ export const SheetPermissionPanelList = () => {children: {label: UNIVER_SHEET_PERMISSION_PANEL,showDetail: true,+ rule: Tools.deepClone(rule),+ oldRule: Tools.deepClone(rule),},width: 330,- footer: {- label: UNIVER_SHEET_PERMISSION_PANEL_FOOTER,- showDetail: true,- },};sidebarService.open(sidebarProps);};- const handleChangeHeaderType = async (isCurrentSheet: boolean) => {+ const handleChangeHeaderType = (isCurrentSheet: boolean) => {setIsCurrentSheet(isCurrentSheet);- const ruleList = await getRuleList(isCurrentSheet);- setRuleList(ruleList);};+ const hasSetProtectPermission = permissionService.getPermissionPoint(new WorkbookCreateProtectPermission(unitId).id)?.value;+return (<div className={styles.sheetPermissionListPanelWrapper}><div className={styles.sheetPermissionListPanelHeader}>@@ -335,6 +340,29 @@ export const SheetPermissionPanelList = () => {<p className={styles.sheetPermissionListEmptyText}>{localeService.t('permission.dialog.listEmpty')}</p></div>)}++ {hasSetProtectPermission && (+ <div className={styles.sheetPermissionPanelAddWrapper}>+ <Button+ className={styles.sheetPermissionPanelAddButton}+ type="primary"+ onClick={() => {+ const sidebarProps = {+ header: { title: `${localeService.t('permission.panel.title')}` },+ children: {+ label: UNIVER_SHEET_PERMISSION_PANEL,+ showDetail: true,+ },+ width: 330,+ };+ sidebarService.open(sidebarProps);+ }}+ >+ <div>+ </div>+ {localeService.t('permission.button.addNewPermission')}+ </Button>+ </div>+ )}</div>);};diff --git a/packages/sheets-ui/src/views/permission/panel/index.tsx b/packages/sheets-ui/src/views/permission/panel/index.tsxindex ea61e73a6a..b612cfb5b9 100644--- a/packages/sheets-ui/src/views/permission/panel/index.tsx+++ b/packages/sheets-ui/src/views/permission/panel/index.tsx@@ -14,17 +14,23 @@* limitations under the License.*/-import React from 'react';+import type { IPermissionPanelRule } from '../../../services/permission/sheet-permission-panel.model';import { IUniverInstanceService, useDependency } from '@univerjs/core';-import { getSheetCommandTarget, SheetsSelectionsService } from '@univerjs/sheets';import { serializeRangeWithSheet } from '@univerjs/engine-formula';-import { SheetPermissionPanelList } from '../panel-list';-import { SheetPermissionPanelDetail } from '../panel-detail';+import { getSheetCommandTarget, SheetsSelectionsService } from '@univerjs/sheets';+import React from 'react';import { SheetPermissionPanelModel } from '../../../services/permission/sheet-permission-panel.model';+import { SheetPermissionPanelDetail } from '../panel-detail/PermissionDetailPanel';+import { SheetPermissionPanelList } from '../panel-list';-interface ISheetPermissionPanelProps { showDetail: boolean; fromSheetBar: boolean };+interface ISheetPermissionPanelProps {+ showDetail: boolean;+ fromSheetBar: boolean;+ rule?: IPermissionPanelRule;+ oldRule?: IPermissionPanelRule;+};-export const SheetPermissionPanel = ({ showDetail, fromSheetBar }: ISheetPermissionPanelProps) => {+export const SheetPermissionPanel = ({ showDetail, fromSheetBar, rule, oldRule }: ISheetPermissionPanelProps) => {const univerInstanceService = useDependency(IUniverInstanceService);const sheetsSelectionsService = useDependency(SheetsSelectionsService);const sheetPermissionPanelModel = useDependency(SheetPermissionPanelModel);@@ -39,6 +45,14 @@ export const SheetPermissionPanel = ({ showDetail, fromSheetBar }: ISheetPermissconst key = selectionRanges.reduce((acc, range) => acc + serializeRangeWithSheet(worksheet.getName(), range), '');return (- showDetail ? <SheetPermissionPanelDetail fromSheetBar={fromSheetBar} key={key} /> : <SheetPermissionPanelList key={key} />+ showDetail+ ? (+ <SheetPermissionPanelDetail+ fromSheetBar={fromSheetBar}+ rule={rule}+ oldRule={oldRule}+ />+ )+ : <SheetPermissionPanelList key={key} />);};diff --git a/packages/sheets-ui/src/views/permission/user-dialog/index.tsx b/packages/sheets-ui/src/views/permission/user-dialog/index.tsxindex e70c38cb4c..42f3d7cea4 100644--- a/packages/sheets-ui/src/views/permission/user-dialog/index.tsx+++ b/packages/sheets-ui/src/views/permission/user-dialog/index.tsx@@ -14,17 +14,17 @@* limitations under the License.*/-import React, { useState } from 'react';-import { Avatar, Button, Input } from '@univerjs/design';-import clsx from 'clsx';import { LocaleService, useDependency } from '@univerjs/core';-import { IDialogService } from '@univerjs/ui';-import { type ICollaborator, UnitRole } from '@univerjs/protocol';+import { Avatar, Button, Input } from '@univerjs/design';import { CheckMarkSingle } from '@univerjs/icons';-import { SheetPermissionUserManagerService } from '../../../services/permission/sheet-permission-user-list.service';+import { type ICollaborator, UnitRole } from '@univerjs/protocol';+import { IDialogService } from '@univerjs/ui';+import clsx from 'clsx';+import React, { useState } from 'react';import { UNIVER_SHEET_PERMISSION_USER_DIALOG_ID } from '../../../consts/permission';-import styles from './index.module.less';+import { SheetPermissionUserManagerService } from '../../../services/permission/sheet-permission-user-list.service';import { UserEmptyBase64 } from './constant';+import styles from './index.module.less';export const SheetPermissionUserDialog = () => {const [inputValue, setInputValue] = React.useState('');@@ -52,7 +52,7 @@ export const SheetPermissionUserDialog = () => {<div className={styles.sheetPermissionUserDialogWrapper}><div className={styles.sheetPermissionUserDialogSearch}><Input- placeholder="search"+ placeholder={localeService.t('permission.dialog.search')}className={styles.sheetPermissionUserDialogSearchInput}value={inputValue}onChange={(v) => setInputValue(v)}diff --git a/packages/sheets-ui/src/views/permission/util.ts b/packages/sheets-ui/src/views/permission/util.tsnew file mode 100644index 0000000000..9a63cf344a--- /dev/null+++ b/packages/sheets-ui/src/views/permission/util.ts@@ -0,0 +1,136 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { Injector, IRange, Workbook, Worksheet } from '@univerjs/core';+import type { IPermissionPanelRule } from '../../services/permission/sheet-permission-panel.model';+import { IUniverInstanceService, LocaleService, RANGE_TYPE, Rectangle, UniverInstanceType } from '@univerjs/core';+import { EditStateEnum, RangeProtectionRuleModel, SheetsSelectionsService, UnitObject, ViewStateEnum, WorksheetProtectionRuleModel } from '@univerjs/sheets';++export const checkRangeValid = (injector: Injector, permissionRanges: IRange[], permissionId: string, unitId: string, subUnitId: string) => {+ const localeService = injector.get(LocaleService);+ const worksheetRuleModel = injector.get(WorksheetProtectionRuleModel);+ const rangeProtectionRuleModel = injector.get(RangeProtectionRuleModel);++ let rangeErrorString = '';+ if (permissionRanges.length === 0) {+ rangeErrorString = localeService.t('permission.panel.emptyRangeError');+ } else if (permissionRanges.length > 1) {+ let hasLap = false;+ for (let i = 0; i < permissionRanges.length; i++) {+ for (let j = i + 1; j < permissionRanges.length; j++) {+ if (Rectangle.intersects(permissionRanges[i], permissionRanges[j])) {+ hasLap = true;+ break;+ }+ }+ if (hasLap) {+ break;+ }+ }+ if (hasLap) {+ rangeErrorString = localeService.t('permission.panel.rangeOverlapError');+ }+ }+ if (!rangeErrorString) {+ const worksheetRule = worksheetRuleModel.getRule(unitId, subUnitId);+ if (worksheetRule && !permissionId) {+ rangeErrorString = localeService.t('permission.panel.rangeOverlapOverPermissionError');+ return rangeErrorString;+ }+ const lapRule = rangeProtectionRuleModel.getSubunitRuleList(unitId, subUnitId).filter((rule) => {+ return rule.permissionId !== permissionId;+ }).find((rule) => {+ return rule.ranges.some((ruleRange) => {+ return permissionRanges.some((r) => Rectangle.intersects(ruleRange, r));+ });+ });+ const lapRange = lapRule?.ranges.find((range) => {+ return permissionRanges.some((r) => Rectangle.intersects(range, r));+ });+ if (lapRange) {+ rangeErrorString = localeService.t('permission.panel.rangeOverlapOverPermissionError');+ }+ }+ return rangeErrorString === '' ? undefined : rangeErrorString;+};++export const checkRangesIsWholeSheet = (ranges: IRange[], sheet: Worksheet) => {+ if (ranges.length !== 1) {+ return false;+ }+ const range = ranges[0];+ const rowCount = sheet.getRowCount();+ const colCount = sheet.getColumnCount();++ const { startRow, endRow, startColumn, endColumn } = range;++ return startRow === 0 && startColumn === 0 && endRow === rowCount - 1 && endColumn === colCount - 1;+};++export const generateDefaultRule = (injector: Injector, fromSheetBar: boolean) => {+ const univerInstanceService = injector.get(IUniverInstanceService);+ const selectionManagerService = injector.get(SheetsSelectionsService);+ const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ const worksheet = workbook.getActiveSheet();++ let unitType = UnitObject.SelectRange;+ let ranges = selectionManagerService.getCurrentSelections()?.map((s) => s.range) ?? [];++ if (fromSheetBar) {+ unitType = UnitObject.Worksheet;+ ranges = [{+ startRow: 0,+ startColumn: 0,+ endRow: worksheet.getRowCount() - 1,+ endColumn: worksheet.getColumnCount() - 1,+ rangeType: RANGE_TYPE.ALL,+ }];+ }++ return {+ unitId: workbook.getUnitId(),+ subUnitId: worksheet.getSheetId(),+ permissionId: '',+ unitType,+ description: '',+ id: '',+ ranges,+ editState: EditStateEnum.OnlyMe,+ viewState: ViewStateEnum.OthersCanView,+ };+};++export const generateRuleByUnitType = (injector: Injector, rule: IPermissionPanelRule) => {+ const univerInstanceService = injector.get(IUniverInstanceService);+ const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ const worksheet = workbook.getActiveSheet();+ const { unitType } = rule;++ if (unitType === UnitObject.Worksheet) {+ return {+ ...rule,+ ranges: [{+ startRow: 0,+ startColumn: 0,+ endRow: worksheet.getRowCount() - 1,+ endColumn: worksheet.getColumnCount() - 1,+ rangeType: RANGE_TYPE.ALL,+ }],+ };+ }++ return rule;+};diff --git a/packages/sheets/src/commands/commands/add-range-protection.command.ts b/packages/sheets/src/commands/commands/add-range-protection.command.tsindex 3a0c6ac4c6..866eb0cbee 100644--- a/packages/sheets/src/commands/commands/add-range-protection.command.ts+++ b/packages/sheets/src/commands/commands/add-range-protection.command.ts@@ -15,8 +15,8 @@*/import type { ICommand } from '@univerjs/core';-import { CommandType, ICommandService, IUndoRedoService } from '@univerjs/core';import type { IRangeProtectionRule } from '../../model/range-protection-rule.model';+import { CommandType, ICommandService, IUndoRedoService } from '@univerjs/core';import { RangeProtectionRuleModel } from '../../model/range-protection-rule.model';import { AddRangeProtectionMutation } from '../mutations/add-range-protection.mutation';import { DeleteRangeProtectionMutation } from '../mutations/delete-range-protection.mutation';@@ -37,16 +37,17 @@ export const AddRangeProtectionCommand: ICommand<IAddRangeProtectionCommandParamconst selectionProtectionModel = accessor.get(RangeProtectionRuleModel);const { rule, permissionId } = params;- const { unitId, subUnitId, ranges, name, description } = rule;+ const { unitId, subUnitId, ranges, description, viewState, editState } = rule;const rules = [{ranges,permissionId,id: selectionProtectionModel.createRuleId(unitId, subUnitId),- name,description,unitType: rule.unitType,unitId,subUnitId,+ viewState,+ editState,}];const result = await commandService.executeCommand(AddRangeProtectionMutation.id, {diff --git a/packages/sheets/src/commands/commands/add-worksheet-protection.command.ts b/packages/sheets/src/commands/commands/add-worksheet-protection.command.tsnew file mode 100644index 0000000000..69479cb642--- /dev/null+++ b/packages/sheets/src/commands/commands/add-worksheet-protection.command.ts@@ -0,0 +1,58 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICommand } from '@univerjs/core';+import type { IWorksheetProtectionRule } from '../../services/permission/type';+import { CommandType, ICommandService, IUndoRedoService } from '@univerjs/core';+import { AddWorksheetProtectionMutation } from '../mutations/add-worksheet-protection.mutation';+import { DeleteWorksheetProtectionMutation } from '../mutations/delete-worksheet-protection.mutation';++export interface IAddWorksheetProtectionParams {+ unitId: string;+ rule: IWorksheetProtectionRule;+}++export const AddWorksheetProtectionCommand: ICommand<IAddWorksheetProtectionParams> = {+ type: CommandType.COMMAND,+ id: 'sheet.command.add-worksheet-protection',+ async handler(accessor, params) {+ if (!params) {+ return false;+ }+ const commandService = accessor.get(ICommandService);+ const undoRedoService = accessor.get(IUndoRedoService);+ const { rule, unitId } = params;+ const subUnitId = rule.subUnitId;++ const result = await commandService.executeCommand(AddWorksheetProtectionMutation.id, {+ unitId,+ rule,+ subUnitId: rule.subUnitId,+ });++ if (result) {+ const redoMutations = [{ id: AddWorksheetProtectionMutation.id, params: { unitId, rule, subUnitId: rule.subUnitId } }];+ const undoMutations = [{ id: DeleteWorksheetProtectionMutation.id, params: { unitId, subUnitId } }];+ undoRedoService.pushUndoRedo({+ unitID: unitId,+ redoMutations,+ undoMutations,+ });+ }++ return true;+ },+};diff --git a/packages/sheets/src/commands/commands/delete-worksheet-protection.command.ts b/packages/sheets/src/commands/commands/delete-worksheet-protection.command.tsnew file mode 100644index 0000000000..a4da2d002e--- /dev/null+++ b/packages/sheets/src/commands/commands/delete-worksheet-protection.command.ts@@ -0,0 +1,55 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICommand } from '@univerjs/core';+import type { IWorksheetProtectionRule } from '../../services/permission/type';+import { CommandType, ICommandService, IUndoRedoService } from '@univerjs/core';+import { AddWorksheetProtectionMutation } from '../mutations/add-worksheet-protection.mutation';+import { DeleteWorksheetProtectionMutation } from '../mutations/delete-worksheet-protection.mutation';++export interface IDeleteWorksheetProtectionParams {+ unitId: string;+ subUnitId: string;+ rule: IWorksheetProtectionRule;+}++export const DeleteWorksheetProtectionCommand: ICommand<IDeleteWorksheetProtectionParams> = {+ type: CommandType.COMMAND,+ id: 'sheet.command.delete-worksheet-protection',+ handler(accessor, params) {+ if (!params) {+ return false;+ }+ const commandService = accessor.get(ICommandService);+ const undoRedoService = accessor.get(IUndoRedoService);+ const { rule, unitId, subUnitId } = params;++ commandService.executeCommand(DeleteWorksheetProtectionMutation.id, {+ unitId,+ subUnitId,+ });++ const redoMutations = [{ id: DeleteWorksheetProtectionMutation.id, params: { unitId, subUnitId } }];+ const undoMutations = [{ id: AddWorksheetProtectionMutation.id, params: { unitId, rule, subUnitId } }];+ undoRedoService.pushUndoRedo({+ unitID: unitId,+ redoMutations,+ undoMutations,+ });++ return true;+ },+};diff --git a/packages/sheets/src/commands/commands/set-protection.command.ts b/packages/sheets/src/commands/commands/set-protection.command.tsnew file mode 100644index 0000000000..02ea3a4a21--- /dev/null+++ b/packages/sheets/src/commands/commands/set-protection.command.ts@@ -0,0 +1,94 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICommand, IRange } from '@univerjs/core';+import type { IRangeProtectionRule } from '../../model/range-protection-rule.model';+import type { IWorksheetProtectionRule } from '../../services/permission/type';+import { CommandType, ICommandService, IUndoRedoService, sequenceExecute } from '@univerjs/core';+import { UnitObject } from '@univerjs/protocol';+import { RangeProtectionRuleModel } from '../../model/range-protection-rule.model';+import { AddRangeProtectionMutation } from '../mutations/add-range-protection.mutation';+import { AddWorksheetProtectionMutation } from '../mutations/add-worksheet-protection.mutation';+import { DeleteRangeProtectionMutation } from '../mutations/delete-range-protection.mutation';+import { DeleteWorksheetProtectionMutation } from '../mutations/delete-worksheet-protection.mutation';+import { SetRangeProtectionMutation } from '../mutations/set-range-protection.mutation';+import { SetWorksheetProtectionMutation } from '../mutations/set-worksheet-protection.mutation';++type IPermissionRule = (IRangeProtectionRule | IWorksheetProtectionRule) & { ranges: IRange[]; id: string };++interface ISetProtectionParams {+ rule: IPermissionRule;+ oldRule: IPermissionRule;+}++export const SetProtectionCommand: ICommand<ISetProtectionParams> = {+ type: CommandType.COMMAND,+ id: 'sheet.command.set-protection',+ async handler(accessor, params) {+ if (!params) {+ return false;+ }+ const commandService = accessor.get(ICommandService);+ const undoRedoService = accessor.get(IUndoRedoService);+ const rangeProtectionRuleModel = accessor.get(RangeProtectionRuleModel);+ const { rule, oldRule } = params;+ const { unitId, subUnitId } = rule;++ const redoMutations = [];+ const undoMutations = [];++ if (oldRule?.unitType === rule.unitType) {+ if (rule.unitType === UnitObject.Worksheet) {+ redoMutations.push({ id: SetWorksheetProtectionMutation.id, params: { unitId, subUnitId, rule } });+ undoMutations.push({ id: SetWorksheetProtectionMutation.id, params: { unitId, subUnitId, rule: oldRule } });+ } else {+ redoMutations.push({ id: SetRangeProtectionMutation.id, params: { unitId, subUnitId, rule, ruleId: (rule as IRangeProtectionRule).id } });+ undoMutations.push({ id: SetRangeProtectionMutation.id, params: { unitId, subUnitId, ruleId: (oldRule as IRangeProtectionRule).id, rule: oldRule } });+ }+ } else {+ if (oldRule) {+ if (oldRule.unitType === UnitObject.Worksheet) {+ redoMutations.push({ id: DeleteWorksheetProtectionMutation.id, params: { unitId, subUnitId } });+ undoMutations.push({ id: AddWorksheetProtectionMutation.id, params: { unitId, rule: oldRule, subUnitId: oldRule.subUnitId } });+ } else if (oldRule.unitType === UnitObject.SelectRange) {+ redoMutations.push({ id: DeleteRangeProtectionMutation.id, params: { unitId, subUnitId, ruleIds: [(oldRule as IRangeProtectionRule).id] } });+ undoMutations.push({ id: AddRangeProtectionMutation.id, params: { unitId, subUnitId, rules: [oldRule] } });+ }+ }++ if (rule.unitType === UnitObject.Worksheet) {+ redoMutations.push({ id: AddWorksheetProtectionMutation.id, params: { unitId, rule, subUnitId: rule.subUnitId } });+ undoMutations.unshift({ id: DeleteWorksheetProtectionMutation.id, params: { unitId, subUnitId } });+ } else if (rule.unitType === UnitObject.SelectRange) {+ (rule as IRangeProtectionRule).id = rangeProtectionRuleModel.createRuleId(unitId, subUnitId);+ redoMutations.push({ id: AddRangeProtectionMutation.id, params: { unitId, subUnitId, rules: [rule] } });+ undoMutations.unshift({ id: DeleteRangeProtectionMutation.id, params: { unitId, subUnitId, ruleIds: [(rule as IRangeProtectionRule).id] } });+ }+ }++ const result = sequenceExecute(redoMutations, commandService);++ if (result) {+ undoRedoService.pushUndoRedo({+ unitID: unitId,+ undoMutations,+ redoMutations,+ });+ }++ return true;+ },+};diff --git a/packages/sheets/src/commands/commands/set-range-protection.command.ts b/packages/sheets/src/commands/commands/set-range-protection.command.tsdeleted file mode 100644index 886f5bafd3..0000000000--- a/packages/sheets/src/commands/commands/set-range-protection.command.ts+++ /dev/null@@ -1,78 +0,0 @@-/**- * Copyright 2023-present DreamNum Inc.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import type { ICommand } from '@univerjs/core';-import { CommandType, ICommandService, IUndoRedoService } from '@univerjs/core';-import { SetRangeProtectionMutation } from '../mutations/set-range-protection.mutation';-import type { IRangeProtectionRule } from '../../model/range-protection-rule.model';-import { RangeProtectionRuleModel } from '../../model/range-protection-rule.model';--export interface ISetRangeProtectionCommandParams {- permissionId: string;- rule: IRangeProtectionRule;- oldRule: IRangeProtectionRule;-};-export const SetRangeProtectionCommand: ICommand<ISetRangeProtectionCommandParams> = {- type: CommandType.COMMAND,- id: 'sheet.command.set-range-protection',- async handler(accessor, params) {- if (!params) {- return false;- }- const commandService = accessor.get(ICommandService);- const selectionProtectionModel = accessor.get(RangeProtectionRuleModel);- const undoRedoService = accessor.get(IUndoRedoService);- const { rule, permissionId, oldRule } = params;-- const { unitId, subUnitId, ranges, name, description } = rule;-- if (rule.id) {- const redoMutationParam = {- unitId,- subUnitId,- ruleId: rule.id,- rule: {- ranges,- permissionId,- id: selectionProtectionModel.createRuleId(unitId, subUnitId),- name,- description,- },- };- const result = await commandService.executeCommand(SetRangeProtectionMutation.id, redoMutationParam);-- if (result) {- const redoMutations = [{- id: SetRangeProtectionMutation.id, params: redoMutationParam,- }];- const undoMutations = [{- id: SetRangeProtectionMutation.id, params: {- unitId,- subUnitId,- ruleId: rule.id,- rule: oldRule,- },- }];- undoRedoService.pushUndoRedo({- unitID: unitId,- redoMutations,- undoMutations,- });- }- }- return true;- },-};diff --git a/packages/sheets/src/commands/commands/set-worksheet-protection.command.ts b/packages/sheets/src/commands/commands/set-worksheet-protection.command.tsnew file mode 100644index 0000000000..0246b9aaa8--- /dev/null+++ b/packages/sheets/src/commands/commands/set-worksheet-protection.command.ts@@ -0,0 +1,62 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICommand } from '@univerjs/core';+import type { IWorksheetProtectionRule } from '../../services/permission/type';+import { CommandType, ICommandService, IUndoRedoService } from '@univerjs/core';+import { SetWorksheetProtectionMutation } from '../mutations/set-worksheet-protection.mutation';++export interface ISetWorksheetProtectionParams {+ permissionId: string;+ rule: IWorksheetProtectionRule;+ oldRule: IWorksheetProtectionRule;+}++export const SetWorksheetProtectionCommand: ICommand<ISetWorksheetProtectionParams> = {+ type: CommandType.COMMAND,+ id: 'sheet.command.set-worksheet-protection',+ async handler(accessor, params) {+ if (!params) {+ return false;+ }+ const commandService = accessor.get(ICommandService);+ const undoRedoService = accessor.get(IUndoRedoService);++ const { rule, permissionId, oldRule } = params;+ const { unitId, subUnitId } = rule;++ const newRule = { ...rule, permissionId };++ const result = await commandService.executeCommand(SetWorksheetProtectionMutation.id, {+ unitId,+ subUnitId,+ newRule,+ });++ if (result) {+ const redoMutations = [{ id: SetWorksheetProtectionMutation.id, params: { unitId, subUnitId, newRule } }];+ const undoMutations = [{ id: SetWorksheetProtectionMutation.id, params: { unitId, subUnitId, rule: oldRule } }];+ undoRedoService.pushUndoRedo({+ unitID: unitId,+ redoMutations,+ undoMutations,+ });+ }++ return true;+ },+};+diff --git a/packages/sheets/src/controllers/basic-worksheet.controller.ts b/packages/sheets/src/controllers/basic-worksheet.controller.tsindex b6dac6910a..20cca98964 100644--- a/packages/sheets/src/controllers/basic-worksheet.controller.ts+++ b/packages/sheets/src/controllers/basic-worksheet.controller.ts@@ -19,6 +19,7 @@ import { Disposable, ICommandService, IConfigService, Optional } from '@univerjsimport { DataSyncPrimaryController } from '@univerjs/rpc';import { AddRangeProtectionCommand } from '../commands/commands/add-range-protection.command';+import { AddWorksheetProtectionCommand } from '../commands/commands/add-worksheet-protection.command';import { ClearSelectionAllCommand } from '../commands/commands/clear-selection-all.command';import { ClearSelectionContentCommand } from '../commands/commands/clear-selection-content.command';import { ClearSelectionFormatCommand } from '../commands/commands/clear-selection-format.command';@@ -26,6 +27,7 @@ import { CopySheetCommand } from '../commands/commands/copy-worksheet.command';import { DeleteRangeMoveLeftCommand } from '../commands/commands/delete-range-move-left.command';import { DeleteRangeMoveUpCommand } from '../commands/commands/delete-range-move-up.command';import { DeleteRangeProtectionCommand } from '../commands/commands/delete-range-protection.command';+import { DeleteWorksheetProtectionCommand } from '../commands/commands/delete-worksheet-protection.command';import { InsertDefinedNameCommand } from '../commands/commands/insert-defined-name.command';import { InsertRangeMoveDownCommand } from '../commands/commands/insert-range-move-down.command';import { InsertRangeMoveRightCommand } from '../commands/commands/insert-range-move-right.command';@@ -60,7 +62,7 @@ import {} from '../commands/commands/set-col-visible.command';import { SetDefinedNameCommand } from '../commands/commands/set-defined-name.command';import { CancelFrozenCommand, SetFrozenCommand } from '../commands/commands/set-frozen.command';-import { SetRangeProtectionCommand } from '../commands/commands/set-range-protection.command';+import { SetProtectionCommand } from '../commands/commands/set-protection.command';import { SetRangeValuesCommand } from '../commands/commands/set-range-values.command';import { SetRowDataCommand } from '../commands/commands/set-row-data.command';import {@@ -87,6 +89,7 @@ import { SetWorksheetHideCommand } from '../commands/commands/set-worksheet-hideimport { SetWorksheetNameCommand } from '../commands/commands/set-worksheet-name.command';import { SetWorksheetOrderCommand } from '../commands/commands/set-worksheet-order.command';import { SetWorksheetPermissionPointsCommand } from '../commands/commands/set-worksheet-permission-points.command';+import { SetWorksheetProtectionCommand } from '../commands/commands/set-worksheet-protection.command';import {DeltaRowHeightCommand,SetRowHeightCommand,@@ -109,11 +112,11 @@ import { RemoveNumfmtMutation, SetNumfmtMutation } from '../commands/mutations/nimport { RemoveColMutation, RemoveRowMutation } from '../commands/mutations/remove-row-col.mutation';import { RemoveSheetMutation } from '../commands/mutations/remove-sheet.mutation';import { RemoveWorksheetMergeMutation } from '../commands/mutations/remove-worksheet-merge.mutation';+import { ReorderRangeMutation } from '../commands/mutations/reorder-range.mutation';import { SetColDataMutation } from '../commands/mutations/set-col-data.mutation';import { SetColHiddenMutation, SetColVisibleMutation } from '../commands/mutations/set-col-visible.mutation';import { SetFrozenMutation } from '../commands/mutations/set-frozen.mutation';-import { SetRangeProtectionMutation } from '../commands/mutations/set-range-protection.mutation';import { SetRangeValuesMutation } from '../commands/mutations/set-range-values.mutation';import { SetRowDataMutation } from '../commands/mutations/set-row-data.mutation';@@ -279,8 +282,11 @@ export class BasicWorksheetController extends Disposable implements IDisposableDeleteWorksheetProtectionMutation,SetWorksheetPermissionPointsMutation,AddRangeProtectionCommand,+ SetProtectionCommand,DeleteRangeProtectionCommand,- SetRangeProtectionCommand,+ AddWorksheetProtectionCommand,+ DeleteWorksheetProtectionCommand,+ SetWorksheetProtectionCommand,AddRangeProtectionMutation,DeleteRangeProtectionMutation,SetRangeProtectionMutation,diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.tsindex 0c6b2e1fc9..ce4f73bfd7 100644--- a/packages/sheets/src/index.ts+++ b/packages/sheets/src/index.ts@@ -150,7 +150,7 @@ export { checkRangesEditablePermission } from './services/permission/util';// range-protectionexport { type ICellPermission, RangeProtectionRenderModel } from './model/range-protection-render.model';-export { type IModel, type IObjectModel, type IRangeProtectionRule, RangeProtectionRuleModel } from './model/range-protection-rule.model';+export { EditStateEnum, type IModel, type IObjectModel, type IRangeProtectionRule, RangeProtectionRuleModel, ViewStateEnum } from './model/range-protection-rule.model';export { RangeProtectionCache } from './model/range-protection.cache';export type { IWorksheetProtectionRenderCellData } from './services/permission/worksheet-permission/type';@@ -182,6 +182,9 @@ export { copyRangeStyles } from './commands/commands/utils/selection-utils';// #region - all commandsexport { AddRangeProtectionCommand, type IAddRangeProtectionCommandParams } from './commands/commands/add-range-protection.command';+export { AddWorksheetProtectionCommand } from './commands/commands/add-worksheet-protection.command';+export { SetWorksheetProtectionCommand } from './commands/commands/set-worksheet-protection.command';+export { DeleteWorksheetProtectionCommand } from './commands/commands/delete-worksheet-protection.command';export {addMergeCellsUtil,AddWorksheetMergeAllCommand,@@ -252,7 +255,6 @@ export { SetDefinedNameCommand } from './commands/commands/set-defined-name.commexport { type ICancelFrozenCommandParams, type ISetFrozenCommandParams } from './commands/commands/set-frozen.command';export { CancelFrozenCommand, SetFrozenCommand } from './commands/commands/set-frozen.command';export { type IToggleGridlinesCommandParams, ToggleGridlinesCommand } from './commands/commands/toggle-gridlines.command';-export { type ISetRangeProtectionCommandParams, SetRangeProtectionCommand } from './commands/commands/set-range-protection.command';export { type ISetRangeValuesCommandParams, SetRangeValuesCommand } from './commands/commands/set-range-values.command';export {type ISetSpecificRowsVisibleCommandParams,@@ -316,6 +318,7 @@ export {export { SetWorksheetShowCommand } from './commands/commands/set-worksheet-show.command';export type { ISetWorksheetShowCommandParams } from './commands/commands/set-worksheet-show.command';export { AddRangeProtectionMutation, FactoryAddRangeProtectionMutation, type IAddRangeProtectionMutationParams } from './commands/mutations/add-range-protection.mutation';+export { SetProtectionCommand } from './commands/commands/set-protection.command';export { AddMergeUndoMutationFactory, AddWorksheetMergeMutation } from './commands/mutations/add-worksheet-merge.mutation';export { AddWorksheetProtectionMutation, type IAddWorksheetProtectionParams } from './commands/mutations/add-worksheet-protection.mutation';export { DeleteRangeProtectionMutation, FactoryDeleteRangeProtectionMutation, type IDeleteRangeProtectionMutationParams } from './commands/mutations/delete-range-protection.mutation';diff --git a/packages/sheets/src/model/range-protection-rule.model.ts b/packages/sheets/src/model/range-protection-rule.model.tsindex d9302d3fdb..581e81a3ad 100644--- a/packages/sheets/src/model/range-protection-rule.model.ts+++ b/packages/sheets/src/model/range-protection-rule.model.ts@@ -20,15 +20,26 @@ import { Tools } from '@univerjs/core';import { BehaviorSubject, Subject } from 'rxjs';+export enum ViewStateEnum {+ OthersCanView = 'othersCanView',+ NoOneElseCanView = 'noOneElseCanView',+}++export enum EditStateEnum {+ DesignedUserCanEdit = 'designedUserCanEdit',+ OnlyMe = 'onlyMe',+}+export interface IRangeProtectionRule {ranges: IRange[];permissionId: string;id: string;- name: string;description?: string;unitType: UnitObject;unitId: string;subUnitId: string;+ viewState: ViewStateEnum;+ editState: EditStateEnum;}export type IObjectModel = Record<string, Record<string, IRangeProtectionRule[]>>;diff --git a/packages/sheets/src/services/permission/type.ts b/packages/sheets/src/services/permission/type.tsindex 4c8dde1a93..07e725459f 100644--- a/packages/sheets/src/services/permission/type.ts+++ b/packages/sheets/src/services/permission/type.ts@@ -15,6 +15,7 @@*/import type { UnitObject } from '@univerjs/protocol';+import type { EditStateEnum, ViewStateEnum } from '../../model/range-protection-rule.model';export interface IWorksheetProtectionRule {permissionId: string;@@ -22,7 +23,8 @@ export interface IWorksheetProtectionRule {unitType: UnitObject;unitId: string;subUnitId: string;- name: string;+ viewState: ViewStateEnum;+ editState: EditStateEnum;}export interface IWorksheetProtectionPointRule {