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.

chore: remove legacy code in core (#220)

Wenzhao Hu55bd8ea02e9e
diff --git a/packages/base-sheets/src/Basics/Interfaces/MutationInterface.ts b/packages/base-sheets/src/Basics/Interfaces/MutationInterface.ts
index b9ad903b04..9bc7880f35 100644
--- a/packages/base-sheets/src/Basics/Interfaces/MutationInterface.ts
+++ b/packages/base-sheets/src/Basics/Interfaces/MutationInterface.ts
@@ -39,7 +39,7 @@ export interface IInsertColMutationParams {
}
/** Params of InsertRowMutation */
-export interface IRemoveRowMutationParams {
+export interface IRemoveRowsMutationParams {
workbookId: string;
worksheetId: string;
ranges: IRange[];
diff --git a/packages/base-sheets/src/Controller/BasicWorkbook.controller.ts b/packages/base-sheets/src/Controller/BasicWorkbook.controller.ts
deleted file mode 100644
index 950c5b7371..0000000000
--- a/packages/base-sheets/src/Controller/BasicWorkbook.controller.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import {
- Disposable,
- ICommandService,
- IWorksheetConfig,
- LifecycleStages,
- ObserverManager,
- OnLifecycle,
-} from '@univerjs/core';
-import { IDisposable, Inject, SkipSelf } from '@wendellhu/redi';
-
-import { InsertSheetCommand } from '../commands/commands/insert-sheet.command';
-import { RemoveSheetCommand } from '../commands/commands/remove-sheet.command';
-
-/**
- * The controller to provide the most basic sheet CRUD methods to other modules of sheet modules.
- */
-@OnLifecycle(LifecycleStages.Rendered, BasicWorkbookController)
-export class BasicWorkbookController extends Disposable implements IDisposable {
- constructor(
- @ICommandService private readonly _commandService: ICommandService,
- @SkipSelf() @Inject(ObserverManager) private readonly _globalObserverManager: ObserverManager
- ) {
- super();
- }
-
- onInitialize() {}
-
- /**
- * Insert new worksheet
- */
- async insertSheet(index: number, sheet: Partial<IWorksheetConfig>, workbookId: string): Promise<boolean> {
- const options = {
- index,
- sheet,
- workbookId,
- };
- return this._commandService.executeCommand(InsertSheetCommand.id, options);
- }
-
- /**
- * remove worksheet
- */
- async removeSheet(sheetId: string, workbookId: string): Promise<boolean> {
- const options = {
- sheetId,
- workbookId,
- };
- return this._commandService.executeCommand(RemoveSheetCommand.id, options);
- }
-
- // TODO@Dushusir setDefaultActiveSheet(use worksheet set status) activateSheetByIndex(use worksheet activate)
-}
diff --git a/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts b/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts
index c2d346c32b..00077685d6 100644
--- a/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts
+++ b/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts
@@ -23,6 +23,7 @@ import {
InsertRowCommand,
} from '../commands/commands/insert-row-col.command';
import { InsertSheetCommand } from '../commands/commands/insert-sheet.command';
+import { MoveRowsCommand } from '../commands/commands/move-rows.command';
import { RemoveColCommand, RemoveRowCommand } from '../commands/commands/remove-row-col.command';
import { RemoveSheetCommand } from '../commands/commands/remove-sheet.command';
import { RemoveWorksheetMergeCommand } from '../commands/commands/remove-worksheet-merge.command';
@@ -124,6 +125,7 @@ export class BasicWorksheetController extends Disposable implements IDisposable
InsertColMutation,
RemoveColCommand,
RemoveColMutation,
+ MoveRowsCommand,
SetColWidthCommand,
SetWorksheetColWidthMutation,
diff --git a/packages/base-sheets/src/Controller/header-move.controller.ts b/packages/base-sheets/src/Controller/header-move.controller.ts
index 2df3c1298d..a2c6a65b1a 100644
--- a/packages/base-sheets/src/Controller/header-move.controller.ts
+++ b/packages/base-sheets/src/Controller/header-move.controller.ts
@@ -11,6 +11,7 @@ import {
} from '@univerjs/base-render';
import {
Disposable,
+ ICommandService,
ICurrentUniverService,
LifecycleStages,
Nullable,
@@ -22,6 +23,8 @@ import { Inject } from '@wendellhu/redi';
import { getCoordByOffset, getSheetObject, ISheetObjectParam } from '../Basics/component-tools';
import { SHEET_COMPONENT_HEADER_LAYER_INDEX, VIEWPORT_KEY } from '../Basics/Const/DEFAULT_SPREADSHEET_VIEW';
+import { IMoveColumnsCommandParams, MoveColumnsCommand } from '../commands/commands/move-columns-to.command';
+import { IMoveRowsCommandParams, MoveRowsCommand } from '../commands/commands/move-rows.command';
import { SelectionManagerService } from '../services/selection-manager.service';
import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';
@@ -103,6 +106,7 @@ export class HeaderMoveController extends Disposable {
@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
+ @ICommandService private readonly _commandService: ICommandService,
@ISelectionTransformerShapeManager
private readonly _selectionTransformerShapeManager: ISelectionTransformerShapeManager,
@Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService
@@ -240,22 +244,33 @@ export class HeaderMoveController extends Disposable {
});
});
- this._upObserver = scene.onPointerUpObserver.add((upEvt: IPointerEvent | IMouseEvent) => {
+ this._upObserver = scene.onPointerUpObserver.add((_upEvt: IPointerEvent | IMouseEvent) => {
this._disposeBackgroundAndLine();
scene.resetCursor();
scene.enableEvent();
this._clearObserverEvent();
this._scrollTimer?.dispose();
- if (initialType === HEADER_MOVE_TYPE.ROW) {
- console.log(this._changeToRow);
- // this._commandService.executeCommand();
- // alert(`moveColumnTo: ${this._changeToRow}`);
+ // when multi ranges are selected, we should only move the range that contains
+ // `changeFromRow`
+ if (initialType === HEADER_MOVE_TYPE.ROW) {
+ if (this._changeFromRow !== this._changeToRow) {
+ this._commandService.executeCommand<IMoveRowsCommandParams>(MoveRowsCommand.id, {
+ fromRow: this._changeFromRow,
+ toRow: this._changeToRow,
+ });
+ }
+
+ // reset dragging status
this._changeToRow = this._changeFromRow = -1;
} else {
- console.log(this._changeToColumn);
- // alert(`moveColumnTo: ${this._changeToColumn}`);
+ if (this._changeFromColumn !== this._changeToColumn) {
+ this._commandService.executeCommand<IMoveColumnsCommandParams>(MoveColumnsCommand.id, {
+ fromColumn: this._changeFromColumn,
+ toColumn: this._changeToColumn,
+ });
+ }
this._changeToColumn = this._changeFromColumn = -1;
}
diff --git a/packages/base-sheets/src/Controller/index.ts b/packages/base-sheets/src/Controller/index.ts
index 14a3e4ba4f..145f80077e 100644
--- a/packages/base-sheets/src/Controller/index.ts
+++ b/packages/base-sheets/src/Controller/index.ts
@@ -1,3 +1,2 @@
-export * from './BasicWorkbook.controller';
export * from './BasicWorksheet.controller';
export * from './CountBarController';
diff --git a/packages/base-sheets/src/SheetPlugin.ts b/packages/base-sheets/src/SheetPlugin.ts
index a4f5af6637..d7fdaed2f5 100644
--- a/packages/base-sheets/src/SheetPlugin.ts
+++ b/packages/base-sheets/src/SheetPlugin.ts
@@ -4,7 +4,7 @@ import { Dependency, Inject, Injector } from '@wendellhu/redi';
import { SheetPluginObserve, uninstall } from './Basics/Observer';
import { SetSelectionsOperation } from './commands/operations/selection.operation';
-import { BasicWorkbookController, CountBarController } from './Controller';
+import { CountBarController } from './Controller';
import { BasicWorksheetController } from './Controller/BasicWorksheet.controller';
import { FormulaBarController } from './Controller/FormulaBarController';
import { FreezeController } from './Controller/freeze.controller';
@@ -28,6 +28,7 @@ export class SheetPlugin extends Plugin<SheetPluginObserve> {
static override type = PluginType.Sheet;
constructor(
+ config: undefined,
@ICommandService private readonly _commandService: ICommandService,
@Inject(LocaleService) private readonly _localeService: LocaleService,
@Inject(Injector) override readonly _injector: Injector
@@ -53,7 +54,6 @@ export class SheetPlugin extends Plugin<SheetPluginObserve> {
this._injector.get(CountBarController);
this._injector.get(BasicWorksheetController);
- this._injector.get(BasicWorkbookController);
this._injector.get(SelectionController);
@@ -108,7 +108,6 @@ export class SheetPlugin extends Plugin<SheetPluginObserve> {
[FormulaBarController],
[CountBarController],
[BasicWorksheetController],
- [BasicWorkbookController],
[SelectionController],
[SheetRenderController],
[HeaderMenuController],
diff --git a/packages/base-sheets/src/commands/commands/insert-row-col.command.ts b/packages/base-sheets/src/commands/commands/insert-row-col.command.ts
index 7f27fd12fc..a587f7c116 100644
--- a/packages/base-sheets/src/commands/commands/insert-row-col.command.ts
+++ b/packages/base-sheets/src/commands/commands/insert-row-col.command.ts
@@ -1,15 +1,19 @@
import {
CommandType,
Dimension,
+ Direction,
ICellData,
ICommand,
+ ICommandInfo,
ICommandService,
ICurrentUniverService,
IRange,
IUndoRedoService,
Nullable,
ObjectMatrix,
+ sequenceExecute,
Tools,
+ Worksheet,
} from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
@@ -20,7 +24,7 @@ import {
IInsertRangeMutationParams,
IInsertRowMutationParams,
IRemoveColMutationParams,
- IRemoveRowMutationParams,
+ IRemoveRowsMutationParams,
IRemoveWorksheetMergeMutationParams,
} from '../../Basics/Interfaces/MutationInterface';
import { SelectionManagerService } from '../../services/selection-manager.service';
@@ -31,7 +35,7 @@ import {
InsertColMutation,
InsertColMutationFactory,
InsertRowMutation,
- InsertRowMutationFactory,
+ InsertRowMutationUndoFactory,
} from '../mutations/insert-row-col.mutation';
import { RemoveColMutation, RemoveRowMutation } from '../mutations/remove-row-col.mutation';
import {
@@ -39,46 +43,48 @@ import {
RemoveWorksheetMergeMutationFactory,
} from '../mutations/remove-worksheet-merge.mutation';
-export interface InsertRowCommandParams {
- value: number;
-}
-
-export interface InsertRowCommandBaseParams {
+export interface IInsertRowCommandParams {
workbookId: string;
worksheetId: string;
+ direction: Direction.UP | Direction.DOWN;
range: IRange;
}
+/**
+ * @internal use `InsertRowBeforeCommand` or `InsertRowAfterCommand` as an external user
+ *
+ * this command and its interface should not be exported from index.ts
+ */
export const InsertRowCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.insert-row',
- // eslint-disable-next-line max-lines-per-function
- handler: async (accessor: IAccessor, params: InsertRowCommandBaseParams) => {
+ handler: async (accessor: IAccessor, params: IInsertRowCommandParams) => {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const workbook = currentUniverService.getUniverSheetInstance(params.workbookId)?.getWorkBook();
- if (!workbook) return false;
- const worksheet = workbook.getSheetBySheetId(params.worksheetId);
- if (!worksheet) return false;
+ const workbook = currentUniverService.getUniverSheetInstance(params.workbookId)!.getWorkBook()!;
+ const worksheet = workbook.getSheetBySheetId(params.worksheetId)!;
- const redoMutationParams: IInsertRowMutationParams = {
+ // insert rows & undos
+ const redoInsertMutationParams: IInsertRowMutationParams = {
workbookId: params.workbookId,
worksheetId: params.worksheetId,
ranges: [params.range],
};
- const undoMutationParams: IRemoveRowMutationParams = InsertRowMutationFactory(accessor, redoMutationParams);
- const result = commandService.executeCommand(InsertRowMutation.id, redoMutationParams);
+ const undoMutationParams: IRemoveRowsMutationParams = InsertRowMutationUndoFactory(
+ accessor,
+ redoInsertMutationParams
+ );
+ // insert range values & undos
const { startRow, endRow, startColumn, endColumn } = params.range;
const cellValue = new ObjectMatrix<ICellData>();
for (let i = startRow; i <= endRow; i++) {
for (let j = startColumn; j <= endColumn; j++) {
- cellValue.setValue(i, j, { v: '', m: '' });
+ cellValue.setValue(i, j, { v: '', m: '' }); // FIXME@wzhudev: should copy styles
}
}
-
const insertRangeMutationParams: IInsertRangeMutationParams = {
workbookId: params.workbookId,
worksheetId: params.worksheetId,
@@ -86,14 +92,12 @@ export const InsertRowCommand: ICommand = {
shiftDimension: Dimension.ROWS,
cellValue: cellValue.getData(),
};
-
- const deleteRangeMutationParams: Nullable<IDeleteRangeMutationParams> = InsertRangeUndoMutationFactory(
+ const undoInsertRangeMutationParams: Nullable<IDeleteRangeMutationParams> = InsertRangeUndoMutationFactory(
accessor,
insertRangeMutationParams
);
- if (!deleteRangeMutationParams) return false;
- const deleteResult = commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);
+ // update merged cells & undos
const mergeData = Tools.deepClone(worksheet.getMergeData());
for (let i = 0; i < mergeData.length; i++) {
const merge = mergeData[i];
@@ -107,7 +111,6 @@ export const InsertRowCommand: ICommand = {
merge.endRow += count;
}
}
-
const removeMergeMutationParams: IRemoveWorksheetMergeMutationParams = {
workbookId: params.workbookId,
worksheetId: params.worksheetId,
@@ -117,74 +120,53 @@ export const InsertRowCommand: ICommand = {
accessor,
removeMergeMutationParams
);
- const removeResult = commandService.executeCommand(RemoveWorksheetMergeMutation.id, removeMergeMutationParams);
-
const addMergeMutationParams: IAddWorksheetMergeMutationParams = {
workbookId: params.workbookId,
worksheetId: params.worksheetId,
ranges: mergeData,
};
- const deleteMergeMutationParams: IRemoveWorksheetMergeMutationParams = AddWorksheetMergeMutationFactory(
+ const undoAddMergeMutationParams: IRemoveWorksheetMergeMutationParams = AddWorksheetMergeMutationFactory(
accessor,
addMergeMutationParams
);
- const mergeResult = commandService.executeCommand(AddWorksheetMergeMutation.id, addMergeMutationParams);
- if (result && deleteResult && removeResult && mergeResult) {
+ const result = await sequenceExecute(
+ [
+ { id: InsertRowMutation.id, params: redoInsertMutationParams },
+ { id: InsertRangeMutation.id, params: insertRangeMutationParams },
+ { id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams },
+ { id: AddWorksheetMergeMutation.id, params: addMergeMutationParams },
+ ],
+ commandService
+ );
+
+ if (result.result) {
undoRedoService.pushUndoRedo({
URI: params.workbookId,
- undo() {
- return (
- commandService.executeCommand(
- DeleteRangeMutation.id,
- deleteRangeMutationParams
- ) as Promise<boolean>
- )
- .then((res) => {
- if (res) return commandService.executeCommand(RemoveRowMutation.id, undoMutationParams);
- return false;
- })
- .then((res) => {
- if (res)
- return commandService.executeCommand(
- RemoveWorksheetMergeMutation.id,
- deleteMergeMutationParams
- );
- return false;
- })
- .then((res) => {
- if (res)
- return commandService.executeCommand(
- AddWorksheetMergeMutation.id,
- undoRemoveMergeMutationParams
- );
- return false;
- });
- },
- redo() {
- return (commandService.executeCommand(InsertRowMutation.id, redoMutationParams) as Promise<boolean>)
- .then((res) => {
- if (res)
- return commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);
- return false;
- })
- .then((res) => {
- if (res)
- return commandService.executeCommand(
- RemoveWorksheetMergeMutation.id,
- removeMergeMutationParams
- );
- return false;
- })
- .then((res) => {
- if (res)
- return commandService.executeCommand(
- AddWorksheetMergeMutation.id,
- addMergeMutationParams
- );
- return false;
- });
- },
+ undo: async () =>
+ (
+ await sequenceExecute(
+ [
+ { id: DeleteRangeMutation.id, params: undoInsertRangeMutationParams },
+ { id: RemoveRowMutation.id, params: undoMutationParams },
+ { id: AddWorksheetMergeMutation.id, params: undoRemoveMergeMutationParams },
+ { id: RemoveWorksheetMergeMutation.id, params: undoAddMergeMutationParams },
+ ],
+ commandService
+ )
+ ).result,
+ redo: async () =>
+ (
+ await sequenceExecute(
+ [
+ { id: InsertRowMutation.id, params: redoInsertMutationParams },
+ { id: InsertRangeMutation.id, params: insertRangeMutationParams },
+ { id: RemoveWorksheetMergeMutation.id, params: removeMergeMutationParams },
+ { id: AddWorksheetMergeMutation.id, params: addMergeMutationParams },
+ ],
+ commandService
+ )
+ ).result,
});
return true;
}
@@ -193,97 +175,101 @@ export const InsertRowCommand: ICommand = {
},
};
-export const InsertRowBeforeCommand: ICommand<InsertRowCommandParams> = {
+export interface IInsertRowBeforeOrAfterCommandParams {
+ value: number;
+}
+
+export const InsertRowBeforeCommand: ICommand<IInsertRowBeforeOrAfterCommandParams> = {
type: CommandType.COMMAND,
id: 'sheet.command.insert-row-before',
- handler: async (accessor: IAccessor, params?: InsertRowCommandParams) => {
- const commandService = accessor.get(ICommandService);
- const currentUniverService = accessor.get(ICurrentUniverService);
+ handler: async (accessor: IAccessor, params?: IInsertRowBeforeOrAfterCommandParams) => {
const selectionManagerService = accessor.get(SelectionManagerService);
-
- const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
- const worksheetId = currentUniverService
- .getCurrentUniverSheetInstance()
- .getWorkBook()
- .getActiveSheet()
- .getSheetId();
+ const selections = selectionManagerService.getSelections()?.map((s) => s.range);
let range: IRange;
- const selections = selectionManagerService.getRangeDatas();
- if (selections && selections.length === 1) {
+
+ if (selections?.length === 1) {
range = selections[0];
} else {
+ // if there are multi selections, we can't decide which row to insert
+ // in fact, UI would hides / disables the insert row button
return false;
}
- const workbook = currentUniverService.getUniverSheetInstance(workbookId)?.getWorkBook();
- if (!workbook) return false;
- const worksheet = workbook.getSheetBySheetId(worksheetId);
- if (!worksheet) return false;
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const workbook = currentUniverService.getCurrentUniverSheetInstance()?.getWorkBook();
+ if (!workbook) {
+ return false;
+ }
- let count = range.endRow - range.startRow + 1;
- if (params) {
- count = params.value ?? 1;
+ const worksheet = workbook.getActiveSheet();
+ if (!worksheet) {
+ return false;
}
- const insertRowParams: InsertRowCommandBaseParams = {
+ const workbookId = workbook.getUnitId();
+ const worksheetId = worksheet.getSheetId();
+ const rowCount = params?.value || range.endRow - range.startRow + 1;
+
+ const insertRowParams: IInsertRowCommandParams = {
workbookId,
worksheetId,
+ direction: Direction.UP,
range: {
startRow: range.startRow,
- endRow: range.startRow + count - 1,
+ endRow: range.startRow + rowCount - 1,
startColumn: 0,
- endColumn: worksheet.getLastColumn(),
+ endColumn: 0,
},
};
- return commandService.executeCommand(InsertRowCommand.id, insertRowParams);
+ return accessor.get(ICommandService).executeCommand(InsertRowCommand.id, insertRowParams);
},
};
-export const InsertRowAfterCommand: ICommand<InsertRowCommandParams> = {
+export const InsertRowAfterCommand: ICommand<IInsertRowBeforeOrAfterCommandParams> = {
type: CommandType.COMMAND,
id: 'sheet.command.insert-row-after',
- handler: async (accessor: IAccessor, params: InsertRowCommandParams) => {
- const commandService = accessor.get(ICommandService);
- const currentUniverService = accessor.get(ICurrentUniverService);
+ handler: async (accessor: IAccessor, params: IInsertRowBeforeOrAfterCommandParams) => {
const selectionManagerService = accessor.get(SelectionManagerService);
-
- const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
- const worksheetId = currentUniverService
- .getCurrentUniverSheetInstance()
- .getWorkBook()
- .getActiveSheet()
- .getSheetId();
+ const selections = selectionManagerService.getSelections()?.map((s) => s.range);
let range: IRange;
- const selections = selectionManagerService.getRangeDatas();
- if (selections && selections.length === 1) {
+
+ if (selections?.length === 1) {
range = selections[0];
} else {
+ // if there are multi selections, we can't decide which row to insert
+ // in fact, UI would hides / disables the insert row button
return false;
}
- const workbook = currentUniverService.getUniverSheetInstance(workbookId)?.getWorkBook();
- if (!workbook) return false;
- const worksheet = workbook.getSheetBySheetId(worksheetId);
- if (!worksheet) return false;
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const workbook = currentUniverService.getCurrentUniverSheetInstance()?.getWorkBook();
+ if (!workbook) {
+ return false;
+ }
- let count = range.endRow - range.startRow + 1;
- if (params) {
- count = params.value ?? 1;
+ const worksheet = workbook.getActiveSheet();
+ if (!worksheet) {
+ return false;
}
- const insertRowParams: InsertRowCommandBaseParams = {
+ const workbookId = workbook.getUnitId();
+ const worksheetId = worksheet.getSheetId();
+ const rowCount = params?.value || range.endRow - range.startRow + 1;
+
+ const insertRowParams: IInsertRowCommandParams = {
workbookId,
worksheetId,
+ direction: Direction.DOWN,
range: {
startRow: range.endRow + 1,
- endRow: range.endRow + count,
+ endRow: range.endRow + rowCount,
startColumn: 0,
- endColumn: worksheet.getLastColumn(),
+ endColumn: 0,
},
};
- return commandService.executeCommand(InsertRowCommand.id, insertRowParams);
+ return accessor.get(ICommandService).executeCommand(InsertRowCommand.id, insertRowParams);
},
};
@@ -534,3 +520,47 @@ export const InsertColAfterCommand: ICommand<InsertColCommandParams> = {
return commandService.executeCommand(InsertColCommand.id, insertColParams);
},
};
+
+/**
+ * When inserting a row, the inserted row should copy cell styles from the anchor row.
+ */
+export function InsertRowMutationFactory(
+ anchorRow: number,
+ rowCount: number,
+ workbookId: string,
+ worksheet: Worksheet
+): ICommandInfo[] {
+ const worksheetId = worksheet.getSheetId();
+ const redoMutations: ICommandInfo[] = [];
+
+ // TODO: insert before or insert after
+
+ redoMutations.push({
+ id: InsertRowMutation.id,
+ params: {
+ workbookId,
+ worksheetId,
+ ranges: [
+ {
+ startRow: anchorRow,
+ endRow: anchorRow + rowCount - 1,
+ startColumn: 0,
+ endColumn: worksheet.getColumnCount() - 1,
+ },
+ ],
+ },
+ });
+
+ // copy cell styles to previous rows
+
+ return redoMutations;
+}
+
+export function InsertColumnMutationFactory(
+ anchorColumn: number,
+ columnCount: number,
+ worksheetId: string,
+ worksheet: Worksheet
+): ICommandInfo[] {
+ return [];
+}
diff --git a/packages/base-sheets/src/commands/commands/move-columns-to.command.ts b/packages/base-sheets/src/commands/commands/move-columns-to.command.ts
index ad4fac99b5..a1e91eaa45 100644
--- a/packages/base-sheets/src/commands/commands/move-columns-to.command.ts
+++ b/packages/base-sheets/src/commands/commands/move-columns-to.command.ts
@@ -6,14 +6,15 @@ import { SelectionManagerService } from '../../services/selection-manager.servic
import { InsertColMutation, InsertColMutationFactory } from '../mutations/insert-row-col.mutation';
import { IRemoveColMutationFactory, RemoveColMutation } from '../mutations/remove-row-col.mutation';
-export interface IMoveColumnsToCommandParams {
- destinationIndex: number;
+export interface IMoveColumnsCommandParams {
+ fromColumn: number;
+ toColumn: number;
}
-export const MoveColumnsToCommand: ICommand = {
+export const MoveColumnsCommand: ICommand = {
type: CommandType.COMMAND,
- id: 'sheet.command.move-columns-to',
- handler: async (accessor: IAccessor, params: IMoveColumnsToCommandParams) => {
+ id: 'sheet.command.move-columns',
+ handler: async (accessor: IAccessor, params: IMoveColumnsCommandParams) => {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
@@ -60,8 +61,8 @@ export const MoveColumnsToCommand: ICommand = {
...undoRemoveColumnMutationParams,
ranges: [
{
- startColumn: params.destinationIndex,
- endColumn: params.destinationIndex + endColumn - startColumn,
+ startColumn: params.toColumn,
+ endColumn: params.toColumn + endColumn - startColumn,
startRow: 0,
endRow: 0,
},
diff --git a/packages/base-sheets/src/commands/commands/move-rows-to.command.ts b/packages/base-sheets/src/commands/commands/move-rows-to.command.ts
deleted file mode 100644
index 049f2d150f..0000000000
--- a/packages/base-sheets/src/commands/commands/move-rows-to.command.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import { CommandType, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService } from '@univerjs/core';
-import { IAccessor } from '@wendellhu/redi';
-
-import { IInsertRowMutationParams, IRemoveRowMutationParams } from '../../Basics/Interfaces/MutationInterface';
-import { SelectionManagerService } from '../../services/selection-manager.service';
-import { InsertRowMutation, InsertRowMutationFactory } from '../mutations/insert-row-col.mutation';
-import { IRemoveRowMutationFactory, RemoveRowMutation } from '../mutations/remove-row-col.mutation';
-
-export interface IMoveRowsToCommandParams {
- destinationIndex: number;
-}
-
-export const MoveRowsToCommand: ICommand = {
- type: CommandType.COMMAND,
- id: 'sheet.command.move-rows-to',
- handler: async (accessor: IAccessor, params: IMoveRowsToCommandParams) => {
- const commandService = accessor.get(ICommandService);
- const undoRedoService = accessor.get(IUndoRedoService);
- const currentUniverService = accessor.get(ICurrentUniverService);
- const selectionManagerService = accessor.get(SelectionManagerService);
-
- const originRange = selectionManagerService.getRangeDatas()?.[0];
- if (!originRange) {
- return false;
- }
-
- const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
- const worksheetId = currentUniverService
- .getCurrentUniverSheetInstance()
- .getWorkBook()
- .getActiveSheet()
- .getSheetId();
- const workbook = currentUniverService.getUniverSheetInstance(workbookId)?.getWorkBook();
- if (!workbook) return false;
- const worksheet = workbook.getSheetBySheetId(worksheetId);
- if (!worksheet) return false;
-
- const { startRow, endRow } = originRange;
-
- const removeRowMutationParams: IRemoveRowMutationParams = {
- workbookId,
- worksheetId,
- ranges: [
- {
- startColumn: 0,
- endColumn: 0,
- startRow,
- endRow,
- },
- ],
- };
- const undoRemoveRowMutationParams: IInsertRowMutationParams = IRemoveRowMutationFactory(
- accessor,
- removeRowMutationParams
- );
-
- const removeResult = commandService.executeCommand(RemoveRowMutation.id, removeRowMutationParams);
-
- const insertRowMutationParams: IInsertRowMutationParams = {
- ...undoRemoveRowMutationParams,
- ranges: [
- {
- startColumn: 0,
- endColumn: 0,
- startRow: params.destinationIndex,
- endRow: params.destinationIndex + endRow - startRow,
- },
- ],
- };
-
- const undoMutationParams: IRemoveRowMutationParams = InsertRowMutationFactory(
- accessor,
- insertRowMutationParams
- );
-
- const result = commandService.executeCommand(InsertRowMutation.id, insertRowMutationParams);
-
- if (removeResult && result) {
- undoRedoService.pushUndoRedo({
- URI: workbookId,
- undo() {
- return (
- commandService.executeCommand(
- InsertRowMutation.id,
- undoRemoveRowMutationParams
- ) as Promise<boolean>
- ).then((res) => {
- if (res) return commandService.executeCommand(RemoveRowMutation.id, undoMutationParams);
- return false;
- });
- },
- redo() {
- return (
- commandService.executeCommand(RemoveRowMutation.id, removeRowMutationParams) as Promise<boolean>
- ).then((res) => {
- if (res) return commandService.executeCommand(InsertRowMutation.id, insertRowMutationParams);
- return false;
- });
- },
- });
- return true;
- }
-
- return false;
- },
-};
diff --git a/packages/base-sheets/src/commands/commands/move-rows.command.ts b/packages/base-sheets/src/commands/commands/move-rows.command.ts
new file mode 100644
index 0000000000..bec73b7b17
--- /dev/null
+++ b/packages/base-sheets/src/commands/commands/move-rows.command.ts
@@ -0,0 +1,117 @@
+import {
+ CommandType,
+ ICommand,
+ ICommandService,
+ ICurrentUniverService,
+ IUndoRedoService,
+ RANGE_TYPE,
+} from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+
+import { IInsertRowMutationParams, IRemoveRowsMutationParams } from '../../Basics/Interfaces/MutationInterface';
+import { SelectionManagerService } from '../../services/selection-manager.service';
+import { InsertRowMutation, InsertRowMutationUndoFactory } from '../mutations/insert-row-col.mutation';
+import { RemoveRowMutation, RemoveRowsMutationFactory } from '../mutations/remove-row-col.mutation';
+
+export interface IMoveRowsCommandParams {
+ fromRow: number;
+ toRow: number;
+}
+
+/**
+ * Command to move the selected rows (must currently selected) to the specified row.
+ */
+export const MoveRowsCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.move-rows',
+ handler: async (accessor: IAccessor, params: IMoveRowsCommandParams) => {
+ const selectionManagerService = accessor.get(SelectionManagerService);
+
+ const selections = selectionManagerService.getSelections();
+ if (!selections?.length) {
+ return false;
+ }
+
+ const findMoveRanges = selections.filter(
+ (s) =>
+ s.range.rangeType === RANGE_TYPE.ROW &&
+ s.range.startRow <= params.fromRow &&
+ params.fromRow <= s.range.endRow
+ );
+ if (findMoveRanges.length !== 1) {
+ return false;
+ }
+
+ const movedRanges = findMoveRanges[0];
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const workbook = currentUniverService.getCurrentUniverSheetInstance()?.getWorkBook();
+ if (!workbook) return false;
+ const workbookId = workbook.getUnitId();
+ const worksheet = workbook.getActiveSheet();
+ if (!worksheet) return false;
+ const worksheetId = worksheet.getSheetId();
+
+ // TODO: we should add a move row mutation instead of using an insert mutation and a delete mutation
+ // they are not logically the same
+
+ const { startRow, endRow } = movedRanges.range;
+ const removeRowMutationParams: IRemoveRowsMutationParams = {
+ workbookId,
+ worksheetId,
+ ranges: [
+ {
+ startColumn: 0,
+ endColumn: 0,
+ startRow,
+ endRow,
+ },
+ ],
+ };
+ const undoRemoveRowMutationParams: IInsertRowMutationParams = RemoveRowsMutationFactory(
+ removeRowMutationParams,
+ worksheet
+ );
+
+ const insertRowMutationParams: IInsertRowMutationParams = {
+ ...undoRemoveRowMutationParams,
+ ranges: [
+ {
+ startColumn: 0,
+ endColumn: 0,
+ startRow: params.toRow,
+ endRow: params.toRow + endRow - startRow,
+ },
+ ],
+ };
+ const undoMutationParams: IRemoveRowsMutationParams = InsertRowMutationUndoFactory(
+ accessor,
+ insertRowMutationParams
+ );
+
+ // TODO: we should expose a hook on a service to let other features to hook in mutations when rows are moved
+
+ const commandService = accessor.get(ICommandService);
+ const removeResult = commandService.executeCommand(RemoveRowMutation.id, removeRowMutationParams);
+ const insertResult = commandService.executeCommand(InsertRowMutation.id, insertRowMutationParams);
+
+ if (removeResult && insertResult) {
+ accessor.get(IUndoRedoService).pushUndoRedo({
+ URI: workbookId,
+ async undo() {
+ const res = await commandService.executeCommand(InsertRowMutation.id, undoRemoveRowMutationParams);
+ if (res) return commandService.executeCommand(RemoveRowMutation.id, undoMutationParams);
+ return false;
+ },
+ async redo() {
+ const res = await commandService.executeCommand(RemoveRowMutation.id, removeRowMutationParams);
+ if (res) return commandService.executeCommand(InsertRowMutation.id, insertRowMutationParams);
+ return false;
+ },
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/base-sheets/src/commands/commands/remove-row-col.command.ts b/packages/base-sheets/src/commands/commands/remove-row-col.command.ts
index 426446c53e..398bd278df 100644
--- a/packages/base-sheets/src/commands/commands/remove-row-col.command.ts
+++ b/packages/base-sheets/src/commands/commands/remove-row-col.command.ts
@@ -18,7 +18,7 @@ import {
IInsertRangeMutationParams,
IInsertRowMutationParams,
IRemoveColMutationParams,
- IRemoveRowMutationParams,
+ IRemoveRowsMutationParams,
IRemoveWorksheetMergeMutationParams,
} from '../../Basics/Interfaces/MutationInterface';
import { SelectionManagerService } from '../../services/selection-manager.service';
@@ -28,9 +28,9 @@ import { InsertRangeMutation } from '../mutations/insert-range.mutation';
import { InsertColMutation, InsertRowMutation } from '../mutations/insert-row-col.mutation';
import {
IRemoveColMutationFactory,
- IRemoveRowMutationFactory,
RemoveColMutation,
RemoveRowMutation,
+ RemoveRowsMutationFactory,
} from '../mutations/remove-row-col.mutation';
import {
RemoveWorksheetMergeMutation,
@@ -65,13 +65,13 @@ export const RemoveRowCommand: ICommand = {
item.endColumn = worksheet.getMaxColumns();
});
- const redoMutationParams: IRemoveRowMutationParams = {
+ const redoMutationParams: IRemoveRowsMutationParams = {
workbookId,
worksheetId,
ranges: selections,
};
- const undoMutationParams: IInsertRowMutationParams = IRemoveRowMutationFactory(accessor, redoMutationParams);
+ const undoMutationParams: IInsertRowMutationParams = RemoveRowsMutationFactory(redoMutationParams, worksheet);
const result = commandService.executeCommand(RemoveRowMutation.id, redoMutationParams);
const deleteRangeValueMutationParams: IDeleteRangeMutationParams = {
diff --git a/packages/base-sheets/src/commands/mutations/insert-row-col.mutation.ts b/packages/base-sheets/src/commands/mutations/insert-row-col.mutation.ts
index a068d49d15..eef10d553d 100644
--- a/packages/base-sheets/src/commands/mutations/insert-row-col.mutation.ts
+++ b/packages/base-sheets/src/commands/mutations/insert-row-col.mutation.ts
@@ -5,15 +5,13 @@ import {
IInsertColMutationParams,
IInsertRowMutationParams,
IRemoveColMutationParams,
- IRemoveRowMutationParams,
+ IRemoveRowsMutationParams,
} from '../../Basics/Interfaces/MutationInterface';
-// TODO: InsertRowMutation should have an undo factory
-
-export const InsertRowMutationFactory = (
+export const InsertRowMutationUndoFactory = (
accessor: IAccessor,
params: IInsertRowMutationParams
-): IRemoveRowMutationParams => {
+): IRemoveRowsMutationParams => {
const currentUniverService = accessor.get(ICurrentUniverService);
const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
@@ -32,15 +30,15 @@ export const InsertRowMutation: IMutation<IInsertRowMutationParams> = {
id: 'sheet.mutation.insert-row',
type: CommandType.MUTATION,
handler: async (accessor, params) => {
+ const { workbookId, worksheetId, ranges, rowInfo } = params;
const currentUniverService = accessor.get(ICurrentUniverService);
- const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
+ const universheet = currentUniverService.getUniverSheetInstance(workbookId);
if (universheet == null) {
throw new Error('universheet is null error!');
}
- const worksheet = universheet.getWorkBook().getSheetBySheetId(params.worksheetId);
-
+ const worksheet = universheet.getWorkBook().getSheetBySheetId(worksheetId);
if (worksheet == null) {
throw new Error('worksheet is null error!');
}
@@ -50,8 +48,8 @@ export const InsertRowMutation: IMutation<IInsertRowMutationParams> = {
const rowWrapper = new ObjectArray(rowPrimitive);
const defaultRowHeight = worksheet.getConfig().defaultRowHeight;
- for (let i = 0; i < params.ranges.length; i++) {
- const range = params.ranges[i];
+ for (let i = 0; i < ranges.length; i++) {
+ const range = ranges[i];
const rowIndex = range.startRow;
const rowCount = range.endRow - range.startRow + 1;
@@ -60,8 +58,9 @@ export const InsertRowMutation: IMutation<IInsertRowMutationParams> = {
h: defaultRowHeight,
hd: 0,
};
- if (params.rowInfo) {
- rowWrapper.insert(j, params.rowInfo.get(j) ?? defaultRowInfo);
+
+ if (rowInfo) {
+ rowWrapper.insert(j, rowInfo.get(j) ?? defaultRowInfo);
} else {
rowWrapper.insert(j, defaultRowInfo);
}
diff --git a/packages/base-sheets/src/commands/mutations/remove-row-col.mutation.ts b/packages/base-sheets/src/commands/mutations/remove-row-col.mutation.ts
index c532800254..d3cf271595 100644
--- a/packages/base-sheets/src/commands/mutations/remove-row-col.mutation.ts
+++ b/packages/base-sheets/src/commands/mutations/remove-row-col.mutation.ts
@@ -1,29 +1,25 @@
-import { CommandType, IColumnData, ICurrentUniverService, IMutation, IRowData, ObjectArray } from '@univerjs/core';
+import {
+ CommandType,
+ IColumnData,
+ ICurrentUniverService,
+ IMutation,
+ IRowData,
+ ObjectArray,
+ Worksheet,
+} from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
import {
IInsertColMutationParams,
IInsertRowMutationParams,
IRemoveColMutationParams,
- IRemoveRowMutationParams,
+ IRemoveRowsMutationParams,
} from '../../Basics/Interfaces/MutationInterface';
-export const IRemoveRowMutationFactory = (
- accessor: IAccessor,
- params: IRemoveRowMutationParams
+export const RemoveRowsMutationFactory = (
+ params: IRemoveRowsMutationParams,
+ worksheet: Worksheet
): IInsertRowMutationParams => {
- const currentUniverService = accessor.get(ICurrentUniverService);
- const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
-
- if (universheet == null) {
- throw new Error('universheet is null error!');
- }
-
- const worksheet = universheet.getWorkBook().getSheetBySheetId(params.worksheetId);
- if (worksheet == null) {
- throw new Error('universheet is null error!');
- }
-
const manager = worksheet.getRowManager();
const rowPrimitive = manager.getRowData().toJSON();
const rowWrapper = new ObjectArray(rowPrimitive);
@@ -31,7 +27,6 @@ export const IRemoveRowMutationFactory = (
for (let i = 0; i < params.ranges.length; i++) {
const range = params.ranges[i];
-
const slice = rowWrapper.slice(range.startRow, range.endRow);
rowInfo.concat(slice);
}
@@ -44,7 +39,7 @@ export const IRemoveRowMutationFactory = (
};
};
-export const RemoveRowMutation: IMutation<IRemoveRowMutationParams> = {
+export const RemoveRowMutation: IMutation<IRemoveRowsMutationParams> = {
id: 'sheet.mutation.remove-row',
type: CommandType.MUTATION,
handler: async (accessor, params) => {
diff --git a/packages/base-sheets/src/index.ts b/packages/base-sheets/src/index.ts
index b5106bd149..10ee1e2180 100644
--- a/packages/base-sheets/src/index.ts
+++ b/packages/base-sheets/src/index.ts
@@ -28,7 +28,10 @@ export { ClearSelectionContentCommand } from './commands/commands/clear-selectio
export { CopySheetCommand } from './commands/commands/copy-worksheet.command';
export { DeleteRangeMoveLeftCommand } from './commands/commands/delete-range-move-left.command';
export { DeleteRangeMoveUpCommand } from './commands/commands/delete-range-move-up.command';
-export type { InsertColCommandParams, InsertRowCommandParams } from './commands/commands/insert-row-col.command';
+export type {
+ InsertColCommandParams,
+ IInsertRowBeforeOrAfterCommandParams as InsertRowCommandParams,
+} from './commands/commands/insert-row-col.command';
export {
InsertColAfterCommand,
InsertColBeforeCommand,
@@ -97,7 +100,7 @@ export {
InsertColMutation,
InsertColMutationFactory,
InsertRowMutation,
- InsertRowMutationFactory,
+ InsertRowMutationUndoFactory as InsertRowMutationFactory,
} from './commands/mutations/insert-row-col.mutation';
export { InsertSheetMutation, InsertSheetUndoMutationFactory } from './commands/mutations/insert-sheet.mutation';
export { RemoveSheetMutation, RemoveSheetUndoMutationFactory } from './commands/mutations/remove-sheet.mutation';
diff --git a/packages/base-sheets/src/services/selection-manager.service.ts b/packages/base-sheets/src/services/selection-manager.service.ts
index c213722b15..5305826f3f 100644
--- a/packages/base-sheets/src/services/selection-manager.service.ts
+++ b/packages/base-sheets/src/services/selection-manager.service.ts
@@ -98,7 +98,7 @@ export class SelectionManagerService implements IDisposable {
return this._getSelectionDatas(this._currentSelection);
}
- /** @deprecated use getSelectionsData instead */
+ /** @deprecated use `getSelections` instead */
getRangeDatas(): Nullable<IRange[]> {
const selectionDataList = this.getSelections();
if (selectionDataList == null) {
diff --git a/packages/base-ui/src/Components/CustomLabel/CustomLabel.tsx b/packages/base-ui/src/Components/CustomLabel/CustomLabel.tsx
index 424972b00e..2cd18f3f17 100644
--- a/packages/base-ui/src/Components/CustomLabel/CustomLabel.tsx
+++ b/packages/base-ui/src/Components/CustomLabel/CustomLabel.tsx
@@ -79,6 +79,7 @@ export function NeoCustomLabel(
<Item
selected={selected}
label={title}
+ value={value}
suffix={LabelComponent ? <LabelComponent /> : null}
disabled={false}
></Item>
diff --git a/packages/base-ui/src/Components/Menu/Menu.tsx b/packages/base-ui/src/Components/Menu/Menu.tsx
index b0555fa4c2..71a8b702e4 100644
--- a/packages/base-ui/src/Components/Menu/Menu.tsx
+++ b/packages/base-ui/src/Components/Menu/Menu.tsx
@@ -342,9 +342,8 @@
// }
// }
// }
-import { isRealNum } from '@univerjs/core';
import React, { useContext, useEffect, useRef, useState } from 'react';
-import { Subscription } from 'rxjs';
+import { of } from 'rxjs';
import { AppContext } from '../../Common/AppContext';
import {
@@ -355,11 +354,13 @@ import {
IMenuSelectorItem,
isValueOptions,
IValueOption,
+ MenuItemDefaultValueType,
MenuItemType,
} from '../../services/menu/menu';
import { IMenuService } from '../../services/menu/menu.service';
import { joinClassNames } from '../../Utils';
import { CustomLabel, NeoCustomLabel } from '../CustomLabel/CustomLabel';
+import { useObservable } from '../hooks/observable';
import { BaseMenuItem } from '../Item/Item';
import { DisplayTypes } from '../Select/Select';
import styles from './index.module.less';
@@ -666,11 +667,7 @@ export interface IMenuItemState {
export function MenuItem({ menuItem, index, onClick }: IMenuItemProps) {
const context = useContext(AppContext);
- const [disabled, setDisabled] = useState(false);
- const [value, setValue] = useState<any>(undefined);
const [menuItems, setMenuItems] = useState<Array<IDisplayMenuItem<IMenuItem>>>([]);
- const [disabledSubscription, setDisabledSubscription] = useState<Subscription | undefined>();
- const [valueSubscription, setValueSubscription] = useState<Subscription | undefined>();
const [itemShow, setItemShow] = useState<boolean>(false);
const mouseEnter = (e: React.MouseEvent<HTMLLIElement, MouseEvent>, index: number) => {
@@ -690,45 +687,25 @@ export function MenuItem({ menuItem, index, onClick }: IMenuItemProps) {
}
};
- // const handleClick = (e: React.MouseEvent<HTMLLIElement, MouseEvent>, item: IDisplayMenuItem<IMenuItem>, index: number) => {
- // // const commandService: ICommandService = context.injector.get(ICommandService);
- // onClick();
-
- // const itemValue = value;
- // // !(item.subMenuItems && item.subMenuItems.length > 0) && commandService.executeCommand(item.id, { value });
- // };
-
/**
* user input change value from CustomLabel
* @param e
*/
const onChange = (v: string | number) => {
- const newValue = isRealNum(v) && typeof v === 'string' ? parseInt(v) : v;
-
- setValue(newValue);
+ // const newValue = isRealNum(v) && typeof v === 'string' ? parseInt(v) : v;
+ // setValue(newValue);
};
useEffect(() => {
- setDisabledSubscription(
- menuItem.disabled$?.subscribe((disabled) => {
- setDisabled(disabled);
- })
- );
-
- setValueSubscription(
- menuItem.value$?.subscribe((newValue) => {
- setValue(newValue);
- })
- );
-
getSubMenus();
- return () => {
- disabledSubscription?.unsubscribe();
- valueSubscription?.unsubscribe();
- };
+ return () => {};
}, [menuItem]);
+ const disabled = useObservable<boolean>(menuItem.disabled$ || of(false), false, true);
+ const hidden = useObservable(menuItem.hidden$ || of(false), false, true);
+ const value = useObservable<MenuItemDefaultValueType>(menuItem.value$ || of(undefined), undefined, true);
+
const renderButtonType = () => {
const item = menuItem as IDisplayMenuItem<IMenuButtonItem>;
const { title, display, label } = item;
@@ -756,7 +733,7 @@ export function MenuItem({ menuItem, index, onClick }: IMenuItemProps) {
};
const renderSelectorType = () => {
- const item = menuItem as IDisplayMenuItem<IMenuSelectorItem<unknown>>;
+ const item = menuItem as IDisplayMenuItem<IMenuSelectorItem>;
return (
<li
@@ -774,7 +751,7 @@ export function MenuItem({ menuItem, index, onClick }: IMenuItemProps) {
label={item.label}
></NeoCustomLabel>
{item.shortcut && ` (${item.shortcut})`}
- {(menuItems.length > 0 || (item as IMenuSelectorItem<unknown>).selections?.length) && (
+ {(menuItems.length > 0 || (item as IMenuSelectorItem).selections?.length) && (
<Menu
show={itemShow}
onOptionSelect={(v) => {
@@ -793,7 +770,7 @@ export function MenuItem({ menuItem, index, onClick }: IMenuItemProps) {
};
const renderSubItemsType = () => {
- const item = menuItem as IDisplayMenuItem<IMenuSelectorItem<unknown>>;
+ const item = menuItem as IDisplayMenuItem<IMenuSelectorItem>;
return (
<li
@@ -822,6 +799,10 @@ export function MenuItem({ menuItem, index, onClick }: IMenuItemProps) {
);
};
+ if (hidden) {
+ return null;
+ }
+
return (
<>
{menuItem.type === MenuItemType.SELECTOR && renderSelectorType()}
diff --git a/packages/base-ui/src/Components/hooks/observable.ts b/packages/base-ui/src/Components/hooks/observable.ts
new file mode 100644
index 0000000000..90570e40a8
--- /dev/null
+++ b/packages/base-ui/src/Components/hooks/observable.ts
@@ -0,0 +1,38 @@
+import React, { useRef, useState } from 'react';
+import { Observable, Subscription } from 'rxjs';
+
+export function useObservable<T>(observable: Observable<T>, defaultValue?: T): T | undefined;
+export function useObservable<T>(observable: Observable<T>, defaultValue?: T, shouldHaveSyncValue?: true): T;
+export function useObservable<T>(
+ observable: Observable<T>,
+ defaultValue?: T,
+ shouldHaveSyncValue?: true
+): T | undefined {
+ const observableRef = useRef<Observable<T> | null>(null);
+ const subscriptionRef = useRef<Subscription | null>(null);
+
+ let setValue: React.Dispatch<React.SetStateAction<T | undefined>>;
+ let initialized = false;
+ let innerDefaultValue: T | undefined;
+ if (!observableRef.current || observableRef.current !== observable) {
+ subscriptionRef.current?.unsubscribe();
+ subscriptionRef.current = observable.subscribe((v) => {
+ if (setValue) {
+ setValue(v);
+ } else {
+ innerDefaultValue = v;
+ initialized = true;
+ }
+ });
+ }
+
+ if (shouldHaveSyncValue && !initialized) {
+ throw new Error('[useObservable]: expect shouldHaveSyncValue but not getting a sync value!');
+ }
+
+ const s = useState<T | undefined>(innerDefaultValue || defaultValue);
+ const value = s[0];
+ setValue = s[1];
+
+ return value;
+}
diff --git a/packages/base-ui/src/services/menu/menu.ts b/packages/base-ui/src/services/menu/menu.ts
index c9977202c1..08b9d2265a 100644
--- a/packages/base-ui/src/services/menu/menu.ts
+++ b/packages/base-ui/src/services/menu/menu.ts
@@ -97,7 +97,7 @@ export function isCustomComponentOption(v: IValueOption | ICustomComponentOption
return typeof (v as ICustomComponentOption).id !== 'undefined';
}
-export interface IMenuSelectorItem<V> extends IMenuItemBase<V> {
+export interface IMenuSelectorItem<V = MenuItemDefaultValueType> extends IMenuItemBase<V> {
type: MenuItemType.SELECTOR | MenuItemType.SUBITEMS;
/** @deprecated this parameter would be removed after we complete refactoring, because they will be all NEO */
@@ -111,11 +111,13 @@ export interface IMenuSelectorItem<V> extends IMenuItemBase<V> {
selections?: Array<IValueOption | ICustomComponentOption>;
}
-export function isMenuSelectorItem<T>(v: IMenuItem): v is IMenuSelectorItem<T> {
+export function isMenuSelectorItem<T extends MenuItemDefaultValueType>(v: IMenuItem): v is IMenuSelectorItem<T> {
return v.type === MenuItemType.SELECTOR || v.type === MenuItemType.SUBITEMS;
}
-export type IMenuItem = IMenuButtonItem | IMenuSelectorItem<unknown>;
+export type MenuItemDefaultValueType = string | number | undefined;
+
+export type IMenuItem = IMenuButtonItem | IMenuSelectorItem<MenuItemDefaultValueType>;
export type IDisplayMenuItem<T extends IMenuItem> = T & {
shortcut?: string;
diff --git a/packages/base-ui/src/views/components/contextmenu/contextmenu.tsx b/packages/base-ui/src/views/components/contextmenu/contextmenu.tsx
index 2602521b69..b8fb51ed94 100644
--- a/packages/base-ui/src/views/components/contextmenu/contextmenu.tsx
+++ b/packages/base-ui/src/views/components/contextmenu/contextmenu.tsx
@@ -90,20 +90,26 @@ export class ContextMenu extends Component<IContextMenuProps, IContextMenuState>
handleContextMenu = async (event: IMouseEvent, menuType: string) => {
event.preventDefault();
- this.setState({ visible: true }, () => {
- new Promise<void>((resolve) => {
- resolve();
- }).then(() => {
- // 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,
- },
- menuType,
- });
+ const showMenu = () => {
+ this.setState({
+ visible: true,
+ clientPosition: {
+ clientX: event.clientX,
+ clientY: event.clientY,
+ },
+ menuType,
});
- });
+ };
+
+ // if it is visible, should set it to visible and set back to refresh inner contents
+
+ if (this.state.visible) {
+ this.setState({ visible: false }, () => {
+ setTimeout(() => showMenu(), 200);
+ });
+ } else {
+ showMenu();
+ }
};
private handleClick = (e: MouseEvent) => {
diff --git a/packages/base-ui/src/views/components/toolbar/toolbar-item.tsx b/packages/base-ui/src/views/components/toolbar/toolbar-item.tsx
index 1ad9e5c90d..52033e6284 100644
--- a/packages/base-ui/src/views/components/toolbar/toolbar-item.tsx
+++ b/packages/base-ui/src/views/components/toolbar/toolbar-item.tsx
@@ -59,7 +59,7 @@ export class ToolbarItem extends Component<IDisplayMenuItem<IMenuItem>, IToolbar
}
if (this.props.type === MenuItemType.SELECTOR) {
- const props = this.props as IDisplayMenuItem<IMenuSelectorItem<unknown>>;
+ const props = this.props as IDisplayMenuItem<IMenuSelectorItem>;
this.currentValueSubscription = props.value$?.subscribe((value) => {
this.setState({ value });
});
@@ -87,7 +87,7 @@ export class ToolbarItem extends Component<IDisplayMenuItem<IMenuItem>, IToolbar
const commandService: ICommandService = context.injector.get(ICommandService);
const { disabled, value } = state;
- const props = this.props as IDisplayMenuItem<IMenuSelectorItem<unknown>>;
+ const props = this.props as IDisplayMenuItem<IMenuSelectorItem>;
const { icon, title, label, display, selectType, selections, id, onClose } = props;
return (
diff --git a/packages/base-ui/src/views/components/toolbar/toolbar.tsx b/packages/base-ui/src/views/components/toolbar/toolbar.tsx
index 5e461183f2..7cb40da0a4 100644
--- a/packages/base-ui/src/views/components/toolbar/toolbar.tsx
+++ b/packages/base-ui/src/views/components/toolbar/toolbar.tsx
@@ -57,6 +57,7 @@ export class Toolbar extends Component<IToolbarProps, IToolbarState> {
override render() {
const { menuItems } = this.state;
+
return (
<Container style={{ position: 'relative' }}>
<div className={`${styles.toolbarWarp} ${styles.toolbar}`} ref={this.toolbarRef}>
diff --git a/packages/core/src/Basics/Environment.ts b/packages/core/src/Basics/Environment.ts
deleted file mode 100644
index d30c9fd493..0000000000
--- a/packages/core/src/Basics/Environment.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-/**
- * Operating environment, equipment, platform information
- */
-export class Environment {
- os: string;
-
- app_version: string;
-
- device_id: string;
-
- platform: string;
-
- os_version: string;
-
- constructor() {
- this.os = '';
- this.app_version = '';
- this.platform = '';
- this.device_id = '';
- this.os_version = '';
- }
-}
diff --git a/packages/core/src/Basics/Univer.ts b/packages/core/src/Basics/Univer.ts
index 1f4169e6d9..451be28734 100644
--- a/packages/core/src/Basics/Univer.ts
+++ b/packages/core/src/Basics/Univer.ts
@@ -17,7 +17,6 @@ import { Nullable } from '../Shared';
import { LocaleType } from '../Types/Enum/LocaleType';
import { IDocumentData, ISlideData, IUniverData, IWorkbookConfig } from '../Types/Interfaces';
import { UniverDoc } from './UniverDoc';
-import { UniverObserverImpl } from './UniverObserverImpl';
import { UniverSheet } from './UniverSheet';
import { UniverSlide } from './UniverSlide';
@@ -33,11 +32,9 @@ export class Univer {
constructor(univerData: Partial<IUniverData> = {}) {
this._univerInjector = this._initDependencies();
- this._setObserver();
const { theme, locale, locales } = univerData;
theme && this._univerInjector.get(ThemeService).setTheme(theme);
- // initialize localization info
locales && this._univerInjector.get(LocaleService).load(locales);
locale && this._univerInjector.get(LocaleService).setLocale(locale);
}
@@ -141,10 +138,6 @@ export class Univer {
return this._currentUniverService.getCurrentUniverSlideInstance();
}
- protected _setObserver(): void {
- new UniverObserverImpl().install(this._univerInjector.get(ObserverManager));
- }
-
private _initDependencies(): Injector {
return new Injector([
[ObserverManager],
diff --git a/packages/core/src/Basics/UniverObserver.ts b/packages/core/src/Basics/UniverObserver.ts
deleted file mode 100644
index 43202a8bcf..0000000000
--- a/packages/core/src/Basics/UniverObserver.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { Observable } from '../Observer/Observable';
-import { UIObserver } from '../Types/Interfaces';
-
-export type UniverObserver<T> = {
- onUIChangeObservable: Observable<UIObserver<T>>;
- onUIDidMountObservable: Observable<boolean>;
- onAfterChangeUISkinObservable: Observable<string>;
- onAfterChangeUILocaleObservable: Observable<string>;
- onViewComponentFocusChange: Observable<void>;
-};
diff --git a/packages/core/src/Basics/UniverObserverImpl.ts b/packages/core/src/Basics/UniverObserverImpl.ts
deleted file mode 100644
index cc36c3fd00..0000000000
--- a/packages/core/src/Basics/UniverObserverImpl.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { Observable, ObserverManager } from '../Observer';
-
-export class UniverObserverImpl {
- install(manager: ObserverManager) {
- // Event = > UIChange
- manager.addObserver('onUIChangeObservable', 'core', new Observable());
- manager.addObserver('onUIDidMountObservable', 'core', new Observable());
- manager.addObserver('onAfterChangeUISkinObservable', 'core', new Observable());
- manager.addObserver('onAfterChangeUILocaleObservable', 'core', new Observable());
- manager.addObserver('onViewComponentFocusChange', 'core', new Observable());
-
- // SheetBar
- manager.addObserver('onAddSheet', 'core', new Observable());
- manager.addObserver('onDeleteSheet', 'core', new Observable());
- manager.addObserver('onHideSheet', 'core', new Observable());
- manager.addObserver('onUnHideSheet', 'core', new Observable());
- manager.addObserver('onToLeftSheet', 'core', new Observable());
- manager.addObserver('onToRightSheet', 'core', new Observable());
- manager.addObserver('onCopySheet', 'core', new Observable());
- manager.addObserver('onRemoveSheet', 'core', new Observable());
- manager.addObserver('onSheetColor', 'core', new Observable());
- }
-}
diff --git a/packages/core/src/Basics/UniverSheet.ts b/packages/core/src/Basics/UniverSheet.ts
index 6bbc1dbf70..2eb0e837e1 100644
--- a/packages/core/src/Basics/UniverSheet.ts
+++ b/packages/core/src/Basics/UniverSheet.ts
@@ -28,9 +28,10 @@ export class UniverSheet implements IDisposable {
this.univerSheetConfig = univerSheetData;
this._sheetInjector = this._initDependencies(parentInjector);
- this.setObserver();
this._workbook = this._sheetInjector.createInstance(Workbook, univerSheetData);
this._sheetInjector.get(LifecycleInitializerService).start();
+
+ new WorkBookObserverImpl().install(this._sheetInjector.get(ObserverManager));
}
static newInstance(univerSheetData: Partial<IWorkbookConfig> = {}): UniverSheet {
@@ -84,11 +85,4 @@ export class UniverSheet implements IDisposable {
return parentInjector ? parentInjector.createChild(dependencies) : new Injector(dependencies);
}
-
- /**
- * @deprecated
- */
- private setObserver(): void {
- new WorkBookObserverImpl().install(this._sheetInjector.get(ObserverManager));
- }
}
diff --git a/packages/core/src/Basics/WorkBookObserver.ts b/packages/core/src/Basics/WorkBookObserver.ts
deleted file mode 100644
index 71a0045233..0000000000
--- a/packages/core/src/Basics/WorkBookObserver.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { Observable } from '../Observer/Observable';
-import { Worksheet } from '../Sheets/Domain';
-
-export type WorkBookObserver = {
- onBeforeInsertSheetObservable: Observable<{ index: number; sheetId: string }>;
- onAfterInsertSheetObservable: Observable<{ index: number; sheetId: string }>;
-
- onAfterSetSelectionObservable: Observable<void>;
-
- onBeforeChangeNameObservable: Observable<void>;
- onAfterChangeNameObservable: Observable<void>;
-
- onSheetTabColorChangeObservable: Observable<void>;
-
- onSheetOrderObservable: Observable<void>;
-
- onBeforeChangeSheetColorObservable: Observable<void>;
- onAfterChangeSheetColorObservable: Observable<void>;
-
- onBeforeChangeSheetDataObservable: Observable<void>;
- onAfterChangeSheetDataObservable: Observable<void>;
-
- onSheetRenderDidMountObservable: Observable<void>;
-
- onZoomRatioSheetObservable: Observable<{ zoomRatio: number }>;
-
- onHideSheetObservable: Observable<{ sheet: Worksheet }>;
- onShowSheetObservable: Observable<{ sheet: Worksheet }>;
-
- onBeforeChangeActiveSheetObservable: Observable<{ sheet: Worksheet }>;
- onAfterChangeActiveSheetObservable: Observable<{ sheet: Worksheet }>;
-
- onBeforeChangeSheetNameObservable: Observable<void>;
- onAfterChangeSheetNameObservable: Observable<{ name: string; sheet: Worksheet }>;
-};
diff --git a/packages/core/src/Basics/index.ts b/packages/core/src/Basics/index.ts
index 5e59b00777..6eccb9b7d4 100644
--- a/packages/core/src/Basics/index.ts
+++ b/packages/core/src/Basics/index.ts
@@ -1,11 +1,6 @@
-export * from './Environment';
export * from './Registry';
export * from './Univer';
export * from './UniverDoc';
-export * from './UniverObserver';
-export * from './UniverObserverImpl';
export * from './UniverSheet';
export * from './UniverSlide';
export * from './Version';
-export * from './WorkBookObserver';
-export * from './WorkBookObserverImpl';
diff --git a/packages/core/src/Shared/Tools.ts b/packages/core/src/Shared/Tools.ts
index ecf67cecfb..07d49d2182 100644
--- a/packages/core/src/Shared/Tools.ts
+++ b/packages/core/src/Shared/Tools.ts
@@ -1,6 +1,5 @@
import { nanoid } from 'nanoid';
-import { Environment } from '../Basics/Environment';
import { ObjectArray, ObjectArrayPrimitiveType } from './ObjectArray';
import { ObjectMatrix, ObjectMatrixPrimitiveType } from './ObjectMatrix';
import { Class, IKeyValue } from './Types';
@@ -54,18 +53,6 @@ export class Tools {
return str;
}
- static getEnvironment(): Environment {
- const { appVersion } = navigator;
- const system = this.getSystemType();
- return {
- app_version: appVersion,
- os: system,
- os_version: system,
- device_id: '',
- platform: 'web',
- };
- }
-
static indexAt(code: string): number {
let ret = 0;
for (let i = 0; i < code.length - 1; i += 1) {
diff --git a/packages/core/src/common/promise/sequence.ts b/packages/core/src/common/promise/sequence.ts
new file mode 100644
index 0000000000..e4df99c1c9
--- /dev/null
+++ b/packages/core/src/common/promise/sequence.ts
@@ -0,0 +1,22 @@
+/**
+ *
+ * @param tasks all promise tasks that need to be triggered
+ * @returns
+ */
+export async function sequence(
+ tasks: Array<() => Promise<boolean> | boolean>
+): Promise<{ result: boolean; index: number }> {
+ for (const [index, task] of tasks.entries()) {
+ if (!(await task())) {
+ return {
+ index,
+ result: false,
+ };
+ }
+ }
+
+ return {
+ result: true,
+ index: -1,
+ };
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index c285b30eef..51b993583e 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -13,6 +13,7 @@ export {
type IMultiCommand,
type IMutation,
type IOperation,
+ sequenceExecute,
} from './services/command/command.service';
export { IConfigService } from './services/config/config.service';
export { FOCUSING_DOC, FOCUSING_SHEET, FOCUSING_SLIDE } from './services/context/context';
diff --git a/packages/core/src/services/command/command.service.ts b/packages/core/src/services/command/command.service.ts
index 0116aee6e8..16d0a3dc25 100644
--- a/packages/core/src/services/command/command.service.ts
+++ b/packages/core/src/services/command/command.service.ts
@@ -1,5 +1,6 @@
import { createIdentifier, IAccessor, IDisposable, Inject, Injector, Optional, SkipSelf } from '@wendellhu/redi';
+import { sequence } from '../../common/promise/sequence';
import { toDisposable } from '../../Shared/lifecycle';
import { IKeyValue } from '../../Shared/Types';
import { IContextService } from '../context/context.service';
@@ -302,7 +303,7 @@ export class CommandService implements ICommandService {
): Promise<R> {
this._log.log(
'[CommandService]',
- `${'|-'.repeat(this._commandExecutingLevel)}executing command "${command.id}".`
+ `${'|-'.repeat(this._commandExecutingLevel)}executing command "${command.id}"`
);
this._commandExecutingLevel++;
@@ -374,3 +375,8 @@ class MultiCommand implements IMultiCommand {
return false;
};
}
+
+export function sequenceExecute(tasks: ICommandInfo[], commandService: ICommandService) {
+ const promises = tasks.map((task) => () => commandService.executeCommand(task.id, task.params));
+ return sequence(promises);
+}
diff --git a/packages/core/src/services/current.service.ts b/packages/core/src/services/current.service.ts
index 85e57c8a7b..a6a2f284c7 100644
--- a/packages/core/src/services/current.service.ts
+++ b/packages/core/src/services/current.service.ts
@@ -30,6 +30,8 @@ export interface ICurrentUniverService {
getUniverSheetInstance(id: string): Nullable<UniverSheet>;
getUniverDocInstance(id: string): Nullable<UniverDoc>;
getUniverSlideInstance(id: string): Nullable<UniverSlide>;
+
+ // TODO: this should be nullable
getCurrentUniverSheetInstance(): UniverSheet;
getCurrentUniverDocInstance(): UniverDoc;
getCurrentUniverSlideInstance(): UniverSlide;
diff --git a/packages/sheets-plugin-import-xlsx/src/services/upload.service.ts b/packages/sheets-plugin-import-xlsx/src/services/upload.service.ts
index 95e3ead58e..372338ff94 100644
--- a/packages/sheets-plugin-import-xlsx/src/services/upload.service.ts
+++ b/packages/sheets-plugin-import-xlsx/src/services/upload.service.ts
@@ -1,14 +1,9 @@
-import { BasicWorkbookController } from '@univerjs/base-sheets';
import { ICurrentUniverService, IKeyValue, migrate, Tools } from '@univerjs/core';
-import { Inject } from '@wendellhu/redi';
// @ts-ignore
import * as LuckyExcel from 'luckyexcel'; // no type definition for package luckyexcel
export class UploadService {
- constructor(
- @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
- @Inject(BasicWorkbookController) private readonly _basicWorkbookController: BasicWorkbookController
- ) {}
+ constructor(@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService) {}
upload() {
const input = document.createElement('input');
@@ -57,7 +52,11 @@ export class UploadService {
return console.error('No content');
}
- const workbook = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance()?.getWorkBook();
+ if (!workbook) {
+ return false;
+ }
+
const workbookId = workbook.getUnitId();
const order = Tools.deepClone(workbook.getConfig().sheetOrder);
@@ -66,14 +65,14 @@ export class UploadService {
const sheetData = sheets[sheetId];
// workbook.insertSheet(sheetData);
const index = order.length - 1 + i;
- this._basicWorkbookController.insertSheet(index, sheetData, workbookId);
+ // this._basicWorkbookController.insertSheet(index, sheetData, workbookId);
});
// remove other sheets
order.forEach((sheetId: string) => {
// workbook.removeSheetBySheetId(sheetId);
// workbook.removeSheetBySheetId(sheetId);
- this._basicWorkbookController.removeSheet(sheetId, workbookId);
+ // this._basicWorkbookController.removeSheet(sheetId, workbookId);
});
});
}
diff --git a/packages/ui-plugin-docs/src/Locale/en.ts b/packages/ui-plugin-docs/src/Locale/en.ts
index 96f0973a17..f53dc04baa 100644
--- a/packages/ui-plugin-docs/src/Locale/en.ts
+++ b/packages/ui-plugin-docs/src/Locale/en.ts
@@ -426,8 +426,10 @@ export default {
cut: 'Cut',
paste: 'Paste',
insert: 'Insert',
- insertRow: 'InsertRow',
- insertColumn: 'InsertColumn',
+ insertRowBefore: 'Insert Row Before',
+ insertRow: 'Insert Row After',
+ insertColumnBefore: 'Insert Column Before',
+ insertColumn: 'Insert Column After',
delete: 'Delete',
deleteCell: 'Delete cell',
deleteSelected: 'Delete selected ',
diff --git a/packages/ui-plugin-docs/src/Locale/zh.ts b/packages/ui-plugin-docs/src/Locale/zh.ts
index 9d1e00fefa..1ba5e844b5 100644
--- a/packages/ui-plugin-docs/src/Locale/zh.ts
+++ b/packages/ui-plugin-docs/src/Locale/zh.ts
@@ -290,8 +290,9 @@ export default {
paste: '粘贴',
insert: '插入',
delete: '删除',
- insertRow: '插入行',
- insertColumn: '插入列',
+ insertRowBefore: '在上方插入行',
+ insertRow: '在下方插入行',
+ insertColumn: '在右侧插入列',
deleteCell: '删除单元格',
deleteSelected: '删除选中',
hide: '隐藏',
diff --git a/packages/ui-plugin-sheets/src/View/RightMenu/RightMenuInput.tsx b/packages/ui-plugin-sheets/src/View/RightMenu/RightMenuInput.tsx
index 18cc0df610..5bc0965be6 100644
--- a/packages/ui-plugin-sheets/src/View/RightMenu/RightMenuInput.tsx
+++ b/packages/ui-plugin-sheets/src/View/RightMenu/RightMenuInput.tsx
@@ -1,5 +1,5 @@
import { CustomLabel, ICustomComponentProps, Input } from '@univerjs/base-ui';
-import React, { useState } from 'react';
+import React, { useEffect, useState } from 'react';
interface IProps extends ICustomComponentProps<string> {
prefix: string;
@@ -7,8 +7,8 @@ interface IProps extends ICustomComponentProps<string> {
onKeyUp?: (e: Event) => void;
}
-export const RightMenuInput: React.FC<IProps> = ({ prefix, suffix, onChange }) => {
- const [inputValue, setInputValue] = useState<string>(''); // Initialized to an empty string
+export const RightMenuInput: React.FC<IProps> = ({ prefix, suffix, value, onChange }) => {
+ const [inputValue, setInputValue] = useState<string>(); // Initialized to an empty string
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
@@ -16,6 +16,10 @@ export const RightMenuInput: React.FC<IProps> = ({ prefix, suffix, onChange }) =
onChange(newValue);
};
+ useEffect(() => {
+ setInputValue(value);
+ }, [value]);
+
return (
<div>
<CustomLabel label={prefix} />
diff --git a/packages/ui-plugin-sheets/src/controller/menu/menu.ts b/packages/ui-plugin-sheets/src/controller/menu/menu.ts
index ac0df4cd6c..a3e368b43d 100644
--- a/packages/ui-plugin-sheets/src/controller/menu/menu.ts
+++ b/packages/ui-plugin-sheets/src/controller/menu/menu.ts
@@ -4,7 +4,9 @@ import {
DeleteRangeMoveLeftCommand,
DeleteRangeMoveUpCommand,
InsertColAfterCommand,
+ InsertColBeforeCommand,
InsertRowAfterCommand,
+ InsertRowBeforeCommand,
RemoveColCommand,
RemoveRowCommand,
RemoveSheetCommand,
@@ -954,21 +956,64 @@ export function ClearSelectionMenuItemFactory(): IMenuButtonItem {
};
}
-export function InsertRowMenuItemFactory(): IMenuButtonItem {
+export function InsertRowBeforeMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
+ const selectionManager = accessor.get(SelectionManagerService);
+
+ return {
+ id: InsertRowBeforeCommand.id,
+ type: MenuItemType.BUTTON,
+ title: 'rightClick.insertRowBefore',
+ positions: [SheetMenuPosition.ROW_HEADER_CONTEXT_MENU, MenuPosition.CONTEXT_MENU],
+ hidden$: new Observable((observer) => {
+ // if there are multi selections this item should be hidden
+ const selections = selectionManager.getSelections();
+ observer.next(selections?.length !== 1);
+ }),
+ };
+}
+
+export function InsertRowAfterMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
+ const selectionManager = accessor.get(SelectionManagerService);
return {
id: InsertRowAfterCommand.id,
type: MenuItemType.BUTTON,
- positions: [MenuPosition.CONTEXT_MENU, SheetMenuPosition.ROW_HEADER_CONTEXT_MENU],
+ positions: [SheetMenuPosition.ROW_HEADER_CONTEXT_MENU],
title: 'rightClick.insertRow',
+ hidden$: new Observable((observer) => {
+ // if there are multi selections this item should be hidden
+ const selections = selectionManager.getSelections();
+ observer.next(selections?.length !== 1);
+ }),
+ };
+}
+
+export function InsertColBeforeMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
+ const selectionManager = accessor.get(SelectionManagerService);
+ return {
+ id: InsertColBeforeCommand.id,
+ type: MenuItemType.BUTTON,
+ positions: [SheetMenuPosition.COL_HEADER_CONTEXT_MENU, MenuPosition.CONTEXT_MENU],
+ title: 'rightClick.insertColumnBefore',
+ hidden$: new Observable((observer) => {
+ // if there are multi selections this item should be hidden
+ const selections = selectionManager.getSelections();
+ observer.next(selections?.length !== 1);
+ }),
};
}
-export function InsertColMenuItemFactory(): IMenuButtonItem {
+export function InsertColAfterMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
+ const selectionManager = accessor.get(SelectionManagerService);
return {
id: InsertColAfterCommand.id,
type: MenuItemType.BUTTON,
positions: [MenuPosition.CONTEXT_MENU, SheetMenuPosition.COL_HEADER_CONTEXT_MENU],
title: 'rightClick.insertColumn',
+ hidden$: new Observable((observer) => {
+ // if there are multi selections this item should be hidden
+ const selections = selectionManager.getSelections();
+ observer.next(selections?.length !== 1);
+ }),
};
}
@@ -1032,8 +1077,7 @@ export function SetRowHeightMenuItemFactory(accessor: IAccessor): IMenuButtonIte
const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
let rowHeight;
if (primary != null) {
- const range = worksheet.getRange(primary.startRow, primary.startColumn);
- rowHeight = range?.getHeight();
+ rowHeight = worksheet.getRowHeight(primary.startRow);
}
subscriber.next(rowHeight ?? 0);
@@ -1074,13 +1118,13 @@ export function SetColWidthMenuItemFactory(accessor: IAccessor): IMenuButtonItem
function update() {
const primary = selectionManagerService.getLast()?.primary;
const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
- let rowHeight;
+
+ let colWidth: number = 0;
if (primary != null) {
- const range = worksheet.getRange(primary.startRow, primary.startColumn);
- rowHeight = range?.getWidth();
+ colWidth = worksheet.getColumnWidth(primary.startColumn);
}
- subscriber.next(rowHeight ?? 0);
+ subscriber.next(colWidth);
}
const disposable = commandService.onCommandExecuted((c) => {
diff --git a/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts b/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts
index 720ddf62fb..ec6de64ac3 100644
--- a/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts
+++ b/packages/ui-plugin-sheets/src/controller/sheet-ui.controller.ts
@@ -46,8 +46,10 @@ import {
FontSizeSelectorMenuItemFactory,
HideSheetMenuItemFactory,
HorizontalAlignMenuItemFactory,
- InsertColMenuItemFactory,
- InsertRowMenuItemFactory,
+ InsertColAfterMenuItemFactory,
+ InsertColBeforeMenuItemFactory,
+ InsertRowAfterMenuItemFactory,
+ InsertRowBeforeMenuItemFactory,
ItalicMenuItemFactory,
PasteMenuItemFactory,
RedoMenuItemFactory,
@@ -159,8 +161,10 @@ export class SheetUIController extends Disposable {
PasteMenuItemFactory,
ClearSelectionMenuItemFactory,
- InsertRowMenuItemFactory,
- InsertColMenuItemFactory,
+ InsertRowBeforeMenuItemFactory,
+ InsertRowAfterMenuItemFactory,
+ InsertColBeforeMenuItemFactory,
+ InsertColAfterMenuItemFactory,
RemoveRowMenuItemFactory,
RemoveColMenuItemFactory,
SetRowHeightMenuItemFactory,
diff --git a/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts b/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts
index ad1a5a2da2..7dd9cbc2f9 100644
--- a/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts
+++ b/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts
@@ -15,6 +15,7 @@ export class SheetUIPlugin extends Plugin {
static override type = PluginType.Sheet;
constructor(
+ config: undefined,
@Inject(Injector) override readonly _injector: Injector,
@Inject(LocaleService) private readonly _localeService: LocaleService
) {