Skip to content

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

feat(base-sheets): clear content/clear format/clear all command, set range values supports style (#159)

Dushusird09b9ea81178
diff --git a/packages/base-docs/src/Locale/en.ts b/packages/base-docs/src/Locale/en.ts
index e3809e731b..f6ba473eaa 100644
--- a/packages/base-docs/src/Locale/en.ts
+++ b/packages/base-docs/src/Locale/en.ts
@@ -447,7 +447,7 @@ export default {
confirm: 'Confirm',
orderAZ: 'A-Z order',
orderZA: 'Z-A order',
- clearContent: 'Clear content',
+ clearContent: 'Clear Contents',
matrix: 'Matrix operation',
sortSelection: 'Sort',
filterSelection: 'Filter',
diff --git a/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts b/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts
index 898af668af..bd475530fb 100644
--- a/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts
+++ b/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts
@@ -63,7 +63,7 @@ import { InsertSheetMutation } from '../commands/mutations/insert-sheet.mutation
import { RemoveColMutation, RemoveRowMutation } from '../commands/mutations/remove-row-col.mutation';
import { RemoveSheetMutation } from '../commands/mutations/remove-sheet.mutation';
import { RemoveWorksheetMergeMutation } from '../commands/mutations/remove-worksheet-merge.mutation';
-import { SetBorderStylesMutation } from '../commands/mutations/set-border-styles.mutatio';
+import { SetBorderStylesMutation } from '../commands/mutations/set-border-styles.mutation';
import { SetRangeFormattedValueMutation } from '../commands/mutations/set-range-formatted-value.mutation';
import { SetRangeStyleMutation } from '../commands/mutations/set-range-styles.mutation';
import { SetRangeValuesMutation } from '../commands/mutations/set-range-values.mutation';
diff --git a/packages/base-sheets/src/commands/commands/__tests__/clear-selection-command.spec.ts b/packages/base-sheets/src/commands/commands/__tests__/clear-selection-command.spec.ts
new file mode 100644
index 0000000000..a7b940b7b8
--- /dev/null
+++ b/packages/base-sheets/src/commands/commands/__tests__/clear-selection-command.spec.ts
@@ -0,0 +1,236 @@
+import {
+ ICellData,
+ ICommandService,
+ ICurrentUniverService,
+ IStyleData,
+ Nullable,
+ RedoCommand,
+ SELECTION_TYPE,
+ UndoCommand,
+ Univer,
+} from '@univerjs/core';
+import { Injector } from '@wendellhu/redi';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../../services/selection-manager.service';
+import { SetRangeValuesMutation } from '../../mutations/set-range-values.mutation';
+import { ClearSelectionAllCommand } from '../clear-selection-all.command';
+import { ClearSelectionContentCommand } from '../clear-selection-content.command';
+import { ClearSelectionFormatCommand } from '../clear-selection-format.command';
+import { ISetRangeValuesCommandParams, SetRangeValuesCommand } from '../set-range-values.command';
+import { createCommandTestBed } from './create-command-test-bed';
+
+describe('Test clear selection content commands', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+ let currentUniverService: ICurrentUniverService;
+
+ beforeEach(() => {
+ const testBed = createCommandTestBed();
+ univer = testBed.univer;
+ get = testBed.get;
+
+ commandService = get(ICommandService);
+ commandService.registerCommand(ClearSelectionContentCommand);
+ commandService.registerCommand(ClearSelectionFormatCommand);
+ commandService.registerCommand(ClearSelectionAllCommand);
+ commandService.registerCommand(SetRangeValuesCommand);
+ commandService.registerCommand(SetRangeValuesMutation);
+
+ currentUniverService = get(ICurrentUniverService);
+ currentUniverService.focusUniverInstance('test'); // used in undo
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ describe('clear selection content', () => {
+ describe('correct situations', () => {
+ it('will clear selection content when there is a selected range', async () => {
+ const selectionManager = get(SelectionManagerService);
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+ selectionManager.add([
+ {
+ rangeData: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0 },
+ cellRange: null,
+ selectionType: SELECTION_TYPE.NORMAL,
+ style: null,
+ },
+ ]);
+
+ function getValue(): Nullable<ICellData> {
+ return get(ICurrentUniverService)
+ .getUniverSheetInstance('test')
+ ?.getWorkBook()
+ .getSheetBySheetId('sheet1')
+ ?.getRange(0, 0, 0, 0)
+ .getValue();
+ }
+
+ expect(await commandService.executeCommand(ClearSelectionContentCommand.id)).toBeTruthy();
+ expect(getValue()).toStrictEqual({});
+ // undo
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getValue()).toStrictEqual({
+ v: 'A1',
+ });
+ // redo
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+ expect(getValue()).toStrictEqual({});
+ });
+ });
+
+ describe('fault situations', () => {
+ it('will not apply when there is no selected ranges', async () => {
+ const result = await commandService.executeCommand(ClearSelectionContentCommand.id);
+ expect(result).toBeFalsy();
+ });
+ });
+ });
+ describe('clear selection format', () => {
+ describe('correct situations', () => {
+ it('will clear selection format when there is a selected range', async () => {
+ const selectionManager = get(SelectionManagerService);
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+ selectionManager.add([
+ {
+ rangeData: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0 },
+ cellRange: null,
+ selectionType: SELECTION_TYPE.NORMAL,
+ style: null,
+ },
+ ]);
+
+ function getValue(): Nullable<ICellData> {
+ return get(ICurrentUniverService)
+ .getUniverSheetInstance('test')
+ ?.getWorkBook()
+ .getSheetBySheetId('sheet1')
+ ?.getRange(0, 0, 0, 0)
+ .getValue();
+ }
+
+ function getStyle(): Nullable<IStyleData> {
+ const value = getValue();
+ const styles = get(ICurrentUniverService).getUniverSheetInstance('test')?.getWorkBook().getStyles();
+ if (value && styles) {
+ return styles.getStyleByCell(value);
+ }
+ }
+
+ // set formats
+ const paramsStyle: ISetRangeValuesCommandParams = {
+ value: {
+ s: {
+ ff: 'Arial',
+ },
+ },
+ };
+
+ expect(await commandService.executeCommand(SetRangeValuesCommand.id, paramsStyle)).toBeTruthy();
+ expect(getStyle()).toStrictEqual({
+ ff: 'Arial',
+ });
+
+ // clear formats
+ expect(await commandService.executeCommand(ClearSelectionFormatCommand.id)).toBeTruthy();
+ expect(getValue()).toStrictEqual({});
+
+ // undo
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getStyle()).toStrictEqual({
+ ff: 'Arial',
+ });
+ // redo
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+ expect(getValue()).toStrictEqual({});
+ });
+ });
+
+ describe('fault situations', () => {
+ it('will not apply when there is no selected ranges', async () => {
+ const result = await commandService.executeCommand(ClearSelectionFormatCommand.id);
+ expect(result).toBeFalsy();
+ });
+ });
+ });
+ describe('clear selection all', () => {
+ describe('correct situations', () => {
+ it('will clear selection all when there is a selected range', async () => {
+ const selectionManager = get(SelectionManagerService);
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+ selectionManager.add([
+ {
+ rangeData: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0 },
+ cellRange: null,
+ selectionType: SELECTION_TYPE.NORMAL,
+ style: null,
+ },
+ ]);
+
+ function getValue(): Nullable<ICellData> {
+ return get(ICurrentUniverService)
+ .getUniverSheetInstance('test')
+ ?.getWorkBook()
+ .getSheetBySheetId('sheet1')
+ ?.getRange(0, 0, 0, 0)
+ .getValue();
+ }
+
+ function getStyle(): Nullable<IStyleData> {
+ const value = getValue();
+ const styles = get(ICurrentUniverService).getUniverSheetInstance('test')?.getWorkBook().getStyles();
+ if (value && styles) {
+ return styles.getStyleByCell(value);
+ }
+ }
+
+ // set formats
+ const paramsStyle: ISetRangeValuesCommandParams = {
+ value: {
+ s: {
+ ff: 'Arial',
+ },
+ },
+ };
+
+ expect(await commandService.executeCommand(SetRangeValuesCommand.id, paramsStyle)).toBeTruthy();
+ expect(getStyle()).toStrictEqual({
+ ff: 'Arial',
+ });
+
+ expect(await commandService.executeCommand(ClearSelectionAllCommand.id)).toBeTruthy();
+ expect(getValue()).toStrictEqual({});
+ // undo
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getStyle()).toStrictEqual({
+ ff: 'Arial',
+ });
+ // redo
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+ expect(getValue()).toStrictEqual({});
+ });
+ });
+
+ describe('fault situations', () => {
+ it('will not apply when there is no selected ranges', async () => {
+ const result = await commandService.executeCommand(ClearSelectionAllCommand.id);
+ expect(result).toBeFalsy();
+ });
+ });
+ });
+});
diff --git a/packages/base-sheets/src/commands/commands/__tests__/set-range-values-command.spec.ts b/packages/base-sheets/src/commands/commands/__tests__/set-range-values-command.spec.ts
new file mode 100644
index 0000000000..5cf41dabc8
--- /dev/null
+++ b/packages/base-sheets/src/commands/commands/__tests__/set-range-values-command.spec.ts
@@ -0,0 +1,280 @@
+import {
+ CellValueType,
+ ICellData,
+ ICommandService,
+ ICurrentUniverService,
+ IDocumentData,
+ IStyleData,
+ Nullable,
+ RedoCommand,
+ SELECTION_TYPE,
+ Tools,
+ UndoCommand,
+ Univer,
+} from '@univerjs/core';
+import { Injector } from '@wendellhu/redi';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../../services/selection-manager.service';
+import { SetRangeValuesMutation } from '../../mutations/set-range-values.mutation';
+import { ISetRangeValuesCommandParams, SetRangeValuesCommand } from '../set-range-values.command';
+import { createCommandTestBed } from './create-command-test-bed';
+
+describe('Test set range values commands', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+ let currentUniverService: ICurrentUniverService;
+ let selectionManager: SelectionManagerService;
+ let getValue: () => any;
+ let getStyle: () => any;
+
+ beforeEach(() => {
+ const testBed = createCommandTestBed();
+ univer = testBed.univer;
+ get = testBed.get;
+
+ commandService = get(ICommandService);
+ commandService.registerCommand(SetRangeValuesCommand);
+ commandService.registerCommand(SetRangeValuesMutation);
+
+ currentUniverService = get(ICurrentUniverService);
+ currentUniverService.focusUniverInstance('test'); // used in undo
+
+ selectionManager = get(SelectionManagerService);
+ selectionManager.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId: 'test',
+ sheetId: 'sheet1',
+ });
+ selectionManager.add([
+ {
+ rangeData: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0 },
+ cellRange: null,
+ selectionType: SELECTION_TYPE.NORMAL,
+ style: null,
+ },
+ ]);
+
+ getValue = (): Nullable<ICellData> =>
+ get(ICurrentUniverService)
+ .getUniverSheetInstance('test')
+ ?.getWorkBook()
+ .getSheetBySheetId('sheet1')
+ ?.getRange(0, 0, 0, 0)
+ .getValue();
+
+ getStyle = (): Nullable<IStyleData> => {
+ const value = getValue();
+ const styles = get(ICurrentUniverService).getUniverSheetInstance('test')?.getWorkBook().getStyles();
+ if (value && styles) {
+ return styles.getStyleByCell(value);
+ }
+ };
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+ describe('set range values', () => {
+ describe('correct situations', () => {
+ it('will set range values when there is a selected range', async () => {
+ function getParams() {
+ const richTextDemo: IDocumentData = {
+ id: 'd',
+ body: {
+ dataStream: `Instructions:\f①Project division - Fill in the specific division of labor after the project is disassembled:\f②Responsible Person - Enter the responsible person's name here:\f③Date-The specific execution time of the project (detailed to the date of a certain month), and the gray color block marks the planned real-time time of the division of labor of the project (for example,\fthe specific execution time of [regional scene model arrangement and construction] is the 2 days marked in gray. \r\n`,
+ textRuns: [
+ {
+ st: 0,
+ ed: 488,
+ ts: {
+ cl: {
+ rgb: 'rgb(92,92,92)',
+ },
+ },
+ },
+ ],
+ paragraphs: [
+ {
+ startIndex: 489,
+ paragraphStyle: {
+ spaceAbove: 10,
+ lineSpacing: 1.2,
+ },
+ },
+ ],
+ },
+ documentStyle: {
+ pageSize: {
+ width: Infinity,
+ height: Infinity,
+ },
+ marginTop: 0,
+ marginBottom: 0,
+ marginRight: 2,
+ marginLeft: 2,
+ },
+ };
+
+ const params: ISetRangeValuesCommandParams = {
+ value: {
+ p: richTextDemo,
+ v: 'a1',
+ m: 'a1',
+ t: CellValueType.STRING,
+ },
+ };
+
+ return params;
+ }
+
+ expect(await commandService.executeCommand(SetRangeValuesCommand.id, getParams())).toBeTruthy();
+ expect(getValue()).toStrictEqual(getParams().value);
+ // undo
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getValue()).toStrictEqual({
+ v: 'A1',
+ });
+
+ // redo
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+ expect(getValue()).toStrictEqual(getParams().value);
+ });
+ it('set formats', async () => {
+ // set IStyleBase, the original cell has no style information
+ function getParamsStyleBase() {
+ const paramsStyleBase: ISetRangeValuesCommandParams = {
+ value: {
+ s: {
+ ff: 'Arial',
+ fs: 12,
+ it: 1,
+ bl: 1,
+ ul: {
+ s: 1,
+ cl: {
+ rgb: 'rgb(0,0,0)',
+ },
+ t: 1,
+ },
+ st: {
+ s: 1,
+ cl: {
+ rgb: 'rgb(0,0,0)',
+ },
+ t: 1,
+ },
+ ol: {
+ s: 1,
+ cl: {
+ rgb: 'rgb(0,0,0)',
+ },
+ t: 1,
+ },
+ bg: {
+ rgb: 'rgb(0,0,0)',
+ },
+ bd: {
+ t: {
+ s: 1,
+ cl: {
+ rgb: 'rgb(0,0,0)',
+ },
+ },
+ r: {
+ s: 1,
+ cl: {
+ rgb: 'rgb(0,0,0)',
+ },
+ },
+ b: {
+ s: 1,
+ cl: {
+ rgb: 'rgb(0,0,0)',
+ },
+ },
+ l: {
+ s: 1,
+ cl: {
+ rgb: 'rgb(0,0,0)',
+ },
+ },
+ },
+ cl: {
+ rgb: 'rgb(0,0,0)',
+ },
+ va: 1,
+ },
+ },
+ };
+
+ return paramsStyleBase;
+ }
+
+ function getParamsStyleBaseObject() {
+ const paramsStyleBase = getParamsStyleBase();
+ return (paramsStyleBase.value as ICellData).s as IStyleData;
+ }
+
+ expect(
+ await commandService.executeCommand(SetRangeValuesCommand.id, getParamsStyleBase())
+ ).toBeTruthy();
+ expect(getStyle()).toStrictEqual(getParamsStyleBaseObject());
+
+ // set IStyleData, the original cell has style information
+ function getParamsStyleData() {
+ const paramsStyleData: ISetRangeValuesCommandParams = {
+ value: {
+ s: {
+ tr: {
+ a: 45,
+ v: 0,
+ },
+ td: 1,
+ ht: 1,
+ vt: 1,
+ tb: 1,
+ pd: {
+ t: 4,
+ r: 4,
+ b: 4,
+ l: 4,
+ },
+ },
+ },
+ };
+
+ return paramsStyleData;
+ }
+
+ const allStyle = Tools.deepMerge({}, getParamsStyleBase(), getParamsStyleData());
+ expect(
+ await commandService.executeCommand(SetRangeValuesCommand.id, getParamsStyleData())
+ ).toBeTruthy();
+ expect(getStyle()).toStrictEqual((allStyle.value as ICellData).s);
+
+ // undo
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getStyle()).toStrictEqual(getParamsStyleBaseObject());
+
+ // redo
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+ expect(getStyle()).toStrictEqual((allStyle.value as ICellData).s);
+ });
+ });
+
+ describe('fault situations', () => {
+ it('will not apply when there is no selected ranges', async () => {
+ selectionManager.clear();
+ const params: ISetRangeValuesCommandParams = {
+ value: {
+ v: 'a1',
+ },
+ };
+ const result = await commandService.executeCommand(SetRangeValuesCommand.id, params);
+ expect(result).toBeFalsy();
+ });
+ });
+ });
+});
diff --git a/packages/base-sheets/src/commands/commands/__tests__/set-selections.command.spec.ts b/packages/base-sheets/src/commands/commands/__tests__/set-selections.command.spec.ts
index 4a199b9a64..8f28ac5c46 100644
--- a/packages/base-sheets/src/commands/commands/__tests__/set-selections.command.spec.ts
+++ b/packages/base-sheets/src/commands/commands/__tests__/set-selections.command.spec.ts
@@ -1,6 +1,4 @@
-import { describe, it } from 'node:test';
-
-import { expect } from 'vitest';
+import { describe, expect, it } from 'vitest';
// This spec file also tests selection-util.ts
@@ -11,15 +9,15 @@ describe('Test commands used for change selections', () => {
});
});
- describe('Move to next gap cell', () => {
- expect(true).toBeTruthy();
- });
+ // describe('Move to next gap cell', () => {
+ // expect(true).toBeTruthy();
+ // });
- describe('Expand to next selection or shrink', () => {
- expect(true).toBeTruthy();
- });
+ // describe('Expand to next selection or shrink', () => {
+ // expect(true).toBeTruthy();
+ // });
- describe('Expand to next gap position or shrink', () => {
- expect(true).toBeTruthy();
- });
+ // describe('Expand to next gap position or shrink', () => {
+ // expect(true).toBeTruthy();
+ // });
});
diff --git a/packages/base-sheets/src/commands/commands/__tests__/set-style-command.spec.ts b/packages/base-sheets/src/commands/commands/__tests__/set-style-command.spec.ts
index 9be7466d43..ec8d84ea93 100644
--- a/packages/base-sheets/src/commands/commands/__tests__/set-style-command.spec.ts
+++ b/packages/base-sheets/src/commands/commands/__tests__/set-style-command.spec.ts
@@ -1,4 +1,12 @@
-import { FontWeight, ICommandService, ICurrentUniverService, SELECTION_TYPE, Univer } from '@univerjs/core';
+import {
+ FontWeight,
+ ICommandService,
+ ICurrentUniverService,
+ RedoCommand,
+ SELECTION_TYPE,
+ UndoCommand,
+ Univer,
+} from '@univerjs/core';
import { Injector } from '@wendellhu/redi';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -11,6 +19,7 @@ describe('Test style commands', () => {
let univer: Univer;
let get: Injector['get'];
let commandService: ICommandService;
+ let currentUniverService: ICurrentUniverService;
beforeEach(() => {
const testBed = createCommandTestBed();
@@ -21,6 +30,9 @@ describe('Test style commands', () => {
commandService.registerCommand(SetBoldCommand);
commandService.registerCommand(SetStyleCommand);
commandService.registerCommand(SetRangeStyleMutation);
+
+ currentUniverService = get(ICurrentUniverService);
+ currentUniverService.focusUniverInstance('test'); // used in undo
});
afterEach(() => {
@@ -58,6 +70,12 @@ describe('Test style commands', () => {
expect(getFontBold()).toBe(FontWeight.BOLD);
expect(await commandService.executeCommand(SetBoldCommand.id)).toBeTruthy();
expect(getFontBold()).toBe(FontWeight.NORMAL);
+ // undo
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(getFontBold()).toBe(FontWeight.BOLD);
+ // undo
+ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();
+ expect(getFontBold()).toBe(FontWeight.NORMAL);
});
});
diff --git a/packages/base-sheets/src/commands/commands/clear-selection-all.command.ts b/packages/base-sheets/src/commands/commands/clear-selection-all.command.ts
new file mode 100644
index 0000000000..b03d546bef
--- /dev/null
+++ b/packages/base-sheets/src/commands/commands/clear-selection-all.command.ts
@@ -0,0 +1,87 @@
+import {
+ CommandType,
+ ICellData,
+ ICommand,
+ ICommandService,
+ ICurrentUniverService,
+ ISelectionRange,
+ IUndoRedoService,
+ ObjectMatrix,
+ ObjectMatrixPrimitiveType,
+} from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+
+import { SelectionManagerService } from '../../services/selection-manager.service';
+import {
+ ISetRangeValuesMutationParams,
+ SetRangeValuesMutation,
+ SetRangeValuesUndoMutationFactory,
+} from '../mutations/set-range-values.mutation';
+
+/**
+ * The command to clear all in current selected ranges.
+ */
+export const ClearSelectionAllCommand: ICommand = {
+ id: 'sheet.command.clear-selection-all',
+ type: CommandType.COMMAND,
+ handler: async (accessor: IAccessor) => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const commandService = accessor.get(ICommandService);
+ const selectionManagerService = accessor.get(SelectionManagerService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const workbook = currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
+ const workbookId = workbook.getUnitId();
+ const worksheet = workbook.getActiveSheet();
+ const worksheetId = worksheet.getSheetId();
+ const selections = selectionManagerService.getRangeDatas();
+ if (!selections?.length) {
+ return false;
+ }
+
+ const clearMutationParams: ISetRangeValuesMutationParams = {
+ rangeData: selections,
+ worksheetId,
+ workbookId,
+ cellValue: generateNullCellValue(selections),
+ };
+ const undoClearMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(
+ accessor,
+ clearMutationParams
+ );
+
+ const result = commandService.executeCommand(SetRangeValuesMutation.id, clearMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ // If there are multiple mutations that form an encapsulated project, they must be encapsulated in the same undo redo element.
+ // Hooks can be used to hook the code of external controllers to add new actions.
+ URI: workbookId,
+ undo() {
+ return commandService.executeCommand(SetRangeValuesMutation.id, undoClearMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(SetRangeValuesMutation.id, clearMutationParams);
+ },
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
+
+// Generate cellValue from rangeData and set null
+function generateNullCellValue(rangeData: ISelectionRange[]): ObjectMatrixPrimitiveType<ICellData> {
+ const cellValue = new ObjectMatrix<ICellData>();
+ rangeData.forEach((range: ISelectionRange) => {
+ const { startRow, startColumn, endRow, endColumn } = range;
+ for (let i = startRow; i <= endRow; i++) {
+ for (let j = startColumn; j <= endColumn; j++) {
+ cellValue.setValue(i, j, null);
+ }
+ }
+ });
+
+ return cellValue.getData();
+}
diff --git a/packages/base-sheets/src/commands/commands/clear-selection-content.command.ts b/packages/base-sheets/src/commands/commands/clear-selection-content.command.ts
index 0a6bf62365..180e1d2361 100644
--- a/packages/base-sheets/src/commands/commands/clear-selection-content.command.ts
+++ b/packages/base-sheets/src/commands/commands/clear-selection-content.command.ts
@@ -1,4 +1,14 @@
-import { CommandType, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService } from '@univerjs/core';
+import {
+ CommandType,
+ ICellData,
+ ICommand,
+ ICommandService,
+ ICurrentUniverService,
+ ISelectionRange,
+ IUndoRedoService,
+ ObjectMatrix,
+ ObjectMatrixPrimitiveType,
+} from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
import { SelectionManagerService } from '../../services/selection-manager.service';
@@ -12,7 +22,7 @@ import {
* The command to clear content in current selected ranges.
*/
export const ClearSelectionContentCommand: ICommand = {
- id: 'sheet.command.clear-selection',
+ id: 'sheet.command.clear-selection-content',
type: CommandType.COMMAND,
handler: async (accessor: IAccessor) => {
const currentUniverService = accessor.get(ICurrentUniverService);
@@ -23,6 +33,7 @@ export const ClearSelectionContentCommand: ICommand = {
const workbook = currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
const workbookId = workbook.getUnitId();
const worksheet = workbook.getActiveSheet();
+ const worksheetId = worksheet.getSheetId();
const selections = selectionManagerService.getRangeDatas();
if (!selections?.length) {
return false;
@@ -30,8 +41,9 @@ export const ClearSelectionContentCommand: ICommand = {
const clearMutationParams: ISetRangeValuesMutationParams = {
rangeData: selections,
- workbookId: workbook.getUnitId(),
- worksheetId: worksheet.getSheetId(),
+ worksheetId,
+ workbookId,
+ cellValue: generateNullCellValue(selections),
};
const undoClearMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(
accessor,
@@ -41,8 +53,8 @@ export const ClearSelectionContentCommand: ICommand = {
const result = commandService.executeCommand(SetRangeValuesMutation.id, clearMutationParams);
if (result) {
undoRedoService.pushUndoRedo({
- // 如果有多个 mutation 构成一个封装项目,那么要封装在同一个 undo redo element 里面
- // 通过勾子可以 hook 外部 controller 的代码来增加新的 action
+ // If there are multiple mutations that form an encapsulated project, they must be encapsulated in the same undo redo element.
+ // Hooks can be used to hook the code of external controllers to add new actions.
URI: workbookId,
undo() {
return commandService.executeCommand(SetRangeValuesMutation.id, undoClearMutationParams);
@@ -58,3 +70,21 @@ export const ClearSelectionContentCommand: ICommand = {
return false;
},
};
+
+// Generate cellValue from rangeData and set v/m to null
+function generateNullCellValue(rangeData: ISelectionRange[]): ObjectMatrixPrimitiveType<ICellData> {
+ const cellValue = new ObjectMatrix<ICellData>();
+ rangeData.forEach((range: ISelectionRange) => {
+ const { startRow, startColumn, endRow, endColumn } = range;
+ for (let i = startRow; i <= endRow; i++) {
+ for (let j = startColumn; j <= endColumn; j++) {
+ cellValue.setValue(i, j, {
+ v: null,
+ m: null,
+ });
+ }
+ }
+ });
+
+ return cellValue.getData();
+}
diff --git a/packages/base-sheets/src/commands/commands/clear-selection-format.command.ts b/packages/base-sheets/src/commands/commands/clear-selection-format.command.ts
new file mode 100644
index 0000000000..13c46c75d5
--- /dev/null
+++ b/packages/base-sheets/src/commands/commands/clear-selection-format.command.ts
@@ -0,0 +1,89 @@
+import {
+ CommandType,
+ ICellData,
+ ICommand,
+ ICommandService,
+ ICurrentUniverService,
+ ISelectionRange,
+ IUndoRedoService,
+ ObjectMatrix,
+ ObjectMatrixPrimitiveType,
+} from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+
+import { SelectionManagerService } from '../../services/selection-manager.service';
+import {
+ ISetRangeValuesMutationParams,
+ SetRangeValuesMutation,
+ SetRangeValuesUndoMutationFactory,
+} from '../mutations/set-range-values.mutation';
+
+/**
+ * The command to clear content in current selected ranges.
+ */
+export const ClearSelectionFormatCommand: ICommand = {
+ id: 'sheet.command.clear-selection-format',
+ type: CommandType.COMMAND,
+ handler: async (accessor: IAccessor) => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const commandService = accessor.get(ICommandService);
+ const selectionManagerService = accessor.get(SelectionManagerService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const workbook = currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
+ const workbookId = workbook.getUnitId();
+ const worksheet = workbook.getActiveSheet();
+ const worksheetId = worksheet.getSheetId();
+ const selections = selectionManagerService.getRangeDatas();
+ if (!selections?.length) {
+ return false;
+ }
+
+ const clearMutationParams: ISetRangeValuesMutationParams = {
+ rangeData: selections,
+ worksheetId,
+ workbookId,
+ cellValue: generateNullCellValue(selections),
+ };
+ const undoClearMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(
+ accessor,
+ clearMutationParams
+ );
+
+ const result = commandService.executeCommand(SetRangeValuesMutation.id, clearMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ // If there are multiple mutations that form an encapsulated project, they must be encapsulated in the same undo redo element.
+ // Hooks can be used to hook the code of external controllers to add new actions.
+ URI: workbookId,
+ undo() {
+ return commandService.executeCommand(SetRangeValuesMutation.id, undoClearMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(SetRangeValuesMutation.id, clearMutationParams);
+ },
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
+
+// Generate cellValue from rangeData and set s to null
+function generateNullCellValue(rangeData: ISelectionRange[]): ObjectMatrixPrimitiveType<ICellData> {
+ const cellValue = new ObjectMatrix<ICellData>();
+ rangeData.forEach((range: ISelectionRange) => {
+ const { startRow, startColumn, endRow, endColumn } = range;
+ for (let i = startRow; i <= endRow; i++) {
+ for (let j = startColumn; j <= endColumn; j++) {
+ cellValue.setValue(i, j, {
+ s: null,
+ });
+ }
+ }
+ });
+
+ return cellValue.getData();
+}
diff --git a/packages/base-sheets/src/commands/commands/move-range-to.command.ts b/packages/base-sheets/src/commands/commands/move-range-to.command.ts
index 999dded42a..f3745489aa 100644
--- a/packages/base-sheets/src/commands/commands/move-range-to.command.ts
+++ b/packages/base-sheets/src/commands/commands/move-range-to.command.ts
@@ -49,6 +49,7 @@ export const MoveRangeToCommand: ICommand = {
const clearMutationParams: ISetRangeValuesMutationParams = {
rangeData: [originRange],
worksheetId,
+ workbookId,
};
const undoClearMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(
accessor,
diff --git a/packages/base-sheets/src/commands/commands/set-border-command.ts b/packages/base-sheets/src/commands/commands/set-border-command.ts
index 4bedf4ed9b..071e110b0a 100644
--- a/packages/base-sheets/src/commands/commands/set-border-command.ts
+++ b/packages/base-sheets/src/commands/commands/set-border-command.ts
@@ -22,7 +22,7 @@ import {
ISetBorderStylesMutationParams,
SetBorderStylesMutation,
SetBorderStylesUndoMutationFactory,
-} from '../mutations/set-border-styles.mutatio';
+} from '../mutations/set-border-styles.mutation';
function forEach(rangeData: ISelectionRange, action: (row: number, column: number) => void): void {
const { startRow, startColumn, endRow, endColumn } = rangeData;
diff --git a/packages/base-sheets/src/commands/commands/set-border-styles-command.ts b/packages/base-sheets/src/commands/commands/set-border-styles-command.ts
index 98553e3aca..18f05ce859 100644
--- a/packages/base-sheets/src/commands/commands/set-border-styles-command.ts
+++ b/packages/base-sheets/src/commands/commands/set-border-styles-command.ts
@@ -21,7 +21,7 @@ import {
ISetBorderStylesMutationParams,
SetBorderStylesMutation,
SetBorderStylesUndoMutationFactory,
-} from '../mutations/set-border-styles.mutatio';
+} from '../mutations/set-border-styles.mutation';
export interface ISetBorderCommandParams {
workbookId?: string;
diff --git a/packages/base-sheets/src/commands/commands/set-range-values.command.ts b/packages/base-sheets/src/commands/commands/set-range-values.command.ts
index 3b776b526b..378bbf38fd 100644
--- a/packages/base-sheets/src/commands/commands/set-range-values.command.ts
+++ b/packages/base-sheets/src/commands/commands/set-range-values.command.ts
@@ -24,6 +24,12 @@ export interface ISetRangeValuesCommandParams {
worksheetId?: string;
workbookId?: string;
range?: ISelectionRange;
+
+ /**
+ * 1. ICellData: Normal cell data
+ * 2. ICellData[][]: The two-dimensional array indicates the data of multiple cells
+ * 3. ObjectMatrixPrimitiveType<ICellData>: Bring the row/column information MATRIX, indicating the data of multiple cells
+ */
value: ICellData | ICellData[][] | ObjectMatrixPrimitiveType<ICellData>;
}
@@ -58,20 +64,38 @@ export const SetRangeValuesCommand: ICommand = {
const cellValue = new ObjectMatrix<ICellData>();
let realCellValue: ObjectMatrixPrimitiveType<ICellData> | undefined;
- // FIXME: this is actually not ideal
- for (let i = 0; i < currentSelections.length; i++) {
- const { startRow, startColumn, endRow, endColumn } = currentSelections[i];
- if (Tools.isArray(value)) {
+ // for (let i = 0; i < currentSelections.length; i++) {
+ // const { startRow, startColumn, endRow, endColumn } = currentSelections[i];
+ // if (Tools.isArray(value)) {
+ // for (let r = 0; r <= endRow - startRow; r++) {
+ // for (let c = 0; c <= endColumn - startColumn; c++) {
+ // cellValue.setValue(r + startRow, c + startColumn, value[r][c]);
+ // }
+ // }
+ // } else if (isICellData(value)) {
+ // cellValue.setValue(startRow, startColumn, value);
+ // } else {
+ // realCellValue = value as ObjectMatrixPrimitiveType<ICellData>;
+ // }
+ // }
+ if (Tools.isArray(value)) {
+ for (let i = 0; i < currentSelections.length; i++) {
+ const { startRow, startColumn, endRow, endColumn } = currentSelections[i];
+
for (let r = 0; r <= endRow - startRow; r++) {
for (let c = 0; c <= endColumn - startColumn; c++) {
cellValue.setValue(r + startRow, c + startColumn, value[r][c]);
}
}
- } else if (isICellData(value)) {
+ }
+ } else if (isICellData(value)) {
+ for (let i = 0; i < currentSelections.length; i++) {
+ const { startRow, startColumn } = currentSelections[i];
+
cellValue.setValue(startRow, startColumn, value);
- } else {
- realCellValue = value as ObjectMatrixPrimitiveType<ICellData>;
}
+ } else {
+ realCellValue = value as ObjectMatrixPrimitiveType<ICellData>;
}
const setRangeValuesMutationParams: ISetRangeValuesMutationParams = {
diff --git a/packages/base-sheets/src/commands/mutations/set-border-styles.mutatio.ts b/packages/base-sheets/src/commands/mutations/set-border-styles.mutation.ts
similarity index 84%
rename from packages/base-sheets/src/commands/mutations/set-border-styles.mutatio.ts
rename to packages/base-sheets/src/commands/mutations/set-border-styles.mutation.ts
index 2b7c2bc5ec..a0f30e36f2 100644
--- a/packages/base-sheets/src/commands/mutations/set-border-styles.mutatio.ts
+++ b/packages/base-sheets/src/commands/mutations/set-border-styles.mutation.ts
@@ -189,15 +189,18 @@ export function mergeStyle(
backupStyle[k] = Object.assign(backupStyle[k], newStyle[k]);
} else {
backupStyle[k] = (newStyle as IKeyValue)[k];
+ }
+ }
- // overline/strikethrough/underline add color
- if ('cl' in backupStyle) {
- if (['ul', 'ol', 'st'].includes(k)) {
- backupStyle[k].cl = backupStyle.cl;
- }
+ // Overline/Strikethrough/Underline color follows text color
+ if ('cl' in backupStyle) {
+ for (const k in newStyle) {
+ if (['ul', 'ol', 'st'].includes(k)) {
+ backupStyle[k].cl = backupStyle.cl;
}
}
}
+
return backupStyle;
}
@@ -207,39 +210,6 @@ export function mergeStyle(
* @param newStyle
*/
export function mergeRichTextStyle(p: IDocumentData, newStyle: Nullable<IStyleData>) {
- // p.body?.blockElements.forEach((blockElement) => {
- // if (blockElement.blockType === 0) {
- // const paragraph = blockElement.paragraph;
- // paragraph?.elements.forEach((element) => {
- // if (!element.tr) {
- // element.tr = {};
- // }
-
- // const textRun = element.tr as ITextRun;
-
- // if (!textRun.ts) {
- // textRun.ts = {};
- // }
-
- // const oldStyle = textRun.ts;
-
- // const merge = mergeStyle(
- // oldStyle as Nullable<IStyleData>,
- // newStyle,
- // true
- // );
-
- // // then remove null
- // merge && Tools.removeNull(merge);
-
- // if (Tools.isEmptyObject(merge)) {
- // delete textRun.ts;
- // } else {
- // textRun.ts = merge as ITextStyle;
- // }
- // });
- // }
- // });
p.body?.textRuns?.forEach((textRun) => {
if (!textRun.ts) {
textRun.ts = {};
diff --git a/packages/base-sheets/src/commands/mutations/set-range-styles.mutation.ts b/packages/base-sheets/src/commands/mutations/set-range-styles.mutation.ts
index 0aedd16de7..0c3455af44 100644
--- a/packages/base-sheets/src/commands/mutations/set-range-styles.mutation.ts
+++ b/packages/base-sheets/src/commands/mutations/set-range-styles.mutation.ts
@@ -28,6 +28,7 @@ export interface ISetRangeStyleMutationParams {
* @param {IAccessor} accessor - injector accessor
* @param {ISetRangeStyleMutationParams} params - do mutation params
* @returns {ISetRangeStyleMutationParams} undo mutation params
+ *
*/
export const SetRangeStyleUndoMutationFactory = (
accessor: IAccessor,
@@ -69,6 +70,9 @@ export const SetRangeStyleUndoMutationFactory = (
} as ISetRangeStyleMutationParams;
};
+/**
+ * @deprecated use set range values mutation instead
+ */
export const SetRangeStyleMutation: IMutation<ISetRangeStyleMutationParams, boolean> = {
id: 'sheet.mutation.set-range-style',
type: CommandType.MUTATION,
diff --git a/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts b/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts
index 6ecf38b813..9fa2e37c5b 100644
--- a/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts
+++ b/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts
@@ -5,19 +5,26 @@ import {
ICurrentUniverService,
IMutation,
ISelectionRange,
+ IStyleData,
+ Nullable,
ObjectMatrix,
ObjectMatrixPrimitiveType,
Tools,
} from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
+import { mergeRichTextStyle, mergeStyle, transformStyle } from './set-border-styles.mutation';
+
/** Params of `SetRangeValuesMutation` */
export interface ISetRangeValuesMutationParams {
- workbookId?: string;
+ rangeData: ISelectionRange[]; // FIXME: maybe don't need this
worksheetId: string;
- rangeData: ISelectionRange[];
+ workbookId: string;
- cellValue?: ObjectMatrixPrimitiveType<ICellData>;
+ /**
+ * null for clear all
+ */
+ cellValue?: ObjectMatrixPrimitiveType<ICellData | null>;
/**
* @deprecated not a good design
@@ -36,28 +43,45 @@ export const SetRangeValuesUndoMutationFactory = (
accessor: IAccessor,
params: ISetRangeValuesMutationParams
): ISetRangeValuesMutationParams => {
+ const { workbookId, worksheetId, cellValue } = params;
const currentUniverService = accessor.get(ICurrentUniverService);
- const worksheet = currentUniverService
- .getCurrentUniverSheetInstance()
- .getWorkBook()
- .getSheetBySheetId(params.worksheetId);
+ const universheet = currentUniverService.getUniverSheetInstance(workbookId);
+ if (universheet == null) {
+ throw new Error('universheet is null error!');
+ }
+
+ const workbook = universheet.getWorkBook();
+
+ const worksheet = workbook.getSheetBySheetId(worksheetId);
if (worksheet == null) {
throw new Error('worksheet is null error!');
}
- const cellMatrix = worksheet.getCellMatrix();
+ const cellMatrix = worksheet.getCellMatrix();
+ const styles = workbook.getStyles();
const undoData = new ObjectMatrix<ICellData>();
- for (let i = 0; i < params.rangeData.length; i++) {
- const { startRow, endRow, startColumn, endColumn } = params.rangeData[i];
+ const newValues = new ObjectMatrix(cellValue);
- for (let r = startRow; r <= endRow; r++) {
- for (let c = startColumn; c <= endColumn; c++) {
- const value = cellMatrix?.getValue(r, c);
- undoData.setValue(r, c, Tools.deepClone(value as ICellData));
- }
- }
- }
+ // for (let i = 0; i < rangeData.length; i++) {
+ newValues.forValue((row, col, newVal) => {
+ const cell = Tools.deepClone(cellMatrix?.getValue(row, col)) || {}; // clone cell data,prevent modify the original data
+ const oldStyle = styles.getStyleByCell(cell);
+ const newStyle = transformStyle(oldStyle, newVal && newVal.s ? (newVal.s as Nullable<IStyleData>) : null);
+ cell.s = newStyle;
+
+ undoData.setValue(row, col, Tools.deepClone(setNull(cell)));
+ });
+ // for (let i = 0; i < params.rangeData.length; i++) {
+ // const { startRow, endRow, startColumn, endColumn } = params.rangeData[i];
+
+ // for (let r = startRow; r <= endRow; r++) {
+ // for (let c = startColumn; c <= endColumn; c++) {
+ // const value = cellMatrix?.getValue(r, c);
+ // undoData.setValue(r, c, Tools.deepClone(value as ICellData));
+ // }
+ // }
+ // }
return {
...Tools.deepClone(params),
@@ -66,7 +90,37 @@ export const SetRangeValuesUndoMutationFactory = (
} as ISetRangeValuesMutationParams;
};
-// TODO@Dushusir: this would cover style as well. Which is not expected.
+/**
+ * Supplement the data of the cell, set the other value to NULL, Used to reset properties when undoing
+ * @param value
+ * @returns
+ */
+function setNull(value: Nullable<ICellData>) {
+ if (value == null) return null;
+
+ if (value.p === undefined) {
+ value.p = null;
+ }
+
+ if (value.v === undefined) {
+ value.v = null;
+ }
+
+ if (value.m === undefined) {
+ value.m = null;
+ }
+
+ if (value.t === undefined) {
+ value.t = null;
+ }
+
+ if (value.s === undefined) {
+ value.s = null;
+ }
+
+ return value;
+}
+
export const SetRangeValuesMutation: IMutation<ISetRangeValuesMutationParams, boolean> = {
id: 'sheet.mutation.set-range-values',
type: CommandType.MUTATION,
@@ -77,59 +131,67 @@ export const SetRangeValuesMutation: IMutation<ISetRangeValuesMutationParams, bo
if (!worksheet) {
return false;
}
-
const cellMatrix = worksheet.getCellMatrix();
- const { cellValue, rangeData } = params;
+ const styles = workbook.getStyles();
+ const { cellValue } = params;
const newValues = new ObjectMatrix(cellValue);
- for (let i = 0; i < rangeData.length; i++) {
- const { startRow, startColumn, endColumn, endRow } = rangeData[i];
+ newValues.forValue((row, col, newVal) => {
+ // clear all
+ if (!newVal) {
+ cellMatrix?.setValue(row, col, {});
+ } else {
+ const oldVal = cellMatrix.getValue(row, col) || {};
- // clear selection content
- // createRowColIter(startRow, endRow, startColumn, endColumn).forEach((r, c) => {
- // if (cellMatrix.getValue(r, c)) {
- // cellMatrix.setValue(r, c, { v: null });
- // }
- // });
+ if (newVal.p !== undefined) {
+ oldVal.p = newVal.p;
+ }
- newValues.forValue((row, col, newVal) => {
- const oldVal = cellMatrix.getValue(row, col) || {};
+ // Set to null, clear content
+ if (newVal.v !== undefined) {
+ oldVal.v = newVal.v;
+ oldVal.m = String(oldVal.v);
+ }
- // clear all
- if (!newVal) {
- cellMatrix?.setValue(row, col, {
- v: null,
- });
- } else {
- let dirty = false;
-
- if (newVal.p != null) {
- oldVal.p = newVal.p;
- dirty = true;
- }
+ if (newVal.m !== undefined) {
+ oldVal.m = newVal.m;
+ }
+
+ if (newVal.t !== undefined) {
+ oldVal.t = newVal.t;
+ }
+
+ // handle style
+ if (newVal.s !== undefined) {
+ // use null to clear style
+ const oldStyle = styles.getStyleByCell(oldVal);
- if (newVal.v != null) {
- oldVal.v = newVal.v;
- dirty = true;
+ if (oldStyle == null) {
+ // clear
+ delete oldVal.s;
}
- if (newVal.m != null) {
- oldVal.m = newVal.m;
- dirty = true;
+ // set style
+ const merge = mergeStyle(oldStyle, newVal.s ? (newVal.s as Nullable<IStyleData>) : null);
+
+ // then remove null
+ merge && Tools.removeNull(merge);
+
+ if (Tools.isEmptyObject(merge)) {
+ delete oldVal.s;
} else {
- oldVal.m = String(oldVal.v);
- dirty = true;
+ oldVal.s = styles.setValue(merge);
}
- if (newVal.t != null) {
- oldVal.t = newVal.t;
- dirty = true;
+ // When the rich text sets the cell style, you need to modify the style of all rich text
+ if (oldVal.p) {
+ mergeRichTextStyle(oldVal.p, newVal.s ? (newVal.s as Nullable<IStyleData>) : null);
}
-
- cellMatrix.setValue(row, col, oldVal);
}
- });
- }
+
+ cellMatrix.setValue(row, col, Tools.removeNull(oldVal));
+ }
+ });
return true;
},
diff --git a/packages/base-slides/src/Locale/en.ts b/packages/base-slides/src/Locale/en.ts
index e3809e731b..f6ba473eaa 100644
--- a/packages/base-slides/src/Locale/en.ts
+++ b/packages/base-slides/src/Locale/en.ts
@@ -447,7 +447,7 @@ export default {
confirm: 'Confirm',
orderAZ: 'A-Z order',
orderZA: 'Z-A order',
- clearContent: 'Clear content',
+ clearContent: 'Clear Contents',
matrix: 'Matrix operation',
sortSelection: 'Sort',
filterSelection: 'Filter',
diff --git a/packages/base-ui/src/views/components/contextmenu/contextmenu.tsx b/packages/base-ui/src/views/components/contextmenu/contextmenu.tsx
index 7028765bba..af6f6f490d 100644
--- a/packages/base-ui/src/views/components/contextmenu/contextmenu.tsx
+++ b/packages/base-ui/src/views/components/contextmenu/contextmenu.tsx
@@ -1,5 +1,5 @@
import { IMouseEvent } from '@univerjs/base-render';
-import { DisposableCollection } from '@univerjs/core';
+import { DisposableCollection, ICommandService } from '@univerjs/core';
import { RediContext, WithDependency } from '@wendellhu/redi/react-bindings';
import React, { Component, createRef } from 'react';
@@ -13,10 +13,12 @@ export interface IContextMenuProps extends BaseMenuItem {}
export interface IContextMenuState {
visible: boolean;
- srcElement?: HTMLElement; // FIXME: any?
- eventType: string | null;
children: IContextMenuProps[];
menuItems: Array<IDisplayMenuItem<IMenuItem>>;
+ clientPosition: {
+ clientX: number;
+ clientY: number;
+ };
}
export class ContextMenu extends Component<IContextMenuProps, IContextMenuState> {
@@ -27,8 +29,6 @@ export class ContextMenu extends Component<IContextMenuProps, IContextMenuState>
@WithDependency(IContextMenuService)
private declare contextMenuService: IContextMenuService;
- private menuRef = createRef<Menu>();
-
private rootRef = createRef<HTMLDivElement>();
private _disposables = new DisposableCollection();
@@ -38,10 +38,12 @@ export class ContextMenu extends Component<IContextMenuProps, IContextMenuState>
this.state = {
visible: false,
- srcElement: null, // WTF: this property is weird
- eventType: null, // WTF: this property is weird
children: [] as IContextMenuProps[],
menuItems: [] as Array<IDisplayMenuItem<IMenuItem>>,
+ clientPosition: {
+ clientX: 0,
+ clientY: 0,
+ },
};
}
@@ -61,12 +63,23 @@ export class ContextMenu extends Component<IContextMenuProps, IContextMenuState>
}
override render() {
- const { visible } = this.state;
+ const { visible, clientPosition } = this.state;
return (
visible && (
<div ref={this.rootRef} className={styles.contextMenu} onContextMenu={(e) => e.preventDefault()}>
- <Menu menuId={MenuPosition.CONTEXT_MENU} onClick={this.handleClick} show={visible} />
+ <Menu
+ menuId={MenuPosition.CONTEXT_MENU}
+ onClick={this.handleClick}
+ clientPosition={clientPosition}
+ show={visible}
+ onOptionSelect={(params) => {
+ const { label: commandId, value } = params;
+ const commandService = this.context.injector?.get(ICommandService);
+ commandService && commandService.executeCommand(commandId as string, { value });
+ this.setState({ visible: false });
+ }}
+ />
</div>
)
);
@@ -75,64 +88,29 @@ export class ContextMenu extends Component<IContextMenuProps, IContextMenuState>
handleContextMenu = async (event: IMouseEvent, rect?: any, down?: boolean) => {
event.preventDefault();
- // FIXME: srcElement is deprecated
// FIXME: contextmenu position algorithm is not correct
- this.setState({ visible: true, srcElement: event.srcElement, eventType: event.type }, () => {
+ this.setState({ visible: true }, () => {
new Promise<void>((resolve, reject) => {
resolve();
}).then(() => {
- // clientX/Y 获取到的是触发点相对于浏览器可视区域左上角距离
- const clickX = !down ? event.clientX : rect.x;
- const clickY = !down ? event.clientY : rect.y;
-
- // window.innerWidth/innerHeight 获取的是当前浏览器窗口的视口宽度/高度
- const screenW = window.innerWidth;
- const screenH = window.innerHeight;
- // 获取自定义菜单的宽度/高度
- const currentUl = this.menuRef.current?.getMenuRef().current;
- const rootW = currentUl?.offsetWidth || 0;
- const rootH = currentUl?.offsetHeight || 0;
-
- // right为true,说明鼠标点击的位置到浏览器的右边界的宽度可以放下菜单。否则,菜单放到左边。
- // bottom为true,说明鼠标点击位置到浏览器的下边界的高度可以放下菜单。否则,菜单放到上边。
- const right = screenW - clickX > rootW;
- const left = !right;
- const bottom = screenH - clickY > rootH;
- const top = !bottom;
-
- const current = this.rootRef.current;
- if (!current) {
- return;
- }
-
- if (right) {
- current.style.left = `${clickX}px`;
- }
- if (left) {
- current.style.left = `${clickX - rootW}px`;
- }
-
- if (bottom) {
- current.style.top = `${clickY}px`;
- }
- if (top) {
- current.style.top = `${clickY - rootH}px`;
- }
+ // clientX/Y obtains the distance between the trigger point and the upper left corner of the browser's visible area.
+ this.setState({
+ clientPosition: {
+ clientX: event.clientX,
+ clientY: event.clientY,
+ },
+ });
});
});
};
private handleClick = (e: MouseEvent) => {
- const { visible, eventType, srcElement } = this.state;
+ const { visible } = this.state;
if (!this.rootRef.current) {
return;
}
- if (eventType === 'click' && srcElement && srcElement.contains(e.target)) {
- return;
- }
-
- if (this.rootRef.current.contains(e.target)) {
+ if (this.rootRef.current.contains(e.target as Node)) {
return;
}
diff --git a/packages/core/src/Basics/Univer.ts b/packages/core/src/Basics/Univer.ts
index 52f49f077d..43b78dc349 100644
--- a/packages/core/src/Basics/Univer.ts
+++ b/packages/core/src/Basics/Univer.ts
@@ -238,4 +238,6 @@ export class Univer {
slide.addPlugin(p.plugin as unknown as PluginCtor<any>, p.options);
});
}
+
+ dispose(): void {}
}
diff --git a/packages/core/src/Shared/ObjectArray.ts b/packages/core/src/Shared/ObjectArray.ts
index d4819c2959..5424d40dca 100644
--- a/packages/core/src/Shared/ObjectArray.ts
+++ b/packages/core/src/Shared/ObjectArray.ts
@@ -130,13 +130,14 @@ export class ObjectArray<T> {
}
set(index: number, value: T): void {
- if (define(value)) {
- const length = this._length;
- this._array[index] = value;
- if (index >= length) {
- this._length = index + 1;
- }
+ // Accept NULL, for cell clear all
+ // if (define(value)) {
+ const length = this._length;
+ this._array[index] = value;
+ if (index >= length) {
+ this._length = index + 1;
}
+ // }
}
pop(): Nullable<T> {
diff --git a/packages/core/src/Shared/Tools.ts b/packages/core/src/Shared/Tools.ts
index 4bbeeffc3d..ecf67cecfb 100644
--- a/packages/core/src/Shared/Tools.ts
+++ b/packages/core/src/Shared/Tools.ts
@@ -477,7 +477,6 @@ export class Tools {
*/
static removeNull(value: IKeyValue): object {
if (this.isObject(value)) {
- const clone = {};
Object.keys(value).forEach((key) => {
const item = value[key];
if (item == null) {
@@ -486,7 +485,6 @@ export class Tools {
Tools.removeNull(item);
}
});
- return clone;
}
return value;
}
diff --git a/packages/core/src/Types/Interfaces/ICellData.ts b/packages/core/src/Types/Interfaces/ICellData.ts
index 9cf1e9bdbe..44941c458e 100644
--- a/packages/core/src/Types/Interfaces/ICellData.ts
+++ b/packages/core/src/Types/Interfaces/ICellData.ts
@@ -18,7 +18,7 @@ export type ICellV = string | number | boolean;
export interface ICellData {
// The unique key, a random string, is used for the plug-in to associate the cell. When the cell information changes, the plug-in does not need to change the data, reducing the pressure on the back-end interface
// id?: string;
- p?: IDocumentData; // univer docs
+ p?: Nullable<IDocumentData>; // univer docs, set null for cell clear all
s?: string | Nullable<IStyleData>; // style id
/**
* Origin value
@@ -26,7 +26,7 @@ export interface ICellData {
v?: Nullable<ICellV>;
m?: Nullable<string>; // formatted value
// Usually the type is automatically determined based on the data, or the user directly specifies
- t?: CellValueType; // 0 string, 1 number, 2 boolean, 3 force string, green icon
+ t?: Nullable<CellValueType>; // 0 string, 1 number, 2 boolean, 3 force string, green icon, set null for cell clear all
// f?: string; // formula '=SUM(1)'
/**
* format
diff --git a/packages/ui-plugin-docs/src/Locale/en.ts b/packages/ui-plugin-docs/src/Locale/en.ts
index c9571663cd..96f0973a17 100644
--- a/packages/ui-plugin-docs/src/Locale/en.ts
+++ b/packages/ui-plugin-docs/src/Locale/en.ts
@@ -462,7 +462,7 @@ export default {
confirm: 'Confirm',
orderAZ: 'A-Z order',
orderZA: 'Z-A order',
- clearContent: 'Clear content',
+ clearContent: 'Clear Contents',
matrix: 'Matrix operation',
sortSelection: 'Sort',
filterSelection: 'Filter',
diff --git a/packages/ui-plugin-sheets/src/Locale/en.ts b/packages/ui-plugin-sheets/src/Locale/en.ts
index edca50b117..b0ce07f3a8 100644
--- a/packages/ui-plugin-sheets/src/Locale/en.ts
+++ b/packages/ui-plugin-sheets/src/Locale/en.ts
@@ -462,7 +462,7 @@ export default {
confirm: 'Confirm',
orderAZ: 'A-Z order',
orderZA: 'Z-A order',
- clearContent: 'Clear content',
+ clearContent: 'Clear Contents',
matrix: 'Matrix operation',
sortSelection: 'Sort',
filterSelection: 'Filter',