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: cut paste undo bug & optimize status bar calc (#1353)

YuHong072e0de9aaae
diff --git a/packages/sheets-ui/src/controllers/clipboard/utils.ts b/packages/sheets-ui/src/controllers/clipboard/utils.ts
index 1ee9bda942..dc4238a533 100644
--- a/packages/sheets-ui/src/controllers/clipboard/utils.ts
+++ b/packages/sheets-ui/src/controllers/clipboard/utils.ts
@@ -15,12 +15,13 @@
*/
import type { ICellData, IDocumentBody, IMutationInfo, IParagraph, IRange, Nullable } from '@univerjs/core';
-import { IUniverInstanceService, ObjectMatrix, Range, Rectangle } from '@univerjs/core';
+import { IUniverInstanceService, ObjectMatrix, Range, Rectangle, Tools } from '@univerjs/core';
import type {
IAddWorksheetMergeMutationParams,
IMoveRangeMutationParams,
IRemoveWorksheetMergeMutationParams,
ISetRangeValuesMutationParams,
+ ISetSelectionsOperationParams,
} from '@univerjs/sheets';
import {
AddMergeUndoMutationFactory,
@@ -124,13 +125,13 @@ export function getMoveRangeMutations(
const toCellMatrix = toWorksheet.getCellMatrix();
Range.foreach(fromRange, (row, col) => {
- fromCellValue.setValue(row, col, fromCellMatrix.getValue(row, col));
+ fromCellValue.setValue(row, col, Tools.deepClone(fromCellMatrix.getValue(row, col)));
newFromCellValue.setValue(row, col, null);
});
const toCellValue = new ObjectMatrix<Nullable<ICellData>>();
Range.foreach(toRange, (row, col) => {
- toCellValue.setValue(row, col, toCellMatrix.getValue(row, col));
+ toCellValue.setValue(row, col, Tools.deepClone(toCellMatrix.getValue(row, col)));
});
const newToCellValue = new ObjectMatrix<Nullable<ICellData>>();
@@ -251,10 +252,10 @@ export function getMoveRangeMutations(
id: SetSelectionsOperation.id,
params: {
unitId,
- sheetId: toSubUnitId,
+ subUnitId: toSubUnitId,
pluginName: NORMAL_SELECTION_PLUGIN_NAME,
selections: [{ range: toRange }],
- },
+ } as ISetSelectionsOperationParams,
},
];
undos = [
diff --git a/packages/sheets-ui/src/controllers/status-bar.controller.ts b/packages/sheets-ui/src/controllers/status-bar.controller.ts
index f31940a408..4187e735d7 100644
--- a/packages/sheets-ui/src/controllers/status-bar.controller.ts
+++ b/packages/sheets-ui/src/controllers/status-bar.controller.ts
@@ -39,6 +39,7 @@ import {
} from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
+import { debounceTime } from 'rxjs';
import type { IStatusBarServiceStatus } from '../services/status-bar.service';
import { IStatusBarService } from '../services/status-bar.service';
@@ -85,18 +86,20 @@ export class StatusBarController extends Disposable {
);
this.disposeWithMe(
toDisposable(
- this._selectionManagerService.selectionMoveEnd$.subscribe((selections) => {
- if (this._selectionManagerService.getCurrent()?.pluginName !== NORMAL_SELECTION_PLUGIN_NAME) {
- return;
- }
- if (selections) {
- const primary = selections[selections.length - 1].primary;
- this._calculateSelection(
- selections.map((selection) => selection.range),
- primary
- );
- }
- })
+ this._selectionManagerService.selectionMoveEnd$
+ .pipe(debounceTime(100))
+ .subscribe((selections) => {
+ if (this._selectionManagerService.getCurrent()?.pluginName !== NORMAL_SELECTION_PLUGIN_NAME) {
+ return;
+ }
+ if (selections) {
+ const primary = selections[selections.length - 1].primary;
+ this._calculateSelection(
+ selections.map((selection) => selection.range),
+ primary
+ );
+ }
+ })
)
);
this.disposeWithMe(
@@ -151,12 +154,13 @@ export class StatusBarController extends Disposable {
return ref.toArrayValueObject(false);
});
const res = executor?.calculate(...arrayValue) as BaseValueObject;
- if (!res.getValue) {
+ const value = res?.getValue();
+ if (!value) {
return undefined;
}
return {
func: f.func,
- value: (executor?.calculate(...arrayValue) as BaseValueObject).getValue(),
+ value,
};
});
if (calcResult.every((r) => r === undefined)) {
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts
index 60641540a2..b5637b029c 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-service.spec.ts
@@ -15,9 +15,10 @@
*/
import type { ICellData, IRange, IStyleData, Nullable, Univer } from '@univerjs/core';
-import { ICommandService, IUniverInstanceService, RANGE_TYPE, Rectangle } from '@univerjs/core';
+import { ICommandService, IUniverInstanceService, RANGE_TYPE, Rectangle, RedoCommand, UndoCommand } from '@univerjs/core';
import {
AddWorksheetMergeMutation,
+ MoveRangeMutation,
NORMAL_SELECTION_PLUGIN_NAME,
RemoveWorksheetMergeMutation,
SelectionManagerService,
@@ -30,6 +31,7 @@ import type { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { ISheetClipboardService } from '../clipboard.service';
+import { COPY_TYPE } from '../type';
import { clipboardTestBed } from './clipboard-test-bed';
import type { IClipboardItem } from './mock-clipboard';
import { MockClipboard } from './mock-clipboard';
@@ -72,6 +74,7 @@ describe('Test clipboard', () => {
commandService.registerCommand(AddWorksheetMergeMutation);
commandService.registerCommand(RemoveWorksheetMergeMutation);
commandService.registerCommand(SetSelectionsOperation);
+ commandService.registerCommand(MoveRangeMutation);
sheetClipboardService = get(ISheetClipboardService);
@@ -879,4 +882,55 @@ describe('Test clipboard', () => {
]);
});
});
+
+ describe('Test cut command in single selection', () => {
+ it('cut value from A25 to B25', async () => {
+ const unitId = 'test';
+ const subUnitId = 'sheet1';
+ const fromRange = { startRow: 24, startColumn: 0, endRow: 24, endColumn: 0 };
+ const toRange = { startRow: 24, startColumn: 1, endRow: 24, endColumn: 1 };
+ const copyContentCache = sheetClipboardService.copyContentCache();
+ const { matrixFragment, copyId } = (sheetClipboardService as any)._generateCopyContent(unitId, subUnitId, fromRange, []);
+
+ // cache the copy content for internal paste
+ copyContentCache.set(copyId, {
+ unitId,
+ subUnitId,
+ range: fromRange,
+ matrix: matrixFragment,
+ copyType: COPY_TYPE.CUT,
+ });
+
+ const selectionManager = get(SelectionManagerService);
+
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+
+ selectionManager.add([
+ {
+ range: { ...toRange, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ (sheetClipboardService as any)._pasteInternal(copyId, 'default-paste');
+
+ expect(getValues(24, 0, 24, 0)![0][0]).toBe(null);
+ expect(getValues(24, 1, 24, 1)![0][0]!.v).toBe('A25');
+
+ // undo
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getValues(24, 0, 24, 0)![0][0]!.v).toStrictEqual('A25');
+ expect(getValues(24, 1, 24, 1)![0][0]!.v).toStrictEqual('B25');
+
+ // redo
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+ expect(getValues(24, 0, 24, 0)![0][0]).toBe(null);
+ expect(getValues(24, 1, 24, 1)![0][0]!.v).toBe('A25');
+ });
+ });
});
diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts
index 16420694d0..87a58f1cf8 100644
--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts
+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts
@@ -17,7 +17,7 @@
import type { IWorkbookData } from '@univerjs/core';
import { ILogService, IUniverInstanceService, LocaleType, LogLevel, Plugin, PluginType, Univer } from '@univerjs/core';
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
-import { SelectionManagerService } from '@univerjs/sheets';
+import { SelectionManagerService, SheetInterceptorService } from '@univerjs/sheets';
import {
BrowserClipboardService,
DesktopMessageService,
@@ -298,6 +298,20 @@ const cellData = {
s: '3UpAbI',
},
},
+ 24: {
+ 0: {
+ v: 'A25',
+ s: '3UpAbI',
+ },
+ 1: {
+ v: 'B25',
+ s: '3UpAbI',
+ },
+ 2: {
+ v: 'C25',
+ s: '3UpAbI',
+ },
+ },
};
const styles = {
@@ -518,6 +532,7 @@ export function clipboardTestBed(workbookConfig?: IWorkbookData, dependencies?:
// Because SheetClipboardController is initialized in the rendered life cycle, here we need to initialize it manually
const sheetClipboardController = injector.createInstance(SheetClipboardController);
injector.add([SheetClipboardController, { useValue: sheetClipboardController }]);
+ injector.add([SheetInterceptorService]);
dependencies?.forEach((d) => injector.add(d));
}
diff --git a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
index 62689937ba..d0c0a30241 100644
--- a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
@@ -40,7 +40,7 @@ import { BehaviorSubject } from 'rxjs';
import { IMarkSelectionService } from '../mark-selection/mark-selection.service';
import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
-import { copyContentCache, extractId, genId } from './copy-content-cache';
+import { CopyContentCache, extractId, genId } from './copy-content-cache';
import { HtmlToUSMService } from './html-to-usm/converter';
import PastePluginLark from './html-to-usm/paste-plugins/plugin-lark';
import PastePluginWord from './html-to-usm/paste-plugins/plugin-word';
@@ -72,11 +72,12 @@ HtmlToUSMService.use(PastePluginLark);
export interface ISheetClipboardService {
copy(): Promise<boolean>;
cut(): Promise<boolean>;
- paste(item: ClipboardItem, pasteType?: string): Promise<boolean>;
- legacyPaste(html?: string, text?: string): Promise<boolean>;
+ paste(item: ClipboardItem, pasteType?: string): Promise<boolean>; // get content from a ClipboardItem and paste it.
+ legacyPaste(html?: string, text?: string): Promise<boolean>; // paste a HTML string or plain text directly.
- addClipboardHook(hook: ISheetClipboardHook): IDisposable;
- getClipboardHooks(): ISheetClipboardHook[];
+ copyContentCache(): CopyContentCache; // return the cache content for inner copy/cut/paste.
+ addClipboardHook(hook: ISheetClipboardHook): IDisposable; // add a hook to the clipboard service
+ getClipboardHooks(): ISheetClipboardHook[]; // get all hooks
}
export const ISheetClipboardService = createIdentifier<ISheetClipboardService>('sheet.clipboard-service');
@@ -90,6 +91,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
private _htmlToUSM: HtmlToUSMService;
private _usmToHtml: USMToHtmlService;
+ private _copyContentCache: CopyContentCache;
private _copyMarkId: string | null = null;
constructor(
@@ -107,59 +109,36 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
getCurrentSkeleton: () => this._sheetSkeletonManagerService.getCurrent(),
});
this._usmToHtml = new USMToHtmlService();
+ this._copyContentCache = new CopyContentCache();
+ }
+
+ copyContentCache(): CopyContentCache {
+ return this._copyContentCache;
}
async copy(copyType = COPY_TYPE.COPY): Promise<boolean> {
- // 1. get the selected range, the range should be the last one of selected ranges
const selection = this._selectionManagerService.getLast();
if (!selection) {
return false; // maybe we should notify user that there is no selection
}
- // 2. get filtered out rows those are filtered out by plugins (e.g. filter feature)
- const hooks = this._clipboardHooks;
- const filteredRows = hooks.reduce((acc, cur) => {
- const rows = cur.getFilteredOutRows?.();
- rows?.forEach((r) => acc.add(r));
- return acc;
- }, new Set<number>());
-
- // 3. calculate selection matrix, span cells would only - maybe warn uses that cells are too may in the future
- const { startColumn, startRow, endColumn, endRow } = selection.range;
const workbook = this._currentUniverService.getCurrentUniverSheetInstance();
const worksheet = workbook.getActiveSheet();
- const matrix = worksheet.getMatrixWithMergedCells(startRow, startColumn, endRow, endColumn);
- const matrixFragment = new ObjectMatrix<ICellDataWithSpanInfo>();
- for (let r = startRow; r <= endRow; r++) {
- for (let c = startColumn; c <= endColumn; c++) {
- const cellData = matrix.getValue(r, c);
- if (cellData) {
- matrixFragment.setValue(r - startRow, c - startColumn, {
- ...getEmptyCell(),
- ...Tools.deepClone(cellData),
- });
- } else {
- matrixFragment.setValue(r - startRow, c - startColumn, getEmptyCell());
- }
- }
- }
-
- // 4. use filteredRows into to remove rows for the matrix
- // TODO: filtering
+ const hooks = this._clipboardHooks;
- // tell hooks to get ready for copying
+ // 1. tell hooks to get ready for copying
hooks.forEach((h) => h.onBeforeCopy?.(workbook.getUnitId(), worksheet.getSheetId(), selection.range));
- // 5. convert matrix to html
- let html = this._usmToHtml.convert(matrix, selection.range, hooks);
+ const copyContent = this._generateCopyContent(workbook.getUnitId(), worksheet.getSheetId(), selection.range, hooks);
+ if (!copyContent) {
+ return false;
+ }
- const plain = getMatrixPlainText(matrixFragment);
- // 6. cache inner copy content
- const copyId = genId();
- html = html.replace(/(<[a-z]+)/, (_p0, p1) => `${p1} data-copy-id="${copyId}"`);
+ // 2. extract copy content for both internal and external
+ const { html, plain, matrixFragment, copyId } = copyContent;
- // 7. cache the copy content for internal paste
- copyContentCache.set(copyId, {
+ // 3. cache the copy content for internal paste
+ this._copyContentCache.set(copyId, {
unitId: workbook.getUnitId(),
subUnitId: worksheet.getSheetId(),
range: selection.range,
@@ -167,16 +146,16 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
copyType,
});
- // 8. write html and get plain text info the clipboard interface
+ // 4. write html and get plain text info the clipboard interface
await this._clipboardInterfaceService.write(plain, html);
- // 9. mark the copy range
+ // 5. mark the copy range
this._markSelectionService.removeAllShapes();
const style = this._selectionManagerService.createCopyPasteSelection();
this._copyMarkId = this._markSelectionService.addShape({ ...selection, style });
- // tell hooks to clean up
+ // 6. tell hooks to clean up
hooks.forEach((h) => h.onAfterCopy?.());
return true;
@@ -250,6 +229,55 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
return this._clipboardHooks;
}
+ private _generateCopyContent(unitId: string, subUnitId: string, range: IRange, hooks: ISheetClipboardHook[]) {
+ const workbook = this._currentUniverService.getUniverSheetInstance(unitId);
+ const worksheet = workbook?.getSheetBySheetId(subUnitId);
+
+ if (!workbook || !worksheet) {
+ return null;
+ }
+
+ // get filtered out rows those are filtered out by plugins (e.g. filter feature)
+ const filteredRows = hooks.reduce((acc, cur) => {
+ const rows = cur.getFilteredOutRows?.();
+ rows?.forEach((r) => acc.add(r));
+ return acc;
+ }, new Set<number>());
+
+ // calculate selection matrix, span cells would only - maybe warn uses that cells are too may in the future
+ const { startColumn, startRow, endColumn, endRow } = range;
+
+ const matrix = worksheet.getMatrixWithMergedCells(startRow, startColumn, endRow, endColumn);
+ const matrixFragment = new ObjectMatrix<ICellDataWithSpanInfo>();
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ const cellData = matrix.getValue(r, c);
+ if (cellData) {
+ matrixFragment.setValue(r - startRow, c - startColumn, {
+ ...getEmptyCell(),
+ ...Tools.deepClone(cellData),
+ });
+ } else {
+ matrixFragment.setValue(r - startRow, c - startColumn, getEmptyCell());
+ }
+ }
+ }
+
+ // convert matrix to html
+ let html = this._usmToHtml.convert(matrix, range, hooks);
+
+ const plain = getMatrixPlainText(matrixFragment);
+ const copyId = genId();
+ html = html.replace(/(<[a-z]+)/, (_p0, p1) => `${p1} data-copy-id="${copyId}"`);
+
+ return {
+ copyId,
+ plain,
+ html,
+ matrixFragment,
+ };
+ }
+
private _notifyClipboardHook() {
this._clipboardHooks$.next(this._clipboardHooks);
}
@@ -309,7 +337,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
const copyId = extractId(html);
- if (copyId && copyContentCache.get(copyId)) {
+ if (copyId && this._copyContentCache.get(copyId)) {
return this._pasteInternal(copyId, pasteType);
}
return this._pasteExternal(html, pasteType);
@@ -372,7 +400,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
private async _pasteInternal(copyId: string, pasteType: string): Promise<boolean> {
const target = this._getPastingTarget();
const { selection, unitId, subUnitId } = target;
- const cachedData = Tools.deepClone(copyContentCache.get(copyId));
+ const cachedData = Tools.deepClone(this._copyContentCache.get(copyId));
const { range, matrix: cellMatrix, unitId: copyUnitId, subUnitId: copySubUnitId } = cachedData || {};
if (!selection || !cellMatrix || !cachedData || !range || !copyUnitId || !copySubUnitId) {
return false;
@@ -449,7 +477,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
);
if (cachedData.copyType === COPY_TYPE.CUT) {
- copyContentCache.set(copyId, { ...cachedData, matrix: null });
+ this._copyContentCache.set(copyId, { ...cachedData, matrix: null });
this._copyMarkId && this._markSelectionService.removeShape(this._copyMarkId);
this._copyMarkId = null;
}
diff --git a/packages/sheets/src/commands/commands/move-range.command.ts b/packages/sheets/src/commands/commands/move-range.command.ts
index 7c83ea85db..bd5a672c61 100644
--- a/packages/sheets/src/commands/commands/move-range.command.ts
+++ b/packages/sheets/src/commands/commands/move-range.command.ts
@@ -32,6 +32,7 @@ import { NORMAL_SELECTION_PLUGIN_NAME } from '../../services/selection-manager.s
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import type { IMoveRangeMutationParams } from '../mutations/move-range.mutation';
import { MoveRangeMutation } from '../mutations/move-range.mutation';
+import type { ISetSelectionsOperationParams } from '../operations/selection.operation';
import { SetSelectionsOperation } from '../operations/selection.operation';
import { alignToMergedCellsBorders, getPrimaryForRange } from './utils/selection-utils';
@@ -76,10 +77,10 @@ export const MoveRangeCommand: ICommand = {
id: SetSelectionsOperation.id,
params: {
unitId,
- sheetId: subUnitId,
+ subUnitId,
pluginName: NORMAL_SELECTION_PLUGIN_NAME,
selections: [{ range: params.toRange, primary: getPrimaryForRange(params.toRange, worksheet) }],
- },
+ } as ISetSelectionsOperationParams,
},
];
const undos = [
@@ -87,10 +88,10 @@ export const MoveRangeCommand: ICommand = {
id: SetSelectionsOperation.id,
params: {
unitId,
- sheetId: subUnitId,
+ subUnitId,
pluginName: NORMAL_SELECTION_PLUGIN_NAME,
selections: [{ range: params.fromRange, primary: getPrimaryForRange(params.fromRange, worksheet) }],
- },
+ } as ISetSelectionsOperationParams,
},
...moveRangeMutations.undos,
...interceptorCommands.undos,
diff --git a/packages/sheets/src/commands/commands/utils/selection-utils.ts b/packages/sheets/src/commands/commands/utils/selection-utils.ts
index d6542f35c2..9ee724dcf3 100644
--- a/packages/sheets/src/commands/commands/utils/selection-utils.ts
+++ b/packages/sheets/src/commands/commands/utils/selection-utils.ts
@@ -18,6 +18,7 @@ import type { IRange, ISelectionCell, Workbook, Worksheet } from '@univerjs/core
import { RANGE_TYPE, Rectangle, selectionToArray } from '@univerjs/core';
import { NORMAL_SELECTION_PLUGIN_NAME } from '../../../services/selection-manager.service';
+import type { ISetSelectionsOperationParams } from '../../operations/selection.operation';
import { SetSelectionsOperation } from '../../operations/selection.operation';
export interface IExpandParams {
@@ -165,8 +166,8 @@ export const followSelectionOperation = (range: IRange, workbook: Workbook, work
id: SetSelectionsOperation.id,
params: {
unitId: workbook.getUnitId(),
- sheetId: worksheet.getSheetId(),
+ subUnitId: worksheet.getSheetId(),
pluginName: NORMAL_SELECTION_PLUGIN_NAME,
selections: [{ range, primary: getPrimaryForRange(range, worksheet) }],
- },
+ } as ISetSelectionsOperationParams,
});