Skip to content

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

feat(sheets): add excel-style f4 parity (#6702)

alex waddington89e5ded4e11e
diff --git a/packages/sheets-formula-ui/src/commands/operations/reference-absolute.operation.ts b/packages/sheets-formula-ui/src/commands/operations/reference-absolute.operation.ts
index 8712357b85..690c4029b4 100644
--- a/packages/sheets-formula-ui/src/commands/operations/reference-absolute.operation.ts
+++ b/packages/sheets-formula-ui/src/commands/operations/reference-absolute.operation.ts
@@ -15,10 +15,48 @@
*/
import type { IAccessor, ICommand } from '@univerjs/core';
-import { CommandType } from '@univerjs/core';
+import { BuildTextUtils, CommandType, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY } from '@univerjs/core';
+import { DocSelectionManagerService } from '@univerjs/docs';
+import { IEditorService } from '@univerjs/docs-ui';
+import { LexerTreeBuilder } from '@univerjs/engine-formula';
+import { toggleReferenceAbsoluteAtCursor } from '../utils/reference-absolute';
export const ReferenceAbsoluteOperation: ICommand = {
id: 'formula-ui.operation.change-ref-to-absolute',
type: CommandType.OPERATION,
- handler: async (accessor: IAccessor) => true,
+ handler: async (accessor: IAccessor) => {
+ const editorService = accessor.get(IEditorService);
+ const docSelectionManagerService = accessor.get(DocSelectionManagerService);
+ const lexerTreeBuilder = accessor.get(LexerTreeBuilder);
+ const focusEditor = editorService.getFocusEditor();
+
+ if (!focusEditor) {
+ return false;
+ }
+
+ const editorId = focusEditor.getEditorId();
+ if (editorId !== DOCS_NORMAL_EDITOR_UNIT_ID_KEY && editorId !== DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {
+ return false;
+ }
+
+ const activeTextRange = docSelectionManagerService.getActiveTextRange();
+ if (!activeTextRange) {
+ return false;
+ }
+
+ const formulaText = BuildTextUtils.transform.getPlainText(focusEditor.getDocumentData().body?.dataStream ?? '');
+ const nextReferenceState = toggleReferenceAbsoluteAtCursor(lexerTreeBuilder, formulaText, activeTextRange.endOffset);
+
+ if (!nextReferenceState) {
+ return false;
+ }
+
+ focusEditor.replaceText(nextReferenceState.formulaText, [{
+ startOffset: nextReferenceState.cursorOffset,
+ endOffset: nextReferenceState.cursorOffset,
+ collapsed: true,
+ }]);
+
+ return 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
new file mode 100644
index 0000000000..7c70adba47
--- /dev/null
+++ b/packages/sheets-formula-ui/src/commands/utils/__tests__/reference-absolute.spec.ts
@@ -0,0 +1,99 @@
+/**
+ * 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 { LexerTreeBuilder } from '@univerjs/engine-formula';
+import { describe, expect, it } from 'vitest';
+import { toggleReferenceAbsoluteAtCursor } from '../reference-absolute';
+
+describe('toggleReferenceAbsoluteAtCursor', () => {
+ const lexerTreeBuilder = new LexerTreeBuilder();
+
+ it('cycles a single reference through all Excel absolute states', () => {
+ let formulaText = '=A1';
+ let cursorOffset = formulaText.length;
+
+ const expectedCycle = ['=$A$1', '=A$1', '=$A1', '=A1'];
+
+ for (const expectedFormulaText of expectedCycle) {
+ const nextState = toggleReferenceAbsoluteAtCursor(lexerTreeBuilder, formulaText, cursorOffset);
+
+ expect(nextState).not.toBeNull();
+ expect(nextState!.formulaText).toBe(expectedFormulaText);
+
+ formulaText = nextState!.formulaText;
+ cursorOffset = nextState!.cursorOffset;
+ }
+ });
+
+ it('cycles the cell part of a cross-sheet reference', () => {
+ const nextState = toggleReferenceAbsoluteAtCursor(lexerTreeBuilder, '=Sheet2!B5', '=Sheet2!B'.length);
+
+ expect(nextState).toEqual({
+ formulaText: '=Sheet2!$B$5',
+ cursorOffset: '=Sheet2!B'.length,
+ });
+ });
+
+ it('cycles only the referenced side of a range based on cursor position', () => {
+ const startSide = toggleReferenceAbsoluteAtCursor(lexerTreeBuilder, '=A1:B2', '=A'.length);
+ const endSide = toggleReferenceAbsoluteAtCursor(lexerTreeBuilder, '=A1:B2', '=A1:'.length + 1);
+
+ expect(startSide?.formulaText).toBe('=$A$1:B2');
+ expect(endSide?.formulaText).toBe('=A1:$B$2');
+ });
+
+ it('cycles both sides when the caret is adjacent to the range separator', () => {
+ const beforeColon = toggleReferenceAbsoluteAtCursor(lexerTreeBuilder, '=A1:B2', '=A1'.length);
+ const afterColon = toggleReferenceAbsoluteAtCursor(lexerTreeBuilder, '=A1:B2', '=A1:'.length);
+
+ expect(beforeColon?.formulaText).toBe('=$A$1:$B$2');
+ expect(afterColon?.formulaText).toBe('=$A$1:$B$2');
+ expect(beforeColon?.cursorOffset).toBe('=$A$1'.length);
+ expect(afterColon?.cursorOffset).toBe('=$A$1:'.length);
+ });
+
+ it('keeps cycling both sides on repeated F4 presses at the range separator', () => {
+ let formulaText = '=A1:B2';
+ let cursorOffset = '=A1'.length;
+
+ const expectedCycle = ['=$A$1:$B$2', '=A$1:B$2', '=$A1:$B2', '=A1:B2'];
+
+ for (const expectedFormulaText of expectedCycle) {
+ const nextState = toggleReferenceAbsoluteAtCursor(lexerTreeBuilder, formulaText, cursorOffset);
+
+ expect(nextState?.formulaText).toBe(expectedFormulaText);
+
+ formulaText = nextState!.formulaText;
+ cursorOffset = nextState!.cursorOffset;
+ }
+ });
+
+ 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);
+
+ expect(startBoundary?.formulaText).toBe('=$A$1+SUM(B2)');
+ expect(endBoundary?.formulaText).toBe('=SUM(1)+$B$2');
+ });
+
+ it('returns null when the cursor is not on a cell reference', () => {
+ expect(toggleReferenceAbsoluteAtCursor(lexerTreeBuilder, '=SUM(1, 2)', '=SUM('.length)).toBeNull();
+ expect(toggleReferenceAbsoluteAtCursor(lexerTreeBuilder, '="A1"', '="'.length + 1)).toBeNull();
+ expect(toggleReferenceAbsoluteAtCursor(lexerTreeBuilder, '=namedRange', '=named'.length)).toBeNull();
+ expect(toggleReferenceAbsoluteAtCursor(lexerTreeBuilder, '', 0)).toBeNull();
+ expect(toggleReferenceAbsoluteAtCursor(lexerTreeBuilder, '=1', 1)).toBeNull();
+ });
+});
diff --git a/packages/sheets-formula-ui/src/commands/utils/reference-absolute.ts b/packages/sheets-formula-ui/src/commands/utils/reference-absolute.ts
new file mode 100644
index 0000000000..548774dfa0
--- /dev/null
+++ b/packages/sheets-formula-ui/src/commands/utils/reference-absolute.ts
@@ -0,0 +1,224 @@
+/**
+ * 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 { ISequenceNode } from '@univerjs/engine-formula';
+import { AbsoluteRefType } from '@univerjs/core';
+import {
+ deserializeRangeWithSheetWithCache,
+ generateStringWithSequence,
+ getAbsoluteRefTypeWithSingleString,
+ handleRefStringInfo,
+ sequenceNodeType,
+ serializeRangeToRefString,
+} from '@univerjs/engine-formula';
+
+const CELL_REFERENCE_REGEX = /^\$?[A-Za-z]+\$?\d+$/;
+
+export interface IReferenceAbsoluteResult {
+ formulaText: string;
+ cursorOffset: number;
+}
+
+interface ILexerTreeBuilderLike {
+ sequenceNodesBuilder(formulaString: string): Array<string | ISequenceNode> | undefined;
+}
+
+interface IToggleReferenceTokenResult {
+ token: string;
+ referenceTarget: 'start' | 'end' | 'both';
+ previousSeparatorOffset: number | null;
+ nextSeparatorOffset: number | null;
+}
+
+export function toggleReferenceAbsoluteAtCursor(
+ lexerTreeBuilder: ILexerTreeBuilderLike,
+ formulaText: string,
+ cursorOffset: number
+): IReferenceAbsoluteResult | null {
+ if (!formulaText.startsWith('=') || formulaText.length <= 1) {
+ return null;
+ }
+
+ const sequenceNodes = lexerTreeBuilder.sequenceNodesBuilder(formulaText);
+ if (!sequenceNodes?.length) {
+ return null;
+ }
+
+ const normalizedCursorOffset = Math.min(Math.max(cursorOffset, 0), formulaText.length);
+ const relativeCursorOffset = normalizedCursorOffset - 1;
+ if (relativeCursorOffset < 0) {
+ return null;
+ }
+
+ const matchedReference = sequenceNodes.find((node) => {
+ if (typeof node === 'string' || node.nodeType !== sequenceNodeType.REFERENCE) {
+ return false;
+ }
+
+ return relativeCursorOffset >= node.startIndex && relativeCursorOffset <= node.endIndex + 1;
+ });
+
+ if (!matchedReference || typeof matchedReference === 'string') {
+ return null;
+ }
+
+ const nextReferenceState = _toggleReferenceToken(matchedReference, relativeCursorOffset - matchedReference.startIndex);
+ if (nextReferenceState == null || nextReferenceState.token === matchedReference.token) {
+ return null;
+ }
+
+ const nextSequenceNodes = sequenceNodes.map((node) => {
+ if (node !== matchedReference) {
+ return node;
+ }
+
+ return {
+ ...node,
+ token: nextReferenceState.token,
+ endIndex: node.startIndex + nextReferenceState.token.length - 1,
+ };
+ });
+
+ const nextFormulaText = `=${generateStringWithSequence(nextSequenceNodes)}`;
+ const nextCursorOffset = _translateCursorOffset(
+ normalizedCursorOffset,
+ matchedReference.startIndex + 1,
+ matchedReference.endIndex + 2,
+ nextReferenceState.token.length,
+ nextReferenceState
+ );
+
+ return {
+ formulaText: nextFormulaText,
+ cursorOffset: nextCursorOffset,
+ };
+}
+
+function _toggleReferenceToken(referenceNode: ISequenceNode, offsetInToken: number): IToggleReferenceTokenResult | null {
+ const sequenceGrid = deserializeRangeWithSheetWithCache(referenceNode.token);
+ if (sequenceGrid == null) {
+ return null;
+ }
+
+ const { refBody } = handleRefStringInfo(referenceNode.token);
+ const referenceParts = refBody.split(':');
+ const previousSeparatorOffset = referenceParts.length === 2 ? referenceNode.token.indexOf(':') : null;
+
+ if (referenceParts.some((part) => !CELL_REFERENCE_REGEX.test(part))) {
+ return null;
+ }
+
+ const isRangeReference = referenceParts.length === 2;
+ const referenceTarget = !isRangeReference
+ ? 'start'
+ : _getRangeReferenceTarget(referenceNode.token, refBody, offsetInToken);
+
+ const nextRange = {
+ ...sequenceGrid.range,
+ };
+
+ if (referenceTarget === 'start' || referenceTarget === 'both') {
+ const nextAbsoluteRefType = _getNextAbsoluteRefType(getAbsoluteRefTypeWithSingleString(referenceParts[0]));
+ nextRange.startAbsoluteRefType = nextAbsoluteRefType;
+ if (!isRangeReference) {
+ nextRange.endAbsoluteRefType = nextAbsoluteRefType;
+ }
+ }
+
+ if (referenceTarget === 'end' || referenceTarget === 'both') {
+ nextRange.endAbsoluteRefType = _getNextAbsoluteRefType(getAbsoluteRefTypeWithSingleString(referenceParts[1]));
+ }
+
+ const token = serializeRangeToRefString({
+ ...sequenceGrid,
+ range: nextRange,
+ });
+
+ return {
+ token,
+ referenceTarget,
+ previousSeparatorOffset,
+ nextSeparatorOffset: referenceParts.length === 2 ? token.indexOf(':') : null,
+ };
+}
+
+function _getRangeReferenceTarget(
+ token: string,
+ refBody: string,
+ offsetInToken: number
+): 'start' | 'end' | 'both' {
+ const prefixLength = token.length - refBody.length;
+ const separatorOffset = prefixLength + refBody.indexOf(':');
+
+ if (offsetInToken === separatorOffset || offsetInToken === separatorOffset + 1) {
+ return 'both';
+ }
+
+ return offsetInToken < separatorOffset ? 'start' : 'end';
+}
+
+function _getNextAbsoluteRefType(absoluteRefType: AbsoluteRefType): AbsoluteRefType {
+ switch (absoluteRefType) {
+ case AbsoluteRefType.NONE:
+ return AbsoluteRefType.ALL;
+ case AbsoluteRefType.ALL:
+ return AbsoluteRefType.ROW;
+ case AbsoluteRefType.ROW:
+ return AbsoluteRefType.COLUMN;
+ case AbsoluteRefType.COLUMN:
+ default:
+ return AbsoluteRefType.NONE;
+ }
+}
+
+function _translateCursorOffset(
+ cursorOffset: number,
+ replaceStartOffset: number,
+ replaceEndOffsetExclusive: number,
+ nextLength: number,
+ toggleResult: IToggleReferenceTokenResult
+): number {
+ if (
+ toggleResult.referenceTarget === 'both' &&
+ toggleResult.previousSeparatorOffset != null &&
+ toggleResult.nextSeparatorOffset != null
+ ) {
+ const previousColonOffset = replaceStartOffset + toggleResult.previousSeparatorOffset;
+ const nextColonOffset = replaceStartOffset + toggleResult.nextSeparatorOffset;
+
+ if (cursorOffset === previousColonOffset) {
+ return nextColonOffset;
+ }
+
+ if (cursorOffset === previousColonOffset + 1) {
+ return nextColonOffset + 1;
+ }
+ }
+
+ if (cursorOffset <= replaceStartOffset) {
+ return cursorOffset;
+ }
+
+ const previousLength = replaceEndOffsetExclusive - replaceStartOffset;
+ const lengthDiff = nextLength - previousLength;
+
+ if (cursorOffset >= replaceEndOffsetExclusive) {
+ return cursorOffset + lengthDiff;
+ }
+
+ const offsetInsideReference = cursorOffset - replaceStartOffset;
+ return replaceStartOffset + Math.min(offsetInsideReference, nextLength);
+}
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 fd332789dd..d0aac83540 100644
--- a/packages/sheets-formula-ui/src/controllers/shortcuts/prompt.shortcut.ts
+++ b/packages/sheets-formula-ui/src/controllers/shortcuts/prompt.shortcut.ts
@@ -14,7 +14,9 @@
* 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';
@@ -103,9 +105,17 @@ export function promptSelectionShortcutItemCtrlAndShift() {
export const ChangeRefToAbsoluteShortcut: IShortcutItem = {
id: ReferenceAbsoluteOperation.id,
binding: KeyCode.F4,
- preconditions: (contextService) => whenFormulaEditorActivated(contextService),
+ 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]) {
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 5e5b62c4b6..ebe18864db 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,14 +43,18 @@ import {
DeleteRangeProtectionMutation,
DeleteWorksheetProtectionCommand,
RangeProtectionRuleModel,
+ RemoveColCommand,
RemoveSheetCommand,
SetBoldCommand,
SetFontFamilyCommand,
SetFontSizeCommand,
SetItalicCommand,
+ SetRangeValuesCommand,
SetStrikeThroughCommand,
+ SetStyleCommand,
SetTextColorCommand,
SetUnderlineCommand,
+ SheetPermissionCheckController,
SheetsSelectionsService,
WorksheetProtectionRuleModel,
} from '@univerjs/sheets';
@@ -59,6 +63,7 @@ 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';
@@ -88,6 +93,7 @@ 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';
@@ -224,6 +230,160 @@ 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
new file mode 100644
index 0000000000..f82ccb2438
--- /dev/null
+++ b/packages/sheets-ui/src/commands/commands/repeat-last-action.command.ts
@@ -0,0 +1,165 @@
+/**
+ * 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 { IAccessor, ICommand, IRange } from '@univerjs/core';
+import type { RepeatLastActionPermission } from '../../services/repeat-last-action.service';
+import {
+ CommandType,
+ ICommandService,
+ IUniverInstanceService,
+ LocaleService,
+} from '@univerjs/core';
+import {
+ getSheetCommandTarget,
+ RangeProtectionPermissionEditPoint,
+ SetBorderBasicCommand,
+ SetRangeValuesCommand,
+ SheetPermissionCheckController,
+ SheetsSelectionsService,
+ WorkbookEditablePermission,
+ WorksheetEditPermission,
+ WorksheetSetCellStylePermission,
+ WorksheetSetCellValuePermission,
+} from '@univerjs/sheets';
+import { IRepeatLastActionService } from '../../services/repeat-last-action.service';
+
+const SET_NUMFMT_COMMAND_ID = 'sheet.command.numfmt.set.numfmt';
+
+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:
+ 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,
+ });
+ }
+ }
+ });
+
+ return values;
+}
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 51f18249a4..feaa5916e4 100644
--- a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
@@ -93,6 +93,7 @@ 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';
@@ -134,6 +135,7 @@ 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();
@@ -679,6 +681,8 @@ 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/sheet-ui.controller.ts b/packages/sheets-ui/src/controllers/sheet-ui.controller.ts
index c38c5af6a9..f04c0265d9 100644
--- a/packages/sheets-ui/src/controllers/sheet-ui.controller.ts
+++ b/packages/sheets-ui/src/controllers/sheet-ui.controller.ts
@@ -50,6 +50,7 @@ import { InsertRangeMoveRightConfirmCommand } from '../commands/commands/insert-
import { AddRangeProtectionFromContextMenuCommand, AddRangeProtectionFromSheetBarCommand, AddRangeProtectionFromToolbarCommand, DeleteRangeProtectionFromContextMenuCommand, SetRangeProtectionFromContextMenuCommand, ViewSheetPermissionFromContextMenuCommand, ViewSheetPermissionFromSheetBarCommand } from '../commands/commands/range-protection.command';
import { RemoveColConfirmCommand, RemoveRowConfirmCommand } from '../commands/commands/remove-row-col-confirm.command';
import { RemoveSheetConfirmCommand } from '../commands/commands/remove-sheet-confirm.command';
+import { RepeatLastActionCommand } from '../commands/commands/repeat-last-action.command';
import {
ApplyFormatPainterCommand,
SetInfiniteFormatPainterCommand,
@@ -108,6 +109,7 @@ import {
EditorDeleteLeftShortcutInActive,
EditorDeleteRightShortcut,
generateArrowSelectionShortCutItem,
+ RepeatLastActionShortcut,
ShiftEditorDeleteLeftShortcut,
StartEditWithF2Shortcut,
} from './shortcuts/editor.shortcut';
@@ -264,6 +266,7 @@ export class SheetUIController extends Disposable {
SetWorksheetColAutoWidthCommand,
SetRowHeaderWidthCommand,
SetColumnHeaderHeightCommand,
+ RepeatLastActionCommand,
].forEach((c) => {
this.disposeWithMe(this._commandService.registerCommand(c));
});
@@ -320,6 +323,7 @@ export class SheetUIController extends Disposable {
ShiftDeleteSelectionValueShortcutItem,
...generateArrowSelectionShortCutItem(),
EditorCursorEnterShortcut,
+ RepeatLastActionShortcut,
StartEditWithF2Shortcut,
EditorCursorTabShortcut,
EditorBreakLineShortcut,
diff --git a/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts b/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts
index 45a1d5f88b..f6a1e1fc63 100644
--- a/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts
+++ b/packages/sheets-ui/src/controllers/shortcuts/editor.shortcut.ts
@@ -86,6 +86,14 @@ export const StartEditWithF2Shortcut: IShortcutItem = {
},
};
+export const RepeatLastActionShortcut: IShortcutItem = {
+ id: 'sheet.command.repeat-last-action',
+ binding: KeyCode.F4,
+ description: 'shortcut.sheet.repeat-last-action',
+ group: '4_sheet-edit',
+ preconditions: whenSheetEditorFocused,
+};
+
export const EditorCursorEnterShortcut: IShortcutItem = {
id: SetCellEditVisibleOperation.id,
binding: KeyCode.ENTER,
diff --git a/packages/sheets-ui/src/plugin.ts b/packages/sheets-ui/src/plugin.ts
index 4a73047048..608bb22942 100644
--- a/packages/sheets-ui/src/plugin.ts
+++ b/packages/sheets-ui/src/plugin.ts
@@ -86,6 +86,7 @@ import { SheetPermissionPanelModel } from './services/permission/sheet-permissio
import { SheetPermissionRenderManagerService } from './services/permission/sheet-permission-render-manager.service';
import { SheetPermissionUserManagerService } from './services/permission/sheet-permission-user-list.service';
import { SheetPrintInterceptorService } from './services/print-interceptor.service';
+import { IRepeatLastActionService, RepeatLastActionService } from './services/repeat-last-action.service';
import { SheetScrollManagerService } from './services/scroll-manager.service';
import { SelectAllService } from './services/select-all/select-all.service';
import { ISheetSelectionRenderService } from './services/selection/base-selection-render.service';
@@ -153,6 +154,7 @@ export class UniverSheetsUIPlugin extends Plugin {
[IFormulaEditorManagerService, { useClass: FormulaEditorManagerService }],
[IRefSelectionsService, { useClass: RefSelectionsService }],
[SheetPrintInterceptorService],
+ [IRepeatLastActionService, { useClass: RepeatLastActionService }],
[IStatusBarService, { useClass: StatusBarService }],
[IMarkSelectionService, { useClass: MarkSelectionService }],
[HoverManagerService],
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
new file mode 100644
index 0000000000..1e2c2390fe
--- /dev/null
+++ b/packages/sheets-ui/src/services/__tests__/repeat-last-action.service.spec.ts
@@ -0,0 +1,93 @@
+/**
+ * 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
new file mode 100644
index 0000000000..b7fc205d7f
--- /dev/null
+++ b/packages/sheets-ui/src/services/repeat-last-action.service.ts
@@ -0,0 +1,300 @@
+/**
+ * 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 { ICellData, ICommandInfo, IExecutionOptions } from '@univerjs/core';
+import type { IBorderInfo, ISetBorderBasicCommandParams, ISetColWidthCommandParams, ISetStyleCommandParams } from '@univerjs/sheets';
+import { createIdentifier, Disposable, ICommandService, Tools } from '@univerjs/core';
+import {
+ AddWorksheetMergeAllCommand,
+ AddWorksheetMergeHorizontalCommand,
+ AddWorksheetMergeVerticalCommand,
+ ClearSelectionContentCommand,
+ ClearSelectionFormatCommand,
+ InsertColAfterCommand,
+ InsertColBeforeCommand,
+ InsertRowAfterCommand,
+ InsertRowBeforeCommand,
+ RemoveColCommand,
+ RemoveRowCommand,
+ RemoveWorksheetMergeCommand,
+ SetBackgroundColorCommand,
+ SetBorderBasicCommand,
+ 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 interface IRepeatLastActionSetRangeValues {
+ kind: 'set-range-values';
+ value: ICellData;
+ permission: 'cellValue';
+ selectionRequirement: 'none';
+}
+
+export type IRepeatLastAction =
+ | IRepeatLastActionCommand
+ | IRepeatLastActionSetBorder
+ | IRepeatLastActionSetNumfmt
+ | IRepeatLastActionSetRangeValues;
+
+export interface IRepeatLastActionService {
+ getAction(): IRepeatLastAction | null;
+ setAction(action: IRepeatLastAction | null): void;
+ setCellContentAction(value: ICellData): void;
+ runWithoutRecording<T>(callback: () => Promise<T>): Promise<T>;
+}
+
+export const IRepeatLastActionService = createIdentifier<IRepeatLastActionService>('sheet-ui.repeat-last-action.service');
+
+export class RepeatLastActionService extends Disposable implements IRepeatLastActionService {
+ private _action: IRepeatLastAction | null = null;
+ private _recordingDepth = 0;
+
+ constructor(
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ super();
+
+ this._initCommandRecording();
+ }
+
+ getAction(): IRepeatLastAction | null {
+ return this._action ? Tools.deepClone(this._action) : null;
+ }
+
+ setAction(action: IRepeatLastAction | null): void {
+ this._action = action ? Tools.deepClone(action) : null;
+ }
+
+ setCellContentAction(value: ICellData): void {
+ this.setAction({
+ kind: 'set-range-values',
+ value: Tools.deepClone(value),
+ permission: 'cellValue',
+ selectionRequirement: 'none',
+ });
+ }
+
+ async runWithoutRecording<T>(callback: () => Promise<T>): Promise<T> {
+ this._recordingDepth += 1;
+
+ try {
+ return await callback();
+ } finally {
+ this._recordingDepth -= 1;
+ }
+ }
+
+ private _initCommandRecording(): void {
+ this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo, options) => {
+ if (this._recordingDepth > 0 || options?.fromCollab || options?.fromChangeset) {
+ return;
+ }
+
+ const nextAction = this._normalizeAction(commandInfo, options);
+ if (nextAction) {
+ this._action = nextAction;
+ }
+ }));
+ }
+
+ 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;
+ }
+
+ return {
+ style: Tools.deepClone(params.style),
+ };
+ }
+
+ private _normalizeSetRowHeightParams(params: { value: number } | undefined): Record<string, unknown> | undefined {
+ if (!params) {
+ return undefined;
+ }
+
+ return {
+ value: params.value,
+ };
+ }
+
+ private _normalizeSetColWidthParams(params: ISetColWidthCommandParams | undefined): Record<string, unknown> | undefined {
+ if (!params) {
+ return undefined;
+ }
+
+ return {
+ value: params.value,
+ };
+ }
+
+ private _normalizeSetBorderAction(params: ISetBorderBasicCommandParams | undefined): IRepeatLastActionSetBorder | null {
+ if (!params) {
+ return null;
+ }
+
+ return {
+ kind: 'set-border-basic',
+ value: Tools.deepClone(params.value),
+ permission: 'cellStyle',
+ selectionRequirement: 'none',
+ };
+ }
+
+ private _normalizeSetNumfmtAction(params: { values?: Array<{ pattern?: string; type?: string }> } | undefined): IRepeatLastActionSetNumfmt | null {
+ const values = params?.values;
+ if (!values?.length) {
+ return null;
+ }
+
+ const [firstValue] = values;
+ const isUniform = values.every((value) => value.pattern === firstValue.pattern && value.type === firstValue.type);
+ if (!isUniform) {
+ return null;
+ }
+
+ return {
+ kind: 'set-numfmt',
+ pattern: firstValue.pattern,
+ type: firstValue.type,
+ permission: 'cellStyle',
+ selectionRequirement: 'none',
+ };
+ }
+}