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: fix and supplement the relevant logic for the F4 shortcut key (#6736)

wpxp123456bab5bc9cfbd9
diff --git a/packages/sheets-formula-ui/src/commands/operations/editor-formula.operation.ts b/packages/sheets-formula-ui/src/commands/operations/editor-formula.operation.ts
deleted file mode 100644
index c928295f03..0000000000
--- a/packages/sheets-formula-ui/src/commands/operations/editor-formula.operation.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { IOperation } from '@univerjs/core';
-import type { DeviceInputEventType } from '@univerjs/engine-render';
-import type { KeyCode, MetaKeys } from '@univerjs/ui';
-import type { META_KEY_CTRL_AND_SHIFT } from '../../common/prompt';
-
-import { CommandType } from '@univerjs/core';
-
-export interface ISelectEditorFormulaOperationParam {
- eventType: DeviceInputEventType;
- keycode?: KeyCode;
- metaKey?: MetaKeys | typeof META_KEY_CTRL_AND_SHIFT;
- isSingleEditor?: boolean;
-}
-
-// FIXME: this is an anti-pattern, using operation as an event
-
-export const SelectEditorFormulaOperation: IOperation<ISelectEditorFormulaOperationParam> = {
- id: 'formula-ui.operation.select-editor-formula',
- type: CommandType.OPERATION,
- handler: (accessor, params) => true,
-};
diff --git a/packages/sheets-formula-ui/src/commands/utils/__tests__/reference-absolute.spec.ts b/packages/sheets-formula-ui/src/commands/utils/__tests__/reference-absolute.spec.ts
index 7c70adba47..554619c082 100644
--- a/packages/sheets-formula-ui/src/commands/utils/__tests__/reference-absolute.spec.ts
+++ b/packages/sheets-formula-ui/src/commands/utils/__tests__/reference-absolute.spec.ts
@@ -81,6 +81,14 @@ describe('toggleReferenceAbsoluteAtCursor', () => {
}
});
+ it('the reference is row or column only', () => {
+ const rowReference = toggleReferenceAbsoluteAtCursor(lexerTreeBuilder, '=1:1', '=1'.length);
+ const columnReference = toggleReferenceAbsoluteAtCursor(lexerTreeBuilder, '=A:A', '=A'.length);
+
+ expect(rowReference?.formulaText).toBe('=$1:$1');
+ expect(columnReference?.formulaText).toBe('=$A:$A');
+ });
+
it('handles references at formula boundaries', () => {
const startBoundary = toggleReferenceAbsoluteAtCursor(lexerTreeBuilder, '=A1+SUM(B2)', '=A1'.length);
const endBoundary = toggleReferenceAbsoluteAtCursor(lexerTreeBuilder, '=SUM(1)+B2', '=SUM(1)+B2'.length);
diff --git a/packages/sheets-formula-ui/src/commands/utils/reference-absolute.ts b/packages/sheets-formula-ui/src/commands/utils/reference-absolute.ts
index 548774dfa0..159434aeac 100644
--- a/packages/sheets-formula-ui/src/commands/utils/reference-absolute.ts
+++ b/packages/sheets-formula-ui/src/commands/utils/reference-absolute.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { ISequenceNode } from '@univerjs/engine-formula';
-import { AbsoluteRefType } from '@univerjs/core';
+import type { ISequenceNode, LexerTreeBuilder } from '@univerjs/engine-formula';
+import { AbsoluteRefType, RANGE_TYPE } from '@univerjs/core';
import {
deserializeRangeWithSheetWithCache,
generateStringWithSequence,
@@ -32,10 +32,6 @@ export interface IReferenceAbsoluteResult {
cursorOffset: number;
}
-interface ILexerTreeBuilderLike {
- sequenceNodesBuilder(formulaString: string): Array<string | ISequenceNode> | undefined;
-}
-
interface IToggleReferenceTokenResult {
token: string;
referenceTarget: 'start' | 'end' | 'both';
@@ -44,7 +40,7 @@ interface IToggleReferenceTokenResult {
}
export function toggleReferenceAbsoluteAtCursor(
- lexerTreeBuilder: ILexerTreeBuilderLike,
+ lexerTreeBuilder: LexerTreeBuilder,
formulaText: string,
cursorOffset: number
): IReferenceAbsoluteResult | null {
@@ -113,6 +109,26 @@ function _toggleReferenceToken(referenceNode: ISequenceNode, offsetInToken: numb
return null;
}
+ const { range } = sequenceGrid;
+
+ if (range.rangeType === RANGE_TYPE.ROW || range.rangeType === RANGE_TYPE.COLUMN) {
+ const newToken = serializeRangeToRefString({
+ ...sequenceGrid,
+ range: {
+ ...range,
+ startAbsoluteRefType: range.startAbsoluteRefType === AbsoluteRefType.NONE ? AbsoluteRefType.ALL : AbsoluteRefType.NONE,
+ endAbsoluteRefType: range.endAbsoluteRefType === AbsoluteRefType.NONE ? AbsoluteRefType.ALL : AbsoluteRefType.NONE,
+ },
+ });
+
+ return {
+ token: newToken,
+ referenceTarget: 'both',
+ previousSeparatorOffset: null,
+ nextSeparatorOffset: null,
+ };
+ }
+
const { refBody } = handleRefStringInfo(referenceNode.token);
const referenceParts = refBody.split(':');
const previousSeparatorOffset = referenceParts.length === 2 ? referenceNode.token.indexOf(':') : null;
@@ -127,7 +143,7 @@ function _toggleReferenceToken(referenceNode: ISequenceNode, offsetInToken: numb
: _getRangeReferenceTarget(referenceNode.token, refBody, offsetInToken);
const nextRange = {
- ...sequenceGrid.range,
+ ...range,
};
if (referenceTarget === 'start' || referenceTarget === 'both') {
diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/formula-ui.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/formula-ui.controller.spec.ts
index 3a6ab5c485..c46d6d93d8 100644
--- a/packages/sheets-formula-ui/src/controllers/__tests__/formula-ui.controller.spec.ts
+++ b/packages/sheets-formula-ui/src/controllers/__tests__/formula-ui.controller.spec.ts
@@ -45,8 +45,8 @@ describe('FormulaUIController', () => {
expect(controller).toBeTruthy();
expect(mergeMenu).toHaveBeenCalledTimes(1);
- expect(registerCommand).toHaveBeenCalledTimes(8);
- expect(registerShortcut.mock.calls.length).toBeGreaterThan(3);
+ expect(registerCommand).toHaveBeenCalledTimes(7);
+ expect(registerShortcut.mock.calls.length).toBeLessThan(3);
expect(registerComponent).toHaveBeenCalledWith(SheetsUIPart.FORMULA_AUX, expect.any(Function));
expect(componentRegister).toHaveBeenCalledWith(MORE_FUNCTIONS_COMPONENT, expect.any(Function));
expect(registerRenderModule).toHaveBeenCalledWith(UniverInstanceType.UNIVER_SHEET, [expect.any(Function)]);
diff --git a/packages/sheets-formula-ui/src/controllers/formula-ui.controller.ts b/packages/sheets-formula-ui/src/controllers/formula-ui.controller.ts
index a111b83e0d..d6383c70f9 100644
--- a/packages/sheets-formula-ui/src/controllers/formula-ui.controller.ts
+++ b/packages/sheets-formula-ui/src/controllers/formula-ui.controller.ts
@@ -17,11 +17,9 @@
import type { Dependency } from '@univerjs/core';
import { Disposable, ICommandService, Inject, Injector, UniverInstanceType } from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
-
import { SheetsUIPart } from '@univerjs/sheets-ui';
import { ComponentManager, connectInjector, IMenuManagerService, IShortcutService, IUIPartsService } from '@univerjs/ui';
import { SheetCopyFormulaOnlyCommand, SheetOnlyPasteFormulaCommand } from '../commands/commands/formula-clipboard.command';
-import { SelectEditorFormulaOperation } from '../commands/operations/editor-formula.operation';
import { HelpFunctionOperation } from '../commands/operations/help-function.operation';
import { InsertFunctionOperation } from '../commands/operations/insert-function.operation';
import { MoreFunctionsOperation } from '../commands/operations/more-functions.operation';
@@ -32,14 +30,7 @@ import { FormulaProgressBar } from '../views/formula-progress/FormulaProgress';
import { MORE_FUNCTIONS_COMPONENT } from '../views/more-functions/interface';
import { MoreFunctions } from '../views/more-functions/MoreFunctions';
import { FormulaEditorShowController } from './formula-editor-show.controller';
-import {
- ChangeRefToAbsoluteShortcut,
- promptSelectionShortcutItem,
- promptSelectionShortcutItemCtrl,
- promptSelectionShortcutItemCtrlAndShift,
- promptSelectionShortcutItemShift,
- singleEditorPromptSelectionShortcutItem,
-} from './shortcuts/prompt.shortcut';
+import { ChangeRefToAbsoluteShortcut } from './shortcuts/prompt.shortcut';
import { QuickSumShortcut } from './shortcuts/quick-sum.shortcut';
export class FormulaUIController extends Disposable {
@@ -77,18 +68,12 @@ export class FormulaUIController extends Disposable {
MoreFunctionsOperation,
SearchFunctionOperation,
HelpFunctionOperation,
- SelectEditorFormulaOperation,
ReferenceAbsoluteOperation,
].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
}
private _registerShortcuts(): void {
[
- ...promptSelectionShortcutItem(),
- ...promptSelectionShortcutItemShift(),
- ...promptSelectionShortcutItemCtrl(),
- ...promptSelectionShortcutItemCtrlAndShift(),
- ...singleEditorPromptSelectionShortcutItem(),
QuickSumShortcut,
ChangeRefToAbsoluteShortcut,
].forEach((item) => {
diff --git a/packages/sheets-formula-ui/src/controllers/shortcuts/prompt.shortcut.ts b/packages/sheets-formula-ui/src/controllers/shortcuts/prompt.shortcut.ts
index d0aac83540..5a5e17aa9b 100644
--- a/packages/sheets-formula-ui/src/controllers/shortcuts/prompt.shortcut.ts
+++ b/packages/sheets-formula-ui/src/controllers/shortcuts/prompt.shortcut.ts
@@ -14,121 +14,13 @@
* limitations under the License.
*/
-import type { IContextService } from '@univerjs/core';
import type { IShortcutItem } from '@univerjs/ui';
-import { EDITOR_ACTIVATED, FOCUSING_SHEET, FOCUSING_UNIVER_EDITOR } from '@univerjs/core';
-import { DeviceInputEventType } from '@univerjs/engine-render';
-import { whenFormulaEditorActivated } from '@univerjs/sheets-ui';
-import { KeyCode, MetaKeys } from '@univerjs/ui';
-
-import { SelectEditorFormulaOperation } from '../../commands/operations/editor-formula.operation';
+import { whenSheetEditorActivated } from '@univerjs/sheets-ui';
+import { KeyCode } from '@univerjs/ui';
import { ReferenceAbsoluteOperation } from '../../commands/operations/reference-absolute.operation';
-import { META_KEY_CTRL_AND_SHIFT } from '../../common/prompt';
-import { whenEditorStandalone } from '../utils/utils';
-
-export const PROMPT_SELECTION_KEYCODE_ARROW_LIST = [
- KeyCode.ARROW_DOWN,
- KeyCode.ARROW_UP,
- KeyCode.ARROW_LEFT,
- KeyCode.ARROW_RIGHT,
-];
-
-export const PROMPT_SELECTION_KEYCODE_LIST = [...PROMPT_SELECTION_KEYCODE_ARROW_LIST, KeyCode.ENTER, KeyCode.TAB, KeyCode.ESC];
-
-export function promptSelectionShortcutItem() {
- const shortcutList: IShortcutItem[] = [];
- for (const keycode of PROMPT_SELECTION_KEYCODE_LIST) {
- shortcutList.push({
- id: SelectEditorFormulaOperation.id,
- binding: keycode,
- preconditions: (contextService) => whenFormulaEditorActivated(contextService),
- staticParameters: {
- eventType: DeviceInputEventType.Keyboard,
- keycode,
- },
- });
- }
- return shortcutList;
-}
-
-export function promptSelectionShortcutItemShift() {
- const shortcutList: IShortcutItem[] = [];
- for (const keycode of PROMPT_SELECTION_KEYCODE_ARROW_LIST) {
- shortcutList.push({
- id: SelectEditorFormulaOperation.id,
- binding: keycode | MetaKeys.SHIFT,
- preconditions: (contextService) => whenFormulaEditorActivated(contextService),
- staticParameters: {
- eventType: DeviceInputEventType.Keyboard,
- keycode,
- metaKey: MetaKeys.SHIFT,
- },
- });
- }
- return shortcutList;
-}
-
-export function promptSelectionShortcutItemCtrl() {
- const shortcutList: IShortcutItem[] = [];
- for (const keycode of PROMPT_SELECTION_KEYCODE_ARROW_LIST) {
- shortcutList.push({
- id: SelectEditorFormulaOperation.id,
- binding: keycode | MetaKeys.CTRL_COMMAND,
- preconditions: (contextService) => whenFormulaEditorActivated(contextService),
- staticParameters: {
- eventType: DeviceInputEventType.Keyboard,
- keycode,
- metaKey: MetaKeys.CTRL_COMMAND,
- },
- });
- }
- return shortcutList;
-}
-
-export function promptSelectionShortcutItemCtrlAndShift() {
- const shortcutList: IShortcutItem[] = [];
- for (const keycode of PROMPT_SELECTION_KEYCODE_ARROW_LIST) {
- shortcutList.push({
- id: SelectEditorFormulaOperation.id,
- binding: keycode | MetaKeys.SHIFT | MetaKeys.CTRL_COMMAND,
- preconditions: (contextService) => whenFormulaEditorActivated(contextService),
- staticParameters: {
- eventType: DeviceInputEventType.Keyboard,
- keycode,
- metaKey: META_KEY_CTRL_AND_SHIFT,
- },
- });
- }
- return shortcutList;
-}
export const ChangeRefToAbsoluteShortcut: IShortcutItem = {
id: ReferenceAbsoluteOperation.id,
binding: KeyCode.F4,
preconditions: (contextService) => whenSheetEditorActivated(contextService),
};
-
-function whenSheetEditorActivated(contextService: IContextService): boolean {
- return (
- contextService.getContextValue(FOCUSING_SHEET) &&
- contextService.getContextValue(FOCUSING_UNIVER_EDITOR) &&
- contextService.getContextValue(EDITOR_ACTIVATED)
- );
-}
-
-export function singleEditorPromptSelectionShortcutItem() {
- const shortcutList: IShortcutItem[] = [];
- for (const keycode of [KeyCode.ENTER, KeyCode.TAB, KeyCode.ARROW_DOWN, KeyCode.ARROW_UP]) {
- shortcutList.push({
- id: SelectEditorFormulaOperation.id,
- binding: keycode,
- preconditions: (contextService) => whenEditorStandalone(contextService),
- staticParameters: {
- eventType: DeviceInputEventType.Keyboard,
- keycode,
- isSingleEditor: true,
- },
- });
- }
- return shortcutList;
-}
diff --git a/packages/sheets-formula-ui/src/index.ts b/packages/sheets-formula-ui/src/index.ts
index 8eec8b3e8f..5e0a010e8b 100644
--- a/packages/sheets-formula-ui/src/index.ts
+++ b/packages/sheets-formula-ui/src/index.ts
@@ -17,7 +17,6 @@
import './global.css';
export { SheetCopyFormulaOnlyCommand, SheetOnlyPasteFormulaCommand } from './commands/commands/formula-clipboard.command';
-export { SelectEditorFormulaOperation } from './commands/operations/editor-formula.operation';
export { HelpFunctionOperation } from './commands/operations/help-function.operation';
export { InsertFunctionOperation } from './commands/operations/insert-function.operation';
export { MoreFunctionsOperation } from './commands/operations/more-functions.operation';
diff --git a/packages/sheets-numfmt-ui/src/controllers/numfmt-repeat-last-action-controller.ts b/packages/sheets-numfmt-ui/src/controllers/numfmt-repeat-last-action-controller.ts
new file mode 100644
index 0000000000..34f60ae20d
--- /dev/null
+++ b/packages/sheets-numfmt-ui/src/controllers/numfmt-repeat-last-action-controller.ts
@@ -0,0 +1,67 @@
+/**
+ * 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 { ISetNumfmtCommandParams } from '@univerjs/sheets-numfmt';
+import type { RepeatableCommandHandler } from '@univerjs/sheets-ui';
+import { Disposable, Inject } from '@univerjs/core';
+import { SetNumfmtCommand } from '@univerjs/sheets-numfmt';
+import { IRepeatLastActionService, RepeatLastActionPermission } from '@univerjs/sheets-ui';
+
+export class NumfmtRepeatLastActionController extends Disposable {
+ constructor(
+ @Inject(IRepeatLastActionService) private readonly _repeatLastActionService: IRepeatLastActionService
+ ) {
+ super();
+
+ this._initCommandRecording();
+ }
+
+ private _initCommandRecording(): void {
+ const handler: RepeatableCommandHandler<ISetNumfmtCommandParams> = (selections, params) => {
+ if (!params) return;
+
+ const { values } = params;
+ const numfmtCell = values.find((cell) => cell.pattern);
+
+ if (!numfmtCell) return;
+
+ const { pattern, type } = numfmtCell;
+ const newValues = [];
+ const cache = new Set<string>();
+
+ for (const selection of selections) {
+ const { startRow, startColumn, endRow, endColumn } = selection;
+ for (let row = startRow; row <= endRow; row++) {
+ for (let col = startColumn; col <= endColumn; col++) {
+ const key = `${row}-${col}`;
+ if (cache.has(key)) {
+ continue;
+ }
+ cache.add(key);
+ newValues.push({ row, col, pattern, type });
+ }
+ }
+ }
+
+ return {
+ ...params,
+ values: newValues,
+ };
+ };
+
+ this.disposeWithMe(this._repeatLastActionService.registerRepeatableCommand(SetNumfmtCommand.id, handler, RepeatLastActionPermission.CellStyle));
+ }
+}
diff --git a/packages/sheets-numfmt-ui/src/plugin.ts b/packages/sheets-numfmt-ui/src/plugin.ts
index 05716d33c0..219b0a12a2 100644
--- a/packages/sheets-numfmt-ui/src/plugin.ts
+++ b/packages/sheets-numfmt-ui/src/plugin.ts
@@ -23,6 +23,7 @@ import { UniverSheetsUIPlugin } from '@univerjs/sheets-ui';
import pkg from '../package.json';
import { defaultPluginConfig } from './config/config';
import { NumfmtAlertRenderController } from './controllers/numfmt-alert-render.controller';
+import { NumfmtRepeatLastActionController } from './controllers/numfmt-repeat-last-action-controller';
import { SheetNumfmtUIController } from './controllers/numfmt.controller';
import { NumfmtEditorController } from './controllers/numfmt.editor.controller';
import { UserHabitController } from './controllers/user-habit.controller';
@@ -62,6 +63,7 @@ export class UniverSheetsNumfmtUIPlugin extends Plugin {
[NumfmtEditorController],
[UserHabitController],
[NumfmtMenuController],
+ [NumfmtRepeatLastActionController],
]);
}
@@ -71,6 +73,7 @@ export class UniverSheetsNumfmtUIPlugin extends Plugin {
[SheetNumfmtUIController],
[NumfmtEditorController],
[NumfmtMenuController],
+ [NumfmtRepeatLastActionController],
]);
}
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/command-behavior.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/command-behavior.spec.ts
index ebe18864db..5e5b62c4b6 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/command-behavior.spec.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/command-behavior.spec.ts
@@ -43,18 +43,14 @@ import {
DeleteRangeProtectionMutation,
DeleteWorksheetProtectionCommand,
RangeProtectionRuleModel,
- RemoveColCommand,
RemoveSheetCommand,
SetBoldCommand,
SetFontFamilyCommand,
SetFontSizeCommand,
SetItalicCommand,
- SetRangeValuesCommand,
SetStrikeThroughCommand,
- SetStyleCommand,
SetTextColorCommand,
SetUnderlineCommand,
- SheetPermissionCheckController,
SheetsSelectionsService,
WorksheetProtectionRuleModel,
} from '@univerjs/sheets';
@@ -63,7 +59,6 @@ import { SHEET_VIEW_KEY, SHEET_ZOOM_RANGE } from '../../../common/keys';
import { AutoWidthController } from '../../../controllers/auto-width.controller';
import * as menuUtils from '../../../menu/utils';
import { IEditorBridgeService } from '../../../services/editor-bridge.service';
-import { IRepeatLastActionService } from '../../../services/repeat-last-action.service';
import { ISheetBarService } from '../../../services/sheet-bar/sheet-bar.service';
import { SetScrollOperation } from '../../operations/scroll.operation';
import { SetZoomRatioOperation } from '../../operations/set-zoom-ratio.operation';
@@ -93,7 +88,6 @@ import {
ViewSheetPermissionFromSheetBarCommand,
} from '../range-protection.command';
import { RemoveSheetConfirmCommand } from '../remove-sheet-confirm.command';
-import { RepeatLastActionCommand } from '../repeat-last-action.command';
import { ResetScrollCommand, ScrollCommand, ScrollToCellCommand, SetScrollRelativeCommand } from '../set-scroll.command';
import { SetWorksheetColAutoWidthCommand } from '../set-worksheet-auto-col-width.command';
import { ChangeZoomRatioCommand, SetZoomRatioCommand } from '../set-zoom-ratio.command';
@@ -230,160 +224,6 @@ describe('sheets-ui command behaviors', () => {
expect(await SetRangeFontIncreaseCommand.handler(noSelectionAccessor, undefined as any)).toBe(false);
});
- it('replays the stored style action against the current selection', async () => {
- const executeCommand = vi.fn(async () => true);
- const repeatLastActionService = {
- getAction: vi.fn(() => ({
- kind: 'command',
- commandId: SetStyleCommand.id,
- params: {
- style: {
- type: 'bl',
- value: true,
- },
- },
- permission: 'cellStyle',
- selectionRequirement: 'none',
- })),
- runWithoutRecording: vi.fn(async (callback: () => Promise<boolean>) => callback()),
- };
- const permissionCheckController = {
- permissionCheckWithRanges: vi.fn(() => true),
- blockExecuteWithoutPermission: vi.fn(),
- };
-
- const accessor = createAccessor([
- [ICommandService, { executeCommand }],
- [IRepeatLastActionService, repeatLastActionService],
- [SheetsSelectionsService, { getCurrentSelections: () => [{ range: { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 } }] }],
- [IUniverInstanceService, {
- getCurrentUnitOfType: () => ({
- getUnitId: () => 'workbook-1',
- getActiveSheet: () => ({
- getSheetId: () => 'sheet-1',
- getMaxRows: () => 100,
- getMaxColumns: () => 50,
- }),
- }),
- }],
- [LocaleService, { t: vi.fn((key: string) => key) }],
- [SheetPermissionCheckController, permissionCheckController],
- ]);
-
- expect(await RepeatLastActionCommand.handler(accessor, undefined as any)).toBe(true);
- expect(permissionCheckController.permissionCheckWithRanges).toHaveBeenCalledTimes(1);
- expect(executeCommand).toHaveBeenCalledWith(SetStyleCommand.id, {
- style: {
- type: 'bl',
- value: true,
- },
- });
- });
-
- it('fails silently when the stored structural action does not match the current selection shape', async () => {
- const executeCommand = vi.fn(async () => true);
- const accessor = createAccessor([
- [ICommandService, { executeCommand }],
- [IRepeatLastActionService, {
- getAction: () => ({
- kind: 'command',
- commandId: RemoveColCommand.id,
- permission: 'none',
- selectionRequirement: 'fullColumns',
- }),
- runWithoutRecording: async (callback: () => Promise<boolean>) => callback(),
- }],
- [SheetsSelectionsService, { getCurrentSelections: () => [{ range: { startRow: 1, endRow: 2, startColumn: 1, endColumn: 1 } }] }],
- [IUniverInstanceService, {
- getCurrentUnitOfType: () => ({
- getUnitId: () => 'workbook-1',
- getActiveSheet: () => ({
- getSheetId: () => 'sheet-1',
- getMaxRows: () => 100,
- getMaxColumns: () => 50,
- }),
- }),
- }],
- [LocaleService, { t: vi.fn((key: string) => key) }],
- [SheetPermissionCheckController, {
- permissionCheckWithRanges: vi.fn(() => true),
- blockExecuteWithoutPermission: vi.fn(),
- }],
- ]);
-
- expect(await RepeatLastActionCommand.handler(accessor, undefined as any)).toBe(false);
- expect(executeCommand).not.toHaveBeenCalled();
- });
-
- it('replays stored value and numfmt actions using the current selection coordinates', async () => {
- const executeCommand = vi.fn(async () => true);
- const selectionRange = { startRow: 3, endRow: 4, startColumn: 5, endColumn: 6 };
- const permissionCheckController = {
- permissionCheckWithRanges: vi.fn(() => true),
- blockExecuteWithoutPermission: vi.fn(),
- };
- const baseAccessor = [
- [ICommandService, { executeCommand }],
- [SheetsSelectionsService, { getCurrentSelections: () => [{ range: selectionRange }] }],
- [IUniverInstanceService, {
- getCurrentUnitOfType: () => ({
- getUnitId: () => 'workbook-1',
- getActiveSheet: () => ({
- getSheetId: () => 'sheet-1',
- getMaxRows: () => 100,
- getMaxColumns: () => 50,
- }),
- }),
- }],
- [LocaleService, { t: vi.fn((key: string) => key) }],
- [SheetPermissionCheckController, permissionCheckController],
- ] as Array<[unknown, unknown]>;
-
- const valueAccessor = createAccessor([
- ...baseAccessor,
- [IRepeatLastActionService, {
- getAction: () => ({
- kind: 'set-range-values',
- value: { v: 'repeat', t: 1 },
- permission: 'cellValue',
- selectionRequirement: 'none',
- }),
- runWithoutRecording: async (callback: () => Promise<boolean>) => callback(),
- }],
- ]);
-
- expect(await RepeatLastActionCommand.handler(valueAccessor, undefined as any)).toBe(true);
- expect(executeCommand).toHaveBeenCalledWith(SetRangeValuesCommand.id, {
- value: { v: 'repeat', t: 1 },
- });
-
- executeCommand.mockClear();
-
- const numfmtAccessor = createAccessor([
- ...baseAccessor,
- [IRepeatLastActionService, {
- getAction: () => ({
- kind: 'set-numfmt',
- pattern: '0.00%',
- type: 'percent',
- permission: 'cellStyle',
- selectionRequirement: 'none',
- }),
- runWithoutRecording: async (callback: () => Promise<boolean>) => callback(),
- }],
- ]);
-
- expect(await RepeatLastActionCommand.handler(numfmtAccessor, undefined as any)).toBe(true);
- expect(executeCommand).toHaveBeenCalledWith('sheet.command.numfmt.set.numfmt', {
- values: [
- { row: 3, col: 5, pattern: '0.00%', type: 'percent' },
- { row: 3, col: 6, pattern: '0.00%', type: 'percent' },
- { row: 4, col: 5, pattern: '0.00%', type: 'percent' },
- { row: 4, col: 6, pattern: '0.00%', type: 'percent' },
- ],
- });
- });
-
it('updates header sizes and custom header components', async () => {
const rowHeader = { setCustomHeader: vi.fn() };
const colHeader = { setCustomHeader: vi.fn() };
diff --git a/packages/sheets-ui/src/commands/commands/repeat-last-action.command.ts b/packages/sheets-ui/src/commands/commands/repeat-last-action.command.ts
index f82ccb2438..6ee354a5e4 100644
--- a/packages/sheets-ui/src/commands/commands/repeat-last-action.command.ts
+++ b/packages/sheets-ui/src/commands/commands/repeat-last-action.command.ts
@@ -14,152 +14,101 @@
* limitations under the License.
*/
-import type { IAccessor, ICommand, IRange } from '@univerjs/core';
-import type { RepeatLastActionPermission } from '../../services/repeat-last-action.service';
+import type { IAccessor, ICommand } from '@univerjs/core';
+import { CommandType, LocaleService } from '@univerjs/core';
import {
- CommandType,
- ICommandService,
- IUniverInstanceService,
- LocaleService,
-} from '@univerjs/core';
-import {
- getSheetCommandTarget,
RangeProtectionPermissionEditPoint,
- SetBorderBasicCommand,
- SetRangeValuesCommand,
SheetPermissionCheckController,
SheetsSelectionsService,
WorkbookEditablePermission,
WorksheetEditPermission,
WorksheetSetCellStylePermission,
WorksheetSetCellValuePermission,
+ WorksheetSetColumnStylePermission,
+ WorksheetSetRowStylePermission,
} from '@univerjs/sheets';
-import { IRepeatLastActionService } from '../../services/repeat-last-action.service';
+import { IRepeatLastActionService, RepeatLastActionPermission } from '../../services/repeat-last-action.service';
-const SET_NUMFMT_COMMAND_ID = 'sheet.command.numfmt.set.numfmt';
+const permissionCheckMap = {
+ [RepeatLastActionPermission.Editable]: {
+ permissionTypes: {
+ workbookTypes: [WorkbookEditablePermission],
+ worksheetTypes: [WorksheetEditPermission],
+ rangeTypes: [RangeProtectionPermissionEditPoint],
+ },
+ errorMessageKey: 'permission.dialog.editErr',
+ },
+ [RepeatLastActionPermission.CellStyle]: {
+ permissionTypes: {
+ workbookTypes: [WorkbookEditablePermission],
+ worksheetTypes: [WorksheetEditPermission, WorksheetSetCellStylePermission],
+ rangeTypes: [RangeProtectionPermissionEditPoint],
+ },
+ errorMessageKey: 'permission.dialog.setStyleErr',
+ },
+ [RepeatLastActionPermission.CellValue]: {
+ permissionTypes: {
+ workbookTypes: [WorkbookEditablePermission],
+ worksheetTypes: [WorksheetEditPermission, WorksheetSetCellValuePermission],
+ rangeTypes: [RangeProtectionPermissionEditPoint],
+ },
+ errorMessageKey: 'permission.dialog.editErr',
+ },
+ [RepeatLastActionPermission.RowStyle]: {
+ permissionTypes: {
+ workbookTypes: [WorkbookEditablePermission],
+ worksheetTypes: [WorksheetEditPermission, WorksheetSetRowStylePermission],
+ rangeTypes: [RangeProtectionPermissionEditPoint],
+ },
+ errorMessageKey: 'permission.dialog.setRowColStyleErr',
+ },
+ [RepeatLastActionPermission.ColumnStyle]: {
+ permissionTypes: {
+ workbookTypes: [WorkbookEditablePermission],
+ worksheetTypes: [WorksheetEditPermission, WorksheetSetColumnStylePermission],
+ rangeTypes: [RangeProtectionPermissionEditPoint],
+ },
+ errorMessageKey: 'permission.dialog.setRowColStyleErr',
+ },
+};
export const RepeatLastActionCommand: ICommand = {
id: 'sheet.command.repeat-last-action',
type: CommandType.COMMAND,
handler: async (accessor: IAccessor) => {
- const repeatLastActionService = accessor.get(IRepeatLastActionService);
- const commandService = accessor.get(ICommandService);
const selectionManagerService = accessor.get(SheetsSelectionsService);
- const univerInstanceService = accessor.get(IUniverInstanceService);
- const localeService = accessor.get(LocaleService);
- const permissionCheckController = accessor.get(SheetPermissionCheckController);
-
- const action = repeatLastActionService.getAction();
- if (!action) {
- return false;
- }
-
const selections = selectionManagerService.getCurrentSelections()?.map((selection) => selection.range);
if (!selections?.length) {
return false;
}
- const target = getSheetCommandTarget(univerInstanceService);
- if (!target) {
- return false;
- }
-
- const { worksheet } = target;
- if (!_matchesSelectionRequirement(action.selectionRequirement, selections, worksheet.getMaxRows() - 1, worksheet.getMaxColumns() - 1)) {
- return false;
- }
-
- _ensurePermission(accessor, action.permission, permissionCheckController, localeService);
-
- return repeatLastActionService.runWithoutRecording(async () => {
- switch (action.kind) {
- case 'command':
- return commandService.executeCommand(action.commandId, action.params);
- case 'set-border-basic':
- return commandService.executeCommand(SetBorderBasicCommand.id, {
- value: action.value,
- ranges: selections,
- });
- case 'set-numfmt':
- return commandService.executeCommand(SET_NUMFMT_COMMAND_ID, {
- values: _buildNumfmtValues(selections, action.pattern, action.type),
- });
- case 'set-range-values':
- return commandService.executeCommand(SetRangeValuesCommand.id, {
- value: action.value,
- });
- default:
+ const repeatLastActionService = accessor.get(IRepeatLastActionService);
+ const sheetPermissionCheckController = accessor.get(SheetPermissionCheckController);
+ const localeService = accessor.get(LocaleService);
+ const actionPermissionType = repeatLastActionService.getActionPermission();
+
+ if (Array.isArray(actionPermissionType)) {
+ for (const permissionType of actionPermissionType) {
+ if (permissionType === RepeatLastActionPermission.None) {
+ continue;
+ }
+
+ const permissionConfig = permissionCheckMap[permissionType];
+ const permission = sheetPermissionCheckController.permissionCheckWithRanges(permissionConfig.permissionTypes);
+ if (!permission) {
+ sheetPermissionCheckController.blockExecuteWithoutPermission(localeService.t(permissionConfig.errorMessageKey));
return false;
+ }
}
- });
- },
-};
-
-function _ensurePermission(
- accessor: IAccessor,
- permission: RepeatLastActionPermission,
- permissionCheckController: SheetPermissionCheckController,
- localeService: LocaleService
-) {
- if (permission === 'none') {
- return;
- }
-
- const hasPermission = permission === 'cellStyle'
- ? permissionCheckController.permissionCheckWithRanges({
- workbookTypes: [WorkbookEditablePermission],
- rangeTypes: [RangeProtectionPermissionEditPoint],
- worksheetTypes: [WorksheetSetCellStylePermission, WorksheetEditPermission],
- })
- : permissionCheckController.permissionCheckWithRanges({
- workbookTypes: [WorkbookEditablePermission],
- rangeTypes: [RangeProtectionPermissionEditPoint],
- worksheetTypes: [WorksheetSetCellValuePermission, WorksheetEditPermission],
- });
-
- if (hasPermission) {
- return;
- }
-
- const errorMessage = permission === 'cellStyle'
- ? localeService.t('permission.dialog.setStyleErr')
- : localeService.t('permission.dialog.editErr');
-
- permissionCheckController.blockExecuteWithoutPermission(errorMessage);
-}
-
-function _matchesSelectionRequirement(
- selectionRequirement: 'none' | 'fullRows' | 'fullColumns',
- selections: IRange[],
- maxRow: number,
- maxColumn: number
-): boolean {
- if (selectionRequirement === 'none') {
- return true;
- }
-
- if (selectionRequirement === 'fullRows') {
- return selections.every((range) => range.startColumn === 0 && range.endColumn === maxColumn);
- }
-
- return selections.every((range) => range.startRow === 0 && range.endRow === maxRow);
-}
-
-function _buildNumfmtValues(selections: IRange[], pattern?: string, type?: string) {
- const values: Array<{ pattern?: string; row: number; col: number; type?: string }> = [];
-
- selections.forEach((range) => {
- for (let row = range.startRow; row <= range.endRow; row++) {
- for (let col = range.startColumn; col <= range.endColumn; col++) {
- values.push({
- row,
- col,
- pattern,
- type,
- });
+ } else if (actionPermissionType !== RepeatLastActionPermission.None) {
+ const permissionConfig = permissionCheckMap[actionPermissionType];
+ const permission = sheetPermissionCheckController.permissionCheckWithRanges(permissionConfig.permissionTypes);
+ if (!permission) {
+ sheetPermissionCheckController.blockExecuteWithoutPermission(localeService.t(permissionConfig.errorMessageKey));
+ return false;
}
}
- });
- return values;
-}
+ return await repeatLastActionService.runWithoutRecording(selections);
+ },
+};
diff --git a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
index feaa5916e4..51f18249a4 100644
--- a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
@@ -93,7 +93,6 @@ import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../config/config';
import { IEditorBridgeService } from '../../services/editor-bridge.service';
import { ICellEditorManagerService } from '../../services/editor/cell-editor-manager.service';
import { SheetCellEditorResizeService } from '../../services/editor/cell-editor-resize.service';
-import { IRepeatLastActionService } from '../../services/repeat-last-action.service';
import { EditorBridgeRenderController } from '../render-controllers/editor-bridge.render-controller';
import { MOVE_SELECTION_KEYCODE_LIST } from '../shortcuts/editor.shortcut';
import { extractStringFromForceString, isForceString } from '../utils/cell-tools';
@@ -135,7 +134,6 @@ export class EditingRenderController extends Disposable {
@Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,
@Inject(SheetCellEditorResizeService) private readonly _sheetCellEditorResizeService: SheetCellEditorResizeService,
@Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
- @IRepeatLastActionService private readonly _repeatLastActionService: IRepeatLastActionService,
@IConfigService private readonly _configService: IConfigService
) {
super();
@@ -681,8 +679,6 @@ export class EditingRenderController extends Disposable {
this._undoRedoService.rollback(redoUndoId, unitId);
return false;
}
-
- this._repeatLastActionService.setCellContentAction(finalCell);
}
return true;
diff --git a/packages/sheets-ui/src/controllers/repeat-last-action.controller.ts b/packages/sheets-ui/src/controllers/repeat-last-action.controller.ts
new file mode 100644
index 0000000000..f793b8c5ec
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/repeat-last-action.controller.ts
@@ -0,0 +1,43 @@
+/**
+ * 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 { Disposable, ICommandService, Inject } from '@univerjs/core';
+import { IRepeatLastActionService } from '../services/repeat-last-action.service';
+
+export class RepeatLastActionController extends Disposable {
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService,
+ @Inject(IRepeatLastActionService) private readonly _repeatLastActionService: IRepeatLastActionService
+ ) {
+ super();
+
+ this._initCommandRecording();
+ }
+
+ private _initCommandRecording(): void {
+ this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo, options) => {
+ if (options?.fromCollab || options?.fromChangeset) {
+ return;
+ }
+
+ if (!this._repeatLastActionService.getRepeatableCommands().has(commandInfo.id)) {
+ return;
+ }
+
+ this._repeatLastActionService.setAction(commandInfo);
+ }));
+ }
+}
diff --git a/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts b/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts
index f6a1e1fc63..b4f5c80c6e 100644
--- a/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts
+++ b/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts
@@ -16,9 +16,9 @@
import type { IShortcutItem } from '@univerjs/ui';
import { BreakLineCommand, DeleteLeftCommand, DeleteRightCommand } from '@univerjs/docs-ui';
-
import { DeviceInputEventType } from '@univerjs/engine-render';
import { KeyCode, MetaKeys } from '@univerjs/ui';
+import { RepeatLastActionCommand } from '../../commands/commands/repeat-last-action.command';
import {
SetCellEditVisibleArrowOperation,
SetCellEditVisibleOperation,
@@ -87,7 +87,7 @@ export const StartEditWithF2Shortcut: IShortcutItem = {
};
export const RepeatLastActionShortcut: IShortcutItem = {
- id: 'sheet.command.repeat-last-action',
+ id: RepeatLastActionCommand.id,
binding: KeyCode.F4,
description: 'shortcut.sheet.repeat-last-action',
group: '4_sheet-edit',
diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.ts
index 2d5edfdbdd..344e5c7fc9 100644
--- a/packages/sheets-ui/src/index.ts
+++ b/packages/sheets-ui/src/index.ts
@@ -111,7 +111,7 @@ export { HeaderResizeRenderController } from './controllers/render-controllers/h
export { SheetsScrollRenderController } from './controllers/render-controllers/scroll.render-controller';
export { type ITelemetryData, SheetRenderController } from './controllers/render-controllers/sheet.render-controller';
export { SheetUIController } from './controllers/sheet-ui.controller';
-export { whenFormulaEditorActivated, whenSheetEditorFocused } from './controllers/shortcuts/utils';
+export { whenFormulaEditorActivated, whenSheetEditorActivated, whenSheetEditorFocused } from './controllers/shortcuts/utils';
export { StatusBarController } from './controllers/status-bar.controller';
export { getCoordByCell, getCoordByOffset, getSheetObject, getTransformCoord } from './controllers/utils/component-tools';
export { virtualizeDiscreteRanges } from './controllers/utils/range-tools';
@@ -144,6 +144,7 @@ export { IMarkSelectionService, MarkSelectionService } from './services/mark-sel
export { type ProtectedRangeShadowStrategy, SheetPermissionRenderManagerService } from './services/permission/sheet-permission-render-manager.service';
export { SheetPermissionUserManagerService } from './services/permission/sheet-permission-user-list.service';
export { SheetPrintInterceptorService } from './services/print-interceptor.service';
+export { IRepeatLastActionService, type RepeatableCommandHandler, RepeatLastActionPermission } from './services/repeat-last-action.service';
export { SheetScrollManagerService } from './services/scroll-manager.service';
export type { IScrollState, IViewportScrollState } from './services/scroll-manager.service';
export { BaseSelectionRenderService, genSelectionByRange, selectionDataForSelectAll as getAllSelection, getTopLeftSelectionOfCurrSheet, ISheetSelectionRenderService } from './services/selection/base-selection-render.service';
diff --git a/packages/sheets-ui/src/plugin.ts b/packages/sheets-ui/src/plugin.ts
index 608bb22942..80a6a3fc84 100644
--- a/packages/sheets-ui/src/plugin.ts
+++ b/packages/sheets-ui/src/plugin.ts
@@ -63,6 +63,7 @@ import { SheetsScrollRenderController } from './controllers/render-controllers/s
import { SheetRenderController } from './controllers/render-controllers/sheet.render-controller';
import { SheetSkeletonRenderController } from './controllers/render-controllers/skeleton.render-controller';
import { SheetsZoomRenderController } from './controllers/render-controllers/zoom.render-controller';
+import { RepeatLastActionController } from './controllers/repeat-last-action.controller';
import { SheetUIController } from './controllers/sheet-ui.controller';
import { StatusBarController } from './controllers/status-bar.controller';
import { AutoHeightService } from './services/auto-height.service';
@@ -179,6 +180,7 @@ export class UniverSheetsUIPlugin extends Plugin {
[EditorDataSyncController],
[SheetCheckboxController],
[EditingRenderController],
+ [RepeatLastActionController],
// permission
[SheetPermissionPanelModel],
@@ -225,6 +227,7 @@ export class UniverSheetsUIPlugin extends Plugin {
[EditorDataSyncController],
[SheetCheckboxController],
[EditingRenderController],
+ [RepeatLastActionController],
]);
}
diff --git a/packages/sheets-ui/src/services/__tests__/repeat-last-action.service.spec.ts b/packages/sheets-ui/src/services/__tests__/repeat-last-action.service.spec.ts
deleted file mode 100644
index 1e2c2390fe..0000000000
--- a/packages/sheets-ui/src/services/__tests__/repeat-last-action.service.spec.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import type { CommandListener, ICommandService } from '@univerjs/core';
-import { SetStyleCommand } from '@univerjs/sheets';
-import { describe, expect, it, vi } from 'vitest';
-import { RepeatLastActionService } from '../repeat-last-action.service';
-
-describe('RepeatLastActionService', () => {
- it('records explicit repeatable commands and ignores nested recording-disabled executions', async () => {
- let listener: CommandListener | undefined;
- const commandService = {
- onCommandExecuted: vi.fn((cb: CommandListener) => {
- listener = cb;
- return { dispose: vi.fn() };
- }),
- } as unknown as ICommandService;
-
- const service = new RepeatLastActionService(commandService);
-
- listener?.({
- id: SetStyleCommand.id,
- params: {
- style: {
- type: 'bl',
- value: true,
- },
- },
- });
-
- expect(service.getAction()).toEqual({
- kind: 'command',
- commandId: SetStyleCommand.id,
- params: {
- style: {
- type: 'bl',
- value: true,
- },
- },
- permission: 'cellStyle',
- selectionRequirement: 'none',
- });
-
- await service.runWithoutRecording(async () => {
- listener?.({
- id: SetStyleCommand.id,
- params: {
- style: {
- type: 'it',
- value: true,
- },
- },
- });
-
- return true;
- });
-
- expect(service.getAction()).toEqual({
- kind: 'command',
- commandId: SetStyleCommand.id,
- params: {
- style: {
- type: 'bl',
- value: true,
- },
- },
- permission: 'cellStyle',
- selectionRequirement: 'none',
- });
-
- service.setCellContentAction({ v: 'hello', t: 1 } as any);
-
- expect(service.getAction()).toEqual({
- kind: 'set-range-values',
- value: { v: 'hello', t: 1 },
- permission: 'cellValue',
- selectionRequirement: 'none',
- });
- });
-});
diff --git a/packages/sheets-ui/src/services/repeat-last-action.service.ts b/packages/sheets-ui/src/services/repeat-last-action.service.ts
index b7fc205d7f..b7e2d2d48a 100644
--- a/packages/sheets-ui/src/services/repeat-last-action.service.ts
+++ b/packages/sheets-ui/src/services/repeat-last-action.service.ts
@@ -14,287 +14,282 @@
* limitations under the License.
*/
-import type { ICellData, ICommandInfo, IExecutionOptions } from '@univerjs/core';
-import type { IBorderInfo, ISetBorderBasicCommandParams, ISetColWidthCommandParams, ISetStyleCommandParams } from '@univerjs/sheets';
-import { createIdentifier, Disposable, ICommandService, Tools } from '@univerjs/core';
+import type { ICommandInfo, IDisposable, IRange } from '@univerjs/core';
+import type {
+ IAddMergeCommandParams,
+ IClearSelectionAllCommandParams,
+ IClearSelectionContentCommandParams,
+ IClearSelectionFormatCommandParams,
+ IDeleteRangeMoveLeftCommandParams,
+ IDeleteRangeMoveUpCommandParams,
+ IInsertRangeMoveDownCommandParams,
+ IInsertRangeMoveRightCommandParams,
+ IRemoveWorksheetMergeCommandParams,
+ ISetBorderCommandParams,
+ ISetColWidthCommandParams,
+ ISetRowHeightCommandParams,
+ ISetStyleCommandParams,
+} from '@univerjs/sheets';
+import { createIdentifier, Disposable, ICommandService, toDisposable } from '@univerjs/core';
import {
- AddWorksheetMergeAllCommand,
- AddWorksheetMergeHorizontalCommand,
- AddWorksheetMergeVerticalCommand,
+ AddWorksheetMergeCommand,
+ ClearSelectionAllCommand,
ClearSelectionContentCommand,
ClearSelectionFormatCommand,
- InsertColAfterCommand,
- InsertColBeforeCommand,
- InsertRowAfterCommand,
- InsertRowBeforeCommand,
+ DeleteRangeMoveLeftCommand,
+ DeleteRangeMoveUpCommand,
+ InsertColCommand,
+ InsertRangeMoveDownCommand,
+ InsertRangeMoveRightCommand,
+ InsertRowCommand,
RemoveColCommand,
RemoveRowCommand,
RemoveWorksheetMergeCommand,
- SetBackgroundColorCommand,
- SetBorderBasicCommand,
+ SetBorderCommand,
SetColWidthCommand,
SetRowHeightCommand,
SetStyleCommand,
- SetTextColorCommand,
- SetWorksheetRowIsAutoHeightCommand,
} from '@univerjs/sheets';
-import { SetWorksheetColAutoWidthCommand } from '../commands/commands/set-worksheet-auto-col-width.command';
-
-const SET_NUMFMT_COMMAND_ID = 'sheet.command.numfmt.set.numfmt';
-const REPEAT_LAST_ACTION_COMMAND_ID = 'sheet.command.repeat-last-action';
-
-export type RepeatLastActionPermission = 'none' | 'cellStyle' | 'cellValue';
-export type RepeatLastActionSelectionRequirement = 'none' | 'fullRows' | 'fullColumns';
-
-export interface IRepeatLastActionCommand {
- kind: 'command';
- commandId: string;
- params?: Record<string, unknown>;
- permission: RepeatLastActionPermission;
- selectionRequirement: RepeatLastActionSelectionRequirement;
-}
-
-export interface IRepeatLastActionSetBorder {
- kind: 'set-border-basic';
- value: IBorderInfo;
- permission: 'cellStyle';
- selectionRequirement: 'none';
-}
-export interface IRepeatLastActionSetNumfmt {
- kind: 'set-numfmt';
- pattern?: string;
- type?: string;
- permission: 'cellStyle';
- selectionRequirement: 'none';
-}
+export type RepeatableCommandHandler<T = any> = (selections: IRange[], params?: T) => T | undefined;
-export interface IRepeatLastActionSetRangeValues {
- kind: 'set-range-values';
- value: ICellData;
- permission: 'cellValue';
- selectionRequirement: 'none';
+export enum RepeatLastActionPermission {
+ None = 'none',
+ Editable = 'editable',
+ CellStyle = 'cellStyle',
+ CellValue = 'cellValue',
+ RowStyle = 'rowStyle',
+ ColumnStyle = 'columnStyle',
}
-export type IRepeatLastAction =
- | IRepeatLastActionCommand
- | IRepeatLastActionSetBorder
- | IRepeatLastActionSetNumfmt
- | IRepeatLastActionSetRangeValues;
+type RepeatableCommandRangesParams =
+ | ISetBorderCommandParams
+ | ISetRowHeightCommandParams
+ | ISetColWidthCommandParams
+ | IClearSelectionContentCommandParams
+ | IClearSelectionFormatCommandParams
+ | IClearSelectionAllCommandParams
+ | IRemoveWorksheetMergeCommandParams;
+
+export const SHEETS_BASIC_REPEATABLE_COMMANDS = [
+ SetStyleCommand.id,
+ SetBorderCommand.id,
+ AddWorksheetMergeCommand.id,
+ RemoveWorksheetMergeCommand.id,
+ InsertRowCommand.id,
+ InsertColCommand.id,
+ RemoveRowCommand.id,
+ RemoveColCommand.id,
+ SetRowHeightCommand.id,
+ SetColWidthCommand.id,
+ ClearSelectionContentCommand.id,
+ ClearSelectionFormatCommand.id,
+ ClearSelectionAllCommand.id,
+];
export interface IRepeatLastActionService {
- getAction(): IRepeatLastAction | null;
- setAction(action: IRepeatLastAction | null): void;
- setCellContentAction(value: ICellData): void;
- runWithoutRecording<T>(callback: () => Promise<T>): Promise<T>;
+ setAction(commandInfo: ICommandInfo | null): void;
+ getAction(): ICommandInfo | null;
+ getRepeatableCommands(): Set<string>;
+ getActionPermission(): RepeatLastActionPermission | RepeatLastActionPermission[];
+ registerRepeatableCommand(commandId: string, handler: RepeatableCommandHandler, permissionType?: RepeatLastActionPermission): IDisposable;
+ runWithoutRecording(selections: IRange[]): Promise<boolean>;
}
export const IRepeatLastActionService = createIdentifier<IRepeatLastActionService>('sheet-ui.repeat-last-action.service');
export class RepeatLastActionService extends Disposable implements IRepeatLastActionService {
- private _action: IRepeatLastAction | null = null;
+ private _action: ICommandInfo | null = null;
private _recordingDepth = 0;
+ private _repeatableCommands = new Set<string>(SHEETS_BASIC_REPEATABLE_COMMANDS);
+ private _customCommandHandlers = new Map<string, RepeatableCommandHandler>();
+ private _permissionCheckMap = new Map<RepeatLastActionPermission, Set<string>>([
+ [
+ RepeatLastActionPermission.Editable,
+ new Set<string>([
+ InsertRowCommand.id,
+ InsertColCommand.id,
+ RemoveRowCommand.id,
+ RemoveColCommand.id,
+ ]),
+ ],
+ [
+ RepeatLastActionPermission.CellStyle,
+ new Set<string>([
+ SetStyleCommand.id,
+ SetBorderCommand.id,
+ ClearSelectionFormatCommand.id,
+ ClearSelectionAllCommand.id,
+ ]),
+ ],
+ [
+ RepeatLastActionPermission.CellValue,
+ new Set<string>([
+ ClearSelectionContentCommand.id,
+ ClearSelectionAllCommand.id,
+ ]),
+ ],
+ [
+ RepeatLastActionPermission.RowStyle,
+ new Set<string>([
+ SetRowHeightCommand.id,
+ ]),
+ ],
+ [
+ RepeatLastActionPermission.ColumnStyle,
+ new Set<string>([
+ SetColWidthCommand.id,
+ ]),
+ ],
+ ]);
constructor(
@ICommandService private readonly _commandService: ICommandService
) {
super();
-
- this._initCommandRecording();
}
- getAction(): IRepeatLastAction | null {
- return this._action ? Tools.deepClone(this._action) : null;
+ override dispose(): void {
+ super.dispose();
+
+ this._action = null;
+ this._repeatableCommands.clear();
+ this._customCommandHandlers.clear();
+ this._permissionCheckMap.clear();
}
- setAction(action: IRepeatLastAction | null): void {
- this._action = action ? Tools.deepClone(action) : null;
+ setAction(commandInfo: ICommandInfo | null): void {
+ if (this._recordingDepth > 0) {
+ return;
+ }
+
+ this._action = commandInfo;
}
- setCellContentAction(value: ICellData): void {
- this.setAction({
- kind: 'set-range-values',
- value: Tools.deepClone(value),
- permission: 'cellValue',
- selectionRequirement: 'none',
- });
+ getAction(): ICommandInfo | null {
+ return this._action;
}
- async runWithoutRecording<T>(callback: () => Promise<T>): Promise<T> {
- this._recordingDepth += 1;
+ getRepeatableCommands(): Set<string> {
+ return this._repeatableCommands;
+ }
- try {
- return await callback();
- } finally {
- this._recordingDepth -= 1;
+ getActionPermission(): RepeatLastActionPermission | RepeatLastActionPermission[] {
+ if (!this._action) {
+ return RepeatLastActionPermission.None;
}
- }
- private _initCommandRecording(): void {
- this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo, options) => {
- if (this._recordingDepth > 0 || options?.fromCollab || options?.fromChangeset) {
- return;
- }
+ const permissions: RepeatLastActionPermission[] = [];
- const nextAction = this._normalizeAction(commandInfo, options);
- if (nextAction) {
- this._action = nextAction;
+ for (const [permission, commandSet] of this._permissionCheckMap.entries()) {
+ if (commandSet.has(this._action.id)) {
+ permissions.push(permission);
}
- }));
- }
-
- private _normalizeAction(commandInfo: Readonly<ICommandInfo>, _options?: IExecutionOptions): IRepeatLastAction | null {
- switch (commandInfo.id) {
- case SetStyleCommand.id:
- return {
- kind: 'command',
- commandId: SetStyleCommand.id,
- params: this._normalizeSetStyleParams(commandInfo.params as ISetStyleCommandParams<unknown> | undefined),
- permission: 'cellStyle',
- selectionRequirement: 'none',
- };
- case SetTextColorCommand.id:
- case SetBackgroundColorCommand.id:
- return {
- kind: 'command',
- commandId: commandInfo.id,
- params: Tools.deepClone(commandInfo.params as Record<string, unknown> | undefined),
- permission: 'cellStyle',
- selectionRequirement: 'none',
- };
- case InsertRowBeforeCommand.id:
- case InsertRowAfterCommand.id:
- case InsertColBeforeCommand.id:
- case InsertColAfterCommand.id:
- return {
- kind: 'command',
- commandId: commandInfo.id,
- params: Tools.deepClone(commandInfo.params as Record<string, unknown> | undefined),
- permission: 'none',
- selectionRequirement: 'none',
- };
- case RemoveRowCommand.id:
- return {
- kind: 'command',
- commandId: RemoveRowCommand.id,
- permission: 'none',
- selectionRequirement: 'fullRows',
- };
- case RemoveColCommand.id:
- return {
- kind: 'command',
- commandId: RemoveColCommand.id,
- permission: 'none',
- selectionRequirement: 'fullColumns',
- };
- case SetRowHeightCommand.id:
- return {
- kind: 'command',
- commandId: SetRowHeightCommand.id,
- params: this._normalizeSetRowHeightParams(commandInfo.params as { value: number } | undefined),
- permission: 'none',
- selectionRequirement: 'none',
- };
- case SetColWidthCommand.id:
- return {
- kind: 'command',
- commandId: SetColWidthCommand.id,
- params: this._normalizeSetColWidthParams(commandInfo.params as ISetColWidthCommandParams | undefined),
- permission: 'none',
- selectionRequirement: 'none',
- };
- case SetWorksheetRowIsAutoHeightCommand.id:
- case SetWorksheetColAutoWidthCommand.id:
- return {
- kind: 'command',
- commandId: commandInfo.id,
- permission: 'none',
- selectionRequirement: 'none',
- };
- case ClearSelectionContentCommand.id:
- case ClearSelectionFormatCommand.id:
- case AddWorksheetMergeAllCommand.id:
- case AddWorksheetMergeVerticalCommand.id:
- case AddWorksheetMergeHorizontalCommand.id:
- case RemoveWorksheetMergeCommand.id:
- return {
- kind: 'command',
- commandId: commandInfo.id,
- permission: 'none',
- selectionRequirement: 'none',
- };
- case SetBorderBasicCommand.id:
- return this._normalizeSetBorderAction(commandInfo.params as ISetBorderBasicCommandParams | undefined);
- case SET_NUMFMT_COMMAND_ID:
- return this._normalizeSetNumfmtAction(commandInfo.params as { values?: Array<{ pattern?: string; type?: string }> } | undefined);
- case REPEAT_LAST_ACTION_COMMAND_ID:
- return null;
- default:
- return null;
}
- }
- private _normalizeSetStyleParams(params: ISetStyleCommandParams<unknown> | undefined): Record<string, unknown> | undefined {
- if (!params) {
- return undefined;
+ if (permissions.length === 0) {
+ return RepeatLastActionPermission.None;
}
- return {
- style: Tools.deepClone(params.style),
- };
+ return permissions.length === 1 ? permissions[0] : permissions;
}
- private _normalizeSetRowHeightParams(params: { value: number } | undefined): Record<string, unknown> | undefined {
- if (!params) {
- return undefined;
+ registerRepeatableCommand(commandId: string, handler: RepeatableCommandHandler, permissionType: RepeatLastActionPermission = RepeatLastActionPermission.None): IDisposable {
+ this._repeatableCommands.add(commandId);
+ this._customCommandHandlers.set(commandId, handler);
+
+ if (!this._permissionCheckMap.has(permissionType)) {
+ this._permissionCheckMap.set(permissionType, new Set<string>());
}
+ this._permissionCheckMap.get(permissionType)?.add(commandId);
- return {
- value: params.value,
- };
+ return toDisposable(() => {
+ this._repeatableCommands.delete(commandId);
+ this._customCommandHandlers.delete(commandId);
+ this._permissionCheckMap.get(permissionType)?.delete(commandId);
+ });
}
- private _normalizeSetColWidthParams(params: ISetColWidthCommandParams | undefined): Record<string, unknown> | undefined {
- if (!params) {
- return undefined;
+ // eslint-disable-next-line max-lines-per-function
+ async runWithoutRecording(selections: IRange[]): Promise<boolean> {
+ if (!this._action) {
+ return false;
}
- return {
- value: params.value,
- };
- }
+ this._recordingDepth += 1;
- private _normalizeSetBorderAction(params: ISetBorderBasicCommandParams | undefined): IRepeatLastActionSetBorder | null {
- if (!params) {
- return null;
- }
+ try {
+ const { id, params } = this._action as ICommandInfo;
- return {
- kind: 'set-border-basic',
- value: Tools.deepClone(params.value),
- permission: 'cellStyle',
- selectionRequirement: 'none',
- };
- }
+ if (id === SetStyleCommand.id) {
+ const styleParams: ISetStyleCommandParams<unknown> = {
+ ...(params as ISetStyleCommandParams<unknown>),
+ range: selections[selections.length - 1],
+ };
+ return await this._commandService.executeCommand(id, styleParams);
+ }
- private _normalizeSetNumfmtAction(params: { values?: Array<{ pattern?: string; type?: string }> } | undefined): IRepeatLastActionSetNumfmt | null {
- const values = params?.values;
- if (!values?.length) {
- return null;
- }
+ if (id === AddWorksheetMergeCommand.id) {
+ const mergeParams: IAddMergeCommandParams = {
+ ...(params as IAddMergeCommandParams),
+ selections,
+ };
+ return await this._commandService.executeCommand(id, mergeParams);
+ }
- const [firstValue] = values;
- const isUniform = values.every((value) => value.pattern === firstValue.pattern && value.type === firstValue.type);
- if (!isUniform) {
- return null;
- }
+ if (id === InsertRowCommand.id) {
+ const insertRangeMoveDownParams: IInsertRangeMoveDownCommandParams = {
+ range: selections[selections.length - 1],
+ };
+ return await this._commandService.executeCommand(InsertRangeMoveDownCommand.id, insertRangeMoveDownParams);
+ }
+
+ if (id === InsertColCommand.id) {
+ const insertRangeMoveRightParams: IInsertRangeMoveRightCommandParams = {
+ range: selections[selections.length - 1],
+ };
+ return await this._commandService.executeCommand(InsertRangeMoveRightCommand.id, insertRangeMoveRightParams);
+ }
+
+ if (id === RemoveRowCommand.id) {
+ const deleteRangeMoveUpParams: IDeleteRangeMoveUpCommandParams = {
+ range: selections[selections.length - 1],
+ };
+ return await this._commandService.executeCommand(DeleteRangeMoveUpCommand.id, deleteRangeMoveUpParams);
+ }
+
+ if (id === RemoveColCommand.id) {
+ const deleteRangeMoveLeftParams: IDeleteRangeMoveLeftCommandParams = {
+ range: selections[selections.length - 1],
+ };
+ return await this._commandService.executeCommand(DeleteRangeMoveLeftCommand.id, deleteRangeMoveLeftParams);
+ }
- return {
- kind: 'set-numfmt',
- pattern: firstValue.pattern,
- type: firstValue.type,
- permission: 'cellStyle',
- selectionRequirement: 'none',
- };
+ if (
+ id === SetBorderCommand.id ||
+ id === SetRowHeightCommand.id ||
+ id === SetColWidthCommand.id ||
+ id === ClearSelectionContentCommand.id ||
+ id === ClearSelectionFormatCommand.id ||
+ id === ClearSelectionAllCommand.id ||
+ id === RemoveWorksheetMergeCommand.id
+ ) {
+ const newRangesParams: RepeatableCommandRangesParams = {
+ ...(params as RepeatableCommandRangesParams),
+ ranges: selections,
+ };
+ return await this._commandService.executeCommand(id, newRangesParams);
+ }
+
+ if (this._customCommandHandlers.has(id)) {
+ const handler = this._customCommandHandlers.get(id) as RepeatableCommandHandler;
+ const customParams = handler(selections, params);
+ return await this._commandService.executeCommand(id, customParams);
+ }
+
+ return await this._commandService.executeCommand(id, params);
+ } finally {
+ this._recordingDepth -= 1;
+ }
}
}
diff --git a/packages/sheets/src/commands/commands/clear-selection-all.command.ts b/packages/sheets/src/commands/commands/clear-selection-all.command.ts
index 910efc7395..df84566b3e 100644
--- a/packages/sheets/src/commands/commands/clear-selection-all.command.ts
+++ b/packages/sheets/src/commands/commands/clear-selection-all.command.ts
@@ -30,7 +30,7 @@ import { SheetsSelectionsService } from '../../services/selections/selection.ser
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../mutations/set-range-values.mutation';
-interface IClearSelectionAllCommandParams {
+export interface IClearSelectionAllCommandParams {
unitId?: string;
subUnitId?: string;
ranges?: IRange[];
diff --git a/packages/sheets/src/commands/commands/clear-selection-format.command.ts b/packages/sheets/src/commands/commands/clear-selection-format.command.ts
index 2220d019dd..d8e102828f 100644
--- a/packages/sheets/src/commands/commands/clear-selection-format.command.ts
+++ b/packages/sheets/src/commands/commands/clear-selection-format.command.ts
@@ -30,7 +30,7 @@ import { SheetsSelectionsService } from '../../services/selections/selection.ser
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../mutations/set-range-values.mutation';
-interface IClearSelectionFormatCommandParams {
+export interface IClearSelectionFormatCommandParams {
unitId?: string;
subUnitId?: string;
ranges?: IRange[];
diff --git a/packages/sheets/src/commands/commands/remove-worksheet-merge.command.ts b/packages/sheets/src/commands/commands/remove-worksheet-merge.command.ts
index 13782b5773..b8165c7f85 100644
--- a/packages/sheets/src/commands/commands/remove-worksheet-merge.command.ts
+++ b/packages/sheets/src/commands/commands/remove-worksheet-merge.command.ts
@@ -27,7 +27,7 @@ import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../mu
import { SetSelectionsOperation } from '../operations/selection.operation';
import { getSheetCommandTarget } from './utils/target-util';
-interface IRemoveWorksheetMergeCommandParams extends ISheetCommandSharedParams {
+export interface IRemoveWorksheetMergeCommandParams extends ISheetCommandSharedParams {
ranges?: IRange[];
}
diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.ts
index cc40d360bf..34fb8922a2 100644
--- a/packages/sheets/src/index.ts
+++ b/packages/sheets/src/index.ts
@@ -65,15 +65,16 @@ export {
AddWorksheetMergeVerticalCommand,
getClearContentMutationParamForRange,
getClearContentMutationParamsForRanges,
+ type IAddMergeCommandParams,
type IMergeCellsUtilOptions,
} from './commands/commands/add-worksheet-merge.command';
export { AddWorksheetProtectionCommand } from './commands/commands/add-worksheet-protection.command';
export { SetWorksheetRangeThemeStyleCommand } from './commands/commands/add-worksheet-range-theme.command';
export { AppendRowCommand, type IAppendRowCommandParams } from './commands/commands/append-row.command';
export { AutoClearContentCommand, AutoFillCommand, type IAutoClearContentCommand, type IAutoFillCommandParams, SheetCopyDownCommand, SheetCopyRightCommand } from './commands/commands/auto-fill.command';
-export { ClearSelectionAllCommand } from './commands/commands/clear-selection-all.command';
+export { ClearSelectionAllCommand, type IClearSelectionAllCommandParams } from './commands/commands/clear-selection-all.command';
export { ClearSelectionContentCommand, type IClearSelectionContentCommandParams } from './commands/commands/clear-selection-content.command';
-export { ClearSelectionFormatCommand } from './commands/commands/clear-selection-format.command';
+export { ClearSelectionFormatCommand, type IClearSelectionFormatCommandParams } from './commands/commands/clear-selection-format.command';
export { CopySheetCommand } from './commands/commands/copy-worksheet.command';
export type { ICopySheetCommandParams } from './commands/commands/copy-worksheet.command';
export { DeleteRangeMoveLeftCommand, type IDeleteRangeMoveLeftCommandParams } from './commands/commands/delete-range-move-left.command';
@@ -114,7 +115,7 @@ export type { IRegisterWorksheetRangeThemeStyleCommandParams } from './commands/
export { RemoveDefinedNameCommand } from './commands/commands/remove-defined-name.command';
export { type IRemoveColByRangeCommandParams, type IRemoveRowByRangeCommandParams, type IRemoveRowColCommandInterceptParams, type IRemoveRowColCommandParams, RemoveColByRangeCommand, RemoveColCommand, RemoveRowByRangeCommand, RemoveRowCommand } from './commands/commands/remove-row-col.command';
export { type IRemoveSheetCommandParams, RemoveSheetCommand } from './commands/commands/remove-sheet.command';
-export { RemoveWorksheetMergeCommand } from './commands/commands/remove-worksheet-merge.command';
+export { type IRemoveWorksheetMergeCommandParams, RemoveWorksheetMergeCommand } from './commands/commands/remove-worksheet-merge.command';
export { type IReorderRangeCommandParams, ReorderRangeCommand } from './commands/commands/reorder-range.command';
export {
type ISetBorderBasicCommandParams,
@@ -192,7 +193,7 @@ export { SetWorksheetPermissionPointsCommand } from './commands/commands/set-wor
export { SetWorksheetProtectionCommand } from './commands/commands/set-worksheet-protection.command';
export { SetWorksheetRightToLeftCommand } from './commands/commands/set-worksheet-right-to-left.command';
export { SetWorksheetRowCountCommand } from './commands/commands/set-worksheet-row-count.command';
-export { DeltaRowHeightCommand, SetRowHeightCommand, SetWorksheetRowIsAutoHeightCommand } from './commands/commands/set-worksheet-row-height.command';
+export { DeltaRowHeightCommand, type ISetRowHeightCommandParams, SetRowHeightCommand, SetWorksheetRowIsAutoHeightCommand } from './commands/commands/set-worksheet-row-height.command';
export type { IDeltaRowHeightCommand, ISetWorksheetRowIsAutoHeightCommandParams } from './commands/commands/set-worksheet-row-height.command';
export { SetWorksheetShowCommand } from './commands/commands/set-worksheet-show.command';
export type { ISetWorksheetShowCommandParams } from './commands/commands/set-worksheet-show.command';