Skip to content

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

feat(docs): add document permission controls (#7586)

Univer0d8490125948
diff --git a/packages/docs-drawing-ui/package.json b/packages/docs-drawing-ui/package.json
index 30d6f54733..da146f7280 100644
--- a/packages/docs-drawing-ui/package.json
+++ b/packages/docs-drawing-ui/package.json
@@ -87,6 +87,7 @@
"devDependencies": {
"@testing-library/react": "^16.3.2",
"@univerjs-infra/shared": "workspace:*",
+ "@univerjs/protocol": "workspace:*",
"postcss": "^8.5.26",
"react": "18.3.1",
"rxjs": "^7.8.2",
diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-update.render-controller.spec.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-update.render-controller.spec.ts
index 71cdec7d7c..5ccf677e74 100644
--- a/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-update.render-controller.spec.ts
+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-update.render-controller.spec.ts
@@ -14,10 +14,11 @@
* limitations under the License.
*/
-import { BooleanNumber, DrawingTypeEnum, FOCUSING_COMMON_DRAWINGS, ObjectRelativeFromH, ObjectRelativeFromV, PositionedObjectLayoutType } from '@univerjs/core';
-import { RichTextEditingMutation } from '@univerjs/docs';
+import { BooleanNumber, DrawingTypeEnum, FOCUSING_COMMON_DRAWINGS, ObjectRelativeFromH, ObjectRelativeFromV, PermissionService, PositionedObjectLayoutType } from '@univerjs/core';
+import { RichTextEditingMutation, setDocumentPermissionValue } from '@univerjs/docs';
import { SetDocDrawingArrangeCommand, UpdateDrawingDocTransformCommand } from '@univerjs/docs-drawing';
import { DocumentEditArea } from '@univerjs/engine-render';
+import { UnitAction } from '@univerjs/protocol';
import { Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
import { GroupDocDrawingCommand } from '../../../commands/commands/group-doc-drawing.command';
@@ -36,6 +37,8 @@ function createController(options: {
const featurePluginGroupUpdate$ = new Subject<any>();
const featurePluginUngroupUpdate$ = new Subject<any>();
const focus$ = new Subject<any[] | null>();
+ const add$ = new Subject<Array<{ unitId: string }>>();
+ const update$ = new Subject<Array<{ unitId: string }>>();
const changeEnd$ = new Subject<any>();
const editAreaChange$ = new Subject<void>();
const refreshDrawings$ = new Subject<unknown>();
@@ -47,6 +50,7 @@ function createController(options: {
const transformer = {
changeEnd$,
+ clearControlByIds: vi.fn(),
resetProps: vi.fn(),
};
const shapeByDrawingId = new Map<string, any>();
@@ -57,13 +61,17 @@ function createController(options: {
if (!shapeByDrawingId.has(drawingId)) {
shapeByDrawingId.set(drawingId, {
drawingId,
+ evented: true,
+ oKey: drawingId,
setOpacity: vi.fn(),
+ transformerConfig: {},
});
}
return [shapeByDrawingId.get(drawingId)];
}),
attachTransformerTo: vi.fn(),
detachTransformerFrom: vi.fn(),
+ getTransformer: vi.fn(() => transformer),
};
const viewModel = {
editAreaChange$,
@@ -76,6 +84,7 @@ function createController(options: {
};
const snapshot = {
body: {
+ dataStream: 'abcdefghij\r\n',
customBlocks: [
{ blockId: 'body-drawing', startIndex: 4 },
],
@@ -83,6 +92,7 @@ function createController(options: {
headers: {
'header-1': {
body: {
+ dataStream: 'abcdefghij\r\n',
customBlocks: [
{ blockId: 'header-drawing', startIndex: 2 },
],
@@ -92,6 +102,7 @@ function createController(options: {
footers: {
'footer-1': {
body: {
+ dataStream: 'abcdefghij\r\n',
customBlocks: [
{ blockId: 'footer-drawing', startIndex: 7 },
],
@@ -105,6 +116,10 @@ function createController(options: {
unit: {
getDrawings: vi.fn(() => snapshot.drawings),
getSnapshot: vi.fn(() => snapshot),
+ getBody: vi.fn(() => snapshot.body),
+ getSelfOrHeaderFooterModel: vi.fn((segmentId: string) => ({
+ getBody: () => segmentId ? snapshot.headers[segmentId as keyof typeof snapshot.headers]?.body ?? snapshot.footers[segmentId as keyof typeof snapshot.footers]?.body : snapshot.body,
+ })),
},
scene,
mainComponent: {
@@ -131,12 +146,16 @@ function createController(options: {
getDrawingByParam: vi.fn(({ drawingId }: { drawingId: string }) => options.drawings?.[drawingId]),
};
const drawingManagerService = {
+ add$,
featurePluginUpdate$,
featurePluginOrderUpdate$,
featurePluginGroupUpdate$,
featurePluginUngroupUpdate$,
focus$,
+ update$,
getDrawingByParam: vi.fn(({ drawingId }: { drawingId: string }) => options.drawings?.[drawingId]),
+ focusDrawing: vi.fn(),
+ getFocusDrawings: vi.fn(() => []),
};
const contextService = {
setContextValue: vi.fn(),
@@ -160,6 +179,7 @@ function createController(options: {
openFile: vi.fn(options.openFile ?? (async () => [])),
};
+ const permissionService = new PermissionService();
const controller = new DocDrawingUpdateRenderController(
context as never,
commandService as never,
@@ -168,6 +188,7 @@ function createController(options: {
imageIoService as never,
docDrawingService as never,
drawingManagerService as never,
+ permissionService,
contextService as never,
{ show: vi.fn() } as never,
{ t: vi.fn((key: string) => key) } as never,
@@ -191,6 +212,7 @@ function createController(options: {
getShape: (drawingId: string) => shapeByDrawingId.get(drawingId),
onBlur$,
onFocus$,
+ permissionService,
refreshDrawings$,
scene,
setEditArea: (value: DocumentEditArea) => {
@@ -200,6 +222,7 @@ function createController(options: {
isFocusing = value;
},
transformer,
+ update$,
};
}
@@ -394,6 +417,41 @@ describe('DocDrawingUpdateRenderController', () => {
expect(commandService.executeCommand).not.toHaveBeenCalled();
});
+ it('does not open the image picker when Document Edit is denied', async () => {
+ const openFile = vi.fn(async () => [{} as File]);
+ const { commandService, controller, permissionService } = createController({ openFile });
+ setDocumentPermissionValue(permissionService, 'doc-1', 'doc-1', UnitAction.Edit, false);
+
+ await expect(controller.insertDocImage()).resolves.toBe(false);
+
+ expect(openFile).not.toHaveBeenCalled();
+ expect(commandService.executeCommand).not.toHaveBeenCalled();
+ });
+
+ it('does not insert an image when Document Edit is revoked during upload', async () => {
+ let finishSaving: (value: unknown) => void = () => {};
+ const saveImage = vi.fn(() => new Promise<unknown>((resolve) => {
+ finishSaving = resolve;
+ }));
+ const { commandService, controller, permissionService } = createController({
+ openFile: async () => [{} as File],
+ saveImage,
+ });
+
+ const insertion = controller.insertDocImage();
+ await vi.waitFor(() => expect(saveImage).toHaveBeenCalledTimes(1));
+ setDocumentPermissionValue(permissionService, 'doc-1', 'doc-1', UnitAction.Edit, false);
+ finishSaving({
+ imageId: 'image-1',
+ imageSourceType: 'URL',
+ source: 'image.png',
+ base64Cache: 'data:image/png;base64,',
+ });
+
+ await expect(insertion).resolves.toBe(false);
+ expect(commandService.executeCommand).not.toHaveBeenCalled();
+ });
+
it('toggles drawing editability between body and header/footer edit areas', () => {
const bodyDrawing = {
drawingId: 'body-drawing',
@@ -423,6 +481,53 @@ describe('DocDrawingUpdateRenderController', () => {
expect(getShape('body-drawing').setOpacity).toHaveBeenLastCalledWith(0.5);
});
+ it('removes read-only drawings from picking and transformer interaction, then restores both', async () => {
+ const { getShape, permissionService, scene, transformer } = createController({
+ drawings: {
+ 'body-drawing': {
+ drawingId: 'body-drawing',
+ isMultiTransform: BooleanNumber.FALSE,
+ },
+ },
+ });
+
+ setDocumentPermissionValue(permissionService, 'doc-1', 'doc-1', UnitAction.Edit, false);
+
+ expect(getShape('body-drawing').evented).toBe(false);
+ expect(transformer.clearControlByIds).toHaveBeenCalledWith(['body-drawing']);
+ expect(getShape('body-drawing').transformerConfig).toMatchObject({
+ moveEnabled: false,
+ resizeEnabled: false,
+ rotateEnabled: false,
+ });
+
+ setDocumentPermissionValue(permissionService, 'doc-1', 'doc-1', UnitAction.Edit, true);
+ expect(getShape('body-drawing').evented).toBe(true);
+ expect(scene.attachTransformerTo).toHaveBeenLastCalledWith(getShape('body-drawing'));
+ expect(getShape('body-drawing').transformerConfig).not.toHaveProperty('moveEnabled', false);
+ expect(getShape('body-drawing').transformerConfig).not.toHaveProperty('resizeEnabled', false);
+ expect(getShape('body-drawing').transformerConfig).not.toHaveProperty('rotateEnabled', false);
+ });
+
+ it('keeps a remotely updated drawing non-interactive while local permission is read-only', async () => {
+ const { getShape, permissionService, scene, update$ } = createController({
+ drawings: {
+ 'body-drawing': {
+ drawingId: 'body-drawing',
+ isMultiTransform: BooleanNumber.FALSE,
+ },
+ },
+ });
+ setDocumentPermissionValue(permissionService, 'doc-1', 'doc-1', UnitAction.Edit, false);
+ scene.attachTransformerTo.mockClear();
+
+ update$.next([{ unitId: 'doc-1' }]);
+ await Promise.resolve();
+
+ expect(getShape('body-drawing').evented).toBe(false);
+ expect(scene.attachTransformerTo).not.toHaveBeenCalled();
+ });
+
it('keeps all drawings opaque while the document input is not focused', () => {
const bodyDrawing = {
drawingId: 'body-drawing',
diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts
index d1940e5b0d..089564f2e6 100644
--- a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts
+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts
@@ -18,7 +18,7 @@ import type { DocumentDataModel, ICommandInfo, IDocDrawingPosition, IDrawingPara
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { IDocDrawing, IDrawingDocTransform, IInsertDocDrawingCommandParams, ISetDocDrawingArrangeCommandParams, IUpdateDrawingDocTransformCommandParams } from '@univerjs/docs-drawing';
import type { IImageData } from '@univerjs/drawing';
-import type { Documents, Image, IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import type { BaseObject, Documents, Image, IRenderContext, IRenderModule, ITransformerConfig } from '@univerjs/engine-render';
import type { LocaleKey } from '../../locale/types';
import {
BooleanNumber,
@@ -30,12 +30,24 @@ import {
IImageIoService,
ImageUploadStatusType,
Inject,
+ IPermissionService,
LocaleService,
PositionedObjectLayoutType,
WrapTextType,
} from '@univerjs/core';
import { MessageType } from '@univerjs/design';
-import { buildDocTransform, docDrawingPositionToTransform, DocSelectionManagerService, DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
+import {
+ buildDocTransform,
+ canEditDocumentTargets,
+ docDrawingPositionToTransform,
+ DocSelectionManagerService,
+ DocSkeletonManagerService,
+ getDocumentDrawingSegmentId,
+ getDocumentEditTargetObjectIds,
+ getDocumentEntityParentPermissionObjectIds,
+ getDocumentEntityPermissionObjectId,
+ RichTextEditingMutation,
+} from '@univerjs/docs';
import { IDocDrawingService, InsertDocDrawingCommand, SetDocDrawingArrangeCommand, UpdateDrawingDocTransformCommand } from '@univerjs/docs-drawing';
import { DocSelectionRenderService } from '@univerjs/docs-ui';
import {
@@ -61,6 +73,10 @@ interface IImageInsertPosition {
}
export class DocDrawingUpdateRenderController extends Disposable implements IRenderModule {
+ private readonly _editableTransformerConfigs = new WeakMap<BaseObject, ITransformerConfig>();
+ private readonly _editableEventedStates = new WeakMap<BaseObject, boolean>();
+ private _editStatusUpdateScheduled = false;
+
constructor(
private readonly _context: IRenderContext<DocumentDataModel>,
@ICommandService private readonly _commandService: ICommandService,
@@ -69,6 +85,7 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
@IImageIoService private readonly _imageIoService: IImageIoService,
@IDocDrawingService private readonly _docDrawingService: IDocDrawingService,
@IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
+ @IPermissionService private readonly _permissionService: IPermissionService,
@IContextService private readonly _contextService: IContextService,
@IMessageService private readonly _messageService: IMessageService,
@Inject(LocaleService) private readonly _localeService: LocaleService,
@@ -84,6 +101,16 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
this._focusDrawingListener();
this._transformDrawingListener();
this._editAreaChangeListener();
+ const scheduleEditStatusUpdate = (drawings: Array<{ unitId: string }>) => {
+ if (drawings.some((drawing) => drawing.unitId === this._context?.unitId)) {
+ this._scheduleDrawingsEditStatusUpdate();
+ }
+ };
+ this.disposeWithMe(this._drawingManagerService.add$.subscribe(scheduleEditStatusUpdate));
+ this.disposeWithMe(this._drawingManagerService.update$.subscribe(scheduleEditStatusUpdate));
+ this.disposeWithMe(this._permissionService.permissionPointUpdate$.subscribe(() => {
+ this._updateDrawingsEditStatus();
+ }));
}
override dispose(): void {
@@ -95,12 +122,15 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
async insertDocImage(): Promise<boolean> {
const insertPosition = this._getCurrentImageInsertPosition();
const textRange = this._getCurrentImageInsertTextRange();
+ if (!this._canInsertDocImage(textRange)) {
+ return false;
+ }
const files = await this._fileOpenerService.openFile({
multiple: true,
accept: DRAWING_IMAGE_ALLOW_IMAGE_LIST.map((image) => `.${image.replace('image/', '')}`).join(','),
});
- if (this._disposed) {
+ if (this._disposed || !this._canInsertDocImage(textRange)) {
return false;
}
@@ -152,7 +182,7 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
});
}
- if (this._disposed || imageParams.length === 0) {
+ if (this._disposed || imageParams.length === 0 || !this._canInsertDocImage(textRange)) {
return false;
}
@@ -166,7 +196,7 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
const { imageId, imageSourceType, source, base64Cache } = imageParam;
const { width, height, image } = await getImageSize(base64Cache || '');
- if (this._disposed) {
+ if (this._disposed || !this._canInsertDocImage(textRange)) {
return false;
}
@@ -418,7 +448,7 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
this._docDrawingService.focusDrawing(params);
this._setDrawingSelections(params);
const prevSegmentId = this._docSelectionRenderService.getSegment();
- const segmentId = this._findSegmentIdByDrawingId(params[0].drawingId);
+ const segmentId = getDocumentDrawingSegmentId(this._context.unit, params[0].drawingId);
// Change segmentId when click drawing in different segment.
if (prevSegmentId !== segmentId) {
@@ -437,32 +467,6 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
);
}
- private _findSegmentIdByDrawingId(drawingId: string) {
- const { unit: DocDataModel } = this._context;
-
- const { body, headers = {}, footers = {} } = DocDataModel.getSnapshot();
-
- const bodyCustomBlocks = body?.customBlocks ?? [];
-
- if (bodyCustomBlocks.some((b) => b.blockId === drawingId)) {
- return '';
- }
-
- for (const headerId of Object.keys(headers)) {
- if (headers[headerId].body.customBlocks?.some((b) => b.blockId === drawingId)) {
- return headerId;
- }
- }
-
- for (const footerId of Object.keys(footers)) {
- if (footers[footerId].body.customBlocks?.some((b) => b.blockId === drawingId)) {
- return footerId;
- }
- }
-
- return '';
- }
-
// Update drawings edit status and opacity. You can not edit header footer images when you are editing body. and vice verse.
private _updateDrawingsEditStatus() {
if (!this._context) return;
@@ -481,15 +485,23 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
const { drawings = {} } = snapshot;
const isEditBody = viewModel.getEditArea() === DocumentEditArea.BODY;
const isDocInputFocusing = this._docSelectionRenderService.isFocusing;
+ const readOnlyDrawingIds = new Set<string>();
for (const key of Object.keys(drawings)) {
const drawing = drawings[key];
+ const segmentId = getDocumentDrawingSegmentId(docDataModel, drawing.drawingId);
+ const editable = canEditDocumentTargets(this._permissionService, unitId, [
+ ...getDocumentEntityParentPermissionObjectIds(docDataModel, segmentId, 'drawing', drawing.drawingId),
+ getDocumentEntityPermissionObjectId(segmentId, 'drawing', drawing.drawingId),
+ ]);
+ this._recordReadOnlyDrawing(readOnlyDrawingIds, drawing.drawingId, editable);
const objectKey = getDrawingShapeKeyByDrawingSearch({ unitId, drawingId: drawing.drawingId, subUnitId: unitId });
const drawingShapes = scene.fuzzyMathObjects(objectKey, true);
if (drawingShapes.length) {
for (const shape of drawingShapes) {
scene.detachTransformerFrom(shape);
+ this._setTransformerEditable(shape, editable);
try {
(shape as Image).setOpacity(isDocInputFocusing ? 0.5 : 1);
} catch {
@@ -501,9 +513,7 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
(isEditBody && drawing.isMultiTransform !== BooleanNumber.TRUE)
|| (!isEditBody && drawing.isMultiTransform === BooleanNumber.TRUE)
) {
- if (drawing.allowTransform !== false) {
- scene.attachTransformerTo(shape);
- }
+ this._attachTransformerIfEditable(shape, editable, drawing.allowTransform);
try {
(shape as Image).setOpacity(1);
@@ -513,6 +523,84 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
}
}
}
+
+ this._clearReadOnlyDrawingFocus(unitId, readOnlyDrawingIds);
+ }
+
+ private _recordReadOnlyDrawing(readOnlyDrawingIds: Set<string>, drawingId: string, editable: boolean): void {
+ if (!editable) {
+ readOnlyDrawingIds.add(drawingId);
+ }
+ }
+
+ private _attachTransformerIfEditable(shape: BaseObject, editable: boolean, allowTransform?: boolean): void {
+ if (editable && allowTransform !== false) {
+ this._context.scene.attachTransformerTo(shape);
+ }
+ }
+
+ private _clearReadOnlyDrawingFocus(unitId: string, readOnlyDrawingIds: Set<string>): void {
+ if (readOnlyDrawingIds.size === 0) {
+ return;
+ }
+ const focusedDrawings = this._drawingManagerService.getFocusDrawings();
+ const editableFocus = focusedDrawings.filter((drawing) =>
+ drawing.unitId !== unitId || !readOnlyDrawingIds.has(drawing.drawingId));
+ if (editableFocus.length !== focusedDrawings.length) {
+ this._drawingManagerService.focusDrawing(editableFocus);
+ }
+ }
+
+ private _setTransformerEditable(shape: BaseObject, editable: boolean): void {
+ if (editable) {
+ const config = this._editableTransformerConfigs.get(shape);
+ if (config) {
+ shape.transformerConfig = config;
+ this._editableTransformerConfigs.delete(shape);
+ }
+ const evented = this._editableEventedStates.get(shape);
+ if (evented !== undefined) {
+ shape.evented = evented;
+ this._editableEventedStates.delete(shape);
+ }
+ return;
+ }
+
+ if (!this._editableTransformerConfigs.has(shape)) {
+ this._editableTransformerConfigs.set(shape, shape.transformerConfig);
+ }
+ if (!this._editableEventedStates.has(shape)) {
+ this._editableEventedStates.set(shape, shape.evented);
+ }
+ shape.evented = false;
+ this._context.scene.getTransformer()?.clearControlByIds([shape.oKey]);
+ shape.transformerConfig = {
+ ...shape.transformerConfig,
+ moveEnabled: false,
+ resizeEnabled: false,
+ rotateEnabled: false,
+ };
+ }
+
+ private _scheduleDrawingsEditStatusUpdate(): void {
+ if (this._editStatusUpdateScheduled) {
+ return;
+ }
+ this._editStatusUpdateScheduled = true;
+ queueMicrotask(() => {
+ this._editStatusUpdateScheduled = false;
+ if (!this._disposed) {
+ this._updateDrawingsEditStatus();
+ }
+ });
+ }
+
+ private _canInsertDocImage(textRange: Nullable<ITextRangeParam>): boolean {
+ const { unit, unitId } = this._context;
+ const objectIds = textRange?.startOffset == null || textRange.endOffset == null
+ ? []
+ : getDocumentEditTargetObjectIds(unit, textRange.segmentId ?? '', textRange);
+ return canEditDocumentTargets(this._permissionService, unitId, objectIds);
}
private _editAreaChangeListener() {
diff --git a/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts b/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts
index 4be67c9adf..6a72817439 100644
--- a/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts
+++ b/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts
@@ -23,12 +23,19 @@ import {
ICommandService,
IContextService,
Inject,
+ IPermissionService,
isInternalEditorID,
IUniverInstanceService,
RxDisposable,
toDisposable,
UniverInstanceType,
} from '@univerjs/core';
+import {
+ canEditDocumentTargets,
+ getDocumentDrawingSegmentId,
+ getDocumentEntityParentPermissionObjectIds,
+ getDocumentEntityPermissionObjectId,
+} from '@univerjs/docs';
import { IDocDrawingAdapterService, RemoveDocDrawingCommand } from '@univerjs/docs-drawing';
import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
import { IDrawingManagerService } from '@univerjs/drawing';
@@ -61,8 +68,8 @@ export class DocDrawingPopupMenuController extends RxDisposable {
@IDocDrawingAdapterService private readonly _drawingAdapterService: IDocDrawingAdapterService,
@Inject(DocDrawingFloatingToolbarAdapterService) private readonly _floatingToolbarAdapterService: DocDrawingFloatingToolbarAdapterService,
@ICommandService private readonly _commandService: ICommandService,
- @IMenuManagerService private readonly _menuManagerService: IMenuManagerService
-
+ @IMenuManagerService private readonly _menuManagerService: IMenuManagerService,
+ @IPermissionService private readonly _permissionService: IPermissionService
) {
super();
@@ -92,6 +99,14 @@ export class DocDrawingPopupMenuController extends RxDisposable {
}
})
);
+ this.disposeWithMe(this._permissionService.permissionPointUpdate$.subscribe(() => {
+ if (this._drawingManagerService.getFocusDrawings().some((drawing) =>
+ this._univerInstanceService.getUnitType(drawing.unitId) === UniverInstanceType.UNIVER_DOC &&
+ !this._canEditDrawing(drawing.unitId, drawing.drawingId)
+ )) {
+ this._clearPopups();
+ }
+ }));
this.disposeWithMe(
this._univerInstanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC).pipe(takeUntil(this.dispose$)).subscribe((documentDataModel) => this._create(documentDataModel))
@@ -214,6 +229,9 @@ export class DocDrawingPopupMenuController extends RxDisposable {
}
const { unitId, subUnitId, drawingId, drawingType } = drawingParam;
+ if (!this._canEditDrawing(unitId, drawingId)) {
+ return;
+ }
const isImage = drawingType === DrawingTypeEnum.DRAWING_IMAGE;
// Charts use the document toolbar placement, while retaining chart-specific actions and controls.
const isChart = drawingType === DrawingTypeEnum.DRAWING_CHART;
@@ -262,6 +280,21 @@ export class DocDrawingPopupMenuController extends RxDisposable {
return disposable;
}
+ private _canEditDrawing(unitId: string, drawingId: string): boolean {
+ const documentDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(
+ unitId,
+ UniverInstanceType.UNIVER_DOC
+ );
+ if (!documentDataModel) {
+ return false;
+ }
+ const segmentId = getDocumentDrawingSegmentId(documentDataModel, drawingId);
+ return canEditDocumentTargets(this._permissionService, unitId, [
+ ...getDocumentEntityParentPermissionObjectIds(documentDataModel, segmentId, 'drawing', drawingId),
+ getDocumentEntityPermissionObjectId(segmentId, 'drawing', drawingId),
+ ]);
+ }
+
private _getDrawingPopupMenuItems(unitId: string, subUnitId: string, drawingId: string, drawingType: number) {
const drawing = this._drawingManagerService.getDrawingByParam({ unitId, subUnitId, drawingId }) as IDocDrawing | null;
const floatingToolbarMenuItems = drawing
diff --git a/packages/docs-hyper-link-ui/package.json b/packages/docs-hyper-link-ui/package.json
index c531ffd8aa..b7762e6911 100644
--- a/packages/docs-hyper-link-ui/package.json
+++ b/packages/docs-hyper-link-ui/package.json
@@ -81,6 +81,7 @@
"@univerjs/docs-ui": "workspace:*",
"@univerjs/engine-render": "workspace:*",
"@univerjs/icons": "1.38.0",
+ "@univerjs/protocol": "workspace:*",
"@univerjs/ui": "workspace:*"
},
"devDependencies": {
diff --git a/packages/docs-hyper-link-ui/src/commands/operations/__tests__/popup.operation.spec.ts b/packages/docs-hyper-link-ui/src/commands/operations/__tests__/popup.operation.spec.ts
index b8d5d66ed4..fd4d3ba5e7 100644
--- a/packages/docs-hyper-link-ui/src/commands/operations/__tests__/popup.operation.spec.ts
+++ b/packages/docs-hyper-link-ui/src/commands/operations/__tests__/popup.operation.spec.ts
@@ -105,7 +105,7 @@ describe('doc hyperlink popup operations', () => {
const result = await commandService.executeCommand(ShowDocHyperLinkEditPopupOperation.id);
expect(result).toBe(true);
- expect(popupService.editing).toBeUndefined();
+ expect(popupService.editing).toBeNull();
});
it('keeps the hyperlink editor closed when there is no selected text', async () => {
diff --git a/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts b/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts
index 87df8a1ea1..f1202eebc8 100644
--- a/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts
+++ b/packages/docs-hyper-link-ui/src/commands/operations/popup.operation.ts
@@ -62,7 +62,7 @@ export const ShowDocHyperLinkEditPopupOperation: ICommand<IShowDocHyperLinkEditP
if (!unitId) {
return false;
}
- hyperLinkService.showEditPopup(unitId, linkInfo);
+ hyperLinkService.showEditPopup(unitId, linkInfo ?? null);
return true;
},
};
diff --git a/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts b/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts
index 07b82d334b..9d3044a4db 100644
--- a/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts
+++ b/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts
@@ -25,11 +25,14 @@ import {
IContextService,
ILogService,
Injector,
+ IPermissionService,
IUniverInstanceService,
+ PermissionService,
UniverInstanceService,
} from '@univerjs/core';
-import { DocSelectionManagerService } from '@univerjs/docs';
+import { DocSelectionManagerService, setDocumentPermissionValue } from '@univerjs/docs';
import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
+import { UnitAction } from '@univerjs/protocol';
import { describe, expect, it } from 'vitest';
import { DocHyperLinkPopupService } from '../hyper-link-popup.service';
@@ -53,6 +56,7 @@ function createService() {
injector.add([IContextService, { useClass: ContextService }]);
injector.add([ICommandService, { useClass: CommandService }]);
injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
+ injector.add([IPermissionService, { useClass: PermissionService }]);
injector.add([DocCanvasPopManagerService, { useClass: CapturingDocCanvasPopManagerServiceCtor }]);
injector.add([DocSelectionManagerService]);
injector.add([DocHyperLinkPopupService]);
@@ -61,12 +65,14 @@ function createService() {
const selectionManager = injector.get(DocSelectionManagerService);
selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: 'doc-1', subUnitId: 'doc-1' });
const popupManager = injector.get(DocCanvasPopManagerService) as unknown as CapturingDocCanvasPopManagerService;
+ const permissionService = injector.get(IPermissionService);
return {
service: injector.get(DocHyperLinkPopupService),
selectionManager,
attached: popupManager.attached,
disposed: popupManager.disposed,
+ permissionService,
};
}
@@ -213,4 +219,18 @@ describe('DocHyperLinkPopupService', () => {
expect(service.showing).toEqual(link);
expect(attached).toHaveLength(2);
});
+
+ it('does not open an edit popup without document edit permission', () => {
+ const { service, attached, permissionService } = createService();
+ setDocumentPermissionValue(
+ permissionService,
+ 'doc-1',
+ 'doc-1',
+ UnitAction.Edit,
+ false
+ );
+
+ expect(service.showEditPopup('doc-1', null)).toBeNull();
+ expect(attached).toEqual([]);
+ });
});
diff --git a/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts b/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts
index 52035d8662..21f5f43792 100644
--- a/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts
+++ b/packages/docs-hyper-link-ui/src/services/hyper-link-popup.service.ts
@@ -14,9 +14,8 @@
* limitations under the License.
*/
-import type { DocumentDataModel, IDisposable, Nullable } from '@univerjs/core';
-import { Disposable, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
-import { DocSelectionManagerService } from '@univerjs/docs';
+import { Disposable, DocumentDataModel, Inject, IPermissionService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { canEditDocumentTargets, DocSelectionManagerService, getDocumentEntityParentPermissionObjectIds, getDocumentEntityPermissionObjectId } from '@univerjs/docs';
import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
import { BehaviorSubject } from 'rxjs';
import { DocHyperLinkEdit } from '../views/DocHyperLinkEdit';
@@ -31,21 +30,24 @@ export interface ILinkInfo {
endIndex: number;
}
+type LinkPopupDisposable = ReturnType<DocCanvasPopManagerService['attachPopupToRange']>;
+
export class DocHyperLinkPopupService extends Disposable {
- private readonly _editingLink$ = new BehaviorSubject<Nullable<ILinkInfo>>(null);
- private readonly _showingLink$ = new BehaviorSubject<Nullable<ILinkInfo>>(null);
+ private readonly _editingLink$ = new BehaviorSubject<ILinkInfo | null>(null);
+ private readonly _showingLink$ = new BehaviorSubject<ILinkInfo | null>(null);
readonly editingLink$ = this._editingLink$.asObservable();
readonly showingLink$ = this._showingLink$.asObservable();
- private _editPopup: Nullable<IDisposable> = null;
- private _infoPopup: Nullable<IDisposable> = null;
+ private _editPopup: LinkPopupDisposable | null = null;
+ private _infoPopup: LinkPopupDisposable | null = null;
private _infoPopupSuppressed = false;
private _infoPopupSuppressionTimer: ReturnType<typeof setTimeout> | null = null;
constructor(
@Inject(DocCanvasPopManagerService) private readonly _docCanvasPopupManagerService: DocCanvasPopManagerService,
@Inject(DocSelectionManagerService) private readonly _textSelectionManagerService: DocSelectionManagerService,
- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
+ @IPermissionService private readonly _permissionService: IPermissionService
) {
super();
@@ -56,6 +58,17 @@ export class DocHyperLinkPopupService extends Disposable {
this._editingLink$.complete();
this._showingLink$.complete();
});
+
+ this.disposeWithMe(this._permissionService.permissionPointUpdate$.subscribe(() => {
+ const editing = this.editing;
+ if (editing && !this.canEditLink(editing.unitId, editing)) {
+ this.hideEditPopup();
+ }
+ const showing = this.showing;
+ if (showing) {
+ this._showingLink$.next({ ...showing });
+ }
+ }));
}
get editing() {
@@ -66,7 +79,10 @@ export class DocHyperLinkPopupService extends Disposable {
return this._showingLink$.value;
}
- showEditPopup(unitId: string, linkInfo: Nullable<ILinkInfo>): Nullable<IDisposable> {
+ showEditPopup(unitId: string, linkInfo: ILinkInfo | null): LinkPopupDisposable | null {
+ if (!this.canEditLink(unitId, linkInfo)) {
+ return null;
+ }
if (this._editPopup) {
this._editPopup.dispose();
}
@@ -111,7 +127,7 @@ export class DocHyperLinkPopupService extends Disposable {
this._editPopup?.dispose();
}
- showInfoPopup(info: ILinkInfo): Nullable<IDisposable> {
+ showInfoPopup(info: ILinkInfo): LinkPopupDisposable | null | undefined {
if (this._infoPopupSuppressed) {
return;
}
@@ -131,8 +147,8 @@ export class DocHyperLinkPopupService extends Disposable {
if (this._infoPopup) {
this._infoPopup.dispose();
}
- const doc = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
- if (!doc) {
+ const doc = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);
+ if (!(doc instanceof DocumentDataModel)) {
return;
}
this._showingLink$.next({ unitId, linkId, segmentId, segmentPage, startIndex, endIndex });
@@ -176,4 +192,19 @@ export class DocHyperLinkPopupService extends Disposable {
this._infoPopupSuppressionTimer = null;
}, 0);
}
+
+ canEditLink(unitId: string, linkInfo: ILinkInfo | null): boolean {
+ const document = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);
+ if (!(document instanceof DocumentDataModel)) {
+ return false;
+ }
+ if (!linkInfo) {
+ return canEditDocumentTargets(this._permissionService, unitId, []);
+ }
+ const segmentId = linkInfo.segmentId ?? '';
+ return canEditDocumentTargets(this._permissionService, unitId, [
+ ...getDocumentEntityParentPermissionObjectIds(document, segmentId, 'custom-range', linkInfo.linkId),
+ getDocumentEntityPermissionObjectId(segmentId, 'custom-range', linkInfo.linkId),
+ ]);
+ }
}
diff --git a/packages/docs-hyper-link-ui/src/views/DocLinkPopup.tsx b/packages/docs-hyper-link-ui/src/views/DocLinkPopup.tsx
index f00d28d7b3..3dbabac0dc 100644
--- a/packages/docs-hyper-link-ui/src/views/DocLinkPopup.tsx
+++ b/packages/docs-hyper-link-ui/src/views/DocLinkPopup.tsx
@@ -14,17 +14,20 @@
* limitations under the License.
*/
-import type { DocumentDataModel } from '@univerjs/core';
import type { LocaleKey } from '../locale/types';
import {
CustomRangeType,
+ DocumentDataModel,
ICommandService,
+ IPermissionService,
IUniverInstanceService,
LocaleService,
UniverInstanceType,
} from '@univerjs/core';
-import { borderClassName, clsx, MessageType, Tooltip } from '@univerjs/design';
+import { borderClassName, Button, clsx, MessageType, Tooltip } from '@univerjs/design';
+import { getDocumentPermissionValue } from '@univerjs/docs';
import { CopyIcon, LinkIcon, UnlinkIcon, WriteIcon } from '@univerjs/icons';
+import { UnitAction } from '@univerjs/protocol';
import { IMessageService, useDependency, useObservable } from '@univerjs/ui';
import { DeleteDocHyperLinkCommand } from '../commands/commands/delete-link.command';
import { ShowDocHyperLinkEditPopupOperation } from '../commands/operations/popup.operation';
@@ -37,13 +40,16 @@ export const DocLinkPopup = () => {
const localeService = useDependency(LocaleService);
const currentPopup = useObservable(hyperLinkService.showingLink$);
const univerInstanceService = useDependency(IUniverInstanceService);
+ const permissionService = useDependency(IPermissionService);
if (!currentPopup) {
return null;
}
const { unitId, linkId, segmentId, startIndex, endIndex } = currentPopup;
- const doc = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
- const body = doc?.getSelfOrHeaderFooterModel(segmentId)?.getBody();
+ const doc = univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);
+ const body = doc instanceof DocumentDataModel
+ ? doc.getSelfOrHeaderFooterModel(segmentId)?.getBody()
+ : undefined;
const link = body?.customRanges?.find((range) => range.rangeId === linkId && range.rangeType === CustomRangeType.HYPERLINK && range.startIndex === startIndex && range.endIndex === endIndex);
if (!link) {
@@ -51,7 +57,8 @@ export const DocLinkPopup = () => {
}
const url = link.properties?.url;
-
+ const canEdit = hyperLinkService.canEditLink(unitId, currentPopup);
+ const canCopy = getDocumentPermissionValue(permissionService, unitId, unitId, UnitAction.Copy);
return (
<div
className={clsx(`
@@ -84,11 +91,19 @@ export const DocLinkPopup = () => {
</Tooltip>
</div>
<div className="univer-flex univer-h-6 univer-flex-[0_0_auto] univer-items-center univer-justify-center">
- <div
- className={`
- univer-ml-2 univer-flex univer-size-6 univer-cursor-pointer univer-items-center
- univer-justify-center univer-rounded univer-text-base
- `}
+ <Button
+ type="button"
+ variant="text"
+ size="small"
+ aria-label={localeService.t<LocaleKey>('docs-hyper-link-ui.info.copy')}
+ className="
+ univer-ml-2 !univer-flex univer-size-6 !univer-rounded !univer-border-0 !univer-bg-transparent
+ !univer-p-0 !univer-text-base !univer-font-normal
+ hover:!univer-bg-transparent
+ active:!univer-bg-transparent
+ disabled:!univer-pointer-events-auto disabled:!univer-opacity-40
+ "
+ disabled={!canCopy}
onClick={() => {
navigator.clipboard.writeText(url);
messageService.show({
@@ -100,40 +115,43 @@ export const DocLinkPopup = () => {
<Tooltip placement="bottom" title={localeService.t<LocaleKey>('docs-hyper-link-ui.info.copy')}>
<CopyIcon />
</Tooltip>
-
- </div>
- <div
- className={`
- univer-ml-2 univer-flex univer-size-6 univer-cursor-pointer univer-items-center
- univer-justify-center univer-rounded univer-text-base
- `}
- onClick={() => {
- commandService.executeCommand(ShowDocHyperLinkEditPopupOperation.id, {
- link: currentPopup,
- });
- }}
- >
- <Tooltip placement="bottom" title={localeService.t<LocaleKey>('docs-hyper-link-ui.info.edit')}>
- <WriteIcon />
- </Tooltip>
- </div>
- <div
- className={`
- univer-ml-2 univer-flex univer-size-6 univer-cursor-pointer univer-items-center
- univer-justify-center univer-rounded univer-text-base
- `}
- onClick={() => {
- commandService.executeCommand(DeleteDocHyperLinkCommand.id, {
- unitId,
- linkId: link.rangeId,
- segmentId,
- });
- }}
- >
- <Tooltip placement="bottom" title={localeService.t<LocaleKey>('docs-hyper-link-ui.info.cancel')}>
- <UnlinkIcon />
- </Tooltip>
- </div>
+ </Button>
+ {canEdit && (
+ <>
+ <div
+ className={`
+ univer-ml-2 univer-flex univer-size-6 univer-cursor-pointer univer-items-center
+ univer-justify-center univer-rounded univer-text-base
+ `}
+ onClick={() => {
+ commandService.executeCommand(ShowDocHyperLinkEditPopupOperation.id, {
+ link: currentPopup,
+ });
+ }}
+ >
+ <Tooltip placement="bottom" title={localeService.t<LocaleKey>('docs-hyper-link-ui.info.edit')}>
+ <WriteIcon />
+ </Tooltip>
+ </div>
+ <div
+ className={`
+ univer-ml-2 univer-flex univer-size-6 univer-cursor-pointer univer-items-center
+ univer-justify-center univer-rounded univer-text-base
+ `}
+ onClick={() => {
+ commandService.executeCommand(DeleteDocHyperLinkCommand.id, {
+ unitId,
+ linkId: link.rangeId,
+ segmentId,
+ });
+ }}
+ >
+ <Tooltip placement="bottom" title={localeService.t<LocaleKey>('docs-hyper-link-ui.info.cancel')}>
+ <UnlinkIcon />
+ </Tooltip>
+ </div>
+ </>
+ )}
</div>
</div>
);
diff --git a/packages/docs-hyper-link-ui/src/views/__tests__/DocLinkPopup.spec.tsx b/packages/docs-hyper-link-ui/src/views/__tests__/DocLinkPopup.spec.tsx
index 3b99a4f23f..bfcde3a0eb 100644
--- a/packages/docs-hyper-link-ui/src/views/__tests__/DocLinkPopup.spec.tsx
+++ b/packages/docs-hyper-link-ui/src/views/__tests__/DocLinkPopup.spec.tsx
@@ -19,6 +19,7 @@ import type { Root } from 'react-dom/client';
import {
CustomRangeType,
ICommandService,
+ IPermissionService,
IUniverInstanceService,
LocaleService,
LocaleType,
@@ -26,9 +27,10 @@ import {
Univer,
UniverInstanceType,
} from '@univerjs/core';
-import { DocSelectionManagerService, DocStateEmitService, RichTextEditingMutation } from '@univerjs/docs';
+import { DocSelectionManagerService, DocStateEmitService, RichTextEditingMutation, setDocumentPermissionValue } from '@univerjs/docs';
import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
+import { UnitAction } from '@univerjs/protocol';
import { IMessageService, RediContext } from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
@@ -232,6 +234,28 @@ describe('DocLinkPopup', () => {
});
});
+ it('disables the copy action when document copy permission is denied', () => {
+ currentTestBed = createPopupTestBed();
+ setDocumentPermissionValue(
+ currentTestBed.injector.get(IPermissionService),
+ UNIT_ID,
+ UNIT_ID,
+ UnitAction.Copy,
+ false
+ );
+ showExistingLink(currentTestBed);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ renderPopup(root, container, currentTestBed);
+
+ const copy = container.querySelector<HTMLButtonElement>('button[aria-label="Copy"]');
+ expect(copy).toBeInstanceOf(HTMLButtonElement);
+ expect(copy?.dataset.uComp).toBe('button');
+ expect(copy?.disabled).toBe(true);
+ });
+
it('removes the displayed hyperlink while keeping the document text', async () => {
currentTestBed = createPopupTestBed();
showExistingLink(currentTestBed);
diff --git a/packages/docs-thread-comment-ui/package.json b/packages/docs-thread-comment-ui/package.json
index abca0c1a06..c94e44da9d 100644
--- a/packages/docs-thread-comment-ui/package.json
+++ b/packages/docs-thread-comment-ui/package.json
@@ -81,6 +81,7 @@
"@univerjs/drawing": "workspace:*",
"@univerjs/engine-render": "workspace:*",
"@univerjs/icons": "1.38.0",
+ "@univerjs/protocol": "workspace:*",
"@univerjs/thread-comment": "workspace:*",
"@univerjs/thread-comment-ui": "workspace:*",
"@univerjs/ui": "workspace:*"
diff --git a/packages/docs-thread-comment-ui/src/menu/menu.ts b/packages/docs-thread-comment-ui/src/menu/menu.ts
index 1b38f56302..209301ce99 100644
--- a/packages/docs-thread-comment-ui/src/menu/menu.ts
+++ b/packages/docs-thread-comment-ui/src/menu/menu.ts
@@ -14,21 +14,35 @@
* limitations under the License.
*/
-import type { IAccessor } from '@univerjs/core';
-import type { IMenuButtonItem } from '@univerjs/ui';
-import type { LocaleKey } from '../locale/types';
-import { IUniverInstanceService, SHEET_EDITOR_UNITS, UniverInstanceType } from '@univerjs/core';
-import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
+import { IPermissionService, IUniverInstanceService, SHEET_EDITOR_UNITS, UniverInstanceType } from '@univerjs/core';
+import { DocSelectionManagerService, DocSkeletonManagerService, getDocumentPermissionValue } from '@univerjs/docs';
import { DocumentEditArea, IRenderManagerService, withCurrentTypeOfRenderer } from '@univerjs/engine-render';
+import { UnitAction } from '@univerjs/protocol';
import { getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';
-import { debounceTime, Observable } from 'rxjs';
+import { combineLatest, debounceTime, map, startWith } from 'rxjs';
import {
AddDocDrawingCommentOperation,
StartAddCommentOperation,
ToggleCommentPanelOperation,
} from '../commands/operations/show-comment-panel.operation';
-export function AddDocDrawingCommentMenuItemFactory(accessor: IAccessor): IMenuButtonItem<LocaleKey> {
+type MenuAccessor = Parameters<typeof getMenuHiddenObservable>[0];
+
+function getCommentPermissionDisabled$(accessor: MenuAccessor) {
+ const instanceService = accessor.get(IUniverInstanceService);
+ const permissionService = accessor.get(IPermissionService);
+ return combineLatest([
+ instanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_DOC),
+ permissionService.permissionPointUpdate$.pipe(startWith(undefined)),
+ ]).pipe(map(([document]) => !document || !getDocumentPermissionValue(
+ permissionService,
+ document.getUnitId(),
+ document.getUnitId(),
+ UnitAction.Comment
+ )));
+}
+
+export function AddDocDrawingCommentMenuItemFactory(accessor: MenuAccessor) {
return {
id: AddDocDrawingCommentOperation.id,
type: MenuItemType.BUTTON,
@@ -36,16 +50,28 @@ export function AddDocDrawingCommentMenuItemFactory(accessor: IAccessor): IMenuB
title: 'docs-thread-comment-ui.panel.addComment',
tooltip: 'docs-thread-comment-ui.panel.addComment',
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
+ disabled$: getCommentPermissionDisabled$(accessor),
};
}
-export const shouldDisableAddComment = (accessor: IAccessor) => {
+export const shouldDisableAddComment = (accessor: MenuAccessor) => {
const renderManagerService = accessor.get(IRenderManagerService);
const docSelectionManagerService = accessor.get(DocSelectionManagerService);
+ const instanceService = accessor.get(IUniverInstanceService);
+ const permissionService = accessor.get(IPermissionService);
+ const document = instanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC);
+ if (!document || !getDocumentPermissionValue(
+ permissionService,
+ document.getUnitId(),
+ document.getUnitId(),
+ UnitAction.Comment
+ )) {
+ return true;
+ }
const skeleton = withCurrentTypeOfRenderer(
UniverInstanceType.UNIVER_DOC,
DocSkeletonManagerService,
- accessor.get(IUniverInstanceService),
+ instanceService,
renderManagerService
)?.getSkeleton();
@@ -63,7 +89,7 @@ export const shouldDisableAddComment = (accessor: IAccessor) => {
return false;
};
-export function AddDocCommentMenuItemFactory(accessor: IAccessor): IMenuButtonItem<LocaleKey> {
+export function AddDocCommentMenuItemFactory(accessor: MenuAccessor) {
return {
id: StartAddCommentOperation.id,
type: MenuItemType.BUTTON,
@@ -71,20 +97,19 @@ export function AddDocCommentMenuItemFactory(accessor: IAccessor): IMenuButtonIt
title: 'docs-thread-comment-ui.panel.addComment',
tooltip: 'docs-thread-comment-ui.panel.addComment',
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC, undefined, SHEET_EDITOR_UNITS),
- disabled$: new Observable(function (subscribe) {
- const textSelectionService = accessor.get(DocSelectionManagerService);
- const observer = textSelectionService.textSelection$.pipe(debounceTime(16)).subscribe(() => {
- subscribe.next(shouldDisableAddComment(accessor));
- });
-
- return () => {
- observer.unsubscribe();
- };
- }),
+ disabled$: combineLatest([
+ accessor.get(DocSelectionManagerService).textSelection$.pipe(
+ debounceTime(16),
+ map(() => shouldDisableAddComment(accessor)),
+ startWith(shouldDisableAddComment(accessor))
+ ),
+ getCommentPermissionDisabled$(accessor),
+ ]).pipe(map(([selectionDisabled, permissionDisabled]) =>
+ selectionDisabled || permissionDisabled)),
};
}
-export function ToolbarDocCommentMenuItemFactory(accessor: IAccessor): IMenuButtonItem<LocaleKey> {
+export function ToolbarDocCommentMenuItemFactory(accessor: MenuAccessor) {
return {
id: ToggleCommentPanelOperation.id,
type: MenuItemType.BUTTON,
diff --git a/packages/docs-thread-comment-ui/src/views/DocThreadCommentPanel.tsx b/packages/docs-thread-comment-ui/src/views/DocThreadCommentPanel.tsx
index 1dd87ecf29..dc177ad479 100644
--- a/packages/docs-thread-comment-ui/src/views/DocThreadCommentPanel.tsx
+++ b/packages/docs-thread-comment-ui/src/views/DocThreadCommentPanel.tsx
@@ -17,14 +17,14 @@
import type { DocumentDataModel } from '@univerjs/core';
import type { IAddDocCommentComment } from '../commands/commands/add-doc-comment.command';
import type { IDeleteDocCommentComment } from '../commands/commands/delete-doc-comment.command';
-import { ICommandService, Injector, isInternalEditorID, IUniverInstanceService, UniverInstanceType, UserManagerService } from '@univerjs/core';
+import { ICommandService, Injector, IPermissionService, isInternalEditorID, IUniverInstanceService, UniverInstanceType, UserManagerService } from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
import { DEFAULT_DOC_SUBUNIT_ID } from '@univerjs/docs-thread-comment';
import { deserializeThreadCommentAnchor, serializeThreadCommentAnchor, ThreadCommentAnchorKind, ThreadCommentModel } from '@univerjs/thread-comment';
import { ThreadCommentDraftService, ThreadCommentPanel } from '@univerjs/thread-comment-ui';
import { useDependency, useObservable } from '@univerjs/ui';
import { useEffect, useMemo, useState } from 'react';
-import { debounceTime, filter, map, Observable } from 'rxjs';
+import { debounceTime, filter, map, merge, Observable } from 'rxjs';
import { AddDocCommentComment } from '../commands/commands/add-doc-comment.command';
import { DeleteDocCommentComment } from '../commands/commands/delete-doc-comment.command';
import { StartAddCommentOperation } from '../commands/operations/show-comment-panel.operation';
@@ -51,11 +51,16 @@ export const DocThreadCommentPanel = () => {
() => docSelectionManagerService.textSelection$.pipe(debounceTime(16)),
[docSelectionManagerService.textSelection$]
);
+ const permissionService = useDependency(IPermissionService);
+ const disableAddChange$ = useMemo(
+ () => merge(selectionChange$, permissionService.permissionPointUpdate$),
+ [permissionService.permissionPointUpdate$, selectionChange$]
+ );
const disableAdd = useObservable(
- () => selectionChange$.pipe(map(() => shouldDisableAddComment(injector))),
+ () => disableAddChange$.pipe(map(() => shouldDisableAddComment(injector))),
shouldDisableAddComment(injector),
false,
- [injector, selectionChange$]
+ [disableAddChange$, injector]
);
const commandService = useDependency(ICommandService);
const threadCommentModel = useDependency(ThreadCommentModel);
diff --git a/packages/docs-ui/package.json b/packages/docs-ui/package.json
index 4898edb7bb..662faeac5b 100644
--- a/packages/docs-ui/package.json
+++ b/packages/docs-ui/package.json
@@ -90,6 +90,7 @@
"@univerjs/docs": "workspace:*",
"@univerjs/engine-render": "workspace:*",
"@univerjs/icons": "1.38.0",
+ "@univerjs/protocol": "workspace:*",
"@univerjs/ui": "workspace:*"
},
"devDependencies": {
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-selection-render.controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-selection-render.controller.spec.ts
index a2257aee8a..8e2df9e4db 100644
--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-selection-render.controller.spec.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc-selection-render.controller.spec.ts
@@ -18,11 +18,11 @@
import type { EmbedInteractionBoundaryService } from '../../../services/doc-embed-integration.service';
import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY } from '@univerjs/core';
-import { EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, EmbedRuntimeFocusCoordinator } from '../../../services/doc-embed-integration.service';
import { CURSOR_TYPE, DocumentEditArea } from '@univerjs/engine-render';
import { Subject } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { SetDocZoomRatioOperation } from '../../../commands/operations/set-doc-zoom-ratio.operation';
+import { EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, EmbedRuntimeFocusCoordinator } from '../../../services/doc-embed-integration.service';
import { DocSelectionRenderController } from '../doc-selection-render.controller';
const neoGetDocObjectMock = vi.hoisted(() => vi.fn());
@@ -413,6 +413,21 @@ describe('DocSelectionRenderController', () => {
controller.dispose();
});
+ it('cancels deferred editor focus when the render controller is disposed', () => {
+ vi.useFakeTimers();
+ const { controller, document, docSelectionRenderService, editorService } = createController({ hasEditor: true });
+
+ document.onPointerDown$.emit(
+ { offsetX: 11, offsetY: 22, button: 0 },
+ { stopPropagation: vi.fn() }
+ );
+ controller.dispose();
+ vi.runOnlyPendingTimers();
+
+ expect(editorService.focus).toHaveBeenCalledTimes(1);
+ expect(docSelectionRenderService.setCursorManually).not.toHaveBeenCalled();
+ });
+
it('preserves the host unit focus for configured editors', () => {
const { controller, document, editorService, instanceService } = createController({
hasEditor: true,
diff --git a/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.controller.ts
index d1302924e2..3d651a093f 100644
--- a/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.controller.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/doc-selection-render.controller.ts
@@ -43,6 +43,7 @@ import { DocSelectionRenderService } from '../../services/selection/doc-selectio
export class DocSelectionRenderController extends Disposable implements IRenderModule {
private _loadedMap = new WeakSet<RenderComponentType>();
+ private _deferredEditorFocusTimer: ReturnType<typeof setTimeout> | null = null;
constructor(
private readonly _context: IRenderContext<DocumentDataModel>,
@@ -192,7 +193,11 @@ export class DocSelectionRenderController extends Disposable implements IRenderM
this._setEditorFocus(unitId);
const { offsetX, offsetY } = evt;
- setTimeout(() => {
+ if (this._deferredEditorFocusTimer != null) {
+ clearTimeout(this._deferredEditorFocusTimer);
+ }
+ this._deferredEditorFocusTimer = setTimeout(() => {
+ this._deferredEditorFocusTimer = null;
if (unitId === this._editorService.getFocusId() || this._docSelectionRenderService.isOnPointerEvent) {
return;
}
@@ -229,6 +234,14 @@ export class DocSelectionRenderController extends Disposable implements IRenderM
}));
}
+ override dispose(): void {
+ if (this._deferredEditorFocusTimer != null) {
+ clearTimeout(this._deferredEditorFocusTimer);
+ this._deferredEditorFocusTimer = null;
+ }
+ super.dispose();
+ }
+
private _getTransformCoordForDocumentOffset(evtOffsetX: number, evtOffsetY: number) {
const docObject = neoGetDocObject(this._context);
const { document, scene } = docObject;
diff --git a/packages/docs-ui/src/menu/__tests__/context-menu.spec.ts b/packages/docs-ui/src/menu/__tests__/context-menu.spec.ts
index 16eb1469f2..4f293ff79b 100644
--- a/packages/docs-ui/src/menu/__tests__/context-menu.spec.ts
+++ b/packages/docs-ui/src/menu/__tests__/context-menu.spec.ts
@@ -14,11 +14,12 @@
* limitations under the License.
*/
-import { Injector, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
-import { DocSelectionManagerService } from '@univerjs/docs';
-import { of } from 'rxjs';
+import { Injector, IPermissionService, IUniverInstanceService, PermissionService, UniverInstanceType } from '@univerjs/core';
+import { DocSelectionManagerService, setDocumentPermissionValue } from '@univerjs/docs';
+import { UnitAction } from '@univerjs/protocol';
+import { firstValueFrom, of } from 'rxjs';
import { describe, expect, it } from 'vitest';
-import { ParagraphSettingMenuFactory, SectionSettingMenuFactory } from '../context-menu';
+import { CopyMenuFactory, ParagraphSettingMenuFactory, PasteMenuFactory, SectionSettingMenuFactory } from '../context-menu';
describe('settings context menu factories', () => {
it('does not show leading icons', () => {
@@ -32,9 +33,11 @@ describe('settings context menu factories', () => {
[IUniverInstanceService, {
useValue: {
focused$: of('doc-1'),
+ getCurrentTypeOfUnit$: () => of({ getUnitId: () => 'doc-1' }),
getUnitType: () => UniverInstanceType.UNIVER_DOC,
},
}],
+ [IPermissionService, { useClass: PermissionService }],
]);
expect(ParagraphSettingMenuFactory(accessor).icon).toBeUndefined();
@@ -42,4 +45,58 @@ describe('settings context menu factories', () => {
accessor.dispose();
});
+
+ it('disables copy without Unit Copy while keeping copy available in read-only mode', async () => {
+ const permissionService = new PermissionService();
+ const accessor = new Injector([
+ [DocSelectionManagerService, {
+ useValue: {
+ textSelection$: of({}),
+ getDocRanges: () => [{ collapsed: false }],
+ },
+ }],
+ [IUniverInstanceService, {
+ useValue: {
+ getCurrentTypeOfUnit$: () => of({ getUnitId: () => 'doc-1' }),
+ },
+ }],
+ [IPermissionService, { useValue: permissionService }],
+ ]);
+
+ setDocumentPermissionValue(permissionService, 'doc-1', 'doc-1', UnitAction.Copy, false);
+ const copyDisabled$ = CopyMenuFactory(accessor).disabled$;
+ if (!copyDisabled$) {
+ throw new Error('Copy menu must expose disabled state.');
+ }
+ expect(await firstValueFrom(copyDisabled$)).toBe(true);
+
+ setDocumentPermissionValue(permissionService, 'doc-1', 'doc-1', UnitAction.Copy, true);
+ setDocumentPermissionValue(permissionService, 'doc-1', 'doc-1', UnitAction.Edit, false);
+ expect(await firstValueFrom(copyDisabled$)).toBe(false);
+
+ accessor.dispose();
+ });
+
+ it('disables mutating context-menu actions in read-only mode', async () => {
+ const permissionService = new PermissionService();
+ const accessor = new Injector([
+ [IUniverInstanceService, {
+ useValue: {
+ getCurrentTypeOfUnit$: () => of({ getUnitId: () => 'doc-1' }),
+ },
+ }],
+ [IPermissionService, { useValue: permissionService }],
+ ]);
+ setDocumentPermissionValue(permissionService, 'doc-1', 'doc-1', UnitAction.Edit, false);
+
+ const pasteDisabled$ = PasteMenuFactory(accessor).disabled$;
+ const paragraphSettingDisabled$ = ParagraphSettingMenuFactory(accessor).disabled$;
+ if (!pasteDisabled$ || !paragraphSettingDisabled$) {
+ throw new Error('Mutating menus must expose disabled state.');
+ }
+ expect(await firstValueFrom(pasteDisabled$)).toBe(true);
+ expect(await firstValueFrom(paragraphSettingDisabled$)).toBe(true);
+
+ accessor.dispose();
+ });
});
diff --git a/packages/docs-ui/src/menu/context-menu.ts b/packages/docs-ui/src/menu/context-menu.ts
index 0869005514..feea568a59 100644
--- a/packages/docs-ui/src/menu/context-menu.ts
+++ b/packages/docs-ui/src/menu/context-menu.ts
@@ -21,8 +21,9 @@ import type { Subscriber } from 'rxjs';
import type { LocaleKey } from '../locale/types';
import { DOC_RANGE_TYPE, DocumentFlavor, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
+import { UnitAction } from '@univerjs/protocol';
import { getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';
-import { combineLatest, Observable } from 'rxjs';
+import { combineLatest, map, Observable } from 'rxjs';
import { DocCopyCommand, DocCutCommand, DocPasteCommand } from '../commands/commands/clipboard.command';
import { DeleteLeftCommand } from '../commands/commands/doc-delete.command';
import {
@@ -38,6 +39,7 @@ import {
} from '../commands/commands/table/doc-table-insert.command';
import { DocParagraphSettingPanelOperation } from '../commands/operations/doc-paragraph-setting-panel.operation';
import { DocSectionSettingPanelOperation } from '../commands/operations/doc-section-setting-panel.operation';
+import { disableMenuWithoutDocumentUnitPermission } from './menu';
const getDisableOnCollapsedObservable = (accessor: IAccessor) => {
const docSelectionManagerService = accessor.get(DocSelectionManagerService);
@@ -56,6 +58,10 @@ const getDisableOnCollapsedObservable = (accessor: IAccessor) => {
});
};
+function combineMenuDisabled(...states: Observable<boolean>[]): Observable<boolean> {
+ return combineLatest(states).pipe(map((values) => values.some(Boolean)));
+}
+
function inSameTable(rectRanges: Readonly<IRectRangeWithStyle[]>) {
if (rectRanges.length < 2) {
return true;
@@ -120,7 +126,10 @@ export function CopyMenuFactory(accessor: IAccessor): IMenuButtonItem<LocaleKey>
type: MenuItemType.BUTTON,
icon: 'CopyDoubleIcon',
title: 'docs-ui.rightClick.copy',
- disabled$: getDisableOnCollapsedObservable(accessor),
+ disabled$: combineMenuDisabled(
+ getDisableOnCollapsedObservable(accessor),
+ disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Copy)
+ ),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
};
};
@@ -130,6 +139,7 @@ export function ParagraphSettingMenuFactory(accessor: IAccessor): IMenuButtonIte
id: DocParagraphSettingPanelOperation.id,
type: MenuItemType.BUTTON,
title: 'docs-ui.doc.menu.paragraphSetting',
+ disabled$: disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Edit),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
};
};
@@ -140,7 +150,11 @@ export function CutMenuFactory(accessor: IAccessor): IMenuButtonItem<LocaleKey>
type: MenuItemType.BUTTON,
icon: 'CopyDoubleIcon',
title: 'docs-ui.rightClick.cut',
- disabled$: getDisableOnCollapsedObservable(accessor),
+ disabled$: combineMenuDisabled(
+ getDisableOnCollapsedObservable(accessor),
+ disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Copy),
+ disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Edit)
+ ),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
};
};
@@ -151,6 +165,7 @@ export function PasteMenuFactory(accessor: IAccessor): IMenuButtonItem<LocaleKey
type: MenuItemType.BUTTON,
icon: 'PasteSpecialDoubleIcon',
title: 'docs-ui.rightClick.paste',
+ disabled$: disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Edit),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
};
};
@@ -161,7 +176,10 @@ export function DeleteMenuFactory(accessor: IAccessor): IMenuButtonItem<LocaleKe
type: MenuItemType.BUTTON,
icon: 'PasteSpecialDoubleIcon',
title: 'docs-ui.rightClick.delete',
- disabled$: getDisableOnCollapsedObservable(accessor),
+ disabled$: combineMenuDisabled(
+ getDisableOnCollapsedObservable(accessor),
+ disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Edit)
+ ),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
};
};
@@ -173,6 +191,7 @@ export function TableInsertMenuItemFactory(accessor: IAccessor): IMenuSelectorIt
type: MenuItemType.SUBITEMS,
title: 'docs-ui.table.insert',
icon: 'InsertDoubleIcon',
+ disabled$: disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Edit),
hidden$: combineLatest(getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC), getDisableWhenSelectionNotInTableObservable(accessor), (one, two) => {
return one || two;
}),
@@ -207,6 +226,7 @@ export function SectionSettingMenuFactory(accessor: IAccessor): IMenuButtonItem<
id: DocSectionSettingPanelOperation.id,
type: MenuItemType.BUTTON,
title: 'docs-ui.doc.menu.sectionSetting',
+ disabled$: disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Edit),
hidden$: combineLatest(
getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
getSectionSettingUnavailableObservable(accessor),
@@ -221,7 +241,10 @@ export function InsertRowBeforeMenuItemFactory(accessor: IAccessor): IMenuButton
type: MenuItemType.BUTTON,
title: 'docs-ui.table.insertRowAbove',
icon: 'InsertRowAboveDoubleIcon',
- disabled$: getDisableWhenSelectionNotInTableObservable(accessor),
+ disabled$: combineMenuDisabled(
+ getDisableWhenSelectionNotInTableObservable(accessor),
+ disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Edit)
+ ),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
};
}
@@ -232,7 +255,10 @@ export function InsertRowAfterMenuItemFactory(accessor: IAccessor): IMenuButtonI
type: MenuItemType.BUTTON,
title: 'docs-ui.table.insertRowBelow',
icon: 'InsertRowBelowDoubleIcon',
- disabled$: getDisableWhenSelectionNotInTableObservable(accessor),
+ disabled$: combineMenuDisabled(
+ getDisableWhenSelectionNotInTableObservable(accessor),
+ disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Edit)
+ ),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
};
}
@@ -243,7 +269,10 @@ export function InsertColumnLeftMenuItemFactory(accessor: IAccessor): IMenuButto
type: MenuItemType.BUTTON,
title: 'docs-ui.table.insertColumnLeft',
icon: 'LeftInsertColumnDoubleIcon',
- disabled$: getDisableWhenSelectionNotInTableObservable(accessor),
+ disabled$: combineMenuDisabled(
+ getDisableWhenSelectionNotInTableObservable(accessor),
+ disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Edit)
+ ),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
};
}
@@ -254,7 +283,10 @@ export function InsertColumnRightMenuItemFactory(accessor: IAccessor): IMenuButt
type: MenuItemType.BUTTON,
title: 'docs-ui.table.insertColumnRight',
icon: 'RightInsertColumnDoubleIcon',
- disabled$: getDisableWhenSelectionNotInTableObservable(accessor),
+ disabled$: combineMenuDisabled(
+ getDisableWhenSelectionNotInTableObservable(accessor),
+ disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Edit)
+ ),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
};
}
@@ -266,6 +298,7 @@ export function TableDeleteMenuItemFactory(accessor: IAccessor): IMenuSelectorIt
type: MenuItemType.SUBITEMS,
title: 'docs-ui.table.delete',
icon: 'ReduceDoubleIcon',
+ disabled$: disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Edit),
hidden$: combineLatest(getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC), getDisableWhenSelectionNotInTableObservable(accessor), (one, two) => {
return one || two;
}),
@@ -278,7 +311,10 @@ export function DeleteRowsMenuItemFactory(accessor: IAccessor): IMenuButtonItem<
type: MenuItemType.BUTTON,
title: 'docs-ui.table.deleteRows',
icon: 'DeleteRowDoubleIcon',
- disabled$: getDisableWhenSelectionNotInTableObservable(accessor),
+ disabled$: combineMenuDisabled(
+ getDisableWhenSelectionNotInTableObservable(accessor),
+ disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Edit)
+ ),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
};
}
@@ -289,7 +325,10 @@ export function DeleteColumnsMenuItemFactory(accessor: IAccessor): IMenuButtonIt
type: MenuItemType.BUTTON,
title: 'docs-ui.table.deleteColumns',
icon: 'DeleteColumnDoubleIcon',
- disabled$: getDisableWhenSelectionNotInTableObservable(accessor),
+ disabled$: combineMenuDisabled(
+ getDisableWhenSelectionNotInTableObservable(accessor),
+ disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Edit)
+ ),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
};
}
@@ -300,7 +339,10 @@ export function DeleteTableMenuItemFactory(accessor: IAccessor): IMenuButtonItem
type: MenuItemType.BUTTON,
title: 'docs-ui.table.deleteTable',
icon: 'DeleteTableDoubleIcon',
- disabled$: getDisableWhenSelectionNotInTableObservable(accessor),
+ disabled$: combineMenuDisabled(
+ getDisableWhenSelectionNotInTableObservable(accessor),
+ disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Edit)
+ ),
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
};
}
diff --git a/packages/docs-ui/src/menu/menu.ts b/packages/docs-ui/src/menu/menu.ts
index 57e995d61a..f369756247 100644
--- a/packages/docs-ui/src/menu/menu.ts
+++ b/packages/docs-ui/src/menu/menu.ts
@@ -27,6 +27,7 @@ import {
DocumentFlavor,
HorizontalAlign,
ICommandService,
+ IPermissionService,
IUniverInstanceService,
NAMED_STYLE_MAP,
NamedStyleType,
@@ -39,10 +40,12 @@ import {
import {
DocSelectionManagerService,
DocSkeletonManagerService,
+ getDocumentPermissionValue,
RichTextEditingMutation,
SetTextSelectionsOperation,
} from '@univerjs/docs';
import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render';
+import { UnitAction } from '@univerjs/protocol';
import {
COLOR_PICKER_COMPONENT,
COMMON_LABEL_COMPONENT,
@@ -58,7 +61,7 @@ import {
SYMBOL_PICKER_COMPONENT,
} from '@univerjs/ui';
-import { combineLatest, distinctUntilChanged, map, Observable, shareReplay } from 'rxjs';
+import { combineLatest, distinctUntilChanged, map, Observable, shareReplay, startWith } from 'rxjs';
import { OpenHeaderFooterPanelCommand } from '../commands/commands/doc-header-footer.command';
import { HorizontalLineCommand } from '../commands/commands/doc-horizontal-line.command';
import {
@@ -328,7 +331,7 @@ export function disableMenuWhenNoDocRange(accessor: IAccessor): Observable<boole
const docSelectionManagerService = accessor.get(DocSelectionManagerService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- return new Observable((subscriber) => {
+ const selectionDisabled$ = new Observable<boolean>((subscriber) => {
const subscription = docSelectionManagerService.textSelection$.subscribe((selection) => {
if (selection == null) {
subscriber.next(true);
@@ -356,6 +359,28 @@ export function disableMenuWhenNoDocRange(accessor: IAccessor): Observable<boole
return () => subscription.unsubscribe();
});
+
+ return combineLatest([selectionDisabled$, disableMenuWithoutDocumentEditPermission(accessor)]).pipe(
+ map(([selectionDisabled, permissionDisabled]) => selectionDisabled || permissionDisabled)
+ );
+}
+
+export function disableMenuWithoutDocumentUnitPermission(accessor: IAccessor, action: UnitAction): Observable<boolean> {
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const permissionService = accessor.get(IPermissionService);
+ return combineLatest([
+ univerInstanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC),
+ permissionService.permissionPointUpdate$.pipe(startWith(undefined)),
+ ]).pipe(map(([document]) => !document || !getDocumentPermissionValue(
+ permissionService,
+ document.getUnitId(),
+ document.getUnitId(),
+ action
+ )));
+}
+
+function disableMenuWithoutDocumentEditPermission(accessor: IAccessor): Observable<boolean> {
+ return disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Edit);
}
export const DOC_INSERT_EMOJI_MENU_ID = 'doc.menu.insert-emoji';
@@ -1741,5 +1766,6 @@ export function PageSettingMenuItemFactory(accessor: IAccessor): IMenuButtonItem
icon: 'DocSettingIcon',
tooltip: 'docs-ui.toolbar.pageSetup',
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),
+ disabled$: disableMenuWithoutDocumentEditPermission(accessor),
};
}
diff --git a/packages/docs-ui/src/menu/paragraph-menu.ts b/packages/docs-ui/src/menu/paragraph-menu.ts
index 58f5c3cd51..71954709a2 100644
--- a/packages/docs-ui/src/menu/paragraph-menu.ts
+++ b/packages/docs-ui/src/menu/paragraph-menu.ts
@@ -19,6 +19,7 @@ import type { IMenuButtonItem, IMenuItem, IMenuSelectorItem } from '@univerjs/ui
import type { LocaleKey } from '../locale/types';
import { ICommandService, NamedStyleType, ThemeService, UniverInstanceType } from '@univerjs/core';
import { SetTextSelectionsOperation } from '@univerjs/docs';
+import { UnitAction } from '@univerjs/protocol';
import { getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';
import { Observable } from 'rxjs';
@@ -64,6 +65,7 @@ import { getHighlightBackgroundColor } from '../views/paragraph-menu/theme-color
import {
BackgroundColorSelectorMenuItemFactory,
disableMenuWhenNoDocRange,
+ disableMenuWithoutDocumentUnitPermission,
getParagraphStyleAtCursor,
shouldSuppressDocMenuStateRefresh,
TextColorSelectorMenuItemFactory,
@@ -336,21 +338,23 @@ export function EmptyParagraphHorizontalLineMenuItemFactory(): IMenuButtonItem<L
};
}
-export function CopyCurrentParagraphMenuItemFactory(): IMenuItem<LocaleKey> {
+export function CopyCurrentParagraphMenuItemFactory(accessor: IAccessor): IMenuItem<LocaleKey> {
return {
id: DocCopyCurrentParagraphCommand.id,
type: MenuItemType.BUTTON,
icon: 'CopyDoubleIcon',
title: 'docs-ui.rightClick.copy',
+ disabled$: disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Copy),
};
}
-export function CutCurrentParagraphMenuItemFactory(): IMenuItem<LocaleKey> {
+export function CutCurrentParagraphMenuItemFactory(accessor: IAccessor): IMenuItem<LocaleKey> {
return {
id: DocCutCurrentParagraphCommand.id,
type: MenuItemType.BUTTON,
icon: 'CutIcon',
title: 'docs-ui.rightClick.cut',
+ disabled$: disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Copy),
};
}
@@ -421,13 +425,14 @@ export function getDocBlockRangeMenuId(blockType: string): string {
return `doc.block-range.${blockType}.menu`;
}
-export function TableBlockCopyMenuItemFactory(): IMenuItem<LocaleKey> {
+export function TableBlockCopyMenuItemFactory(accessor: IAccessor): IMenuItem<LocaleKey> {
return {
id: DocCopyCommand.name,
commandId: DocCopyCommand.id,
type: MenuItemType.BUTTON,
icon: 'CopyDoubleIcon',
title: 'docs-ui.rightClick.copy',
+ disabled$: disableMenuWithoutDocumentUnitPermission(accessor, UnitAction.Copy),
};
}
diff --git a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
index 3c6260c051..b4bdd807d8 100644
--- a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts
@@ -23,7 +23,9 @@ import {
DocumentBlockType,
PresetListType,
} from '@univerjs/core';
+import { createDocumentPermissionPoint, getDocumentParagraphPermissionObjectId } from '@univerjs/docs';
import { DocumentEditArea } from '@univerjs/engine-render';
+import { UnitAction } from '@univerjs/protocol';
import { BehaviorSubject, Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
import {
@@ -54,6 +56,44 @@ describe('DocParagraphMenuService', () => {
expect(attachPopupToRect).toHaveBeenCalledTimes(1);
});
+ it('does not show paragraph or table menus without document edit permission', () => {
+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));
+ const service = createService({
+ attachPopupToRect,
+ canEdit: false,
+ dataStream: 'Text\r',
+ tables: [{ tableId: 'table-1', startIndex: 0, endIndex: 4 }],
+ });
+
+ service.showParagraphMenu(createParagraphBound({ paragraphStart: 0, paragraphEnd: 4, startIndex: 4 }));
+ service.showTableMenu({
+ pageIndex: 0,
+ rect: { bottom: 40, left: 20, right: 120, top: 10 },
+ tableId: 'table-1',
+ });
+
+ expect(attachPopupToRect).not.toHaveBeenCalled();
+ });
+
+ it('does not show a menu for a paragraph without paragraph edit permission', () => {
+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));
+ const paragraphPermissionId = createDocumentPermissionPoint(
+ 'doc-1',
+ getDocumentParagraphPermissionObjectId('', 'paragraph-1'),
+ UnitAction.Edit
+ ).id;
+ const service = createService({
+ attachPopupToRect,
+ dataStream: 'Text\r',
+ getPermissionValue: (permissionId) => permissionId !== paragraphPermissionId,
+ paragraphs: [{ paragraphId: 'paragraph-1', startIndex: 4 }],
+ });
+
+ service.showParagraphMenu(createParagraphBound({ paragraphStart: 0, paragraphEnd: 4, startIndex: 4 }));
+
+ expect(attachPopupToRect).not.toHaveBeenCalled();
+ });
+
it('treats empty column paragraphs as empty paragraph menu targets', () => {
const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));
const T = DataStreamTreeTokenType;
@@ -1257,13 +1297,15 @@ function createService(options: {
activeTextRange?: { collapsed: boolean; endOffset: number; startOffset: number };
attachPopupToRect: ReturnType<typeof vi.fn>;
blockRanges?: Array<{ blockId: string; blockType: string; endIndex: number; startIndex: number }>;
+ canEdit?: boolean;
clickCustomRanges$?: Subject<unknown>;
customBlocks?: Array<{ blockId: string; blockType: BlockType; startIndex: number }>;
dataStream: string;
findParagraphBoundByIndex?: (index: number) => unknown;
docRanges?: Array<{ collapsed?: boolean; endOffset?: number; rangeType?: DOC_RANGE_TYPE | string; startOffset?: number }>;
getDocRanges?: () => Array<{ collapsed?: boolean; endOffset?: number; rangeType?: DOC_RANGE_TYPE | string; startOffset?: number }>;
- paragraphs?: Array<{ bullet?: { listType?: PresetListType }; paragraphStyle?: Record<string, unknown>; startIndex: number }>;
+ getPermissionValue?: (permissionId: string) => boolean;
+ paragraphs?: Array<{ bullet?: { listType?: PresetListType }; paragraphId?: string; paragraphStyle?: Record<string, unknown>; startIndex: number }>;
paragraphBounds?: Map<number, IMutiPageParagraphBound>;
hoverParagraphLeft$?: BehaviorSubject<IMutiPageParagraphBound | null>;
hoverParagraphRealTime$?: BehaviorSubject<IMutiPageParagraphBound | null>;
@@ -1279,18 +1321,21 @@ function createService(options: {
tables?: Array<{ endIndex: number; startIndex: number; tableId: string }>;
viewportScrollY?: number;
}) {
+ const body = {
+ blockRanges: options.blockRanges ?? [],
+ customBlocks: options.customBlocks ?? [],
+ dataStream: options.dataStream,
+ paragraphs: options.paragraphs ?? [],
+ tables: options.tables ?? [],
+ };
return new DocParagraphMenuService(
{
unitId: 'doc-1',
unit: {
- getBody: () => ({
- blockRanges: options.blockRanges ?? [],
- customBlocks: options.customBlocks ?? [],
- dataStream: options.dataStream,
- paragraphs: options.paragraphs ?? [],
- tables: options.tables ?? [],
- }),
+ getBody: () => body,
getDisabled: () => false,
+ getSelfOrHeaderFooterModel: () => ({ getBody: () => body }),
+ getSnapshot: () => ({ body, drawings: {} }),
},
engine: {
getCanvasElement: () => ({
@@ -1347,6 +1392,12 @@ function createService(options: {
onKeydown$: options.keydown$ ?? new Subject(),
onSelectionStart$: options.selectionStart$ ?? new Subject(),
isOnPointerEvent: options.isOnPointerEvent ?? false,
+ } as never,
+ {
+ getPermissionPoint: (permissionId: string) => ({
+ value: options.getPermissionValue?.(permissionId) ?? options.canEdit ?? true,
+ }),
+ permissionPointUpdate$: new Subject(),
} as never
);
}
diff --git a/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts b/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts
index 66cb0837ad..456acf2ae6 100644
--- a/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts
+++ b/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts
@@ -30,12 +30,15 @@ import {
IContextService,
ILogService,
Injector,
+ IPermissionService,
IUniverInstanceService,
+ PermissionService,
RANGE_DIRECTION,
UniverInstanceService,
} from '@univerjs/core';
-import { DocSelectionManagerService, SetTextSelectionsOperation } from '@univerjs/docs';
+import { DocSelectionManagerService, setDocumentPermissionValue, SetTextSelectionsOperation } from '@univerjs/docs';
import { NORMAL_TEXT_SELECTION_PLUGIN_STYLE } from '@univerjs/engine-render';
+import { UnitAction } from '@univerjs/protocol';
import { ComponentManager } from '@univerjs/ui';
import { Subject } from 'rxjs';
import { describe, expect, it } from 'vitest';
@@ -93,6 +96,7 @@ function createActiveFloatMenuHarness(
runtimeFocusCoordinator?: EmbedRuntimeFocusCoordinator
) {
const injector = new Injector();
+ injector.add([IPermissionService, { useClass: PermissionService }]);
injector.add([ILogService, { useClass: DesktopLogService }]);
injector.add([IConfigService, { useClass: ConfigService }]);
injector.add([IContextService, { useClass: ContextService }]);
@@ -125,6 +129,7 @@ function createActiveFloatMenuHarness(
describe('DocFloatMenuService', () => {
it('does not register or show a floating toolbar inside internal document editors', () => {
const injector = new Injector();
+ injector.add([IPermissionService, { useClass: PermissionService }]);
injector.add([ILogService, { useClass: DesktopLogService }]);
injector.add([IConfigService, { useClass: ConfigService }]);
injector.add([IContextService, { useClass: ContextService }]);
@@ -143,6 +148,7 @@ describe('DocFloatMenuService', () => {
it('shows one floating toolbar for a text selection and hides it when selection restarts', () => {
const injector = new Injector();
+ injector.add([IPermissionService, { useClass: PermissionService }]);
injector.add([ILogService, { useClass: DesktopLogService }]);
injector.add([IConfigService, { useClass: ConfigService }]);
injector.add([IContextService, { useClass: ContextService }]);
@@ -207,8 +213,47 @@ describe('DocFloatMenuService', () => {
expect(popupService.disposedCount).toBe(1);
});
+ it('hides the floating toolbar when document edit permission is revoked', () => {
+ const unitId = 'doc-read-only-float-menu';
+ const harness = createActiveFloatMenuHarness(unitId, {
+ dataStream: 'Hello world\r\n',
+ paragraphs: [{ paragraphId: 'para_docs_ui_read_only_float_menu', startIndex: 11 }],
+ sectionBreaks: [],
+ customRanges: [],
+ tables: [],
+ textRuns: [],
+ });
+ const selection = {
+ textRanges: [{ startOffset: 0, endOffset: 5, collapsed: false }],
+ rectRanges: [],
+ segmentId: '',
+ segmentPage: -1,
+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
+ isEditing: true,
+ };
+ harness.selectionManager.__replaceTextRangesWithNoRefresh(selection, { unitId, subUnitId: unitId });
+ expect(harness.service.floatMenu).toMatchObject({ start: 0, end: 5 });
+
+ setDocumentPermissionValue(
+ harness.injector.get(IPermissionService),
+ unitId,
+ unitId,
+ UnitAction.Edit,
+ false
+ );
+
+ expect(harness.service.floatMenu).toBeNull();
+ expect(harness.popupService.disposedCount).toBe(1);
+ harness.selectionManager.__replaceTextRangesWithNoRefresh({
+ ...selection,
+ textRanges: [{ startOffset: 6, endOffset: 11, collapsed: false }],
+ }, { unitId, subUnitId: unitId });
+ expect(harness.popupService.ranges).toEqual(['0:5']);
+ });
+
it('does not show the floating toolbar for selections inside code blocks', () => {
const injector = new Injector();
+ injector.add([IPermissionService, { useClass: PermissionService }]);
injector.add([ILogService, { useClass: DesktopLogService }]);
injector.add([IConfigService, { useClass: ConfigService }]);
injector.add([IContextService, { useClass: ContextService }]);
diff --git a/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts b/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts
index 372894d885..e00e09e0e2 100644
--- a/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts
+++ b/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts
@@ -24,11 +24,19 @@ import {
DocumentBlockRangeType,
ICommandService,
ImageSourceType,
+ IPermissionService,
IUniverInstanceService,
SliceBodyType,
UniverInstanceType,
} from '@univerjs/core';
-import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';
+import {
+ DocSelectionManagerService,
+ getDocumentParagraphPermissionObjectId,
+ RichTextEditingMutation,
+ setDocumentPermissionValue,
+ SetTextSelectionsOperation,
+} from '@univerjs/docs';
+import { UnitAction } from '@univerjs/protocol';
import { IClipboardInterfaceService } from '@univerjs/ui';
import { describe, expect, it, vi } from 'vitest';
import { createCommandTestBed } from '../../../commands/commands/__tests__/create-command-test-bed';
@@ -223,6 +231,45 @@ describe('DocClipboardService table copy helpers', () => {
testBed.univer.dispose();
});
+ it('does not expose document content when Unit Copy permission is denied', async () => {
+ const documentData: IDocumentData = {
+ id: 'denied-copy-doc',
+ body: {
+ dataStream: 'Secret\r\n',
+ paragraphs: [{ paragraphId: 'denied-copy-paragraph', startIndex: 6 }],
+ sectionBreaks: [],
+ customBlocks: [],
+ textRuns: [],
+ },
+ documentStyle: {},
+ };
+ const testBed = createCommandTestBed(documentData, [
+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],
+ [IDocClipboardService, { useClass: DocClipboardService }],
+ ]);
+ const selectionManager = testBed.get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: documentData.id, subUnitId: '' });
+ selectionManager.__TEST_ONLY_add([{
+ startOffset: 0,
+ endOffset: 6,
+ collapsed: false,
+ isActive: true,
+ segmentId: '',
+ }]);
+ setDocumentPermissionValue(
+ testBed.get(IPermissionService),
+ documentData.id,
+ documentData.id,
+ UnitAction.Copy,
+ false
+ );
+
+ expect(await testBed.get(IDocClipboardService).copy()).toBe(false);
+ expect((testBed.get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService).writes).toEqual([]);
+
+ testBed.univer.dispose();
+ });
+
it('copies multiple selected text ranges in document order', async () => {
const documentData: IDocumentData = {
id: 'multi-copy-doc',
@@ -343,6 +390,93 @@ describe('DocClipboardService table copy helpers', () => {
testBed.univer.dispose();
});
+ it('does not write to the clipboard when Cut lacks Unit Edit permission', async () => {
+ const documentData: IDocumentData = {
+ id: 'copy-only-cut-doc',
+ body: {
+ dataStream: 'Keep me\r\n',
+ paragraphs: [{ paragraphId: 'copy-only-cut-paragraph', startIndex: 7 }],
+ sectionBreaks: [],
+ customBlocks: [],
+ textRuns: [],
+ },
+ documentStyle: {},
+ };
+ const clipboard = new TestClipboardInterfaceService();
+ const testBed = createCommandTestBed(documentData, [
+ [IClipboardInterfaceService, { useValue: clipboard }],
+ [IDocClipboardService, { useClass: DocClipboardService }],
+ ]);
+ const selectionManager = testBed.get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: documentData.id, subUnitId: '' });
+ const ranges: ITextRangeWithStyle[] = [{
+ startOffset: 0,
+ endOffset: 4,
+ collapsed: false,
+ isActive: true,
+ segmentId: '',
+ rangeType: DOC_RANGE_TYPE.TEXT,
+ }];
+ selectionManager.__TEST_ONLY_add(ranges);
+ setDocumentPermissionValue(
+ testBed.get(IPermissionService),
+ documentData.id,
+ documentData.id,
+ UnitAction.Edit,
+ false
+ );
+
+ expect(await testBed.get(IDocClipboardService).cut(ranges)).toBe(false);
+ expect(clipboard.writes).toEqual([]);
+ expect(testBed.get(IUniverInstanceService)
+ .getUnit<DocumentDataModel>(documentData.id, UniverInstanceType.UNIVER_DOC)
+ ?.getBody()
+ ?.dataStream).toBe('Keep me\r\n');
+
+ testBed.univer.dispose();
+ });
+
+ it('does not delete selected text when writing cut content to the clipboard fails', async () => {
+ const documentData: IDocumentData = {
+ id: 'failed-cut-doc',
+ body: {
+ dataStream: 'Keep me\r\n',
+ paragraphs: [{ paragraphId: 'failed-cut-paragraph', startIndex: 7 }],
+ sectionBreaks: [],
+ customBlocks: [],
+ textRuns: [],
+ },
+ documentStyle: {},
+ };
+ const testBed = createCommandTestBed(documentData, [
+ [IClipboardInterfaceService, { useClass: RejectingClipboardInterfaceService }],
+ [IDocClipboardService, { useClass: DocClipboardService }],
+ ]);
+ const commandService = testBed.get(ICommandService);
+ commandService.registerCommand(CutContentCommand);
+ commandService.registerCommand(RichTextEditingMutation);
+ commandService.registerCommand(SetTextSelectionsOperation);
+ const selectionManager = testBed.get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: documentData.id, subUnitId: '' });
+ const ranges: ITextRangeWithStyle[] = [{
+ startOffset: 0,
+ endOffset: 4,
+ collapsed: false,
+ isActive: true,
+ segmentId: '',
+ rangeType: DOC_RANGE_TYPE.TEXT,
+ }];
+ selectionManager.__TEST_ONLY_add(ranges);
+
+ expect(await testBed.get(IDocClipboardService).cut(ranges)).toBe(false);
+ expect(testBed.get(IUniverInstanceService)
+ .getUnit<DocumentDataModel>(documentData.id, UniverInstanceType.UNIVER_DOC)!
+ .getBody()
+ ?.dataStream).toBe('Keep me\r\n');
+
+ testBed.univer.dispose();
+ });
+
it('pastes browser html clipboard content into the active document', async () => {
const documentData: IDocumentData = {
id: 'html-clipboard-doc',
@@ -639,6 +773,180 @@ describe('DocClipboardService table copy helpers', () => {
testBed.univer.dispose();
});
+ it('does not upload pasted images when Document Edit is denied', async () => {
+ const documentData: IDocumentData = {
+ id: 'denied-image-paste-doc',
+ body: {
+ dataStream: 'Body\r\n',
+ paragraphs: [{ paragraphId: 'denied-image-paragraph', startIndex: 4 }],
+ sectionBreaks: [],
+ customBlocks: [],
+ textRuns: [],
+ },
+ documentStyle: {},
+ };
+ const testBed = createCommandTestBed(documentData, [
+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],
+ [IDocClipboardService, { useClass: DocClipboardService }],
+ ]);
+ const service = testBed.get(IDocClipboardService);
+ const selectionManager = testBed.get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: documentData.id, subUnitId: '' });
+ selectionManager.__TEST_ONLY_add([{
+ startOffset: 0,
+ endOffset: 0,
+ collapsed: true,
+ isActive: true,
+ segmentId: '',
+ }]);
+ const upload = vi.fn(async () => ({
+ imageSourceType: ImageSourceType.UUID,
+ source: 'must-not-upload',
+ }));
+ service.addClipboardHook({ onBeforePasteImage: upload });
+ setDocumentPermissionValue(
+ testBed.get(IPermissionService),
+ documentData.id,
+ getDocumentParagraphPermissionObjectId('', 'denied-image-paragraph'),
+ UnitAction.Edit,
+ false
+ );
+
+ await expect(service.legacyPaste({
+ html: '<p><img src="data:image/png;base64,AA=="></p>',
+ files: [],
+ })).resolves.toBe(false);
+ expect(upload).not.toHaveBeenCalled();
+
+ testBed.univer.dispose();
+ });
+
+ it('does not paste an image when paragraph Edit is revoked during upload', async () => {
+ const documentData: IDocumentData = {
+ id: 'revoked-image-paste-doc',
+ body: {
+ dataStream: 'Body\r\n',
+ paragraphs: [{ paragraphId: 'revoked-image-paragraph', startIndex: 4 }],
+ sectionBreaks: [],
+ customBlocks: [],
+ textRuns: [],
+ },
+ drawings: {},
+ drawingsOrder: [],
+ documentStyle: {},
+ };
+ const testBed = createCommandTestBed(documentData, [
+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],
+ [IDocClipboardService, { useClass: DocClipboardService }],
+ ]);
+ const commandService = testBed.get(ICommandService);
+ commandService.registerCommand(InnerPasteCommand);
+ commandService.registerCommand(RichTextEditingMutation);
+ commandService.registerCommand(SetTextSelectionsOperation);
+ const selectionManager = testBed.get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: documentData.id, subUnitId: '' });
+ selectionManager.__TEST_ONLY_add([{
+ startOffset: 0,
+ endOffset: 0,
+ collapsed: true,
+ isActive: true,
+ segmentId: '',
+ }]);
+ const service = testBed.get(IDocClipboardService);
+ let finishUpload: ((value: { source: string; imageSourceType: ImageSourceType }) => void) | undefined;
+ const upload = vi.fn(() => new Promise<{ source: string; imageSourceType: ImageSourceType }>((resolve) => {
+ finishUpload = resolve;
+ }));
+ service.addClipboardHook({ onBeforePasteImage: upload });
+
+ const paste = service.legacyPaste({
+ html: '<p><img src="data:image/png;base64,AA=="></p>',
+ files: [],
+ });
+ await vi.waitFor(() => expect(finishUpload).toBeDefined());
+ setDocumentPermissionValue(
+ testBed.get(IPermissionService),
+ documentData.id,
+ getDocumentParagraphPermissionObjectId('', 'revoked-image-paragraph'),
+ UnitAction.Edit,
+ false
+ );
+ finishUpload?.({ source: 'remote-file-id', imageSourceType: ImageSourceType.UUID });
+
+ await expect(paste).resolves.toBe(false);
+ const documentModel = testBed.get(IUniverInstanceService)
+ .getUnit<DocumentDataModel>(documentData.id, UniverInstanceType.UNIVER_DOC)!;
+ expect(documentModel.getBody()?.dataStream).toBe('Body\r\n');
+
+ testBed.univer.dispose();
+ });
+
+ it('does not paste into another Document after the active Unit changes during upload', async () => {
+ const documentData: IDocumentData = {
+ id: 'unit-switch-image-paste-doc',
+ body: {
+ dataStream: 'Body\r\n',
+ paragraphs: [{ paragraphId: 'unit-switch-image-paragraph', startIndex: 4 }],
+ sectionBreaks: [],
+ customBlocks: [],
+ textRuns: [],
+ },
+ drawings: {},
+ drawingsOrder: [],
+ documentStyle: {},
+ };
+ const otherDocumentData: IDocumentData = {
+ ...documentData,
+ id: 'unit-switch-image-paste-other-doc',
+ body: {
+ ...documentData.body!,
+ paragraphs: [{ paragraphId: 'unit-switch-image-other-paragraph', startIndex: 4 }],
+ },
+ };
+ const testBed = createCommandTestBed(documentData, [
+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],
+ [IDocClipboardService, { useClass: DocClipboardService }],
+ ]);
+ const commandService = testBed.get(ICommandService);
+ commandService.registerCommand(InnerPasteCommand);
+ commandService.registerCommand(RichTextEditingMutation);
+ commandService.registerCommand(SetTextSelectionsOperation);
+ const selectionManager = testBed.get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: documentData.id, subUnitId: '' });
+ selectionManager.__TEST_ONLY_add([{
+ startOffset: 0,
+ endOffset: 0,
+ collapsed: true,
+ isActive: true,
+ segmentId: '',
+ }]);
+ const service = testBed.get(IDocClipboardService);
+ let finishUpload: ((value: { source: string; imageSourceType: ImageSourceType }) => void) | undefined;
+ service.addClipboardHook({
+ onBeforePasteImage: vi.fn(() => new Promise<{ source: string; imageSourceType: ImageSourceType }>((resolve) => {
+ finishUpload = resolve;
+ })),
+ });
+
+ const paste = service.legacyPaste({
+ html: '<p><img src="data:image/png;base64,AA=="></p>',
+ files: [],
+ });
+ await vi.waitFor(() => expect(finishUpload).toBeDefined());
+ testBed.univer.createUnit(UniverInstanceType.UNIVER_DOC, otherDocumentData);
+ testBed.get(IUniverInstanceService).focusUnit(otherDocumentData.id);
+ finishUpload?.({ source: 'remote-file-id', imageSourceType: ImageSourceType.UUID });
+
+ await expect(paste).resolves.toBe(false);
+ const instanceService = testBed.get(IUniverInstanceService);
+ expect(instanceService.getUnit<DocumentDataModel>(documentData.id, UniverInstanceType.UNIVER_DOC)?.getBody()?.dataStream)
+ .toBe('Body\r\n');
+ expect(instanceService.getUnit<DocumentDataModel>(otherDocumentData.id, UniverInstanceType.UNIVER_DOC)?.getBody()?.dataStream)
+ .toBe('Body\r\n');
+
+ testBed.univer.dispose();
+ });
+
it('turns pasted image files into inline document drawings through the image paste hook', async () => {
class TestImage {
naturalWidth = 20;
diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
index 6e1f01ca22..1812470372 100644
--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts
@@ -32,6 +32,7 @@ import {
ILogService,
ImageSourceType,
Inject,
+ IPermissionService,
IUniverInstanceService,
normalizeBody,
ObjectRelativeFromH,
@@ -42,7 +43,13 @@ import {
Tools,
UniverInstanceType,
} from '@univerjs/core';
-import { DocSelectionManagerService } from '@univerjs/docs';
+import {
+ canEditDocumentTargets,
+ DocSelectionManagerService,
+ getDocumentEditTargetObjectIds,
+ getDocumentPermissionValue,
+} from '@univerjs/docs';
+import { UnitAction } from '@univerjs/protocol';
import {
FILE__BMP_CLIPBOARD_MIME_TYPE,
FILE__JPEG_CLIPBOARD_MIME_TYPE,
@@ -172,6 +179,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@ILogService private readonly _logService: ILogService,
@ICommandService private readonly _commandService: ICommandService,
+ @IPermissionService private readonly _permissionService: IPermissionService,
@IClipboardInterfaceService private readonly _clipboardInterfaceService: IClipboardInterfaceService,
@Inject(DocHtmlExportService) docHtmlExportService: DocHtmlExportService,
@Inject(DocSelectionManagerService) private readonly _docSelectionManagerService: DocSelectionManagerService
@@ -181,6 +189,15 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
}
async copy(sliceType: SliceBodyType = SliceBodyType.copy, ranges?: ITextRangeWithStyle[]): Promise<boolean> {
+ const document = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ if (!document || !getDocumentPermissionValue(
+ this._permissionService,
+ document.getUnitId(),
+ document.getUnitId(),
+ UnitAction.Copy
+ )) {
+ return false;
+ }
const {
newSnapshotList = [],
needCache = false,
@@ -214,13 +231,20 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
}
async paste(items?: ClipboardItem[]): Promise<boolean> {
+ const targetUnitId = this._getCurrentDocumentUnitId();
+ if (!targetUnitId || !this._canEditTargets(targetUnitId)) {
+ return false;
+ }
if (!items?.length) {
- return this._memoryClipboardData ? this._paste(Tools.deepClone(this._memoryClipboardData)) : false;
+ return this._memoryClipboardData ? this._paste(Tools.deepClone(this._memoryClipboardData), targetUnitId) : false;
}
const partDocData = await this._genDocDataFromClipboardItems(items);
+ if (!this._canEditTargets(targetUnitId)) {
+ return false;
+ }
- return this._paste(partDocData);
+ return this._paste(partDocData, targetUnitId);
}
async legacyPaste(options: {
@@ -229,15 +253,21 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
text?: string;
files: File[];
}): Promise<boolean> {
- let { html, internalJson, text, files } = options;
const currentDocInstance = this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC);
const docUnitId = currentDocInstance?.getUnitId() || '';
+ if (!docUnitId || !this._canEditTargets(docUnitId)) {
+ return false;
+ }
+ let { html, internalJson, text, files } = options;
if (!html && !text && files.length) {
html = await this._createImagePasteHtml(files);
} else if (html && files.length) {
html += await this._createImagePasteHtml(files);
}
html = await this._uploadBase64ImagesInHtml(html);
+ if (!this._canEditTargets(docUnitId)) {
+ return false;
+ }
if (!html && !text) {
this._logService.warn('[DocClipboardController] html and text cannot be both empty!');
return false;
@@ -247,12 +277,41 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
if (docUnitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {
if (text) {
const textDocData = BuildTextUtils.transform.fromPlainText(text);
- return this._paste({ body: textDocData });
+ return this._paste({ body: textDocData }, docUnitId);
} else {
partDocData.body!.textRuns = [];
}
}
- return this._paste(partDocData);
+ return this._paste(partDocData, docUnitId);
+ }
+
+ private _getCurrentDocumentUnitId(): string | null {
+ return this._univerInstanceService
+ .getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)
+ ?.getUnitId() ?? null;
+ }
+
+ private _canEditTargets(
+ expectedUnitId?: string,
+ ranges?: ReadonlyArray<ITextRangeWithStyle | IRectRangeWithStyle>
+ ): boolean {
+ const document = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
+ if (!document || (expectedUnitId && document.getUnitId() !== expectedUnitId)) {
+ return false;
+ }
+ const objectIds = new Set<string>();
+ const targetRanges = ranges ?? [
+ ...(this._docSelectionManagerService.getTextRanges() ?? []),
+ ...(this._docSelectionManagerService.getRectRanges() ?? []),
+ ];
+ targetRanges.forEach((range) => {
+ if (range.startOffset == null || range.endOffset == null) {
+ return;
+ }
+ getDocumentEditTargetObjectIds(document, range.segmentId ?? '', range)
+ .forEach((objectId) => objectIds.add(objectId));
+ });
+ return canEditDocumentTargets(this._permissionService, document.getUnitId(), objectIds);
}
private async _cut(ranges?: ITextRangeWithStyle[]): Promise<boolean> {
@@ -271,8 +330,15 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
return false;
}
+ const unitId = this._getCurrentDocumentUnitId();
+ if (!unitId || !this._canEditTargets(unitId, [...textRanges, ...rectRanges])) {
+ return false;
+ }
+
// Set content to clipboard.
- this.copy(SliceBodyType.cut, ranges);
+ if (!await this.copy(SliceBodyType.cut, ranges)) {
+ return false;
+ }
try {
let cursor = 0;
@@ -315,7 +381,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
}
}
- private async _paste(docData: Partial<IDocumentData>): Promise<boolean> {
+ private async _paste(docData: Partial<IDocumentData>, expectedUnitId?: string): Promise<boolean> {
const { body: _body } = docData;
if (_body == null) {
@@ -325,7 +391,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ
let body = normalizeBody(_body);
const currentDocument = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
- if (!currentDocument) {
+ if (!currentDocument || (expectedUnitId && currentDocument.getUnitId() !== expectedUnitId)) {
return false;
}
diff --git a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
index ae2605aa19..80ff760a32 100644
--- a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
+++ b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts
@@ -18,8 +18,8 @@ import type { DocumentDataModel, ICustomBlock, ICustomTable, IDocumentBlockRange
import type { IBoundRectNoAngle, IRenderContext, IRenderModule, ITextRangeWithStyle } from '@univerjs/engine-render';
import type { IMutiPageParagraphBound, ITableBound, ITableParagraphBound } from './doc-event-manager.service';
import type { IEditorInputConfig } from './selection/doc-selection-render.service';
-import { BlockType, DataStreamTreeTokenType, Disposable, DOC_RANGE_TYPE, DocumentBlockType, getParagraphContentStartOffset, Inject, isInternalEditorID, PresetListType } from '@univerjs/core';
-import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
+import { BlockType, DataStreamTreeTokenType, Disposable, DOC_RANGE_TYPE, DocumentBlockType, getParagraphContentStartOffset, Inject, IPermissionService, isInternalEditorID, PresetListType } from '@univerjs/core';
+import { canEditDocumentTargets, DocSelectionManagerService, DocSkeletonManagerService, getDocumentEditTargetObjectIds } from '@univerjs/docs';
import { DocumentEditArea } from '@univerjs/engine-render';
import { BehaviorSubject, combineLatest, first, throttleTime } from 'rxjs';
import { VIEWPORT_KEY } from '../basics/docs-view-key';
@@ -151,7 +151,8 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
@Inject(DocCanvasPopManagerService) private _docPopupManagerService: DocCanvasPopManagerService,
@Inject(DocSkeletonManagerService) private _docSkeletonManagerService: DocSkeletonManagerService,
@Inject(DocFloatMenuService) private _floatMenuService: DocFloatMenuService,
- @Inject(DocSelectionRenderService) private _docSelectionRenderService: DocSelectionRenderService
+ @Inject(DocSelectionRenderService) private _docSelectionRenderService: DocSelectionRenderService,
+ @IPermissionService private readonly _permissionService: IPermissionService
) {
super();
@@ -160,6 +161,13 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
}
this._init();
+ this.disposeWithMe(this._permissionService.permissionPointUpdate$.subscribe(() => {
+ const menu = this._paragraphMenu;
+ if (!this._canEditDocument(menu?.target.menuRange, menu?.paragraph.segmentId)) {
+ this._isBlockMenuDragging = false;
+ this.hideParagraphMenu(true);
+ }
+ }));
}
private _isCursorInActiveParagraph() {
@@ -263,7 +271,8 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
if (
viewModel.getEditArea() === DocumentEditArea.BODY &&
!this._floatMenuService.floatMenu &&
- !this._context.unit.getDisabled()
+ !this._context.unit.getDisabled() &&
+ this._canEditDocument()
) {
if (this._paragraphMenu?.active) {
return;
@@ -393,21 +402,23 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
private _shouldOpenSlashMenu(config: IEditorInputConfig): boolean {
const event = config.event as KeyboardEvent;
- if (event.key !== '/' || event.altKey || event.ctrlKey || event.metaKey) {
+ const range = this._getCollapsedTextRange(config);
+ if (!range || !this._canEditDocument(range, range.segmentId) || event.key !== '/' || event.altKey || event.ctrlKey || event.metaKey) {
return false;
}
- return this._getCollapsedTextRange(config) != null;
+ return true;
}
private _shouldOpenSlashMenuFromInput(config: IEditorInputConfig): boolean {
const event = config.event as InputEvent;
const content = config.content ?? event.data ?? '';
- if (content !== '/') {
+ const range = this._getCollapsedTextRange(config);
+ if (!range || !this._canEditDocument(range, range.segmentId) || content !== '/') {
return false;
}
- return this._getCollapsedTextRange(config) != null;
+ return true;
}
private _getCollapsedTextRange(config: IEditorInputConfig): ITextRangeWithStyle | null {
@@ -473,7 +484,7 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
}
const target = this._buildParagraphMenuTarget(paragraph);
- if (!target) {
+ if (!target || !this._canEditDocument(target.menuRange, paragraph.segmentId)) {
this.hideParagraphMenu(true);
return;
}
@@ -560,6 +571,10 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
emptyMode: false,
draggable: true,
};
+ if (!this._canEditDocument(target.menuRange)) {
+ this.hideParagraphMenu(true);
+ return;
+ }
if (this._shouldKeepCurrentCellMenuForTable(table)) {
return;
@@ -674,6 +689,17 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule
}
}
+ private _canEditDocument(
+ range?: { startOffset: number; endOffset: number },
+ segmentId = ''
+ ): boolean {
+ return canEditDocumentTargets(
+ this._permissionService,
+ this._context.unitId,
+ range ? getDocumentEditTargetObjectIds(this._context.unit, segmentId, range) : []
+ );
+ }
+
private _buildParagraphMenuTarget(paragraph: IMutiPageParagraphBound): IDocBlockMenuTarget | null {
const body = this._context.unit.getBody();
const dataStream = body?.dataStream ?? '';
diff --git a/packages/docs-ui/src/services/float-menu.service.ts b/packages/docs-ui/src/services/float-menu.service.ts
index 44ecfc4596..f4514b81fd 100644
--- a/packages/docs-ui/src/services/float-menu.service.ts
+++ b/packages/docs-ui/src/services/float-menu.service.ts
@@ -24,13 +24,15 @@ import {
FOCUSING_COMMON_DRAWINGS,
IContextService,
Inject,
+ IPermissionService,
isInternalEditorID,
IUniverInstanceService,
Optional,
toDisposable,
UniverInstanceType,
} from '@univerjs/core';
-import { DocSelectionManagerService } from '@univerjs/docs';
+import { DocSelectionManagerService, getDocumentPermissionValue } from '@univerjs/docs';
+import { UnitAction } from '@univerjs/protocol';
import { FLOAT_MENU_COMPONENT_KEY } from '../views/float-toolbar/FloatToolbar';
import { IDocEmbedRuntimeFocusCoordinator } from './doc-embed-integration.service';
import { DocCanvasPopManagerService } from './doc-popup-manager.service';
@@ -64,6 +66,7 @@ export class DocFloatMenuService extends Disposable implements IRenderModule {
@Inject(IUniverInstanceService) private readonly _univerInstanceService: IUniverInstanceService,
@Inject(DocSelectionRenderService) private readonly _docSelectionRenderService: DocSelectionRenderService,
@IContextService private readonly _contextService: IContextService,
+ @IPermissionService private readonly _permissionService: IPermissionService,
@Optional(IDocEmbedRuntimeFocusCoordinator) private readonly _embedRuntimeFocusCoordinator?: IDocEmbedRuntimeFocusCoordinator
) {
super();
@@ -71,6 +74,7 @@ export class DocFloatMenuService extends Disposable implements IRenderModule {
if (isInternalEditorID(this._context.unitId)) {
return;
}
+ this._initPermissionLifecycle();
this._initSelectionChange();
this._initEmbedRuntimeLifecycle();
@@ -136,6 +140,23 @@ export class DocFloatMenuService extends Disposable implements IRenderModule {
}));
}
+ private _initPermissionLifecycle(): void {
+ this.disposeWithMe(this._permissionService.permissionPointUpdate$.subscribe(() => {
+ if (!this._canEditDocument()) {
+ this._hideFloatMenu();
+ }
+ }));
+ }
+
+ private _canEditDocument(): boolean {
+ return getDocumentPermissionValue(
+ this._permissionService,
+ this._context.unitId,
+ this._context.unitId,
+ UnitAction.Edit
+ );
+ }
+
private _initEmbedRuntimeLifecycle(): void {
if (!this._embedRuntimeFocusCoordinator) {
return;
@@ -176,7 +197,7 @@ export class DocFloatMenuService extends Disposable implements IRenderModule {
private _showFloatMenu(unitId: string, range: ITextRangeParam) {
const documentDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
- if (!documentDataModel || documentDataModel.getDisabled()) {
+ if (!documentDataModel || documentDataModel.getDisabled() || !this._canEditDocument()) {
return;
}
diff --git a/packages/docs/package.json b/packages/docs/package.json
index bcad02879b..53ea1c4561 100644
--- a/packages/docs/package.json
+++ b/packages/docs/package.json
@@ -79,7 +79,8 @@
},
"dependencies": {
"@univerjs/core": "workspace:*",
- "@univerjs/engine-render": "workspace:*"
+ "@univerjs/engine-render": "workspace:*",
+ "@univerjs/protocol": "workspace:*"
},
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
diff --git a/packages/docs/src/commands/commands/set-document-permission.command.ts b/packages/docs/src/commands/commands/set-document-permission.command.ts
new file mode 100644
index 0000000000..3689b24f84
--- /dev/null
+++ b/packages/docs/src/commands/commands/set-document-permission.command.ts
@@ -0,0 +1,53 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand } from '@univerjs/core';
+import type { DocumentUnitPermissionAction } from '../../services/permission/document-permission';
+import { CommandType, IPermissionService } from '@univerjs/core';
+import { UnitAction } from '@univerjs/protocol';
+import {
+ DOCUMENT_UNIT_PERMISSION_ACTIONS,
+ setDocumentPermissionValue,
+} from '../../services/permission/document-permission';
+
+export interface ISetDocumentPermissionCommandParams {
+ unitId: string;
+ objectId: string;
+ action: DocumentUnitPermissionAction;
+ value: boolean;
+}
+
+export const SetDocumentPermissionCommand: ICommand<ISetDocumentPermissionCommandParams> = {
+ type: CommandType.COMMAND,
+ id: 'doc.command.set-permission',
+ handler(accessor, params) {
+ if (!params || !DOCUMENT_UNIT_PERMISSION_ACTIONS.includes(params.action)) {
+ return false;
+ }
+ if (params.objectId !== params.unitId && params.action !== UnitAction.Edit) {
+ return false;
+ }
+
+ setDocumentPermissionValue(
+ accessor.get(IPermissionService),
+ params.unitId,
+ params.objectId,
+ params.action,
+ params.value
+ );
+ return true;
+ },
+};
diff --git a/packages/docs/src/controllers/__tests__/doc-permission.controller.spec.ts b/packages/docs/src/controllers/__tests__/doc-permission.controller.spec.ts
new file mode 100644
index 0000000000..d6426db426
--- /dev/null
+++ b/packages/docs/src/controllers/__tests__/doc-permission.controller.spec.ts
@@ -0,0 +1,442 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentData, Univer } from '@univerjs/core';
+import type { FDocument } from '../../facade/f-document';
+import {
+ CommandType,
+ DocumentFlavor,
+ DrawingTypeEnum,
+ ICommandService,
+ IPermissionService,
+ IUndoRedoService,
+ IUniverInstanceService,
+ JSONX,
+ RedoCommand,
+ TextXActionType,
+ UndoCommand,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { UnitAction, UnitObject } from '@univerjs/protocol';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { InsertTextCommand } from '../../commands/commands/core-editing.command';
+import { DeleteDocumentSectionBreakCommand } from '../../commands/commands/update-document-section.command';
+import { RichTextEditingMutation } from '../../commands/mutations/core-editing.mutation';
+import { DocsRenameMutation } from '../../commands/mutations/docs-rename.mutation';
+import { createDocumentData, createTableDocument, createTestBed } from '../../facade/__tests__/create-test-bed';
+import {
+ createDocumentPermissionPoint,
+ DOCUMENT_UNIT_PERMISSION_ACTIONS,
+ getDocumentEntityPermissionObjectId,
+ getDocumentParagraphPermissionObjectId,
+ getDocumentSectionPermissionObjectId,
+} from '../../services/permission/document-permission';
+
+function createTwoSectionDocument(): IDocumentData {
+ const data = createDocumentData('permission-test', {
+ dataStream: 'One\r\nTwo\r\n',
+ paragraphs: [
+ { startIndex: 3, paragraphId: 'paragraph-one' },
+ { startIndex: 8, paragraphId: 'paragraph-two' },
+ ],
+ sectionBreaks: [
+ { sectionId: 'section-one', startIndex: 4 },
+ { sectionId: 'section-two', startIndex: 9 },
+ ],
+ });
+ data.documentStyle = { ...data.documentStyle, documentFlavor: DocumentFlavor.TRADITIONAL };
+ return data;
+}
+
+function createSharedHeaderDocument(): IDocumentData {
+ const data = createTwoSectionDocument();
+ data.headers = {
+ 'shared-header': {
+ headerId: 'shared-header',
+ body: {
+ dataStream: 'Head\r\n',
+ paragraphs: [{ startIndex: 4, paragraphId: 'header-paragraph' }],
+ sectionBreaks: [],
+ },
+ },
+ };
+ data.documentStyle.defaultHeaderId = 'shared-header';
+ return data;
+}
+
+function createDrawingDocument(): IDocumentData {
+ const data = createDocumentData('permission-drawing', {
+ dataStream: 'A\b\r\n',
+ paragraphs: [{ startIndex: 2, paragraphId: 'drawing-paragraph' }],
+ sectionBreaks: [{ sectionId: 'drawing-section', startIndex: 3 }],
+ customBlocks: [{ startIndex: 1, blockId: 'drawing-one' }],
+ });
+ data.drawings = {
+ 'drawing-one': {
+ drawingId: 'drawing-one',
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ docTransform: { angle: 0 },
+ } as never,
+ };
+ data.drawingsOrder = ['drawing-one'];
+ return data;
+}
+
+describe('DocPermissionController', () => {
+ let univer: Univer;
+ let document: FDocument;
+ let get: ReturnType<typeof createTestBed>['get'];
+
+ beforeEach(() => {
+ const testBed = createTestBed(createTwoSectionDocument());
+ univer = testBed.univer;
+ get = testBed.get;
+ document = testBed.univerAPI.getActiveDocument()!;
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('registers every whole-Document permission point when the unit is created', () => {
+ const permissionService = get(IPermissionService);
+ DOCUMENT_UNIT_PERMISSION_ACTIONS.forEach((action) => {
+ expect(permissionService.getPermissionPoint(
+ createDocumentPermissionPoint(document.getId(), document.getId(), action).id
+ )).not.toBeNull();
+ });
+ });
+
+ it('uses dedicated UnitObject values for stable Document scopes', () => {
+ const unitId = document.getId();
+ expect(createDocumentPermissionPoint(
+ unitId,
+ getDocumentSectionPermissionObjectId('', 'section-one'),
+ UnitAction.Edit
+ ).type).toBe(UnitObject.DocumentSection);
+ expect(createDocumentPermissionPoint(
+ unitId,
+ getDocumentParagraphPermissionObjectId('', 'paragraph-one'),
+ UnitAction.Edit
+ ).type).toBe(UnitObject.DocumentParagraph);
+ expect(createDocumentPermissionPoint(
+ unitId,
+ getDocumentEntityPermissionObjectId('', 'table', 'table-one'),
+ UnitAction.Edit
+ ).type).toBe(UnitObject.DocumentEntity);
+ });
+
+ it('enforces document edit permission through the facade and command pipeline', async () => {
+ await document.getPermission().setReadOnly();
+
+ expect(document.getPermission().canEdit()).toBe(false);
+ expect(document.getParagraph('paragraph-one')!.setText('Denied')).toBe(false);
+ expect(document.getParagraph('paragraph-one')!.getText()).toBe('One');
+ });
+
+ it('uses section and paragraph ids as hierarchical edit boundaries', async () => {
+ const firstSection = document.getSection(0)!;
+ const firstParagraph = document.getParagraphs()[0];
+ const secondParagraph = document.getParagraph('paragraph-two')!;
+ if (!firstParagraph) {
+ throw new Error('Paragraph not found.');
+ }
+
+ await firstSection.getPermission().setReadOnly();
+
+ expect(firstSection.getPermission().canEdit()).toBe(false);
+ expect(firstParagraph.getPermission().canEdit()).toBe(false);
+ expect(secondParagraph.getPermission().canEdit()).toBe(true);
+ expect(firstParagraph.setText('Denied')).toBe(false);
+ expect(secondParagraph.setText('Allowed')).toBe(true);
+
+ await document.getSection(0)!.getPermission().setEditable();
+ await document.getParagraph('paragraph-one')!.getPermission().setEditable(false);
+ expect(document.getParagraph('paragraph-one')!.setText('Denied again')).toBe(false);
+ });
+
+ it('requires every owner Section to edit a shared header', async () => {
+ univer.dispose();
+ const testBed = createTestBed(createSharedHeaderDocument());
+ univer = testBed.univer;
+ get = testBed.get;
+ document = testBed.univerAPI.getActiveDocument()!;
+ await document.getSection(1)!.getPermission().setEditable(false);
+
+ expect(get(ICommandService).syncExecuteCommand(InsertTextCommand.id, {
+ unitId: document.getId(),
+ segmentId: 'shared-header',
+ range: { startOffset: 1, endOffset: 1, collapsed: true },
+ body: { dataStream: 'X' },
+ })).toBe(false);
+
+ await document.getSection(1)!.getPermission().setEditable(true);
+ expect(get(ICommandService).syncExecuteCommand(InsertTextCommand.id, {
+ unitId: document.getId(),
+ segmentId: 'shared-header',
+ range: { startOffset: 1, endOffset: 1, collapsed: true },
+ body: { dataStream: 'X' },
+ })).toBe(true);
+ });
+
+ it('accepts collaboration mutations despite local edit permission', async () => {
+ await document.getPermission().setReadOnly();
+
+ await expect(get(ICommandService).executeCommand(DocsRenameMutation.id, {
+ unitId: document.getId(),
+ name: 'Remote name',
+ }, { fromCollab: true })).resolves.toBe(true);
+ expect(document.getName()).toBe('Remote name');
+ });
+
+ it('applies incoming changesets without creating local Undo history', async () => {
+ get(IUndoRedoService).clearUndoRedo(document.getId());
+ await document.getPermission().setReadOnly();
+
+ await expect(get(ICommandService).executeCommand(DocsRenameMutation.id, {
+ unitId: document.getId(),
+ name: 'Remote changeset',
+ }, { fromChangeset: true })).resolves.toBe(true);
+ await document.getPermission().setEditable(true);
+
+ expect(get(ICommandService).syncExecuteCommand(UndoCommand.id)).toBe(false);
+ expect(document.getName()).toBe('Remote changeset');
+ });
+
+ it('enforces stable entity ids together with their current Section parent', async () => {
+ univer.dispose();
+ const testBed = createTestBed(createTableDocument('permission-entity'));
+ univer = testBed.univer;
+ document = testBed.univerAPI.getActiveDocument()!;
+
+ await document.getEntityPermission('', 'table', 'table-1').setEditable(false);
+
+ expect(document.getEntityPermission('', 'table', 'table-1').canEdit()).toBe(false);
+ expect(document.getTextRange(0, 2).setText('Denied')).toBe(false);
+ });
+
+ it('enforces Drawing entity permission on direct JSONX transform mutations', async () => {
+ univer.dispose();
+ const testBed = createTestBed(createDrawingDocument());
+ univer = testBed.univer;
+ get = testBed.get;
+ document = testBed.univerAPI.getActiveDocument()!;
+ const drawingId = document.getDocumentDataModel().getSnapshot().drawingsOrder?.[0];
+ if (!drawingId) {
+ throw new Error('Drawing not found.');
+ }
+ await document.getEntityPermission('', 'drawing', drawingId).setReadOnly();
+ const actions = JSONX.getInstance().replaceOp(
+ ['drawings', drawingId, 'docTransform', 'angle'],
+ 0,
+ 15
+ );
+
+ expect(get(ICommandService).syncExecuteCommand(RichTextEditingMutation.id, {
+ unitId: document.getId(),
+ segmentId: '',
+ actions,
+ textRanges: [],
+ })).toBe(false);
+ expect(document.getDocumentDataModel().getSnapshot().drawings?.[drawingId].docTransform?.angle).toBe(0);
+ });
+
+ it('enforces paragraph permission on direct RichText mutations used by paste and undo/redo', async () => {
+ await document.getParagraph('paragraph-one')!.getPermission().setEditable(false);
+ const actions = JSONX.getInstance().editOp([
+ { t: TextXActionType.RETAIN, len: 1 },
+ { t: TextXActionType.INSERT, len: 1, body: { dataStream: 'X' } },
+ ]);
+
+ expect(get(ICommandService).syncExecuteCommand(RichTextEditingMutation.id, {
+ unitId: document.getId(),
+ segmentId: '',
+ actions,
+ textRanges: [],
+ })).toBe(false);
+ expect(get(ICommandService).syncExecuteCommand(RichTextEditingMutation.id, {
+ unitId: document.getId(),
+ segmentId: '',
+ actions: JSONX.getInstance().editOp([{ t: TextXActionType.DELETE, len: 1 }]),
+ textRanges: [],
+ })).toBe(false);
+ expect(document.getParagraph('paragraph-one')!.getText()).toBe('One');
+
+ await document.getParagraph('paragraph-one')!.getPermission().setEditable(true);
+ expect(get(ICommandService).syncExecuteCommand(RichTextEditingMutation.id, {
+ unitId: document.getId(),
+ segmentId: '',
+ actions,
+ textRanges: [],
+ })).toBeTruthy();
+ expect(document.getParagraph('paragraph-one')!.getText()).toBe('OXne');
+ });
+
+ it('keeps denied Undo history available until the paragraph is editable again', async () => {
+ const paragraph = document.getParagraph('paragraph-one')!;
+ expect(paragraph.setText('Changed')).toBe(true);
+ await paragraph.getPermission().setEditable(false);
+
+ expect(get(ICommandService).syncExecuteCommand(UndoCommand.id)).toBe(false);
+ expect(paragraph.getText()).toBe('Changed');
+
+ await paragraph.getPermission().setEditable(true);
+ expect(get(ICommandService).syncExecuteCommand(UndoCommand.id)).toBe(true);
+ expect(paragraph.getText()).toBe('One');
+ });
+
+ it('keeps denied Redo history available until the paragraph is editable again', async () => {
+ const paragraph = document.getParagraph('paragraph-one')!;
+ expect(paragraph.setText('Changed')).toBe(true);
+ expect(get(ICommandService).syncExecuteCommand(UndoCommand.id)).toBe(true);
+ await paragraph.getPermission().setEditable(false);
+
+ expect(get(ICommandService).syncExecuteCommand(RedoCommand.id)).toBe(false);
+ expect(paragraph.getText()).toBe('One');
+
+ await paragraph.getPermission().setEditable(true);
+ expect(get(ICommandService).syncExecuteCommand(RedoCommand.id)).toBe(true);
+ expect(paragraph.getText()).toBe('Changed');
+ });
+
+ it('rejects a range edit when any covered Paragraph is read-only', async () => {
+ await document.getParagraph('paragraph-two')!.getPermission().setEditable(false);
+
+ expect(document.getTextRange(0, 8).setText('Denied')).toBe(false);
+ expect(document.getParagraph('paragraph-one')!.getText()).toBe('One');
+ expect(document.getParagraph('paragraph-two')!.getText()).toBe('Two');
+ });
+
+ it('requires both adjacent Sections before deleting their shared boundary', async () => {
+ await document.getSection(1)!.getPermission().setEditable(false);
+
+ expect(get(ICommandService).syncExecuteCommand(DeleteDocumentSectionBreakCommand.id, {
+ unitId: document.getId(),
+ sectionId: 'section-one',
+ })).toBe(false);
+ expect(document.getSection(0)?.getId()).toBe('section-one');
+ expect(document.getSection(1)?.getId()).toBe('section-two');
+ });
+
+ it.each([
+ [UnitAction.Copy, 'doc.command.copy-current-paragraph'],
+ [UnitAction.Print, 'docs.operation.print'],
+ [UnitAction.Export, 'docs-exchange-client.operation.export-doc'],
+ [UnitAction.Comment, 'docs.command.add-comment'],
+ [UnitAction.Comment, 'docs.operation.add-drawing-comment'],
+ ] as const)('enforces unit action %s on its existing command surface', async (point, commandId) => {
+ const commandService = get(ICommandService);
+ commandService.registerCommand({ id: commandId, type: CommandType.OPERATION, handler: () => true });
+ await document.getPermission().setPoint(point, false);
+
+ expect(commandService.syncExecuteCommand(commandId)).toBe(false);
+ });
+
+ it('keeps Copy and Comment available when only Document Edit is denied', async () => {
+ const commandService = get(ICommandService);
+ commandService.registerCommand({ id: 'doc.command.copy-current-paragraph', type: CommandType.OPERATION, handler: () => true });
+ commandService.registerCommand({ id: 'docs.command.add-comment', type: CommandType.COMMAND, handler: () => true });
+ await document.getPermission().setReadOnly();
+
+ expect(commandService.syncExecuteCommand('doc.command.copy-current-paragraph')).toBe(true);
+ expect(commandService.syncExecuteCommand('docs.command.add-comment')).toBe(true);
+ });
+
+ it('blocks local comment mutations and still accepts remote comments', async () => {
+ const commandService = get(ICommandService);
+ commandService.registerCommand({ id: 'thread-comment.mutation.add-comment', type: CommandType.MUTATION, handler: () => true });
+ await document.getPermission().setPoint(UnitAction.Comment, false);
+ const params = { unitId: document.getId() };
+
+ expect(commandService.syncExecuteCommand('thread-comment.mutation.add-comment', params)).toBe(false);
+ await expect(commandService.executeCommand(
+ 'thread-comment.mutation.add-comment',
+ params,
+ { fromChangeset: true }
+ )).resolves.toBe(true);
+ });
+
+ it('blocks extension edit commands and resource mutations at the Unit ceiling', async () => {
+ const commandService = get(ICommandService);
+ commandService.registerCommand({ id: 'doc.command.insert-float-image', type: CommandType.COMMAND, handler: () => true });
+ commandService.registerCommand({ id: 'doc.command.switch-mode', type: CommandType.COMMAND, handler: () => true });
+ commandService.registerCommand({ id: 'docs-code.mutation.set-config', type: CommandType.MUTATION, handler: () => true });
+ commandService.registerCommand({ id: 'doc.command.open-header-footer-panel', type: CommandType.COMMAND, handler: () => true });
+ await document.getPermission().setReadOnly();
+ const params = { unitId: document.getId() };
+
+ expect(commandService.syncExecuteCommand('doc.command.insert-float-image', params)).toBe(false);
+ expect(commandService.syncExecuteCommand('doc.command.switch-mode', params)).toBe(false);
+ expect(commandService.syncExecuteCommand('docs-code.mutation.set-config', params)).toBe(false);
+ expect(commandService.syncExecuteCommand('doc.command.open-header-footer-panel', params)).toBe(true);
+ });
+
+ it('enforces stable Entity permissions on direct extension mutations', async () => {
+ const commandService = get(ICommandService);
+ commandService.registerCommand({ id: 'doc.mutation.update-shape-data', type: CommandType.MUTATION, handler: () => true });
+ await document.getEntityPermission('', 'custom-block', 'shape-one').setEditable(false);
+ const params = { unitId: document.getId(), shapeId: 'shape-one' };
+
+ expect(commandService.syncExecuteCommand('doc.mutation.update-shape-data', params)).toBe(false);
+ expect(commandService.syncExecuteCommand('doc.mutation.update-shape-data', {
+ ...params,
+ formulaLastValueGuard: { sessionId: 1 },
+ })).toBe(true);
+ await expect(commandService.executeCommand(
+ 'doc.mutation.update-shape-data',
+ params,
+ { fromChangeset: true }
+ )).resolves.toBe(true);
+ });
+
+ it('keeps derived Formula persistence available in read-only Documents', async () => {
+ const commandService = get(ICommandService);
+ commandService.registerCommand({ id: 'docs-formula.mutation.set-last-values', type: CommandType.MUTATION, handler: () => true });
+ await document.getPermission().setReadOnly();
+
+ expect(commandService.syncExecuteCommand('docs-formula.mutation.set-last-values', {
+ unitId: document.getId(),
+ updates: [],
+ })).toBe(true);
+ });
+
+ it('uses the execution Unit instead of the active Document for external actions', async () => {
+ const commandService = get(ICommandService);
+ commandService.registerCommand({ id: 'docs.operation.print', type: CommandType.OPERATION, handler: () => true });
+ await document.getPermission().setPoint(UnitAction.Print, false);
+ univer.createUnit(UniverInstanceType.UNIVER_DOC, createDocumentData('other-doc', {
+ dataStream: '\r\n',
+ paragraphs: [{ startIndex: 0, paragraphId: 'other-paragraph' }],
+ }));
+
+ expect(commandService.syncExecuteCommand(
+ 'docs.operation.print',
+ undefined,
+ { unitId: document.getId() }
+ )).toBe(false);
+ });
+
+ it('clears Unit and object permissions when the Document is disposed', async () => {
+ const unitPermission = document.getPermission();
+ const paragraphPermission = document.getParagraph('paragraph-one')!.getPermission();
+ await unitPermission.setReadOnly();
+ await paragraphPermission.setEditable(false);
+
+ expect(get(IUniverInstanceService).disposeUnit(document.getId())).toBe(true);
+ expect(unitPermission.getPoint(UnitAction.Edit)).toBe(true);
+ expect(paragraphPermission.canEdit()).toBe(true);
+ });
+});
diff --git a/packages/docs/src/controllers/doc-permission.controller.ts b/packages/docs/src/controllers/doc-permission.controller.ts
new file mode 100644
index 0000000000..9a505f8e59
--- /dev/null
+++ b/packages/docs/src/controllers/doc-permission.controller.ts
@@ -0,0 +1,359 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { DocumentDataModel, ICommandInfo, IExecutionOptions } from '@univerjs/core';
+import type {
+ IDeleteTextCommandParams,
+ IInsertTextCommandParams,
+ IUpdateTextCommandParams,
+} from '../commands/commands/core-editing.command';
+import type { ICreateHeaderFooterCommandParams } from '../commands/commands/create-header-footer.command';
+import type { ISetSectionHeaderFooterLinkCommandParams } from '../commands/commands/set-section-header-footer-link.command';
+import type { IUpdateDocumentParagraphStyleCommandParams } from '../commands/commands/update-document-paragraph-style.command';
+import type {
+ IDeleteDocumentSectionBreakCommandParams,
+ IInsertDocumentColumnBreakCommandParams,
+ IInsertDocumentSectionBreakCommandParams,
+ IUpdateDocumentSectionCommandParams,
+} from '../commands/commands/update-document-section.command';
+import type { IRichTextEditingMutationParams } from '../commands/mutations/core-editing.mutation';
+import {
+ CustomCommandExecutionError,
+ DeleteDirection,
+ Disposable,
+ ICommandService,
+ IPermissionService,
+ IUniverInstanceService,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { UnitAction } from '@univerjs/protocol';
+import { DeleteTextCommand, InsertTextCommand, UpdateTextCommand } from '../commands/commands/core-editing.command';
+import { CreateHeaderFooterCommand } from '../commands/commands/create-header-footer.command';
+import { SetDocumentPermissionCommand } from '../commands/commands/set-document-permission.command';
+import { SetSectionHeaderFooterLinkCommand } from '../commands/commands/set-section-header-footer-link.command';
+import { UpdateDocumentParagraphStyleCommand } from '../commands/commands/update-document-paragraph-style.command';
+import {
+ DeleteDocumentSectionBreakCommand,
+ InsertDocumentColumnBreakCommand,
+ InsertDocumentSectionBreakCommand,
+ UpdateDocumentSectionCommand,
+} from '../commands/commands/update-document-section.command';
+import { RichTextEditingMutation } from '../commands/mutations/core-editing.mutation';
+import { DocsRenameMutation } from '../commands/mutations/docs-rename.mutation';
+import {
+ canEditDocumentTargets,
+ clearDocumentPermissionValuesForUnit,
+ createDocumentPermissionPoint,
+ DOCUMENT_UNIT_PERMISSION_ACTIONS,
+ getDocumentEntityPermissionObjectId,
+ getDocumentPermissionValue,
+ getDocumentSectionPermissionObjectId,
+} from '../services/permission/document-permission';
+import {
+ getDocumentDrawingSegmentId,
+ getDocumentEditTargetObjectIds,
+ getDocumentEditTargetObjectIdsFromActions,
+ getDocumentEntityParentPermissionObjectIds,
+ getDocumentSectionIdsAtOffset,
+ getDocumentSectionPermissionObjectIdsByIds,
+} from '../services/permission/document-permission-resolver';
+import { getTopLevelSectionBreaks } from '../utils/sections';
+
+const NON_EDIT_DOCUMENT_COMMAND_IDS = new Set([
+ SetDocumentPermissionCommand.id,
+ 'doc.command.open-header-footer-panel',
+ 'doc.command.close-header-footer',
+ 'doc.command.select-all',
+ 'doc.command.set-zoom-ratio',
+]);
+
+const DERIVED_DOCUMENT_MUTATION_IDS = new Set([
+ 'docs-formula.mutation.set-last-values',
+]);
+
+export class DocPermissionController extends Disposable {
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @IPermissionService private readonly _permissionService: IPermissionService,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
+ ) {
+ super();
+ this._univerInstanceService.getAllUnitsForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)
+ .forEach((unit) => this._registerUnitPermissionPoints(unit.getUnitId()));
+ this.disposeWithMe(this._univerInstanceService
+ .getTypeOfUnitAdded$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)
+ .subscribe(({ unit }) => this._registerUnitPermissionPoints(unit.getUnitId())));
+ this.disposeWithMe(this._commandService.beforeCommandExecuted((commandInfo, options) => {
+ this._check(commandInfo, options);
+ }));
+ this.disposeWithMe(this._univerInstanceService
+ .getTypeOfUnitDisposed$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)
+ .subscribe((unit) => clearDocumentPermissionValuesForUnit(
+ this._permissionService,
+ unit.getUnitId()
+ )));
+ }
+
+ private _registerUnitPermissionPoints(unitId: string): void {
+ DOCUMENT_UNIT_PERMISSION_ACTIONS.forEach((action) => {
+ const point = createDocumentPermissionPoint(unitId, unitId, action);
+ if (!this._permissionService.getPermissionPoint(point.id)) {
+ this._permissionService.addPermissionPoint(point);
+ }
+ });
+ }
+
+ private _check(commandInfo: Readonly<ICommandInfo>, options?: IExecutionOptions): void {
+ if (options?.fromCollab || options?.fromChangeset) {
+ return;
+ }
+ const unitAction = getDocumentUnitAction(commandInfo.id);
+ const unitId = getUnitId(commandInfo, options) ?? (unitAction
+ ? this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC)?.getUnitId()
+ : undefined);
+ if (!unitId || this._univerInstanceService.getUnitType(unitId) !== UniverInstanceType.UNIVER_DOC) {
+ return;
+ }
+ if (unitAction) {
+ if (!getDocumentPermissionValue(this._permissionService, unitId, unitId, unitAction)) {
+ throw new CustomCommandExecutionError(`Document ${UnitAction[unitAction]} permission denied.`);
+ }
+ return;
+ }
+ const documentDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(
+ unitId,
+ UniverInstanceType.UNIVER_DOC
+ );
+ if (!documentDataModel) {
+ return;
+ }
+ const targetObjectIds = this._resolveTargetObjectIds(documentDataModel, commandInfo);
+ if (targetObjectIds === null) {
+ return;
+ }
+ if (!canEditDocumentTargets(this._permissionService, unitId, targetObjectIds)) {
+ throw new CustomCommandExecutionError('Document edit permission denied.');
+ }
+ }
+
+ private _resolveTargetObjectIds(
+ documentDataModel: DocumentDataModel,
+ commandInfo: Readonly<ICommandInfo>
+ ): string[] | null {
+ if (commandInfo.id === RichTextEditingMutation.id) {
+ const params = commandInfo.params as IRichTextEditingMutationParams;
+ return getDocumentEditTargetObjectIdsFromActions(
+ documentDataModel,
+ params.segmentId ?? '',
+ params.actions
+ );
+ }
+ if (commandInfo.id === DocsRenameMutation.id) {
+ return [];
+ }
+ if (isDerivedDocumentMutation(commandInfo)) {
+ return null;
+ }
+ const knownTargets = resolveTextTargets(documentDataModel, commandInfo) ??
+ resolveSectionTargets(documentDataModel, commandInfo);
+ if (knownTargets) {
+ return knownTargets;
+ }
+ const entityTargets = resolveEntityTargets(documentDataModel, commandInfo);
+ if (entityTargets.length) {
+ return entityTargets;
+ }
+ return isDocumentEditCommand(commandInfo.id) || isDocumentDataMutation(commandInfo)
+ ? []
+ : null;
+ }
+}
+
+function isDocumentEditCommand(id: string): boolean {
+ if (NON_EDIT_DOCUMENT_COMMAND_IDS.has(id)) {
+ return false;
+ }
+ return id.startsWith('doc.command.') ||
+ id.startsWith('docs.command.') ||
+ id.startsWith('doc.command-') ||
+ id.startsWith('doc.table.');
+}
+
+function isDocumentDataMutation(commandInfo: Readonly<ICommandInfo>): boolean {
+ const { id } = commandInfo;
+ if (isDerivedDocumentMutation(commandInfo)) {
+ return false;
+ }
+ return id.startsWith('doc.mutation.') ||
+ id.startsWith('docs.mutation.') ||
+ /^docs-[^.]+\.mutation\./.test(id);
+}
+
+function isDerivedDocumentMutation(commandInfo: Readonly<ICommandInfo>): boolean {
+ const params = isRecord(commandInfo.params) ? commandInfo.params : undefined;
+ return DERIVED_DOCUMENT_MUTATION_IDS.has(commandInfo.id) ||
+ (commandInfo.id === 'doc.mutation.update-shape-data' &&
+ !!params?.formulaLastValueGuard);
+}
+
+function resolveEntityTargets(
+ documentDataModel: DocumentDataModel,
+ commandInfo: Readonly<ICommandInfo>
+): string[] {
+ const params = commandInfo.params;
+ if (!isRecord(params)) {
+ return [];
+ }
+ const result = new Set<string>();
+ const add = (segmentId: string, entityType: string, entityId: string): void => {
+ result.add(getDocumentEntityPermissionObjectId(segmentId, entityType, entityId));
+ getDocumentEntityParentPermissionObjectIds(documentDataModel, segmentId, entityType, entityId)
+ .forEach((objectId) => result.add(objectId));
+ };
+ collectEntityReferences(params).forEach(({ entityType, entityId }) => {
+ const explicitSegmentId = params.segmentId;
+ const segmentId = typeof explicitSegmentId === 'string'
+ ? explicitSegmentId
+ : entityType === 'drawing' || entityType === 'custom-block'
+ ? getDocumentDrawingSegmentId(documentDataModel, entityId)
+ : '';
+ add(segmentId, entityType, entityId);
+ });
+ return [...result];
+}
+
+function collectEntityReferences(value: unknown): Array<{ entityType: string; entityId: string }> {
+ const result = new Map<string, { entityType: string; entityId: string }>();
+ const typeByKey: Record<string, string[]> = {
+ blockId: ['custom-block'],
+ drawingId: ['drawing'],
+ shapeId: ['drawing', 'custom-block'],
+ tableId: ['table'],
+ rangeId: ['custom-range'],
+ columnGroupId: ['column-group'],
+ };
+ const visit = (candidate: unknown, key = ''): void => {
+ if (typeof candidate === 'string') {
+ typeByKey[key]?.forEach((entityType) => {
+ result.set(`${entityType}\u001F${candidate}`, { entityType, entityId: candidate });
+ });
+ return;
+ }
+ if (Array.isArray(candidate)) {
+ const singularKey = key.endsWith('Ids') ? `${key.slice(0, -3)}Id` : key;
+ candidate.forEach((item) => visit(item, singularKey));
+ return;
+ }
+ if (!isRecord(candidate)) {
+ return;
+ }
+ Object.entries(candidate).forEach(([childKey, child]) => visit(child, childKey));
+ };
+ visit(value);
+ return [...result.values()];
+}
+
+function getUnitId(commandInfo: Readonly<ICommandInfo>, options?: IExecutionOptions): string | undefined {
+ const params = isRecord(commandInfo.params) ? commandInfo.params : undefined;
+ return typeof params?.unitId === 'string'
+ ? params.unitId
+ : typeof options?.unitId === 'string'
+ ? options.unitId
+ : undefined;
+}
+
+function getDocumentUnitAction(commandId: string): UnitAction | undefined {
+ if (commandId === 'doc.command.copy-current-paragraph' || commandId === 'docs-table.command.copy-selection') {
+ return UnitAction.Copy;
+ }
+ if (commandId === 'docs.operation.print') {
+ return UnitAction.Print;
+ }
+ if (commandId === 'docs-exchange-client.operation.export-doc') {
+ return UnitAction.Export;
+ }
+ if (commandId === 'docs.operation.start-add-comment' ||
+ commandId === 'docs.operation.add-drawing-comment' ||
+ (commandId.startsWith('docs.command.') && commandId.includes('comment')) ||
+ commandId.startsWith('thread-comment.command.') ||
+ commandId.startsWith('thread-comment.mutation.')) {
+ return UnitAction.Comment;
+ }
+ return undefined;
+}
+
+function resolveTextTargets(
+ documentDataModel: DocumentDataModel,
+ commandInfo: Readonly<ICommandInfo>
+): string[] | null {
+ const { id } = commandInfo;
+ if (id === InsertTextCommand.id || id === UpdateTextCommand.id) {
+ const params = commandInfo.params as IInsertTextCommandParams | IUpdateTextCommandParams;
+ return getDocumentEditTargetObjectIds(documentDataModel, params.segmentId ?? '', params.range);
+ }
+ if (id === DeleteTextCommand.id) {
+ const params = commandInfo.params as IDeleteTextCommandParams;
+ const isDeleteLeft = params.direction === DeleteDirection.LEFT;
+ return getDocumentEditTargetObjectIds(documentDataModel, params.segmentId ?? '', {
+ startOffset: isDeleteLeft ? params.range.startOffset - (params.len ?? 1) : params.range.startOffset,
+ endOffset: isDeleteLeft ? params.range.startOffset : params.range.startOffset + (params.len ?? 1),
+ });
+ }
+ if (id === UpdateDocumentParagraphStyleCommand.id) {
+ const params = commandInfo.params as IUpdateDocumentParagraphStyleCommandParams;
+ return getDocumentEditTargetObjectIds(documentDataModel, params.segmentId ?? '', params);
+ }
+ return null;
+}
+
+function resolveSectionTargets(
+ documentDataModel: DocumentDataModel,
+ commandInfo: Readonly<ICommandInfo>
+): string[] | null {
+ const { id } = commandInfo;
+ if (id === UpdateDocumentSectionCommand.id) {
+ const params = commandInfo.params as IUpdateDocumentSectionCommandParams;
+ return getDocumentSectionPermissionObjectIdsByIds(params.updates.map((update) => update.sectionId));
+ }
+ if (id === InsertDocumentSectionBreakCommand.id || id === InsertDocumentColumnBreakCommand.id) {
+ const params = commandInfo.params as IInsertDocumentSectionBreakCommandParams | IInsertDocumentColumnBreakCommandParams;
+ const body = documentDataModel.getBody();
+ return body ? getDocumentSectionPermissionObjectIdsByIds(getDocumentSectionIdsAtOffset(body, params.offset)) : [];
+ }
+ if (id === DeleteDocumentSectionBreakCommand.id) {
+ const params = commandInfo.params as IDeleteDocumentSectionBreakCommandParams;
+ const body = documentDataModel.getBody();
+ const sections = body ? getTopLevelSectionBreaks(body) : [];
+ const index = sections.findIndex((section) => section.sectionId === params.sectionId);
+ return getDocumentSectionPermissionObjectIdsByIds([
+ params.sectionId,
+ ...(index >= 0 && index + 1 < sections.length ? [sections[index + 1].sectionId] : []),
+ ]);
+ }
+ if (id === SetSectionHeaderFooterLinkCommand.id) {
+ const params = commandInfo.params as ISetSectionHeaderFooterLinkCommandParams;
+ return [getDocumentSectionPermissionObjectId('', params.sectionId)];
+ }
+ if (id === CreateHeaderFooterCommand.id) {
+ const params = commandInfo.params as ICreateHeaderFooterCommandParams;
+ return params.sectionId ? [getDocumentSectionPermissionObjectId('', params.sectionId)] : [];
+ }
+ return null;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
diff --git a/packages/docs/src/facade/f-document-paragraph.ts b/packages/docs/src/facade/f-document-paragraph.ts
index ad87a67f72..6fff71f69f 100644
--- a/packages/docs/src/facade/f-document-paragraph.ts
+++ b/packages/docs/src/facade/f-document-paragraph.ts
@@ -17,9 +17,10 @@
import type { IDocumentBody, Injector, IParagraph, IParagraphStyle } from '@univerjs/core';
import type { FDocument } from './f-document';
import type { IFDocumentTextRange } from './utils';
-import { getParagraphContentStartOffset, ICommandService, PresetListType, regexp, RESTORE_INSERTED_PARAGRAPH_IDS, UpdateDocsAttributeType } from '@univerjs/core';
+import { getParagraphContentStartOffset, ICommandService, IPermissionService, PresetListType, regexp, RESTORE_INSERTED_PARAGRAPH_IDS, UpdateDocsAttributeType } from '@univerjs/core';
import { FBaseInitialable } from '@univerjs/core/facade';
-import { UpdateDocumentParagraphStyleCommand } from '@univerjs/docs';
+import { getDocumentParagraphParentPermissionObjectIds, getDocumentParagraphPermissionObjectId, UpdateDocumentParagraphStyleCommand } from '@univerjs/docs';
+import { FDocumentObjectPermission } from './f-document-permission';
import { FDocumentTextRange } from './f-document-text-range';
import { buildPlainTextInsertBody, replaceBodyRange, retainBodyRange } from './utils';
@@ -69,7 +70,8 @@ export class FDocumentParagraph extends FBaseInitialable {
protected readonly _paragraphId: string,
protected readonly _segmentId = '',
protected override readonly _injector: Injector,
- @ICommandService private readonly _commandService: ICommandService
+ @ICommandService private readonly _commandService: ICommandService,
+ @IPermissionService private readonly _permissionService: IPermissionService
) {
super(_injector);
}
@@ -104,6 +106,30 @@ export class FDocumentParagraph extends FBaseInitialable {
return this._segmentId;
}
+ /**
+ * Returns this Paragraph's permission facade.
+ * @returns {FDocumentObjectPermission} Permission facade combining Document, Section, and Paragraph Edit points.
+ * @example
+ * ```ts
+ * const paragraph = univerAPI.getActiveDocument()?.getParagraphs()[0];
+ * if (!paragraph) throw new Error('Paragraph not found.');
+ * await paragraph.getPermission().setReadOnly();
+ * ```
+ */
+ getPermission(): FDocumentObjectPermission {
+ return new FDocumentObjectPermission(
+ this._document.getId(),
+ getDocumentParagraphPermissionObjectId(this._segmentId, this._paragraphId),
+ this._commandService,
+ this._permissionService,
+ () => getDocumentParagraphParentPermissionObjectIds(
+ this._document.getDocumentDataModel(),
+ this._segmentId,
+ this._paragraphId
+ )
+ );
+ }
+
/**
* Get this paragraph's metadata.
* @returns {IFDocumentParagraphInfo} The paragraph info.
diff --git a/packages/docs/src/facade/f-document-permission.ts b/packages/docs/src/facade/f-document-permission.ts
new file mode 100644
index 0000000000..16ea03d32b
--- /dev/null
+++ b/packages/docs/src/facade/f-document-permission.ts
@@ -0,0 +1,198 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommandService, IPermissionService } from '@univerjs/core';
+import type { DocumentUnitPermissionAction } from '@univerjs/docs';
+import { canEditDocumentTargets, getDocumentPermissionValue, SetDocumentPermissionCommand } from '@univerjs/docs';
+import { UnitAction } from '@univerjs/protocol';
+
+/**
+ * Command-backed permissions for one Document unit.
+ * @hideconstructor
+ */
+export class FDocumentPermission {
+ constructor(
+ private readonly _unitId: string,
+ private readonly _commandService: ICommandService,
+ private readonly _permissionService: IPermissionService
+ ) {}
+
+ /**
+ * Sets one Document unit permission through the command system.
+ *
+ * Supported actions are Edit, Copy, Print, Export, and Comment. Await the returned promise
+ * before reading the new value or performing an action that depends on it.
+ *
+ * @param {DocumentUnitPermissionAction} action Unit permission action to update.
+ * @param {boolean} value Whether the action is allowed.
+ * @returns {Promise<void>} Resolves after the permission command finishes.
+ * @example Disable copying while keeping the Document editable
+ * ```ts
+ * import { UnitAction } from '@univerjs/protocol';
+ *
+ * const document = univerAPI.getActiveDocument();
+ * if (!document) throw new Error('No active Document.');
+ * await document.getPermission().setPoint(UnitAction.Copy, false);
+ * ```
+ */
+ async setPoint(action: DocumentUnitPermissionAction, value: boolean): Promise<void> {
+ await this._commandService.executeCommand(SetDocumentPermissionCommand.id, {
+ unitId: this._unitId,
+ objectId: this._unitId,
+ action,
+ value,
+ });
+ }
+
+ /**
+ * Returns the current value of one Document unit permission.
+ * @param {DocumentUnitPermissionAction} action Unit permission action to query.
+ * @returns {boolean} Whether the action is currently allowed.
+ * @example
+ * ```ts
+ * import { UnitAction } from '@univerjs/protocol';
+ *
+ * const document = univerAPI.getActiveDocument();
+ * const canPrint = document?.getPermission().getPoint(UnitAction.Print) ?? false;
+ * console.log(canPrint);
+ * ```
+ */
+ getPoint(action: DocumentUnitPermissionAction): boolean {
+ return getDocumentPermissionValue(
+ this._permissionService,
+ this._unitId,
+ this._unitId,
+ action
+ );
+ }
+
+ /**
+ * Enables or disables editing for the whole Document.
+ * @param {boolean} [editable] Whether editing is allowed. Defaults to true.
+ * @returns {Promise<void>} Resolves after the permission command finishes.
+ */
+ async setEditable(editable = true): Promise<void> {
+ await this._commandService.executeCommand(SetDocumentPermissionCommand.id, {
+ unitId: this._unitId,
+ objectId: this._unitId,
+ action: UnitAction.Edit,
+ value: editable,
+ });
+ }
+
+ /**
+ * Makes the whole Document read-only.
+ * @returns {Promise<void>} Resolves after the permission command finishes.
+ * @example
+ * ```ts
+ * const document = univerAPI.getActiveDocument();
+ * if (!document) throw new Error('No active Document.');
+ * await document.getPermission().setReadOnly();
+ * ```
+ */
+ async setReadOnly(): Promise<void> {
+ await this._commandService.executeCommand(SetDocumentPermissionCommand.id, {
+ unitId: this._unitId,
+ objectId: this._unitId,
+ action: UnitAction.Edit,
+ value: false,
+ });
+ }
+
+ /**
+ * Returns whether the whole Document is currently editable.
+ * @returns {boolean} Whether Document editing is allowed.
+ */
+ canEdit(): boolean {
+ return getDocumentPermissionValue(
+ this._permissionService,
+ this._unitId,
+ this._unitId,
+ UnitAction.Edit
+ );
+ }
+}
+
+/**
+ * Command-backed Edit permission for one stable Document object.
+ * @hideconstructor
+ */
+export class FDocumentObjectPermission {
+ constructor(
+ private readonly _unitId: string,
+ private readonly _objectId: string,
+ private readonly _commandService: ICommandService,
+ private readonly _permissionService: IPermissionService,
+ private readonly _getParentObjectIds: () => string[] = () => []
+ ) {}
+
+ /**
+ * Enables or disables editing for this stable Document object.
+ *
+ * This changes only the object's Edit point. `canEdit()` also applies the Document unit and
+ * parent Section or Paragraph ceilings.
+ *
+ * @param {boolean} [editable] Whether object editing is allowed. Defaults to true.
+ * @returns {Promise<void>} Resolves after the permission command finishes.
+ * @example Restore editing for a paragraph
+ * ```ts
+ * const document = univerAPI.getActiveDocument();
+ * const paragraph = document?.getParagraphs()[0];
+ * if (!paragraph) throw new Error('Paragraph not found.');
+ * await paragraph.getPermission().setEditable();
+ * ```
+ */
+ async setEditable(editable = true): Promise<void> {
+ await this._commandService.executeCommand(SetDocumentPermissionCommand.id, {
+ unitId: this._unitId,
+ objectId: this._objectId,
+ action: UnitAction.Edit,
+ value: editable,
+ });
+ }
+
+ /**
+ * Makes this stable Document object read-only.
+ * @returns {Promise<void>} Resolves after the permission command finishes.
+ * @example
+ * ```ts
+ * const document = univerAPI.getActiveDocument();
+ * const section = document?.getSection(0);
+ * if (!section) throw new Error('Section not found.');
+ * await section.getPermission().setReadOnly();
+ * ```
+ */
+ async setReadOnly(): Promise<void> {
+ await this._commandService.executeCommand(SetDocumentPermissionCommand.id, {
+ unitId: this._unitId,
+ objectId: this._objectId,
+ action: UnitAction.Edit,
+ value: false,
+ });
+ }
+
+ /**
+ * Returns the effective Edit result after applying the Document, parent, and object permissions.
+ * @returns {boolean} Whether the object is currently editable.
+ */
+ canEdit(): boolean {
+ return canEditDocumentTargets(
+ this._permissionService,
+ this._unitId,
+ [...this._getParentObjectIds(), this._objectId]
+ );
+ }
+}
diff --git a/packages/docs/src/facade/f-document-section.ts b/packages/docs/src/facade/f-document-section.ts
index 46d66f2f00..7f1228973f 100644
--- a/packages/docs/src/facade/f-document-section.ts
+++ b/packages/docs/src/facade/f-document-section.ts
@@ -18,8 +18,9 @@ import type { IResolvedSectionHeaderFooterReference, ISectionBreak, ISectionColu
import type { IEffectiveSectionPageSetup, IHeaderFooterProps } from '@univerjs/docs';
import type { FDocument } from './f-document';
import type { IFDocumentTextRange } from './utils';
-import { ColumnSeparatorType, DocumentFlavor, generateRandomId, getSectionHeaderFooterReferenceKey, ICommandService, PageOrientType, resolveSectionHeaderFooterReference, SectionType, Tools } from '@univerjs/core';
-import { CreateHeaderFooterCommand, createSectionColumnProperties, DeleteDocumentSectionBreakCommand, getEffectiveSectionPageSetup, getSectionContentWidth, getTopLevelSectionBreaks, HeaderFooterType, SetSectionHeaderFooterLinkCommand, UpdateDocumentSectionCommand } from '@univerjs/docs';
+import { ColumnSeparatorType, DocumentFlavor, generateRandomId, getSectionHeaderFooterReferenceKey, ICommandService, IPermissionService, PageOrientType, resolveSectionHeaderFooterReference, SectionType, Tools } from '@univerjs/core';
+import { CreateHeaderFooterCommand, createSectionColumnProperties, DeleteDocumentSectionBreakCommand, getDocumentSectionPermissionObjectId, getEffectiveSectionPageSetup, getSectionContentWidth, getTopLevelSectionBreaks, HeaderFooterType, SetSectionHeaderFooterLinkCommand, UpdateDocumentSectionCommand } from '@univerjs/docs';
+import { FDocumentObjectPermission } from './f-document-permission';
export interface IFDocumentSectionColumnOptions {
/** Gap after each column except the last, in 96-DPI layout pixels. */
@@ -92,7 +93,8 @@ export class FDocumentSection {
constructor(
private readonly _document: FDocument,
private readonly _sectionId: string,
- @ICommandService private readonly _commandService: ICommandService
+ @ICommandService private readonly _commandService: ICommandService,
+ @IPermissionService private readonly _permissionService: IPermissionService
) {}
/**
@@ -107,6 +109,25 @@ export class FDocumentSection {
return this._sectionId;
}
+ /**
+ * Returns this Section's permission facade.
+ * @returns {FDocumentObjectPermission} Permission facade combining Document and Section Edit points.
+ * @example
+ * ```ts
+ * const section = univerAPI.getActiveDocument()?.getSection(0);
+ * if (!section) throw new Error('Section not found.');
+ * await section.getPermission().setReadOnly();
+ * ```
+ */
+ getPermission(): FDocumentObjectPermission {
+ return new FDocumentObjectPermission(
+ this._document.getId(),
+ getDocumentSectionPermissionObjectId('', this._sectionId),
+ this._commandService,
+ this._permissionService
+ );
+ }
+
/**
* Returns the current zero-based section index.
* @example
diff --git a/packages/docs/src/facade/f-document.ts b/packages/docs/src/facade/f-document.ts
index bd3870f13b..d09765d950 100644
--- a/packages/docs/src/facade/f-document.ts
+++ b/packages/docs/src/facade/f-document.ts
@@ -28,14 +28,16 @@ import {
ICommandService,
Inject,
Injector,
+ IPermissionService,
IResourceLoaderService,
IUniverInstanceService,
RedoCommand,
UndoCommand,
} from '@univerjs/core';
import { FBaseInitialable } from '@univerjs/core/facade';
-import { CreateHeaderFooterCommand, generateParagraphs, getTopLevelSectionBreaks, HeaderFooterType, InsertDocumentColumnBreakCommand, InsertDocumentSectionBreakCommand, SetDocumentNameCommand } from '@univerjs/docs';
+import { CreateHeaderFooterCommand, generateParagraphs, getDocumentEntityParentPermissionObjectIds, getDocumentEntityPermissionObjectId, getTopLevelSectionBreaks, HeaderFooterType, InsertDocumentColumnBreakCommand, InsertDocumentSectionBreakCommand, SetDocumentNameCommand } from '@univerjs/docs';
import { FDocumentParagraph } from './f-document-paragraph';
+import { FDocumentObjectPermission, FDocumentPermission } from './f-document-permission';
import { DocsSectionUnsupportedDocumentFlavorError, FDocumentSection } from './f-document-section';
import { FDocumentTextRange } from './f-document-text-range';
import { buildPlainTextInsertBody, replaceBodyRange } from './utils';
@@ -89,7 +91,8 @@ export class FDocument extends FBaseInitialable {
@Inject(Injector) protected override readonly _injector: Injector,
@IUniverInstanceService protected readonly _univerInstanceService: IUniverInstanceService,
@Inject(IResourceLoaderService) protected readonly _resourceLoaderService: IResourceLoaderService,
- @ICommandService private readonly _commandService: ICommandService
+ @ICommandService private readonly _commandService: ICommandService,
+ @IPermissionService private readonly _permissionService: IPermissionService
) {
super(_injector);
@@ -182,6 +185,48 @@ export class FDocument extends FBaseInitialable {
return this.id;
}
+ /**
+ * Returns the Document unit permission facade.
+ * @returns {FDocumentPermission} Permission facade for Edit, Copy, Print, Export, and Comment.
+ * @example
+ * ```ts
+ * const document = univerAPI.getActiveDocument();
+ * if (!document) throw new Error('No active Document.');
+ * await document.getPermission().setReadOnly();
+ * ```
+ */
+ getPermission(): FDocumentPermission {
+ return new FDocumentPermission(this.id, this._commandService, this._permissionService);
+ }
+
+ /**
+ * Returns the permission facade for an entity with a stable id, such as a Table, Drawing, or Custom Block.
+ *
+ * Parent Section and Paragraph permission ceilings are resolved from the current Document model.
+ * @param {string} segmentId Segment id, or an empty string for the main body.
+ * @param {string} entityType Stable entity type used by the owning Doc feature.
+ * @param {string} entityId Stable entity id.
+ * @returns {FDocumentObjectPermission} Effective permission facade for the entity.
+ * @example Make one drawing read-only
+ * ```ts
+ * const document = univerAPI.getActiveDocument();
+ * if (!document) throw new Error('No active Document.');
+ * const snapshot = document.getDocumentDataModel().getSnapshot();
+ * const drawingId = snapshot.drawingsOrder?.[0];
+ * if (!drawingId) throw new Error('Drawing not found.');
+ * await document.getEntityPermission('', 'drawing', drawingId).setReadOnly();
+ * ```
+ */
+ getEntityPermission(segmentId: string, entityType: string, entityId: string): FDocumentObjectPermission {
+ return new FDocumentObjectPermission(
+ this.id,
+ getDocumentEntityPermissionObjectId(segmentId, entityType, entityId),
+ this._commandService,
+ this._permissionService,
+ () => getDocumentEntityParentPermissionObjectIds(this._documentDataModel, segmentId, entityType, entityId)
+ );
+ }
+
/**
* Get the document name.
* @returns {string} The document name.
diff --git a/packages/docs/src/facade/index.ts b/packages/docs/src/facade/index.ts
index f41ef86fca..b9fabe453a 100644
--- a/packages/docs/src/facade/index.ts
+++ b/packages/docs/src/facade/index.ts
@@ -24,6 +24,7 @@ export {
} from './f-document';
export { FDocumentParagraph, isParagraphFacade } from './f-document-paragraph';
export type { IFDocumentFindTextOptions, IFDocumentParagraphInfo } from './f-document-paragraph';
+export { FDocumentObjectPermission, FDocumentPermission } from './f-document-permission';
export { DocsSectionUnsupportedDocumentFlavorError, FDocumentSection } from './f-document-section';
export type { FDocumentSectionPageSetup, IFDocumentSectionColumnOptions, IFDocumentSectionDescription } from './f-document-section';
export { FDocumentTextRange } from './f-document-text-range';
diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.ts
index da5e7732e1..d5dba204f1 100644
--- a/packages/docs/src/index.ts
+++ b/packages/docs/src/index.ts
@@ -33,6 +33,8 @@ export type {
} from './commands/commands/set-document-default-paragraph-style.command';
export { SetDocumentNameCommand } from './commands/commands/set-document-name.command';
export type { ISetDocumentNameCommandParams } from './commands/commands/set-document-name.command';
+export { SetDocumentPermissionCommand } from './commands/commands/set-document-permission.command';
+export type { ISetDocumentPermissionCommandParams } from './commands/commands/set-document-permission.command';
export { SetSectionHeaderFooterLinkCommand } from './commands/commands/set-section-header-footer-link.command';
export type { ISetSectionHeaderFooterLinkCommandParams } from './commands/commands/set-section-header-footer-link.command';
export { UpdateDocumentParagraphStyleCommand } from './commands/commands/update-document-paragraph-style.command';
@@ -92,6 +94,22 @@ export type {
IResolvedDocText,
IResolvedDocTextCharacter,
} from './services/doc-text-resolver.service';
+export {
+ canEditDocumentTargets,
+ createDocumentPermissionPoint,
+ getDocumentEntityPermissionObjectId,
+ getDocumentParagraphPermissionObjectId,
+ getDocumentPermissionValue,
+ getDocumentSectionPermissionObjectId,
+ setDocumentPermissionValue,
+} from './services/permission/document-permission';
+export type { DocumentUnitPermissionAction } from './services/permission/document-permission';
+export {
+ getDocumentDrawingSegmentId,
+ getDocumentEditTargetObjectIds,
+ getDocumentEntityParentPermissionObjectIds,
+ getDocumentParagraphParentPermissionObjectIds,
+} from './services/permission/document-permission-resolver';
export {
addCustomRangeBySelectionFactory,
addCustomRangeFactory,
diff --git a/packages/docs/src/plugin.ts b/packages/docs/src/plugin.ts
index 3354e2fa15..cc24634002 100644
--- a/packages/docs/src/plugin.ts
+++ b/packages/docs/src/plugin.ts
@@ -29,6 +29,7 @@ import { DeleteTextCommand, InsertTextCommand, UpdateTextCommand } from './comma
import { CreateHeaderFooterCommand } from './commands/commands/create-header-footer.command';
import { SetDocumentDefaultParagraphStyleCommand } from './commands/commands/set-document-default-paragraph-style.command';
import { SetDocumentNameCommand } from './commands/commands/set-document-name.command';
+import { SetDocumentPermissionCommand } from './commands/commands/set-document-permission.command';
import { SetSectionHeaderFooterLinkCommand } from './commands/commands/set-section-header-footer-link.command';
import { UpdateDocumentParagraphStyleCommand } from './commands/commands/update-document-paragraph-style.command';
import { DeleteDocumentSectionBreakCommand, InsertDocumentColumnBreakCommand, InsertDocumentSectionBreakCommand, UpdateDocumentSectionCommand } from './commands/commands/update-document-section.command';
@@ -37,6 +38,7 @@ import { DocsRenameMutation } from './commands/mutations/docs-rename.mutation';
import { SetTextSelectionsOperation } from './commands/operations/text-selection.operation';
import { defaultPluginConfig, DOCS_PLUGIN_CONFIG_KEY } from './config/config';
import { DocCustomRangeController } from './controllers/custom-range.controller';
+import { DocPermissionController } from './controllers/doc-permission.controller';
import { DocBlockMoveValidatorService } from './services/doc-block-move-validator.service';
import { DocContentInsertService } from './services/doc-content-insert.service';
import { DocSelectionManagerService } from './services/doc-selection-manager.service';
@@ -78,6 +80,7 @@ export class UniverDocsPlugin extends Plugin {
DeleteTextCommand,
UpdateTextCommand,
CreateHeaderFooterCommand,
+ SetDocumentPermissionCommand,
SetDocumentDefaultParagraphStyleCommand,
SetDocumentNameCommand,
SetSectionHeaderFooterLinkCommand,
@@ -105,6 +108,7 @@ export class UniverDocsPlugin extends Plugin {
[DocContentInsertService],
[DocTextResolverService],
[DocCustomRangeController],
+ [DocPermissionController],
] as Dependency[]
).forEach((d) => this._injector.add(d));
}
@@ -112,5 +116,6 @@ export class UniverDocsPlugin extends Plugin {
override onReady(): void {
this._injector.get(DocStateChangeManagerService);
this._injector.get(DocCustomRangeController);
+ this._injector.get(DocPermissionController);
}
}
diff --git a/packages/docs/src/services/permission/document-permission-resolver.ts b/packages/docs/src/services/permission/document-permission-resolver.ts
new file mode 100644
index 0000000000..7aae40b85d
--- /dev/null
+++ b/packages/docs/src/services/permission/document-permission-resolver.ts
@@ -0,0 +1,345 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type {
+ DocumentDataModel,
+ IDocumentBody,
+ ISectionBreak,
+ JSONXActions,
+ SectionHeaderFooterReferenceKey,
+ TextXAction,
+} from '@univerjs/core';
+import {
+ getParagraphContentStartOffset,
+ resolveSectionHeaderFooterReference,
+ TextX,
+ TextXActionType,
+} from '@univerjs/core';
+import { getTopLevelSectionBreaks } from '../../utils/sections';
+import {
+ getDocumentEntityPermissionObjectId,
+ getDocumentParagraphPermissionObjectId,
+ getDocumentSectionPermissionObjectId,
+} from './document-permission';
+
+const HEADER_FOOTER_REFERENCE_KEYS: SectionHeaderFooterReferenceKey[] = [
+ 'defaultHeaderId',
+ 'defaultFooterId',
+ 'firstPageHeaderId',
+ 'firstPageFooterId',
+ 'evenPageHeaderId',
+ 'evenPageFooterId',
+];
+
+export interface IDocumentPermissionRange {
+ startOffset: number;
+ endOffset: number;
+}
+
+export function getDocumentDrawingSegmentId(documentDataModel: DocumentDataModel, drawingId: string): string {
+ const { body, headers = {}, footers = {} } = documentDataModel.getSnapshot();
+ if (body?.customBlocks?.some((block) => block.blockId === drawingId)) {
+ return '';
+ }
+ for (const [segmentId, header] of Object.entries(headers)) {
+ if (header.body.customBlocks?.some((block) => block.blockId === drawingId)) {
+ return segmentId;
+ }
+ }
+ for (const [segmentId, footer] of Object.entries(footers)) {
+ if (footer.body.customBlocks?.some((block) => block.blockId === drawingId)) {
+ return segmentId;
+ }
+ }
+ return '';
+}
+
+export function getDocumentEditTargetObjectIds(
+ documentDataModel: DocumentDataModel,
+ segmentId: string,
+ range: IDocumentPermissionRange
+): string[] {
+ const body = documentDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
+ if (!body) {
+ return [];
+ }
+ return [
+ ...getSectionPermissionObjectIds(documentDataModel, segmentId, range),
+ ...getParagraphPermissionObjectIds(body, segmentId, range),
+ ...getEntityPermissionObjectIds(documentDataModel, body, segmentId, range),
+ ];
+}
+
+export function getDocumentEditTargetObjectIdsFromActions(
+ documentDataModel: DocumentDataModel,
+ segmentId: string,
+ actions: JSONXActions
+): string[] {
+ const textActions = getTextXActions(actions);
+ const result = new Set<string>();
+ if (textActions) {
+ let offset = 0;
+ const addRange = (startOffset: number, endOffset: number): void => {
+ getDocumentEditTargetObjectIds(documentDataModel, segmentId, { startOffset, endOffset })
+ .forEach((objectId) => result.add(objectId));
+ };
+
+ textActions.forEach((action) => {
+ if (action.t === TextXActionType.INSERT) {
+ addRange(offset, offset);
+ return;
+ }
+ if (action.t === TextXActionType.DELETE) {
+ addRange(offset, offset + action.len);
+ offset += action.len;
+ return;
+ }
+ if (action.body !== undefined || action.oldBody !== undefined || action.coverType !== undefined) {
+ addRange(offset, offset + action.len);
+ }
+ offset += action.len;
+ });
+ }
+
+ getDrawingIdsFromActions(actions).forEach((drawingId) => {
+ result.add(getDocumentEntityPermissionObjectId(segmentId, 'drawing', drawingId));
+ const body = documentDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
+ const block = body?.customBlocks?.find((item) => item.blockId === drawingId);
+ if (block) {
+ getSectionPermissionObjectIds(documentDataModel, segmentId, {
+ startOffset: block.startIndex,
+ endOffset: block.startIndex + 1,
+ }).forEach((objectId) => result.add(objectId));
+ }
+ });
+
+ return [...result];
+}
+
+function getDrawingIdsFromActions(actions: JSONXActions): string[] {
+ const result = new Set<string>();
+ const visit = (value: unknown): void => {
+ if (Array.isArray(value)) {
+ value.forEach((item, index) => {
+ if (item === 'drawings' && typeof value[index + 1] === 'string') {
+ result.add(value[index + 1]);
+ }
+ visit(item);
+ });
+ return;
+ }
+ if (!isRecord(value)) {
+ return;
+ }
+ Object.values(value).forEach(visit);
+ };
+ visit(actions);
+ return [...result];
+}
+
+function getTextXActions(actions: JSONXActions): TextXAction[] | null {
+ if (!Array.isArray(actions) || actions.length !== 2 || actions[0] !== 'body' || !isRecord(actions[1])) {
+ return null;
+ }
+ const edit = actions[1];
+ return edit.et === TextX.id && Array.isArray(edit.e) && edit.e.every(isTextXAction) ? edit.e : null;
+}
+
+function isTextXAction(value: unknown): value is TextXAction {
+ if (!isRecord(value) || typeof value.len !== 'number') {
+ return false;
+ }
+ if (value.t === TextXActionType.INSERT) {
+ return isRecord(value.body);
+ }
+ return value.t === TextXActionType.RETAIN || value.t === TextXActionType.DELETE;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+export function getDocumentEntityParentPermissionObjectIds(
+ documentDataModel: DocumentDataModel,
+ segmentId: string,
+ entityType: string,
+ entityId: string
+): string[] {
+ const body = documentDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
+ const range = body ? getEntityRange(body, entityType, entityId) : null;
+ return range ? getSectionPermissionObjectIds(documentDataModel, segmentId, range) : [];
+}
+
+export function getDocumentParagraphParentPermissionObjectIds(
+ documentDataModel: DocumentDataModel,
+ segmentId: string,
+ paragraphId: string
+): string[] {
+ const body = documentDataModel.getSelfOrHeaderFooterModel(segmentId)?.getBody();
+ const paragraph = body?.paragraphs?.find((item) => item.paragraphId === paragraphId);
+ if (!body || !paragraph) {
+ return [];
+ }
+ return getSectionPermissionObjectIds(documentDataModel, segmentId, {
+ startOffset: getParagraphContentStartOffset(body, paragraph),
+ endOffset: paragraph.startIndex + 1,
+ });
+}
+
+export function getDocumentSectionPermissionObjectIdsByIds(
+ sectionIds: Iterable<string>
+): string[] {
+ return Array.from(sectionIds, (sectionId) => getDocumentSectionPermissionObjectId('', sectionId));
+}
+
+export function getDocumentSectionIdsAtOffset(body: IDocumentBody, offset: number): string[] {
+ return getSectionsIntersectingRange(getTopLevelSectionBreaks(body), {
+ startOffset: offset,
+ endOffset: offset,
+ }).map((section) => section.sectionId);
+}
+
+function getSectionPermissionObjectIds(
+ documentDataModel: DocumentDataModel,
+ segmentId: string,
+ range: IDocumentPermissionRange
+): string[] {
+ if (segmentId) {
+ return getHeaderFooterOwnerSectionIds(documentDataModel, segmentId)
+ .map((sectionId) => getDocumentSectionPermissionObjectId('', sectionId));
+ }
+ const body = documentDataModel.getBody();
+ if (!body) {
+ return [];
+ }
+ return getSectionsIntersectingRange(getTopLevelSectionBreaks(body), range)
+ .map((section) => getDocumentSectionPermissionObjectId('', section.sectionId));
+}
+
+function getParagraphPermissionObjectIds(
+ body: IDocumentBody,
+ segmentId: string,
+ range: IDocumentPermissionRange
+): string[] {
+ const startOffset = Math.min(range.startOffset, range.endOffset);
+ const endOffset = Math.max(range.startOffset, range.endOffset);
+ return (body.paragraphs ?? [])
+ .filter((paragraph) => intersectsRange(
+ getParagraphContentStartOffset(body, paragraph),
+ paragraph.startIndex + 1,
+ startOffset,
+ endOffset
+ ))
+ .flatMap((paragraph) => paragraph.paragraphId
+ ? [getDocumentParagraphPermissionObjectId(segmentId, paragraph.paragraphId)]
+ : []);
+}
+
+function getEntityPermissionObjectIds(
+ documentDataModel: DocumentDataModel,
+ body: IDocumentBody,
+ segmentId: string,
+ range: IDocumentPermissionRange
+): string[] {
+ const drawings = documentDataModel.getSnapshot().drawings ?? {};
+ const candidates = [
+ ...(body.tables ?? []).map((item) => ({ type: 'table', id: item.tableId, start: item.startIndex, end: item.endIndex })),
+ ...(body.customBlocks ?? []).map((item) => ({
+ type: drawings[item.blockId] ? 'drawing' : 'custom-block',
+ id: item.blockId,
+ start: item.startIndex,
+ end: item.startIndex + 1,
+ })),
+ ...(body.blockRanges ?? []).map((item) => ({ type: 'block-range', id: item.blockId, start: item.startIndex, end: item.endIndex + 1 })),
+ ...(body.customRanges ?? []).map((item) => ({ type: 'custom-range', id: item.rangeId, start: item.startIndex, end: item.endIndex + 1 })),
+ ...(body.columnGroups ?? []).map((item) => ({ type: 'column-group', id: item.columnGroupId, start: item.startIndex, end: item.endIndex + 1 })),
+ ];
+ const startOffset = Math.min(range.startOffset, range.endOffset);
+ const endOffset = Math.max(range.startOffset, range.endOffset);
+ return candidates
+ .filter((item) => intersectsRange(item.start, item.end, startOffset, endOffset))
+ .map((item) => getDocumentEntityPermissionObjectId(segmentId, item.type, item.id));
+}
+
+function getEntityRange(
+ body: IDocumentBody,
+ entityType: string,
+ entityId: string
+): IDocumentPermissionRange | null {
+ if (entityType === 'table') {
+ const item = body.tables?.find((table) => table.tableId === entityId);
+ return item ? { startOffset: item.startIndex, endOffset: item.endIndex } : null;
+ }
+ if (entityType === 'custom-block' || entityType === 'drawing') {
+ const item = body.customBlocks?.find((block) => block.blockId === entityId);
+ return item ? { startOffset: item.startIndex, endOffset: item.startIndex + 1 } : null;
+ }
+ if (entityType === 'block-range') {
+ const item = body.blockRanges?.find((block) => block.blockId === entityId);
+ return item ? { startOffset: item.startIndex, endOffset: item.endIndex + 1 } : null;
+ }
+ if (entityType === 'custom-range') {
+ const item = body.customRanges?.find((customRange) => customRange.rangeId === entityId);
+ return item ? { startOffset: item.startIndex, endOffset: item.endIndex + 1 } : null;
+ }
+ if (entityType === 'column-group') {
+ const item = body.columnGroups?.find((columnGroup) => columnGroup.columnGroupId === entityId);
+ return item ? { startOffset: item.startIndex, endOffset: item.endIndex + 1 } : null;
+ }
+ return null;
+}
+
+function getSectionsIntersectingRange(
+ sections: ISectionBreak[],
+ range: IDocumentPermissionRange
+): ISectionBreak[] {
+ const startOffset = Math.min(range.startOffset, range.endOffset);
+ const endOffset = Math.max(range.startOffset, range.endOffset);
+ return sections.filter((section, index) => intersectsRange(
+ index === 0 ? 0 : sections[index - 1].startIndex + 1,
+ section.startIndex + 1,
+ startOffset,
+ endOffset
+ ));
+}
+
+function intersectsRange(
+ targetStart: number,
+ targetEnd: number,
+ rangeStart: number,
+ rangeEnd: number
+): boolean {
+ if (rangeStart === rangeEnd) {
+ return rangeStart >= targetStart && rangeStart < targetEnd;
+ }
+ return rangeStart < targetEnd && rangeEnd > targetStart;
+}
+
+function getHeaderFooterOwnerSectionIds(
+ documentDataModel: DocumentDataModel,
+ segmentId: string
+): string[] {
+ const snapshot = documentDataModel.getSnapshot();
+ const sections = snapshot.body ? getTopLevelSectionBreaks(snapshot.body) : [];
+ const result = new Set<string>();
+ sections.forEach((section, sectionIndex) => {
+ if (HEADER_FOOTER_REFERENCE_KEYS.some((key) =>
+ resolveSectionHeaderFooterReference(snapshot.documentStyle, sections, sectionIndex, key).segmentId === segmentId)) {
+ result.add(section.sectionId);
+ }
+ });
+ return [...result];
+}
diff --git a/packages/docs/src/services/permission/document-permission.ts b/packages/docs/src/services/permission/document-permission.ts
new file mode 100644
index 0000000000..5f36f6fa18
--- /dev/null
+++ b/packages/docs/src/services/permission/document-permission.ts
@@ -0,0 +1,152 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IPermissionService } from '@univerjs/core';
+import { UnitAction, UnitObject } from '@univerjs/protocol';
+import { DocumentCommentPermission } from './permission-point/document/comment';
+import { DocumentCopyPermission } from './permission-point/document/copy';
+import { DocumentEditablePermission } from './permission-point/document/editable';
+import { DocumentExportPermission } from './permission-point/document/export';
+import { DocumentPrintPermission } from './permission-point/document/print';
+import { DocumentEntityEditPermission } from './permission-point/entity/edit';
+import { DocumentParagraphEditPermission } from './permission-point/paragraph/edit';
+import { DocumentSectionEditPermission } from './permission-point/section/edit';
+
+export const DOCUMENT_UNIT_PERMISSION_ACTIONS = [
+ UnitAction.Edit,
+ UnitAction.Copy,
+ UnitAction.Print,
+ UnitAction.Export,
+ UnitAction.Comment,
+] as const;
+
+export type DocumentUnitPermissionAction = typeof DOCUMENT_UNIT_PERMISSION_ACTIONS[number];
+
+const DOCUMENT_PERMISSION_OBJECT_TYPES = new Set([
+ UnitObject.Document,
+ UnitObject.DocumentSection,
+ UnitObject.DocumentParagraph,
+ UnitObject.DocumentEntity,
+]);
+const DOCUMENT_SECTION_PERMISSION_OBJECT_PREFIX = 'section/';
+const DOCUMENT_PARAGRAPH_PERMISSION_OBJECT_PREFIX = 'paragraph/';
+const DOCUMENT_ENTITY_PERMISSION_OBJECT_PREFIX = 'entity/';
+
+export function getDocumentSectionPermissionObjectId(segmentId: string, sectionId: string): string {
+ return `${DOCUMENT_SECTION_PERMISSION_OBJECT_PREFIX}${encodeURIComponent(segmentId)}/${encodeURIComponent(sectionId)}`;
+}
+
+export function getDocumentParagraphPermissionObjectId(segmentId: string, paragraphId: string): string {
+ return `${DOCUMENT_PARAGRAPH_PERMISSION_OBJECT_PREFIX}${encodeURIComponent(segmentId)}/${encodeURIComponent(paragraphId)}`;
+}
+
+export function getDocumentEntityPermissionObjectId(
+ segmentId: string,
+ entityType: string,
+ entityId: string
+): string {
+ return `${DOCUMENT_ENTITY_PERMISSION_OBJECT_PREFIX}${encodeURIComponent(segmentId)}/${encodeURIComponent(entityType)}/${encodeURIComponent(entityId)}`;
+}
+
+export function createDocumentPermissionPoint(
+ unitId: string,
+ objectId: string,
+ action: UnitAction
+) {
+ if (objectId === unitId) {
+ switch (action) {
+ case UnitAction.Edit:
+ return new DocumentEditablePermission(unitId);
+ case UnitAction.Copy:
+ return new DocumentCopyPermission(unitId);
+ case UnitAction.Print:
+ return new DocumentPrintPermission(unitId);
+ case UnitAction.Export:
+ return new DocumentExportPermission(unitId);
+ case UnitAction.Comment:
+ return new DocumentCommentPermission(unitId);
+ default:
+ throw new Error(`Unsupported Document permission action: ${action}`);
+ }
+ }
+
+ if (action !== UnitAction.Edit) {
+ throw new Error(`Document object permissions only support Edit: ${objectId}`);
+ }
+ if (objectId.startsWith(DOCUMENT_SECTION_PERMISSION_OBJECT_PREFIX)) {
+ return new DocumentSectionEditPermission(unitId, objectId);
+ }
+ if (objectId.startsWith(DOCUMENT_PARAGRAPH_PERMISSION_OBJECT_PREFIX)) {
+ return new DocumentParagraphEditPermission(unitId, objectId);
+ }
+ if (objectId.startsWith(DOCUMENT_ENTITY_PERMISSION_OBJECT_PREFIX)) {
+ return new DocumentEntityEditPermission(unitId, objectId);
+ }
+ throw new Error(`Unsupported Document permission object: ${objectId}`);
+}
+
+export function getDocumentPermissionValue(
+ permissionService: IPermissionService,
+ unitId: string,
+ objectId: string,
+ action: UnitAction
+): boolean {
+ return permissionService.getPermissionPoint(createDocumentPermissionPoint(unitId, objectId, action).id)?.value ?? true;
+}
+
+export function setDocumentPermissionValue(
+ permissionService: IPermissionService,
+ unitId: string,
+ objectId: string,
+ action: UnitAction,
+ value: boolean
+): void {
+ const point = createDocumentPermissionPoint(unitId, objectId, action);
+ if (!permissionService.getPermissionPoint(point.id)) {
+ permissionService.addPermissionPoint(point);
+ }
+ permissionService.updatePermissionPoint(point.id, value);
+}
+
+export function clearDocumentPermissionValuesForUnit(
+ permissionService: IPermissionService,
+ unitId: string
+): void {
+ permissionService.getAllPermissionPoint().forEach((point$, id) => {
+ const subscription = point$.subscribe((point) => {
+ if (DOCUMENT_PERMISSION_OBJECT_TYPES.has(point.type) && 'unitId' in point && point.unitId === unitId) {
+ permissionService.deletePermissionPoint(id);
+ }
+ });
+ subscription.unsubscribe();
+ });
+}
+
+export function canEditDocumentTargets(
+ permissionService: IPermissionService,
+ unitId: string,
+ objectIds: Iterable<string>
+): boolean {
+ if (!getDocumentPermissionValue(permissionService, unitId, unitId, UnitAction.Edit)) {
+ return false;
+ }
+ for (const objectId of objectIds) {
+ if (!getDocumentPermissionValue(permissionService, unitId, objectId, UnitAction.Edit)) {
+ return false;
+ }
+ }
+ return true;
+}
diff --git a/packages/docs/src/services/permission/permission-point/document/comment.ts b/packages/docs/src/services/permission/permission-point/document/comment.ts
new file mode 100644
index 0000000000..4f50bccc55
--- /dev/null
+++ b/packages/docs/src/services/permission/permission-point/document/comment.ts
@@ -0,0 +1,31 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IPermissionPoint } from '@univerjs/core';
+import { PermissionStatus } from '@univerjs/core';
+import { UnitAction, UnitObject } from '@univerjs/protocol';
+
+export class DocumentCommentPermission implements IPermissionPoint {
+ readonly type = UnitObject.Document;
+ readonly subType = UnitAction.Comment;
+ readonly status = PermissionStatus.INIT;
+ readonly id: string;
+ value = true;
+
+ constructor(readonly unitId: string) {
+ this.id = `${this.type}.${this.subType}_${unitId}`;
+ }
+}
diff --git a/packages/docs/src/services/permission/permission-point/document/copy.ts b/packages/docs/src/services/permission/permission-point/document/copy.ts
new file mode 100644
index 0000000000..5c696c9acb
--- /dev/null
+++ b/packages/docs/src/services/permission/permission-point/document/copy.ts
@@ -0,0 +1,31 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IPermissionPoint } from '@univerjs/core';
+import { PermissionStatus } from '@univerjs/core';
+import { UnitAction, UnitObject } from '@univerjs/protocol';
+
+export class DocumentCopyPermission implements IPermissionPoint {
+ readonly type = UnitObject.Document;
+ readonly subType = UnitAction.Copy;
+ readonly status = PermissionStatus.INIT;
+ readonly id: string;
+ value = true;
+
+ constructor(readonly unitId: string) {
+ this.id = `${this.type}.${this.subType}_${unitId}`;
+ }
+}
diff --git a/packages/docs/src/services/permission/permission-point/document/editable.ts b/packages/docs/src/services/permission/permission-point/document/editable.ts
new file mode 100644
index 0000000000..72d520c7e4
--- /dev/null
+++ b/packages/docs/src/services/permission/permission-point/document/editable.ts
@@ -0,0 +1,31 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IPermissionPoint } from '@univerjs/core';
+import { PermissionStatus } from '@univerjs/core';
+import { UnitAction, UnitObject } from '@univerjs/protocol';
+
+export class DocumentEditablePermission implements IPermissionPoint {
+ readonly type = UnitObject.Document;
+ readonly subType = UnitAction.Edit;
+ readonly status = PermissionStatus.INIT;
+ readonly id: string;
+ value = true;
+
+ constructor(readonly unitId: string) {
+ this.id = `${this.type}.${this.subType}_${unitId}`;
+ }
+}
diff --git a/packages/docs/src/services/permission/permission-point/document/export.ts b/packages/docs/src/services/permission/permission-point/document/export.ts
new file mode 100644
index 0000000000..dacf90c992
--- /dev/null
+++ b/packages/docs/src/services/permission/permission-point/document/export.ts
@@ -0,0 +1,31 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IPermissionPoint } from '@univerjs/core';
+import { PermissionStatus } from '@univerjs/core';
+import { UnitAction, UnitObject } from '@univerjs/protocol';
+
+export class DocumentExportPermission implements IPermissionPoint {
+ readonly type = UnitObject.Document;
+ readonly subType = UnitAction.Export;
+ readonly status = PermissionStatus.INIT;
+ readonly id: string;
+ value = true;
+
+ constructor(readonly unitId: string) {
+ this.id = `${this.type}.${this.subType}_${unitId}`;
+ }
+}
diff --git a/packages/docs/src/services/permission/permission-point/document/print.ts b/packages/docs/src/services/permission/permission-point/document/print.ts
new file mode 100644
index 0000000000..703ddb46ae
--- /dev/null
+++ b/packages/docs/src/services/permission/permission-point/document/print.ts
@@ -0,0 +1,31 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IPermissionPoint } from '@univerjs/core';
+import { PermissionStatus } from '@univerjs/core';
+import { UnitAction, UnitObject } from '@univerjs/protocol';
+
+export class DocumentPrintPermission implements IPermissionPoint {
+ readonly type = UnitObject.Document;
+ readonly subType = UnitAction.Print;
+ readonly status = PermissionStatus.INIT;
+ readonly id: string;
+ value = true;
+
+ constructor(readonly unitId: string) {
+ this.id = `${this.type}.${this.subType}_${unitId}`;
+ }
+}
diff --git a/packages/docs/src/services/permission/permission-point/entity/edit.ts b/packages/docs/src/services/permission/permission-point/entity/edit.ts
new file mode 100644
index 0000000000..8e6f0dbb25
--- /dev/null
+++ b/packages/docs/src/services/permission/permission-point/entity/edit.ts
@@ -0,0 +1,31 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IPermissionPoint } from '@univerjs/core';
+import { PermissionStatus } from '@univerjs/core';
+import { UnitAction, UnitObject } from '@univerjs/protocol';
+
+export class DocumentEntityEditPermission implements IPermissionPoint {
+ readonly type = UnitObject.DocumentEntity;
+ readonly subType = UnitAction.Edit;
+ readonly status = PermissionStatus.INIT;
+ readonly id: string;
+ value = true;
+
+ constructor(readonly unitId: string, readonly objectId: string) {
+ this.id = `${this.type}.${this.subType}_${unitId}_${objectId}`;
+ }
+}
diff --git a/packages/docs/src/services/permission/permission-point/paragraph/edit.ts b/packages/docs/src/services/permission/permission-point/paragraph/edit.ts
new file mode 100644
index 0000000000..56974da123
--- /dev/null
+++ b/packages/docs/src/services/permission/permission-point/paragraph/edit.ts
@@ -0,0 +1,31 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IPermissionPoint } from '@univerjs/core';
+import { PermissionStatus } from '@univerjs/core';
+import { UnitAction, UnitObject } from '@univerjs/protocol';
+
+export class DocumentParagraphEditPermission implements IPermissionPoint {
+ readonly type = UnitObject.DocumentParagraph;
+ readonly subType = UnitAction.Edit;
+ readonly status = PermissionStatus.INIT;
+ readonly id: string;
+ value = true;
+
+ constructor(readonly unitId: string, readonly objectId: string) {
+ this.id = `${this.type}.${this.subType}_${unitId}_${objectId}`;
+ }
+}
diff --git a/packages/docs/src/services/permission/permission-point/section/edit.ts b/packages/docs/src/services/permission/permission-point/section/edit.ts
new file mode 100644
index 0000000000..057c90e5d1
--- /dev/null
+++ b/packages/docs/src/services/permission/permission-point/section/edit.ts
@@ -0,0 +1,31 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IPermissionPoint } from '@univerjs/core';
+import { PermissionStatus } from '@univerjs/core';
+import { UnitAction, UnitObject } from '@univerjs/protocol';
+
+export class DocumentSectionEditPermission implements IPermissionPoint {
+ readonly type = UnitObject.DocumentSection;
+ readonly subType = UnitAction.Edit;
+ readonly status = PermissionStatus.INIT;
+ readonly id: string;
+ value = true;
+
+ constructor(readonly unitId: string, readonly objectId: string) {
+ this.id = `${this.type}.${this.subType}_${unitId}_${objectId}`;
+ }
+}
diff --git a/packages/engine-render/src/__tests__/scene.transformer.spec.ts b/packages/engine-render/src/__tests__/scene.transformer.spec.ts
index bd10335c63..c3adfe2c14 100644
--- a/packages/engine-render/src/__tests__/scene.transformer.spec.ts
+++ b/packages/engine-render/src/__tests__/scene.transformer.spec.ts
@@ -77,4 +77,30 @@ describe('Transformer', () => {
scene.dispose();
engine.dispose();
});
+
+ it('keeps read-only objects selectable without starting a move gesture', () => {
+ const engine = new Engine('transformer-readonly-engine', { elementWidth: 100, elementHeight: 100, dpr: 1 });
+ const scene = new Scene('transformer-readonly-scene', engine);
+ const rect = new Rect('transformer-readonly-rect', { width: 10, height: 10 });
+ rect.transformerConfig = {
+ moveEnabled: false,
+ resizeEnabled: false,
+ rotateEnabled: false,
+ };
+ const transformer = new Transformer(scene);
+ const changeStart = vi.fn();
+ const subscription = transformer.changeStart$.subscribe(changeStart);
+
+ transformer.attachTo(rect);
+ rect.onPointerDown$.emitEvent({ offsetX: 5, offsetY: 5 } as never);
+
+ expect(transformer.getSelectedObjectMap().get(rect.oKey)).toBe(rect);
+ expect(changeStart).not.toHaveBeenCalled();
+
+ subscription.unsubscribe();
+ transformer.dispose();
+ rect.dispose();
+ scene.dispose();
+ engine.dispose();
+ });
});
diff --git a/packages/engine-render/src/basics/transformer-config.ts b/packages/engine-render/src/basics/transformer-config.ts
index db5ebf703a..a84f83bdf3 100644
--- a/packages/engine-render/src/basics/transformer-config.ts
+++ b/packages/engine-render/src/basics/transformer-config.ts
@@ -48,6 +48,7 @@ export interface ITransformerConfig {
borderSpacing?: number;
resizeEnabled?: boolean;
+ moveEnabled?: boolean;
enabledAnchors?: number[];
anchorFill?: string;
anchorStroke?: string;
@@ -81,6 +82,7 @@ export interface ITransformerConfig {
}
export const DEFAULT_TRANSFORMER_CONFIG = {
+ moveEnabled: true,
resizeEnabled: true,
rotateEnabled: true,
rotateAnchorOffset: 28,
diff --git a/packages/engine-render/src/scene.transformer.ts b/packages/engine-render/src/scene.transformer.ts
index fddb280ca1..e8e42b102d 100644
--- a/packages/engine-render/src/scene.transformer.ts
+++ b/packages/engine-render/src/scene.transformer.ts
@@ -158,6 +158,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
hoverEnterFunc: Nullable<(e: IPointerEvent | IMouseEvent) => void>;
hoverLeaveFunc: Nullable<(e: IPointerEvent | IMouseEvent) => void>;
+ moveEnabled: boolean = DEFAULT_TRANSFORMER_CONFIG.moveEnabled;
resizeEnabled: boolean = DEFAULT_TRANSFORMER_CONFIG.resizeEnabled;
rotateEnabled: boolean = DEFAULT_TRANSFORMER_CONFIG.rotateEnabled;
@@ -356,6 +357,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
hoverEnabled,
hoverEnterFunc,
hoverLeaveFunc,
+ moveEnabled,
resizeEnabled,
rotateEnabled,
rotationSnaps,
@@ -404,6 +406,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
hoverEnabled = objectTransformerConfig.hoverEnabled ?? hoverEnabled;
hoverEnterFunc = objectTransformerConfig.hoverEnterFunc ?? hoverEnterFunc;
hoverLeaveFunc = objectTransformerConfig.hoverLeaveFunc ?? hoverLeaveFunc;
+ moveEnabled = objectTransformerConfig.moveEnabled ?? moveEnabled;
resizeEnabled = objectTransformerConfig.resizeEnabled ?? resizeEnabled;
rotateEnabled = objectTransformerConfig.rotateEnabled ?? rotateEnabled;
rotationSnaps = objectTransformerConfig.rotationSnaps ?? rotationSnaps;
@@ -453,6 +456,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
hoverEnabled,
hoverEnterFunc,
hoverLeaveFunc,
+ moveEnabled,
resizeEnabled,
rotateEnabled,
rotationSnaps,
@@ -509,7 +513,12 @@ export class Transformer extends Disposable implements ITransformerConfig {
this._startOffsetX = evtOffsetX;
this._startOffsetY = evtOffsetY;
- const { isCropper } = this._getConfig(applyObject);
+ const { isCropper, moveEnabled } = this._getConfig(applyObject);
+
+ if (!isCropper && !moveEnabled) {
+ this._updateActiveObjectList(applyObject, evt);
+ return;
+ }
const scene = this._getTopScene();
diff --git a/packages/protocol/src/ts/univer/permission.ts b/packages/protocol/src/ts/univer/permission.ts
index 1978fdd327..77b5e8e2b3 100644
--- a/packages/protocol/src/ts/univer/permission.ts
+++ b/packages/protocol/src/ts/univer/permission.ts
@@ -108,6 +108,18 @@ export enum UnitObject {
Base = 6,
Board = 7,
Pdf = 8,
+ DocumentSection = 9,
+ DocumentParagraph = 10,
+ DocumentEntity = 11,
+ SlidePage = 12,
+ SlideElement = 13,
+ SlideMaster = 14,
+ BaseTable = 15,
+ BaseField = 16,
+ BaseRecord = 17,
+ BaseView = 18,
+ BaseDashboard = 19,
+ BoardElement = 20,
UNRECOGNIZED = -1,
}
diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkPopup.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkPopup.tsx
index 9e2c3d15b5..b14e715da6 100644
--- a/packages/sheets-hyper-link-ui/src/views/CellLinkPopup.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkPopup.tsx
@@ -17,7 +17,7 @@
import type { ICustomRange, Nullable, Workbook } from '@univerjs/core';
import type { LocaleKey } from '../locale/types';
import { ICommandService, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';
-import { borderClassName, clsx, MessageType, Tooltip } from '@univerjs/design';
+import { borderClassName, Button, clsx, MessageType, Tooltip } from '@univerjs/design';
import { AllBorderIcon, CopyIcon, LinkIcon, SheetsMultiIcon, UnlinkIcon, WriteIcon } from '@univerjs/icons';
import {
CancelHyperLinkCommand,
@@ -108,36 +108,36 @@ export const CellLinkPopupPure = (props: ICellLinkPopupPureProps) => {
univer-gap-2
`}
>
- {copyPermission && (
- <div
- className={clsx(`
- univer-flex univer-size-6 univer-cursor-pointer univer-flex-row univer-items-center
- univer-justify-center univer-rounded univer-text-base
- hover:univer-bg-gray-100
- dark:hover:!univer-bg-gray-700
- `, { 'univer-text-red-500': isError })}
- onClick={() => {
- if (isError) {
- return;
- }
- if (linkObj.type !== SheetHyperLinkType.URL) {
- const url = new URL(window.location.href);
- url.hash = linkObj.url.slice(1);
- navigator.clipboard.writeText(url.href);
- } else {
- navigator.clipboard.writeText(linkObj.url);
- }
- messageService.show({
- content: localeService.t<LocaleKey>('sheets-hyper-link-ui.message.coped'),
- type: MessageType.Info,
- });
- }}
- >
- <Tooltip placement="bottom" title={localeService.t<LocaleKey>('sheets-hyper-link-ui.popup.copy')}>
- <CopyIcon className="dark:!univer-text-gray-0" />
- </Tooltip>
- </div>
- )}
+ <Button
+ type="button"
+ variant="text"
+ size="small"
+ data-u-comp="cell-link-popup-copy"
+ aria-label={localeService.t<LocaleKey>('sheets-hyper-link-ui.popup.copy')}
+ className={clsx(`
+ !univer-flex univer-size-6 !univer-rounded !univer-border-0 !univer-p-0 !univer-text-base
+ !univer-font-normal
+ disabled:!univer-pointer-events-auto
+ `, { 'univer-text-red-500': isError })}
+ disabled={!copyPermission || isError}
+ onClick={() => {
+ if (linkObj.type !== SheetHyperLinkType.URL) {
+ const url = new URL(window.location.href);
+ url.hash = linkObj.url.slice(1);
+ navigator.clipboard.writeText(url.href);
+ } else {
+ navigator.clipboard.writeText(linkObj.url);
+ }
+ messageService.show({
+ content: localeService.t<LocaleKey>('sheets-hyper-link-ui.message.coped'),
+ type: MessageType.Info,
+ });
+ }}
+ >
+ <Tooltip placement="bottom" title={localeService.t<LocaleKey>('sheets-hyper-link-ui.popup.copy')}>
+ <CopyIcon className="dark:!univer-text-gray-0" />
+ </Tooltip>
+ </Button>
{editPermission && (
<>
<div
diff --git a/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsx b/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsx
index cbb1d804b5..4d69ba72de 100644
--- a/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsx
@@ -355,6 +355,7 @@ function renderPopup(
});
return {
+ copy: container.querySelector<HTMLButtonElement>('[data-u-comp="cell-link-popup-copy"]'),
edit: container.querySelector('[data-u-comp="cell-link-popup-edit"]') as HTMLElement,
remove: container.querySelector('[data-u-comp="cell-link-popup-remove"]') as HTMLElement,
};
@@ -386,6 +387,7 @@ describe('CellLinkPopupPure', () => {
executedCommands.push({ id: command.id, params: command.params });
});
const actions = renderPopup(root, container, currentTestBed);
+ expect(actions.copy?.disabled).toBe(true);
await act(async () => {
actions.edit.click();
diff --git a/packages/sheets-thread-comment-ui/src/controllers/__tests__/sheets-thread-comment-permission.controller.spec.ts b/packages/sheets-thread-comment-ui/src/controllers/__tests__/sheets-thread-comment-permission.controller.spec.ts
index 38d877e5ae..f4b0a9354f 100644
--- a/packages/sheets-thread-comment-ui/src/controllers/__tests__/sheets-thread-comment-permission.controller.spec.ts
+++ b/packages/sheets-thread-comment-ui/src/controllers/__tests__/sheets-thread-comment-permission.controller.spec.ts
@@ -25,7 +25,7 @@ import {
UpdateCommentCommand,
} from '@univerjs/thread-comment';
import { describe, expect, it, vi } from 'vitest';
-import { ShowAddSheetCommentModalOperation } from '../../commands/operations/comment.operation';
+import { AddSheetDrawingCommentOperation, ShowAddSheetCommentModalOperation } from '../../commands/operations/comment.operation';
import { SheetsThreadCommentPermissionController } from '../sheets-thread-comment-permission.controller';
type BeforeCommandHandler = (command: { id: string; params?: unknown }) => void;
@@ -67,6 +67,7 @@ describe('SheetsThreadCommentPermissionController', () => {
const beforeCommandHandler = getBeforeCommandHandler();
beforeCommandHandler?.({ id: ShowAddSheetCommentModalOperation.id });
+ beforeCommandHandler?.({ id: AddSheetDrawingCommentOperation.id });
beforeCommandHandler?.({
id: AddCommentCommand.id,
params: {
@@ -92,7 +93,7 @@ describe('SheetsThreadCommentPermissionController', () => {
},
});
- expect(permissionCheck.permissionCheckWithoutRange).toHaveBeenCalledTimes(1);
+ expect(permissionCheck.permissionCheckWithoutRange).toHaveBeenCalledTimes(2);
expect(permissionCheck.permissionCheckWithRanges).toHaveBeenCalledWith(expect.any(Object), [{
startRow: 1,
startColumn: 1,
@@ -105,7 +106,7 @@ describe('SheetsThreadCommentPermissionController', () => {
endRow: 3,
endColumn: 2,
}], 'unit-1', 'sheet-1');
- expect(permissionCheck.blockExecuteWithoutPermission).toHaveBeenCalledTimes(4);
+ expect(permissionCheck.blockExecuteWithoutPermission).toHaveBeenCalledTimes(5);
expect(permissionCheck.blockExecuteWithoutPermission).toHaveBeenLastCalledWith('sheets-thread-comment-ui.permission.commentErr');
controller.dispose();
diff --git a/packages/sheets-thread-comment-ui/src/controllers/sheets-thread-comment-permission.controller.ts b/packages/sheets-thread-comment-ui/src/controllers/sheets-thread-comment-permission.controller.ts
index 53adcd3a39..959d075418 100644
--- a/packages/sheets-thread-comment-ui/src/controllers/sheets-thread-comment-permission.controller.ts
+++ b/packages/sheets-thread-comment-ui/src/controllers/sheets-thread-comment-permission.controller.ts
@@ -41,7 +41,7 @@ import {
ThreadCommentAnchorKind,
UpdateCommentCommand,
} from '@univerjs/thread-comment';
-import { ShowAddSheetCommentModalOperation, ToggleSheetCommentPanelOperation } from '../commands/operations/comment.operation';
+import { AddSheetDrawingCommentOperation, ShowAddSheetCommentModalOperation, ToggleSheetCommentPanelOperation } from '../commands/operations/comment.operation';
export class SheetsThreadCommentPermissionController extends Disposable {
constructor(
@@ -60,7 +60,7 @@ export class SheetsThreadCommentPermissionController extends Disposable {
this._commandService.beforeCommandExecuted((command: ICommandInfo) => {
const { id } = command;
- if (id === ShowAddSheetCommentModalOperation.id || id === ToggleSheetCommentPanelOperation.id) {
+ if (id === AddSheetDrawingCommentOperation.id || id === ShowAddSheetCommentModalOperation.id || id === ToggleSheetCommentPanelOperation.id) {
const permission = this._sheetPermissionCheckController.permissionCheckWithoutRange({
workbookTypes: [WorkbookCommentPermission],
worksheetTypes: [WorksheetViewPermission],
diff --git a/packages/sheets-thread-comment-ui/src/menu/menu.ts b/packages/sheets-thread-comment-ui/src/menu/menu.ts
index d9f02cb36c..bf2525886d 100644
--- a/packages/sheets-thread-comment-ui/src/menu/menu.ts
+++ b/packages/sheets-thread-comment-ui/src/menu/menu.ts
@@ -29,6 +29,10 @@ export const drawingCommentMenuFactory = (accessor: IAccessor) => ({
title: 'sheets-thread-comment-ui.menu.addComment',
tooltip: 'sheets-thread-comment-ui.menu.addComment',
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),
+ disabled$: getCurrentRangeDisable$(accessor, {
+ workbookTypes: [WorkbookCommentPermission],
+ worksheetTypes: [WorksheetViewPermission],
+ }),
});
export const threadCommentMenuFactory = (accessor: IAccessor) => {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 291a72bf59..5c54f8c5f4 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1131,6 +1131,9 @@ importers:
'@univerjs/engine-render':
specifier: workspace:*
version: link:../engine-render
+ '@univerjs/protocol':
+ specifier: workspace:*
+ version: link:../protocol
devDependencies:
'@univerjs-infra/shared':
specifier: workspace:*
@@ -1206,6 +1209,9 @@ importers:
'@univerjs-infra/shared':
specifier: workspace:*
version: link:../../common/shared
+ '@univerjs/protocol':
+ specifier: workspace:*
+ version: link:../protocol
postcss:
specifier: ^8.5.26
version: 8.5.26
@@ -1301,6 +1307,9 @@ importers:
'@univerjs/icons':
specifier: 1.38.0
+ '@univerjs/protocol':
+ specifier: workspace:*
+ version: link:../protocol
'@univerjs/ui':
specifier: workspace:*
version: link:../ui
@@ -1433,6 +1442,9 @@ importers:
'@univerjs/icons':
specifier: 1.38.0
+ '@univerjs/protocol':
+ specifier: workspace:*
+ version: link:../protocol
'@univerjs/thread-comment':
specifier: workspace:*
version: link:../thread-comment
@@ -1482,6 +1494,9 @@ importers:
'@univerjs/icons':
specifier: 1.38.0
+ '@univerjs/protocol':
+ specifier: workspace:*
+ version: link:../protocol
'@univerjs/ui':
specifier: workspace:*
version: link:../ui