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.

fix(sheets): enforce permissions and size mobile dialogs (#8078)

wpxp1234564348dfa6e2e5
diff --git a/packages/sheets-ui/src/controllers/render-controllers/mobile/__tests__/mobile-header-resize.render-controller.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/mobile/__tests__/mobile-header-resize.render-controller.spec.ts
index f5010d191e..712ee272a1 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/mobile/__tests__/mobile-header-resize.render-controller.spec.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/mobile/__tests__/mobile-header-resize.render-controller.spec.ts
@@ -17,16 +17,21 @@
import type { Workbook } from '@univerjs/core';
import type { BaseObject, IPointerEvent, IRenderContext } from '@univerjs/engine-render';
import type { ISelectionWithStyle } from '@univerjs/sheets';
-import { EventSubject, ICommandService, LocaleType, RANGE_TYPE, RedoCommand, UndoCommand } from '@univerjs/core';
+import { EventSubject, ICommandService, IPermissionService, LocaleType, RANGE_TYPE, RedoCommand, UndoCommand } from '@univerjs/core';
import {
DeltaColumnWidthCommand,
DeltaRowHeightCommand,
+ RangeProtectionRuleModel,
SelectionMoveType,
SetWorksheetColWidthMutation,
SetWorksheetRowHeightMutation,
SetWorksheetRowIsAutoHeightMutation,
SheetSkeletonService,
SheetsSelectionsService,
+ WorkbookEditablePermission,
+ WorksheetEditPermission,
+ WorksheetSetColumnStylePermission,
+ WorksheetSetRowStylePermission,
} from '@univerjs/sheets';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { SheetScrollManagerService } from '../../../../services/scroll-manager.service';
@@ -80,9 +85,16 @@ function createController(zoomRatio = 2, size = 20) {
cellData: {},
},
},
- }, [[SheetSkeletonService]]);
+ }, [[SheetSkeletonService], [RangeProtectionRuleModel]]);
testBeds.push(testBed);
const injector = testBed.univer.__getInjector();
+ const permissions = injector.get(IPermissionService);
+ [
+ new WorkbookEditablePermission('test'),
+ new WorksheetEditPermission('test', 'sheet-1'),
+ new WorksheetSetRowStylePermission('test', 'sheet-1'),
+ new WorksheetSetColumnStylePermission('test', 'sheet-1'),
+ ].forEach((permission) => permissions.addPermissionPoint(permission));
const canvasElement = document.createElement('canvas');
document.body.appendChild(canvasElement);
const scene = {
@@ -132,6 +144,7 @@ function createController(zoomRatio = 2, size = 20) {
controller,
commandService,
executeCommand,
+ permissions,
scene,
skeleton: skeletonManager.getCurrentSkeleton()!,
selections: injector.get(SheetsSelectionsService),
@@ -145,6 +158,35 @@ afterEach(() => {
});
describe('MobileHeaderResizeRenderController business methods', () => {
+ it.each(['row', 'column'] as const)('hides the %s handle and cancels a drag when edit permission is revoked', (axis) => {
+ const { controller, selections, permissions, scene, executeCommand } = createController();
+ selections.setSelections([{
+ range: { startRow: 0, endRow: 2, startColumn: 0, endColumn: 1, rangeType: axis === 'row' ? RANGE_TYPE.ROW : RANGE_TYPE.COLUMN },
+ primary: null,
+ style: null,
+ }], SelectionMoveType.MOVE_END);
+ const handle = axis === 'row' ? controller._rowResizeButton : controller._columnResizeButton;
+ expect(handle.visible).toBe(true);
+ handle.onPointerDown$.emitEvent(pointerEvent('pointerdown', 100, 100, 1));
+ document.dispatchEvent(pointerEvent('pointermove', 110, 110, 1));
+
+ permissions.updatePermissionPoint(new WorkbookEditablePermission('test').id, false);
+ expect(handle.visible).toBe(false);
+ expect(scene.enableObjectsEvent).toHaveBeenCalled();
+ document.dispatchEvent(pointerEvent('pointerup', 110, 110, 1));
+ expect(executeCommand).not.toHaveBeenCalled();
+
+ permissions.updatePermissionPoint(new WorkbookEditablePermission('test').id, true);
+ expect(handle.visible).toBe(true);
+ const permission = axis === 'row'
+ ? new WorksheetSetRowStylePermission('test', 'sheet-1')
+ : new WorksheetSetColumnStylePermission('test', 'sheet-1');
+ permissions.updatePermissionPoint(permission.id, false);
+ expect(handle.visible).toBe(false);
+ handle.onPointerDown$.emitEvent(pointerEvent('pointerdown', 100, 100, 1));
+ expect(executeCommand).not.toHaveBeenCalled();
+ });
+
it.each([
{ axis: 'row', pointerType: 'mouse' },
{ axis: 'column', pointerType: 'mouse' },
diff --git a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-header-resize.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-header-resize.render-controller.ts
index 044d32642f..b112e8461e 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-header-resize.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-header-resize.render-controller.ts
@@ -23,16 +23,23 @@ import {
ICommandService,
IContextService,
Inject,
+ Injector,
+ IPermissionService,
RANGE_TYPE,
toDisposable,
} from '@univerjs/core';
import { Rect } from '@univerjs/engine-render';
import {
attachSelectionWithCoord,
+ checkRangesEditablePermission,
DeltaColumnWidthCommand,
DeltaRowHeightCommand,
+ RangeProtectionRuleModel,
SheetsSelectionsService,
+ WorksheetSetColumnStylePermission,
+ WorksheetSetRowStylePermission,
} from '@univerjs/sheets';
+import { merge } from 'rxjs';
import { SHEET_COMPONENT_HEADER_LAYER_INDEX } from '../../../common/keys';
import { MOBILE_EXPANDING_SELECTION, MOBILE_PINCH_ZOOMING } from '../../../consts/mobile-context';
import { SheetScrollManagerService } from '../../../services/scroll-manager.service';
@@ -74,7 +81,10 @@ export class MobileHeaderResizeRenderController extends Disposable implements IR
@Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@ICommandService private readonly _commandService: ICommandService,
@IContextService private readonly _contextService: IContextService,
- @Inject(SheetScrollManagerService) private readonly _scrollManagerService: SheetScrollManagerService
+ @Inject(SheetScrollManagerService) private readonly _scrollManagerService: SheetScrollManagerService,
+ @Inject(Injector) private readonly _injector: Injector,
+ @IPermissionService private readonly _permissionService: IPermissionService,
+ @Inject(RangeProtectionRuleModel) private readonly _rangeProtectionRuleModel: RangeProtectionRuleModel
) {
super();
this._init();
@@ -102,6 +112,17 @@ export class MobileHeaderResizeRenderController extends Disposable implements IR
this._initResizeShapes();
this._initSelectionListener();
this._initScrollListener();
+
+ this.disposeWithMe(
+ merge(
+ this._permissionService.permissionPointUpdate$,
+ this._rangeProtectionRuleModel.ruleChange$,
+ this._context.unit.activeSheet$
+ ).subscribe(() => {
+ this._cancelResize();
+ this._handleSelectionChange(this._selectionManagerService.getCurrentSelections());
+ })
+ );
}
private _initResizeShapes(): void {
@@ -144,7 +165,7 @@ export class MobileHeaderResizeRenderController extends Disposable implements IR
this.disposeWithMe(this._scrollSubscription);
}
- private _handleSelectionChange(selections: ISelectionWithStyle[]): void {
+ private _handleSelectionChange(selections: readonly ISelectionWithStyle[]): void {
// Hide all buttons first
this._rowResizeButton?.hide();
this._columnResizeButton?.hide();
@@ -161,9 +182,9 @@ export class MobileHeaderResizeRenderController extends Disposable implements IR
const rangeType = selection.range.rangeType;
// Only show resize button for row/column selections
- if (rangeType === RANGE_TYPE.ROW) {
+ if (rangeType === RANGE_TYPE.ROW && this._canResize('row')) {
this._showRowResizeButton(selection);
- } else if (rangeType === RANGE_TYPE.COLUMN) {
+ } else if (rangeType === RANGE_TYPE.COLUMN && this._canResize('column')) {
this._showColumnResizeButton(selection);
}
}
@@ -285,7 +306,7 @@ export class MobileHeaderResizeRenderController extends Disposable implements IR
private _startResize(evt: IPointerEvent | IMouseEvent, type: 'row' | 'column'): void {
const skeleton = this._sheetSkeletonManagerService.getCurrentSkeleton();
- if (!skeleton) {
+ if (!skeleton || !this._canResize(type)) {
return;
}
@@ -376,7 +397,7 @@ export class MobileHeaderResizeRenderController extends Disposable implements IR
this._cleanupResize();
e.preventDefault();
// A meaningful drag can collapse a dimension smaller than MINIMAL_OFFSET.
- if (shouldResize) {
+ if (shouldResize && this._canResize(type)) {
await this._commandService.executeCommand(
type === 'row' ? DeltaRowHeightCommand.id : DeltaColumnWidthCommand.id,
type === 'row' ? { deltaY: totalDelta, anchorRow: anchor } : { deltaX: totalDelta, anchorCol: anchor }
@@ -387,6 +408,25 @@ export class MobileHeaderResizeRenderController extends Disposable implements IR
this._bindResizeListeners(canvasElement, pointerId, handlePointerMove, handlePointerUp);
}
+ private _canResize(type: 'row' | 'column'): boolean {
+ const unitId = this._context.unitId;
+ const subUnitId = this._context.unit.getActiveSheet()?.getSheetId();
+ if (!subUnitId) {
+ return false;
+ }
+
+ const permission = type === 'row'
+ ? new WorksheetSetRowStylePermission(unitId, subUnitId)
+ : new WorksheetSetColumnStylePermission(unitId, subUnitId);
+ return this._permissionService.getPermissionPoint(permission.id)?.value === true
+ && checkRangesEditablePermission(
+ this._injector,
+ unitId,
+ subUnitId,
+ this._selectionManagerService.getCurrentSelections().map((selection) => selection.range)
+ );
+ }
+
private _bindResizeListeners(
canvasElement: HTMLCanvasElement,
pointerId: number,
diff --git a/packages/sheets-ui/src/views/mobile/action-panel/MobileSheetActionPanel.tsx b/packages/sheets-ui/src/views/mobile/action-panel/MobileSheetActionPanel.tsx
index aadea79d60..cbee335073 100644
--- a/packages/sheets-ui/src/views/mobile/action-panel/MobileSheetActionPanel.tsx
+++ b/packages/sheets-ui/src/views/mobile/action-panel/MobileSheetActionPanel.tsx
@@ -17,8 +17,6 @@
import type { Worksheet } from '@univerjs/core';
import type { ISelectionWithStyle } from '@univerjs/sheets';
import type { IValueOption, MobileDrawerSnap } from '@univerjs/ui';
-import type { LocaleKey } from '../../../locale/types';
-import type { IMobileStyleCommand, MobileStyleView } from './MobileStylePanel';
import {
DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
EDITOR_ACTIVATED,
@@ -26,13 +24,21 @@ import {
FOCUSING_FX_BAR_EDITOR,
ICommandService,
IContextService,
+ Injector,
+ IPermissionService,
LocaleService,
} from '@univerjs/core';
import { clsx, resetButtonClassName, useMobileKeyboardViewportLayout } from '@univerjs/design';
import { IEditorService } from '@univerjs/docs-ui';
import { DeviceInputEventType } from '@univerjs/engine-render';
import { KeyboardIcon, MenuIcon, MoreLeftIcon } from '@univerjs/icons';
-import { getPrimaryForRange, SheetsSelectionsService } from '@univerjs/sheets';
+import {
+ checkRangesEditablePermission,
+ getPrimaryForRange,
+ RangeProtectionRuleModel,
+ SheetsSelectionsService,
+ WorksheetSetCellValuePermission,
+} from '@univerjs/sheets';
import {
ContextMenuGroup,
ContextMenuPosition,
@@ -43,13 +49,18 @@ import {
MobileMenu,
RibbonPosition,
RibbonStartGroup,
+ useConfigValue,
useDependency,
useObservable,
} from '@univerjs/ui';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { map, startWith } from 'rxjs';
+import { map, merge, startWith } from 'rxjs';
+import type { IUniverSheetsUIConfig } from '../../../config/config';
+import type { LocaleKey } from '../../../locale/types';
+import type { IMobileStyleCommand, MobileStyleView } from './MobileStylePanel';
import { ScrollCommand, SetScrollRelativeCommand } from '../../../commands/commands/set-scroll.command';
import { SetCellEditVisibleOperation } from '../../../commands/operations/cell-edit.operation';
+import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../../config/config';
import {
MOBILE_FORMULA_OPERATOR_BAR_HEIGHT,
MOBILE_FORMULA_OPERATORS_VISIBLE,
@@ -165,6 +176,22 @@ function MobileSheetActionPanelContent() {
const menuManagerService = useDependency(IMenuManagerService);
const ribbonService = useDependency(IRibbonService);
const selectionManagerService = useDependency(SheetsSelectionsService);
+ const injector = useDependency(Injector);
+ const permissionService = useDependency(IPermissionService);
+ const rangeProtectionRuleModel = useDependency(RangeProtectionRuleModel);
+ const config = useConfigValue<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);
+ const editingDisabled = useObservable(
+ () => merge(
+ workbook?.activeSheet$ ?? [],
+ selectionManagerService.selectionMoveEnd$,
+ selectionManagerService.selectionSet$,
+ permissionService.permissionPointUpdate$,
+ rangeProtectionRuleModel.ruleChange$
+ ).pipe(startWith(null), map(() => !canEditCell())),
+ true,
+ false,
+ [workbook, selectionManagerService, permissionService, rangeProtectionRuleModel, injector, config?.disableEdit]
+ );
const ribbon = useObservable(ribbonService.ribbon$, []);
const operationSchemas = useObservable(
() => menuManagerService.menuChanged$.pipe(
@@ -344,8 +371,13 @@ function MobileSheetActionPanelContent() {
}
function openKeyboard() {
+ if (!canEditCell()) {
+ return;
+ }
+
closeTools();
layoutService.focus();
+
if (editing) {
contextService.setContextValue(FOCUSING_FX_BAR_EDITOR, true);
editorService.focus(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
@@ -359,6 +391,24 @@ function MobileSheetActionPanelContent() {
}).catch(() => undefined);
}
+ function canEditCell() {
+ const worksheet = workbook?.getActiveSheet();
+ const primary = selectionManagerService.getCurrentLastSelection()?.primary;
+ if (config?.disableEdit || !workbook || !worksheet || !primary) {
+ return false;
+ }
+
+ const unitId = workbook.getUnitId();
+ const subUnitId = worksheet.getSheetId();
+ return permissionService.getPermissionPoint(new WorksheetSetCellValuePermission(unitId, subUnitId).id)?.value === true
+ && checkRangesEditablePermission(injector, unitId, subUnitId, [{
+ startRow: primary.actualRow,
+ endRow: primary.actualRow,
+ startColumn: primary.actualColumn,
+ endColumn: primary.actualColumn,
+ }]);
+ }
+
function executeMenuItem(params: IValueOption | IMobileStyleCommand): boolean {
const command = getMobileMenuCommand(params);
if (!command) {
@@ -410,10 +460,12 @@ function MobileSheetActionPanelContent() {
<button
type="button"
aria-label={localeService.t<LocaleKey>('sheets-ui.shortcut.sheet.start-editing')}
+ disabled={editingDisabled}
className={clsx(resetButtonClassName, `
univer-pointer-events-auto univer-flex univer-size-12 univer-items-center univer-justify-center
univer-rounded-full univer-bg-gray-0 univer-text-xl univer-text-primary-600 univer-shadow-lg
active:univer-bg-gray-100
+ disabled:univer-cursor-not-allowed disabled:univer-opacity-40
dark:!univer-bg-gray-800 dark:!univer-text-primary-400
dark:active:!univer-bg-gray-700
`)}
@@ -451,10 +503,12 @@ function MobileSheetActionPanelContent() {
<button
type="button"
aria-label={localeService.t<LocaleKey>('sheets-ui.shortcut.sheet.start-editing')}
+ disabled={editingDisabled}
className={clsx(resetButtonClassName, `
univer-pointer-events-auto univer-flex univer-size-12 univer-items-center univer-justify-center
univer-rounded-full univer-bg-gray-0 univer-text-xl univer-text-primary-600 univer-shadow-lg
active:univer-bg-gray-100
+ disabled:univer-cursor-not-allowed disabled:univer-opacity-40
dark:!univer-bg-gray-800 dark:!univer-text-primary-400
dark:active:!univer-bg-gray-700
`)}
diff --git a/packages/sheets-ui/src/views/mobile/action-panel/MobileStylePanel.tsx b/packages/sheets-ui/src/views/mobile/action-panel/MobileStylePanel.tsx
index f6dfa502fd..702a7fe70a 100644
--- a/packages/sheets-ui/src/views/mobile/action-panel/MobileStylePanel.tsx
+++ b/packages/sheets-ui/src/views/mobile/action-panel/MobileStylePanel.tsx
@@ -24,7 +24,6 @@ import type {
IValueOption,
MenuItemDefaultValueType,
} from '@univerjs/ui';
-import type { LocaleKey } from '../../../locale/types';
import { BorderStyleTypes, BorderType, LocaleService, ThemeService } from '@univerjs/core';
import {
borderBottomClassName,
@@ -58,6 +57,7 @@ import {
} from '@univerjs/ui';
import { useMemo, useState } from 'react';
import { isObservable } from 'rxjs';
+import type { LocaleKey } from '../../../locale/types';
import {
ResetRangeTextColorCommand,
SetRangeBoldCommand,
@@ -185,7 +185,7 @@ export type MobileStyleView =
config: IMobileNumberFormatMenuConfig;
};
-export function MobileStylePanel(props: {
+interface IMobileStylePanelProps {
groups: IMenuSchema[];
currentView: MobileStyleView | null;
recentColors: string[];
@@ -193,7 +193,41 @@ export function MobileStylePanel(props: {
onBack: () => void;
onExecute: (params: IMobileStyleCommand) => void;
onUseColor: (color: string) => void;
-}) {
+}
+
+export function MobileStylePanel(props: IMobileStylePanelProps) {
+ const { currentView, onExecute } = props;
+ const disabled = useObservable(currentView?.item.disabled$, false);
+ const hidden = useObservable(currentView?.item.hidden$, false);
+
+ function executeCommand(params: IMobileStyleCommand) {
+ if (!disabled && !hidden) {
+ onExecute(params);
+ }
+ }
+
+ if (currentView && hidden) {
+ return null;
+ }
+
+ if (!currentView) {
+ return <MobileStylePanelContent {...props} />;
+ }
+
+ return (
+ <fieldset
+ disabled={disabled}
+ className="
+ univer-m-0 univer-min-w-0 univer-border-0 univer-p-0
+ disabled:univer-opacity-40
+ "
+ >
+ <MobileStylePanelContent {...props} onExecute={executeCommand} />
+ </fieldset>
+ );
+}
+
+function MobileStylePanelContent(props: IMobileStylePanelProps) {
const { groups, currentView, recentColors, onOpenView, onBack, onExecute, onUseColor } = props;
const localeService = useDependency(LocaleService);
const themeService = useDependency(ThemeService);
@@ -571,6 +605,7 @@ function MobileNumberFormatGroup(props: {
>
<MobileActionRow
title={localeService.t(config.detailTitle)}
+ disabled={status.disabled}
value={typeof status.value === 'string' ? status.value : undefined}
valueType="text"
trailing={<MoreRightIcon />}
@@ -898,6 +933,7 @@ function MobileStyleNavigationItem(props: {
return (
<MobileActionRow
title={title}
+ disabled={status.disabled}
value={typeof status.value === 'string' ? status.value : undefined}
bordered={bordered}
trailing={<MoreRightIcon />}
diff --git a/packages/sheets-ui/src/views/mobile/action-panel/__tests__/MobileSheetActionPanel.spec.ts b/packages/sheets-ui/src/views/mobile/action-panel/__tests__/MobileSheetActionPanel.spec.ts
index 5428add09c..b1e8d3a502 100644
--- a/packages/sheets-ui/src/views/mobile/action-panel/__tests__/MobileSheetActionPanel.spec.ts
+++ b/packages/sheets-ui/src/views/mobile/action-panel/__tests__/MobileSheetActionPanel.spec.ts
@@ -14,15 +14,16 @@
* limitations under the License.
*/
+import type { IWorkbookData, Workbook } from '@univerjs/core';
import type { IMenuSchema } from '@univerjs/ui';
import type { Root } from 'react-dom/client';
-import type { MobileNumberFormatItem } from '../MobileStylePanel';
import {
CommandType,
FOCUSING_COMMON_DRAWINGS,
getSheetsEmptySnapshot,
ICommandService,
IContextService,
+ IPermissionService,
IUniverInstanceService,
LocaleService,
LocaleType,
@@ -30,7 +31,14 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import { IEditorService } from '@univerjs/docs-ui';
-import { SheetsSelectionsService } from '@univerjs/sheets';
+import {
+ getPrimaryForRange,
+ RangeProtectionRuleModel,
+ SheetsSelectionsService,
+ WorkbookEditablePermission,
+ WorksheetEditPermission,
+ WorksheetSetCellValuePermission,
+} from '@univerjs/sheets';
import {
ComponentManager,
IconManager,
@@ -47,6 +55,8 @@ import { act, createElement } from 'react';
import { createRoot } from 'react-dom/client';
import { BehaviorSubject, EMPTY } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
+import type { MobileNumberFormatItem } from '../MobileStylePanel';
+import { SetCellEditVisibleOperation } from '../../../../commands/operations/cell-edit.operation';
import enUS from '../../../../locale/en-US';
import { IEditorBridgeService } from '../../../../services/editor-bridge.service';
import {
@@ -112,7 +122,11 @@ function renderMobileSheetActionPanel(ribbon: IMenuSchema[] = []) {
injector.get(LocaleService).load({ [LocaleType.EN_US]: enUS });
injector.get(LocaleService).setLocale(LocaleType.EN_US);
- univer.createUnit(UniverInstanceType.UNIVER_SHEET, getSheetsEmptySnapshot('mobile-sheet'));
+ injector.get(LocaleService).setDirection('ltr');
+ const workbook = univer.createUnit<IWorkbookData, Workbook>(
+ UniverInstanceType.UNIVER_SHEET,
+ getSheetsEmptySnapshot('mobile-sheet')
+ );
injector.get(IUniverInstanceService).focusUnit('mobile-sheet');
injector.add([IEditorBridgeService, {
useValue: {
@@ -134,14 +148,22 @@ function renderMobileSheetActionPanel(ribbon: IMenuSchema[] = []) {
injector.add([IRibbonService, {
useValue: { ribbon$: new BehaviorSubject(ribbon) } as unknown as IRibbonService,
}]);
- injector.add([SheetsSelectionsService, {
- useValue: {
- selectionMoveEnd$: EMPTY,
- getCurrentSelections: () => [],
- getCurrentLastSelection: () => null,
- setSelections: vi.fn(),
- } as unknown as SheetsSelectionsService,
+ injector.add([SheetsSelectionsService]);
+ injector.add([RangeProtectionRuleModel]);
+ const worksheet = workbook.getActiveSheet();
+ const range = { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 };
+ injector.get(SheetsSelectionsService).setSelections([{
+ range,
+ primary: getPrimaryForRange(range, worksheet),
+ style: null,
}]);
+ const permissions = injector.get(IPermissionService);
+ const subUnitId = worksheet.getSheetId();
+ [
+ new WorkbookEditablePermission(workbook.getUnitId()),
+ new WorksheetEditPermission(workbook.getUnitId(), subUnitId),
+ new WorksheetSetCellValuePermission(workbook.getUnitId(), subUnitId),
+ ].forEach((permission) => permissions.addPermissionPoint(permission));
const container = document.createElement('div');
document.body.appendChild(container);
@@ -154,7 +176,7 @@ function renderMobileSheetActionPanel(ribbon: IMenuSchema[] = []) {
));
});
- return { commandService: injector.get(ICommandService), container, contextService, root, univer };
+ return { commandService: injector.get(ICommandService), container, contextService, permissions, root, subUnitId, univer };
}
function clickButton(container: HTMLElement, name: string) {
@@ -183,6 +205,30 @@ function disposeRenderedPanel(root: Root, container: HTMLElement, univer: Univer
}
describe('mobile sheet action panel visibility', () => {
+ it('disables both keyboard entrances when cell editing is forbidden', () => {
+ const { commandService, container, permissions, root, subUnitId, univer } = renderMobileSheetActionPanel();
+ const startEditing = vi.fn(() => true);
+ commandService.registerCommand({ ...SetCellEditVisibleOperation, handler: startEditing });
+ const keyboard = () => container.querySelector<HTMLButtonElement>(
+ 'button[aria-label="Start Editing (Selection into the Editor)"]'
+ )!;
+ try {
+ expect(keyboard().disabled).toBe(false);
+ act(() => permissions.updatePermissionPoint(new WorkbookEditablePermission('mobile-sheet').id, false));
+ expect(keyboard().disabled).toBe(true);
+ act(() => keyboard().click());
+ expect(startEditing).not.toHaveBeenCalled();
+ clickButton(container, 'Open sheet tools');
+ expect(keyboard().disabled).toBe(true);
+ act(() => permissions.updatePermissionPoint(new WorkbookEditablePermission('mobile-sheet').id, true));
+ expect(keyboard().disabled).toBe(false);
+ act(() => permissions.updatePermissionPoint(new WorksheetSetCellValuePermission('mobile-sheet', subUnitId).id, false));
+ expect(keyboard().disabled).toBe(true);
+ } finally {
+ disposeRenderedPanel(root, container, univer);
+ }
+ });
+
it('does not reopen the previous sheet drawer after drawing focus ends', () => {
const { container, contextService, root, univer } = renderMobileSheetActionPanel();
diff --git a/packages/sheets-ui/src/views/mobile/action-panel/__tests__/MobileStylePanel.spec.tsx b/packages/sheets-ui/src/views/mobile/action-panel/__tests__/MobileStylePanel.spec.tsx
index 17a37ad7a8..8f9319e21f 100644
--- a/packages/sheets-ui/src/views/mobile/action-panel/__tests__/MobileStylePanel.spec.tsx
+++ b/packages/sheets-ui/src/views/mobile/action-panel/__tests__/MobileStylePanel.spec.tsx
@@ -17,7 +17,6 @@
import type { IDisplayMenuItem, IMenuItem, IMenuSchema } from '@univerjs/ui';
import type { ComponentProps } from 'react';
import type { Root } from 'react-dom/client';
-import type { MobileNumberFormatItem } from '../MobileStylePanel';
import {
BorderStyleTypes,
BorderType,
@@ -52,6 +51,7 @@ import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { BehaviorSubject } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { MobileNumberFormatItem, MobileStyleView } from '../MobileStylePanel';
import {
ResetRangeTextColorCommand,
SetRangeBoldCommand,
@@ -137,6 +137,55 @@ afterEach(() => {
});
describe('MobileStylePanel', () => {
+ it.each(['color', 'border', 'border-color', 'border-style'] as const)(
+ 'disables an open %s view when its menu permission changes',
+ (kind) => {
+ const disabled$ = new BehaviorSubject(false);
+ const hidden$ = new BehaviorSubject(false);
+ const item = { id: SetBorderBasicCommand.id, type: MenuItemType.BUTTON as const, disabled$, hidden$ };
+ const currentView: MobileStyleView = kind === 'color'
+ ? { kind, title: 'Color', item, target: 'background' as const }
+ : { kind, title: 'Border', item };
+ const onExecute = vi.fn();
+ const rendered = renderStylePanel({ currentView, onExecute });
+ root = rendered.root;
+ container = rendered.container;
+ const button = container.querySelector('button')!;
+
+ act(() => disabled$.next(true));
+ expect(container.querySelector('fieldset')?.disabled).toBe(true);
+ act(() => button.dispatchEvent(new MouseEvent('click', { bubbles: true })));
+ expect(onExecute).not.toHaveBeenCalled();
+
+ act(() => disabled$.next(false));
+ expect(container.querySelector('fieldset')?.disabled).toBe(false);
+ act(() => button.click());
+ expect(onExecute).toHaveBeenCalledOnce();
+
+ act(() => hidden$.next(true));
+ expect(container.querySelector('button')).toBeNull();
+ }
+ );
+
+ it('does not open color or border navigation when the menu is disabled', () => {
+ const onOpenView = vi.fn();
+ const rendered = renderStylePanel({
+ groups: [{ key: 'style', order: 0, children: [SetBackgroundColorCommand.id, SetBorderBasicCommand.id].map((id) => ({
+ key: id,
+ order: 0,
+ item: { id, type: MenuItemType.BUTTON, title: id, disabled$: new BehaviorSubject(true) },
+ })) }],
+ onOpenView,
+ });
+ root = rendered.root;
+ container = rendered.container;
+ for (const button of container.querySelectorAll('button')) {
+ expect(button.disabled).toBe(true);
+ act(() => button.click());
+ }
+ expect(onOpenView).not.toHaveBeenCalled();
+ });
+
it.each([
[LocaleType.EN_US, 'Dashed'],
[LocaleType.ZH_CN, '虚线'],
diff --git a/packages/sheets-ui/src/views/mobile/sheet-bar/MobileSheetBar.tsx b/packages/sheets-ui/src/views/mobile/sheet-bar/MobileSheetBar.tsx
index 4be7dd8654..f7f257d508 100644
--- a/packages/sheets-ui/src/views/mobile/sheet-bar/MobileSheetBar.tsx
+++ b/packages/sheets-ui/src/views/mobile/sheet-bar/MobileSheetBar.tsx
@@ -16,10 +16,7 @@
import type { ICommandInfo, Workbook } from '@univerjs/core';
import type { MouseEvent } from 'react';
-import type { IUniverSheetsUIConfig } from '../../../config/config';
-import type { LocaleKey } from '../../../locale/types';
-import type { IBaseSheetBarProps } from '../../sheet-bar/sheet-bar-tabs/SheetBarItem';
-import { ICommandService, LocaleService, nameCharacterCheck } from '@univerjs/core';
+import { ICommandService, IPermissionService, LocaleService, nameCharacterCheck } from '@univerjs/core';
import {
borderBottomClassName,
borderLeftClassName,
@@ -42,14 +39,23 @@ import {
SetWorksheetNameMutation,
SetWorksheetOrderMutation,
SetWorksheetShowCommand,
+ WorkbookCreateSheetPermission,
+ WorkbookEditablePermission,
+ WorkbookHideSheetPermission,
+ WorkbookRenameSheetPermission,
} from '@univerjs/sheets';
import {
ContextMenuPosition,
IContextMenuService,
useConfigValue,
useDependency,
+ useObservable,
} from '@univerjs/ui';
import { useCallback, useEffect, useRef, useState } from 'react';
+import { EMPTY } from 'rxjs';
+import type { IUniverSheetsUIConfig } from '../../../config/config';
+import type { LocaleKey } from '../../../locale/types';
+import type { IBaseSheetBarProps } from '../../sheet-bar/sheet-bar-tabs/SheetBarItem';
import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../../config/config';
import { ISheetBarService } from '../../../services/sheet-bar/sheet-bar.service';
import { useActiveWorkbook } from '../../hook';
@@ -79,6 +85,35 @@ function MobileSheetBarImpl(props: { workbook: Workbook }) {
const contextMenuService = useDependency(IContextMenuService);
const localeService = useDependency(LocaleService);
const sheetBarService = useDependency(ISheetBarService);
+ const permissionService = useDependency(IPermissionService);
+ const unitId = workbook.getUnitId();
+ const workbookEditable = useObservable(
+ () => permissionService.getPermissionPoint$(new WorkbookEditablePermission(unitId).id) ?? EMPTY,
+ undefined,
+ false,
+ [permissionService, unitId]
+ )?.value;
+ const workbookCreateSheet = useObservable(
+ () => permissionService.getPermissionPoint$(new WorkbookCreateSheetPermission(unitId).id) ?? EMPTY,
+ undefined,
+ false,
+ [permissionService, unitId]
+ )?.value;
+ const workbookRenameSheet = useObservable(
+ () => permissionService.getPermissionPoint$(new WorkbookRenameSheetPermission(unitId).id) ?? EMPTY,
+ undefined,
+ false,
+ [permissionService, unitId]
+ )?.value;
+ const workbookHideSheet = useObservable(
+ () => permissionService.getPermissionPoint$(new WorkbookHideSheetPermission(unitId).id) ?? EMPTY,
+ undefined,
+ false,
+ [permissionService, unitId]
+ )?.value;
+ const addSheetDisabled = !(workbookEditable && workbookCreateSheet);
+ const renameDisabled = !(workbookEditable && workbookRenameSheet);
+ const unhideDisabled = !(workbookEditable && workbookHideSheet);
const config = useConfigValue<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);
const addSheetButtonShow = (config?.footer || {}).addSheetButtonConfig?.show ?? true;
@@ -154,11 +189,14 @@ function MobileSheetBarImpl(props: { workbook: Workbook }) {
}, [contextMenuService, workbook]);
const addSheet = useCallback(() => {
+ if (addSheetDisabled) {
+ return;
+ }
commandService.executeCommand(InsertSheetCommand.id, { unitId: workbook.getUnitId() });
- }, [commandService, workbook]);
+ }, [addSheetDisabled, commandService, workbook]);
const confirmRename = useCallback(() => {
- if (!renameSheetId) {
+ if (!renameSheetId || renameDisabled) {
return;
}
@@ -182,7 +220,7 @@ function MobileSheetBarImpl(props: { workbook: Workbook }) {
name,
});
setRenameSheetId(null);
- }, [commandService, localeService, renameSheetId, renameValue, workbook]);
+ }, [commandService, localeService, renameDisabled, renameSheetId, renameValue, workbook]);
useEffect(() => {
const disposable = commandService.onCommandExecuted((commandInfo: ICommandInfo) => {
@@ -289,10 +327,12 @@ function MobileSheetBarImpl(props: { workbook: Workbook }) {
<button
type="button"
aria-label={localeService.t<LocaleKey>('sheets-ui.mobile.addSheet')}
+ disabled={addSheetDisabled}
className={clsx(resetButtonClassName, borderLeftClassName, `
univer-flex univer-h-10 univer-w-12 univer-shrink-0 univer-items-center univer-justify-center
univer-bg-gray-100 univer-text-lg univer-text-gray-800
active:univer-bg-gray-200
+ disabled:univer-cursor-not-allowed disabled:univer-opacity-40
dark:!univer-bg-gray-800 dark:!univer-text-gray-100
dark:active:!univer-bg-gray-700
`)}
@@ -306,7 +346,7 @@ function MobileSheetBarImpl(props: { workbook: Workbook }) {
open={Boolean(renameSheetId)}
title={localeService.t<LocaleKey>('sheets-ui.sheetConfig.rename')}
showCancel
- showOk
+ showOk={!renameDisabled}
onCancel={() => setRenameSheetId(null)}
onOk={confirmRename}
onOpenChange={(open) => {
@@ -318,6 +358,7 @@ function MobileSheetBarImpl(props: { workbook: Workbook }) {
<div className="univer-grid univer-gap-2">
<Input
autoFocus
+ disabled={renameDisabled}
size="large"
value={renameValue}
onChange={(value) => {
@@ -358,14 +399,19 @@ function MobileSheetBarImpl(props: { workbook: Workbook }) {
<button
key={sheetId}
type="button"
+ disabled={unhideDisabled}
className={clsx(resetButtonClassName, borderBottomClassName, `
univer-flex univer-min-h-12 univer-w-full univer-items-center univer-px-4 univer-py-2
univer-text-left univer-text-base univer-font-medium univer-text-gray-900
active:univer-bg-gray-100
+ disabled:univer-opacity-40
dark:!univer-text-gray-100
dark:active:!univer-bg-gray-700
`)}
onClick={() => {
+ if (unhideDisabled) {
+ return;
+ }
commandService.executeCommand(SetWorksheetShowCommand.id, {
unitId: workbook.getUnitId(),
subUnitId: sheetId,
diff --git a/packages/sheets-ui/src/views/mobile/sheet-bar/__tests__/MobileSheetBar.spec.tsx b/packages/sheets-ui/src/views/mobile/sheet-bar/__tests__/MobileSheetBar.spec.tsx
new file mode 100644
index 0000000000..e8a049e15a
--- /dev/null
+++ b/packages/sheets-ui/src/views/mobile/sheet-bar/__tests__/MobileSheetBar.spec.tsx
@@ -0,0 +1,112 @@
+/**
+ * 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 { IWorkbookData, Workbook } from '@univerjs/core';
+import {
+ getSheetsEmptySnapshot,
+ ICommandService,
+ IConfigService,
+ IPermissionService,
+ LocaleService,
+ LocaleType,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import {
+ InsertSheetCommand,
+ InsertSheetMutation,
+ WorkbookCreateSheetPermission,
+ WorkbookEditablePermission,
+ WorkbookHideSheetPermission,
+ WorkbookRenameSheetPermission,
+} from '@univerjs/sheets';
+import { ContextMenuService, IContextMenuService, RediContext } from '@univerjs/ui';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, describe, expect, it } from 'vitest';
+import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../../../config/config';
+import enUS from '../../../../locale/en-US';
+import { ISheetBarService, SheetBarService } from '../../../../services/sheet-bar/sheet-bar.service';
+import { MobileSheetBar } from '../MobileSheetBar';
+
+const disposals: Array<() => void> = [];
+
+function renderSheetBar(show = true) {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ injector.add([ISheetBarService, { useClass: SheetBarService }]);
+ injector.add([IContextMenuService, { useClass: ContextMenuService }]);
+ injector.get(IConfigService).setConfig(SHEETS_UI_PLUGIN_CONFIG_KEY, { footer: { addSheetButtonConfig: { show } } });
+ const localeService = injector.get(LocaleService);
+ localeService.load({ [LocaleType.EN_US]: enUS });
+ localeService.setLocale(LocaleType.EN_US);
+ localeService.setDirection('ltr');
+ const workbook = univer.createUnit<IWorkbookData, Workbook>(
+ UniverInstanceType.UNIVER_SHEET,
+ getSheetsEmptySnapshot('mobile-sheet')
+ );
+ const permissions = injector.get(IPermissionService);
+ [
+ new WorkbookEditablePermission(workbook.getUnitId()),
+ new WorkbookCreateSheetPermission(workbook.getUnitId()),
+ new WorkbookRenameSheetPermission(workbook.getUnitId()),
+ new WorkbookHideSheetPermission(workbook.getUnitId()),
+ ].forEach((permission) => permissions.addPermissionPoint(permission));
+ const commandService = injector.get(ICommandService);
+ commandService.registerCommand(InsertSheetCommand);
+ commandService.registerCommand(InsertSheetMutation);
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ act(() => root.render(<RediContext.Provider value={{ injector }}><MobileSheetBar /></RediContext.Provider>));
+ disposals.push(() => {
+ act(() => root.unmount());
+ container.remove();
+ univer.dispose();
+ });
+ return { container, workbook, permissions };
+}
+
+afterEach(() => disposals.splice(0).forEach((dispose) => dispose()));
+
+describe('MobileSheetBar permissions', () => {
+ it.each([
+ { label: 'workbook editing', Permission: WorkbookEditablePermission },
+ { label: 'sheet creation', Permission: WorkbookCreateSheetPermission },
+ ])(
+ 'prevents insertion when $label is revoked and allows it after permission is restored',
+ async ({ Permission }) => {
+ const { container, workbook, permissions } = renderSheetBar();
+ const button = container.querySelector<HTMLButtonElement>('button[aria-label="Add sheet"]')!;
+ const initialCount = workbook.getSheets().length;
+ const permission = new Permission(workbook.getUnitId());
+ act(() => permissions.updatePermissionPoint(permission.id, false));
+ expect(button.disabled).toBe(true);
+ await act(async () => button.click());
+ expect(workbook.getSheets()).toHaveLength(initialCount);
+
+ act(() => permissions.updatePermissionPoint(permission.id, true));
+ expect(button.disabled).toBe(false);
+ await act(async () => button.click());
+ expect(workbook.getSheets()).toHaveLength(initialCount + 1);
+ }
+ );
+
+ it('preserves the explicit option to hide the add button', () => {
+ const { container } = renderSheetBar(false);
+ expect(container.querySelector('button[aria-label="Add sheet"]')).toBeNull();
+ });
+});
diff --git a/packages/sheets/src/commands/commands/__tests__/permission-and-worksheet-meta.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/permission-and-worksheet-meta.command.spec.ts
index d07bef2e3d..e9fa7c305f 100644
--- a/packages/sheets/src/commands/commands/__tests__/permission-and-worksheet-meta.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/permission-and-worksheet-meta.command.spec.ts
@@ -15,8 +15,6 @@
*/
import type { IAccessor, IRange } from '@univerjs/core';
-import type { IRangeProtectionRule } from '../../../models/range-protection-rule.model';
-import type { IWorksheetProtectionRule } from '../../../services/permission/type';
import {
BooleanNumber,
ICommandService,
@@ -28,6 +26,8 @@ import {
} from '@univerjs/core';
import { UnitObject } from '@univerjs/protocol';
import { describe, expect, it } from 'vitest';
+import type { IRangeProtectionRule } from '../../../models/range-protection-rule.model';
+import type { IWorksheetProtectionRule } from '../../../services/permission/type';
import { EditStateEnum, RangeProtectionRuleModel, ViewStateEnum } from '../../../models/range-protection-rule.model';
import { AddRangeProtectionMutation } from '../../mutations/add-range-protection.mutation';
import { AddWorksheetProtectionMutation } from '../../mutations/add-worksheet-protection.mutation';
@@ -129,7 +129,7 @@ function createWorkbookTarget() {
}
describe('range protection commands', () => {
- it('adds a range protection rule and records undo/redo mutations when the mutation succeeds', async () => {
+ it('adds a range protection rule without recording an undo item', async () => {
const commandService = createCommandService();
const undoRedoService = createUndoRedoService();
const ruleModel = new RangeProtectionRuleModel();
@@ -155,12 +155,7 @@ describe('range protection commands', () => {
viewState: sourceRule.viewState,
editState: sourceRule.editState,
});
- expect(undoRedoService.records).toHaveLength(1);
- expect(undoRedoService.records[0]).toMatchObject({
- unitID: 'unit-1',
- redoMutations: [{ id: AddRangeProtectionMutation.id }],
- undoMutations: [{ id: DeleteRangeProtectionMutation.id }],
- });
+ expect(undoRedoService.records).toEqual([]);
await expect(AddRangeProtectionCommand.handler(accessor, undefined as never)).resolves.toBe(false);
});
@@ -174,7 +169,7 @@ describe('range protection commands', () => {
[RangeProtectionRuleModel, new RangeProtectionRuleModel()],
]));
- await expect(AddRangeProtectionCommand.handler(accessor, { permissionId: 'permission-new', rule: createRangeRule('source-rule') })).resolves.toBe(true);
+ await expect(AddRangeProtectionCommand.handler(accessor, { permissionId: 'permission-new', rule: createRangeRule('source-rule') })).resolves.toBe(false);
expect(undoRedoService.records).toEqual([]);
});
@@ -229,7 +224,7 @@ describe('worksheet protection commands', () => {
params: { unitId: 'unit-1', subUnitId: 'sheet-1', newRule: { ...rule, permissionId: 'permission-updated' } },
async: true,
});
- expect(undoRedoService.records).toHaveLength(3);
+ expect(undoRedoService.records).toHaveLength(2);
await expect(AddWorksheetProtectionCommand.handler(accessor, undefined as never)).resolves.toBe(false);
expect(DeleteWorksheetProtectionCommand.handler(accessor, undefined as never)).toBe(false);
@@ -248,7 +243,7 @@ describe('worksheet protection commands', () => {
]));
const rule = createWorksheetRule('permission-new');
- await expect(AddWorksheetProtectionCommand.handler(accessor, { unitId: 'unit-1', rule })).resolves.toBe(true);
+ await expect(AddWorksheetProtectionCommand.handler(accessor, { unitId: 'unit-1', rule })).resolves.toBe(false);
await expect(SetWorksheetProtectionCommand.handler(accessor, { permissionId: 'permission-updated', rule, oldRule: createWorksheetRule('permission-old') })).resolves.toBe(true);
expect(undoRedoService.records).toEqual([]);
});
@@ -319,7 +314,7 @@ describe('mixed protection command', () => {
});
});
- it('switches worksheet protection to range protection with reversible mutations', async () => {
+ it('switches worksheet protection to range protection without recording an undo item', async () => {
const commandService = createCommandService();
const undoRedoService = createUndoRedoService();
const ruleModel = new RangeProtectionRuleModel();
@@ -342,22 +337,12 @@ describe('mixed protection command', () => {
params: { unitId: 'unit-1', subUnitId: 'sheet-1', rules: [rule] },
});
expect(rule.id).not.toBe('');
- expect(undoRedoService.records[0]).toMatchObject({
- unitID: 'unit-1',
- undoMutations: [
- { id: DeleteRangeProtectionMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', ruleIds: [rule.id] } },
- { id: AddWorksheetProtectionMutation.id, params: { unitId: 'unit-1', rule: oldRule, subUnitId: 'sheet-1' } },
- ],
- redoMutations: [
- { id: DeleteWorksheetProtectionMutation.id },
- { id: AddRangeProtectionMutation.id },
- ],
- });
+ expect(undoRedoService.records).toEqual([]);
await expect(SetProtectionCommand.handler(accessor, undefined as never)).resolves.toBe(false);
});
- it('switches range protection to worksheet protection with reversible mutations', async () => {
+ it('switches range protection to worksheet protection without recording an undo item', async () => {
const commandService = createCommandService();
const undoRedoService = createUndoRedoService();
const accessor = createAccessor(new Map<unknown, unknown>([
@@ -382,17 +367,7 @@ describe('mixed protection command', () => {
async: false,
},
]);
- expect(undoRedoService.records[0]).toMatchObject({
- unitID: 'unit-1',
- undoMutations: [
- { id: DeleteWorksheetProtectionMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1' } },
- { id: AddRangeProtectionMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', rules: [oldRule] } },
- ],
- redoMutations: [
- { id: DeleteRangeProtectionMutation.id },
- { id: AddWorksheetProtectionMutation.id },
- ],
- });
+ expect(undoRedoService.records).toEqual([]);
});
it('does not create an undo item when protection update mutations fail', async () => {
diff --git a/packages/sheets/src/commands/commands/add-range-protection.command.ts b/packages/sheets/src/commands/commands/add-range-protection.command.ts
index e682fe0d64..7949d916a8 100644
--- a/packages/sheets/src/commands/commands/add-range-protection.command.ts
+++ b/packages/sheets/src/commands/commands/add-range-protection.command.ts
@@ -15,11 +15,10 @@
*/
import type { ICommand } from '@univerjs/core';
+import { CommandType, ICommandService } from '@univerjs/core';
import type { IRangeProtectionRule } from '../../models/range-protection-rule.model';
-import { CommandType, ICommandService, IUndoRedoService } from '@univerjs/core';
import { RangeProtectionRuleModel } from '../../models/range-protection-rule.model';
import { AddRangeProtectionMutation } from '../mutations/add-range-protection.mutation';
-import { DeleteRangeProtectionMutation } from '../mutations/delete-range-protection.mutation';
export interface IAddRangeProtectionCommandParams {
permissionId: string;
@@ -33,7 +32,6 @@ export const AddRangeProtectionCommand: ICommand<IAddRangeProtectionCommandParam
return false;
}
const commandService = accessor.get(ICommandService);
- const undoRedoService = accessor.get(IUndoRedoService);
const selectionProtectionModel = accessor.get(RangeProtectionRuleModel);
const { rule, permissionId } = params;
@@ -56,16 +54,6 @@ export const AddRangeProtectionCommand: ICommand<IAddRangeProtectionCommandParam
rules,
});
- if (result) {
- const redoMutations = [{ id: AddRangeProtectionMutation.id, params: { unitId, subUnitId, rules } }];
- const undoMutations = [{ id: DeleteRangeProtectionMutation.id, params: { unitId, subUnitId, ruleIds: rules.map((rule) => rule.id) } }];
- undoRedoService.pushUndoRedo({
- unitID: unitId,
- redoMutations,
- undoMutations,
- });
- }
-
- return true;
+ return result;
},
};
diff --git a/packages/sheets/src/commands/commands/add-worksheet-protection.command.ts b/packages/sheets/src/commands/commands/add-worksheet-protection.command.ts
index 29f7fc20a9..4f742f0d63 100644
--- a/packages/sheets/src/commands/commands/add-worksheet-protection.command.ts
+++ b/packages/sheets/src/commands/commands/add-worksheet-protection.command.ts
@@ -15,10 +15,9 @@
*/
import type { ICommand } from '@univerjs/core';
+import { CommandType, ICommandService } from '@univerjs/core';
import type { IWorksheetProtectionRule } from '../../services/permission/type';
-import { CommandType, ICommandService, IUndoRedoService } from '@univerjs/core';
import { AddWorksheetProtectionMutation } from '../mutations/add-worksheet-protection.mutation';
-import { DeleteWorksheetProtectionMutation } from '../mutations/delete-worksheet-protection.mutation';
export interface IAddWorksheetProtectionParams {
unitId: string;
@@ -33,26 +32,13 @@ export const AddWorksheetProtectionCommand: ICommand<IAddWorksheetProtectionPara
return false;
}
const commandService = accessor.get(ICommandService);
- const undoRedoService = accessor.get(IUndoRedoService);
const { rule, unitId } = params;
- const subUnitId = rule.subUnitId;
-
const result = await commandService.executeCommand(AddWorksheetProtectionMutation.id, {
unitId,
rule,
subUnitId: rule.subUnitId,
});
- if (result) {
- const redoMutations = [{ id: AddWorksheetProtectionMutation.id, params: { unitId, rule, subUnitId: rule.subUnitId } }];
- const undoMutations = [{ id: DeleteWorksheetProtectionMutation.id, params: { unitId, subUnitId } }];
- undoRedoService.pushUndoRedo({
- unitID: unitId,
- redoMutations,
- undoMutations,
- });
- }
-
- return true;
+ return result;
},
};
diff --git a/packages/sheets/src/commands/commands/set-protection.command.ts b/packages/sheets/src/commands/commands/set-protection.command.ts
index 01b89cb9e8..cbf0116b78 100644
--- a/packages/sheets/src/commands/commands/set-protection.command.ts
+++ b/packages/sheets/src/commands/commands/set-protection.command.ts
@@ -15,10 +15,10 @@
*/
import type { ICommand, IRange } from '@univerjs/core';
-import type { IRangeProtectionRule } from '../../models/range-protection-rule.model';
-import type { IWorksheetProtectionRule } from '../../services/permission/type';
import { CommandType, ICommandService, IUndoRedoService, sequenceExecute } from '@univerjs/core';
import { UnitObject } from '@univerjs/protocol';
+import type { IRangeProtectionRule } from '../../models/range-protection-rule.model';
+import type { IWorksheetProtectionRule } from '../../services/permission/type';
import { RangeProtectionRuleModel } from '../../models/range-protection-rule.model';
import { AddRangeProtectionMutation } from '../mutations/add-range-protection.mutation';
import { AddWorksheetProtectionMutation } from '../mutations/add-worksheet-protection.mutation';
@@ -62,26 +62,22 @@ export const SetProtectionCommand: ICommand<ISetProtectionParams> = {
if (oldRule) {
if (oldRule.unitType === UnitObject.Worksheet) {
redoMutations.push({ id: DeleteWorksheetProtectionMutation.id, params: { unitId, subUnitId } });
- undoMutations.push({ id: AddWorksheetProtectionMutation.id, params: { unitId, rule: oldRule, subUnitId: oldRule.subUnitId } });
} else if (oldRule.unitType === UnitObject.SelectRange) {
redoMutations.push({ id: DeleteRangeProtectionMutation.id, params: { unitId, subUnitId, ruleIds: [(oldRule as IRangeProtectionRule).id] } });
- undoMutations.push({ id: AddRangeProtectionMutation.id, params: { unitId, subUnitId, rules: [oldRule] } });
}
}
if (rule.unitType === UnitObject.Worksheet) {
redoMutations.push({ id: AddWorksheetProtectionMutation.id, params: { unitId, rule, subUnitId: rule.subUnitId } });
- undoMutations.unshift({ id: DeleteWorksheetProtectionMutation.id, params: { unitId, subUnitId } });
} else if (rule.unitType === UnitObject.SelectRange) {
(rule as IRangeProtectionRule).id = rangeProtectionRuleModel.createRuleId(unitId, subUnitId);
redoMutations.push({ id: AddRangeProtectionMutation.id, params: { unitId, subUnitId, rules: [rule] } });
- undoMutations.unshift({ id: DeleteRangeProtectionMutation.id, params: { unitId, subUnitId, ruleIds: [(rule as IRangeProtectionRule).id] } });
}
}
const result = sequenceExecute(redoMutations, commandService);
- if (result.result) {
+ if (result.result && oldRule?.unitType === rule.unitType) {
undoRedoService.pushUndoRedo({
unitID: unitId,
undoMutations,
diff --git a/packages/sheets/src/controllers/permission/__tests__/sheet-permission-init.controller.spec.ts b/packages/sheets/src/controllers/permission/__tests__/sheet-permission-init.controller.spec.ts
new file mode 100644
index 0000000000..b169b08f51
--- /dev/null
+++ b/packages/sheets/src/controllers/permission/__tests__/sheet-permission-init.controller.spec.ts
@@ -0,0 +1,214 @@
+/**
+ * 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 { IMutationInfo } from '@univerjs/core';
+import {
+ IAuthzIoService,
+ ICommandService,
+ IPermissionService,
+ IUndoRedoService,
+ RedoCommand,
+ UndoCommand,
+} from '@univerjs/core';
+import { UnitAction, UnitObject } from '@univerjs/protocol';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createCommandTestBed } from '../../../commands/commands/__tests__/create-command-test-bed';
+import { AddRangeProtectionCommand } from '../../../commands/commands/add-range-protection.command';
+import { AddWorksheetProtectionCommand } from '../../../commands/commands/add-worksheet-protection.command';
+import { SetProtectionCommand } from '../../../commands/commands/set-protection.command';
+import { SetRangeValuesCommand } from '../../../commands/commands/set-range-values.command';
+import { AddRangeProtectionMutation } from '../../../commands/mutations/add-range-protection.mutation';
+import { AddWorksheetProtectionMutation } from '../../../commands/mutations/add-worksheet-protection.mutation';
+import { DeleteRangeProtectionMutation } from '../../../commands/mutations/delete-range-protection.mutation';
+import { DeleteWorksheetProtectionMutation } from '../../../commands/mutations/delete-worksheet-protection.mutation';
+import { SetRangeValuesMutation } from '../../../commands/mutations/set-range-values.mutation';
+import { SetWorksheetPermissionPointsMutation } from '../../../commands/mutations/set-worksheet-permission-points.mutation';
+import { SetSelectionsOperation } from '../../../commands/operations/selection.operation';
+import { EditStateEnum, RangeProtectionRuleModel, ViewStateEnum } from '../../../models/range-protection-rule.model';
+import { RangeProtectionPermissionEditPoint } from '../../../services/permission/permission-point/range/edit';
+import { WorksheetEditPermission } from '../../../services/permission/permission-point/worksheet/edit';
+import { WorksheetProtectionRuleModel } from '../../../services/permission/worksheet-permission/worksheet-permission-rule.model';
+import { SheetPermissionInitController } from '../sheet-permission-init.controller';
+
+const rangeRule = {
+ id: 'protected-range',
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ permissionId: 'range-permission',
+ unitType: UnitObject.SelectRange,
+ ranges: [{ startRow: 2, endRow: 3, startColumn: 0, endColumn: 1 }],
+ viewState: ViewStateEnum.OthersCanView,
+ editState: EditStateEnum.OnlyMe,
+};
+const worksheetRule = { ...rangeRule, permissionId: 'sheet-permission', unitType: UnitObject.Worksheet };
+const protectionMutations: IMutationInfo[] = [
+ { id: AddRangeProtectionMutation.id, params: { unitId: 'test', subUnitId: 'sheet1', rules: [rangeRule] } },
+ { id: AddWorksheetProtectionMutation.id, params: { unitId: 'test', subUnitId: 'sheet1', rule: worksheetRule } },
+ {
+ id: SetWorksheetPermissionPointsMutation.id,
+ params: { unitId: 'test', subUnitId: 'sheet1', rule: worksheetRule },
+ },
+];
+
+describe('protection history boundary', () => {
+ const disposables: Array<{ dispose(): void }> = [];
+
+ afterEach(() => {
+ disposables.splice(0).forEach((disposable) => disposable.dispose());
+ });
+
+ function createTestBed() {
+ const bed = createCommandTestBed(undefined, [[SheetPermissionInitController]]);
+ disposables.push(bed.univer);
+ const commands = bed.get(ICommandService);
+ [
+ AddRangeProtectionCommand,
+ AddWorksheetProtectionCommand,
+ SetProtectionCommand,
+ AddRangeProtectionMutation,
+ AddWorksheetProtectionMutation,
+ SetWorksheetPermissionPointsMutation,
+ DeleteRangeProtectionMutation,
+ DeleteWorksheetProtectionMutation,
+ SetRangeValuesMutation,
+ SetRangeValuesCommand,
+ SetSelectionsOperation,
+ ].forEach((command) => commands.registerCommand(command));
+ bed.get(SheetPermissionInitController);
+ const history = bed.get(IUndoRedoService);
+ const edit = (value: string) => commands.syncExecuteCommand(SetRangeValuesCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },
+ value: { v: value },
+ });
+ edit('first');
+ edit('second');
+ expect(commands.syncExecuteCommand(UndoCommand.id)).toBe(true);
+ expect(history.getUndoRedoStatus('test')).toEqual({ undos: 1, redos: 1 });
+ return { ...bed, commands, history, edit };
+ }
+
+ describe.each([false, true])('fromCollab: %s', (fromCollab) => {
+ it.each(protectionMutations)('clears both histories when $id takes effect', ({ id, params }) => {
+ const { commands, history, sheet } = createTestBed();
+ history.pushUndoRedo({ unitID: 'other-book', undoMutations: [], redoMutations: [] });
+ expect(commands.syncExecuteCommand(id, { ...params }, { fromCollab })).toBe(true);
+ expect(history.getUndoRedoStatus('test')).toEqual({ undos: 0, redos: 0 });
+ expect(history.getUndoRedoStatus('other-book')).toEqual({ undos: 1, redos: 0 });
+ expect(commands.syncExecuteCommand(UndoCommand.id)).toBe(false);
+ expect(commands.syncExecuteCommand(RedoCommand.id)).toBe(false);
+ expect(sheet.getSheetBySheetId('sheet1')!.getCell(0, 0)?.v).toBe('first');
+ });
+ });
+
+ it.each([
+ { id: AddRangeProtectionCommand.id, params: { rule: rangeRule, permissionId: rangeRule.permissionId } },
+ { id: AddWorksheetProtectionCommand.id, params: { unitId: 'test', rule: worksheetRule } },
+ { id: SetProtectionCommand.id, params: { rule: { ...rangeRule } } },
+ { id: SetProtectionCommand.id, params: { rule: { ...rangeRule }, oldRule: worksheetRule } },
+ { id: SetProtectionCommand.id, params: { rule: worksheetRule, oldRule: rangeRule } },
+ ])('does not push newly applied protection back into history via $id', async ({ id, params }) => {
+ const { commands, history } = createTestBed();
+ await expect(commands.executeCommand(id, params)).resolves.toBe(true);
+ expect(history.getUndoRedoStatus('test')).toEqual({ undos: 0, redos: 0 });
+ });
+
+ it('allows subsequent edits to build a new undo/redo history', () => {
+ const { commands, history, edit, sheet } = createTestBed();
+ commands.syncExecuteCommand(AddRangeProtectionMutation.id, { ...protectionMutations[0].params });
+ expect(edit('after protection')).toBe(true);
+ expect(history.getUndoRedoStatus('test')).toEqual({ undos: 1, redos: 0 });
+ expect(commands.syncExecuteCommand(UndoCommand.id)).toBe(true);
+ expect(sheet.getSheetBySheetId('sheet1')!.getCell(0, 0)?.v).toBe('first');
+ expect(commands.syncExecuteCommand(RedoCommand.id)).toBe(true);
+ expect(sheet.getSheetBySheetId('sheet1')!.getCell(0, 0)?.v).toBe('after protection');
+ });
+
+ it('does not clear history for an empty protection batch or rejected command', async () => {
+ const { commands, history } = createTestBed();
+ commands.syncExecuteCommand(AddRangeProtectionMutation.id, { unitId: 'test', subUnitId: 'sheet1', rules: [] });
+ await expect(commands.executeCommand(AddRangeProtectionCommand.id)).resolves.toBe(false);
+ expect(history.getUndoRedoStatus('test')).toEqual({ undos: 1, redos: 1 });
+ });
+
+ it('preserves undo/redo when restoring an existing protection range', () => {
+ const { commands, history, get } = createTestBed();
+ commands.syncExecuteCommand(AddRangeProtectionMutation.id, { ...protectionMutations[0].params });
+ commands.syncExecuteCommand(DeleteRangeProtectionMutation.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ ruleIds: [rangeRule.id],
+ });
+ history.pushUndoRedo({
+ unitID: 'test',
+ undoMutations: [{ ...protectionMutations[0], params: { ...protectionMutations[0].params } }],
+ redoMutations: [{
+ id: DeleteRangeProtectionMutation.id,
+ params: { unitId: 'test', subUnitId: 'sheet1', ruleIds: [rangeRule.id] },
+ }],
+ });
+ expect(commands.syncExecuteCommand(UndoCommand.id)).toBe(true);
+ expect(get(RangeProtectionRuleModel).getRule('test', 'sheet1', rangeRule.id)).toEqual(rangeRule);
+ expect(history.getUndoRedoStatus('test')).toEqual({ undos: 0, redos: 1 });
+ expect(commands.syncExecuteCommand(RedoCommand.id)).toBe(true);
+ expect(get(RangeProtectionRuleModel).getRule('test', 'sheet1', rangeRule.id)).toBeUndefined();
+ expect(history.getUndoRedoStatus('test')).toEqual({ undos: 1, redos: 0 });
+ });
+
+ it('does not clear history when worksheet protection is removed', () => {
+ const { commands, history, get, edit } = createTestBed();
+ commands.syncExecuteCommand(AddWorksheetProtectionMutation.id, { ...protectionMutations[1].params });
+ edit('allowed edit');
+ commands.syncExecuteCommand(DeleteWorksheetProtectionMutation.id, { unitId: 'test', subUnitId: 'sheet1' });
+ expect(get(WorksheetProtectionRuleModel).getRule('test', 'sheet1')).toBeUndefined();
+ expect(history.getUndoRedoStatus('test')).toEqual({ undos: 1, redos: 0 });
+ });
+
+ describe.each([false, true])('existing protection permission changed: %s', (changed) => {
+ it.each([rangeRule, worksheetRule])('handles the refreshed permissions for $permissionId', async (rule) => {
+ const { commands, history, get, edit } = createTestBed();
+ const isRange = rule.unitType === UnitObject.SelectRange;
+ commands.syncExecuteCommand(
+ isRange ? AddRangeProtectionMutation.id : AddWorksheetProtectionMutation.id,
+ { unitId: 'test', subUnitId: 'sheet1', rule, rules: [rule] }
+ );
+ const point = isRange
+ ? new RangeProtectionPermissionEditPoint('test', 'sheet1', rule.permissionId)
+ : new WorksheetEditPermission('test', 'sheet1');
+ const permissions = get(IPermissionService);
+ permissions.addPermissionPoint(point);
+ permissions.updatePermissionPoint(point.id, true);
+ edit('before permission refresh');
+ edit('pending redo');
+ commands.syncExecuteCommand(UndoCommand.id);
+ const authz = vi.spyOn(get(IAuthzIoService), 'allowed').mockResolvedValue([
+ { action: UnitAction.Edit, allowed: !changed },
+ ]);
+ try {
+ get(SheetPermissionInitController).refreshPermission('test', rule.permissionId);
+ await Promise.resolve();
+ expect(permissions.getPermissionPoint(point.id)?.value).toBe(!changed);
+ expect(history.getUndoRedoStatus('test')).toEqual({
+ undos: changed ? 0 : 1,
+ redos: changed ? 0 : 1,
+ });
+ } finally {
+ authz.mockRestore();
+ }
+ });
+ });
+});
diff --git a/packages/sheets/src/controllers/permission/sheet-permission-init.controller.ts b/packages/sheets/src/controllers/permission/sheet-permission-init.controller.ts
index ebf21cd493..82d2a34c8c 100644
--- a/packages/sheets/src/controllers/permission/sheet-permission-init.controller.ts
+++ b/packages/sheets/src/controllers/permission/sheet-permission-init.controller.ts
@@ -14,23 +14,43 @@
* limitations under the License.
*/
-import type { Workbook } from '@univerjs/core';
+import type { IMutationCommonParams, Workbook } from '@univerjs/core';
import type { UnitAction } from '@univerjs/protocol';
+import {
+ Disposable,
+ IAuthzIoService,
+ ICommandService,
+ Inject,
+ IPermissionService,
+ IUndoRedoService,
+ IUniverInstanceService,
+ RedoCommandId,
+ UndoCommandId,
+ UniverInstanceType,
+ UserManagerService,
+} from '@univerjs/core';
+import { UnitObject } from '@univerjs/protocol';
+import { skip } from 'rxjs';
import type { IAddRangeProtectionMutationParams } from '../../commands/mutations/add-range-protection.mutation';
import type { IAddWorksheetProtectionParams } from '../../commands/mutations/add-worksheet-protection.mutation';
import type { ISetWorksheetPermissionPointsMutationParams } from '../../commands/mutations/set-worksheet-permission-points.mutation';
-import { Disposable, IAuthzIoService, ICommandService, Inject, IPermissionService, IUndoRedoService, IUniverInstanceService, UniverInstanceType, UserManagerService } from '@univerjs/core';
-import { UnitObject } from '@univerjs/protocol';
-import { skip } from 'rxjs';
import { AddRangeProtectionMutation } from '../../commands/mutations/add-range-protection.mutation';
import { AddWorksheetProtectionMutation } from '../../commands/mutations/add-worksheet-protection.mutation';
import { SetWorksheetPermissionPointsMutation } from '../../commands/mutations/set-worksheet-permission-points.mutation';
import { RangeProtectionRuleModel } from '../../models/range-protection-rule.model';
-import { defaultWorksheetPermissionPoint, getAllWorksheetPermissionPoint, getAllWorksheetPermissionPointByPointPanel } from '../../services/permission';
import { baseProtectionActions, getAllRangePermissionPoint } from '../../services/permission/range-permission/util';
-import { defaultWorkbookPermissionPoints, getAllWorkbookPermissionPoint } from '../../services/permission/workbook-permission';
+import {
+ defaultWorkbookPermissionPoints,
+ getAllWorkbookPermissionPoint,
+} from '../../services/permission/workbook-permission/util';
import { WorkbookPermissionService } from '../../services/permission/workbook-permission/workbook-permission.service';
-import { WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '../../services/permission/worksheet-permission';
+import {
+ defaultWorksheetPermissionPoint,
+ getAllWorksheetPermissionPoint,
+ getAllWorksheetPermissionPointByPointPanel,
+} from '../../services/permission/worksheet-permission/utils';
+import { WorksheetProtectionPointModel } from '../../services/permission/worksheet-permission/worksheet-permission-point.model';
+import { WorksheetProtectionRuleModel } from '../../services/permission/worksheet-permission/worksheet-permission-rule.model';
export class SheetPermissionInitController extends Disposable {
constructor(
@@ -46,6 +66,7 @@ export class SheetPermissionInitController extends Disposable {
@Inject(ICommandService) private _commandService: ICommandService
) {
super();
+ this._clearHistoryOnProtectionApplied();
}
public initPermission() {
@@ -56,7 +77,6 @@ export class SheetPermissionInitController extends Disposable {
this._initWorksheetPermissionPointsChange();
this._initWorkbookPermissionFromSnapshot();
this._initUserChange();
- this._refreshPermissionByCollaCreate();
}
public refreshRangeProtectPermission() {
@@ -490,19 +510,31 @@ export class SheetPermissionInitController extends Disposable {
}
}
- private _refreshPermissionByCollaCreate() {
+ private _clearHistoryOnProtectionApplied() {
this.disposeWithMe(
this._commandService.onCommandExecuted((command, options) => {
- if (options?.fromCollab) {
- if (
- command.id === AddRangeProtectionMutation.id
- || command.id === AddWorksheetProtectionMutation.id
- || command.id === SetWorksheetPermissionPointsMutation.id
- ) {
- const params = command.params as IAddRangeProtectionMutationParams | IAddWorksheetProtectionParams | ISetWorksheetPermissionPointsMutationParams;
- this._undoRedoService.clearUndoRedo(params.unitId);
- }
+ if (
+ command.id !== AddRangeProtectionMutation.id
+ && command.id !== AddWorksheetProtectionMutation.id
+ && command.id !== SetWorksheetPermissionPointsMutation.id
+ ) {
+ return;
}
+
+ const params = command.params as (
+ IAddRangeProtectionMutationParams
+ | IAddWorksheetProtectionParams
+ | ISetWorksheetPermissionPointsMutationParams
+ ) & IMutationCommonParams;
+ // Structural undo/redo can restore existing protection ranges along with rows or columns.
+ if (!options?.fromCollab && (params.trigger === UndoCommandId || params.trigger === RedoCommandId)) {
+ return;
+ }
+ if (command.id === AddRangeProtectionMutation.id && !(params as IAddRangeProtectionMutationParams).rules.length) {
+ return;
+ }
+
+ this._undoRedoService.clearUndoRedo(params.unitId);
})
);
}
diff --git a/packages/ui/src/views/components/dialog-part/MobileDialogPart.tsx b/packages/ui/src/views/components/dialog-part/MobileDialogPart.tsx
index 8bb85dbd8d..72807fcc81 100644
--- a/packages/ui/src/views/components/dialog-part/MobileDialogPart.tsx
+++ b/packages/ui/src/views/components/dialog-part/MobileDialogPart.tsx
@@ -15,14 +15,14 @@
*/
import type { ReactNode } from 'react';
-import type { LocaleKey } from '../../../locale/types';
-import type { MobilePanelLayout } from '../../mobile-workbench/MobileCanvasLayout';
-import type { MobileDrawerSnap } from '../mobile-drawer/MobileDrawer';
-import type { IDialogPartMethodOptions } from './interface';
import { LocaleService } from '@univerjs/core';
import { Button, ConfigContext, MobileActionRowGroup } from '@univerjs/design';
import { CloseIcon } from '@univerjs/icons';
import { useContext, useMemo, useRef, useState } from 'react';
+import type { LocaleKey } from '../../../locale/types';
+import type { MobilePanelLayout } from '../../mobile-workbench/MobileCanvasLayout';
+import type { MobileDrawerSnap } from '../mobile-drawer/MobileDrawer';
+import type { IDialogPartMethodOptions } from './interface';
import { IDialogService } from '../../../services/dialog/dialog.service';
import { useDependency, useObservable } from '../../../utils/di';
import { CustomLabel } from '../../custom-label/CustomLabel';
@@ -118,6 +118,7 @@ export function MobileDialogPart() {
<MobileDrawer
layerRef={layerRef}
layout={options.layout}
+ autoHeight={options.layout !== 'canvas'}
componentName="mobile-dialog-drawer"
snap={snapOverride?.id === options.id ? snapOverride.snap : defaultSnap}
expandLabel={localeService.t<LocaleKey>('ui.sidebar.resize')}
diff --git a/packages/ui/src/views/components/dialog-part/__tests__/MobileDialogPart.spec.tsx b/packages/ui/src/views/components/dialog-part/__tests__/MobileDialogPart.spec.tsx
index 0e902dca42..fe18e28dda 100644
--- a/packages/ui/src/views/components/dialog-part/__tests__/MobileDialogPart.spec.tsx
+++ b/packages/ui/src/views/components/dialog-part/__tests__/MobileDialogPart.spec.tsx
@@ -22,7 +22,9 @@ import designEnUS from '@univerjs/design/locale/en-US';
import { useState } from 'react';
import { createPortal } from 'react-dom';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { ComponentManager, IconManager } from '../../../../common';
+import type { IMobileDialogPartMethodOptions } from '../MobileDialogPart';
+import { ComponentManager } from '../../../../common/component-manager';
+import { IconManager } from '../../../../common/icon-manager';
import enUS from '../../../../locale/en-US';
import { DesktopDialogService } from '../../../../services/dialog/desktop-dialog.service';
import { IDialogService } from '../../../../services/dialog/dialog.service';
@@ -43,6 +45,7 @@ function renderWithDependencies(element: ReactElement, mobileService = false, ke
injector.add([LocaleService]);
injector.get(LocaleService).load({ [LocaleType.EN_US]: enUS });
injector.get(LocaleService).setLocale(LocaleType.EN_US);
+ injector.get(LocaleService).setDirection('ltr');
injector.add([ComponentManager]);
injector.add([IconManager]);
@@ -95,9 +98,11 @@ describe('MobileDialogPart', () => {
afterEach(() => {
cleanup();
vi.restoreAllMocks();
+ vi.unstubAllGlobals();
});
- it('renders the latest active dialog as an 80 percent bottom drawer', () => {
+ it('fits the latest active dialog to its content and preserves its title and footer', () => {
+ vi.stubGlobal('CSS', { supports: () => false });
const rendered = renderWithDependencies(<MobileDialogPart />);
const dialogService = rendered.injector.get(IDialogService);
@@ -112,25 +117,43 @@ describe('MobileDialogPart', () => {
});
const drawer = screen.getByRole('dialog');
- expect(drawer.getAttribute('data-snap')).toBe('expanded');
+ expect(drawer.style.height).toBe('auto');
+ expect(drawer.style.maxHeight).toBe('60vh');
+ expect(screen.queryByRole('button', { name: 'Resize sidebar' })).toBeNull();
expect(screen.queryByText('First')).toBeNull();
expect(screen.getByText('Range selector')).toBeTruthy();
expect(screen.getByText('Second')).toBeTruthy();
expect(screen.getByText('Actions')).toBeTruthy();
});
- it('keeps the active dialog anchored while the mobile keyboard is visible', () => {
+ it('keeps the dialog and its confirmation action above the mobile keyboard', () => {
+ vi.stubGlobal('CSS', { supports: () => false });
vi.stubGlobal('innerHeight', 768);
const rendered = renderWithDependencies(<MobileDialogPart />, false, true);
const dialogService = rendered.injector.get(IDialogService);
act(() => {
- dialogService.open({ id: 'keyboard-aware', children: { title: <input aria-label="Value" /> } });
+ dialogService.open({ id: 'keyboard-aware', children: { title: <input aria-label="Value" /> }, showOk: true });
});
const drawer = screen.getByRole('dialog');
- expect(drawer.style.bottom).toBe('');
- expect(drawer.style.maxHeight).toBe('');
+ expect(drawer.style.bottom).toBe('320px');
+ expect(drawer.style.maxHeight).toBe('min(60vh, 448px)');
+ expect(screen.getByRole('button', { name: 'ok' })).toBeTruthy();
+ });
+
+ it('preserves the resizable drawer for canvas editing panels', () => {
+ vi.stubGlobal('CSS', { supports: () => false });
+ const rendered = renderWithDependencies(<MobileDialogPart />);
+ const options: IMobileDialogPartMethodOptions = {
+ id: 'canvas-editor',
+ layout: 'canvas',
+ children: { title: <input aria-label="Formula" /> },
+ };
+ act(() => rendered.injector.get(IDialogService).open(options));
+ expect(screen.getByRole('dialog').style.height).toBe('40vh');
+ expect(screen.getByRole('dialog').style.maxHeight).toBe('');
+ expect(screen.getByRole('dialog').getAttribute('aria-modal')).toBeNull();
});
it('closes with the close button and invokes dialog callbacks', () => {
diff --git a/packages/ui/src/views/components/mobile-drawer/MobileDrawer.tsx b/packages/ui/src/views/components/mobile-drawer/MobileDrawer.tsx
index a043620a01..d5a383aaa7 100644
--- a/packages/ui/src/views/components/mobile-drawer/MobileDrawer.tsx
+++ b/packages/ui/src/views/components/mobile-drawer/MobileDrawer.tsx
@@ -15,7 +15,6 @@
*/
import type { AriaRole, PointerEvent, ReactNode, RefObject, TouchEvent } from 'react';
-import type { MobilePanelLayout } from '../../mobile-workbench/MobileCanvasLayout';
import {
clsx,
MobileOverlayContext,
@@ -24,6 +23,7 @@ import {
useMobileKeyboardViewportLayout,
} from '@univerjs/design';
import { createContext, useCallback, useContext, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import type { MobilePanelLayout } from '../../mobile-workbench/MobileCanvasLayout';
import { useMobileCanvasPanel, useMobileOverlayRegistration } from '../../mobile-workbench/MobileCanvasLayout';
import { MobileDrawerCoordinatorContext } from './MobileDrawerCoordinator';
@@ -42,6 +42,7 @@ function assignDrawerRef<T>(ref: MobileDrawerRef<T> | undefined, element: T | nu
const MOBILE_DRAWER_COMPACT_PERCENT = 40;
const MOBILE_DRAWER_EXPANDED_PERCENT = 80;
+const MOBILE_DIALOG_MAX_PERCENT = 60;
const MobileDrawerLayoutContext = createContext<MobilePanelLayout>('modal');
export function resolveMobileDrawerRelease(params: {
@@ -78,6 +79,7 @@ export function MobileDrawer(props: {
role?: AriaRole;
ariaLabel?: string;
layout?: MobilePanelLayout;
+ autoHeight?: boolean;
}) {
const {
snap,
@@ -99,6 +101,7 @@ export function MobileDrawer(props: {
role,
ariaLabel,
layout: requestedLayout,
+ autoHeight = false,
} = props;
const coordinator = useContext(MobileDrawerCoordinatorContext);
const registerDrawer = coordinator?.register;
@@ -153,6 +156,9 @@ export function MobileDrawer(props: {
? MOBILE_DRAWER_COMPACT_PERCENT
: MOBILE_DRAWER_EXPANDED_PERCENT);
const keyboardLayout = useMobileKeyboardViewportLayout(panelElementRef);
+ const contentMaxHeight = keyboardLayout
+ ? `min(${MOBILE_DIALOG_MAX_PERCENT}${viewportHeightUnit}, ${keyboardLayout.availableHeight}px)`
+ : `${MOBILE_DIALOG_MAX_PERCENT}${viewportHeightUnit}`;
useLayoutEffect(() => {
if (!registerDrawer || !unregisterDrawer) {
@@ -306,59 +312,64 @@ export function MobileDrawer(props: {
[&_textarea]:!univer-text-base
`, 'univer-pointer-events-auto', dragPercent != null && '!univer-transition-none', panelClassName)}
style={{
- height: `${drawerPercent}${viewportHeightUnit}`,
+ height: autoHeight ? 'auto' : `${drawerPercent}${viewportHeightUnit}`,
+ maxHeight: autoHeight ? contentMaxHeight : undefined,
+ bottom: autoHeight ? keyboardLayout?.bottom : undefined,
paddingBottom: 'env(safe-area-inset-bottom, 0px)',
}}
>
<div
- className="
- univer-relative univer-flex univer-h-14 univer-shrink-0 univer-items-end univer-bg-gray-0
+ className={clsx(`
+ univer-relative univer-flex univer-shrink-0 univer-items-end univer-bg-gray-0
dark:!univer-bg-gray-800
- "
+ `, autoHeight ? 'univer-h-12' : 'univer-h-14')}
>
- <button
- type="button"
- aria-label={snap === 'compact' ? expandLabel : collapseLabel}
- className={clsx(resetButtonClassName, `
- univer-absolute univer-left-1/2 univer-top-0 univer-z-10 univer-flex univer-h-6
- univer-w-16 -univer-translate-x-1/2 univer-touch-none univer-items-center
- univer-justify-center
- `)}
- style={{ touchAction: 'none' }}
- onPointerDown={handlePointerDown}
- onPointerMove={handlePointerMove}
- onPointerUp={handlePointerUp}
- onPointerCancel={handlePointerCancel}
- onTouchStart={handleTouchStart}
- onTouchMove={handleTouchMove}
- onTouchEnd={handleTouchEnd}
- onTouchCancel={handleTouchCancel}
- onClick={() => {
- if (suppressHandleClickRef.current) {
- suppressHandleClickRef.current = false;
- return;
- }
- onSnapChange(snap === 'compact' ? 'expanded' : 'compact');
- }}
- >
- <span
- className="
- univer-h-1 univer-w-10 univer-rounded-full univer-bg-gray-300
- dark:!univer-bg-gray-600
- "
- />
- </button>
+ {!autoHeight && (
+ <button
+ type="button"
+ aria-label={snap === 'compact' ? expandLabel : collapseLabel}
+ className={clsx(resetButtonClassName, `
+ univer-absolute univer-left-1/2 univer-top-0 univer-z-10 univer-flex univer-h-6
+ univer-w-16 -univer-translate-x-1/2 univer-touch-none univer-items-center
+ univer-justify-center
+ `)}
+ style={{ touchAction: 'none' }}
+ onPointerDown={handlePointerDown}
+ onPointerMove={handlePointerMove}
+ onPointerUp={handlePointerUp}
+ onPointerCancel={handlePointerCancel}
+ onTouchStart={handleTouchStart}
+ onTouchMove={handleTouchMove}
+ onTouchEnd={handleTouchEnd}
+ onTouchCancel={handleTouchCancel}
+ onClick={() => {
+ if (suppressHandleClickRef.current) {
+ suppressHandleClickRef.current = false;
+ return;
+ }
+ onSnapChange(snap === 'compact' ? 'expanded' : 'compact');
+ }}
+ >
+ <span
+ className="
+ univer-h-1 univer-w-10 univer-rounded-full univer-bg-gray-300
+ dark:!univer-bg-gray-600
+ "
+ />
+ </button>
+ )}
{header}
</div>
<div
ref={contentRef}
className={clsx(
- 'univer-flex-1 univer-overflow-y-auto univer-overflow-x-hidden univer-p-3',
+ 'univer-overflow-y-auto univer-overflow-x-hidden univer-p-3',
+ autoHeight ? 'univer-min-h-0 univer-flex-initial' : 'univer-flex-1',
scrollbarClassName,
contentClassName
)}
style={{
- paddingBottom: keyboardLayout
+ paddingBottom: !autoHeight && keyboardLayout
? `calc(0.75rem + ${keyboardLayout.bottom}px)`
: undefined,
}}
diff --git a/packages/ui/src/views/components/mobile-drawer/__tests__/MobileDrawer.spec.tsx b/packages/ui/src/views/components/mobile-drawer/__tests__/MobileDrawer.spec.tsx
index 73e90ecb62..a3554cfc3d 100644
--- a/packages/ui/src/views/components/mobile-drawer/__tests__/MobileDrawer.spec.tsx
+++ b/packages/ui/src/views/components/mobile-drawer/__tests__/MobileDrawer.spec.tsx
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-import type { MobileDrawerOpenMode } from '../MobileDrawer';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { ConfigProvider, MobileDropdown } from '@univerjs/design';
import enUS from '@univerjs/design/locale/en-US';
import { createElement, useRef } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { MobileDrawerOpenMode } from '../MobileDrawer';
import { MobileDrawer, resolveMobileDrawerRelease } from '../MobileDrawer';
import { MobileDrawerCoordinatorProvider } from '../MobileDrawerCoordinator';
@@ -50,6 +50,30 @@ afterEach(() => {
});
describe('mobile drawer snap behavior', () => {
+ it.each([false, true])('fits dialog content with a viewport height limit (dynamic viewport: %s)', (dynamicViewport) => {
+ vi.stubGlobal('CSS', { supports: () => dynamicViewport });
+ const onConfirm = vi.fn();
+ const { container } = render(
+ <MobileDrawer
+ autoHeight
+ snap="expanded"
+ expandLabel="Expand drawer"
+ collapseLabel="Collapse drawer"
+ onSnapChange={vi.fn()}
+ onClose={vi.fn()}
+ header={<h2>Permission required</h2>}
+ footer={<button type="button" onClick={onConfirm}>OK</button>}
+ >
+ <p>This range is protected.</p>
+ </MobileDrawer>
+ );
+ expect(container.querySelector('section')?.style.height).toBe('auto');
+ expect(container.querySelector('section')?.style.maxHeight).toBe(dynamicViewport ? '60dvh' : '60vh');
+ expect(screen.queryByRole('button', { name: 'Collapse drawer' })).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'OK' }));
+ expect(onConfirm).toHaveBeenCalledOnce();
+ });
+
it.each(['canvas', 'modal'] as const)('coordinates nested %s menus without changing the other layout', (layout) => {
vi.stubGlobal('CSS', { supports: () => false });
const app = (open: boolean) => (