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(sheet): some bugs on copy&past and autofill (#965)

YuHonga24149b22036
diff --git a/packages/core/src/shared/object-matrix.ts b/packages/core/src/shared/object-matrix.ts
index b87768dd67..abc39f97e7 100644
--- a/packages/core/src/shared/object-matrix.ts
+++ b/packages/core/src/shared/object-matrix.ts
@@ -558,6 +558,7 @@ export class ObjectMatrix<T> {
let startRow = 0;
let startColumn = 0;
let endColumn = 0;
+ let endRow = -1;
let initRow = false;
let initColumn = false;
@@ -582,8 +583,12 @@ export class ObjectMatrix<T> {
startColumn = columnIndex;
}
});
+
+ // max rowIndex is the endRow
+ if (rowIndex > endRow) {
+ endRow = rowIndex;
+ }
});
- const endRow = startRow + this.getSizeOf() - 1;
return {
startRow,
diff --git a/packages/engine-render/src/base-object.ts b/packages/engine-render/src/base-object.ts
index d3c3c6e884..756fd46c75 100644
--- a/packages/engine-render/src/base-object.ts
+++ b/packages/engine-render/src/base-object.ts
@@ -702,6 +702,8 @@ export abstract class BaseObject {
this.parent?.removeObject(this);
this.onDisposeObserver.notifyObservers(this);
+
+ this._makeDirtyMix();
}
toJson() {
diff --git a/packages/engine-render/src/layer.ts b/packages/engine-render/src/layer.ts
index 38490bf26a..f1d725cb53 100644
--- a/packages/engine-render/src/layer.ts
+++ b/packages/engine-render/src/layer.ts
@@ -101,6 +101,7 @@ export class Layer {
}
this._objects.push(object);
this.scene.setObjectBehavior(object);
+ object.layer = this;
}
}
this._objects.push(o);
diff --git a/packages/sheets-formula/src/controllers/active-dirty.controller.ts b/packages/sheets-formula/src/controllers/active-dirty.controller.ts
index 0638ed5797..c643a780a3 100644
--- a/packages/sheets-formula/src/controllers/active-dirty.controller.ts
+++ b/packages/sheets-formula/src/controllers/active-dirty.controller.ts
@@ -215,15 +215,15 @@ export class ActiveDirtyController extends Disposable {
}
private _getMoveRangeMutationDirtyRange(params: IMoveRangeMutationParams) {
- const { subUnitId: sheetId, unitId, from, to } = params;
+ const { unitId, from, to } = params;
const dirtyRanges: IUnitRange[] = [];
- dirtyRanges.push(...this._getDirtyRangesByCellValue(unitId, sheetId, from));
+ dirtyRanges.push(...this._getDirtyRangesByCellValue(unitId, from.subUnitId, from.value));
- dirtyRanges.push(...this._getDirtyRangesByCellValue(unitId, sheetId, to));
+ dirtyRanges.push(...this._getDirtyRangesByCellValue(unitId, to.subUnitId, to.value));
- dirtyRanges.push(...this._getDirtyRangesForArrayFormula(unitId, sheetId, to));
+ dirtyRanges.push(...this._getDirtyRangesForArrayFormula(unitId, to.subUnitId, to.value));
return dirtyRanges;
}
diff --git a/packages/sheets-formula/src/controllers/formula-clipboard.controller.ts b/packages/sheets-formula/src/controllers/formula-clipboard.controller.ts
index c9975f65b3..c05ed52fae 100644
--- a/packages/sheets-formula/src/controllers/formula-clipboard.controller.ts
+++ b/packages/sheets-formula/src/controllers/formula-clipboard.controller.ts
@@ -60,11 +60,17 @@ export class FormulaClipboardController extends Disposable {
private _pasteFormulaHook(): ISheetClipboardHook {
const specialPasteFormulaHook: ISheetClipboardHook = {
- hookName: SPECIAL_PASTE_FORMULA,
+ id: SPECIAL_PASTE_FORMULA,
specialPasteInfo: {
label: 'specialPaste.formula',
},
- onPasteCells: (pastedRange, matrix, pasteType, copyInfo) => {
+ onPasteCells: (pasteFrom, pasteTo, data, payload) => {
+ const copyInfo = {
+ copyType: payload.copyType || COPY_TYPE.COPY,
+ copyRange: pasteFrom?.range,
+ };
+ const pastedRange = pasteTo.range;
+ const matrix = data;
const workbook = this._currentUniverSheet.getCurrentUniverSheetInstance();
const unitId = workbook.getUnitId();
const subUnitId = workbook.getActiveSheet().getSheetId();
@@ -89,8 +95,14 @@ export class FormulaClipboardController extends Disposable {
private _pasteWithFormulaHook(): ISheetClipboardHook {
const specialPasteFormulaHook: ISheetClipboardHook = {
- hookName: DEFAULT_PASTE_FORMULA,
- onPasteCells: (pastedRange, matrix, pasteType, copyInfo) => {
+ id: DEFAULT_PASTE_FORMULA,
+ onPasteCells: (pasteFrom, pasteTo, data, payload) => {
+ const copyInfo = {
+ copyType: payload.copyType || COPY_TYPE.COPY,
+ copyRange: pasteFrom?.range,
+ };
+ const pastedRange = pasteTo.range;
+ const matrix = data;
const workbook = this._currentUniverSheet.getCurrentUniverSheetInstance();
const unitId = workbook.getUnitId();
const subUnitId = workbook.getActiveSheet().getSheetId();
diff --git a/packages/sheets-numfmt/src/controllers/numfmt.copy-paste.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt.copy-paste.controller.ts
index 322de32e05..4282f09f54 100644
--- a/packages/sheets-numfmt/src/controllers/numfmt.copy-paste.controller.ts
+++ b/packages/sheets-numfmt/src/controllers/numfmt.copy-paste.controller.ts
@@ -60,10 +60,14 @@ export class NumfmtCopyPasteController extends Disposable {
private _initClipboardHook() {
this.disposeWithMe(
this._sheetClipboardService.addClipboardHook({
- hookName: 'numfmt',
+ id: 'numfmt',
onBeforeCopy: (unitId, subUnitId, range) => this._collectNumfmt(unitId, subUnitId, range),
- onPasteCells: (pastedRange, _m, _p, _copyInfo) =>
- this._generateNumfmtMutations(pastedRange, { ..._copyInfo, pasteType: _p }),
+ onPasteCells: (pasteFrom, pasteTo, data, payload) => {
+ const { copyType = COPY_TYPE.COPY, pasteType } = payload;
+ const { range: copyRange } = pasteFrom || {};
+ const { range: pastedRange } = pasteTo;
+ return this._generateNumfmtMutations(pastedRange, { copyType, pasteType, copyRange });
+ },
})
);
}
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts
index 0c61d6e2e4..2c1352ef20 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts
@@ -25,6 +25,7 @@ import {
UndoCommand,
} from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
+import type { ISelectionWithCoordAndStyle } from '@univerjs/sheets';
import {
AddWorksheetMergeMutation,
NORMAL_SELECTION_PLUGIN_NAME,
@@ -36,9 +37,10 @@ import {
} from '@univerjs/sheets';
import { createCommandTestBed } from '@univerjs/sheets/commands/commands/__tests__/create-command-test-bed.js';
import type { Injector } from '@wendellhu/redi';
+import { BehaviorSubject } from 'rxjs';
import { beforeEach, describe, expect, it } from 'vitest';
-import { IMarkSelectionService } from '../../..';
+import { IMarkSelectionService, ISelectionRenderService } from '../../..';
import { FormatPainterController } from '../../../controllers/format-painter/format-painter.controller';
import { FormatPainterService, IFormatPainterService } from '../../../services/format-painter/format-painter.service';
import { SetFormatPainterOperation } from '../../operations/set-format-painter.operation';
@@ -187,6 +189,11 @@ class MarkSelectionService extends Disposable implements IMarkSelectionService {
removeAllShapes(): void {}
}
+class SelectionRenderService {
+ private readonly _selectionMoveEnd$ = new BehaviorSubject<ISelectionWithCoordAndStyle[]>([]);
+ readonly selectionMoveEnd$ = this._selectionMoveEnd$.asObservable();
+}
+
class RenderManagerService {
getRenderById(id: string) {
return null;
@@ -203,6 +210,7 @@ describe('Test format painter rules in controller', () => {
const testBed = createCommandTestBed(TEST_WORKBOOK_DATA, [
[IMarkSelectionService, { useClass: MarkSelectionService }],
[IFormatPainterService, { useClass: FormatPainterService }],
+ [ISelectionRenderService, { useClass: SelectionRenderService }],
[IRenderManagerService, { useClass: RenderManagerService }],
[FormatPainterController],
]);
diff --git a/packages/sheets-ui/src/commands/commands/auto-fill.command.ts b/packages/sheets-ui/src/commands/commands/auto-fill.command.ts
index 07368299cb..7f6ea73c29 100644
--- a/packages/sheets-ui/src/commands/commands/auto-fill.command.ts
+++ b/packages/sheets-ui/src/commands/commands/auto-fill.command.ts
@@ -14,12 +14,14 @@
* limitations under the License.
*/
-import type { ICellData, ICommand, IObjectMatrixPrimitiveType, IRange } from '@univerjs/core';
-import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService, ObjectMatrix } from '@univerjs/core';
+import type { ICommand, IRange } from '@univerjs/core';
+import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory, SetSelectionsOperation } from '@univerjs/sheets';
import type { IAccessor } from '@wendellhu/redi';
+import { generateNullCellValue } from '../../services/auto-fill/tools';
+
export interface IAutoFillCommandParams {}
export const AutoFillCommand: ICommand = {
@@ -96,23 +98,3 @@ export const AutoClearContentCommand: ICommand = {
return false;
},
};
-
-// Generate cellValue from range and set v/p/f/si to null
-function generateNullCellValue(range: IRange[]): IObjectMatrixPrimitiveType<ICellData> {
- const cellValue = new ObjectMatrix<ICellData>();
- range.forEach((r: IRange) => {
- const { startRow, startColumn, endRow, endColumn } = r;
- for (let i = startRow; i <= endRow; i++) {
- for (let j = startColumn; j <= endColumn; j++) {
- cellValue.setValue(i, j, {
- v: null,
- p: null,
- f: null,
- si: null,
- });
- }
- }
- });
-
- return cellValue.getData();
-}
diff --git a/packages/sheets-ui/src/controllers/auto-fill.controller.ts b/packages/sheets-ui/src/controllers/auto-fill.controller.ts
index 6d29777ce8..d241cf5df9 100644
--- a/packages/sheets-ui/src/controllers/auto-fill.controller.ts
+++ b/packages/sheets-ui/src/controllers/auto-fill.controller.ts
@@ -39,6 +39,7 @@ import type {
import {
AddMergeUndoMutationFactory,
AddWorksheetMergeMutation,
+ ClearSelectionContentCommand,
getAddMergeMutationRangeByType,
NORMAL_SELECTION_PLUGIN_NAME,
RemoveMergeUndoMutationFactory,
@@ -47,13 +48,14 @@ import {
SetRangeValuesMutation,
SetRangeValuesUndoMutationFactory,
SetSelectionsOperation,
+ SheetInterceptorService,
} from '@univerjs/sheets';
import { Inject, Injector } from '@wendellhu/redi';
import { AutoClearContentCommand, AutoFillCommand } from '../commands/commands/auto-fill.command';
import { IAutoFillService } from '../services/auto-fill/auto-fill.service';
import { otherRule } from '../services/auto-fill/rules';
-import { fillCopy, fillCopyStyles, getDataIndex, getLenS } from '../services/auto-fill/tools';
+import { fillCopy, fillCopyStyles, generateNullCellValue, getDataIndex, getLenS } from '../services/auto-fill/tools';
import type {
APPLY_FUNCTIONS,
IAutoFillLocation,
@@ -79,6 +81,7 @@ export class AutoFillController extends Disposable {
@IUndoRedoService private readonly _undoRedoService: IUndoRedoService,
@IAutoFillService private readonly _autoFillService: IAutoFillService,
@IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
+ @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,
@Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
@Inject(Injector) private readonly _injector: Injector
) {
@@ -133,7 +136,13 @@ export class AutoFillController extends Disposable {
disposableCollection.add(
toDisposable(
controlSelection.selectionFilled$.subscribe((filled) => {
- if (filled == null) {
+ if (
+ filled == null ||
+ filled.startColumn === -1 ||
+ filled.startRow === -1 ||
+ filled.endColumn === -1 ||
+ filled.endRow === -1
+ ) {
return;
}
const source: IRange = {
@@ -310,13 +319,13 @@ export class AutoFillController extends Disposable {
while (matrix.getValue(cur, startColumn - 1)?.v != null && cur < maxRow) {
cur += 1;
}
- detectEndRow = cur;
+ detectEndRow = cur - 1;
} else if (endColumn < maxColumn && matrix.getValue(endRow, endColumn + 1)?.v != null) {
let cur = startRow;
while (matrix.getValue(cur, endColumn + 1)?.v != null && cur < maxRow) {
- cur++;
+ cur += 1;
}
- detectEndRow = cur;
+ detectEndRow = cur - 1;
}
for (let i = endRow + 1; i <= detectEndRow; i++) {
@@ -739,9 +748,7 @@ export class AutoFillController extends Disposable {
const row: Array<Nullable<ICellData>> = [];
for (let j = 0; j < untransformedApplyDatas.length; j++) {
row.push({
- v: null,
s: null,
- ...this._beforeApplyData[i][j],
...untransformedApplyDatas[j][i],
});
}
@@ -755,9 +762,7 @@ export class AutoFillController extends Disposable {
const row: Array<Nullable<ICellData>> = [];
for (let j = 0; j < applyData.length; j++) {
row.push({
- v: null,
s: null,
- ...this._beforeApplyData[i - applyStartRow][j],
...applyData[j],
});
}
@@ -818,6 +823,21 @@ export class AutoFillController extends Disposable {
redos.push({ id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams });
undos.push({ id: AddWorksheetMergeMutation.id, params: undoRemoveMergeMutationParams });
+ // clear range value
+ const clearMutationParams: ISetRangeValuesMutationParams = {
+ subUnitId,
+ unitId,
+ cellValue: generateNullCellValue([target]),
+ };
+ const undoClearMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(
+ accessor,
+ clearMutationParams
+ );
+
+ const intercepted = this._sheetInterceptorService.onCommandExecute({ id: ClearSelectionContentCommand.id });
+ redos.push({ id: SetRangeValuesMutation.id, params: clearMutationParams }, ...intercepted.redos);
+ undos.push(...intercepted.undos, { id: SetRangeValuesMutation.id, params: undoClearMutationParams });
+
// set range value
const cellValue = new ObjectMatrix<ICellData>();
const { startRow, startColumn, endRow, endColumn } = target;
@@ -844,9 +864,6 @@ export class AutoFillController extends Disposable {
undos.push({ id: SetRangeValuesMutation.id, params: undoSetRangeValuesMutationParams });
redos.push({ id: SetRangeValuesMutation.id, params: setRangeValuesMutationParams });
- undos.push({ id: SetRangeValuesMutation.id, params: undoSetRangeValuesMutationParams });
- redos.push({ id: SetRangeValuesMutation.id, params: setRangeValuesMutationParams });
-
// add worksheet merge
if (applyMergeRanges?.length) {
const ranges = getAddMergeMutationRangeByType(applyMergeRanges);
diff --git a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts
index 6c1a12f17b..6205be5457 100644
--- a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts
+++ b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts
@@ -69,10 +69,11 @@ import {
} from '../../commands/commands/clipboard.command';
import { ISheetClipboardService, PREDEFINED_HOOK_NAME } from '../../services/clipboard/clipboard.service';
import type {
- COPY_TYPE,
ICellDataWithSpanInfo,
IClipboardPropertyItem,
+ ICopyPastePayload,
ISheetClipboardHook,
+ ISheetRangeLocation,
} from '../../services/clipboard/type';
import {
getClearAndSetMergeMutations,
@@ -86,7 +87,7 @@ import {
* This controller add basic clipboard logic for basic features such as text color / BISU / row widths to the clipboard
* service. You can create a similar clipboard controller to add logic for your own features.
*/
-@OnLifecycle(LifecycleStages.Rendered, SheetClipboardController)
+@OnLifecycle(LifecycleStages.Ready, SheetClipboardController)
export class SheetClipboardController extends Disposable {
constructor(
@IUniverInstanceService private readonly _currentUniverSheet: IUniverInstanceService,
@@ -127,14 +128,14 @@ export class SheetClipboardController extends Disposable {
const self = this;
let currentSheet: Worksheet | null = null;
return {
- hookName: PREDEFINED_HOOK_NAME.DEFAULT_COPY,
+ id: PREDEFINED_HOOK_NAME.DEFAULT_COPY,
isDefaultHook: true,
onBeforeCopy(unitId, subUnitId) {
currentSheet = self._getWorksheet(unitId, subUnitId);
},
onCopyCellContent(row: number, col: number): string {
const cell = currentSheet!.getCell(row, col);
- return `${cell?.v}` || '';
+ return `${cell?.v || ''}`;
},
onCopyCellStyle: (row: number, col: number, rowSpan?: number, colSpan?: number) => {
const properties: IClipboardPropertyItem = {};
@@ -218,9 +219,9 @@ export class SheetClipboardController extends Disposable {
let currentSheet: Worksheet | null = null;
return {
- hookName: PREDEFINED_HOOK_NAME.DEFAULT_PASTE,
+ id: PREDEFINED_HOOK_NAME.DEFAULT_PASTE,
isDefaultHook: true,
- onBeforePaste(unitId_, subUnitId_, range) {
+ onBeforePaste({ unitId: unitId_, subUnitId: subUnitId_, range }) {
currentSheet = self._getWorksheet(unitId_, subUnitId_);
unitId = unitId_;
subUnitId = subUnitId_;
@@ -240,7 +241,8 @@ export class SheetClipboardController extends Disposable {
return true;
},
- onPasteRows(range, rowProperties) {
+ onPasteRows(pasteTo, rowProperties) {
+ const { range } = pasteTo;
const redoMutations: IMutationInfo[] = [];
const undoMutations: IMutationInfo[] = [];
@@ -332,7 +334,8 @@ export class SheetClipboardController extends Disposable {
};
},
- onPasteColumns(range, colProperties, pasteType) {
+ onPasteColumns(pasteTo, colProperties, pasteType) {
+ const { range } = pasteTo;
const redoMutations: IMutationInfo[] = [];
const undoMutations: IMutationInfo[] = [];
@@ -378,8 +381,17 @@ export class SheetClipboardController extends Disposable {
};
},
- onPasteCells(range, matrix, pasteType, copyInfo) {
- return self._onPasteCells(range, matrix, unitId!, subUnitId!, pasteType, copyInfo);
+ onPastePlainText(pasteTo: ISheetRangeLocation, text: string, payload: ICopyPastePayload) {
+ return self._onPastePlainText(pasteTo, text, payload);
+ },
+
+ onPasteCells(
+ pasteFrom: ISheetRangeLocation,
+ pasteTo: ISheetRangeLocation,
+ data: ObjectMatrix<ICellDataWithSpanInfo>,
+ payload: ICopyPastePayload
+ ) {
+ return self._onPasteCells(pasteFrom, pasteTo, data, payload);
},
onAfterPaste(success) {
@@ -388,16 +400,45 @@ export class SheetClipboardController extends Disposable {
};
}
+ private _onPastePlainText(pasteTo: ISheetRangeLocation, text: string, payload: ICopyPastePayload) {
+ const { range, unitId, subUnitId } = pasteTo;
+ const cellValue: IObjectMatrixPrimitiveType<ICellData> = {
+ [range.startRow]: {
+ [range.startColumn]: {
+ v: text,
+ },
+ },
+ };
+
+ const workbook = this._currentUniverSheet.getCurrentUniverSheetInstance();
+
+ const setRangeValuesParams: ISetRangeValuesMutationParams = {
+ unitId,
+ subUnitId,
+ cellValue,
+ };
+
+ return {
+ redos: [
+ {
+ id: SetRangeValuesMutation.id,
+ params: setRangeValuesParams,
+ },
+ ],
+ undos: [
+ {
+ id: SetRangeValuesMutation.id,
+ params: SetRangeValuesUndoMutationFactory(this._injector, setRangeValuesParams),
+ },
+ ],
+ };
+ }
+
private _onPasteCells(
- pastedRange: IRange,
- matrix: ObjectMatrix<ICellDataWithSpanInfo>,
- unitId: string,
- subUnitId: string,
- pasteType: string,
- copyInfo: {
- copyType: COPY_TYPE;
- copyRange?: IRange;
- }
+ pasteFrom: ISheetRangeLocation,
+ pasteTo: ISheetRangeLocation,
+ data: ObjectMatrix<ICellDataWithSpanInfo>,
+ payload: ICopyPastePayload
): {
redos: IMutationInfo[];
undos: IMutationInfo[];
@@ -405,7 +446,7 @@ export class SheetClipboardController extends Disposable {
const accessor = {
get: this._injector.get.bind(this._injector),
};
- return getDefaultOnPasteCellMutations(pastedRange, matrix, unitId, subUnitId, copyInfo, accessor);
+ return getDefaultOnPasteCellMutations(pasteFrom, pasteTo, data, payload, accessor);
}
private _initSpecialPasteHooks() {
@@ -415,23 +456,23 @@ export class SheetClipboardController extends Disposable {
const self = this;
const specialPasteValueHook: ISheetClipboardHook = {
- hookName: PREDEFINED_HOOK_NAME.SPECIAL_PASTE_VALUE,
+ id: PREDEFINED_HOOK_NAME.SPECIAL_PASTE_VALUE,
specialPasteInfo: {
label: 'specialPaste.value',
},
- onPasteCells: (pastedRange, matrix, pasteType, copyInfo) => {
+ onPasteCells: (pasteFrom, pasteTo, data, pasteType) => {
const workbook = self._currentUniverSheet.getCurrentUniverSheetInstance();
const unitId = workbook.getUnitId();
const subUnitId = workbook.getActiveSheet().getSheetId();
- return getSetCellValueMutations(unitId, subUnitId, pastedRange, matrix, accessor);
+ return getSetCellValueMutations(pasteTo, data, accessor);
},
};
const specialPasteFormatHook: ISheetClipboardHook = {
- hookName: PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMAT,
+ id: PREDEFINED_HOOK_NAME.SPECIAL_PASTE_FORMAT,
specialPasteInfo: {
label: 'specialPaste.format',
},
- onPasteCells(pastedRange, matrix, pasteType, copyInfo) {
+ onPasteCells(pasteFrom, pasteTo, matrix, pasteType) {
const workbook = self._currentUniverSheet.getCurrentUniverSheetInstance();
const unitId = workbook.getUnitId();
const subUnitId = workbook.getActiveSheet().getSheetId();
@@ -439,21 +480,13 @@ export class SheetClipboardController extends Disposable {
const undoMutationsInfo: IMutationInfo[] = [];
// clear cell style
- const { undos: styleUndos, redos: styleRedos } = getClearCellStyleMutations(
- unitId,
- subUnitId,
- pastedRange,
- matrix,
- accessor
- );
+ const { undos: styleUndos, redos: styleRedos } = getClearCellStyleMutations(pasteTo, matrix, accessor);
redoMutationsInfo.push(...styleRedos);
undoMutationsInfo.push(...styleUndos);
// clear and set merge
const { undos: mergeUndos, redos: mergeRedos } = getClearAndSetMergeMutations(
- unitId,
- subUnitId,
- pastedRange,
+ pasteTo,
matrix,
accessor
);
@@ -461,9 +494,7 @@ export class SheetClipboardController extends Disposable {
undoMutationsInfo.push(...mergeUndos);
const { undos: setStyleUndos, redos: setStyleRedos } = getSetCellStyleMutations(
- unitId,
- subUnitId,
- pastedRange,
+ pasteTo,
matrix,
accessor
);
@@ -479,7 +510,7 @@ export class SheetClipboardController extends Disposable {
};
const specialPasteColWidthHook: ISheetClipboardHook = {
- hookName: PREDEFINED_HOOK_NAME.SPECIAL_PASTE_COL_WIDTH,
+ id: PREDEFINED_HOOK_NAME.SPECIAL_PASTE_COL_WIDTH,
specialPasteInfo: {
label: 'specialPaste.colWidth',
},
@@ -489,14 +520,14 @@ export class SheetClipboardController extends Disposable {
redos: [],
};
},
- onPasteColumns(range, colProperties, pasteType) {
+ onPasteColumns(pasteTo, colProperties, payload) {
const workbook = self._currentUniverSheet.getCurrentUniverSheetInstance();
const unitId = workbook.getUnitId();
const subUnitId = workbook.getActiveSheet().getSheetId();
const redoMutations: IMutationInfo[] = [];
const undoMutations: IMutationInfo[] = [];
const currentSheet = self._getWorksheet(unitId, subUnitId);
-
+ const { range } = pasteTo;
// if the range is outside ot the worksheet's boundary, we should add rows
const maxColumn = currentSheet!.getMaxColumns();
const addingColsCount = range.endColumn - maxColumn;
@@ -530,17 +561,16 @@ export class SheetClipboardController extends Disposable {
};
const specialPasteBesidesBorder: ISheetClipboardHook = {
- hookName: PREDEFINED_HOOK_NAME.SPECIAL_PASTE_BESIDES_BORDER,
+ id: PREDEFINED_HOOK_NAME.SPECIAL_PASTE_BESIDES_BORDER,
specialPasteInfo: {
label: 'specialPaste.besidesBorder',
},
- onPasteCells(pastedRange, matrix, pasteType, copyInfo) {
+ onPasteCells(pasteFrom, pasteTo, matrix, payload) {
const workbook = self._currentUniverSheet.getCurrentUniverSheetInstance();
- const unitId = workbook.getUnitId();
- const subUnitId = workbook.getActiveSheet().getSheetId();
const redoMutationsInfo: IMutationInfo[] = [];
const undoMutationsInfo: IMutationInfo[] = [];
- const { startColumn, startRow, endColumn, endRow } = pastedRange;
+ const { range, unitId, subUnitId } = pasteTo;
+ const { startColumn, startRow, endColumn, endRow } = range;
const valueMatrix = new ObjectMatrix<ICellData>();
// TODO@Dushusir: undo selection
@@ -577,7 +607,7 @@ export class SheetClipboardController extends Disposable {
params: undoSetValuesMutation,
});
- const { undos, redos } = getClearAndSetMergeMutations(unitId, subUnitId, pastedRange, matrix, accessor);
+ const { undos, redos } = getClearAndSetMergeMutations(pasteTo, matrix, accessor);
undoMutationsInfo.push(...undos);
redoMutationsInfo.push(...redos);
diff --git a/packages/sheets-ui/src/controllers/clipboard/utils.ts b/packages/sheets-ui/src/controllers/clipboard/utils.ts
index 265ce83099..0823639eba 100644
--- a/packages/sheets-ui/src/controllers/clipboard/utils.ts
+++ b/packages/sheets-ui/src/controllers/clipboard/utils.ts
@@ -37,67 +37,44 @@ import {
} from '@univerjs/sheets';
import type { IAccessor } from '@wendellhu/redi';
-import type { ICellDataWithSpanInfo } from '../../services/clipboard/type';
+import type { ICellDataWithSpanInfo, ICopyPastePayload, ISheetRangeLocation } from '../../services/clipboard/type';
import { COPY_TYPE } from '../../services/clipboard/type';
// if special paste need append mutations instead of replace the default, it can use this function to generate default mutations.
export function getDefaultOnPasteCellMutations(
- pastedRange: IRange,
- matrix: ObjectMatrix<ICellDataWithSpanInfo>,
- unitId: string,
- subUnitId: string,
- copyInfo: {
- copyType: COPY_TYPE;
- copyRange?: IRange;
- },
+ pasteFrom: ISheetRangeLocation,
+ pasteTo: ISheetRangeLocation,
+ data: ObjectMatrix<ICellDataWithSpanInfo>,
+ payload: ICopyPastePayload,
accessor: IAccessor
) {
const redoMutationsInfo: IMutationInfo[] = [];
const undoMutationsInfo: IMutationInfo[] = [];
- if (copyInfo.copyType === COPY_TYPE.CUT) {
- const { undos, redos } = getMoveRangeMutations(pastedRange, unitId, subUnitId, copyInfo, accessor);
+ if (payload.copyType === COPY_TYPE.CUT) {
+ const { undos, redos } = getMoveRangeMutations(pasteFrom, pasteTo, accessor);
redoMutationsInfo.push(...redos);
undoMutationsInfo.push(...undos);
} else {
+ const { unitId, subUnitId, range } = pasteTo;
// clear style
- const { undos: clearStyleUndos, redos: clearStyleRedos } = getClearCellStyleMutations(
- unitId,
- subUnitId,
- pastedRange,
- matrix,
- accessor
- );
+ const { undos: clearStyleUndos, redos: clearStyleRedos } = getClearCellStyleMutations(pasteTo, data, accessor);
redoMutationsInfo.push(...clearStyleRedos);
undoMutationsInfo.push(...clearStyleUndos);
// set values
- const { undos: setValuesUndos, redos: setValuesRedos } = getSetCellValueMutations(
- unitId,
- subUnitId,
- pastedRange,
- matrix,
- accessor
- );
+ const { undos: setValuesUndos, redos: setValuesRedos } = getSetCellValueMutations(pasteTo, data, accessor);
redoMutationsInfo.push(...setValuesRedos);
undoMutationsInfo.push(...setValuesUndos);
// set styles
- const { undos: setStyleUndos, redos: setStyleRedos } = getSetCellStyleMutations(
- unitId,
- subUnitId,
- pastedRange,
- matrix,
- accessor
- );
+ const { undos: setStyleUndos, redos: setStyleRedos } = getSetCellStyleMutations(pasteTo, data, accessor);
redoMutationsInfo.push(...setStyleRedos);
undoMutationsInfo.push(...setStyleUndos);
// clear and add merge
const { undos: clearMergeUndos, redos: clearMergeRedos } = getClearAndSetMergeMutations(
- unitId,
- subUnitId,
- pastedRange,
- matrix,
+ pasteTo,
+ data,
accessor
);
redoMutationsInfo.push(...clearMergeRedos);
@@ -110,70 +87,82 @@ export function getDefaultOnPasteCellMutations(
}
export function getMoveRangeMutations(
- pastedRange: IRange,
- unitId: string,
- subUnitId: string,
- copyInfo: {
- copyType: COPY_TYPE;
- copyRange?: IRange;
+ from: {
+ unitId: string;
+ subUnitId: string;
+ range?: IRange;
+ },
+ to: {
+ unitId: string;
+ subUnitId: string;
+ range?: IRange;
},
accessor: IAccessor
) {
let redoMutationsInfo: IMutationInfo[] = [];
let undoMutationsInfo: IMutationInfo[] = [];
- const { copyRange } = copyInfo;
- if (copyRange) {
+ const { range: fromRange, subUnitId: fromSubUnitId, unitId } = from;
+ const { range: toRange, subUnitId: toSubUnitId } = to;
+ if (fromRange && toRange) {
const univerInstanceService = accessor.get(IUniverInstanceService);
const sheetInterceptorService = accessor.get(SheetInterceptorService);
const workbook = univerInstanceService.getUniverSheetInstance(unitId);
- const worksheet = workbook?.getSheetBySheetId(subUnitId);
- if (worksheet) {
- const fromValues = worksheet.getRange(copyRange).getValues();
+ const fromWorksheet = workbook?.getSheetBySheetId(fromSubUnitId);
+ const toWorksheet = workbook?.getSheetBySheetId(toSubUnitId);
+ if (fromWorksheet && toWorksheet) {
+ const fromValues = fromWorksheet.getRange(fromRange).getValues();
const newFromCellValues = fromValues.reduce((res, row, rowIndex) => {
row.forEach((colItem, colIndex) => {
- res.setValue(copyRange.startRow + rowIndex, copyRange.startColumn + colIndex, null);
+ res.setValue(fromRange.startRow + rowIndex, fromRange.startColumn + colIndex, null);
});
return res;
}, new ObjectMatrix<Nullable<ICellData>>());
const currentFromCellValues = fromValues.reduce((res, row, rowIndex) => {
row.forEach((colItem, colIndex) => {
- res.setValue(copyRange.startRow + rowIndex, copyRange.startColumn + colIndex, colItem);
+ res.setValue(fromRange.startRow + rowIndex, fromRange.startColumn + colIndex, colItem);
});
return res;
}, new ObjectMatrix<Nullable<ICellData>>());
const newToCellValues = fromValues.reduce((res, row, rowIndex) => {
row.forEach((colItem, colIndex) => {
- res.setValue(pastedRange.startRow + rowIndex, pastedRange.startColumn + colIndex, colItem);
+ res.setValue(toRange.startRow + rowIndex, toRange.startColumn + colIndex, colItem);
});
return res;
}, new ObjectMatrix<Nullable<ICellData>>());
- const currentToCellValues = worksheet
- .getRange(pastedRange)
+ const currentToCellValues = toWorksheet
+ .getRange(toRange)
.getValues()
.reduce((res, row, rowIndex) => {
row.forEach((colItem, colIndex) => {
- res.setValue(pastedRange.startRow + rowIndex, pastedRange.startColumn + colIndex, colItem);
+ res.setValue(toRange.startRow + rowIndex, toRange.startColumn + colIndex, colItem);
});
return res;
}, new ObjectMatrix<Nullable<ICellData>>());
const doMoveRangeMutation: IMoveRangeMutationParams = {
- from: newFromCellValues.getMatrix(),
- to: newToCellValues.getMatrix(),
+ from: {
+ value: newFromCellValues.getMatrix(),
+ subUnitId: fromSubUnitId,
+ },
+ to: { value: newToCellValues.getMatrix(), subUnitId: toSubUnitId },
unitId,
- subUnitId,
};
const undoMoveRangeMutation: IMoveRangeMutationParams = {
- from: currentFromCellValues.getMatrix(),
- to: currentToCellValues.getMatrix(),
+ from: {
+ value: currentFromCellValues.getMatrix(),
+ subUnitId: fromSubUnitId,
+ },
+ to: {
+ value: currentToCellValues.getMatrix(),
+ subUnitId: toSubUnitId,
+ },
unitId,
- subUnitId,
};
const interceptorCommands = sheetInterceptorService.onCommandExecute({
id: MoveRangeCommand.id,
- params: { toRange: pastedRange, fromRange: copyRange },
+ params: { toRange, fromRange },
});
redoMutationsInfo = [
@@ -183,9 +172,9 @@ export function getMoveRangeMutations(
id: SetSelectionsOperation.id,
params: {
unitId,
- sheetId: subUnitId,
+ sheetId: toSubUnitId,
pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- selections: [{ range: pastedRange }],
+ selections: [{ range: toRange }],
},
},
];
@@ -194,9 +183,9 @@ export function getMoveRangeMutations(
id: SetSelectionsOperation.id,
params: {
unitId,
- sheetId: subUnitId,
+ sheetId: fromSubUnitId,
pluginName: NORMAL_SELECTION_PLUGIN_NAME,
- selections: [{ range: copyRange }],
+ selections: [{ range: fromRange }],
},
},
...interceptorCommands.undos,
@@ -212,12 +201,11 @@ export function getMoveRangeMutations(
}
export function getSetCellValueMutations(
- unitId: string,
- subUnitId: string,
- range: IRange,
+ pasteTo: ISheetRangeLocation,
matrix: ObjectMatrix<ICellDataWithSpanInfo>,
accessor: IAccessor
) {
+ const { unitId, subUnitId, range } = pasteTo;
const redoMutationsInfo: IMutationInfo[] = [];
const undoMutationsInfo: IMutationInfo[] = [];
const { startColumn, startRow } = range;
@@ -266,26 +254,24 @@ export function getSetCellValueMutations(
}
export function getSetCellStyleMutations(
- unitId: string,
- subUnitId: string,
- range: IRange,
+ pasteTo: ISheetRangeLocation,
matrix: ObjectMatrix<ICellDataWithSpanInfo>,
accessor: IAccessor
) {
const redoMutationsInfo: IMutationInfo[] = [];
const undoMutationsInfo: IMutationInfo[] = [];
+ const { unitId, subUnitId, range } = pasteTo;
const { startColumn, startRow } = range;
const valueMatrix = new ObjectMatrix<ICellData>();
matrix.forValue((row, col, value) => {
- valueMatrix.setValue(row + startRow, col + startColumn, {
+ const newValue: ICellData = {
s: value.s,
- });
+ };
if (value.p?.body) {
- valueMatrix.setValue(row + startRow, col + startColumn, {
- p: value.p,
- });
+ newValue.p = value.p;
}
+ valueMatrix.setValue(row + startRow, col + startColumn, newValue);
});
// set cell style
const setValuesMutation: ISetRangeValuesMutationParams = {
@@ -316,15 +302,14 @@ export function getSetCellStyleMutations(
}
export function getClearCellStyleMutations(
- unitId: string,
- subUnitId: string,
- range: IRange,
+ pasteTo: ISheetRangeLocation,
matrix: ObjectMatrix<ICellDataWithSpanInfo>,
accessor: IAccessor
) {
const redoMutationsInfo: IMutationInfo[] = [];
const undoMutationsInfo: IMutationInfo[] = [];
const clearStyleMatrix = new ObjectMatrix<ICellData>();
+ const { unitId, subUnitId, range } = pasteTo;
const { startColumn, startRow } = range;
matrix.forValue((row, col, value) => {
@@ -363,14 +348,13 @@ export function getClearCellStyleMutations(
}
export function getClearAndSetMergeMutations(
- unitId: string,
- subUnitId: string,
- range: IRange,
+ pasteTo: ISheetRangeLocation,
matrix: ObjectMatrix<ICellDataWithSpanInfo>,
accessor: IAccessor
) {
const redoMutationsInfo: IMutationInfo[] = [];
const undoMutationsInfo: IMutationInfo[] = [];
+ const { unitId, subUnitId, range } = pasteTo;
const { startColumn, startRow, endColumn, endRow } = range;
let hasMerge = false;
const mergeRangeData: IRange[] = [];
diff --git a/packages/sheets-ui/src/controllers/format-painter/format-painter.controller.ts b/packages/sheets-ui/src/controllers/format-painter/format-painter.controller.ts
index d377f94416..b3818bea4f 100644
--- a/packages/sheets-ui/src/controllers/format-painter/format-painter.controller.ts
+++ b/packages/sheets-ui/src/controllers/format-painter/format-painter.controller.ts
@@ -14,12 +14,16 @@
* limitations under the License.
*/
-import type { ICellData, ICommandInfo, IRange } from '@univerjs/core';
-import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import type { ICellData, IRange } from '@univerjs/core';
+import {
+ Disposable,
+ ICommandService,
+ IUniverInstanceService,
+ LifecycleStages,
+ OnLifecycle,
+ toDisposable,
+} from '@univerjs/core';
import { CURSOR_TYPE, IRenderManagerService } from '@univerjs/engine-render';
-import type { ISetSelectionsOperationParams } from '@univerjs/sheets';
-import { SelectionManagerService, SetSelectionsOperation } from '@univerjs/sheets';
-import { Inject } from '@wendellhu/redi';
import type { IApplyFormatPainterCommandParams } from '../../commands/commands/set-format-painter.command';
import {
@@ -27,6 +31,7 @@ import {
SetOnceFormatPainterCommand,
} from '../../commands/commands/set-format-painter.command';
import { FormatPainterStatus, IFormatPainterService } from '../../services/format-painter/format-painter.service';
+import { ISelectionRenderService } from '../../services/selection/selection-render.service';
import { getSheetObject } from '../utils/component-tools';
@OnLifecycle(LifecycleStages.Rendered, FormatPainterController)
@@ -36,7 +41,7 @@ export class FormatPainterController extends Disposable {
@IFormatPainterService private readonly _formatPainterService: IFormatPainterService,
@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
- @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService
+ @ISelectionRenderService private readonly _selectionRenderService: ISelectionRenderService
) {
super();
@@ -62,20 +67,23 @@ export class FormatPainterController extends Disposable {
private _commandExecutedListener() {
this.disposeWithMe(
- this._commandService.onCommandExecuted((command: ICommandInfo) => {
- if (
- command.id === SetSelectionsOperation.id &&
- this._formatPainterService.getStatus() !== FormatPainterStatus.OFF
- ) {
- const { selections } = command.params as ISetSelectionsOperationParams;
- const { range } = selections[selections.length - 1];
- this._applyFormatPainter(range);
- // if once, turn off the format painter
- if (this._formatPainterService.getStatus() === FormatPainterStatus.ONCE) {
- this._commandService.executeCommand(SetOnceFormatPainterCommand.id);
+ toDisposable(
+ this._selectionRenderService.selectionMoveEnd$.subscribe((selections) => {
+ if (this._formatPainterService.getStatus() !== FormatPainterStatus.OFF) {
+ const { rangeWithCoord } = selections[selections.length - 1];
+ this._applyFormatPainter({
+ startRow: rangeWithCoord.startRow,
+ startColumn: rangeWithCoord.startColumn,
+ endRow: rangeWithCoord.endRow,
+ endColumn: rangeWithCoord.endColumn,
+ });
+ // if once, turn off the format painter
+ if (this._formatPainterService.getStatus() === FormatPainterStatus.ONCE) {
+ this._commandService.executeCommand(SetOnceFormatPainterCommand.id);
+ }
}
- }
- })
+ })
+ )
);
}
diff --git a/packages/sheets-ui/src/controllers/mark-selection.controller.ts b/packages/sheets-ui/src/controllers/mark-selection.controller.ts
index 07d55b97cb..ddb9441093 100644
--- a/packages/sheets-ui/src/controllers/mark-selection.controller.ts
+++ b/packages/sheets-ui/src/controllers/mark-selection.controller.ts
@@ -16,7 +16,6 @@
import type { ICommandInfo } from '@univerjs/core';
import { Disposable, ICommandService, LifecycleStages, OnLifecycle, toDisposable } from '@univerjs/core';
-import { SetRangeValuesMutation } from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
import { SetCellEditVisibleOperation } from '../commands/operations/cell-edit.operation';
@@ -40,7 +39,7 @@ export class MarkSelectionController extends Disposable {
}
private _addRemoveListener() {
- const removeCommands = [SetCellEditVisibleOperation.id, SetRangeValuesMutation.id];
+ const removeCommands = [SetCellEditVisibleOperation.id];
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo) => {
if (removeCommands.includes(command.id)) {
diff --git a/packages/sheets-ui/src/controllers/status-bar.controller.ts b/packages/sheets-ui/src/controllers/status-bar.controller.ts
index 9d69bae2ed..70c9df736a 100644
--- a/packages/sheets-ui/src/controllers/status-bar.controller.ts
+++ b/packages/sheets-ui/src/controllers/status-bar.controller.ts
@@ -14,9 +14,10 @@
* limitations under the License.
*/
-import type { IRange } from '@univerjs/core';
+import type { ICommandInfo, IRange } from '@univerjs/core';
import {
Disposable,
+ ICommandService,
IUniverInstanceService,
LifecycleStages,
ObjectMatrix,
@@ -30,7 +31,7 @@ import {
IFunctionService,
RangeReferenceObject,
} from '@univerjs/engine-formula';
-import { SelectionManagerService } from '@univerjs/sheets';
+import { SelectionManagerService, SetRangeValuesMutation } from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
import type { IStatusBarServiceStatus } from '../services/status-bar.service';
@@ -44,6 +45,7 @@ export class StatusBarController extends Disposable {
@Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
@IFunctionService private readonly _functionService: IFunctionService,
@IStatusBarService private readonly _statusBarService: IStatusBarService,
+ @ICommandService private readonly _commandService: ICommandService,
@Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel
) {
super();
@@ -77,6 +79,19 @@ export class StatusBarController extends Disposable {
})
)
);
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (command.id === SetRangeValuesMutation.id) {
+ const selections = this._selectionManagerService.getSelections();
+ if (selections) {
+ clearTimeout(this._calculateTimeout);
+ this._calculateTimeout = setTimeout(() => {
+ this._calculateSelection(selections.map((selection) => selection.range));
+ }, 100);
+ }
+ }
+ })
+ );
}
private _calculateSelection(selections: IRange[]) {
diff --git a/packages/sheets-ui/src/services/auto-fill/tools.ts b/packages/sheets-ui/src/services/auto-fill/tools.ts
index 4e37cada99..62690d9a0b 100644
--- a/packages/sheets-ui/src/services/auto-fill/tools.ts
+++ b/packages/sheets-ui/src/services/auto-fill/tools.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import type { ICellData, IRange, Nullable } from '@univerjs/core';
-import { Direction, Tools } from '@univerjs/core';
+import type { ICellData, IObjectMatrixPrimitiveType, IRange, Nullable } from '@univerjs/core';
+import { Direction, ObjectMatrix, Tools } from '@univerjs/core';
export const chnNumChar = { 零: 0, 一: 1, 二: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9 };
export const chnNumChar2 = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
@@ -328,7 +328,15 @@ export function fillCopy(data: Array<Nullable<ICellData>>, len: number) {
const index = (i - 1) % data.length;
const d = Tools.deepClone(data[index]);
- applyData.push(d);
+ applyData.push({
+ v: null,
+ s: null,
+ p: null,
+ f: null,
+ si: null,
+ t: null,
+ ...d,
+ });
}
return applyData;
@@ -774,3 +782,23 @@ export function getAutoFillRepeatRange(sourceRange: IRange, targetRange: IRange)
return repeats;
}
+
+// Generate cellValue from range and set v/p/f/si to null
+export function generateNullCellValue(range: IRange[]): IObjectMatrixPrimitiveType<ICellData> {
+ const cellValue = new ObjectMatrix<ICellData>();
+ range.forEach((r: IRange) => {
+ const { startRow, startColumn, endRow, endColumn } = r;
+ for (let i = startRow; i <= endRow; i++) {
+ for (let j = startColumn; j <= endColumn; j++) {
+ cellValue.setValue(i, j, {
+ v: null,
+ p: null,
+ f: null,
+ si: null,
+ });
+ }
+ }
+ });
+
+ return cellValue.getData();
+}
diff --git a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
index 756ae435cb..b9cdb8cb00 100644
--- a/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
+++ b/packages/sheets-ui/src/services/clipboard/clipboard.service.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICellData, IMutationInfo, IObjectMatrixPrimitiveType, IRange, Worksheet } from '@univerjs/core';
+import type { ICellData, IMutationInfo, IRange, Worksheet } from '@univerjs/core';
import {
Disposable,
ICommandService,
@@ -26,12 +26,11 @@ import {
toDisposable,
Tools,
} from '@univerjs/core';
-import type { ISetRangeValuesMutationParams, ISetSelectionsOperationParams } from '@univerjs/sheets';
+import type { ISetSelectionsOperationParams } from '@univerjs/sheets';
import {
getPrimaryForRange,
NORMAL_SELECTION_PLUGIN_NAME,
SelectionManagerService,
- SetRangeValuesMutation,
SetSelectionsOperation,
} from '@univerjs/sheets';
import { HTML_CLIPBOARD_MIME_TYPE, IClipboardInterfaceService, PLAIN_TEXT_CLIPBOARD_MIME_TYPE } from '@univerjs/ui';
@@ -47,9 +46,9 @@ import PastePluginLark from './html-to-usm/paste-plugins/plugin-lark';
import PastePluginWord from './html-to-usm/paste-plugins/plugin-word';
import type {
ICellDataWithSpanInfo,
- IPasteSource,
IPasteTarget,
ISheetClipboardHook,
+ ISheetRangeLocation,
IUniverSheetCopyDataModel,
} from './type';
import { COPY_TYPE } from './type';
@@ -203,7 +202,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
}
if (text) {
- return this._pastePlainText(text);
+ return this._pastePlainText(text, pasteType);
}
this._logService.error('[SheetClipboardService]', 'No valid data on clipboard');
@@ -212,8 +211,8 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
}
addClipboardHook(hook: ISheetClipboardHook): IDisposable {
- if (this._clipboardHooks.findIndex((h) => h.hookName === hook.hookName) !== -1) {
- this._logService.error('[SheetClipboardService]', 'hook already exists', hook.hookName);
+ if (this._clipboardHooks.findIndex((h) => h.id === hook.id) !== -1) {
+ this._logService.error('[SheetClipboardService]', 'hook already exists', hook.id);
return { dispose: () => {} };
}
// hook added should be ordered at meaning while
@@ -243,31 +242,53 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
this._clipboardHooks$.next(this._clipboardHooks);
}
- private async _pastePlainText(text: string): Promise<boolean> {
- // this._logService.log('[SheetClipboardService]', 'pasting plain text content.', text);
-
- // TODO: maybe we should support pasting rich text values here? That is not supported yet.
+ private async _pastePlainText(text: string, pasteType: string): Promise<boolean> {
const target = this._getPastingTarget();
if (!target.selection) {
return false;
}
const range = target.selection.range;
- const cellValue: IObjectMatrixPrimitiveType<ICellData> = {
- [range.startRow]: {
- [range.endColumn]: {
- v: text,
- },
- },
- };
+ const { unitId, subUnitId } = target;
+ const hooks = this._clipboardHooks;
+ const enabledHooks: ISheetClipboardHook[] = [];
+ const disableCopying = hooks.some(
+ (h) => enabledHooks.push(h) && h.onBeforePaste?.({ unitId, subUnitId, range }) === false
+ );
+ if (disableCopying) {
+ enabledHooks.forEach((h) => h.onAfterPaste?.(false));
+ return false;
+ }
- const setRangeValuesParams: ISetRangeValuesMutationParams = {
- unitId: target.unitId,
- subUnitId: target.subUnitId,
- cellValue,
- };
+ const redoMutationsInfo: IMutationInfo[] = [];
+ const undoMutationsInfo: IMutationInfo[] = [];
+ enabledHooks.forEach((h) => {
+ const contentReturn = h.onPastePlainText?.(
+ {
+ unitId,
+ subUnitId,
+ range,
+ },
+ text,
+ {
+ pasteType,
+ }
+ );
+ if (contentReturn) {
+ redoMutationsInfo.push(...contentReturn.redos);
+ undoMutationsInfo.push(...contentReturn.undos);
+ }
+ });
+ const result = redoMutationsInfo.every((m) => this._commandService.executeCommand(m.id, m.params));
+ if (result) {
+ // add to undo redo services
+ this._undoRedoService.pushUndoRedo({
+ unitID: this._currentUniverService.getCurrentUniverSheetInstance().getUnitId(),
+ undoMutations: undoMutationsInfo,
+ redoMutations: redoMutationsInfo,
+ });
+ }
- const result = this._commandService.syncExecuteCommand(SetRangeValuesMutation.id, setRangeValuesParams);
return result;
}
@@ -276,7 +297,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
const copyId = extractId(html);
- if (copyId) {
+ if (copyId && copyContentCache.get(copyId)) {
return this._pasteInternal(copyId, pasteType);
}
return this._pasteExternal(html, pasteType);
@@ -340,8 +361,8 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
const target = this._getPastingTarget();
const { selection, unitId, subUnitId } = target;
const cachedData = Tools.deepClone(copyContentCache.get(copyId));
- const { range, matrix: cellMatrix } = cachedData || {};
- if (!selection || !cellMatrix || !cachedData || !range) {
+ const { range, matrix: cellMatrix, unitId: copyUnitId, subUnitId: copySubUnitId } = cachedData || {};
+ if (!selection || !cellMatrix || !cachedData || !range || !copyUnitId || !copySubUnitId) {
return false;
}
@@ -349,7 +370,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
return false;
}
- const styles = this._currentUniverService.getUniverSheetInstance(unitId)?.getStyles();
+ const styles = this._currentUniverService.getUniverSheetInstance(copyUnitId)?.getStyles();
cellMatrix.forValue((row, col, value) => {
if (typeof value.s === 'string') {
const newValue = Tools.deepClone(value);
@@ -370,8 +391,27 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
return false;
}
+ const worksheet = this._currentUniverService
+ .getUniverSheetInstance(copyUnitId)
+ ?.getSheetBySheetId(copySubUnitId);
+ if (!worksheet) {
+ return false;
+ }
+ const manager = worksheet.getColumnManager();
+ const defaultColumnWidth = worksheet.getConfig().defaultColumnWidth;
+
+ const colProperties = [];
+
+ for (let i = startColumn; i <= endColumn; i++) {
+ const column = manager.getColumnOrCreate(i);
+ colProperties.push({ width: `${column.w || defaultColumnWidth}` });
+ }
+
const pasteRes = this._pasteUSM(
- { cellMatrix }, // paste data
+ {
+ cellMatrix,
+ colProperties,
+ }, // paste data
{
unitId, // paste target
subUnitId,
@@ -400,7 +440,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
data: IUniverSheetCopyDataModel,
target: IPasteTarget,
pasteType: string,
- source?: IPasteSource
+ source?: ISheetRangeLocation & { copyId: string; copyType: COPY_TYPE }
): boolean {
const { rowProperties, colProperties, cellMatrix } = data;
const { unitId, subUnitId, pastedRange } = target;
@@ -409,7 +449,7 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
const hooks = this._clipboardHooks;
const enabledHooks: ISheetClipboardHook[] = [];
const disableCopying = hooks.some(
- (h) => enabledHooks.push(h) && h.onBeforePaste?.(unitId, subUnitId, pastedRange) === false
+ (h) => enabledHooks.push(h) && h.onBeforePaste?.({ unitId, subUnitId, range: pastedRange }) === false
);
if (disableCopying) {
enabledHooks.forEach((h) => h.onAfterPaste?.(false));
@@ -417,27 +457,33 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
}
if (!cellMatrix) return false;
- const copyInfo = source
+ const pasteFrom = source
? {
- copyRange: source.range,
- copyType: source.copyType,
unitId: source.unitId,
subUnitId: source.subUnitId,
+ range: source.range,
}
- : { copyType: COPY_TYPE.COPY };
+ : null;
+
+ const payload = {
+ copyType: source?.copyType || COPY_TYPE.COPY,
+ copyId: source?.copyId,
+ pasteType,
+ };
const redoMutationsInfo: IMutationInfo[] = [];
const undoMutationsInfo: IMutationInfo[] = [];
// if hooks are not special or default, it will be executed in any case.
// other hooks will be executed only when the paste type is the same as the hook name, including the default one
- const filteredHooks: ISheetClipboardHook[] = hooks.filter(
- (h) =>
- (!h.specialPasteInfo && h.hookName !== PREDEFINED_HOOK_NAME.DEFAULT_PASTE) || pasteType === h.hookName
+ const filteredHooks: ISheetClipboardHook[] = enabledHooks.filter(
+ (h) => (!h.specialPasteInfo && h.id !== PREDEFINED_HOOK_NAME.DEFAULT_PASTE) || pasteType === h.id
);
filteredHooks.forEach((h) => {
if (rowProperties) {
- const rowReturn = h.onPasteRows?.(pastedRange, rowProperties, pasteType);
+ const rowReturn = h.onPasteRows?.({ range: pastedRange, unitId, subUnitId }, rowProperties, {
+ pasteType,
+ });
if (rowReturn) {
redoMutationsInfo.push(...rowReturn.redos);
undoMutationsInfo.push(...rowReturn.undos);
@@ -445,16 +491,21 @@ export class SheetClipboardService extends Disposable implements ISheetClipboard
}
const colReturn = h.onPasteColumns?.(
- pastedRange,
+ { range: pastedRange, unitId, subUnitId },
colProperties || new Array(colCount).map(() => ({})),
- pasteType
+ { pasteType }
);
if (colReturn) {
redoMutationsInfo.push(...colReturn.redos);
undoMutationsInfo.push(...colReturn.undos);
}
- const contentReturn = h.onPasteCells?.(pastedRange, cellMatrix, pasteType, copyInfo);
+ const contentReturn = h.onPasteCells?.(
+ pasteFrom,
+ { range: pastedRange, unitId, subUnitId },
+ cellMatrix,
+ payload
+ );
if (contentReturn) {
redoMutationsInfo.push(...contentReturn.redos);
undoMutationsInfo.push(...contentReturn.undos);
diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts
index 1373d688fa..2cd43947ee 100644
--- a/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts
+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/converter.ts
@@ -367,7 +367,7 @@ function parseTableCells(tdStrings: string[]) {
Array.from(cellMatches).forEach((cellMatch) => {
const cellProperties = parseProperties(cellMatch[1]);
- const content = cellMatch[2].replace(/&nbsp;/g, ' '); // paste from excel
+ const content = decodeHTMLEntities(cellMatch[2].replace('<br>', '\r').replace(/<\/?[^>]*>/g, '')); // paste from excel
const rowSpan = cellProperties.rowspan ? +cellProperties.rowspan : 1;
const colSpan = cellProperties.colspan ? +cellProperties.colspan : 1;
@@ -457,3 +457,16 @@ function childNodeToHTML(node: ChildNode) {
const htmlString = serializer.serializeToString(node);
return htmlString;
}
+
+function decodeHTMLEntities(input: string): string {
+ const entities: { [key: string]: string } = {
+ '&lt;': '<',
+ '&gt;': '>',
+ '&amp;': '&',
+ '&quot;': '"',
+ '&#39;': "'",
+ '&nbsp;': ' ',
+ };
+
+ return input.replace(/&lt;|&gt;|&amp;|&quot;|&#39;|&nbsp;|<br>/g, (match) => entities[match]);
+}
diff --git a/packages/sheets-ui/src/services/clipboard/type.ts b/packages/sheets-ui/src/services/clipboard/type.ts
index 287ef72a81..faf5200568 100644
--- a/packages/sheets-ui/src/services/clipboard/type.ts
+++ b/packages/sheets-ui/src/services/clipboard/type.ts
@@ -46,14 +46,17 @@ export interface IPasteTarget {
unitId: string;
}
-export interface IPasteSource {
- copyId: string;
+export interface ICopyPastePayload {
+ copyType?: COPY_TYPE;
+ copyId?: string;
+ pasteType: string;
+}
+
+export interface ISheetRangeLocation {
+ range: IRange;
subUnitId: string;
unitId: string;
- range: IRange;
- copyType: COPY_TYPE;
}
-
export interface ISpecialPasteInfo {
label: string;
icon?: string;
@@ -65,7 +68,7 @@ export interface ISpecialPasteInfo {
* 1. When pasting, get access to the clipboard content and append mutations to the paste command.
*/
export interface ISheetClipboardHook {
- hookName: string;
+ id: string;
isDefaultHook?: boolean;
specialPasteInfo?: ISpecialPasteInfo; // only special paste info should be provided, which will replace the default hook.
priority?: number;
@@ -117,38 +120,41 @@ export interface ISheetClipboardHook {
*
* @returns if it block copying it should return false
*/
- onBeforePaste?(unitId: string, subUnitId: string, range: IRange): boolean;
+ onBeforePaste?(pasteTo: ISheetRangeLocation): boolean;
/**
*
* @param row
* @param col
*/
onPasteCells?(
- pastedRange: IRange,
- matrix: ObjectMatrix<ICellDataWithSpanInfo>,
- pasteType: string,
- copyInfo: {
- copyType: COPY_TYPE;
- copyRange?: IRange;
- subUnitId?: string;
- unitId?: string;
- }
+ pasteFrom: ISheetRangeLocation | null,
+ pasteTo: ISheetRangeLocation,
+ data: ObjectMatrix<ICellDataWithSpanInfo>,
+ payload: ICopyPastePayload
): {
undos: IMutationInfo[];
redos: IMutationInfo[];
};
onPasteRows?(
- range: IRange,
+ pasteTo: ISheetRangeLocation,
rowProperties: IClipboardPropertyItem[],
- pasteType: string
+ payload: ICopyPastePayload
): {
undos: IMutationInfo[];
redos: IMutationInfo[];
};
onPasteColumns?(
- range: IRange,
+ pasteTo: ISheetRangeLocation,
colProperties: IClipboardPropertyItem[],
- pasteType: string
+ payload: ICopyPastePayload
+ ): {
+ undos: IMutationInfo[];
+ redos: IMutationInfo[];
+ };
+ onPastePlainText?(
+ pasteTo: ISheetRangeLocation,
+ text: string,
+ payload: ICopyPastePayload
): {
undos: IMutationInfo[];
redos: IMutationInfo[];
diff --git a/packages/sheets-ui/src/services/clipboard/usm-to-html/convertor.ts b/packages/sheets-ui/src/services/clipboard/usm-to-html/convertor.ts
index 68b4564df8..f7b644b92a 100644
--- a/packages/sheets-ui/src/services/clipboard/usm-to-html/convertor.ts
+++ b/packages/sheets-ui/src/services/clipboard/usm-to-html/convertor.ts
@@ -120,15 +120,24 @@ export class USMToHtmlService {
range: IRange,
hooks: ISheetClipboardHook[]
): string {
- const { startColumn, endColumn } = range;
+ const { startColumn, endColumn, startRow, endRow } = range;
const colStyles = getColStyle(getArrayFromTo(startColumn, endColumn), hooks);
// row styles and table contents
const rowContents: string[] = [];
- matrix.forRow((row, cols) => {
- // TODO: cols here should filtered out those in span cells
+ const {
+ startRow: dataStartRow,
+ endRow: dataEndRow,
+ startColumn: dataStartColumn,
+ endColumn: dataEndColumn,
+ } = matrix.getDataRange();
+ for (let row = dataStartRow; row <= dataEndRow; row++) {
+ const cols = Array.from(
+ { length: dataEndColumn - dataStartColumn + 1 },
+ (_, index) => dataStartColumn + index
+ );
rowContents.push(getRowContent(row, cols, hooks, matrix));
- });
+ }
const html = `<google-sheets-html-origin><table xmlns="http://www.w3.org/1999/xhtml" cellspacing="0" cellpadding="0" dir="ltr" border="1" style="table-layout:fixed;font-size:10pt;font-family:Arial;width:0px;border-collapse:collapse;border:none">${colStyles}
<tbody>${rowContents.join('')}</tbody></table>`;
diff --git a/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts b/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts
index 3c88664ea6..b8c7acfdbd 100644
--- a/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts
+++ b/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts
@@ -77,10 +77,13 @@ export class MarkSelectionService extends Disposable implements IMarkSelectionSe
const currentSubUnitId = this._currentService.getCurrentUniverSheetInstance().getActiveSheet().getSheetId();
this._shapeMap.forEach((shape) => {
const { unitId, subUnitId, selection, control: oldControl, zIndex } = shape;
+
+ oldControl && oldControl.dispose();
+
if (unitId !== currentUnitId || subUnitId !== currentSubUnitId) {
- oldControl && oldControl.dispose();
return;
}
+
const { style } = selection;
const { scene } = this._renderManagerService.getRenderById(unitId) || {};
const { rangeWithCoord, primaryWithCoord } =
diff --git a/packages/sheets/src/commands/commands/move-range.command.ts b/packages/sheets/src/commands/commands/move-range.command.ts
index c46082d11f..57fcb9d836 100644
--- a/packages/sheets/src/commands/commands/move-range.command.ts
+++ b/packages/sheets/src/commands/commands/move-range.command.ts
@@ -39,7 +39,7 @@ export const MoveRangeCommandId = 'sheet.command.move-range';
export const MoveRangeCommand: ICommand = {
type: CommandType.COMMAND,
id: MoveRangeCommandId,
- handler: async (accessor: IAccessor, params: IMoveRangeCommandParams) => {
+ handler: (accessor: IAccessor, params: IMoveRangeCommandParams) => {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const univerInstanceService = accessor.get(IUniverInstanceService);
@@ -80,16 +80,26 @@ export const MoveRangeCommand: ICommand = {
}, new ObjectMatrix<Nullable<ICellData>>());
const doMoveRangeMutation: IMoveRangeMutationParams = {
- from: newFromCellValues.getMatrix(),
- to: newToCellValues.getMatrix(),
+ from: {
+ value: newFromCellValues.getMatrix(),
+ subUnitId,
+ },
+ to: {
+ value: newToCellValues.getMatrix(),
+ subUnitId,
+ },
unitId,
- subUnitId,
};
const undoMoveRangeMutation: IMoveRangeMutationParams = {
- from: currentFromCellValues.getMatrix(),
- to: currentToCellValues.getMatrix(),
+ from: {
+ value: currentFromCellValues.getMatrix(),
+ subUnitId,
+ },
+ to: {
+ value: currentToCellValues.getMatrix(),
+ subUnitId,
+ },
unitId,
- subUnitId,
};
const interceptorCommands = sheetInterceptorService.onCommandExecute({ id: MoveRangeCommand.id, params });
@@ -120,7 +130,7 @@ export const MoveRangeCommand: ICommand = {
{ id: MoveRangeMutation.id, params: undoMoveRangeMutation },
];
- const result = await sequenceExecute(redos, commandService).result;
+ const result = sequenceExecute(redos, commandService).result;
if (result) {
undoRedoService.pushUndoRedo({
unitID: unitId,
diff --git a/packages/sheets/src/commands/mutations/move-range.mutation.ts b/packages/sheets/src/commands/mutations/move-range.mutation.ts
index 17a6dd88c3..f66e5c375e 100644
--- a/packages/sheets/src/commands/mutations/move-range.mutation.ts
+++ b/packages/sheets/src/commands/mutations/move-range.mutation.ts
@@ -19,9 +19,14 @@ import { CommandType, IUniverInstanceService, ObjectMatrix } from '@univerjs/cor
export interface IMoveRangeMutationParams {
unitId: string;
- subUnitId: string;
- from: IObjectMatrixPrimitiveType<Nullable<ICellData>>;
- to: IObjectMatrixPrimitiveType<Nullable<ICellData>>;
+ from: {
+ subUnitId: string;
+ value: IObjectMatrixPrimitiveType<Nullable<ICellData>>;
+ };
+ to: {
+ subUnitId: string;
+ value: IObjectMatrixPrimitiveType<Nullable<ICellData>>;
+ };
}
export const MoveRangeMutation: IMutation<IMoveRangeMutationParams, boolean> = {
@@ -40,19 +45,22 @@ export const MoveRangeMutation: IMutation<IMoveRangeMutationParams, boolean> = {
return false;
}
- const worksheet = workbook.getSheetBySheetId(params.subUnitId);
- if (!worksheet) {
+ const fromWorksheet = workbook.getSheetBySheetId(params.from.subUnitId);
+ const toWorksheet = workbook.getSheetBySheetId(params.to.subUnitId);
+
+ if (!fromWorksheet || !toWorksheet) {
return false;
}
- const cellMatrix = worksheet.getCellMatrix();
+ const fromCellMatrix = fromWorksheet.getCellMatrix();
+ const toCellMatrix = toWorksheet.getCellMatrix();
- new ObjectMatrix<Nullable<ICellData>>(from).forValue((row, col, newVal) => {
- cellMatrix.setValue(row, col, newVal);
+ new ObjectMatrix<Nullable<ICellData>>(from.value).forValue((row, col, newVal) => {
+ fromCellMatrix.setValue(row, col, newVal);
});
- new ObjectMatrix<Nullable<ICellData>>(to).forValue((row, col, newVal) => {
- cellMatrix.setValue(row, col, newVal);
+ new ObjectMatrix<Nullable<ICellData>>(to.value).forValue((row, col, newVal) => {
+ toCellMatrix.setValue(row, col, newVal);
});
return true;