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&paste (#1006)

YuHong36fdeed2a4fe
diff --git a/packages/engine-render/src/components/sheets/sheet-skeleton.ts b/packages/engine-render/src/components/sheets/sheet-skeleton.ts
index 11bc87a3c4..de7f29cc73 100644
--- a/packages/engine-render/src/components/sheets/sheet-skeleton.ts
+++ b/packages/engine-render/src/components/sheets/sheet-skeleton.ts
@@ -1699,7 +1699,7 @@ export class SpreadsheetSkeleton extends Skeleton {
} = config;
const { a: angle = 0, v: isVertical = BooleanNumber.FALSE } = textRotation;
- const { t: marginTop, r: marginRight, b: marginBottom, l: marginLeft } = paddingData;
+ const { t: marginTop, r: marginRight, b: marginBottom, l: marginLeft } = paddingData || {};
let centerAngle = 0;
let vertexAngle = angle;
diff --git a/packages/sheets-formula/src/commands/operations/insert-function.operation.ts b/packages/sheets-formula/src/commands/operations/insert-function.operation.ts
index edfcf8b181..82228dcb59 100644
--- a/packages/sheets-formula/src/commands/operations/insert-function.operation.ts
+++ b/packages/sheets-formula/src/commands/operations/insert-function.operation.ts
@@ -144,7 +144,7 @@ export const InsertFunctionOperation: ICommand = {
const setSelectionParams = {
unitId,
- sheetId,
+ subUnitId: sheetId,
pluginName: NORMAL_SELECTION_PLUGIN_NAME,
selections: [resultRange],
};
diff --git a/packages/sheets-ui/package.json b/packages/sheets-ui/package.json
index b9e931fa96..7f234f9be5 100644
--- a/packages/sheets-ui/package.json
+++ b/packages/sheets-ui/package.json
@@ -55,6 +55,7 @@
"@univerjs/icons": "^0.1.24",
"@univerjs/sheets": "workspace:*",
"@univerjs/ui": "workspace:*",
+ "@univerjs/engine-numfmt": "workspace:*",
"@wendellhu/redi": "^0.12.13",
"clsx": "^2.0.0",
"react": "^18.2.0",
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts
index ff913064ea..081094bb1b 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/auto-fill.controller.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { Univer } from '@univerjs/core';
+import type { ICellData, IStyleData, Nullable, Univer } from '@univerjs/core';
import {
CellValueType,
ICommandService,
@@ -37,9 +37,11 @@ import { beforeEach, describe, expect, it } from 'vitest';
import { AutoFillController } from '../../../controllers/auto-fill.controller';
import { AutoFillService, IAutoFillService } from '../../../services/auto-fill/auto-fill.service';
+import { APPLY_TYPE } from '../../../services/auto-fill/type';
import { EditorBridgeService, IEditorBridgeService } from '../../../services/editor-bridge.service';
import { ISelectionRenderService, SelectionRenderService } from '../../../services/selection/selection-render.service';
import { SheetSkeletonManagerService } from '../../../services/sheet-skeleton-manager.service';
+import { RefillCommand } from '../refill.command';
const theme = {
colorBlack: '#35322b',
@@ -56,12 +58,10 @@ const TEST_WORKBOOK_DATA = {
'0': {
'0': {
v: 1,
- m: '1',
t: CellValueType.NUMBER,
},
'1': {
v: 2,
- m: '2',
t: CellValueType.NUMBER,
},
},
@@ -69,12 +69,10 @@ const TEST_WORKBOOK_DATA = {
'1': {
'0': {
v: 2,
- m: '2',
t: CellValueType.NUMBER,
},
'1': {
v: 1,
- m: '1',
t: CellValueType.NUMBER,
},
},
@@ -82,12 +80,10 @@ const TEST_WORKBOOK_DATA = {
'2': {
'0': {
v: '第1',
- m: '第1',
t: CellValueType.STRING,
},
'1': {
v: '第2',
- m: '第2',
t: CellValueType.STRING,
},
},
@@ -95,12 +91,10 @@ const TEST_WORKBOOK_DATA = {
'3': {
'0': {
v: '一',
- m: '一',
t: CellValueType.STRING,
},
'1': {
v: '三',
- m: '三',
t: CellValueType.STRING,
},
},
@@ -108,12 +102,10 @@ const TEST_WORKBOOK_DATA = {
'4': {
'0': {
v: '星期一',
- m: '星期一',
t: CellValueType.STRING,
},
'1': {
v: '星期三',
- m: '星期三',
t: CellValueType.STRING,
},
},
@@ -121,12 +113,10 @@ const TEST_WORKBOOK_DATA = {
'5': {
'0': {
v: '甲',
- m: '甲',
t: CellValueType.STRING,
},
'1': {
v: '乙',
- m: '乙',
t: CellValueType.STRING,
},
},
@@ -134,12 +124,10 @@ const TEST_WORKBOOK_DATA = {
'6': {
'0': {
v: 'copy only',
- m: 'copy only',
t: CellValueType.STRING,
},
'1': {
v: 'no series',
- m: 'no series',
t: CellValueType.STRING,
},
},
@@ -147,22 +135,18 @@ const TEST_WORKBOOK_DATA = {
'7': {
'0': {
v: 1,
- m: '1',
t: CellValueType.NUMBER,
},
'1': {
v: 2,
- m: '2',
t: CellValueType.NUMBER,
},
'2': {
v: '第1',
- m: '第1',
t: CellValueType.STRING,
},
'3': {
v: '第2',
- m: '第2',
t: CellValueType.STRING,
},
},
@@ -170,51 +154,60 @@ const TEST_WORKBOOK_DATA = {
'10': {
'0': {
v: 1,
- m: '1',
t: CellValueType.NUMBER,
},
'1': {
v: 2,
- m: '2',
t: CellValueType.NUMBER,
},
'2': {
v: 3,
- m: '3',
t: CellValueType.NUMBER,
},
'3': {
v: 4,
- m: '4',
t: CellValueType.NUMBER,
},
},
'11': {
'0': {
v: 2,
- m: '2',
t: CellValueType.NUMBER,
},
'2': {
v: 3,
- m: '3',
t: CellValueType.NUMBER,
},
},
'12': {
'0': {
v: 3,
- m: '3',
t: CellValueType.NUMBER,
},
},
'13': {
'0': {
v: 4,
- m: '4',
t: CellValueType.NUMBER,
},
},
+ // left direction & equal ratio & styles
+ '14': {
+ '2': {
+ v: 2,
+ t: CellValueType.NUMBER,
+ s: '_aRLOe',
+ },
+ '3': {
+ v: 4,
+ t: CellValueType.NUMBER,
+ },
+ '4': {
+ v: 8,
+ t: CellValueType.NUMBER,
+ s: '3UpAbI',
+ },
+ },
},
},
},
@@ -225,7 +218,20 @@ const TEST_WORKBOOK_DATA = {
modifiedTime: '',
name: '',
sheetOrder: [],
- styles: {},
+ styles: {
+ _aRLOe: {
+ bg: {
+ rgb: '#ccc',
+ },
+ ht: 2,
+ vt: 2,
+ },
+ '3UpAbI': {
+ bg: {
+ rgb: '#eee',
+ },
+ },
+ },
timeZone: '',
};
@@ -235,6 +241,18 @@ describe('Test auto fill rules in controller', () => {
let commandService: ICommandService;
let autoFillController: AutoFillController;
let themeService: ThemeService;
+ let getValues: (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ) => Array<Array<Nullable<ICellData>>> | undefined;
+ let getStyles: (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ) => Array<Array<Nullable<IStyleData>>> | undefined;
beforeEach(() => {
const testBed = createCommandTestBed(TEST_WORKBOOK_DATA, [
[ISelectionRenderService, { useClass: SelectionRenderService }],
@@ -256,6 +274,32 @@ describe('Test auto fill rules in controller', () => {
commandService.registerCommand(SetSelectionsOperation);
commandService.registerCommand(RemoveWorksheetMergeMutation);
commandService.registerCommand(AddWorksheetMergeMutation);
+ commandService.registerCommand(RefillCommand);
+
+ getValues = (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ): Array<Array<Nullable<ICellData>>> | undefined =>
+ get(IUniverInstanceService)
+ .getUniverSheetInstance('test')
+ ?.getSheetBySheetId('sheet1')
+ ?.getRange(startRow, startColumn, endRow, endColumn)
+ .getValues();
+
+ getStyles = (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ): Array<Array<Nullable<IStyleData>>> | undefined => {
+ const values = getValues(startRow, startColumn, endRow, endColumn);
+ const styles = get(IUniverInstanceService).getUniverSheetInstance('test')?.getStyles();
+ if (values && styles) {
+ return values.map((row) => row.map((cell) => styles.getStyleByCell(cell)));
+ }
+ };
});
describe('auto fill', () => {
@@ -488,4 +532,151 @@ describe('Test auto fill rules in controller', () => {
expect(workbook.getSheetBySheetId('sheet1')?.getCell(13, 1)?.v).toBe(5);
});
});
+
+ describe('auto fill in left direction', async () => {
+ it('correct situation', async () => {
+ const workbook = get(IUniverInstanceService).getCurrentUniverSheetInstance();
+ if (!workbook) throw new Error('This is an error');
+ // test other string
+ (autoFillController as any)._triggerAutoFill(
+ {
+ startRow: 14,
+ startColumn: 2,
+ endRow: 14,
+ endColumn: 4,
+ },
+ {
+ startRow: 14,
+ startColumn: 0,
+ endRow: 14,
+ endColumn: 4,
+ }
+ );
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(14, 0)?.v).toBe(0.5);
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(14, 1)?.v).toBe(1);
+ // undo redo
+ await commandService.executeCommand(UndoCommand.id);
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(14, 0)?.v).toBe(undefined);
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(14, 1)?.v).toBe(undefined);
+
+ await commandService.executeCommand(RedoCommand.id);
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(14, 0)?.v).toBe(0.5);
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(14, 1)?.v).toBe(1);
+ });
+ });
+
+ describe('auto fill with equal ratio & style', async () => {
+ it('correct situation', async () => {
+ const workbook = get(IUniverInstanceService).getCurrentUniverSheetInstance();
+ if (!workbook) throw new Error('This is an error');
+ // equal ratio
+ (autoFillController as any)._triggerAutoFill(
+ {
+ startRow: 14,
+ startColumn: 2,
+ endRow: 14,
+ endColumn: 4,
+ },
+ {
+ startRow: 14,
+ startColumn: 2,
+ endRow: 14,
+ endColumn: 7,
+ }
+ );
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(14, 5)?.v).toBe(16);
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(14, 6)?.v).toBe(32);
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(14, 7)?.v).toBe(64);
+ const styles = getStyles(14, 5, 14, 7);
+ expect(styles && styles[0][0]).toStrictEqual({
+ bg: {
+ rgb: '#ccc',
+ },
+ ht: 2,
+ vt: 2,
+ });
+ expect(styles && styles[0][1]).toStrictEqual(undefined);
+ expect(styles && styles[0][2]).toStrictEqual({
+ bg: {
+ rgb: '#eee',
+ },
+ });
+
+ // undo redo
+ await commandService.executeCommand(UndoCommand.id);
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(14, 5)?.v).toBe(undefined);
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(14, 6)?.v).toBe(undefined);
+
+ await commandService.executeCommand(RedoCommand.id);
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(14, 5)?.v).toBe(16);
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(14, 6)?.v).toBe(32);
+ });
+ });
+
+ describe('auto fill without format', async () => {
+ it('correct situation', async () => {
+ const workbook = get(IUniverInstanceService).getCurrentUniverSheetInstance();
+ if (!workbook) throw new Error('This is an error');
+ // equal ratio
+ (autoFillController as any)._triggerAutoFill(
+ {
+ startRow: 14,
+ startColumn: 2,
+ endRow: 14,
+ endColumn: 3,
+ },
+ {
+ startRow: 14,
+ startColumn: 2,
+ endRow: 14,
+ endColumn: 4,
+ }
+ );
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(14, 4)?.v).toBe(6);
+ const styles = getStyles(14, 4, 14, 4);
+ expect(styles && styles[0][0]).toStrictEqual({
+ bg: {
+ rgb: '#ccc',
+ },
+ ht: 2,
+ vt: 2,
+ });
+
+ commandService.executeCommand(RefillCommand.id, { type: APPLY_TYPE.NO_FORMAT });
+
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(14, 4)?.v).toBe(6);
+ const styles_refill = getStyles(14, 4, 14, 4);
+ expect(styles_refill && styles_refill[0][0]).toStrictEqual({
+ bg: {
+ rgb: '#eee',
+ },
+ ht: null,
+ vt: null,
+ });
+
+ // undo redo
+ await commandService.executeCommand(UndoCommand.id);
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(14, 4)?.v).toBe(6);
+ const styles_undo = getStyles(14, 4, 14, 4);
+ expect(styles_undo && styles_undo[0][0]).toStrictEqual({
+ bg: {
+ rgb: '#ccc',
+ },
+ ht: 2,
+ vt: 2,
+ });
+
+ // redo
+ await commandService.executeCommand(RedoCommand.id);
+ expect(workbook.getSheetBySheetId('sheet1')?.getCell(14, 4)?.v).toBe(6);
+ const styles_redo = getStyles(14, 4, 14, 4);
+ expect(styles_redo && styles_redo[0][0]).toStrictEqual({
+ bg: {
+ rgb: '#eee',
+ },
+ ht: null,
+ vt: null,
+ });
+ });
+ });
});
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 2c1352ef20..d66bdbedd8 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
@@ -187,6 +187,10 @@ class MarkSelectionService extends Disposable implements IMarkSelectionService {
removeShape(id: string): void {}
removeAllShapes(): void {}
+
+ getShapeMap(): Map<string, any> {
+ return new Map();
+ }
}
class SelectionRenderService {
diff --git a/packages/sheets-ui/src/commands/commands/set-selection.command.ts b/packages/sheets-ui/src/commands/commands/set-selection.command.ts
index fe558ff732..24d6bd218c 100644
--- a/packages/sheets-ui/src/commands/commands/set-selection.command.ts
+++ b/packages/sheets-ui/src/commands/commands/set-selection.command.ts
@@ -97,7 +97,7 @@ export const MoveSelectionCommand: ICommand<IMoveSelectionCommandParams> = {
return accessor.get(ICommandService).executeCommand(SetSelectionsOperation.id, {
unitId: workbook.getUnitId(),
- sheetId: worksheet.getSheetId(),
+ subUnitId: worksheet.getSheetId(),
pluginName: NORMAL_SELECTION_PLUGIN_NAME,
selections: [
{
@@ -252,7 +252,7 @@ export const MoveSelectionEnterAndTabCommand: ICommand<IMoveSelectionEnterAndTab
return accessor.get(ICommandService).executeCommand(SetSelectionsOperation.id, {
unitId,
- sheetId,
+ subUnitId: sheetId,
pluginName: NORMAL_SELECTION_PLUGIN_NAME,
selections: [resultRange],
});
@@ -308,7 +308,7 @@ export const ExpandSelectionCommand: ICommand<IExpandSelectionCommandParams> = {
return accessor.get(ICommandService).executeCommand(SetSelectionsOperation.id, {
unitId: currentWorkbook.getUnitId(),
- sheetId: currentWorksheet.getSheetId(),
+ subUnitId: currentWorksheet.getSheetId(),
pluginName: NORMAL_SELECTION_PLUGIN_NAME,
selections: [
{
@@ -399,7 +399,7 @@ export const SelectAllCommand: ICommand<ISelectAllCommandParams> = {
return accessor.get(ICommandService).executeCommand(SetSelectionsOperation.id, {
unitId: workbook.getUnitId(),
- sheetId: worksheet.getSheetId(),
+ subUnitId: worksheet.getSheetId(),
pluginName: NORMAL_SELECTION_PLUGIN_NAME,
selections: [
{
diff --git a/packages/sheets-ui/src/controllers/auto-fill.controller.ts b/packages/sheets-ui/src/controllers/auto-fill.controller.ts
index d241cf5df9..c5137291b6 100644
--- a/packages/sheets-ui/src/controllers/auto-fill.controller.ts
+++ b/packages/sheets-ui/src/controllers/auto-fill.controller.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICellData, IMutationInfo, IRange, Nullable } from '@univerjs/core';
+import type { ICellData, ICommandInfo, IMutationInfo, IRange, Nullable } from '@univerjs/core';
import {
Direction,
Disposable,
@@ -116,85 +116,86 @@ export class AutoFillController extends Disposable {
private _onSelectionControlFillChanged() {
const disposableCollection = new DisposableCollection();
this.disposeWithMe(
- toDisposable(
- this._selectionManagerService.selectionMoveEnd$.subscribe(() => {
- // Each range change requires re-listening
- disposableCollection.dispose();
-
- const current = this._selectionManagerService.getCurrent();
-
- /**
- * Auto fill only responds to regular selections;
- * it does not apply to selections for features like formulas or charts.
- */
- if (current?.pluginName !== NORMAL_SELECTION_PLUGIN_NAME) {
- return;
- }
+ this._commandService.onCommandExecuted((command: ICommandInfo) => {
+ if (command.id !== SetSelectionsOperation.id) {
+ return;
+ }
- const selectionControls = this._selectionRenderService.getCurrentControls();
- selectionControls.forEach((controlSelection) => {
- disposableCollection.add(
- toDisposable(
- controlSelection.selectionFilled$.subscribe((filled) => {
- if (
- filled == null ||
- filled.startColumn === -1 ||
- filled.startRow === -1 ||
- filled.endColumn === -1 ||
- filled.endRow === -1
- ) {
- return;
- }
- const source: IRange = {
- startColumn: controlSelection.model.startColumn,
- endColumn: controlSelection.model.endColumn,
- startRow: controlSelection.model.startRow,
- endRow: controlSelection.model.endRow,
- };
- const selection: IRange = {
- startColumn: filled.startColumn,
- endColumn: filled.endColumn,
- startRow: filled.startRow,
- endRow: filled.endRow,
- };
-
- this._triggerAutoFill(source, selection);
- })
- )
- );
-
- // double click to fill range, range length will align to left or right column.
- // fill results will be as same as drag operation
- disposableCollection.add(
- toDisposable(
- controlSelection.fillControl.onDblclickObserver.add(() => {
- const source = {
- startColumn: controlSelection.model.startColumn,
- endColumn: controlSelection.model.endColumn,
- startRow: controlSelection.model.startRow,
- endRow: controlSelection.model.endRow,
- };
- this._handleDbClickFill(source);
- })
- )
- );
-
- disposableCollection.add(
- toDisposable(
- controlSelection.fillControl.onPointerDownObserver.add(() => {
- const visibleState = this._editorBridgeService.isVisible();
- if (visibleState.visible) {
- this._editorBridgeService.changeVisible({
- visible: false,
- eventType: DeviceInputEventType.PointerDown,
- });
- }
- })
- )
- );
- });
- })
- )
+ /**
+ * Auto fill only responds to regular selections;
+ * it does not apply to selections for features like formulas or charts.
+ */
+ const current = this._selectionManagerService.getCurrent();
+ if (current?.pluginName !== NORMAL_SELECTION_PLUGIN_NAME) {
+ return;
+ }
+
+ // Each range change requires re-listening
+ disposableCollection.dispose();
+
+ const selectionControls = this._selectionRenderService.getCurrentControls();
+ selectionControls.forEach((controlSelection) => {
+ disposableCollection.add(
+ toDisposable(
+ controlSelection.selectionFilled$.subscribe((filled) => {
+ if (
+ filled == null ||
+ filled.startColumn === -1 ||
+ filled.startRow === -1 ||
+ filled.endColumn === -1 ||
+ filled.endRow === -1
+ ) {
+ return;
+ }
+ const source: IRange = {
+ startColumn: controlSelection.model.startColumn,
+ endColumn: controlSelection.model.endColumn,
+ startRow: controlSelection.model.startRow,
+ endRow: controlSelection.model.endRow,
+ };
+ const selection: IRange = {
+ startColumn: filled.startColumn,
+ endColumn: filled.endColumn,
+ startRow: filled.startRow,
+ endRow: filled.endRow,
+ };
+
+ this._triggerAutoFill(source, selection);
+ })
+ )
+ );
+
+ // double click to fill range, range length will align to left or right column.
+ // fill results will be as same as drag operation
+ disposableCollection.add(
+ toDisposable(
+ controlSelection.fillControl.onDblclickObserver.add(() => {
+ const source = {
+ startColumn: controlSelection.model.startColumn,
+ endColumn: controlSelection.model.endColumn,
+ startRow: controlSelection.model.startRow,
+ endRow: controlSelection.model.endRow,
+ };
+ this._handleDbClickFill(source);
+ })
+ )
+ );
+
+ disposableCollection.add(
+ toDisposable(
+ controlSelection.fillControl.onPointerDownObserver.add(() => {
+ const visibleState = this._editorBridgeService.isVisible();
+ if (visibleState.visible) {
+ this._editorBridgeService.changeVisible({
+ visible: false,
+ eventType: DeviceInputEventType.PointerDown,
+ });
+ }
+ })
+ )
+ );
+ });
+ })
);
}
@@ -649,8 +650,8 @@ export class AutoFillController extends Disposable {
windowEndColumn += csLen;
}
} else if (direction === Direction.LEFT) {
- const windowStartColumn = startColumn - csLen;
- const windowEndColumn = endColumn - csLen;
+ let windowStartColumn = startColumn - csLen;
+ let windowEndColumn = endColumn - csLen;
while (windowStartColumn >= target.startColumn) {
applyMergeRanges.push({
startRow,
@@ -658,6 +659,8 @@ export class AutoFillController extends Disposable {
endRow,
endColumn: windowEndColumn,
});
+ windowStartColumn -= csLen;
+ windowEndColumn -= csLen;
}
}
}
@@ -699,6 +702,7 @@ export class AutoFillController extends Disposable {
let hasStyle = true;
if (applyType === APPLY_TYPE.NO_FORMAT) {
hasStyle = false;
+ applyType = APPLY_TYPE.SERIES;
}
const { source, target, unitId, subUnitId } = location;
@@ -794,6 +798,20 @@ export class AutoFillController extends Disposable {
});
}
+ if (applyType === APPLY_TYPE.ONLY_FORMAT) {
+ applyDatas.forEach((row, rowIndex) => {
+ row.forEach((cellData, colIndex) => {
+ if (cellData) {
+ const old = this._beforeApplyData[rowIndex][colIndex] || {};
+ cellData.f = old.f;
+ cellData.si = old.si;
+ cellData.t = old.t;
+ cellData.v = old.v;
+ }
+ });
+ });
+ }
+
const accessor = {
get: this._injector.get.bind(this._injector),
};
diff --git a/packages/sheets-ui/src/controllers/clipboard/utils.ts b/packages/sheets-ui/src/controllers/clipboard/utils.ts
index 0823639eba..7308579d94 100644
--- a/packages/sheets-ui/src/controllers/clipboard/utils.ts
+++ b/packages/sheets-ui/src/controllers/clipboard/utils.ts
@@ -15,7 +15,7 @@
*/
import type { ICellData, IMutationInfo, IRange, Nullable } from '@univerjs/core';
-import { IUniverInstanceService, ObjectMatrix, Rectangle } from '@univerjs/core';
+import { IUniverInstanceService, ObjectMatrix, Range, Rectangle } from '@univerjs/core';
import type {
IAddWorksheetMergeMutationParams,
IMoveRangeMutationParams,
@@ -25,6 +25,7 @@ import type {
import {
AddMergeUndoMutationFactory,
AddWorksheetMergeMutation,
+ getAddMergeMutationRangeByType,
MoveRangeCommand,
MoveRangeMutation,
NORMAL_SELECTION_PLUGIN_NAME,
@@ -99,10 +100,11 @@ export function getMoveRangeMutations(
},
accessor: IAccessor
) {
- let redoMutationsInfo: IMutationInfo[] = [];
- let undoMutationsInfo: IMutationInfo[] = [];
+ let redos: IMutationInfo[] = [];
+ let undos: IMutationInfo[] = [];
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);
@@ -110,52 +112,54 @@ export function getMoveRangeMutations(
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(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(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(toRange.startRow + rowIndex, toRange.startColumn + colIndex, colItem);
- });
- return res;
- }, new ObjectMatrix<Nullable<ICellData>>());
- const currentToCellValues = toWorksheet
- .getRange(toRange)
- .getValues()
- .reduce((res, row, rowIndex) => {
- row.forEach((colItem, colIndex) => {
- res.setValue(toRange.startRow + rowIndex, toRange.startColumn + colIndex, colItem);
- });
- return res;
- }, new ObjectMatrix<Nullable<ICellData>>());
+ const fromCellValue = new ObjectMatrix<Nullable<ICellData>>();
+ const newFromCellValue = new ObjectMatrix<Nullable<ICellData>>();
+ const cellToRange = (row: number, col: number) => ({
+ startRow: row,
+ endRow: row,
+ startColumn: col,
+ endColumn: col,
+ });
+ const fromCellMatrix = fromWorksheet.getCellMatrix();
+ const toCellMatrix = toWorksheet.getCellMatrix();
+
+ Range.foreach(fromRange, (row, col) => {
+ fromCellValue.setValue(row, col, 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));
+ });
+
+ const newToCellValue = new ObjectMatrix<Nullable<ICellData>>();
+
+ Range.foreach(fromRange, (row, col) => {
+ const cellRange = cellToRange(row, col);
+ const relativeRange = Rectangle.getRelativeRange(cellRange, fromRange);
+ const range = Rectangle.getPositionRange(relativeRange, toRange);
+ newToCellValue.setValue(range.startRow, range.startColumn, fromCellMatrix.getValue(row, col));
+ });
const doMoveRangeMutation: IMoveRangeMutationParams = {
from: {
- value: newFromCellValues.getMatrix(),
+ value: newFromCellValue.getMatrix(),
subUnitId: fromSubUnitId,
},
- to: { value: newToCellValues.getMatrix(), subUnitId: toSubUnitId },
+ to: {
+ value: newToCellValue.getMatrix(),
+ subUnitId: toSubUnitId,
+ },
unitId,
};
const undoMoveRangeMutation: IMoveRangeMutationParams = {
from: {
- value: currentFromCellValues.getMatrix(),
+ value: fromCellValue.getMatrix(),
subUnitId: fromSubUnitId,
},
to: {
- value: currentToCellValues.getMatrix(),
+ value: toCellValue.getMatrix(),
subUnitId: toSubUnitId,
},
unitId,
@@ -165,9 +169,84 @@ export function getMoveRangeMutations(
params: { toRange, fromRange },
});
- redoMutationsInfo = [
+ // handle merge mutations
+ const fromMergeData = fromWorksheet.getMergeData();
+ const toMergeData = toWorksheet.getMergeData();
+ const fromMergeRanges = fromMergeData.filter((item) => Rectangle.intersects(item, fromRange));
+ const toMergeRanges = toMergeData.filter((item) => Rectangle.intersects(item, toRange));
+
+ const willMoveToMergeRanges = fromMergeRanges
+ .map((mergeRange) => Rectangle.getRelativeRange(mergeRange, fromRange))
+ .map((relativeRange) => Rectangle.getPositionRange(relativeRange, toRange));
+
+ const addMergeCellRanges = getAddMergeMutationRangeByType(willMoveToMergeRanges).filter(
+ (range) => !toMergeData.some((mergeRange) => Rectangle.equals(range, mergeRange))
+ );
+
+ const mergeRedos: Array<{
+ id: string;
+ params: IAddWorksheetMergeMutationParams | IRemoveWorksheetMergeMutationParams;
+ }> = [
+ {
+ id: RemoveWorksheetMergeMutation.id,
+ params: {
+ unitId,
+ subUnitId: fromSubUnitId,
+ ranges: fromMergeRanges,
+ },
+ },
+ {
+ id: RemoveWorksheetMergeMutation.id,
+ params: {
+ unitId,
+ subUnitId: fromSubUnitId,
+ ranges: toMergeRanges,
+ },
+ },
+ {
+ id: AddWorksheetMergeMutation.id,
+ params: {
+ unitId,
+ subUnitId: toSubUnitId,
+ ranges: addMergeCellRanges,
+ },
+ },
+ ];
+ const mergeUndos: Array<{
+ id: string;
+ params: IAddWorksheetMergeMutationParams | IRemoveWorksheetMergeMutationParams;
+ }> = [
+ {
+ id: RemoveWorksheetMergeMutation.id,
+ params: {
+ unitId,
+ subUnitId: toSubUnitId,
+ ranges: addMergeCellRanges,
+ },
+ },
+ {
+ id: AddWorksheetMergeMutation.id,
+ params: {
+ unitId,
+ subUnitId: toSubUnitId,
+ ranges: toMergeRanges,
+ },
+ },
+ {
+ id: AddWorksheetMergeMutation.id,
+ params: {
+ unitId,
+ subUnitId: fromSubUnitId,
+ ranges: fromMergeRanges,
+ },
+ },
+ ];
+ // +++++++++++++++++++++
+
+ redos = [
{ id: MoveRangeMutation.id, params: doMoveRangeMutation },
...interceptorCommands.redos,
+ ...mergeRedos,
{
id: SetSelectionsOperation.id,
params: {
@@ -178,7 +257,7 @@ export function getMoveRangeMutations(
},
},
];
- undoMutationsInfo = [
+ undos = [
{
id: SetSelectionsOperation.id,
params: {
@@ -189,14 +268,15 @@ export function getMoveRangeMutations(
},
},
...interceptorCommands.undos,
+ ...mergeUndos,
{ id: MoveRangeMutation.id, params: undoMoveRangeMutation },
];
}
}
return {
- undos: undoMutationsInfo,
- redos: redoMutationsInfo,
+ undos,
+ redos,
};
}
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 b3818bea4f..0be244dc8e 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
@@ -120,8 +120,9 @@ export class FormatPainterController extends Disposable {
endRow: merge.endRow - startRow,
endColumn: merge.endColumn - startColumn,
};
- const rowRepeats = Math.floor((range.endRow - range.startRow + 1) / styleRowsNum);
- const colRepeats = Math.floor((range.endColumn - range.startColumn + 1) / styleColsNum);
+ // merge will apply at least once
+ const rowRepeats = Math.max(1, Math.floor((range.endRow - range.startRow + 1) / styleRowsNum));
+ const colRepeats = Math.max(1, Math.floor((range.endColumn - range.startColumn + 1) / styleColsNum));
for (let i = 0; i < rowRepeats; i++) {
for (let j = 0; j < colRepeats; j++) {
mergeRanges.push({
diff --git a/packages/sheets-ui/src/controllers/mark-selection.controller.ts b/packages/sheets-ui/src/controllers/mark-selection.controller.ts
index ddb9441093..e10515f240 100644
--- a/packages/sheets-ui/src/controllers/mark-selection.controller.ts
+++ b/packages/sheets-ui/src/controllers/mark-selection.controller.ts
@@ -44,6 +44,13 @@ export class MarkSelectionController extends Disposable {
this._commandService.onCommandExecuted((command: ICommandInfo) => {
if (removeCommands.includes(command.id)) {
this._markSelectionService.removeAllShapes();
+ } else {
+ const shapes = this._markSelectionService.getShapeMap();
+ shapes.forEach((shape, id) => {
+ if (shape.exits.includes(command.id)) {
+ this._markSelectionService.removeShape(id);
+ }
+ });
}
})
);
diff --git a/packages/sheets-ui/src/controllers/status-bar.controller.ts b/packages/sheets-ui/src/controllers/status-bar.controller.ts
index 70c9df736a..91daada9ba 100644
--- a/packages/sheets-ui/src/controllers/status-bar.controller.ts
+++ b/packages/sheets-ui/src/controllers/status-bar.controller.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICommandInfo, IRange } from '@univerjs/core';
+import type { ICommandInfo, IRange, ISelectionCell, Nullable } from '@univerjs/core';
import {
Disposable,
ICommandService,
@@ -31,7 +31,7 @@ import {
IFunctionService,
RangeReferenceObject,
} from '@univerjs/engine-formula';
-import { SelectionManagerService, SetRangeValuesMutation } from '@univerjs/sheets';
+import { INumfmtService, SelectionManagerService, SetRangeValuesMutation } from '@univerjs/sheets';
import { Inject } from '@wendellhu/redi';
import type { IStatusBarServiceStatus } from '../services/status-bar.service';
@@ -46,7 +46,8 @@ export class StatusBarController extends Disposable {
@IFunctionService private readonly _functionService: IFunctionService,
@IStatusBarService private readonly _statusBarService: IStatusBarService,
@ICommandService private readonly _commandService: ICommandService,
- @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel
+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,
+ @Inject(INumfmtService) private _numfmtService: INumfmtService
) {
super();
@@ -64,7 +65,11 @@ export class StatusBarController extends Disposable {
if (selections) {
clearTimeout(this._calculateTimeout);
this._calculateTimeout = setTimeout(() => {
- this._calculateSelection(selections.map((selection) => selection.range));
+ const primary = selections[selections.length - 1].primary;
+ this._calculateSelection(
+ selections.map((selection) => selection.range),
+ primary
+ );
}, 100);
}
})
@@ -74,7 +79,11 @@ export class StatusBarController extends Disposable {
toDisposable(
this._selectionManagerService.selectionMoveEnd$.subscribe((selections) => {
if (selections) {
- this._calculateSelection(selections.map((selection) => selection.range));
+ const primary = selections[selections.length - 1].primary;
+ this._calculateSelection(
+ selections.map((selection) => selection.range),
+ primary
+ );
}
})
)
@@ -94,7 +103,7 @@ export class StatusBarController extends Disposable {
);
}
- private _calculateSelection(selections: IRange[]) {
+ private _calculateSelection(selections: IRange[], primary: Nullable<ISelectionCell>) {
const workbook = this._univerInstanceService.getCurrentUniverSheetInstance();
const unitId = workbook.getUnitId();
const sheetId = workbook.getActiveSheet().getSheetId();
@@ -142,8 +151,17 @@ export class StatusBarController extends Disposable {
if (calcResult.every((r) => r === undefined)) {
return;
}
+ let pattern = null;
+ if (primary) {
+ const { actualRow, actualColumn } = primary;
+ pattern = this._numfmtService.getValue(unitId, sheetId, actualRow, actualColumn)?.pattern;
+ }
const availableResult = calcResult.filter((r) => r !== undefined);
- this._statusBarService.setState(availableResult as IStatusBarServiceStatus);
+ const newState = {
+ values: availableResult,
+ pattern,
+ };
+ this._statusBarService.setState(newState as IStatusBarServiceStatus);
} else {
this._statusBarService.setState(null);
}
diff --git a/packages/sheets-ui/src/services/auto-fill/rules.ts b/packages/sheets-ui/src/services/auto-fill/rules.ts
index 15de236e21..99bb5f8029 100644
--- a/packages/sheets-ui/src/services/auto-fill/rules.ts
+++ b/packages/sheets-ui/src/services/auto-fill/rules.ts
@@ -51,6 +51,7 @@ export const numberRule: IAutoFillRule = {
const { data } = dataWithIndex;
if (direction === Direction.LEFT || direction === Direction.UP) {
data.reverse();
+ return fillSeries(data, len, direction).reverse();
}
return fillSeries(data, len, direction);
},
diff --git a/packages/sheets-ui/src/services/auto-fill/tools.ts b/packages/sheets-ui/src/services/auto-fill/tools.ts
index 62690d9a0b..ff68e233e0 100644
--- a/packages/sheets-ui/src/services/auto-fill/tools.ts
+++ b/packages/sheets-ui/src/services/auto-fill/tools.ts
@@ -391,12 +391,7 @@ export function fillSeries(data: Array<Nullable<ICellData>>, len: number, direct
const index = (i - 1) % data.length;
const d = Tools.deepClone(data[index]);
- let num;
- if (direction === Direction.DOWN || direction === Direction.RIGHT) {
- num = Number(data[data.length - 1]?.v) * (Number(data[1]?.v) / Number(data[0]?.v)) ** i;
- } else if (direction === Direction.UP || direction === Direction.LEFT) {
- num = Number(data[0]?.v) / (Number(data[1]?.v) / Number(data[0]?.v)) ** i;
- }
+ const num = Number(data[data.length - 1]?.v) * (Number(data[1]?.v) / Number(data[0]?.v)) ** i;
if (d) {
d.v = num;
@@ -409,12 +404,7 @@ export function fillSeries(data: Array<Nullable<ICellData>>, len: number, direct
const index = (i - 1) % data.length;
const d = Tools.deepClone(data[index]);
- let y;
- if (direction === Direction.DOWN || direction === Direction.RIGHT) {
- y = forecast(data.length + i, dataNumArr, xArr);
- } else {
- y = forecast(1 - i, dataNumArr, xArr);
- }
+ const y = forecast(data.length + i, dataNumArr, xArr);
if (d) {
d.v = y;
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 e91e2c324b..67bc902028 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
@@ -37,17 +37,14 @@ const cellData = {
'0': {
'7': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'8': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'10': {
v: '456',
- m: '456',
s: '3UpAbI',
},
'11': {
@@ -57,57 +54,47 @@ const cellData = {
'1': {
'5': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'6': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'7': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'8': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
},
'2': {
'8': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
},
'3': {
'5': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'6': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'7': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'8': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'10': {
s: '3UpAbI',
v: '456',
- m: '456',
},
'11': {
s: '3UpAbI',
@@ -119,39 +106,32 @@ const cellData = {
'5': {
'5': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'6': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'7': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'8': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
},
'6': {
'7': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'8': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'10': {
v: '456',
- m: '456',
s: 'hw-erj',
},
'11': {
@@ -161,39 +141,32 @@ const cellData = {
'7': {
'7': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'8': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
},
'8': {
'5': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'6': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'7': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'8': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'11': {
v: '456',
- m: '456',
s: '_aRLOe',
},
'12': {
@@ -203,12 +176,10 @@ const cellData = {
'9': {
'7': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'8': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'11': {
@@ -221,34 +192,28 @@ const cellData = {
'10': {
'5': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'6': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'7': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'8': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
},
'11': {
'8': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
'10': {
v: '456',
- m: '456',
s: 'Mtn4vb',
},
'11': {
@@ -261,14 +226,12 @@ const cellData = {
'12': {
'8': {
v: ' ',
- m: ' ',
s: 'u5otPe',
},
},
'13': {
'11': {
v: '456',
- m: '456',
s: '3UpAbI',
},
'12': {
@@ -286,7 +249,6 @@ const cellData = {
'16': {
'10': {
v: '456',
- m: '456',
s: '3UpAbI',
},
'11': {
@@ -296,7 +258,6 @@ const cellData = {
'17': {
'11': {
v: '456',
- m: '456',
s: '3UpAbI',
},
'12': {
@@ -314,7 +275,6 @@ const cellData = {
'21': {
'10': {
v: '456',
- m: '456',
s: '3UpAbI',
},
'11': {
@@ -332,7 +292,6 @@ const cellData = {
'23': {
'11': {
v: '456',
- m: '456',
s: '3UpAbI',
},
'12': {
@@ -515,6 +474,10 @@ export class testMarkSelectionService {
removeAllShapes(): void {}
refreshShapes(): void {}
+
+ getShapeMap(): Map<string, any> {
+ return new Map();
+ }
}
export function clipboardTestBed(workbookConfig?: IWorkbookData, dependencies?: Dependency[]) {
diff --git a/packages/sheets-ui/src/services/format-painter/format-painter.service.ts b/packages/sheets-ui/src/services/format-painter/format-painter.service.ts
index 15bb693859..cf08577727 100644
--- a/packages/sheets-ui/src/services/format-painter/format-painter.service.ts
+++ b/packages/sheets-ui/src/services/format-painter/format-painter.service.ts
@@ -17,7 +17,7 @@
import type { ICellData, IRange, IStyleData } from '@univerjs/core';
import { Disposable, IUniverInstanceService, ObjectMatrix } from '@univerjs/core';
import { getCellInfoInMergeData } from '@univerjs/engine-render';
-import { SelectionManagerService } from '@univerjs/sheets';
+import { SelectionManagerService, SetRangeValuesMutation } from '@univerjs/sheets';
import { createIdentifier, Inject } from '@wendellhu/redi';
import type { Observable } from 'rxjs';
import { BehaviorSubject } from 'rxjs';
@@ -81,7 +81,13 @@ export class FormatPainterService extends Disposable implements IFormatPainterSe
const selection = this._selectionManagerService.getLast();
if (selection) {
const style = this._selectionManagerService.createCopyPasteSelection();
- this._markId = this._markSelectionService.addShape({ ...selection, style });
+ if (status === FormatPainterStatus.INFINITE) {
+ this._markId = this._markSelectionService.addShape({ ...selection, style });
+ } else {
+ this._markId = this._markSelectionService.addShape({ ...selection, style }, [
+ SetRangeValuesMutation.id,
+ ]);
+ }
}
}
}
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 b8c7acfdbd..7816841ede 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
@@ -25,10 +25,11 @@ import { SelectionShape } from '../selection/selection-shape';
import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
export interface IMarkSelectionService {
- addShape(selection: ISelectionWithStyle, zIndex?: number): string | null;
+ addShape(selection: ISelectionWithStyle, exits?: string[], zIndex?: number): string | null;
removeShape(id: string): void;
removeAllShapes(): void;
refreshShapes(): void;
+ getShapeMap(): Map<string, IMarkSelectionInfo>;
}
interface IMarkSelectionInfo {
@@ -37,6 +38,7 @@ interface IMarkSelectionInfo {
selection: ISelectionWithStyle;
zIndex: number;
control: SelectionShape | null;
+ exits: string[];
}
const DEFAULT_Z_INDEX = 10000;
@@ -57,7 +59,7 @@ export class MarkSelectionService extends Disposable implements IMarkSelectionSe
super();
}
- addShape(selection: ISelectionWithStyle, zIndex: number = DEFAULT_Z_INDEX): string | null {
+ addShape(selection: ISelectionWithStyle, exits: string[] = [], zIndex: number = DEFAULT_Z_INDEX): string | null {
const workbook = this._currentService.getCurrentUniverSheetInstance();
const subUnitId = workbook.getActiveSheet().getSheetId();
const id = Tools.generateRandomId();
@@ -67,6 +69,7 @@ export class MarkSelectionService extends Disposable implements IMarkSelectionSe
unitId: workbook.getUnitId(),
zIndex,
control: null,
+ exits,
});
this.refreshShapes();
return id;
@@ -97,6 +100,10 @@ export class MarkSelectionService extends Disposable implements IMarkSelectionSe
});
}
+ getShapeMap(): Map<string, IMarkSelectionInfo> {
+ return this._shapeMap;
+ }
+
removeShape(id: string): void {
const shapeInfo = this._shapeMap.get(id);
if (!shapeInfo) return;
diff --git a/packages/sheets-ui/src/services/status-bar.service.ts b/packages/sheets-ui/src/services/status-bar.service.ts
index 03937b536e..805de10997 100644
--- a/packages/sheets-ui/src/services/status-bar.service.ts
+++ b/packages/sheets-ui/src/services/status-bar.service.ts
@@ -30,10 +30,13 @@ export interface IStatusBarService {
getFunctions(): Readonly<IStatusBarFunction[]>;
}
-export type IStatusBarServiceStatus = Array<{
- func: IFunctionNames;
- value: number;
-}>;
+export interface IStatusBarServiceStatus {
+ values: Array<{
+ func: IFunctionNames;
+ value: number;
+ }>;
+ pattern: Nullable<string>;
+}
export interface IStatusBarFunction {
func: IFunctionNames;
@@ -45,38 +48,38 @@ export class StatusBarService implements IStatusBarService, IDisposable {
{
func: FUNCTION_NAMES_STATISTICAL.MAX,
filter: (status: IStatusBarServiceStatus) =>
- (status.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNTA)?.value ?? 0) > 1 &&
- (status.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNT)?.value ?? 0) > 0,
+ (status.values.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNTA)?.value ?? 0) > 1 &&
+ (status.values.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNT)?.value ?? 0) > 0,
},
{
func: FUNCTION_NAMES_STATISTICAL.MIN,
filter: (status: IStatusBarServiceStatus) =>
- (status.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNTA)?.value ?? 0) > 1 &&
- (status.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNT)?.value ?? 0) > 0,
+ (status.values.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNTA)?.value ?? 0) > 1 &&
+ (status.values.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNT)?.value ?? 0) > 0,
},
{
func: FUNCTION_NAMES_MATH.SUM,
filter: (status: IStatusBarServiceStatus) =>
- (status.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNTA)?.value ?? 0) > 1 &&
- (status.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNT)?.value ?? 0) > 0,
+ (status.values.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNTA)?.value ?? 0) > 1 &&
+ (status.values.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNT)?.value ?? 0) > 0,
},
{
func: FUNCTION_NAMES_STATISTICAL.COUNTA,
filter: (status: IStatusBarServiceStatus) =>
- (status.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNTA)?.value ?? 0) > 1,
+ (status.values.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNTA)?.value ?? 0) > 1,
},
{
func: FUNCTION_NAMES_STATISTICAL.COUNT,
filter: (status: IStatusBarServiceStatus) =>
- (status.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNTA)?.value ?? 0) > 1 &&
- (status.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNT)?.value ?? 0) > 0,
+ (status.values.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNTA)?.value ?? 0) > 1 &&
+ (status.values.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNT)?.value ?? 0) > 0,
},
{
func: FUNCTION_NAMES_STATISTICAL.AVERAGE,
filter: (status: IStatusBarServiceStatus) =>
- (status.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNTA)?.value ?? 0) > 1 &&
- (status.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNT)?.value ?? 0) > 0,
+ (status.values.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNTA)?.value ?? 0) > 1 &&
+ (status.values.find((item) => item.func === FUNCTION_NAMES_STATISTICAL.COUNT)?.value ?? 0) > 0,
},
];
private readonly _state$ = new BehaviorSubject<Nullable<IStatusBarServiceStatus>>(null);
@@ -87,14 +90,18 @@ export class StatusBarService implements IStatusBarService, IDisposable {
}
setState(param: IStatusBarServiceStatus | null) {
- const newState: IStatusBarServiceStatus = [];
+ const newState: IStatusBarServiceStatus = {
+ values: [],
+ pattern: null,
+ };
// handle the filter.
- param?.forEach((item) => {
+ param?.values.forEach((item) => {
const func = this._functions.find((func) => func.func === item.func);
if (func && (func.filter === undefined || func.filter(param))) {
- newState.push(item);
+ newState.values.push(item);
}
});
+ newState.pattern = param?.pattern ?? null;
this._state$.next(newState);
}
diff --git a/packages/sheets-ui/src/views/status-bar/CopyableStatisticItem.tsx b/packages/sheets-ui/src/views/status-bar/CopyableStatisticItem.tsx
index 13ee823de9..db71dc07cd 100644
--- a/packages/sheets-ui/src/views/status-bar/CopyableStatisticItem.tsx
+++ b/packages/sheets-ui/src/views/status-bar/CopyableStatisticItem.tsx
@@ -18,6 +18,7 @@ import { LocaleService } from '@univerjs/core';
import { MessageType, Tooltip } from '@univerjs/design';
import type { IFunctionNames } from '@univerjs/engine-formula';
import { FUNCTION_NAMES_MATH, FUNCTION_NAMES_STATISTICAL, FUNCTION_NAMES_TEXT } from '@univerjs/engine-formula';
+import numfmt from '@univerjs/engine-numfmt';
import { IClipboardInterfaceService, IMessageService } from '@univerjs/ui';
import { useDependency } from '@wendellhu/redi/react-bindings';
import React from 'react';
@@ -29,8 +30,16 @@ export interface IStatisticItem {
value: number;
show: boolean;
disable: boolean;
+ pattern: string | null;
}
+const allowPatternFunctions: IFunctionNames[] = [
+ FUNCTION_NAMES_MATH.SUM,
+ FUNCTION_NAMES_STATISTICAL.AVERAGE,
+ FUNCTION_NAMES_STATISTICAL.MIN,
+ FUNCTION_NAMES_STATISTICAL.MAX,
+];
+
export const functionDisplayNames: FunctionNameMap = {
[FUNCTION_NAMES_MATH.SUM]: 'statusbar.sum',
[FUNCTION_NAMES_STATISTICAL.AVERAGE]: 'statusbar.average',
@@ -49,7 +58,8 @@ export const CopyableStatisticItem: React.FC<IStatisticItem> = (item: IStatistic
const messageService = useDependency(IMessageService);
const clipboardService = useDependency(IClipboardInterfaceService);
- const formateValue = formatNumber(item.value);
+ const formateValue = formatNumber(item);
+
const copyToClipboard = async () => {
await clipboardService.writeText(item.value.toString());
messageService.show({
@@ -68,7 +78,8 @@ export const CopyableStatisticItem: React.FC<IStatisticItem> = (item: IStatistic
);
};
-export function formatNumber(num: number) {
+export function formatNumber(item: IStatisticItem) {
+ const { pattern, value: num } = item;
if (typeof num !== 'number') {
return 'Invalid input';
}
@@ -76,5 +87,10 @@ export function formatNumber(num: number) {
if (num >= 1e8) {
return num.toExponential(2);
}
+
+ if (pattern && allowPatternFunctions.includes(item.name)) {
+ return numfmt.format(pattern, num);
+ }
+
return num.toLocaleString();
}
diff --git a/packages/sheets-ui/src/views/status-bar/StatusBar.tsx b/packages/sheets-ui/src/views/status-bar/StatusBar.tsx
index 7e2a120d6b..c9b4f50c21 100644
--- a/packages/sheets-ui/src/views/status-bar/StatusBar.tsx
+++ b/packages/sheets-ui/src/views/status-bar/StatusBar.tsx
@@ -36,13 +36,15 @@ export const StatusBar = () => {
value: 0,
show: true,
disable: false,
+ pattern: null,
}));
const [statistics, setStatistics] = useState<IStatisticItem[]>(items);
const firstItem = statistics.find((item) => item.show && !item.disable);
const showList = isSingle && firstItem ? [firstItem] : statistics.filter((item) => item.show && !item.disable);
useEffect(() => {
- const subscription = statusBarService.state$.subscribe((item) => {
+ const subscription = statusBarService.state$.subscribe((state) => {
+ const item = state?.values;
if (!item || item.length === 0) {
setShow(false);
} else {
@@ -55,6 +57,7 @@ export const StatusBar = () => {
} else {
stat.disable = true;
}
+ stat.pattern = state?.pattern ?? null;
return stat;
});
setStatistics(newStatistics);
diff --git a/packages/sheets-ui/src/views/status-bar/index.module.less b/packages/sheets-ui/src/views/status-bar/index.module.less
index 599ccbff47..01b4c2dfb8 100644
--- a/packages/sheets-ui/src/views/status-bar/index.module.less
+++ b/packages/sheets-ui/src/views/status-bar/index.module.less
@@ -40,7 +40,7 @@
display: flex;
justify-content: start;
- max-width: 96px;
+ max-width: 106px;
margin-right: 8px;
font-size: 12px;
diff --git a/packages/sheets/src/commands/commands/__tests__/move-range-commands.spec.ts b/packages/sheets/src/commands/commands/__tests__/move-range-commands.spec.ts
index 32a3b268cc..fd1121deba 100644
--- a/packages/sheets/src/commands/commands/__tests__/move-range-commands.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/move-range-commands.spec.ts
@@ -92,7 +92,7 @@ describe('Test move range commands', () => {
await commandService.executeCommand(UndoCommand.id);
const undoA1 = getCellInfo(0, 0);
const undoC3 = getCellInfo(2, 2);
- expect(undoC3).toEqual(null);
+ expect(undoC3).toBeFalsy();
expect(undoA1).toEqual(originA1);
});
diff --git a/packages/sheets/src/commands/commands/move-range.command.ts b/packages/sheets/src/commands/commands/move-range.command.ts
index 57fcb9d836..32df376a09 100644
--- a/packages/sheets/src/commands/commands/move-range.command.ts
+++ b/packages/sheets/src/commands/commands/move-range.command.ts
@@ -21,6 +21,8 @@ import {
IUndoRedoService,
IUniverInstanceService,
ObjectMatrix,
+ Range,
+ Rectangle,
sequenceExecute,
} from '@univerjs/core';
import type { IAccessor } from '@wendellhu/redi';
@@ -48,55 +50,54 @@ export const MoveRangeCommand: ICommand = {
const worksheet = workbook.getActiveSheet();
const unitId = workbook.getUnitId();
const subUnitId = worksheet.getSheetId();
- const fromValues = worksheet.getRange(params.fromRange).getValues();
+ const cellMatrix = worksheet.getCellMatrix();
- const newFromCellValues = fromValues.reduce((res, row, rowIndex) => {
- row.forEach((colItem, colIndex) => {
- res.setValue(params.fromRange.startRow + rowIndex, params.fromRange.startColumn + colIndex, null);
- });
- return res;
- }, new ObjectMatrix<Nullable<ICellData>>());
- const currentFromCellValues = fromValues.reduce((res, row, rowIndex) => {
- row.forEach((colItem, colIndex) => {
- res.setValue(params.fromRange.startRow + rowIndex, params.fromRange.startColumn + colIndex, colItem);
- });
- return res;
- }, new ObjectMatrix<Nullable<ICellData>>());
+ const fromCellValue = new ObjectMatrix<Nullable<ICellData>>();
+ const newFromCellValue = new ObjectMatrix<Nullable<ICellData>>();
+ const cellToRange = (row: number, col: number) => ({
+ startRow: row,
+ endRow: row,
+ startColumn: col,
+ endColumn: col,
+ });
- const newToCellValues = fromValues.reduce((res, row, rowIndex) => {
- row.forEach((colItem, colIndex) => {
- res.setValue(params.toRange.startRow + rowIndex, params.toRange.startColumn + colIndex, colItem);
- });
- return res;
- }, new ObjectMatrix<Nullable<ICellData>>());
- const currentToCellValues = worksheet
- .getRange(params.toRange)
- .getValues()
- .reduce((res, row, rowIndex) => {
- row.forEach((colItem, colIndex) => {
- res.setValue(params.toRange.startRow + rowIndex, params.toRange.startColumn + colIndex, colItem);
- });
- return res;
- }, new ObjectMatrix<Nullable<ICellData>>());
+ Range.foreach(params.fromRange, (row, col) => {
+ fromCellValue.setValue(row, col, cellMatrix.getValue(row, col));
+ newFromCellValue.setValue(row, col, null);
+ });
+ const toCellValue = new ObjectMatrix<Nullable<ICellData>>();
+
+ Range.foreach(params.toRange, (row, col) => {
+ toCellValue.setValue(row, col, cellMatrix.getValue(row, col));
+ });
+
+ const newToCellValue = new ObjectMatrix<Nullable<ICellData>>();
+
+ Range.foreach(params.fromRange, (row, col) => {
+ const cellRange = cellToRange(row, col);
+ const relativeRange = Rectangle.getRelativeRange(cellRange, params.fromRange);
+ const range = Rectangle.getPositionRange(relativeRange, params.toRange);
+ newToCellValue.setValue(range.startRow, range.startColumn, cellMatrix.getValue(row, col));
+ });
const doMoveRangeMutation: IMoveRangeMutationParams = {
from: {
- value: newFromCellValues.getMatrix(),
+ value: newFromCellValue.getMatrix(),
subUnitId,
},
to: {
- value: newToCellValues.getMatrix(),
+ value: newToCellValue.getMatrix(),
subUnitId,
},
unitId,
};
const undoMoveRangeMutation: IMoveRangeMutationParams = {
from: {
- value: currentFromCellValues.getMatrix(),
+ value: fromCellValue.getMatrix(),
subUnitId,
},
to: {
- value: currentToCellValues.getMatrix(),
+ value: toCellValue.getMatrix(),
subUnitId,
},
unitId,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 766fadccfc..d0f7e35c92 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1018,6 +1018,9 @@ importers:
'@univerjs/engine-formula':
specifier: workspace:*
version: link:../engine-formula
+ '@univerjs/engine-numfmt':
+ specifier: workspace:*
+ version: link:../engine-numfmt
'@univerjs/engine-render':
specifier: workspace:*
version: link:../engine-render