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.

refactor(core): decompose API from core and refactor to new architecture (#64)

Dushusir58e6b25e53ab
diff --git a/packages/base-render/src/Component/Sheets/Selection/SelectionControl.ts b/packages/base-render/src/Component/Sheets/Selection/SelectionControl.ts
deleted file mode 100644
index cec2355f30..0000000000
--- a/packages/base-render/src/Component/Sheets/Selection/SelectionControl.ts
+++ /dev/null
@@ -1,380 +0,0 @@
-import { Nullable, ISelection, ICellInfo } from '@univerjs/core';
-import { SelectionModel } from './SelectionModel';
-import { Rect } from '../../../Shape/Rect';
-import { Group } from '../../../Group';
-import { Scene } from '../../../Scene';
-import { SELECTION_TYPE } from '../../../Basics/Const';
-
-// export enum DEFAULT_SELECTION_CONFIG {
-// strokeColor = 'rgb(1,136,251)',
-// backgroundColor = 'rgba(1,136,251, 0.1)',
-// strokeWidth = 2,
-// fillSideLength = 6,
-// fillStrokeLength = 1,
-// fillStrokeColor = 'rgb(255,255,255)',
-// }
-export const DEFAULT_SELECTION_CONFIG = {
- strokeColor: 'rgb(1,136,251)',
- backgroundColor: 'rgba(1,136,251, 0.1)',
- strokeWidth: 2,
- fillSideLength: 6,
- fillStrokeLength: 1,
- fillStrokeColor: 'rgb(255,255,255)',
-};
-
-enum SELECTION_MANAGER_KEY {
- Selection = '__SpreadsheetSelectionShape__',
- top = '__SpreadsheetSelectionTopControl__',
- bottom = '__SpreadsheetSelectionBottomControl__',
- left = '__SpreadsheetSelectionShapeLeftControl__',
- right = '__SpreadsheetSelectionShapeRightControl__',
- backgroundTop = '__SpreadsheetSelectionBackgroundControlTop__',
- backgroundMiddleLeft = '__SpreadsheetSelectionBackgroundControlMiddleLeft__',
- backgroundMiddleRight = '__SpreadsheetSelectionBackgroundControlMiddleRight__',
- backgroundBottom = '__SpreadsheetSelectionBackgroundControlBottom__',
- fill = '__SpreadsheetSelectionFillControl__',
- lineMain = '__SpreadsheetDragLineMainControl__',
- lineContent = '__SpreadsheetDragLineContentControl__',
- line = '__SpreadsheetDragLineControl__',
-}
-
-/**
- * The main selection canvas component
- */
-export class SelectionControl {
- private _leftControl: Rect;
-
- private _rightControl: Rect;
-
- private _topControl: Rect;
-
- private _bottomControl: Rect;
-
- private _backgroundControlTop: Rect;
-
- private _backgroundControlBottom: Rect;
-
- private _backgroundControlMiddleLeft: Rect;
-
- private _backgroundControlMiddleRight: Rect;
-
- private _fillControl: Rect;
-
- private _selectionShape: Group;
-
- private _selectionModel: SelectionModel;
-
- constructor(private _scene: Scene, private _zIndex: number) {
- this._initialize();
- }
-
- get zIndex() {
- return this._zIndex;
- }
-
- get leftControl() {
- return this._leftControl;
- }
-
- get rightControl() {
- return this._rightControl;
- }
-
- get topControl() {
- return this._topControl;
- }
-
- get bottomControl() {
- return this._bottomControl;
- }
-
- get fillControl() {
- return this._fillControl;
- }
-
- get backgroundControlTop() {
- return this._backgroundControlTop;
- }
-
- get backgroundControlBottom() {
- return this._backgroundControlBottom;
- }
-
- get backgroundControlMiddleLeft() {
- return this._backgroundControlMiddleLeft;
- }
-
- get backgroundControlMiddleRight() {
- return this._backgroundControlMiddleRight;
- }
-
- get selectionShape() {
- return this._selectionShape;
- }
-
- get model() {
- return this._selectionModel;
- }
-
- static create(scene: Scene, zIndex: number) {
- return new this(scene, zIndex);
- }
-
- static fromJson(scene: Scene, zIndex: number, newSelectionRange: ISelection) {
- const control = SelectionControl.create(scene, zIndex);
- control.update(newSelectionRange);
- return control;
- }
-
- /**
- * just handle the view
- *
- * inner update
- */
- _updateControl() {
- const { startX, startY, endX, endY } = this._selectionModel;
-
- this.leftControl.resize(undefined, endY - startY);
- this.rightControl.transformByState({
- height: endY - startY,
- left: endX - startX - DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
- });
- this.topControl.resize(endX - startX + DEFAULT_SELECTION_CONFIG.strokeWidth);
- this.bottomControl.transformByState({
- width: endX - startX + DEFAULT_SELECTION_CONFIG.strokeWidth,
- top: endY - startY - DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
- });
-
- this.fillControl.translate(endX - startX - DEFAULT_SELECTION_CONFIG.fillSideLength / 2, endY - startY - DEFAULT_SELECTION_CONFIG.fillSideLength / 2);
-
- this._updateBackgroundControl();
-
- this.selectionShape.show();
- this.selectionShape.translate(startX, startY);
-
- this.selectionShape.makeDirty(true);
- }
-
- update(newSelectionRange: ISelection, highlight: Nullable<ICellInfo>) {
- this._selectionModel.setValue(newSelectionRange, highlight);
- this._updateControl();
- }
-
- clearHighlight() {
- this._selectionModel.clearCurrentCell();
- this._updateControl();
- }
-
- getScene() {
- return this._scene;
- }
-
- dispose() {
- this._leftControl?.dispose();
- this._rightControl?.dispose();
- this._topControl?.dispose();
- this._bottomControl?.dispose();
- this._backgroundControlTop?.dispose();
- this._backgroundControlMiddleLeft?.dispose();
- this._backgroundControlMiddleRight?.dispose();
- this._backgroundControlBottom?.dispose();
- this._fillControl?.dispose();
- this._selectionShape?.dispose();
- }
-
- /**
- * Get the cell information of the current selection, considering the case of merging cells
- */
- getCurrentCellInfo(): Nullable<ISelection> {
- const currentCell = this.model.currentCell;
-
- if (currentCell) {
- let currentRangeData;
-
- if (currentCell.isMerged) {
- const mergeInfo = currentCell.mergeInfo;
-
- currentRangeData = {
- startRow: mergeInfo.startRow,
- endRow: mergeInfo.endRow,
- startColumn: mergeInfo.startColumn,
- endColumn: mergeInfo.endColumn,
- startX: mergeInfo.startX,
- endX: mergeInfo.endX,
- startY: mergeInfo.startY,
- endY: mergeInfo.endY,
- };
- } else {
- const { row, column, startX, endX, startY, endY } = currentCell;
- currentRangeData = {
- startRow: row,
- endRow: row,
- startColumn: column,
- endColumn: column,
- startX,
- endX,
- startY,
- endY,
- };
- }
-
- return currentRangeData;
- }
- }
-
- private _initialize() {
- this._selectionModel = new SelectionModel(SELECTION_TYPE.NORMAL);
- const zIndex = this._zIndex;
- this._leftControl = new Rect(SELECTION_MANAGER_KEY.left + zIndex, {
- top: 0,
- left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
- width: DEFAULT_SELECTION_CONFIG.strokeWidth,
- fill: DEFAULT_SELECTION_CONFIG.strokeColor,
- zIndex,
- });
- this._rightControl = new Rect(SELECTION_MANAGER_KEY.right + zIndex, {
- width: DEFAULT_SELECTION_CONFIG.strokeWidth,
- fill: DEFAULT_SELECTION_CONFIG.strokeColor,
- zIndex,
- });
- this._topControl = new Rect(SELECTION_MANAGER_KEY.top + zIndex, {
- top: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
- left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
- height: DEFAULT_SELECTION_CONFIG.strokeWidth,
- fill: DEFAULT_SELECTION_CONFIG.strokeColor,
- zIndex,
- });
- this._bottomControl = new Rect(SELECTION_MANAGER_KEY.bottom + zIndex, {
- height: DEFAULT_SELECTION_CONFIG.strokeWidth,
- fill: DEFAULT_SELECTION_CONFIG.strokeColor,
- left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
- zIndex,
- });
- this._backgroundControlTop = new Rect(SELECTION_MANAGER_KEY.backgroundTop + zIndex, {
- fill: DEFAULT_SELECTION_CONFIG.backgroundColor,
- zIndex: zIndex - 1,
- evented: false,
- });
- this._backgroundControlBottom = new Rect(SELECTION_MANAGER_KEY.backgroundBottom + zIndex, {
- fill: DEFAULT_SELECTION_CONFIG.backgroundColor,
- zIndex: zIndex - 1,
- evented: false,
- });
- this._backgroundControlMiddleLeft = new Rect(SELECTION_MANAGER_KEY.backgroundMiddleLeft + zIndex, {
- fill: DEFAULT_SELECTION_CONFIG.backgroundColor,
- zIndex: zIndex - 1,
- evented: false,
- });
- this._backgroundControlMiddleRight = new Rect(SELECTION_MANAGER_KEY.backgroundMiddleRight + zIndex, {
- fill: DEFAULT_SELECTION_CONFIG.backgroundColor,
- zIndex: zIndex - 1,
- evented: false,
- });
- const fillSideLength = DEFAULT_SELECTION_CONFIG.fillSideLength - DEFAULT_SELECTION_CONFIG.fillStrokeLength;
- this._fillControl = new Rect(SELECTION_MANAGER_KEY.fill + zIndex, {
- width: fillSideLength,
- height: fillSideLength,
- fill: DEFAULT_SELECTION_CONFIG.strokeColor,
- strokeWidth: DEFAULT_SELECTION_CONFIG.fillStrokeLength,
- stroke: DEFAULT_SELECTION_CONFIG.fillStrokeColor,
- zIndex: zIndex + 1,
- });
- this._selectionShape = new Group(
- SELECTION_MANAGER_KEY.Selection + zIndex,
- this._fillControl,
- this._leftControl,
- this._rightControl,
- this._topControl,
- this._bottomControl,
- this._backgroundControlTop,
- this._backgroundControlMiddleLeft,
- this._backgroundControlMiddleRight,
- this._backgroundControlBottom
- );
-
- this._selectionShape.hide();
-
- this._selectionShape.evented = false;
-
- this._selectionShape.zIndex = zIndex;
-
- const scene = this.getScene();
- scene.addObject(this._selectionShape);
- }
-
- private _updateBackgroundControl() {
- const {
- startColumn,
- startRow,
- endColumn,
- endRow,
-
- startX,
- startY,
- endX,
- endY,
- } = this._selectionModel;
-
- const highlightSelection = this._selectionModel.highlightToSelection();
-
- if (!highlightSelection) {
- this._backgroundControlTop.resize(endX - startX, endY - startY);
- this._backgroundControlBottom.resize(0, 0);
- this._backgroundControlMiddleLeft.resize(0, 0);
- this._backgroundControlMiddleRight.resize(0, 0);
- return;
- }
-
- const { startX: h_startX, startY: h_startY, endX: h_endX, endY: h_endY } = highlightSelection;
-
- const strokeOffset = DEFAULT_SELECTION_CONFIG.strokeWidth / 2;
-
- const topConfig = {
- left: -strokeOffset,
- top: -strokeOffset,
- width: endX - startX + strokeOffset * 2,
- height: h_startY - startY + strokeOffset,
- };
- if (topConfig.height < 0) {
- topConfig.width = 0;
- topConfig.height = 0;
- }
- this._backgroundControlTop.transformByState(topConfig);
-
- const middleLeftConfig = {
- left: -strokeOffset,
- top: h_startY - startY,
- width: h_startX - startX + strokeOffset,
- height: h_endY - h_startY,
- };
- if (middleLeftConfig.width < 0) {
- middleLeftConfig.width = 0;
- middleLeftConfig.height = 0;
- }
- this._backgroundControlMiddleLeft.transformByState(middleLeftConfig);
-
- const middleRightConfig = {
- left: h_endX - startX - strokeOffset,
- top: h_startY - startY,
- width: endX - h_endX + strokeOffset * 2,
- height: h_endY - h_startY,
- };
- if (middleRightConfig.width < 0) {
- middleRightConfig.width = 0;
- middleRightConfig.height = 0;
- }
- this._backgroundControlMiddleRight.transformByState(middleRightConfig);
-
- const middleBottomConfig = {
- left: -strokeOffset,
- top: h_endY - startY,
- width: endX - startX + strokeOffset * 2,
- height: endY - h_endY + strokeOffset,
- };
- if (middleBottomConfig.height < 0) {
- middleBottomConfig.width = 0;
- middleBottomConfig.height = 0;
- }
- this._backgroundControlBottom.transformByState(middleBottomConfig);
- }
-}
diff --git a/packages/base-render/src/Component/Sheets/Selection/SelectionManager.ts b/packages/base-render/src/Component/Sheets/Selection/SelectionManager.ts
deleted file mode 100644
index 6f698dd3e4..0000000000
--- a/packages/base-render/src/Component/Sheets/Selection/SelectionManager.ts
+++ /dev/null
@@ -1,419 +0,0 @@
-import { Nullable, Observer, ISelection, makeCellToSelection, IRangeData, IRangeCellData } from '@univerjs/core';
-import { SelectionControl } from './SelectionControl';
-import { ScrollTimer } from '../../../ScrollTimer';
-import { IMouseEvent, IPointerEvent } from '../../../Basics/IEvents';
-import { SheetComponent } from '../SheetComponent';
-import { SelectionModel } from './SelectionModel';
-import { Vector2 } from '../../../Basics/Vector2';
-import { Scene } from '../../../Scene';
-
-/**
- * TODO 注册selection拦截,可能在有公式ArrayObject时,fx公式栏显示不同
- *
- * SelectionManager 维护model数据list,action也是修改这一层数据,obs监听到数据变动后,自动刷新(control仍然可以持有数据)
- */
-export class SelectionManager {
- hasSelection: boolean = false;
-
- private _moveObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
- private _upObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
- private _selectionControls: SelectionControl[] = []; // sheetID:Controls
-
- private _startSelectionRange: ISelection;
-
- private _startOffsetX: number = 0;
-
- private _startOffsetY: number = 0;
-
- private _scrollTimer: ScrollTimer;
-
- private _cancelDownObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
- private _cancelUpObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
- constructor(private _spreadsheet: SheetComponent) {
- this._mainEventInitial();
- }
-
- static create(spreadsheet: SheetComponent) {
- return new SelectionManager(spreadsheet);
- }
-
- /**
- * add a selection
- * @param selectionRange
- * @param curCellRange
- * @returns
- */
- addControlToCurrentByRangeData(selectionRange: IRangeData, curCellRange: Nullable<IRangeCellData>) {
- const currentControls = this.getCurrentControls();
- if (!currentControls) {
- return;
- }
- const main = this._spreadsheet;
-
- const control = SelectionControl.create(this.getScene(), currentControls.length);
-
- let cellInfo = null;
- if (curCellRange) {
- cellInfo = main.getCellByIndex(curCellRange.row, curCellRange.column);
- }
-
- const { startRow, startColumn, endRow, endColumn } = selectionRange;
- const startCell = main.getNoMergeCellPositionByIndex(startRow, startColumn);
- const endCell = main.getNoMergeCellPositionByIndex(endRow, endColumn);
-
- // update control
- control.update(
- {
- startColumn,
- startRow,
- endColumn,
- endRow,
- startY: startCell?.startY || 0,
- endY: endCell?.endY || 0,
- startX: startCell?.startX || 0,
- endX: endCell?.endX || 0,
- },
- cellInfo
- );
-
- currentControls.push(control);
- }
-
- getSpreadsheet() {
- return this._spreadsheet;
- }
-
- getMaxIndex() {
- return this._spreadsheet.zIndex + 1;
- }
-
- getScene() {
- return this._spreadsheet.getScene();
- }
-
- getSkeleton() {
- return this._spreadsheet.getSkeleton();
- }
-
- getRowAndColumnCount() {
- const skeleton = this.getSkeleton();
- return {
- rowCount: skeleton?.getRowCount() || 1000,
- columnCount: skeleton?.getColumnCount() || 50,
- };
- }
-
- getCurrentControls() {
- return this._selectionControls;
- }
-
- getCurrentControl() {
- const controls = this.getCurrentControls();
- if (controls && controls.length > 0) {
- for (const control of controls) {
- const currentCell = control.model.currentCell;
- if (currentCell) {
- return control;
- }
- }
- }
- }
-
- clearSelectionControls() {
- let curControls = this.getCurrentControls();
-
- if (curControls.length > 0) {
- for (let control of curControls) {
- control.dispose();
- }
-
- curControls.length = 0; // clear currentSelectionControls
- }
- }
-
- /**
- * Returns the list of active ranges in the active sheet or null if there are no active ranges.
- * If there is a single range selected, this behaves as a getActiveRange() call.
- *
- * @returns
- */
- getActiveRangeList(): Nullable<IRangeData[]> {
- const controls = this.getCurrentControls();
- if (controls && controls.length > 0) {
- const selections = controls?.map((control: SelectionControl) => {
- const model: SelectionModel = control.model;
- return {
- startRow: model.startRow,
- startColumn: model.startColumn,
- endRow: model.endRow,
- endColumn: model.endColumn,
- };
- });
- return selections;
- }
- }
-
- /**
- * Returns the selected range in the active sheet, or null if there is no active range. If multiple ranges are selected this method returns only the last selected range.
- * TODO: 默认最后一个选区为当前激活选区,或者当前激活单元格所在选区为激活选区
- * @returns
- */
- getActiveRange(): Nullable<IRangeData> {
- const controls = this.getCurrentControls();
- const model = controls && controls[controls.length - 1].model;
- return (
- model && {
- startRow: model.startRow,
- startColumn: model.startColumn,
- endRow: model.endRow,
- endColumn: model.endColumn,
- }
- );
- }
-
- /**
- * get active selection control
- * @returns
- */
- getActiveSelection(): Nullable<SelectionControl> {
- const controls = this.getCurrentControls();
- return controls && controls[controls.length - 1];
- }
-
- dispose() {
- this.clearSelectionControls();
- this._moveObserver = null;
- this._upObserver = null;
- }
-
- /**
- * When mousedown and mouseup need to go to the coordination and undo stack, when mousemove does not need to go to the coordination and undo stack
- * @param moveEvt
- * @param selectionControl
- * @returns
- */
- private _moving(moveOffsetX: number, moveOffsetY: number, selectionControl: Nullable<SelectionControl>) {
- // console.log('moving');
- const main = this._spreadsheet;
- // const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
- const { startRow, startColumn, endRow, endColumn } = this._startSelectionRange;
-
- // const scrollXY = main.getAncestorScrollXY(this._startOffsetX, this._startOffsetY);
- // const scene = this.getScene() as Scene;
-
- // const coord = scene.getRelativeCoord(Vector2.FromArray([moveOffsetX, moveOffsetY]));
- // const { x: newMoveOffsetX, y: newMoveOffsetY } = coord;
-
- const scrollXY = main.getScrollXYByRelativeCoords(Vector2.FromArray([this._startOffsetX, this._startOffsetY]));
-
- const moveCellInfo = main.calculateCellIndexByPosition(moveOffsetX, moveOffsetY, scrollXY);
- const moveActualSelection = makeCellToSelection(moveCellInfo);
-
- if (!moveActualSelection) {
- return false;
- }
- const { startRow: moveStartRow, startColumn: moveStartColumn, endColumn: moveEndColumn, endRow: moveEndRow } = moveActualSelection;
-
- const newStartRow = Math.min(moveStartRow, startRow);
- const newStartColumn = Math.min(moveStartColumn, startColumn);
- const newEndRow = Math.max(moveEndRow, endRow);
- const newEndColumn = Math.max(moveEndColumn, endColumn);
- const newBounding = main.getSelectionBounding(newStartRow, newStartColumn, newEndRow, newEndColumn);
-
- if (!newBounding) {
- return false;
- }
- const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = newBounding;
-
- const startCell = main.getNoMergeCellPositionByIndex(finalStartRow, finalStartColumn);
- const endCell = main.getNoMergeCellPositionByIndex(finalEndRow, finalEndColumn);
-
- const newSelectionRange: ISelection = {
- startColumn: finalStartColumn,
- startRow: finalStartRow,
- endColumn: finalEndColumn,
- endRow: finalEndRow,
- startY: startCell?.startY || 0,
- endY: endCell?.endY || 0,
- startX: startCell?.startX || 0,
- endX: endCell?.endX || 0,
- };
- // Only notify when the selection changes
- const {
- startRow: oldStartRow,
- endRow: oldEndRow,
- startColumn: oldStartColumn,
- endColumn: oldEndColumn,
- } = selectionControl?.model || { startRow: -1, endRow: -1, startColumn: -1, endColumn: -1 };
-
- if (oldStartColumn !== finalStartColumn || oldStartRow !== finalStartRow || oldEndColumn !== finalEndColumn || oldEndRow !== finalEndRow) {
- selectionControl && selectionControl.update(newSelectionRange);
- }
- }
-
- private _endSelection(scene: Scene) {
- scene.onPointerMoveObserver.remove(this._moveObserver);
- scene.onPointerUpObserver.remove(this._upObserver);
- scene.enableEvent();
-
- this._scrollTimer?.stopScroll();
-
- const mainScene = scene.getEngine()?.activeScene;
- mainScene?.onPointerDownObserver.remove(this._cancelDownObserver);
- mainScene?.onPointerUpObserver.remove(this._cancelUpObserver);
- }
-
- private _addCancelObserver() {
- const scene = this.getScene() as Scene;
- const mainScene = scene.getEngine()?.activeScene;
- if (mainScene == null || mainScene === scene) {
- return;
- }
- mainScene.onPointerDownObserver.remove(this._cancelDownObserver);
- mainScene.onPointerUpObserver.remove(this._cancelUpObserver);
- this._cancelDownObserver = mainScene.onPointerDownObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
- this._endSelection(scene);
- });
-
- this._cancelUpObserver = mainScene.onPointerUpObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
- this._endSelection(scene);
- });
- }
-
- // eslint-disable-next-line max-lines-per-function
- private _mainEventInitial() {
- const main = this._spreadsheet;
- // eslint-disable-next-line max-lines-per-function
- main.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {
- const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
-
- const scene = this.getScene() as Scene;
-
- const relativeCoords = scene.getRelativeCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
-
- const { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
-
- this._startOffsetX = newEvtOffsetX;
- this._startOffsetY = newEvtOffsetY;
-
- const scrollXY = main.getScrollXYByRelativeCoords(relativeCoords);
-
- const cellInfo = main.calculateCellIndexByPosition(newEvtOffsetX, newEvtOffsetY, scrollXY);
- const actualSelection = makeCellToSelection(cellInfo);
- if (!actualSelection) {
- return false;
- }
-
- const { startRow, startColumn, endColumn, endRow, startY, endY, startX, endX } = actualSelection;
-
- const startSelectionRange = {
- startColumn,
- startRow,
- endColumn,
- endRow,
- startY,
- endY,
- startX,
- endX,
- };
-
- this._startSelectionRange = startSelectionRange;
-
- let selectionControl: Nullable<SelectionControl> = this.getCurrentControl();
-
- let curControls = this.getCurrentControls();
-
- if (!curControls) {
- return false;
- }
-
- for (let control of curControls) {
- // right click
- if (evt.button === 2 && control.model.isInclude(startSelectionRange)) {
- selectionControl = control;
- return;
- }
- // Click to an existing selection
- if (control.model.isEqual(startSelectionRange)) {
- selectionControl = control;
- break;
- }
-
- // There can only be one highlighted cell, so clear the highlighted cell of the existing selection
- if (!evt.shiftKey) {
- control.clearHighlight();
- }
- }
-
- // In addition to pressing the ctrl or shift key, we must clear the previous selection
- if (curControls.length > 0 && !evt.ctrlKey && !evt.shiftKey) {
- for (let control of curControls) {
- control.dispose();
- }
-
- curControls.length = 0; // clear currentSelectionControls
- }
-
- const currentCell = selectionControl && selectionControl.model.currentCell;
-
- if (selectionControl && evt.shiftKey && currentCell) {
- const { row, column } = currentCell;
-
- // TODO startCell position calculate error
- const startCell = main.getNoMergeCellPositionByIndex(row, column);
- const endCell = main.getNoMergeCellPositionByIndex(endRow, endColumn);
-
- const newSelectionRange = {
- startColumn: column,
- startRow: row,
- endColumn: startSelectionRange.startColumn,
- endRow: startSelectionRange.startRow,
- startY: startCell?.startY || 0,
- endY: endCell?.endY || 0,
- startX: startCell?.startX || 0,
- endX: endCell?.endX || 0,
- };
- selectionControl.update(newSelectionRange, currentCell);
- } else {
- selectionControl = SelectionControl.create(scene, curControls.length + this.getMaxIndex());
- selectionControl.update(startSelectionRange, cellInfo);
- curControls.push(selectionControl);
- }
-
- this.hasSelection = true;
-
- scene.disableEvent();
-
- this._endSelection(scene);
-
- const scrollTimer = ScrollTimer.create(this.getScene());
- scrollTimer.startScroll(newEvtOffsetX, newEvtOffsetY);
-
- this._scrollTimer = scrollTimer;
-
- this._addCancelObserver();
-
- this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
- const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
-
- const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeCoord(Vector2.FromArray([moveOffsetX, moveOffsetY]));
-
- this._moving(newMoveOffsetX, newMoveOffsetY, selectionControl);
-
- scrollTimer.scrolling(newMoveOffsetX, newMoveOffsetY, () => {
- this._moving(newMoveOffsetX, newMoveOffsetY, selectionControl);
- });
- });
-
- this._upObserver = scene.onPointerUpObserver.add((upEvt: IPointerEvent | IMouseEvent) => {
- this._endSelection(scene);
- });
-
- state.stopPropagation();
- });
- }
-}
diff --git a/packages/base-render/src/Component/Sheets/Selection/SelectionModel.ts b/packages/base-render/src/Component/Sheets/Selection/SelectionModel.ts
deleted file mode 100644
index 0a0ae7d7fa..0000000000
--- a/packages/base-render/src/Component/Sheets/Selection/SelectionModel.ts
+++ /dev/null
@@ -1,157 +0,0 @@
-import { ICellInfo, ISelection, Nullable, makeCellToSelection } from '@univerjs/core';
-import { SELECTION_TYPE } from '../../../Basics/Const';
-
-export class SelectionModel implements ISelection {
- private _startColumn: number;
-
- private _startRow: number;
-
- private _endColumn: number;
-
- private _endRow: number;
-
- private _startX: number;
-
- private _startY: number;
-
- private _endX: number;
-
- private _endY: number;
-
- private _type: SELECTION_TYPE;
-
- private _currentCell: Nullable<ICellInfo>;
-
- constructor(type: SELECTION_TYPE = SELECTION_TYPE.NORMAL) {
- this._type = type;
- }
-
- get startColumn() {
- return this._startColumn;
- }
-
- get startRow() {
- return this._startRow;
- }
-
- get endColumn() {
- return this._endColumn;
- }
-
- get endRow() {
- return this._endRow;
- }
-
- get startX() {
- return this._startX;
- }
-
- get startY() {
- return this._startY;
- }
-
- get endX() {
- return this._endX;
- }
-
- get endY() {
- return this._endY;
- }
-
- get type() {
- return this._type;
- }
-
- get currentCell() {
- return this._currentCell;
- }
-
- isEqual(selectionRange: ISelection) {
- const { startColumn, startRow, endColumn, endRow, type } = this;
- const { startColumn: newStartColumn, startRow: newStartRow, endColumn: newEndColumn, endRow: newEndRow } = selectionRange;
- // if (type !== newType) {
- // return false;
- // }
- if (startColumn === newStartColumn && startRow === newStartRow && endColumn === newEndColumn && endRow === newEndRow) {
- return true;
- }
- return false;
- }
-
- isInclude(selectionRange: ISelection) {
- const { startColumn, startRow, endColumn, endRow, type } = this;
- const { startColumn: newStartColumn, startRow: newStartRow, endColumn: newEndColumn, endRow: newEndRow } = selectionRange;
-
- // if (type !== newType) {
- // return false;
- // }
-
- if (!(newEndColumn < startColumn || newStartColumn > endColumn || newStartRow > endRow || newEndRow < startRow)) {
- return true;
- }
- return false;
- }
-
- highlightToSelection() {
- return makeCellToSelection(this._currentCell);
- }
-
- getValue() {
- return {
- selection: {
- startColumn: this._startColumn,
- startRow: this._startRow,
- endColumn: this._endColumn,
- endRow: this._endRow,
-
- startX: this._startX,
- startY: this._startY,
- endX: this._endX,
- endY: this._endY,
- },
- cell: this._currentCell,
- };
- }
-
- setValue(newSelectionRange: ISelection, currentCell: Nullable<ICellInfo>) {
- const {
- startColumn,
- startRow,
- endColumn,
- endRow,
-
- startX,
- startY,
- endX,
- endY,
- } = newSelectionRange;
-
- this._startColumn = startColumn;
-
- this._startRow = startRow;
-
- this._endColumn = endColumn;
-
- this._endRow = endRow;
-
- this._startX = startX;
-
- this._startY = startY;
-
- this._endX = endX;
-
- this._endY = endY;
-
- this.setCurrentCell(currentCell);
- }
-
- setCurrentCell(currentCell: Nullable<ICellInfo>) {
- if (currentCell) {
- this._currentCell = currentCell;
- }
- }
-
- clearCurrentCell() {
- this._currentCell = null;
- }
-}
diff --git a/packages/base-render/src/Component/Sheets/Spreadsheet.ts b/packages/base-render/src/Component/Sheets/Spreadsheet.ts
index 6109412742..be5c82c2e7 100644
--- a/packages/base-render/src/Component/Sheets/Spreadsheet.ts
+++ b/packages/base-render/src/Component/Sheets/Spreadsheet.ts
@@ -21,7 +21,6 @@ import { columnIterator } from '../Docs/Common/Tools';
import { DocumentSkeleton } from '../Docs/DocSkeleton';
import { IDocumentSkeletonColumn } from '../../Basics/IDocumentSkeletonCached';
import { getRotateOffsetAndFarthestHypotenuse, getRotateOrientation } from '../../Basics/Draw';
-import { SelectionManager } from './Selection/SelectionManager';
const OBJECT_KEY = '__SHEET_EXTENSION_FONT_DOCUMENT_INSTANCE__';
@@ -44,8 +43,6 @@ export class Spreadsheet extends SheetComponent {
private _hasSelection = false;
- private _selection: SelectionManager;
-
private _documents: Documents = new Documents(OBJECT_KEY, undefined, {
pageMarginLeft: 0,
pageMarginTop: 0,
@@ -364,12 +361,10 @@ export class Spreadsheet extends SheetComponent {
if (this._hasSelection) {
return;
}
- this._selection = SelectionManager.create(this);
this._hasSelection = true;
}
disableSelection() {
- this._selection?.dispose();
this._hasSelection = false;
}
@@ -736,4 +731,4 @@ export class Spreadsheet extends SheetComponent {
return false;
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-render/src/Engine.ts b/packages/base-render/src/Engine.ts
index 615e593fe5..040734812f 100644
--- a/packages/base-render/src/Engine.ts
+++ b/packages/base-render/src/Engine.ts
@@ -215,7 +215,7 @@ export class Engine extends ThinEngine<Scene> {
_renderFrame() {
for (let index = 0; index < this._activeRenderLoops.length; index++) {
- let renderFunction = this._activeRenderLoops[index];
+ const renderFunction = this._activeRenderLoops[index];
renderFunction();
}
@@ -251,7 +251,7 @@ export class Engine extends ThinEngine<Scene> {
private _handleKeyboardAction() {
const keyboardDownEvent = (evt: any) => {
- let deviceEvent = evt as IKeyboardEvent;
+ const deviceEvent = evt as IKeyboardEvent;
deviceEvent.deviceType = DeviceType.Keyboard;
deviceEvent.inputIndex = evt.keyCode;
deviceEvent.previousState = 0;
@@ -261,7 +261,7 @@ export class Engine extends ThinEngine<Scene> {
};
const keyboardUpEvent = (evt: any) => {
- let deviceEvent = evt as IKeyboardEvent;
+ const deviceEvent = evt as IKeyboardEvent;
deviceEvent.deviceType = DeviceType.Keyboard;
deviceEvent.inputIndex = evt.keyCode;
deviceEvent.previousState = 1;
@@ -291,7 +291,7 @@ export class Engine extends ThinEngine<Scene> {
this.pointer[PointerInput.DeltaHorizontal] = evt.movementX;
this.pointer[PointerInput.DeltaVertical] = evt.movementY;
// console.log('pointerMoveEvent_1', previousHorizontal, evt.clientX, previousVertical, evt.clientY, this.__pointer);
- let deviceEvent = evt as IPointerEvent;
+ const deviceEvent = evt as IPointerEvent;
deviceEvent.deviceType = deviceType;
if (previousHorizontal !== evt.clientX) {
@@ -365,7 +365,7 @@ export class Engine extends ThinEngine<Scene> {
this.pointer[PointerInput.Vertical] = evt.clientY;
this.pointer[evt.button + 2] = 1;
- let deviceEvent = evt as IPointerEvent;
+ const deviceEvent = evt as IPointerEvent;
deviceEvent.deviceType = deviceType;
if (previousHorizontal !== evt.clientX) {
@@ -404,7 +404,7 @@ export class Engine extends ThinEngine<Scene> {
this.pointer[PointerInput.Vertical] = evt.clientY;
this.pointer[evt.button + 2] = 0;
- let deviceEvent = evt as IPointerEvent;
+ const deviceEvent = evt as IPointerEvent;
deviceEvent.deviceType = deviceType;
if (previousHorizontal !== evt.clientX) {
@@ -452,15 +452,15 @@ export class Engine extends ThinEngine<Scene> {
this._pointerWheelEvent = (evt: any) => {
const deviceType = DeviceType.Mouse;
// Store previous values for event
- let previousWheelScrollX = this.pointer[PointerInput.MouseWheelX];
- let previousWheelScrollY = this.pointer[PointerInput.MouseWheelY];
- let previousWheelScrollZ = this.pointer[PointerInput.MouseWheelZ];
+ const previousWheelScrollX = this.pointer[PointerInput.MouseWheelX];
+ const previousWheelScrollY = this.pointer[PointerInput.MouseWheelY];
+ const previousWheelScrollZ = this.pointer[PointerInput.MouseWheelZ];
this.pointer[PointerInput.MouseWheelX] = evt.deltaX || 0;
this.pointer[PointerInput.MouseWheelY] = evt.deltaY || evt.wheelDelta || 0;
this.pointer[PointerInput.MouseWheelZ] = evt.deltaZ || 0;
- let deviceEvent = evt as IPointerEvent;
+ const deviceEvent = evt as IPointerEvent;
deviceEvent.deviceType = deviceType;
if (this.pointer[PointerInput.MouseWheelX] !== 0) {
@@ -491,7 +491,7 @@ export class Engine extends ThinEngine<Scene> {
}
private _getWheelEventName(): string {
- let wheelEventName =
+ const wheelEventName =
'onwheel' in document.createElement('div')
? 'wheel' // Modern browsers support "wheel"
: (document as any).onmousewheel !== undefined
@@ -535,4 +535,4 @@ export class Engine extends ThinEngine<Scene> {
return deviceType;
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-sheets/package.json b/packages/base-sheets/package.json
index 17f437568e..a69bc15102 100644
--- a/packages/base-sheets/package.json
+++ b/packages/base-sheets/package.json
@@ -11,7 +11,6 @@
"license": "MIT",
"main": "./src/index.ts",
"module": "./src/index.ts",
- "types": "./src/Types/index.d.ts",
"publishConfig": {
"main": "./lib/univer-base-sheets.cjs.js",
"module": "./lib/univer-base-sheets.js",
diff --git a/packages/base-sheets/src/Basics/Interfaces/MutationInterface.ts b/packages/base-sheets/src/Basics/Interfaces/MutationInterface.ts
new file mode 100644
index 0000000000..61f778aa7d
--- /dev/null
+++ b/packages/base-sheets/src/Basics/Interfaces/MutationInterface.ts
@@ -0,0 +1,79 @@
+import { Dimension, ICellData, IRangeData, IWorksheetConfig, Nullable, ObjectMatrixPrimitiveType } from '@univerjs/core';
+
+/** Params of `RemoveSheetMutation` */
+export interface IRemoveSheetMutationParams {
+ worksheetId: string;
+ workbookId: string;
+}
+
+/** Params of `InsertSheetMutation` */
+export interface IInsertSheetMutationParams {
+ index: number;
+ sheet: IWorksheetConfig;
+ workbookId: string;
+}
+
+/** Params of InsertRowMutation */
+export interface IInsertRowMutationParams {
+ workbookId: string;
+ worksheetId: string;
+ rowIndex: number;
+ rowCount: number;
+ insertRowData: Nullable<ObjectMatrixPrimitiveType<ICellData>>;
+}
+
+/** Params of InsertColMutation */
+export interface IInsertColMutationParams {
+ workbookId: string;
+ worksheetId: string;
+ colIndex: number;
+ colCount: number;
+ insertColData: Nullable<ObjectMatrixPrimitiveType<ICellData>>;
+}
+
+/** Params of InsertRowMutation */
+export interface IRemoveRowMutationParams {
+ workbookId: string;
+ worksheetId: string;
+ rowIndex: number;
+ rowCount: number;
+}
+
+/** Params of InsertColMutation */
+export interface IRemoveColMutationParams {
+ workbookId: string;
+ worksheetId: string;
+ colIndex: number;
+ colCount: number;
+}
+
+/** Params of DeleteRange */
+export interface IDeleteRangeMutationParams {
+ workbookId: string;
+ worksheetId: string;
+ range: IRangeData;
+ shiftDimension: Dimension;
+}
+
+/** Params of InsertRange */
+export interface IInsertRangeMutationParams {
+ workbookId: string;
+ worksheetId: string;
+ range: IRangeData;
+ shiftDimension: Dimension;
+ cellValue: ObjectMatrixPrimitiveType<ICellData>;
+}
+
+/** Params of RemoveWorksheetMergeMutation */
+export interface IRemoveWorksheetMergeMutationParams {
+ workbookId: string;
+ worksheetId: string;
+ rectangles: IRangeData[];
+}
+
+/** Params of AddWorksheetMergeMutation */
+export interface IAddWorksheetMergeMutationParams {
+ workbookId: string;
+ worksheetId: string;
+ rectangles: IRangeData[];
+}
diff --git a/packages/base-sheets/src/Commands/Commands/add-worksheet-merge.command.ts b/packages/base-sheets/src/Commands/Commands/add-worksheet-merge.command.ts
new file mode 100644
index 0000000000..b43e5419c2
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/add-worksheet-merge.command.ts
@@ -0,0 +1,67 @@
+import { CommandType, ICommand, ICommandService, ICurrentUniverService, IRangeData, IUndoRedoService } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { AddWorksheetMergeMutation, AddWorksheetMergeMutationFactory } from '../Mutations/add-worksheet-merge.mutation';
+import { IRemoveWorksheetMergeMutationParams } from '../../Basics/Interfaces/MutationInterface';
+import { RemoveWorksheetMergeMutation } from '../Mutations/remove-worksheet-merge.mutation';
+import { ISelectionManager } from '../../Services/tokens';
+
+export interface IAddWorksheetMergeCommandParams {
+ workbookId: string;
+ worksheetId: string;
+ rectangles: IRangeData[];
+}
+
+export const AddWorksheetMergeCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.add-worksheet-merge',
+ handler: async (accessor: IAccessor, params?: IAddWorksheetMergeCommandParams) => {
+ const selectionManager = accessor.get(ISelectionManager);
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const currentUniverService = accessor.get(ICurrentUniverService);
+
+ let redoMutationParams: IAddWorksheetMergeCommandParams;
+ if (params == null) {
+ const selections = selectionManager.getCurrentSelections();
+ const workbook = currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
+ if (!selections.length) {
+ return false;
+ }
+ const range = selections[0];
+ redoMutationParams = {
+ workbookId: workbook.getUnitId(),
+ worksheetId: workbook.getActiveSheet().getSheetId(),
+ rectangles: [
+ {
+ startRow: range.startRow,
+ startColumn: range.startColumn,
+ endRow: range.endRow,
+ endColumn: range.endColumn,
+ },
+ ],
+ };
+ } else {
+ redoMutationParams = {
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ rectangles: params.rectangles,
+ };
+ }
+
+ const undoMutationParams: IRemoveWorksheetMergeMutationParams = AddWorksheetMergeMutationFactory(accessor, redoMutationParams);
+ const result = commandService.executeCommand(RemoveWorksheetMergeMutation.id, redoMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: 'sheet',
+ undo() {
+ return commandService.executeCommand(AddWorksheetMergeMutation.id, undoMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(RemoveWorksheetMergeMutation.id, redoMutationParams);
+ },
+ });
+ return true;
+ }
+ return true;
+ },
+};
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 321990843e..35f801147c 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
@@ -2,8 +2,6 @@ import { CommandType, ICommand, ICommandService, ICurrentUniverService, IUndoRed
import { IAccessor } from '@wendellhu/redi';
import { ISelectionManager } from '../../Services/tokens';
-import { SelectionController } from '../../Controller/Selection/SelectionController';
-import { SelectionModel } from '../../Model/SelectionModel';
import { ISetRangeValuesMutationParams, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../Mutations/set-range-values.mutation';
/**
@@ -18,27 +16,14 @@ export const ClearSelectionContentCommand: ICommand = {
const selectionManager = accessor.get(ISelectionManager);
const undoRedoService = accessor.get(IUndoRedoService);
- // TODO: this is to verbose to get a serializable range
- // a range should have worksheet id as well
+ // TODO: this is to verbose to get a serializable range, a range should have worksheet id as well
const workbook = currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
const worksheet = workbook.getActiveSheet();
- const controls = selectionManager.getCurrentControls();
- const selections = controls?.map((control: SelectionController) => {
- const model: SelectionModel = control.model;
- return {
- startRow: model.startRow,
- startColumn: model.startColumn,
- endRow: model.endRow,
- endColumn: model.endColumn,
- };
- });
-
- if (!selections) {
+ const selections = selectionManager.getCurrentSelections();
+ if (!selections.length) {
return false;
}
- // prepare do mutations
-
const range = selections[0];
const clearMutationParams: ISetRangeValuesMutationParams = {
rangeData: range,
@@ -46,7 +31,6 @@ export const ClearSelectionContentCommand: ICommand = {
};
const undoClearMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(accessor, clearMutationParams);
- // execute do mutations and add undo mutations to undo stack if completed
const result = commandService.executeCommand(SetRangeValuesMutation.id, clearMutationParams);
if (result) {
undoRedoService.pushUndoRedo({
diff --git a/packages/base-sheets/src/Commands/Commands/copy-format-to-range.command.ts b/packages/base-sheets/src/Commands/Commands/copy-format-to-range.command.ts
new file mode 100644
index 0000000000..7e92f5a8c7
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/copy-format-to-range.command.ts
@@ -0,0 +1,138 @@
+import {
+ CommandType,
+ ICellData,
+ ICellDataMatrix,
+ ICommand,
+ ICommandService,
+ ICurrentUniverService,
+ IRangeData,
+ IStyleData,
+ IUndoRedoService,
+ Nullable,
+ ObjectMatrix,
+} from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { ISetRangeStyleMutationParams, SetRangeStyleMutation, SetRangeStyleUndoMutationFactory } from '../Mutations/set-range-styles.mutation';
+
+export interface ICopyFormatToRangeCommandParams {
+ workbookId: string;
+ worksheetId: string;
+ originRange: IRangeData;
+ destinationRange: IRangeData;
+}
+
+export const CopyFormatToRangeCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.copy-format-to-range',
+ handler: async (accessor: IAccessor, params: ICopyFormatToRangeCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const workbook = accessor.get(ICurrentUniverService).getUniverSheetInstance(params.workbookId)?.getWorkBook();
+ if (!workbook) return false;
+ const handleResult = handleCopyRange(accessor, params.workbookId, params.worksheetId, params.originRange, params.destinationRange);
+ if (!handleResult) return false;
+ const value = handleResult[0];
+ const range = handleResult[1];
+ const styles = workbook.getStyles();
+ const stylesMatrix = new ObjectMatrix<IStyleData>();
+ value.map((row, r) =>
+ row.map((cell, c) => {
+ cell = cell as ICellData;
+ stylesMatrix.setValue(r, c, styles.getStyleByCell(cell) || {});
+ return styles.getStyleByCell(cell) || {};
+ })
+ );
+
+ const setRangeStyleMutationParams: ISetRangeStyleMutationParams = {
+ range: [range],
+ worksheetId: params.worksheetId,
+ workbookId: params.workbookId,
+ value: stylesMatrix.getData(),
+ };
+
+ const undoMutationParams: ISetRangeStyleMutationParams = SetRangeStyleUndoMutationFactory(accessor, setRangeStyleMutationParams);
+ const result = commandService.executeCommand(SetRangeStyleMutation.id, setRangeStyleMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: 'sheet',
+ undo() {
+ return commandService.executeCommand(SetRangeStyleMutation.id, undoMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(SetRangeStyleMutation.id, setRangeStyleMutationParams);
+ },
+ });
+ return true;
+ }
+ return true;
+ },
+};
+
+function handleCopyRange(
+ accessor: IAccessor,
+ workbookId: string,
+ worksheetId: string,
+ originRange: IRangeData,
+ destinationRange: IRangeData
+): Nullable<[ICellDataMatrix, IRangeData]> {
+ const worksheet = accessor.get(ICurrentUniverService).getUniverSheetInstance(workbookId)?.getWorkBook().getSheetBySheetId(worksheetId);
+ if (!worksheet) return;
+
+ const sheetMatrix = worksheet.getCellMatrix();
+ const rangeMatrix = new ObjectMatrix<ICellData>();
+
+ const { startRow, endRow, startColumn, endColumn } = originRange;
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ rangeMatrix.setValue(r, c, sheetMatrix.getValue(r, c) || null);
+ }
+ }
+
+ const cellData = worksheet.getCellMatrix();
+ // eslint-disable-next-line prefer-const
+ let { startRow: dStartRow, endRow: dEndRow, startColumn: dStartColumn, endColumn: dEndColumn } = destinationRange;
+
+ const originRows = endRow - startRow + 1;
+ const originColumns = endColumn - startColumn + 1;
+ const destinationRows = dEndRow - dStartRow + 1;
+ const destinationColumns = dEndColumn - dStartColumn + 1;
+
+ let value: ICellDataMatrix = [];
+ let range: IRangeData;
+
+ // judge whether N2 is a multiple of N1
+ if (destinationRows % originRows === 0 && destinationColumns % originColumns === 0) {
+ /**
+ * A1,B1 => A1,B1,C1,D1
+ * A2,B2 A2,B2,C2,D2
+ * A3,B3,C3,D3
+ * A4,B4,C4,D4
+ */
+ for (let r = 0; r < destinationRows; r++) {
+ const row = [];
+ for (let c = 0; c < destinationColumns; c++) {
+ // Retrieve the corresponding cell data from the original range, {} as a fallback
+ const cell = cellData.getValue((r + startRow) % originRows, (c + startColumn) % originColumns) || {};
+ row.push(cell);
+ }
+ value.push(row);
+ }
+ range = destinationRange;
+ } else {
+ value = cellData.getFragments(startRow, endRow, startColumn, endColumn).getData() as ICellDataMatrix;
+
+ // Extend the destination to the same size as the original range
+ dEndRow += originRows - destinationRows;
+ dEndColumn += originColumns - destinationColumns;
+
+ range = {
+ startRow: dStartRow,
+ endRow: dEndRow,
+ startColumn: dStartColumn,
+ endColumn: dEndColumn,
+ };
+ }
+
+ return [value, range];
+}
diff --git a/packages/base-sheets/src/Commands/Commands/copy-to.command.ts b/packages/base-sheets/src/Commands/Commands/copy-to.command.ts
new file mode 100644
index 0000000000..1ff4d98682
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/copy-to.command.ts
@@ -0,0 +1,61 @@
+import {
+ CommandType,
+ ICellData,
+ ICellDataMatrix,
+ ICommand,
+ ICommandService,
+ ICurrentUniverService,
+ IOptionData,
+ IRangeData,
+ IStyleData,
+ IUndoRedoService,
+ Nullable,
+ ObjectMatrix,
+} from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { ISetRangeStyleMutationParams, SetRangeStyleMutation, SetRangeStyleUndoMutationFactory } from '../Mutations/set-range-styles.mutation';
+
+
+
+export interface ICopyToCommandParams {
+ workbookId: string;
+ worksheetId: string;
+ originRange: IRangeData;
+ destinationRange: IRangeData;
+ options?: IOptionData |
+}
+
+export const CopyFormatToRangeCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.copy-to',
+ handler: async (accessor: IAccessor, params: ICopyToCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+
+
+ const setRangeStyleMutationParams: ISetRangeStyleMutationParams = {
+ range: [range],
+ worksheetId: params.worksheetId,
+ workbookId: params.workbookId,
+ value: stylesMatrix.getData(),
+ };
+
+ const undoMutationParams: ISetRangeStyleMutationParams = SetRangeStyleUndoMutationFactory(accessor, setRangeStyleMutationParams);
+ const result = commandService.executeCommand(SetRangeStyleMutation.id, setRangeStyleMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: 'sheet',
+ undo() {
+ return commandService.executeCommand(SetRangeStyleMutation.id, undoMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(SetRangeStyleMutation.id, setRangeStyleMutationParams);
+ },
+ });
+ return true;
+ }
+ return true;
+ },
+};
+
diff --git a/packages/base-sheets/src/Commands/Commands/copy-values-to-range.command.ts b/packages/base-sheets/src/Commands/Commands/copy-values-to-range.command.ts
new file mode 100644
index 0000000000..03695ae640
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/copy-values-to-range.command.ts
@@ -0,0 +1,136 @@
+import {
+ CommandType,
+ ICellData,
+ ICellDataMatrix,
+ ICellV,
+ ICommand,
+ ICommandService,
+ ICurrentUniverService,
+ IRangeData,
+ IUndoRedoService,
+ Nullable,
+ ObjectMatrix,
+} from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { ISetRangeFormattedValueMutationParams, SetRangeFormattedValueMutation, SetRangeFormattedValueUndoMutationFactory } from '../Mutations/set-range-formatted-value.mutation';
+
+export interface ICopyValuesToRangeCommandParams {
+ workbookId: string;
+ worksheetId: string;
+ originRange: IRangeData;
+ destinationRange: IRangeData;
+}
+
+export const CopyValuesToRangeCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.copy-values-to-range',
+ handler: async (accessor: IAccessor, params: ICopyValuesToRangeCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const workbook = accessor.get(ICurrentUniverService).getUniverSheetInstance(params.workbookId)?.getWorkBook();
+ if (!workbook) return false;
+ const handleResult = handleCopyRange(accessor, params.workbookId, params.worksheetId, params.originRange, params.destinationRange);
+ if (!handleResult) return false;
+ const value = handleResult[0];
+ const range = handleResult[1];
+ const cellValue = new ObjectMatrix<ICellV>();
+ value.forEach((row, r) =>
+ row.forEach((cell, c) => {
+ cell = cell as ICellData;
+ cellValue.setValue(r + params.destinationRange.startRow, c + params.destinationRange.startColumn, cell?.v || '');
+ })
+ );
+
+ const setRangeFormattedValueMutationParams: ISetRangeFormattedValueMutationParams = {
+ range: [range],
+ worksheetId: params.worksheetId,
+ workbookId: params.workbookId,
+ value: cellValue.getData(),
+ };
+
+ const undoMutationParams: ISetRangeFormattedValueMutationParams = SetRangeFormattedValueUndoMutationFactory(accessor, setRangeFormattedValueMutationParams);
+ const result = commandService.executeCommand(SetRangeFormattedValueMutation.id, setRangeFormattedValueMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: 'sheet',
+ undo() {
+ return commandService.executeCommand(SetRangeFormattedValueMutation.id, undoMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(SetRangeFormattedValueMutation.id, setRangeFormattedValueMutationParams);
+ },
+ });
+ return true;
+ }
+ return true;
+ },
+};
+
+function handleCopyRange(
+ accessor: IAccessor,
+ workbookId: string,
+ worksheetId: string,
+ originRange: IRangeData,
+ destinationRange: IRangeData
+): Nullable<[ICellDataMatrix, IRangeData]> {
+ const worksheet = accessor.get(ICurrentUniverService).getUniverSheetInstance(workbookId)?.getWorkBook().getSheetBySheetId(worksheetId);
+ if (!worksheet) return;
+
+ const sheetMatrix = worksheet.getCellMatrix();
+ const rangeMatrix = new ObjectMatrix<ICellData>();
+
+ const { startRow, endRow, startColumn, endColumn } = originRange;
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ rangeMatrix.setValue(r, c, sheetMatrix.getValue(r, c) || null);
+ }
+ }
+
+ const cellData = worksheet.getCellMatrix();
+ // eslint-disable-next-line prefer-const
+ let { startRow: dStartRow, endRow: dEndRow, startColumn: dStartColumn, endColumn: dEndColumn } = destinationRange;
+
+ const originRows = endRow - startRow + 1;
+ const originColumns = endColumn - startColumn + 1;
+ const destinationRows = dEndRow - dStartRow + 1;
+ const destinationColumns = dEndColumn - dStartColumn + 1;
+
+ let value: ICellDataMatrix = [];
+ let range: IRangeData;
+
+ // judge whether N2 is a multiple of N1
+ if (destinationRows % originRows === 0 && destinationColumns % originColumns === 0) {
+ /**
+ * A1,B1 => A1,B1,C1,D1
+ * A2,B2 A2,B2,C2,D2
+ * A3,B3,C3,D3
+ * A4,B4,C4,D4
+ */
+ for (let r = 0; r < destinationRows; r++) {
+ const row = [];
+ for (let c = 0; c < destinationColumns; c++) {
+ // Retrieve the corresponding cell data from the original range, {} as a fallback
+ const cell = cellData.getValue((r + startRow) % originRows, (c + startColumn) % originColumns) || {};
+ row.push(cell);
+ }
+ value.push(row);
+ }
+ range = destinationRange;
+ } else {
+ value = cellData.getFragments(startRow, endRow, startColumn, endColumn).getData() as ICellDataMatrix;
+
+ // Extend the destination to the same size as the original range
+ dEndRow += originRows - destinationRows;
+ dEndColumn += originColumns - destinationColumns;
+
+ range = {
+ startRow: dStartRow,
+ endRow: dEndRow,
+ startColumn: dStartColumn,
+ endColumn: dEndColumn,
+ };
+ }
+
+ return [value, range];
+}
diff --git a/packages/base-sheets/src/Commands/Commands/delete-range-move-left.command.ts b/packages/base-sheets/src/Commands/Commands/delete-range-move-left.command.ts
new file mode 100644
index 0000000000..11af35f446
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/delete-range-move-left.command.ts
@@ -0,0 +1,57 @@
+import { IAccessor } from '@wendellhu/redi';
+import { CommandType, Dimension, ICommand, ICommandService, IRangeData, IUndoRedoService } from '@univerjs/core';
+
+import { DeleteRangeMutation, DeleteRangeUndoMutationFactory } from '../Mutations/delete-range.mutation';
+import { InsertRangeMutation } from '../Mutations/insert-range.mutation';
+import { IDeleteRangeMutationParams, IInsertRangeMutationParams } from '../../Basics/Interfaces/MutationInterface';
+
+export interface IDeleteRangeMoveLeftParams {
+ workbookId: string;
+ worksheetId: string;
+ range: IRangeData;
+}
+
+/**
+ * The command to delete range.
+ */
+export const DeleteRangeMoveLeftCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.delete-range-move-left',
+
+ handler: async (accessor: IAccessor, params: IDeleteRangeMoveLeftParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const { range, workbookId, worksheetId } = params;
+
+ const deleteRangeMutationParams: IDeleteRangeMutationParams = {
+ range,
+ worksheetId,
+ workbookId,
+ shiftDimension: Dimension.COLUMNS,
+ };
+
+ const insertRangeMutationParams: IInsertRangeMutationParams = DeleteRangeUndoMutationFactory(accessor, deleteRangeMutationParams);
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const result = commandService.executeCommand(DeleteRangeMutation.id, deleteRangeMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ // 如果有多个 mutation 构成一个封装项目,那么要封装在同一个 undo redo element 里面
+ // 通过勾子可以 hook 外部 controller 的代码来增加新的 action
+ URI: 'sheet', // TODO: this URI is fake
+ undo() {
+ return commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(DeleteRangeMutation.id, deleteRangeMutationParams);
+ },
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+ // all subsequent mutations should succeed inorder to make the whole process succeed
+ // Promise.all([]).then(() => true),
+};
diff --git a/packages/base-sheets/src/Commands/Commands/delete-range-move-top.command.ts b/packages/base-sheets/src/Commands/Commands/delete-range-move-top.command.ts
new file mode 100644
index 0000000000..2ec3b47bb6
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/delete-range-move-top.command.ts
@@ -0,0 +1,57 @@
+import { IAccessor } from '@wendellhu/redi';
+import { CommandType, Dimension, ICommand, ICommandService, IRangeData, IUndoRedoService } from '@univerjs/core';
+
+import { DeleteRangeMutation, DeleteRangeUndoMutationFactory } from '../Mutations/delete-range.mutation';
+import { InsertRangeMutation } from '../Mutations/insert-range.mutation';
+import { IDeleteRangeMutationParams, IInsertRangeMutationParams } from '../../Basics/Interfaces/MutationInterface';
+
+export interface IDeleteRangeMoveTopParams {
+ workbookId: string;
+ worksheetId: string;
+ range: IRangeData;
+}
+
+/**
+ * The command to delete range.
+ */
+export const DeleteRangeMoveTopCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.delete-range-move-top',
+
+ handler: async (accessor: IAccessor, params: IDeleteRangeMoveTopParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const { range, workbookId, worksheetId } = params;
+
+ const deleteRangeMutationParams: IDeleteRangeMutationParams = {
+ range,
+ worksheetId,
+ workbookId,
+ shiftDimension: Dimension.ROWS,
+ };
+
+ const insertRangeMutationParams: IInsertRangeMutationParams = DeleteRangeUndoMutationFactory(accessor, deleteRangeMutationParams);
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const result = commandService.executeCommand(DeleteRangeMutation.id, deleteRangeMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ // 如果有多个 mutation 构成一个封装项目,那么要封装在同一个 undo redo element 里面
+ // 通过勾子可以 hook 外部 controller 的代码来增加新的 action
+ URI: 'sheet', // TODO: this URI is fake
+ undo() {
+ return commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(DeleteRangeMutation.id, deleteRangeMutationParams);
+ },
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+ // all subsequent mutations should succeed inorder to make the whole process succeed
+ // Promise.all([]).then(() => true),
+};
diff --git a/packages/base-sheets/src/Commands/Commands/delete-range.command.ts b/packages/base-sheets/src/Commands/Commands/delete-range.command.ts
new file mode 100644
index 0000000000..2c924f2a2f
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/delete-range.command.ts
@@ -0,0 +1,58 @@
+import { IAccessor } from '@wendellhu/redi';
+import { CommandType, Dimension, ICommand, ICommandService, IRangeData, IUndoRedoService } from '@univerjs/core';
+
+import { DeleteRangeMutation, DeleteRangeUndoMutationFactory } from '../Mutations/delete-range.mutation';
+import { InsertRangeMutation } from '../Mutations/insert-range.mutation';
+import { IDeleteRangeMutationParams, IInsertRangeMutationParams } from '../../Basics/Interfaces/MutationInterface';
+
+export interface IDeleteRangeParams {
+ workbookId: string;
+ worksheetId: string;
+ range: IRangeData;
+ shiftDimension: Dimension;
+}
+
+/**
+ * The command to delete range.
+ */
+export const DeleteRangeCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.delete-range',
+
+ handler: async (accessor: IAccessor, params: IDeleteRangeParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const { range, workbookId, worksheetId, shiftDimension } = params;
+
+ const deleteRangeMutationParams: IDeleteRangeMutationParams = {
+ range,
+ worksheetId,
+ workbookId,
+ shiftDimension,
+ };
+
+ const insertRangeMutationParams: IInsertRangeMutationParams = DeleteRangeUndoMutationFactory(accessor, deleteRangeMutationParams);
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const result = commandService.executeCommand(DeleteRangeMutation.id, deleteRangeMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ // 如果有多个 mutation 构成一个封装项目,那么要封装在同一个 undo redo element 里面
+ // 通过勾子可以 hook 外部 controller 的代码来增加新的 action
+ URI: 'sheet', // TODO: this URI is fake
+ undo() {
+ return commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(DeleteRangeMutation.id, deleteRangeMutationParams);
+ },
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+ // all subsequent mutations should succeed inorder to make the whole process succeed
+ // Promise.all([]).then(() => true),
+};
diff --git a/packages/base-sheets/src/Commands/Commands/insert-range-move-bottom.command.ts b/packages/base-sheets/src/Commands/Commands/insert-range-move-bottom.command.ts
new file mode 100644
index 0000000000..59cf4c23e1
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/insert-range-move-bottom.command.ts
@@ -0,0 +1,88 @@
+import { IAccessor } from '@wendellhu/redi';
+import { CommandType, Dimension, ICellData, ICommand, ICommandService, ICurrentUniverService, IRangeData, IUndoRedoService, ObjectMatrix } from '@univerjs/core';
+
+import { DeleteRangeMutation } from '../Mutations/delete-range.mutation';
+import { InsertRangeMutation, InsertRangeUndoMutationFactory } from '../Mutations/insert-range.mutation';
+import { IDeleteRangeMutationParams, IInsertRangeMutationParams } from '../../Basics/Interfaces/MutationInterface';
+
+export interface IInsertRangeMoveBottomParams {
+ workbookId: string;
+ worksheetId: string;
+ range: IRangeData;
+ destination?: IRangeData;
+}
+
+/**
+ * The command to insert range.
+ */
+export const InsertRangeMoveBottomCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.insert-range-move-bottom',
+
+ handler: async (accessor: IAccessor, params: IInsertRangeMoveBottomParams) => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const { destination, workbookId, worksheetId, range } = params;
+ let rangeData: IRangeData = range;
+ const cellValue = new ObjectMatrix<ICellData>();
+ const { startRow, endRow, startColumn, endColumn } = range;
+ if (destination) {
+ const worksheet = currentUniverService.getUniverSheetInstance(workbookId)?.getWorkBook().getSheetBySheetId(worksheetId);
+ if (!worksheet) return false;
+ const sheetMatrix = worksheet.getCellMatrix();
+
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ cellValue.setValue(r - startRow, c - startColumn, sheetMatrix.getValue(r, c) || {});
+ }
+ }
+
+ rangeData = {
+ startRow,
+ endRow: startRow + destination.endRow - destination.startRow,
+ startColumn,
+ endColumn: startRow + destination.endColumn - destination.startColumn,
+ };
+ } else {
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ cellValue.setValue(r, c, { m: '', v: '' });
+ }
+ }
+ }
+
+ const insertRangeMutationParams: IInsertRangeMutationParams = {
+ range: rangeData,
+ worksheetId,
+ workbookId,
+ shiftDimension: Dimension.ROWS,
+ cellValue: cellValue.getData(),
+ };
+
+ const deleteRangeMutationParams: IDeleteRangeMutationParams = InsertRangeUndoMutationFactory(accessor, insertRangeMutationParams);
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const result = commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ // 如果有多个 mutation 构成一个封装项目,那么要封装在同一个 undo redo element 里面
+ // 通过勾子可以 hook 外部 controller 的代码来增加新的 action
+ URI: 'sheet', // TODO: this URI is fake
+ undo() {
+ return commandService.executeCommand(DeleteRangeMutation.id, deleteRangeMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);
+ },
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+ // all subsequent mutations should succeed inorder to make the whole process succeed
+ // Promise.all([]).then(() => true),
+};
diff --git a/packages/base-sheets/src/Commands/Commands/insert-range-move-right.command.ts b/packages/base-sheets/src/Commands/Commands/insert-range-move-right.command.ts
new file mode 100644
index 0000000000..a92b52cd39
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/insert-range-move-right.command.ts
@@ -0,0 +1,88 @@
+import { IAccessor } from '@wendellhu/redi';
+import { CommandType, Dimension, ICellData, ICommand, ICommandService, ICurrentUniverService, IRangeData, IUndoRedoService, ObjectMatrix } from '@univerjs/core';
+
+import { DeleteRangeMutation } from '../Mutations/delete-range.mutation';
+import { InsertRangeMutation, InsertRangeUndoMutationFactory } from '../Mutations/insert-range.mutation';
+import { IDeleteRangeMutationParams, IInsertRangeMutationParams } from '../../Basics/Interfaces/MutationInterface';
+
+export interface IInsertRangeMoveRightParams {
+ workbookId: string;
+ worksheetId: string;
+ range: IRangeData;
+ destination?: IRangeData;
+}
+
+/**
+ * The command to insert range.
+ */
+export const InsertRangeMoveRightCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.insert-range-move-right',
+
+ handler: async (accessor: IAccessor, params: IInsertRangeMoveRightParams) => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const { destination, workbookId, worksheetId, range } = params;
+ let rangeData: IRangeData = range;
+ const cellValue = new ObjectMatrix<ICellData>();
+ const { startRow, endRow, startColumn, endColumn } = range;
+ if (destination) {
+ const worksheet = currentUniverService.getUniverSheetInstance(workbookId)?.getWorkBook().getSheetBySheetId(worksheetId);
+ if (!worksheet) return false;
+ const sheetMatrix = worksheet.getCellMatrix();
+
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ cellValue.setValue(r - startRow, c - startColumn, sheetMatrix.getValue(r, c) || {});
+ }
+ }
+
+ rangeData = {
+ startRow,
+ endRow: startRow + destination.endRow - destination.startRow,
+ startColumn,
+ endColumn: startRow + destination.endColumn - destination.startColumn,
+ };
+ } else {
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ cellValue.setValue(r, c, { m: '', v: '' });
+ }
+ }
+ }
+
+ const insertRangeMutationParams: IInsertRangeMutationParams = {
+ range: rangeData,
+ worksheetId,
+ workbookId,
+ shiftDimension: Dimension.COLUMNS,
+ cellValue: cellValue.getData(),
+ };
+
+ const deleteRangeMutationParams: IDeleteRangeMutationParams = InsertRangeUndoMutationFactory(accessor, insertRangeMutationParams);
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const result = commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ // 如果有多个 mutation 构成一个封装项目,那么要封装在同一个 undo redo element 里面
+ // 通过勾子可以 hook 外部 controller 的代码来增加新的 action
+ URI: 'sheet', // TODO: this URI is fake
+ undo() {
+ return commandService.executeCommand(DeleteRangeMutation.id, deleteRangeMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);
+ },
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+ // all subsequent mutations should succeed inorder to make the whole process succeed
+ // Promise.all([]).then(() => true),
+};
diff --git a/packages/base-sheets/src/Commands/Commands/insert-range.command.ts b/packages/base-sheets/src/Commands/Commands/insert-range.command.ts
new file mode 100644
index 0000000000..240e388a3d
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/insert-range.command.ts
@@ -0,0 +1,89 @@
+import { IAccessor } from '@wendellhu/redi';
+import { CommandType, Dimension, ICellData, ICommand, ICommandService, ICurrentUniverService, IRangeData, IUndoRedoService, ObjectMatrix } from '@univerjs/core';
+
+import { DeleteRangeMutation } from '../Mutations/delete-range.mutation';
+import { InsertRangeMutation, InsertRangeUndoMutationFactory } from '../Mutations/insert-range.mutation';
+import { IDeleteRangeMutationParams, IInsertRangeMutationParams } from '../../Basics/Interfaces/MutationInterface';
+
+export interface IInsertRangeParams {
+ workbookId: string;
+ worksheetId: string;
+ range: IRangeData;
+ shiftDimension: Dimension;
+ destination?: IRangeData;
+}
+
+/**
+ * The command to insert range.
+ */
+export const InsertRangeCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.insert-range',
+
+ handler: async (accessor: IAccessor, params: IInsertRangeParams) => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const { destination, workbookId, worksheetId, range, shiftDimension } = params;
+ let rangeData: IRangeData = range;
+ const cellValue = new ObjectMatrix<ICellData>();
+ const { startRow, endRow, startColumn, endColumn } = range;
+ if (destination) {
+ const worksheet = currentUniverService.getUniverSheetInstance(workbookId)?.getWorkBook().getSheetBySheetId(worksheetId);
+ if (!worksheet) return false;
+ const sheetMatrix = worksheet.getCellMatrix();
+
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ cellValue.setValue(r - startRow, c - startColumn, sheetMatrix.getValue(r, c) || {});
+ }
+ }
+
+ rangeData = {
+ startRow,
+ endRow: startRow + destination.endRow - destination.startRow,
+ startColumn,
+ endColumn: startRow + destination.endColumn - destination.startColumn,
+ };
+ } else {
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ cellValue.setValue(r, c, { m: '', v: '' });
+ }
+ }
+ }
+
+ const insertRangeMutationParams: IInsertRangeMutationParams = {
+ range: rangeData,
+ worksheetId,
+ workbookId,
+ shiftDimension,
+ cellValue: cellValue.getData(),
+ };
+
+ const deleteRangeMutationParams: IDeleteRangeMutationParams = InsertRangeUndoMutationFactory(accessor, insertRangeMutationParams);
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const result = commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ // 如果有多个 mutation 构成一个封装项目,那么要封装在同一个 undo redo element 里面
+ // 通过勾子可以 hook 外部 controller 的代码来增加新的 action
+ URI: 'sheet', // TODO: this URI is fake
+ undo() {
+ return commandService.executeCommand(DeleteRangeMutation.id, deleteRangeMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);
+ },
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+ // all subsequent mutations should succeed inorder to make the whole process succeed
+ // Promise.all([]).then(() => true),
+};
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 0d4cf95280..39c48cd696 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,31 +1,125 @@
-import { CommandType, ICommand } from '@univerjs/core';
+import { CommandType, ICellData, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService, Nullable, ObjectMatrixPrimitiveType } from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
+import { IInsertColMutationParams, IInsertRowMutationParams, IRemoveColMutationParams, IRemoveRowMutationParams } from '../../Basics/Interfaces/MutationInterface';
+import { InsertColMutation, InsertColMutationFactory, InsertRowMutation, InsertRowMutationFactory } from '../Mutations/insert-row-col.mutation';
+import { RemoveColMutation, RemoveRowMutation } from '../Mutations/remove-row-col.mutation';
+import { ISelectionManager } from '../../Services/tokens';
export interface InsertRowCommandParams {
- worksheetId: string;
workbookId: string;
- fromIndex?: number;
- count?: number;
+ worksheetId: string;
+ rowIndex: number;
+ rowCount: number;
+ insertRowData: Nullable<ObjectMatrixPrimitiveType<ICellData>>;
}
-/**
- * The command to insert a row into a worksheet.
- */
export const InsertRowCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.insert-row',
+ handler: async (accessor: IAccessor, params?: InsertRowCommandParams) => {
+ const selectionManager = accessor.get(ISelectionManager);
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const currentUniverService = accessor.get(ICurrentUniverService);
- handler: async (accessor: IAccessor, params: InsertRowCommandParams) => {
- // all subsequent mutations should succeed inorder to make the whole process succeed
- return Promise.all([]).then(() => true);
+ let redoMutationParams: IInsertRowMutationParams;
+ if (params == null) {
+ const selections = selectionManager.getCurrentSelections();
+ const workbook = currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
+ if (!selections.length) {
+ return false;
+ }
+ const range = selections[0];
+ redoMutationParams = {
+ workbookId: workbook.getUnitId(),
+ worksheetId: workbook.getActiveSheet().getSheetId(),
+ rowIndex: range.startRow,
+ rowCount: 1,
+ insertRowData: null,
+ };
+ } else {
+ redoMutationParams = {
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ rowIndex: params.rowIndex,
+ rowCount: params.rowCount,
+ insertRowData: params.insertRowData,
+ };
+ }
+ const undoMutationParams: IRemoveRowMutationParams = InsertRowMutationFactory(accessor, redoMutationParams);
+ const result = commandService.executeCommand(InsertRowMutation.id, redoMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: 'sheet',
+ undo() {
+ return commandService.executeCommand(RemoveRowMutation.id, undoMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(InsertRowMutation.id, redoMutationParams);
+ },
+ });
+ return true;
+ }
+ return true;
},
};
-export const InsertColCommand: ICommand = {
+export interface InsertColCommandParams {
+ colIndex: number;
+ colCount: number;
+ workbookId: string;
+ worksheetId: string;
+ insertColData: ObjectMatrixPrimitiveType<ICellData>;
+}
+
+export const InsertColCommand: ICommand<InsertColCommandParams> = {
type: CommandType.COMMAND,
id: 'sheet.command.insert-col',
+ handler: async (accessor: IAccessor, params?: InsertColCommandParams) => {
+ const selectionManager = accessor.get(ISelectionManager);
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const currentUniverService = accessor.get(ICurrentUniverService);
- handler: async (accessor, params) => {
+ let redoMutationParams: IInsertColMutationParams;
+ if (params == null) {
+ const selections = selectionManager.getCurrentSelections();
+ const workbook = currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
+ if (!selections.length) {
+ return false;
+ }
+ const range = selections[0];
+ redoMutationParams = {
+ workbookId: workbook.getUnitId(),
+ worksheetId: workbook.getActiveSheet().getSheetId(),
+ colIndex: range.startColumn,
+ colCount: 1,
+ insertColData: null,
+ };
+ } else {
+ redoMutationParams = {
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ colIndex: params.colIndex,
+ colCount: params.colCount,
+ insertColData: params.insertColData,
+ };
+ }
+ const undoMutationParams: IRemoveColMutationParams = InsertColMutationFactory(accessor, redoMutationParams);
+ const result = commandService.executeCommand(InsertRowMutation.id, redoMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: 'sheet',
+ undo() {
+ return commandService.executeCommand(RemoveColMutation.id, undoMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(InsertColMutation.id, redoMutationParams);
+ },
+ });
+
+ return true;
+ }
return true;
},
-};
\ No newline at end of file
+};
diff --git a/packages/base-sheets/src/Commands/Commands/insert-sheet.command.ts b/packages/base-sheets/src/Commands/Commands/insert-sheet.command.ts
new file mode 100644
index 0000000000..81ca0c3fdc
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/insert-sheet.command.ts
@@ -0,0 +1,51 @@
+import { CommandType, ICommand, ICommandService, IUndoRedoService, IWorksheetConfig } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+
+import { InsertSheetMutation, InsertSheetUndoMutationFactory } from '../Mutations/insert-sheet.mutation';
+import { RemoveSheetMutation } from '../Mutations/remove-sheet.mutation';
+import { IInsertSheetMutationParams, IRemoveSheetMutationParams } from '../../Basics/Interfaces/MutationInterface';
+
+export interface InsertSheetCommandParams {
+ workbookId: string;
+ index: number;
+ sheet: IWorksheetConfig;
+}
+
+/**
+ * The command to insert new worksheet
+ */
+export const InsertSheetCommand: ICommand = {
+ id: 'sheet.command.insert-sheet',
+ type: CommandType.COMMAND,
+ handler: async (accessor: IAccessor, params: InsertSheetCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const { index, sheet, workbookId } = params;
+ // prepare do mutations
+ const insertSheetMutationParams: IInsertSheetMutationParams = {
+ index,
+ sheet,
+ workbookId,
+ };
+ const removeSheetMutationParams: IRemoveSheetMutationParams = InsertSheetUndoMutationFactory(accessor, insertSheetMutationParams);
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const result = commandService.executeCommand(InsertSheetMutation.id, insertSheetMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: 'sheet',
+ undo() {
+ return commandService.executeCommand(RemoveSheetMutation.id, removeSheetMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(InsertSheetMutation.id, insertSheetMutationParams);
+ },
+ });
+
+ 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
new file mode 100644
index 0000000000..a6561f355b
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/remove-row-col.command.ts
@@ -0,0 +1,120 @@
+import { CommandType, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { IInsertRowMutationParams, IRemoveColMutationParams, IRemoveRowMutationParams } from '../../Basics/Interfaces/MutationInterface';
+import { InsertColMutation, InsertRowMutation } from '../Mutations/insert-row-col.mutation';
+import { IRemoveColMutationFactory, RemoveRowMutationFactory, RemoveColMutation, RemoveRowMutation } from '../Mutations/remove-row-col.mutation';
+import { ISelectionManager } from '../../Services/tokens';
+
+export interface RemoveRowCommandParams {
+ rowIndex: number;
+ rowCount: number;
+ workbookId: string;
+ worksheetId: string;
+}
+
+export const RemoveRowCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.remove-row',
+ handler: async (accessor: IAccessor, params?: RemoveRowCommandParams) => {
+ const selectionManager = accessor.get(ISelectionManager);
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const currentUniverService = accessor.get(ICurrentUniverService);
+
+ let redoMutationParams: IRemoveRowMutationParams;
+ if (params == null) {
+ const selections = selectionManager.getCurrentSelections();
+ const workbook = currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
+ if (!selections.length) {
+ return false;
+ }
+ const range = selections[0];
+ redoMutationParams = {
+ workbookId: workbook.getUnitId(),
+ worksheetId: workbook.getActiveSheet().getSheetId(),
+ rowIndex: range.startRow,
+ rowCount: range.endRow - range.startRow,
+ };
+ } else {
+ redoMutationParams = {
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ rowIndex: params.rowIndex,
+ rowCount: params.rowCount,
+ };
+ }
+
+ const undoMutationParams: IInsertRowMutationParams = RemoveRowMutationFactory(accessor, redoMutationParams);
+ const result = commandService.executeCommand(RemoveRowMutation.id, redoMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: 'sheet',
+ undo() {
+ return commandService.executeCommand(InsertRowMutation.id, undoMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(RemoveRowMutation.id, redoMutationParams);
+ },
+ });
+ return true;
+ }
+ return true;
+ },
+};
+
+export interface RemoveColCommandParams {
+ colIndex: number;
+ colCount: number;
+ workbookId: string;
+ worksheetId: string;
+}
+
+export const RemoveColCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.remove-col',
+ handler: async (accessor: IAccessor, params?: RemoveColCommandParams) => {
+ const selectionManager = accessor.get(ISelectionManager);
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const currentUniverService = accessor.get(ICurrentUniverService);
+
+ let redoMutationParams: IRemoveColMutationParams;
+ if (params == null) {
+ const selections = selectionManager.getCurrentSelections();
+ const workbook = currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
+ if (!selections.length) {
+ return false;
+ }
+ const range = selections[0];
+ redoMutationParams = {
+ workbookId: workbook.getUnitId(),
+ worksheetId: workbook.getActiveSheet().getSheetId(),
+ colIndex: range.startColumn,
+ colCount: range.endColumn - range.startColumn,
+ };
+ } else {
+ redoMutationParams = {
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ colIndex: params.colIndex,
+ colCount: params.colCount,
+ };
+ }
+ const undoMutationParams: IRemoveColMutationParams = IRemoveColMutationFactory(accessor, redoMutationParams);
+ const result = commandService.executeCommand(RemoveColMutation.id, redoMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: 'sheet',
+ undo() {
+ return commandService.executeCommand(InsertColMutation.id, undoMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(RemoveColMutation.id, redoMutationParams);
+ },
+ });
+
+ return true;
+ }
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Commands/remove-sheet.command.ts b/packages/base-sheets/src/Commands/Commands/remove-sheet.command.ts
new file mode 100644
index 0000000000..5ddfbe8c99
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/remove-sheet.command.ts
@@ -0,0 +1,49 @@
+import { CommandType, ICommand, ICommandService, IUndoRedoService } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+
+import { RemoveSheetMutation, RemoveSheetUndoMutationFactory } from '../Mutations/remove-sheet.mutation';
+import { InsertSheetMutation } from '../Mutations/insert-sheet.mutation';
+import { IInsertSheetMutationParams, IRemoveSheetMutationParams } from '../../Basics/Interfaces/MutationInterface';
+
+export interface RemoveSheetCommandParams {
+ workbookId: string;
+ worksheetId: string;
+}
+
+/**
+ * The command to insert new worksheet
+ */
+export const RemoveSheetCommand: ICommand = {
+ id: 'sheet.command.remove-sheet',
+ type: CommandType.COMMAND,
+ handler: async (accessor: IAccessor, params: RemoveSheetCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const { worksheetId, workbookId } = params;
+ // prepare do mutations
+ const RemoveSheetMutationParams: IRemoveSheetMutationParams = {
+ worksheetId,
+ workbookId,
+ };
+ const InsertSheetMutationParams: IInsertSheetMutationParams = RemoveSheetUndoMutationFactory(accessor, RemoveSheetMutationParams);
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const result = commandService.executeCommand(RemoveSheetMutation.id, RemoveSheetMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: 'sheet',
+ undo() {
+ return commandService.executeCommand(InsertSheetMutation.id, InsertSheetMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(RemoveSheetMutation.id, RemoveSheetMutationParams);
+ },
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Commands/remove-worksheet-merge.command.ts b/packages/base-sheets/src/Commands/Commands/remove-worksheet-merge.command.ts
new file mode 100644
index 0000000000..95f2c35fc6
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/remove-worksheet-merge.command.ts
@@ -0,0 +1,67 @@
+import { CommandType, ICommand, ICommandService, ICurrentUniverService, IRangeData, IUndoRedoService } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { IRemoveWorksheetMergeMutationParams } from '../../Basics/Interfaces/MutationInterface';
+import { AddWorksheetMergeMutation } from '../Mutations/add-worksheet-merge.mutation';
+import { RemoveWorksheetMergeMutation, RemoveWorksheetMergeMutationFactory } from '../Mutations/remove-worksheet-merge.mutation';
+import { ISelectionManager } from '../../Services/tokens';
+
+export interface IRemoveWorksheetMergeCommandParams {
+ workbookId: string;
+ worksheetId: string;
+ rectangles: IRangeData[];
+}
+
+export const RemoveWorksheetMergeCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.remove-worksheet-merge',
+ handler: async (accessor: IAccessor, params?: IRemoveWorksheetMergeCommandParams) => {
+ const selectionManager = accessor.get(ISelectionManager);
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const currentUniverService = accessor.get(ICurrentUniverService);
+
+ let redoMutationParams: IRemoveWorksheetMergeMutationParams;
+ if (params == null) {
+ const selections = selectionManager.getCurrentSelections();
+ const workbook = currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
+ if (!selections.length) {
+ return false;
+ }
+ const range = selections[0];
+ redoMutationParams = {
+ workbookId: workbook.getUnitId(),
+ worksheetId: workbook.getActiveSheet().getSheetId(),
+ rectangles: [
+ {
+ startRow: range.startRow,
+ startColumn: range.startColumn,
+ endRow: range.endRow,
+ endColumn: range.endColumn,
+ },
+ ],
+ };
+ } else {
+ redoMutationParams = {
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ rectangles: params.rectangles,
+ };
+ }
+
+ const undoMutationParams: IRemoveWorksheetMergeMutationParams = RemoveWorksheetMergeMutationFactory(accessor, redoMutationParams);
+ const result = commandService.executeCommand(RemoveWorksheetMergeMutation.id, redoMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: 'sheet',
+ undo() {
+ return commandService.executeCommand(AddWorksheetMergeMutation.id, undoMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(RemoveWorksheetMergeMutation.id, redoMutationParams);
+ },
+ });
+ return true;
+ }
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Commands/set-border-command.ts b/packages/base-sheets/src/Commands/Commands/set-border-command.ts
new file mode 100644
index 0000000000..2c542375ee
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/set-border-command.ts
@@ -0,0 +1,315 @@
+import {
+ BorderStyleTypes,
+ CommandType,
+ IBorderStyleData,
+ ICommand,
+ ICommandService,
+ IRangeData,
+ IStyleData,
+ IUndoRedoService,
+ Nullable,
+ ObjectMatrix,
+ Tools,
+} from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+
+import { ISetRangeValuesMutationParams, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../Mutations/set-range-values.mutation';
+
+export interface ISetBorderCommandParams {
+ workbookId: string;
+ worksheetId: string;
+ range: IRangeData;
+ top: Nullable<boolean>;
+ left: Nullable<boolean>;
+ bottom: Nullable<boolean>;
+ right: Nullable<boolean>;
+ vertical: Nullable<boolean>;
+ horizontal: Nullable<boolean>;
+ color?: string;
+ style?: BorderStyleTypes;
+}
+
+function forEach(rangeData: IRangeData, action: (row: number, column: number) => void): void {
+ const { startRow, startColumn, endRow, endColumn } = rangeData;
+ for (let i = startRow; i <= endRow; i++) {
+ for (let j = startColumn; j <= endColumn; j++) {
+ action(i, j);
+ }
+ }
+}
+
+/**
+ * The command to clear content in current selected ranges.
+ */
+export const SetBorderCommand: ICommand = {
+ id: 'sheet.command.set-border',
+ type: CommandType.COMMAND,
+ // eslint-disable-next-line max-lines-per-function
+ handler: async (accessor: IAccessor, params: ISetBorderCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const { top, left, bottom, right, vertical, horizontal, color = 'black', style = BorderStyleTypes.DASH_DOT, workbookId, worksheetId, range } = params;
+ const rangeData = range;
+
+ // Cells in the surrounding range may need to clear the border
+ const topRangeOut = {
+ startRow: rangeData.startRow - 1,
+ startColumn: rangeData.startColumn,
+ endRow: rangeData.startRow - 1,
+ endColumn: rangeData.endColumn,
+ };
+
+ const leftRangeOut = {
+ startRow: rangeData.startRow,
+ startColumn: rangeData.startColumn - 1,
+ endRow: rangeData.endRow,
+ endColumn: rangeData.startColumn - 1,
+ };
+
+ const bottomRangeOut = {
+ startRow: rangeData.endRow + 1,
+ startColumn: rangeData.startColumn,
+ endRow: rangeData.endRow + 1,
+ endColumn: rangeData.endColumn,
+ };
+
+ const rightRangeOut = {
+ startRow: rangeData.startRow,
+ startColumn: rangeData.endColumn + 1,
+ endRow: rangeData.endRow,
+ endColumn: rangeData.endColumn + 1,
+ };
+
+ // Cells in the upper, lower, left and right ranges
+ const topRange = {
+ startRow: rangeData.startRow,
+ startColumn: rangeData.startColumn,
+ endRow: rangeData.startRow,
+ endColumn: rangeData.endColumn,
+ };
+
+ const leftRange = {
+ startRow: rangeData.startRow,
+ startColumn: rangeData.startColumn,
+ endRow: rangeData.endRow,
+ endColumn: rangeData.startColumn,
+ };
+
+ const bottomRange = {
+ startRow: rangeData.endRow,
+ startColumn: rangeData.startColumn,
+ endRow: rangeData.endRow,
+ endColumn: rangeData.endColumn,
+ };
+
+ const rightRange = {
+ startRow: rangeData.startRow,
+ startColumn: rangeData.endColumn,
+ endRow: rangeData.endRow,
+ endColumn: rangeData.endColumn,
+ };
+
+ const mtr = new ObjectMatrix<IStyleData>();
+ const mlr = new ObjectMatrix<IStyleData>();
+ const mbr = new ObjectMatrix<IStyleData>();
+ const mrr = new ObjectMatrix<IStyleData>();
+ const mcr = new ObjectMatrix<IStyleData>();
+
+ const border: IBorderStyleData = {
+ s: style,
+ cl: {
+ rgb: color,
+ },
+ };
+
+ if (top === true || top === false) {
+ // Probably to the border, there are no surrounding cells
+ // Clear the bottom border of the top range
+ forEach(topRangeOut, (row, column) => {
+ mtr.setValue(row, column, { bd: { b: null } });
+ });
+
+ // first row
+ forEach(topRange, (row, column) => {
+ // update
+ if (top === true) {
+ const style = Tools.deepMerge(mcr.getValue(row, column) || {}, {
+ bd: { t: Tools.deepClone(border) },
+ });
+ mcr.setValue(row, column, style);
+ }
+ // delete
+ else if (top === false) {
+ const style = Tools.deepMerge(mcr.getValue(row, column) || {}, {
+ bd: { t: null },
+ });
+ mcr.setValue(row, column, style);
+ }
+ });
+ }
+ if (bottom === true || bottom === false) {
+ // Probably to the border, there are no surrounding cells
+ // Clear the top border of the lower range
+ forEach(bottomRangeOut, (row, column) => {
+ mbr.setValue(row, column, { bd: { t: null } });
+ });
+
+ // the last row
+ forEach(bottomRange, (row, column) => {
+ // update
+ if (bottom === true) {
+ const style = Tools.deepMerge(mcr.getValue(row, column) || {}, {
+ bd: { b: Tools.deepClone(border) },
+ });
+ mcr.setValue(row, column, style);
+ }
+ // delete
+ else if (bottom === false) {
+ const style = Tools.deepMerge(mcr.getValue(row, column) || {}, {
+ bd: { b: null },
+ });
+ mcr.setValue(row, column, style);
+ }
+ });
+ }
+ if (left === true || left === false) {
+ // Probably to the border, there are no surrounding cells
+ // Clear the right border of the left range
+ forEach(leftRangeOut, (row, column) => {
+ mlr.setValue(row, column, { bd: { r: null } });
+ });
+
+ // first column
+ forEach(leftRange, (row, column) => {
+ // update
+ if (left === true) {
+ const style = Tools.deepMerge(mcr.getValue(row, column) || {}, {
+ bd: { l: Tools.deepClone(border) },
+ });
+ mcr.setValue(row, column, style);
+ }
+ // delete
+ else if (left === false) {
+ const style = Tools.deepMerge(mcr.getValue(row, column) || {}, {
+ bd: { l: null },
+ });
+ mcr.setValue(row, column, style);
+ }
+ });
+ }
+ if (right === true || right === false) {
+ // Probably to the border, there are no surrounding cells
+ // Clear the left border of the right range
+ forEach(rightRangeOut, (row, column) => {
+ mrr.setValue(row, column, { bd: { l: null } });
+ });
+
+ // last column
+ forEach(rightRange, (row, column) => {
+ // update
+ if (right === true) {
+ const style = Tools.deepMerge(mcr.getValue(row, column) || {}, {
+ bd: { r: Tools.deepClone(border) },
+ });
+ mcr.setValue(row, column, style);
+ }
+ // delete
+ else if (right === false) {
+ const style = Tools.deepMerge(mcr.getValue(row, column) || {}, {
+ bd: { r: null },
+ });
+ mcr.setValue(row, column, style);
+ }
+ });
+ }
+
+ // inner vertical border
+ if (vertical === true || vertical === false) {
+ // current range
+ forEach(rangeData, (row, column) => {
+ // Set the right border except the last column
+ if (column !== rangeData.endColumn) {
+ // update
+ if (vertical === true) {
+ const style = Tools.deepMerge(mcr.getValue(row, column) || {}, {
+ bd: { r: Tools.deepClone(border) },
+ });
+ mcr.setValue(row, column, style);
+ }
+ // delete
+ else if (vertical === false) {
+ const style = Tools.deepMerge(mcr.getValue(row, column) || {}, {
+ bd: { r: null },
+ });
+ mcr.setValue(row, column, style);
+ }
+ }
+
+ // Except for the first column, clear the left border
+ if (column !== rangeData.startColumn) {
+ const style = Tools.deepMerge(mcr.getValue(row, column) || {}, {
+ bd: { l: null },
+ });
+ mcr.setValue(row, column, style);
+ }
+ });
+ }
+ // inner horizontal border
+ if (horizontal === true || horizontal === false) {
+ // current range
+ forEach(rangeData, (row, column) => {
+ // Except for the last row, set the bottom border
+ if (row !== rangeData.endRow) {
+ // update
+ if (horizontal === true) {
+ const style = Tools.deepMerge(mcr.getValue(row, column) || {}, {
+ bd: { b: Tools.deepClone(border) },
+ });
+ mcr.setValue(row, column, style);
+ }
+ // delete
+ else if (horizontal === false) {
+ const style = Tools.deepMerge(mcr.getValue(row, column) || {}, {
+ bd: { b: null },
+ });
+ mcr.setValue(row, column, style);
+ }
+ }
+
+ // Except for the first row, clear the top border
+ if (row !== rangeData.startRow) {
+ const style = Tools.deepMerge(mcr.getValue(row, column) || {}, {
+ bd: { t: null },
+ });
+ mcr.setValue(row, column, style);
+ }
+ });
+ }
+
+ const clearMutationParams: ISetRangeValuesMutationParams = {
+ rangeData: range,
+ worksheetId: worksheet.getSheetId(),
+ };
+ const undoClearMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(accessor, clearMutationParams);
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const result = commandService.executeCommand(SetRangeValuesMutation.id, clearMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ // 如果有多个 mutation 构成一个封装项目,那么要封装在同一个 undo redo element 里面
+ // 通过勾子可以 hook 外部 controller 的代码来增加新的 action
+ URI: 'sheet', // TODO: this URI is fake
+ undo() {
+ return commandService.executeCommand(SetRangeValuesMutation.id, undoClearMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(SetRangeValuesMutation.id, clearMutationParams);
+ },
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Commands/set-range-formatted-value.command.ts b/packages/base-sheets/src/Commands/Commands/set-range-formatted-value.command.ts
new file mode 100644
index 0000000000..19e6ebb4ae
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/set-range-formatted-value.command.ts
@@ -0,0 +1,80 @@
+import { IAccessor } from '@wendellhu/redi';
+import { CommandType, ICellV, ICommand, ICommandService, IRangeData, IUndoRedoService, ObjectMatrix, Tools } from '@univerjs/core';
+
+import { ISetRangeFormattedValueMutationParams, SetRangeFormattedValueMutation, SetRangeFormattedValueUndoMutationFactory } from '../Mutations/set-range-formatted-value.mutation';
+
+export interface ISetRangeFormattedValueParams {
+ range: IRangeData[];
+ value: ICellV | ICellV[][] | ObjectMatrix<ICellV>;
+ workbookId: string;
+ worksheetId: string;
+}
+
+/**
+ * The command to set range formatted value.
+ */
+export const SetRangeFormattedValueCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-range-formatted-value',
+
+ handler: async (accessor: IAccessor, params: ISetRangeFormattedValueParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ let cellValue = new ObjectMatrix<ICellV>();
+ const value = params.value;
+ for (let i = 0; i < params.range.length; i++) {
+ const rangeData = params.range[i];
+ const { startRow, startColumn, endRow, endColumn } = rangeData;
+ 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 (Tools.isAssignableFrom(value, ObjectMatrix)) {
+ cellValue = value;
+ } else {
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ cellValue.setValue(r, c, value as ICellV);
+ }
+ }
+ }
+ }
+
+ const setRangeFormattedValueMutationParams: ISetRangeFormattedValueMutationParams = {
+ range: params.range,
+ worksheetId: params.worksheetId,
+ workbookId: params.workbookId,
+ value: cellValue.getData(),
+ };
+
+ const undoSetRangeFormattedValueMutationParams: ISetRangeFormattedValueMutationParams = SetRangeFormattedValueUndoMutationFactory(
+ accessor,
+ setRangeFormattedValueMutationParams
+ );
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const result = commandService.executeCommand(SetRangeFormattedValueMutation.id, setRangeFormattedValueMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ // 如果有多个 mutation 构成一个封装项目,那么要封装在同一个 undo redo element 里面
+ // 通过勾子可以 hook 外部 controller 的代码来增加新的 action
+ URI: 'sheet', // TODO: this URI is fake
+ undo() {
+ return commandService.executeCommand(SetRangeFormattedValueMutation.id, undoSetRangeFormattedValueMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(SetRangeFormattedValueMutation.id, setRangeFormattedValueMutationParams);
+ },
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+ // all subsequent mutations should succeed inorder to make the whole process succeed
+ // Promise.all([]).then(() => true),
+};
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
new file mode 100644
index 0000000000..b5e3b6ba02
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/set-range-values.command.ts
@@ -0,0 +1,66 @@
+import { CommandType, ICellData, ICommand, ICommandService, IRangeData, IUndoRedoService, ObjectMatrix, ObjectMatrixPrimitiveType, Tools } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { ISetRangeValuesMutationParams, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../Mutations/set-range-values.mutation';
+
+export interface ISetRangeValuesCommandParams {
+ worksheetId: string;
+ workbookId: string;
+ range: IRangeData;
+ value: ICellData | ICellData[][] | ObjectMatrixPrimitiveType<ICellData>;
+}
+
+/**
+ * The command to set values for ranges.
+ */
+export const SetRangeValuesCommand: ICommand = {
+ id: 'sheet.command.set-range-values',
+ type: CommandType.COMMAND,
+ handler: async (accessor: IAccessor, params: ISetRangeValuesCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const { range, value, workbookId, worksheetId } = params;
+ const { startRow, startColumn, endRow, endColumn } = range;
+ let cellValue = new ObjectMatrix<ICellData>();
+
+ 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 (Tools.isObject(value)) {
+ cellValue = value as ObjectMatrix<ICellData>;
+ } else {
+ cellValue.setValue(startRow, startColumn, value);
+ }
+
+ const setRangeValuesMutationParams: ISetRangeValuesMutationParams = {
+ rangeData: range,
+ worksheetId,
+ workbookId,
+ cellValue: cellValue as any,
+ };
+ const undoSetRangeValuesMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(accessor, setRangeValuesMutationParams);
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const result = commandService.executeCommand(SetRangeValuesMutation.id, setRangeValuesMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ // 如果有多个 mutation 构成一个封装项目,那么要封装在同一个 undo redo element 里面
+ // 通过勾子可以 hook 外部 controller 的代码来增加新的 action
+ URI: 'sheet', // TODO: this URI is fake
+ undo() {
+ return commandService.executeCommand(SetRangeValuesMutation.id, undoSetRangeValuesMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(SetRangeValuesMutation.id, setRangeValuesMutationParams);
+ },
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Commands/set-selections.command.ts b/packages/base-sheets/src/Commands/Commands/set-selections.command.ts
new file mode 100644
index 0000000000..27d075d625
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/set-selections.command.ts
@@ -0,0 +1,75 @@
+import { SetSelectionsOperation } from '@Commands/Operations/selection.operation';
+import { CommandType, Direction, ICommand, ICommandService, ICurrentUniverService, IRangeData } from '@univerjs/core';
+
+import { ISelectionManager } from '../../Services/tokens';
+
+export interface IChangeSelectionCommandParams {
+ direction: Direction;
+ toEnd?: boolean;
+}
+
+export const ChangeSelectionCommand: ICommand<IChangeSelectionCommandParams> = {
+ id: 'sheet.command.change-selection',
+ type: CommandType.COMMAND,
+ handler: async (accessor, params) => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const currentWorksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+ const selectionManager = accessor.get(ISelectionManager);
+ const commandService = accessor.get(ICommandService);
+
+ const selections = selectionManager.getCurrentSelections();
+ if (!selections.length) {
+ return false;
+ }
+
+ const { direction } = params;
+ const originSelection = selections[selections.length - 1];
+ const destRange: IRangeData = { ...originSelection };
+
+ // FIXME: some error here. The selection does not know if there is a span cell.
+ switch (direction) {
+ case Direction.UP:
+ destRange.startRow = Math.max(0, originSelection.startRow - 1);
+ destRange.endRow = destRange.startRow;
+ break;
+ case Direction.DOWN:
+ destRange.startRow = Math.min(originSelection.endRow + 1, currentWorksheet.getRowCount() - 1);
+ destRange.endRow = destRange.startRow;
+ break;
+ case Direction.LEFT:
+ destRange.startColumn = Math.max(0, originSelection.startColumn - 1);
+ destRange.endColumn = destRange.startColumn;
+ break;
+ case Direction.RIGHT:
+ destRange.startColumn = Math.min(originSelection.endColumn + 1, currentWorksheet.getColumnCount() - 1);
+ destRange.endColumn = destRange.startColumn;
+ break;
+ default:
+ break;
+ }
+
+ // TODO: deal with `toEnd` parameter here
+
+ commandService.executeCommand(SetSelectionsOperation.id, {
+ sheetId: currentWorksheet.getSheetId(),
+ selections: [
+ {
+ selection: destRange,
+ },
+ ],
+ });
+
+ return true;
+ },
+};
+
+export interface IExpandSelectionCommandParams {
+ direction: Direction;
+ toEnd?: boolean;
+}
+
+export const ExpandSelectionCommand: ICommand<IExpandSelectionCommandParams> = {
+ id: 'sheet.command.expand-selection',
+ type: CommandType.COMMAND,
+ handler: async (accessor, params) => true,
+};
\ No newline at end of file
diff --git a/packages/base-sheets/src/Commands/Commands/set-style.command.ts b/packages/base-sheets/src/Commands/Commands/set-style.command.ts
index 77f341c51f..5a8529a375 100644
--- a/packages/base-sheets/src/Commands/Commands/set-style.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/set-style.command.ts
@@ -1,43 +1,421 @@
import { IAccessor } from '@wendellhu/redi';
-import { CommandType, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService } from '@univerjs/core';
+import {
+ BooleanNumber,
+ CommandType,
+ FontItalic,
+ FontWeight,
+ HorizontalAlign,
+ IBorderData,
+ IColorStyle,
+ ICommand,
+ ICommandService,
+ ICurrentUniverService,
+ IRangeData,
+ IStyleData,
+ ITextRotation,
+ IUndoRedoService,
+ ObjectMatrix,
+ ObjectMatrixPrimitiveType,
+ Tools,
+ VerticalAlign,
+ WrapStrategy,
+} from '@univerjs/core';
+import { ISetRangeStyleMutationParams, SetRangeStyleMutation, SetRangeStyleUndoMutationFactory } from '../Mutations/set-range-styles.mutation';
import { ISelectionManager } from '../../Services/tokens';
-import { SelectionController } from '../../Controller/Selection/SelectionController';
-import { SelectionModel } from '../../Model/SelectionModel';
-export interface ISetFontFamilyParams {
- fontFamily: string;
+export interface IStyleTypeValue<T> {
+ type: keyof IStyleData;
+ value: T | T[][];
}
+export interface ISetStyleParams<T> {
+ style: IStyleTypeValue<T>;
+
+ ranges?: IRangeData[];
+ workbookId?: string;
+ worksheetId?: string;
+}
+
+// TODO: @wzhudev: move parameters logic from BasicWorksheetController to here. 30th Aug.
+
/**
- * Set new font family for currently selected cells
+ * The command to set cell style.
+ * Set style to a bunch of ranges.
*/
-export const SetFontFamilyCommand: ICommand<ISetFontFamilyParams> = {
- id: 'sheet.command.set-font-family',
+export const SetStyleCommand: ICommand = {
type: CommandType.COMMAND,
- handler: async (accessor: IAccessor) => {
- const currentUniverService = accessor.get(ICurrentUniverService);
+ id: 'sheet.command.set-style',
+
+ handler: async <T>(accessor: IAccessor, params: ISetStyleParams<T>) => {
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.gett(ISelectionManager);
const undoRedoService = accessor.get(IUndoRedoService);
+ const selectionManager = accessor.get(ISelectionManager);
+ const currentUniverService = accessor.get(ICurrentUniverService);
+
+ const ranges = params.ranges || selectionManager.getCurrentSelections();
+ if (!ranges) {
+ return false;
+ }
+
+ const workbookId = params.workbookId || currentUniverService.getCurrentUniverSheetInstance().getUnitId();
+ const worksheetId = params.worksheetId || currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
+ const style = params.style;
+
+ let value: ObjectMatrixPrimitiveType<IStyleData>;
+ for (let i = 0; i < ranges.length; i++) {
+ const { startRow, endRow, startColumn, endColumn } = ranges[i];
+ if (Tools.isArray(style.value)) {
+ const matrix = new ObjectMatrix<IStyleData>();
+ for (let r = 0; r < endRow - startRow + 1; r++) {
+ for (let c = 0; c < endColumn - startColumn + 1; c++) {
+ matrix.setValue(r, c, {
+ [style.type]: style.value[r][c],
+ });
+ }
+ }
+ value = matrix.getData();
+ } else {
+ const colorObj: IStyleData = {
+ [style.type]: style.value,
+ };
+ value = Tools.fillObjectMatrix(endRow - startRow + 1, endColumn - startColumn + 1, colorObj);
+ }
+ }
+
+ const setRangeStyleMutationParams: ISetRangeStyleMutationParams = {
+ range: ranges,
+ worksheetId,
+ workbookId,
+ value: value!,
+ };
+
+ const undoSetRangeStyleMutationParams: ISetRangeStyleMutationParams = SetRangeStyleUndoMutationFactory(accessor, setRangeStyleMutationParams);
+
+ const result = commandService.executeCommand(SetRangeStyleMutation.id, setRangeStyleMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: 'sheet', // TODO: this URI is fake: would be replace with Univer business instance id
+ undo() {
+ return commandService.executeCommand(SetRangeStyleMutation.id, undoSetRangeStyleMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(SetRangeStyleMutation.id, setRangeStyleMutationParams);
+ },
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+};
+
+/**
+ * Set bold font style to currently selected ranges. If the cell is already bold then it will cancel the bold style.
+ */
+export const SetBoldCommand: ICommand = {
+ // TODO@wzhudev: toggle bold command?
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-bold',
+ handler: async (accessor, params) => {
+ const commandService = accessor.get(ICommandService);
+ const selectionManager = accessor.get(ISelectionManager);
+ const currentlyBold = selectionManager.getCurrentCell()?.getFontWeight() === FontWeight.BOLD;
+
+ const setStyleParams: ISetStyleParams<BooleanNumber> = {
+ style: {
+ type: 'bl',
+ value: currentlyBold ? BooleanNumber.FALSE : BooleanNumber.TRUE,
+ },
+ };
+
+ return commandService.executeCommand(SetStyleCommand.id, setStyleParams);
+ },
+};
+
+/**
+ * Set italic font style to currently selected ranges. If the cell is already italic then it will cancel the italic style.
+ */
+export const SetItalicCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-italic',
+ handler: async (accessor, params) => {
+ const commandService = accessor.get(ICommandService);
+ const selectionManager = accessor.get(ISelectionManager);
+ const currentlyItalic = selectionManager.getCurrentCell()?.getFontStyle() === FontItalic.ITALIC;
+
+ const setStyleParams: ISetStyleParams<BooleanNumber> = {
+ style: {
+ type: 'it',
+ value: currentlyItalic ? BooleanNumber.FALSE : BooleanNumber.TRUE,
+ },
+ };
- const workbook = currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
- const worksheet = workbook.getActiveSheet();
- const controls = selectionManager.getCurrentControls();
- const selections = controls?.map((control: SelectionController) => {
- const model: SelectionModel = control.model;
- return {
- startRow: model.startRow,
- startColumn: model.startColumn,
- endRow: model.endRow,
- endColumn: model.endColumn,
- };
- });
+ return commandService.executeCommand(SetStyleCommand.id, setStyleParams);
+ },
+};
+
+/**
+ * Set underline font style to currently selected ranges. If the cell is already underline then it will cancel the underline style.
+ */
+export const SetUnderlineCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-underline',
+ handler: async (accessor, params) => {
+ const commandService = accessor.get(ICommandService);
+ const selectionManager = accessor.get(ISelectionManager);
+ const currentlyUnderline = !!selectionManager.getCurrentCell()?.getUnderline().s;
+
+ const setStyleParams: ISetStyleParams<{ s: number }> = {
+ style: {
+ type: 'ul',
+ value: {
+ s: currentlyUnderline ? BooleanNumber.FALSE : BooleanNumber.TRUE,
+ },
+ },
+ };
+
+ return commandService.executeCommand(SetStyleCommand.id, setStyleParams);
+ },
+};
+
+/**
+ * Set strike through font style to currently selected ranges. If the cell is already stroke then it will cancel the stroke style.
+ */
+export const SetStrikeThroughCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-stroke',
+ handler: async (accessor, params) => {
+ const commandService = accessor.get(ICommandService);
+ const selectionManager = accessor.get(ISelectionManager);
+ const currentlyStrokeThrough = !!selectionManager.getCurrentCell()?.getStrikeThrough().s;
+
+ const setStyleParams: ISetStyleParams<{ s: number }> = {
+ style: {
+ type: 'st',
+ value: { s: currentlyStrokeThrough ? BooleanNumber.FALSE : BooleanNumber.TRUE },
+ },
+ };
- const
+ return commandService.executeCommand(SetStyleCommand.id, setStyleParams);
+ },
+};
+
+export interface ISetFontFamilyCommandParams {
+ fontFamily: string;
+}
- // FIXME: 为什么之前有些 command 支持的多 selection 有的不支持?
+export const SetFontFamilyCommand: ICommand<ISetFontFamilyCommandParams> = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-font-family',
+ handler: async (accessor, params) => {
+ if (!params) {
+ return false;
+ }
+
+ const commandService = accessor.get(ICommandService);
+ const setStyleParams: ISetStyleParams<string> = {
+ style: {
+ type: 'ff',
+ value: params.fontFamily,
+ },
+ };
- return true;
+ return commandService.executeCommand(SetStyleCommand.id, setStyleParams);
},
};
+
+export interface ISetFontSizeCommandParams {
+ fontSize: number;
+}
+
+export const SetFontSizeCommand: ICommand<ISetFontSizeCommandParams> = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-font-family',
+ handler: async (accessor, params) => {
+ if (!params) {
+ return false;
+ }
+
+ const commandService = accessor.get(ICommandService);
+ const setStyleParams: ISetStyleParams<number> = {
+ style: {
+ type: 'fs',
+ value: params.fontSize,
+ },
+ };
+
+ return commandService.executeCommand(SetStyleCommand.id, setStyleParams);
+ },
+};
+
+export interface ISetColorCommandParams {
+ color: IColorStyle;
+}
+
+export const SetTextColorCommand: ICommand<ISetColorCommandParams> = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-font-family',
+ handler: async (accessor, params) => {
+ if (!params) {
+ return false;
+ }
+
+ const commandService = accessor.get(ICommandService);
+ const setStyleParams: ISetStyleParams<IColorStyle> = {
+ style: {
+ type: 'cl',
+ value: params.color,
+ },
+ };
+
+ return commandService.executeCommand(SetStyleCommand.id, setStyleParams);
+ },
+};
+
+export const SetBackgroundColorCommand: ICommand<ISetColorCommandParams> = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-background-color',
+ handler: async (accessor, params) => {
+ if (!params) {
+ return false;
+ }
+
+ const commandService = accessor.get(ICommandService);
+ const setStyleParams: ISetStyleParams<IColorStyle> = {
+ style: {
+ type: 'bg',
+ value: params.color,
+ },
+ };
+
+ return commandService.executeCommand(SetStyleCommand.id, setStyleParams);
+ },
+};
+
+export interface ISetCellBorderCommandParams {
+ border: IBorderData;
+}
+
+export const SetCellBorderCommand: ICommand<ISetCellBorderCommandParams> = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-cell-border',
+ handler: async (accessor, params) => {
+ if (!params) {
+ return false;
+ }
+
+ const commandService = accessor.get(ICommandService);
+ const setStyleParams: ISetStyleParams<IBorderData> = {
+ style: {
+ type: 'bd',
+ value: params.border,
+ },
+ };
+
+ return commandService.executeCommand(SetStyleCommand.id, setStyleParams);
+ },
+};
+
+export interface ISetVerticalTextAlignCommandParams {
+ align: VerticalAlign;
+}
+
+export const SetVerticalTextAlignCommand: ICommand<ISetVerticalTextAlignCommandParams> = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-vertical-text-align',
+ handler: async (accessor, params) => {
+ if (!params) {
+ return false;
+ }
+
+ const commandService = accessor.get(ICommandService);
+ const setStyleParams: ISetStyleParams<VerticalAlign> = {
+ style: {
+ type: 'vt',
+ value: params.align,
+ },
+ };
+
+ return commandService.executeCommand(SetStyleCommand.id, setStyleParams);
+ },
+};
+
+export interface ISetHorizontalTextAlignCommandParams {
+ align: HorizontalAlign;
+}
+
+export const SetHorizontalTextAlignCommand: ICommand<ISetHorizontalTextAlignCommandParams> = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-horizontal-text-align',
+ handler: async (accessor, params) => {
+ if (!params) {
+ return false;
+ }
+
+ const commandService = accessor.get(ICommandService);
+ const setStyleParams: ISetStyleParams<HorizontalAlign> = {
+ style: {
+ type: 'ht',
+ value: params.align,
+ },
+ };
+
+ return commandService.executeCommand(SetStyleCommand.id, setStyleParams);
+ },
+};
+
+export interface ISetTextWrapCommandParams {
+ wrap: WrapStrategy;
+}
+
+export const SetTextWrapCommand: ICommand<ISetTextWrapCommandParams> = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-text-wrap',
+ handler: async (accessor, params) => {
+ if (!params) {
+ return false;
+ }
+
+ const commandService = accessor.get(ICommandService);
+ const setStyleParams: ISetStyleParams<WrapStrategy> = {
+ style: {
+ type: 'tb',
+ value: params.wrap,
+ },
+ };
+
+ return commandService.executeCommand(SetStyleCommand.id, setStyleParams);
+ },
+};
+
+export interface ISetTextRotationCommandParams {
+ rotation: ITextRotation;
+}
+
+export const SetTextRotationCommand: ICommand<ISetTextRotationCommandParams> = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-text-rotation',
+ handler: async (accessor, params) => {
+ if (!params) {
+ return false;
+ }
+
+ const commandService = accessor.get(ICommandService);
+ const setStyleParams: ISetStyleParams<ITextRotation> = {
+ style: {
+ type: 'tr',
+ value: params.rotation,
+ },
+ };
+
+ return commandService.executeCommand(SetStyleCommand.id, setStyleParams);
+ },
+};
+
+export const SetSpanCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-span',
+ handler: async (accessor, params) => true,
+};
diff --git a/packages/base-sheets/src/Commands/Commands/set-worksheet-activate.command.ts b/packages/base-sheets/src/Commands/Commands/set-worksheet-activate.command.ts
new file mode 100644
index 0000000000..d1c04ac071
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/set-worksheet-activate.command.ts
@@ -0,0 +1,38 @@
+import { CommandType, ICommand, ICommandService, IUndoRedoService } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { ISetWorksheetActivateMutationParams, SetWorksheetActivateMutation, SetWorksheetActivateMutationFactory } from '../Mutations/set-worksheet-activate.mutation';
+
+export interface ISetWorksheetActivateCommandParams {
+ workbookId: string;
+ worksheetId: string;
+}
+
+export const SetWorksheetActivateCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-worksheet-activate',
+
+ handler: async (accessor: IAccessor, params: ISetWorksheetActivateCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const redoMutationParams: ISetWorksheetActivateMutationParams = {
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ };
+ const undoMutationParams = SetWorksheetActivateMutationFactory(accessor, redoMutationParams);
+ const result = commandService.executeCommand(SetWorksheetActivateMutation.id, redoMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: 'sheet',
+ undo() {
+ return commandService.executeCommand(SetWorksheetActivateMutation.id, undoMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(SetWorksheetActivateMutation.id, redoMutationParams);
+ },
+ });
+ return true;
+ }
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Commands/set-worksheet-col-width.command.ts b/packages/base-sheets/src/Commands/Commands/set-worksheet-col-width.command.ts
new file mode 100644
index 0000000000..ba18c4f04c
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/set-worksheet-col-width.command.ts
@@ -0,0 +1,42 @@
+import { CommandType, ICommand, ICommandService, IUndoRedoService } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { ISetWorksheetColWidthMutationParams, SetWorksheetColWidthMutation, SetWorksheetColWidthMutationFactory } from '../Mutations/set-worksheet-col-width.mutation';
+
+export interface SetWorksheetColWidthCommandParams {
+ workbookId: string;
+ worksheetId: string;
+ colIndex: number;
+ colWidth: number[];
+}
+
+export const SetWorksheetColWidthCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-worksheet-col-width',
+ handler: async (accessor: IAccessor, params: SetWorksheetColWidthCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const redoMutationParams: ISetWorksheetColWidthMutationParams = {
+ worksheetId: params.worksheetId,
+ workbookId: params.workbookId,
+ colIndex: params.colIndex,
+ colWidth: params.colWidth,
+ };
+ const undoMutationParams: ISetWorksheetColWidthMutationParams = SetWorksheetColWidthMutationFactory(accessor, redoMutationParams);
+ const result = commandService.executeCommand(SetWorksheetColWidthMutation.id, redoMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: 'sheet',
+ undo() {
+ return commandService.executeCommand(SetWorksheetColWidthMutation.id, undoMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(SetWorksheetColWidthMutation.id, redoMutationParams);
+ },
+ });
+
+ return true;
+ }
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Commands/set-worksheet-hide.command.ts b/packages/base-sheets/src/Commands/Commands/set-worksheet-hide.command.ts
new file mode 100644
index 0000000000..ce2ca45733
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/set-worksheet-hide.command.ts
@@ -0,0 +1,42 @@
+import { BooleanNumber, CommandType, ICommand, ICommandService, IUndoRedoService } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { ISetWorksheetHideMutationParams, SetWorksheetHideMutation, SetWorksheetHideMutationFactory } from '../Mutations/set-worksheet-hide.mutation';
+
+export interface ISetWorksheetHiddenCommandParams {
+ hidden: BooleanNumber;
+ workbookId: string;
+ worksheetId: string;
+}
+
+export const SetWorksheetHideCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-worksheet-hidden',
+
+ handler: async (accessor: IAccessor, params: ISetWorksheetHiddenCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const redoMutationParams: ISetWorksheetHideMutationParams = {
+ hidden: params.hidden,
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ };
+
+ const undoMutationParams = SetWorksheetHideMutationFactory(accessor, redoMutationParams);
+ const result = commandService.executeCommand(SetWorksheetHideMutation.id, redoMutationParams);
+
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: 'sheet',
+ undo() {
+ return commandService.executeCommand(SetWorksheetHideMutation.id, undoMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(SetWorksheetHideMutation.id, redoMutationParams);
+ },
+ });
+ return true;
+ }
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Commands/set-worksheet-name.command.ts b/packages/base-sheets/src/Commands/Commands/set-worksheet-name.command.ts
new file mode 100644
index 0000000000..e50ec9ecf8
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/set-worksheet-name.command.ts
@@ -0,0 +1,44 @@
+import { CommandType, ICommand, ICommandService, IUndoRedoService } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { ISetWorksheetNameMutationParams, SetWorksheetNameMutation, SetWorksheetNameMutationFactory } from '../Mutations/set-worksheet-name.mutation';
+
+export interface SetWorksheetNameCommandParams {
+ name: string;
+ worksheetId: string;
+ workbookId: string;
+}
+
+/**
+ * The command to insert a row into a worksheet.
+ */
+export const SetWorksheetNameCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-worksheet-name',
+
+ handler: async (accessor: IAccessor, params: SetWorksheetNameCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const redoMutationParams: ISetWorksheetNameMutationParams = {
+ worksheetId: params.worksheetId,
+ name: params.name,
+ workbookId: params.workbookId,
+ };
+ const undoMutationParams: ISetWorksheetNameMutationParams = SetWorksheetNameMutationFactory(accessor, redoMutationParams);
+ const result = commandService.executeCommand(SetWorksheetNameMutation.id, redoMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: 'sheet',
+ undo() {
+ return commandService.executeCommand(SetWorksheetNameMutation.id, undoMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(SetWorksheetNameMutation.id, redoMutationParams);
+ },
+ });
+
+ return true;
+ }
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Commands/set-worksheet-order.command.ts b/packages/base-sheets/src/Commands/Commands/set-worksheet-order.command.ts
new file mode 100644
index 0000000000..d18a39ea9e
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/set-worksheet-order.command.ts
@@ -0,0 +1,40 @@
+import { CommandType, ICommand, ICommandService, IUndoRedoService } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { ISetWorksheetOrderMutationParams, SetWorksheetOrderMutation, SetWorksheetOrderMutationFactory } from '../Mutations/set-worksheet-order.mutation';
+
+export interface SetWorksheetOrderCommandParams {
+ workbookId: string;
+ worksheetId: string;
+ order: number;
+}
+
+export const SetWorksheetOrderCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-worksheet-order',
+ handler: async (accessor: IAccessor, params: SetWorksheetOrderCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const redoMutationParams: ISetWorksheetOrderMutationParams = {
+ worksheetId: params.worksheetId,
+ workbookId: params.workbookId,
+ order: params.order,
+ };
+ const undoMutationParams: ISetWorksheetOrderMutationParams = SetWorksheetOrderMutationFactory(accessor, redoMutationParams);
+ const result = commandService.executeCommand(SetWorksheetOrderMutation.id, redoMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: 'sheet',
+ undo() {
+ return commandService.executeCommand(SetWorksheetOrderMutation.id, undoMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(SetWorksheetOrderMutation.id, redoMutationParams);
+ },
+ });
+
+ return true;
+ }
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Commands/set-worksheet-row-height.command.ts b/packages/base-sheets/src/Commands/Commands/set-worksheet-row-height.command.ts
new file mode 100644
index 0000000000..ea8b666688
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/set-worksheet-row-height.command.ts
@@ -0,0 +1,42 @@
+import { CommandType, ICommand, ICommandService, IUndoRedoService } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { ISetWorksheetRowHeightMutationParams, SetWorksheetRowHeightMutation, SetWorksheetRowHeightMutationFactory } from '../Mutations/set-worksheet-row-height.mutation';
+
+export interface SetWorksheetRowHeightCommandParams {
+ workbookId: string;
+ worksheetId: string;
+ rowIndex: number;
+ rowHeight: number[];
+}
+
+export const SetWorksheetRowHeightCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-worksheet-row-height',
+ handler: async (accessor: IAccessor, params: SetWorksheetRowHeightCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const redoMutationParams: ISetWorksheetRowHeightMutationParams = {
+ worksheetId: params.worksheetId,
+ workbookId: params.workbookId,
+ rowIndex: params.rowIndex,
+ rowHeight: params.rowHeight,
+ };
+ const undoMutationParams: ISetWorksheetRowHeightMutationParams = SetWorksheetRowHeightMutationFactory(accessor, redoMutationParams);
+ const result = commandService.executeCommand(SetWorksheetRowHeightMutation.id, redoMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: 'sheet',
+ undo() {
+ return commandService.executeCommand(SetWorksheetRowHeightMutation.id, undoMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(SetWorksheetRowHeightMutation.id, redoMutationParams);
+ },
+ });
+
+ return true;
+ }
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Commands/set-worksheet-row-hide.command.ts b/packages/base-sheets/src/Commands/Commands/set-worksheet-row-hide.command.ts
new file mode 100644
index 0000000000..1d29d013df
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/set-worksheet-row-hide.command.ts
@@ -0,0 +1,43 @@
+import { CommandType, ICommand, ICommandService, IUndoRedoService } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { ISetWorksheetRowHideMutationParams, SetWorksheetRowHideMutation, SetWorksheetRowHideMutationFactory } from '../Mutations/set-worksheet-row-hide.mutation';
+import { SetWorksheetRowShowMutation } from '../Mutations/set-worksheet-row-show.mutation';
+
+export interface SetWorksheetRowHideCommandParams {
+ workbookId: string;
+ worksheetId: string;
+ rowIndex: number;
+ rowCount: number;
+}
+
+export const SetWorksheetRowHideCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-worksheet-row-hide',
+ handler: async (accessor: IAccessor, params: SetWorksheetRowHideCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const redoMutationParams: ISetWorksheetRowHideMutationParams = {
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ rowIndex: params.rowIndex,
+ rowCount: params.rowCount,
+ };
+
+ const undoMutationParams = SetWorksheetRowHideMutationFactory(accessor, redoMutationParams);
+ const result = commandService.executeCommand(SetWorksheetRowHideMutation.id, redoMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: 'sheet',
+ undo() {
+ return commandService.executeCommand(SetWorksheetRowShowMutation.id, undoMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(SetWorksheetRowHideMutation.id, redoMutationParams);
+ },
+ });
+ return true;
+ }
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Commands/set-worksheet-row-show.command.ts b/packages/base-sheets/src/Commands/Commands/set-worksheet-row-show.command.ts
new file mode 100644
index 0000000000..76dbced47d
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/set-worksheet-row-show.command.ts
@@ -0,0 +1,44 @@
+import { CommandType, ICommand, ICommandService, IUndoRedoService } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { ISetWorksheetRowShowMutationParams, SetWorksheetRowShowMutation, SetWorksheetRowShowMutationFactory } from '../Mutations/set-worksheet-row-show.mutation';
+import { SetWorksheetRowHideMutation } from '../Mutations/set-worksheet-row-hide.mutation';
+
+export interface SetWorksheetRowShowCommandParams {
+ workbookId: string;
+ worksheetId: string;
+ rowIndex: number;
+ rowCount: number;
+}
+
+export const SetWorksheetRowShowCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-worksheet-row-show',
+ handler: async (accessor: IAccessor, params: SetWorksheetRowShowCommandParams) => {
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const redoMutationParams: ISetWorksheetRowShowMutationParams = {
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ rowIndex: params.rowIndex,
+ rowCount: params.rowCount,
+ };
+
+ const undoMutationParams = SetWorksheetRowShowMutationFactory(accessor, redoMutationParams);
+ const result = commandService.executeCommand(SetWorksheetRowShowMutation.id, redoMutationParams);
+
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ URI: 'sheet',
+ undo() {
+ return commandService.executeCommand(SetWorksheetRowHideMutation.id, undoMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(SetWorksheetRowShowMutation.id, redoMutationParams);
+ },
+ });
+ return true;
+ }
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Commands/set-worksheet-status.command.ts b/packages/base-sheets/src/Commands/Commands/set-worksheet-status.command.ts
new file mode 100644
index 0000000000..625c75cb0e
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/set-worksheet-status.command.ts
@@ -0,0 +1,16 @@
+import { CommandType, ICommand } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { SetWorksheetNameCommandParams } from './set-worksheet-name.command';
+
+export interface SetWorksheetRowShowCommandParams {
+ workbookId: string;
+ worksheetId: string;
+ rowIndex: number;
+ rowCount: number;
+}
+
+export const SetWorksheetNameCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.set-worksheet-name',
+ handler: async (accessor: IAccessor, params: SetWorksheetNameCommandParams) => true,
+};
diff --git a/packages/base-sheets/src/Commands/Commands/trim-whitespace.command.ts b/packages/base-sheets/src/Commands/Commands/trim-whitespace.command.ts
new file mode 100644
index 0000000000..8110ed0f53
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Commands/trim-whitespace.command.ts
@@ -0,0 +1,75 @@
+import { IAccessor } from '@wendellhu/redi';
+import { CommandType, ICellV, ICommand, ICommandService, ICurrentUniverService, IRangeData, IUndoRedoService, ObjectMatrix } from '@univerjs/core';
+
+import { ISetRangeFormattedValueMutationParams, SetRangeFormattedValueMutation, SetRangeFormattedValueUndoMutationFactory } from '../Mutations/set-range-formatted-value.mutation';
+
+export interface ITrimWhitespaceParams {
+ workbookId: string;
+ worksheetId: string;
+ range: IRangeData[];
+}
+
+/**
+ * The command to insert range.
+ */
+export const TrimWhitespaceCommand: ICommand = {
+ type: CommandType.COMMAND,
+ id: 'sheet.command.trim-whitespace',
+
+ handler: async (accessor: IAccessor, params: ITrimWhitespaceParams) => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+
+ const { workbookId, worksheetId, range } = params;
+ const worksheet = currentUniverService.getUniverSheetInstance(workbookId)?.getWorkBook().getSheetBySheetId(worksheetId);
+ if (!worksheet) return false;
+ const sheetMatrix = worksheet.getCellMatrix();
+ const cellValue = new ObjectMatrix<ICellV>();
+
+ for (let i = 0; i < range.length; i++) {
+ const { startRow, endRow, startColumn, endColumn } = range[i];
+ const regx = /\s+/g;
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ const value = sheetMatrix.getValue(r, c)!.m?.replace(regx, '');
+ cellValue.setValue(r, c, value || '');
+ }
+ }
+ }
+
+ const setRangeFormattedValueMutationParams: ISetRangeFormattedValueMutationParams = {
+ range,
+ worksheetId,
+ workbookId,
+ value: cellValue.getData(),
+ };
+
+ const undoSetRangeFormattedValueMutationParams: ISetRangeFormattedValueMutationParams = SetRangeFormattedValueUndoMutationFactory(
+ accessor,
+ setRangeFormattedValueMutationParams
+ );
+
+ // execute do mutations and add undo mutations to undo stack if completed
+ const result = commandService.executeCommand(SetRangeFormattedValueMutation.id, setRangeFormattedValueMutationParams);
+ if (result) {
+ undoRedoService.pushUndoRedo({
+ // 如果有多个 mutation 构成一个封装项目,那么要封装在同一个 undo redo element 里面
+ // 通过勾子可以 hook 外部 controller 的代码来增加新的 action
+ URI: 'sheet', // TODO: this URI is fake
+ undo() {
+ return commandService.executeCommand(SetRangeFormattedValueMutation.id, undoSetRangeFormattedValueMutationParams);
+ },
+ redo() {
+ return commandService.executeCommand(SetRangeFormattedValueMutation.id, setRangeFormattedValueMutationParams);
+ },
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+ // all subsequent mutations should succeed inorder to make the whole process succeed
+ // Promise.all([]).then(() => true),
+};
diff --git a/packages/base-sheets/src/Commands/Mutations/add-worksheet-merge.mutation.ts b/packages/base-sheets/src/Commands/Mutations/add-worksheet-merge.mutation.ts
new file mode 100644
index 0000000000..4eb5179d9f
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Mutations/add-worksheet-merge.mutation.ts
@@ -0,0 +1,39 @@
+import { CommandType, ICurrentUniverService, IMutation } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { IAddWorksheetMergeMutationParams, IRemoveWorksheetMergeMutationParams } from '../../Basics/Interfaces/MutationInterface';
+
+export const AddWorksheetMergeMutationFactory = (accessor: IAccessor, params: IAddWorksheetMergeMutationParams): IRemoveWorksheetMergeMutationParams => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ throw new Error('universheet is null error!');
+ }
+
+ return {
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ rectangles: params.rectangles,
+ };
+};
+
+export const AddWorksheetMergeMutation: IMutation<IAddWorksheetMergeMutationParams> = {
+ id: 'sheet.mutation.add-worksheet-merge',
+ type: CommandType.MUTATION,
+ handler: async (accessor: IAccessor, params: IAddWorksheetMergeMutationParams) => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ throw new Error('universheet is null error!');
+ }
+
+ const config = universheet.getWorkBook().getSheetBySheetId(params.worksheetId)?.getConfig()!;
+ const mergeConfigData = config.mergeData;
+ const mergeAppendData = params.rectangles;
+ for (let i = 0; i < mergeAppendData.length; i++) {
+ mergeConfigData.push(mergeAppendData[i]);
+ }
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Mutations/delete-range.mutation.ts b/packages/base-sheets/src/Commands/Mutations/delete-range.mutation.ts
new file mode 100644
index 0000000000..bd2c4ea311
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Mutations/delete-range.mutation.ts
@@ -0,0 +1,125 @@
+import { CommandType, IMutation, ICurrentUniverService, ObjectMatrix, Tools, Nullable, ICellV, ICellData, Dimension } from '@univerjs/core';
+
+import { IAccessor } from '@wendellhu/redi';
+import { IDeleteRangeMutationParams, IInsertRangeMutationParams } from '../../Basics/Interfaces/MutationInterface';
+
+/**
+ * Generate undo mutation of a `DeleteRangeMutation`
+ *
+ * @param {IAccessor} accessor - injector accessor
+ * @param {IDeleteRangeMutationParams} params - do mutation params
+ * @returns {IInsertRangeMutationParams} undo mutation params
+ */
+export const DeleteRangeUndoMutationFactory = (accessor: IAccessor, params: IDeleteRangeMutationParams): IInsertRangeMutationParams => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getSheetBySheetId(params.worksheetId);
+ const cellMatrix = worksheet?.getCellMatrix();
+
+ const undoData = new ObjectMatrix<ICellV>();
+ const lastEndRow = worksheet?.getConfig().rowCount ?? 0;
+ const lastEndColumn = worksheet?.getConfig().columnCount ?? 0;
+
+ const rangeData = params.range;
+ const { startRow, endRow, startColumn, endColumn } = rangeData;
+
+ const result = new ObjectMatrix<ICellData>();
+ if (params.shiftDimension === Dimension.ROWS) {
+ // build new data
+ for (let r = startRow; r <= lastEndRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ // store old value
+ if (r <= endRow) {
+ const cell: Nullable<ICellData> = cellMatrix?.getValue(r, c);
+ result.setValue(r, c, cell as ICellData);
+ }
+ }
+ }
+ } else if (params.shiftDimension === Dimension.COLUMNS) {
+ // build new data
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= lastEndColumn; c++) {
+ // store old value
+ if (c <= endColumn) {
+ const cell: Nullable<ICellData> = cellMatrix?.getValue(r, c);
+ result.setValue(r, c, cell as ICellData);
+ } else {
+ for (let i = 0; i <= endColumn; i++) {
+ const cell: Nullable<ICellData> = cellMatrix?.getValue(r, c);
+ result.setValue(r, c + i, cell as ICellData);
+ }
+ }
+ }
+ }
+ }
+
+ return {
+ ...Tools.deepClone(params),
+ cellValue: undoData.getData(),
+ };
+};
+
+export const DeleteRangeMutation: IMutation<IDeleteRangeMutationParams, boolean> = {
+ id: 'sheet.mutation.delete-range',
+ type: CommandType.MUTATION,
+ handler: async (accessor, params) => {
+ 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 cellMatrix = worksheet.getCellMatrix();
+ const lastEndRow = worksheet?.getConfig().rowCount ?? 0;
+ const lastEndColumn = worksheet?.getConfig().columnCount ?? 0;
+ const rangeData = params.range;
+ const { startRow, endRow, startColumn, endColumn } = rangeData;
+
+ const rows = endRow - startRow + 1;
+ const columns = endColumn - startColumn + 1;
+
+ if (params.shiftDimension === Dimension.ROWS) {
+ // build new data
+ for (let r = startRow; r <= lastEndRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ // get value blow current range
+ const value = cellMatrix.getValue(r + rows, c);
+ if (value) {
+ cellMatrix.setValue(r, c, Tools.deepClone(value as ICellData));
+ } else {
+ // null means delete
+ const originValue = cellMatrix.getValue(r, c);
+ if (originValue) {
+ cellMatrix.deleteValue(r, c);
+ // Deleting data will cause the column number to change, so subtract 1 here in advance
+ c--;
+ }
+ }
+ }
+ }
+ } else if (params.shiftDimension === Dimension.COLUMNS) {
+ // build new data
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= lastEndColumn; c++) {
+ // get value blow current range
+
+ const value = cellMatrix.getValue(r, c + columns);
+ if (value) {
+ cellMatrix.setValue(r, c, Tools.deepClone(value as ICellData));
+ } else {
+ // null means delete
+ const originValue = cellMatrix.getValue(r, c);
+ if (originValue) {
+ for (let i = 0; i <= endColumn; i++) {
+ cellMatrix.deleteValue(r, c);
+ }
+ break;
+ // Deleting data will cause the column number to change, so subtract 1 here in advance
+ }
+ }
+ }
+ }
+ }
+
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Mutations/insert-range.mutation.ts b/packages/base-sheets/src/Commands/Mutations/insert-range.mutation.ts
new file mode 100644
index 0000000000..1412ab9652
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Mutations/insert-range.mutation.ts
@@ -0,0 +1,78 @@
+import { CommandType, IMutation, ICurrentUniverService, ICellData, Dimension } from '@univerjs/core';
+
+import { IAccessor } from '@wendellhu/redi';
+import { IDeleteRangeMutationParams, IInsertRangeMutationParams } from '../../Basics/Interfaces/MutationInterface';
+
+/**
+ * Generate undo mutation of a `InsertRangeMutation`
+ *
+ * @param {IAccessor} accessor - injector accessor
+ * @param {IInsertRangeMutationParams} params - do mutation params
+ * @returns {IDeleteRangeMutationParams} undo mutation params
+ */
+export const InsertRangeUndoMutationFactory = (accessor: IAccessor, params: IInsertRangeMutationParams): IDeleteRangeMutationParams => ({
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ range: params.range,
+ shiftDimension: params.shiftDimension,
+});
+
+export const InsertRangeMutation: IMutation<IInsertRangeMutationParams, boolean> = {
+ id: 'sheet.mutation.insert-range',
+ type: CommandType.MUTATION,
+ handler: async (accessor, params) => {
+ 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 cellMatrix = worksheet.getCellMatrix();
+ const lastEndRow = worksheet?.getLastRow() ?? 0;
+ const lastEndColumn = worksheet!?.getLastColumn() ?? 0;
+
+ const rangeData = params.range;
+ const { startRow, endRow, startColumn, endColumn } = rangeData;
+ const rows = endRow - startRow + 1;
+ const columns = endColumn - startColumn + 1;
+
+ if (params.shiftDimension === Dimension.ROWS) {
+ // build new data
+ for (let r = lastEndRow; r >= startRow; r--) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ // get value blow current range
+ const value = cellMatrix?.getValue(r, c);
+ cellMatrix?.setValue(r + rows, c, value as ICellData);
+ }
+ }
+ // insert cell value from user
+ for (let r = endRow; r >= startRow; r--) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ cellMatrix?.setValue(r, c, params.cellValue[r - startRow][c - startColumn]);
+ }
+ }
+ } else if (params.shiftDimension === Dimension.COLUMNS) {
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = lastEndColumn; c >= startColumn; c--) {
+ // get value blow current range
+ const value = cellMatrix?.getValue(r, c);
+
+ cellMatrix?.setValue(r, c + columns, value as ICellData);
+ }
+ }
+ // insert cell value from user
+ // for (let r = endRow; r >= startRow; r--) {
+ // for (let c = startColumn; c <= endColumn; c++) {
+ // cellMatrix.setValue(r, c, (cellValue as ICellData)[r - startRow][c - startColumn]);
+ // }
+ // }
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = endColumn; c >= startColumn; c--) {
+ cellMatrix?.setValue(r, c, params.cellValue[r - startRow][c - startColumn]);
+ }
+ }
+ }
+
+ return true;
+ },
+};
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 65a2b10074..661c6d60eb 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
@@ -1,23 +1,91 @@
-import { CommandType, IMutation } from '@univerjs/core';
+import { CommandType, ICurrentUniverService, IMutation, ObjectArray, ObjectMatrix } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { IInsertColMutationParams, IInsertRowMutationParams, IRemoveColMutationParams, IRemoveRowMutationParams } from '../../Basics/Interfaces/MutationInterface';
-export interface IInsertRowParams {}
+export const InsertRowMutationFactory = (accessor: IAccessor, params: IInsertRowMutationParams): IRemoveRowMutationParams => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
-export const InsertRowMutation: IMutation<IInsertRowParams> = {
+ if (universheet == null) {
+ throw new Error('universheet is null error!');
+ }
+
+ return {
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ rowIndex: params.rowIndex,
+ rowCount: params.rowCount,
+ };
+};
+
+export const InsertRowMutation: IMutation<IInsertRowMutationParams> = {
id: 'sheet.mutation.insert-row',
type: CommandType.MUTATION,
handler: async (accessor, params) => {
- // TODO: copy code from
- // packages/core/src/Sheets/Apply/InsertRow.ts
+ 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);
+ const manager = worksheet!.getRowManager();
+ const rowPrimitive = manager.getRowData().toJSON();
+ const rowWrapper = new ObjectArray(rowPrimitive);
+ rowWrapper.inserts(params.rowIndex, new ObjectArray(params.rowCount));
+
+ const cellPrimitive = worksheet!.getCellMatrix().toJSON();
+ const cellWrapper = new ObjectMatrix(cellPrimitive);
+ if (params.insertRowData == null) {
+ cellWrapper.insertRowCount(params.rowIndex, params.rowCount);
+ } else {
+ cellWrapper.insertRows(params.rowIndex, new ObjectMatrix(params.insertRowData));
+ }
return true;
},
};
-export interface IInsertColParams {}
+export const InsertColMutationFactory = (accessor: IAccessor, params: IInsertColMutationParams): IRemoveColMutationParams => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ throw new Error('universheet is null error!');
+ }
-export const IInsertColMutation: IMutation<IInsertColParams> = {
+ return {
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ colIndex: params.colIndex,
+ colCount: params.colCount,
+ };
+};
+
+export const InsertColMutation: IMutation<IInsertColMutationParams> = {
id: 'sheet.mutation.insert-col',
type: CommandType.MUTATION,
handler: async (accessor, params) => {
+ 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);
+ const manager = worksheet!.getColumnManager();
+ const columnPrimitive = manager.getColumnData().toJSON();
+ const columnWrapper = new ObjectArray(columnPrimitive);
+ columnWrapper.inserts(params.colIndex, new ObjectArray(params.colCount));
+
+ const cellPrimitive = worksheet!.getCellMatrix().toJSON();
+ const cellWrapper = new ObjectMatrix(cellPrimitive);
+ if (params.insertColData == null) {
+ cellWrapper.insertColumnCount(params.colIndex, params.colCount);
+ } else {
+ cellWrapper.insertColumns(params.colIndex, new ObjectMatrix(params.insertColData));
+ }
return true;
},
-};
\ No newline at end of file
+};
diff --git a/packages/base-sheets/src/Commands/Mutations/insert-sheet.mutation.ts b/packages/base-sheets/src/Commands/Mutations/insert-sheet.mutation.ts
new file mode 100644
index 0000000000..9c0eeaab97
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Mutations/insert-sheet.mutation.ts
@@ -0,0 +1,34 @@
+import { IMutation, CommandType, ICurrentUniverService } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { IInsertSheetMutationParams, IRemoveSheetMutationParams } from '../../Basics/Interfaces/MutationInterface';
+
+/**
+ * Generate undo mutation of a `InsertSheetMutation`
+ *
+ * @param {IAccessor} accessor - injector accessor
+ * @param {IInsertSheetMutationParams} params - do mutation params
+ * @returns {IRemoveSheetMutationParams} undo mutation params
+ */
+export const InsertSheetUndoMutationFactory = (accessor: IAccessor, params: IInsertSheetMutationParams): IRemoveSheetMutationParams => ({
+ worksheetId: params.sheet.id,
+ workbookId: params.workbookId,
+});
+
+export const InsertSheetMutation: IMutation<IInsertSheetMutationParams, boolean> = {
+ id: 'sheet.mutation.insert-sheet',
+ type: CommandType.MUTATION,
+ handler: async (accessor, params) => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const { sheet, index, workbookId } = params;
+ const workbook = currentUniverService.getUniverSheetInstance(workbookId)?.getWorkBook();
+
+ if (!workbook) {
+ return false;
+ }
+
+ workbook.insertSheetByIndexSheet(index, sheet);
+ // TODO activate next sheet
+
+ return true;
+ },
+};
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
new file mode 100644
index 0000000000..19b34901fe
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Mutations/remove-row-col.mutation.ts
@@ -0,0 +1,89 @@
+import { CommandType, ICurrentUniverService, IMutation, ObjectArray, ObjectMatrix } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { IInsertColMutationParams, IInsertRowMutationParams, IRemoveColMutationParams, IRemoveRowMutationParams } from '../../Basics/Interfaces/MutationInterface';
+
+export const RemoveRowMutationFactory = (accessor: IAccessor, params: IRemoveRowMutationParams): IInsertRowMutationParams => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ throw new Error('universheet is null error!');
+ }
+
+ const rowPrimitive = universheet.getWorkBook().getSheetBySheetId(params.worksheetId)!.getCellMatrix().toJSON();
+ const rowWrapper = new ObjectMatrix(rowPrimitive);
+ return {
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ rowIndex: params.rowIndex,
+ rowCount: params.rowCount,
+ insertRowData: rowWrapper.sliceRows(params.rowIndex, params.rowCount).toJSON(),
+ };
+};
+
+export const RemoveRowMutation: IMutation<IRemoveRowMutationParams> = {
+ id: 'sheet.mutation.remove-row',
+ type: CommandType.MUTATION,
+ handler: async (accessor, params) => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ throw new Error('universheet is null error!');
+ }
+
+ const manager = universheet.getWorkBook().getSheetBySheetId(params.worksheetId)!.getRowManager();
+ const rowPrimitive = manager.getRowData().toJSON();
+ const rowWrapper = new ObjectArray(rowPrimitive);
+ rowWrapper.splice(params.rowIndex, params.rowCount);
+
+ const cellPrimitive = universheet.getWorkBook().getSheetBySheetId(params.worksheetId)!.getCellMatrix().toJSON();
+ const wrapper = new ObjectMatrix(cellPrimitive);
+ wrapper.spliceRows(params.rowIndex, params.rowCount);
+ return true;
+ },
+};
+
+export const IRemoveColMutationFactory = (accessor: IAccessor, params: IRemoveColMutationParams): IInsertColMutationParams => {
+ 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);
+ const cellPrimitive = worksheet!.getCellMatrix().toJSON();
+ return {
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ colIndex: params.colIndex,
+ colCount: params.colCount,
+ insertColData: new ObjectMatrix(cellPrimitive).sliceColumns(params.colIndex, params.colCount).toJSON(),
+ };
+};
+
+export const RemoveColMutation: IMutation<IRemoveColMutationParams> = {
+ id: 'sheet.mutation.remove-col',
+ type: CommandType.MUTATION,
+ handler: async (accessor, params) => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ throw new Error('universheet is null error!');
+ }
+
+ const manager = universheet.getWorkBook().getSheetBySheetId(params.worksheetId)!.getColumnManager();
+ const columnPrimitive = manager.getColumnData().toJSON();
+ const columnWrapper = new ObjectArray(columnPrimitive);
+ const start = params.colIndex;
+ const end = params.colIndex + params.colCount;
+ for (let i = start; i < end; i++) columnWrapper.splice(params.colIndex, 1);
+
+ const cellPrimitive = universheet.getWorkBook().getSheetBySheetId(params.worksheetId)!.getCellMatrix().toJSON();
+ const cellWrapper = new ObjectMatrix(cellPrimitive);
+ cellWrapper.spliceColumns(params.colIndex, params.colCount).toJSON();
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Mutations/remove-sheet.mutation.ts b/packages/base-sheets/src/Commands/Mutations/remove-sheet.mutation.ts
new file mode 100644
index 0000000000..b96809d837
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Mutations/remove-sheet.mutation.ts
@@ -0,0 +1,43 @@
+import { IMutation, CommandType, ICurrentUniverService } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { IInsertSheetMutationParams, IRemoveSheetMutationParams } from '../../Basics/Interfaces/MutationInterface';
+
+/**
+ * Generate undo mutation of a `RemoveSheetMutation`
+ *
+ * @param {IAccessor} accessor - injector accessor
+ * @param {IRemoveSheetMutationParams} params - do mutation params
+ * @returns {IInsertSheetMutationParams} undo mutation params
+ */
+export const RemoveSheetUndoMutationFactory = (accessor: IAccessor, params: IRemoveSheetMutationParams): IInsertSheetMutationParams => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const workbook = currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
+ const { worksheetId, workbookId } = params;
+ const sheet = workbook.getSheetBySheetId(worksheetId)!.getConfig();
+ const config = workbook!.getConfig();
+ const index = config.sheetOrder.findIndex((id) => id === worksheetId);
+
+ return {
+ index,
+ sheet,
+ workbookId,
+ };
+};
+
+export const RemoveSheetMutation: IMutation<IRemoveSheetMutationParams, boolean> = {
+ id: 'sheet.mutation.remove-sheet',
+ type: CommandType.MUTATION,
+ handler: async (accessor, params) => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const { worksheetId, workbookId } = params;
+ const workbook = currentUniverService.getUniverSheetInstance(workbookId)?.getWorkBook();
+
+ if (!workbook) {
+ return false;
+ }
+
+ workbook.removeSheetBySheetId(worksheetId);
+
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Mutations/remove-worksheet-merge.mutation.ts b/packages/base-sheets/src/Commands/Mutations/remove-worksheet-merge.mutation.ts
new file mode 100644
index 0000000000..48d5953bb6
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Mutations/remove-worksheet-merge.mutation.ts
@@ -0,0 +1,45 @@
+import { CommandType, ICurrentUniverService, IMutation, Rectangle } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { IAddWorksheetMergeMutationParams, IRemoveWorksheetMergeMutationParams } from '../../Basics/Interfaces/MutationInterface';
+
+export const RemoveWorksheetMergeMutationFactory = (accessor: IAccessor, params: IRemoveWorksheetMergeMutationParams): IAddWorksheetMergeMutationParams => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ throw new Error('universheet is null error!');
+ }
+
+ return {
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ rectangles: params.rectangles,
+ };
+};
+
+export const RemoveWorksheetMergeMutation: IMutation<IRemoveWorksheetMergeMutationParams> = {
+ id: 'sheet.mutation.remove-worksheet-merge',
+ type: CommandType.MUTATION,
+ handler: async (accessor: IAccessor, params: IRemoveWorksheetMergeMutationParams) => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ throw new Error('universheet is null error!');
+ }
+
+ const config = universheet.getWorkBook().getSheetBySheetId(params.worksheetId)!.getConfig()!;
+ const mergeConfigData = config.mergeData;
+ const mergeRemoveData = params.rectangles;
+ for (let j = 0; j < mergeRemoveData.length; j++) {
+ for (let i = mergeConfigData.length - 1; i >= 0; i--) {
+ const configMerge = mergeConfigData[i];
+ const removeMerge = mergeRemoveData[j];
+ if (Rectangle.intersects(configMerge, removeMerge)) {
+ mergeConfigData.splice(i, 1);
+ }
+ }
+ }
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Mutations/set-range-formatted-value.mutation.ts b/packages/base-sheets/src/Commands/Mutations/set-range-formatted-value.mutation.ts
new file mode 100644
index 0000000000..bc75e36609
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Mutations/set-range-formatted-value.mutation.ts
@@ -0,0 +1,74 @@
+import { CommandType, IMutation, ICurrentUniverService, ObjectMatrix, Tools, Nullable, IRangeData, ObjectMatrixPrimitiveType, ICellV, ICellData } from '@univerjs/core';
+
+import { IAccessor } from '@wendellhu/redi';
+
+export interface ISetRangeFormattedValueMutationParams {
+ workbookId: string;
+ worksheetId: string;
+ range: IRangeData[];
+ value: ObjectMatrixPrimitiveType<ICellV>;
+}
+
+/**
+ * Generate undo mutation of a `SetRangeFormattedValueMutation`
+ *
+ * @param {IAccessor} accessor - injector accessor
+ * @param {ISetRangeFormattedValueMutationParams} params - do mutation params
+ * @returns {ISetRangeFormattedValueMutationParams} undo mutation params
+ */
+export const SetRangeFormattedValueUndoMutationFactory = (accessor: IAccessor, params: ISetRangeFormattedValueMutationParams): ISetRangeFormattedValueMutationParams => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getSheetBySheetId(params.worksheetId);
+ const cellMatrix = worksheet?.getCellMatrix();
+
+ const undoData = new ObjectMatrix<ICellV>();
+ for (let i = 0; i < params.range.length; i++) {
+ const rangeData = params.range[i];
+ for (let j = rangeData.startRow; j <= rangeData.endRow; j++) {
+ for (let k = rangeData.startColumn; k <= rangeData.endColumn; k++) {
+ const cell: Nullable<ICellData> = cellMatrix?.getValue(j, k);
+ undoData.setValue(j, k, (cell && cell.v) || '');
+ }
+ }
+ }
+
+ return {
+ ...Tools.deepClone(params),
+ value: undoData.getData(),
+ } as ISetRangeFormattedValueMutationParams;
+};
+
+export const SetRangeFormattedValueMutation: IMutation<ISetRangeFormattedValueMutationParams, boolean> = {
+ id: 'sheet.mutation.set-range-formatted-value',
+ type: CommandType.MUTATION,
+ handler: async (accessor, params) => {
+ 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 cellMatrix = worksheet.getCellMatrix();
+ const target = new ObjectMatrix(params.value);
+
+ for (let i = 0; i < params.range.length; i++) {
+ const rangeData = params.range[i];
+ for (let j = rangeData.startRow; j <= rangeData.endRow; j++) {
+ for (let k = rangeData.startColumn; k <= rangeData.endColumn; k++) {
+ const value = target.getValue(j, k);
+ const cell: Nullable<ICellData> = cellMatrix.getValue(j, k);
+ // update new value, cell may be undefined
+ const cellValue = Tools.deepClone(cell || {});
+ cellValue.v = value;
+ // TODO:calculate m from cell format
+ // TODO:解析外移,性能监测
+ cellValue.m = `${value}`;
+
+ cellMatrix.setValue(j, k, cellValue || {});
+ }
+ }
+ }
+
+ return true;
+ },
+};
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 5d1a610da3..4efe5b4fd9 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
@@ -1,13 +1,258 @@
-import { CommandType, IMutation } from '@univerjs/core';
+import {
+ CommandType,
+ IMutation,
+ IStyleData,
+ ICurrentUniverService,
+ ObjectMatrix,
+ Tools,
+ Nullable,
+ IBorderData,
+ IKeyValue,
+ IDocumentData,
+ ITextStyle,
+ IRangeData,
+ ObjectMatrixPrimitiveType,
+} from '@univerjs/core';
-export interface ISetRangeStyleMutation {
+import { IAccessor } from '@wendellhu/redi';
+export interface ISetRangeStyleMutationParams {
+ workbookId: string;
+ worksheetId: string;
+ range: IRangeData[];
+ value: ObjectMatrixPrimitiveType<IStyleData>;
}
-export const SetRangeStyleMutation: IMutation<> = {
+/**
+ * Generate undo mutation of a `SetRangeStyleMutation`
+ *
+ * @param {IAccessor} accessor - injector accessor
+ * @param {ISetRangeStyleMutationParams} params - do mutation params
+ * @returns {ISetRangeStyleMutationParams} undo mutation params
+ */
+export const SetRangeStyleUndoMutationFactory = (accessor: IAccessor, params: ISetRangeStyleMutationParams): ISetRangeStyleMutationParams => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const workbook = currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
+ const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getSheetBySheetId(params.worksheetId);
+ const cellMatrix = worksheet?.getCellMatrix();
+ const styles = workbook.getStyles();
+
+ const undoData = new ObjectMatrix<IStyleData>();
+ for (let i = 0; i < params.range.length; i++) {
+ const { startRow, endRow, startColumn, endColumn } = params.range[i];
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ const cell = cellMatrix?.getValue(r, c) || {};
+ const old = styles.getStyleByCell(cell);
+ undoData.setValue(r - startRow, c - startColumn, transformStyle(old, params.value[r - startRow][c - startColumn] as Nullable<IStyleData>));
+ }
+ }
+ }
+
+ return {
+ ...Tools.deepClone(params),
+ value: undoData.getData(),
+ } as ISetRangeStyleMutationParams;
+};
+
+export const SetRangeStyleMutation: IMutation<ISetRangeStyleMutationParams, boolean> = {
id: 'sheet.mutation.set-range-style',
type: CommandType.MUTATION,
handler: async (accessor, params) => {
+ 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 cellMatrix = worksheet.getCellMatrix();
+ const styles = workbook.getStyles();
+
+ for (let i = 0; i < params.range.length; i++) {
+ const { startRow, endRow, startColumn, endColumn } = params.range[i];
+ for (let r = startRow; r <= endRow; r++) {
+ for (let c = startColumn; c <= endColumn; c++) {
+ const cell = cellMatrix.getValue(r, c) || {};
+ // use null to clear style
+ const old = styles.getStyleByCell(cell);
+
+ if (old == null) {
+ // clear
+ delete cell.s;
+ }
+
+ // set style
+ const merge = mergeStyle(old, params.value[r - startRow][c - startColumn] as Nullable<IStyleData>);
+
+ // then remove null
+ merge && Tools.removeNull(merge);
+
+ if (Tools.isEmptyObject(merge)) {
+ delete cell.s;
+ } else {
+ cell.s = styles.setValue(merge);
+ }
+
+ // When the rich text sets the cell style, you need to modify the style of all rich text
+ // TODO redo/undo use setRangeData to undo rich text setting
+ if (cell.p) {
+ mergeRichTextStyle(cell.p, params.value[r - startRow][c - startColumn] as Nullable<IStyleData>);
+ }
+
+ cellMatrix.setValue(r, c, cell);
+ }
+ }
+ }
+
return true;
+ },
+};
+
+/**
+ * Convert old style data for storage
+ * @param style
+ */
+export function transformStyle(oldStyle: Nullable<IStyleData>, newStyle: Nullable<IStyleData>): Nullable<IStyleData> {
+ const backupStyle = transformNormalKey(oldStyle, newStyle);
+ return backupStyle;
+}
+/**
+ * Convert old style normal key for storage
+ *
+ * @param style
+ */
+export function transformNormalKey(oldStyle: Nullable<IStyleData>, newStyle: Nullable<IStyleData>): Nullable<IStyleData> {
+ // If there is no newly set style, directly store the historical style
+ if (!newStyle || !Object.keys(newStyle).length) {
+ return oldStyle;
+ }
+ const backupStyle: { [key: string]: any } = Tools.deepClone(oldStyle) || {};
+
+ for (const k in newStyle) {
+ if (k === 'bd') {
+ backupStyle[k] = transformBorders(backupStyle[k] || {}, newStyle[k]);
+ }
+ // 1. To modify the existing style,we need original setting to undo
+ // 2. Newly set the style, we need null to undo
+ else if (!(k in backupStyle)) {
+ backupStyle[k] = null;
+ }
}
-};
\ No newline at end of file
+ return backupStyle;
+}
+/**
+ * Convert old style border for storage
+ *
+
+ * @param style
+ */
+export function transformBorders(oldBorders: IBorderData, newBorders: Nullable<IBorderData>): IBorderData {
+ // If there is no newly set border, directly store the historical border
+ if (!newBorders || !Object.keys(newBorders).length) {
+ return oldBorders;
+ }
+
+ for (const k in newBorders) {
+ // 1. To modify the existing border,we need original setting to undo
+ // 2. Newly set the border, we need null to undo
+ if (!(k in oldBorders)) {
+ (oldBorders as IKeyValue)[k] = null;
+ }
+ }
+
+ return oldBorders;
+}
+
+/**
+ * merge new style to old style
+ *
+ * @param oldStyle
+ * @param newStyle
+ */
+export function mergeStyle(oldStyle: Nullable<IStyleData>, newStyle: Nullable<IStyleData>, isRichText: boolean = false): Nullable<IStyleData> {
+ // clear style
+ if (newStyle === null) return newStyle;
+ // don't operate
+ if (newStyle === undefined) return oldStyle;
+
+ const backupStyle: { [key: string]: any } = Tools.deepClone(oldStyle) || {};
+ if (!backupStyle) return;
+ for (const k in newStyle) {
+ if (isRichText && ['bd', 'tr', 'td', 'ht', 'vt', 'tb', 'pd'].includes(k)) {
+ continue;
+ }
+ // you can only choose one of the themeColor and rgbColor of the border setting
+ if (k in backupStyle && k === 'bd') {
+ 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;
+ }
+ }
+ }
+ }
+ return backupStyle;
+}
+
+/**
+ * Find the text style of all paragraphs and modify it to the new style
+ * @param p
+ * @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 = {};
+ }
+
+ 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;
+ }
+ });
+}
diff --git a/packages/base-sheets/src/Commands/Mutations/set-worksheet-activate.mutation.ts b/packages/base-sheets/src/Commands/Mutations/set-worksheet-activate.mutation.ts
new file mode 100644
index 0000000000..6f1db3a6ee
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Mutations/set-worksheet-activate.mutation.ts
@@ -0,0 +1,58 @@
+import { BooleanNumber, CommandType, ICurrentUniverService, IMutation, Nullable, Worksheet } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+
+export interface ISetWorksheetActivateMutationParams {
+ workbookId: string;
+ worksheetId: string;
+}
+
+export const SetWorksheetActivateMutationFactory = (accessor: IAccessor, params: ISetWorksheetActivateMutationParams): ISetWorksheetActivateMutationParams => {
+ const universheet = accessor.get(ICurrentUniverService).getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ throw new Error('universheet is null error!');
+ }
+
+ const worksheets = universheet.getWorkBook().getWorksheets();
+ let activate: Nullable<Worksheet> = null;
+
+ for (const [, worksheet] of worksheets) {
+ if (worksheet.getStatus() === BooleanNumber.TRUE) {
+ activate = worksheet;
+ break;
+ }
+ }
+
+ if (activate == null) {
+ throw new Error('not found activate worksheet!');
+ }
+
+ return {
+ workbookId: params.workbookId,
+ worksheetId: activate.getSheetId(),
+ };
+};
+
+export const SetWorksheetActivateMutation: IMutation<ISetWorksheetActivateMutationParams> = {
+ id: 'sheet.mutation.set-worksheet-activate',
+ type: CommandType.MUTATION,
+ handler: async (accessor, params) => {
+ const universheet = accessor.get(ICurrentUniverService).getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ return false;
+ }
+
+ const worksheets = universheet.getWorkBook().getWorksheets();
+
+ for (const [, worksheet] of worksheets) {
+ if (worksheet.getSheetId() === params.worksheetId) {
+ worksheet.setStatus(BooleanNumber.TRUE);
+ } else {
+ worksheet.setStatus(BooleanNumber.FALSE);
+ }
+ }
+
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Mutations/set-worksheet-col-width.mutation.ts b/packages/base-sheets/src/Commands/Mutations/set-worksheet-col-width.mutation.ts
new file mode 100644
index 0000000000..e4b69c6733
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Mutations/set-worksheet-col-width.mutation.ts
@@ -0,0 +1,52 @@
+import { CommandType, ICurrentUniverService, IMutation } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+
+export interface ISetWorksheetColWidthMutationParams {
+ workbookId: string;
+ worksheetId: string;
+ colIndex: number;
+ colWidth: number[];
+}
+
+export const SetWorksheetColWidthMutationFactory = (accessor: IAccessor, params: ISetWorksheetColWidthMutationParams): ISetWorksheetColWidthMutationParams => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ throw new Error('universheet is null error!');
+ }
+
+ const manager = universheet.getWorkBook().getSheetBySheetId(params.worksheetId)!.getColumnManager();
+ const colWidth = [];
+ for (let i = params.colIndex; i < params.colIndex + params.colWidth.length; i++) {
+ const column = manager.getColumnOrCreate(i);
+ colWidth[i - params.colIndex] = column.w;
+ }
+
+ return {
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ colIndex: params.colIndex,
+ colWidth: params.colWidth,
+ };
+};
+
+export const SetWorksheetColWidthMutation: IMutation<ISetWorksheetColWidthMutationParams> = {
+ id: 'sheet.mutation.set-worksheet-col-width',
+ type: CommandType.MUTATION,
+ handler: async (accessor, params) => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ throw new Error('universheet is null error!');
+ }
+
+ const manager = universheet.getWorkBook().getSheetBySheetId(params.worksheetId)!.getColumnManager();
+ for (let i = params.colIndex; i < params.colIndex + params.colWidth.length; i++) {
+ const column = manager.getColumnOrCreate(i);
+ column.w = params.colWidth[i - params.colIndex];
+ }
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Mutations/set-worksheet-hide.mutation.ts b/packages/base-sheets/src/Commands/Mutations/set-worksheet-hide.mutation.ts
new file mode 100644
index 0000000000..d7ac4a0f8c
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Mutations/set-worksheet-hide.mutation.ts
@@ -0,0 +1,42 @@
+import { BooleanNumber, CommandType, ICurrentUniverService, IMutation } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+
+export interface ISetWorksheetHideMutationParams {
+ hidden: BooleanNumber;
+ workbookId: string;
+ worksheetId: string;
+}
+
+export const SetWorksheetHideMutationFactory = (accessor: IAccessor, params: ISetWorksheetHideMutationParams): ISetWorksheetHiddenMutationParams => {
+ const universheet = accessor.get(ICurrentUniverService).getCurrentUniverSheetInstance();
+ const worksheet = universheet.getWorkBook().getSheetBySheetId(params.worksheetId);
+ if (worksheet == null) {
+ throw new Error('worksheet is null error!');
+ }
+ return {
+ hidden: worksheet.isSheetHidden(),
+ workbookId: params.workbookId,
+ worksheetId: worksheet.getSheetId(),
+ };
+};
+
+export const SetWorksheetHideMutation: IMutation<ISetWorksheetHideMutationParams> = {
+ id: 'sheet.mutation.set-worksheet-hidden',
+ type: CommandType.MUTATION,
+ handler: async (accessor, params) => {
+ const universheet = accessor.get(ICurrentUniverService).getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ return false;
+ }
+
+ const worksheet = universheet.getWorkBook().getSheetBySheetId(params.worksheetId);
+
+ if (!worksheet) {
+ return false;
+ }
+
+ worksheet.getConfig().hidden = params.hidden;
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Mutations/set-worksheet-name.mutation.ts b/packages/base-sheets/src/Commands/Mutations/set-worksheet-name.mutation.ts
new file mode 100644
index 0000000000..cb7745c2d1
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Mutations/set-worksheet-name.mutation.ts
@@ -0,0 +1,42 @@
+import { CommandType, ICurrentUniverService, IMutation } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+
+export interface ISetWorksheetNameMutationParams {
+ name: string;
+ workbookId: string;
+ worksheetId: string;
+}
+
+export const SetWorksheetNameMutationFactory = (accessor: IAccessor, params: ISetWorksheetNameMutationParams): ISetWorksheetNameMutationParams => {
+ const universheet = accessor.get(ICurrentUniverService).getCurrentUniverSheetInstance();
+ const worksheet = universheet.getWorkBook().getSheetBySheetId(params.worksheetId);
+ if (worksheet == null) {
+ throw new Error('worksheet is null error!');
+ }
+ return {
+ workbookId: params.workbookId,
+ name: worksheet.getName(),
+ worksheetId: worksheet.getSheetId(),
+ };
+};
+
+export const SetWorksheetNameMutation: IMutation<ISetWorksheetNameMutationParams> = {
+ id: 'sheet.mutation.set-worksheet-name',
+ type: CommandType.MUTATION,
+ handler: async (accessor, params) => {
+ const universheet = accessor.get(ICurrentUniverService).getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ return false;
+ }
+
+ const worksheet = universheet.getWorkBook().getSheetBySheetId(params.worksheetId);
+
+ if (!worksheet) {
+ return false;
+ }
+
+ worksheet.setName(params.name);
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Mutations/set-worksheet-order.mutation.ts b/packages/base-sheets/src/Commands/Mutations/set-worksheet-order.mutation.ts
new file mode 100644
index 0000000000..cb21cb98ea
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Mutations/set-worksheet-order.mutation.ts
@@ -0,0 +1,38 @@
+import { CommandType, ICurrentUniverService, IMutation } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+
+export interface ISetWorksheetOrderMutationParams {
+ order: number;
+ workbookId: string;
+ worksheetId: string;
+}
+
+export const SetWorksheetOrderMutationFactory = (accessor: IAccessor, params: ISetWorksheetOrderMutationParams): ISetWorksheetOrderMutationParams => {
+ const universheet = accessor.get(ICurrentUniverService).getCurrentUniverSheetInstance();
+ const worksheet = universheet.getWorkBook().getSheetBySheetId(params.worksheetId);
+ if (worksheet == null) {
+ throw new Error('worksheet is null error!');
+ }
+ const config = universheet.getWorkBook().getConfig();
+ return {
+ order: config.sheetOrder.findIndex((current: string) => current === params.worksheetId),
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ };
+};
+
+export const SetWorksheetOrderMutation: IMutation<ISetWorksheetOrderMutationParams> = {
+ id: 'sheet.mutation.set-worksheet-order',
+ type: CommandType.MUTATION,
+ handler: async (accessor, params) => {
+ const universheet = accessor.get(ICurrentUniverService).getUniverSheetInstance(params.workbookId);
+ if (universheet == null) {
+ return false;
+ }
+ const config = universheet.getWorkBook().getConfig();
+ const exclude = config.sheetOrder.filter((currentId: string) => currentId !== params.worksheetId);
+ exclude.splice(params.order, 0, params.worksheetId);
+ config.sheetOrder = exclude;
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Mutations/set-worksheet-rightToLeft.mutation.ts b/packages/base-sheets/src/Commands/Mutations/set-worksheet-rightToLeft.mutation.ts
new file mode 100644
index 0000000000..23bdf13f08
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Mutations/set-worksheet-rightToLeft.mutation.ts
@@ -0,0 +1,12 @@
+import { CommandType, IMutation } from '@univerjs/core';
+
+export type ISetWorksheetRightToLeftMutationParams = {
+ workbookId: string;
+ worksheetId: string;
+};
+
+export const SetWorksheetRightToLeftMutation: IMutation<ISetWorksheetRightToLeftMutationParams> = {
+ id: 'sheet.mutation.set-worksheet-rightToLeft',
+ type: CommandType.MUTATION,
+ handler: async (accessor, params) => true,
+};
diff --git a/packages/base-sheets/src/Commands/Mutations/set-worksheet-row-height.mutation.ts b/packages/base-sheets/src/Commands/Mutations/set-worksheet-row-height.mutation.ts
new file mode 100644
index 0000000000..d8651066ab
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Mutations/set-worksheet-row-height.mutation.ts
@@ -0,0 +1,52 @@
+import { CommandType, ICurrentUniverService, IMutation } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+
+export interface ISetWorksheetRowHeightMutationParams {
+ workbookId: string;
+ worksheetId: string;
+ rowIndex: number;
+ rowHeight: number[];
+}
+
+export const SetWorksheetRowHeightMutationFactory = (accessor: IAccessor, params: ISetWorksheetRowHeightMutationParams): ISetWorksheetRowHeightMutationParams => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ throw new Error('universheet is null error!');
+ }
+
+ const manager = universheet.getWorkBook().getSheetBySheetId(params.worksheetId)!.getRowManager();
+ const rowHeight = [];
+ for (let i = params.rowIndex; i < params.rowIndex + params.rowHeight.length; i++) {
+ const row = manager.getRowOrCreate(i);
+ rowHeight[i - params.rowIndex] = row.h;
+ }
+
+ return {
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ rowIndex: params.rowIndex,
+ rowHeight: params.rowHeight,
+ };
+};
+
+export const SetWorksheetRowHeightMutation: IMutation<ISetWorksheetRowHeightMutationParams> = {
+ id: 'sheet.mutation.set-worksheet-row-height',
+ type: CommandType.MUTATION,
+ handler: async (accessor, params) => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ throw new Error('universheet is null error!');
+ }
+
+ const manager = universheet.getWorkBook().getSheetBySheetId(params.worksheetId)!.getRowManager();
+ for (let i = params.rowIndex; i < params.rowIndex + params.rowHeight.length; i++) {
+ const row = manager.getRowOrCreate(i);
+ row.h = params.rowHeight[i - params.rowIndex];
+ }
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Mutations/set-worksheet-row-hide.mutation.ts b/packages/base-sheets/src/Commands/Mutations/set-worksheet-row-hide.mutation.ts
new file mode 100644
index 0000000000..24dc17cf8c
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Mutations/set-worksheet-row-hide.mutation.ts
@@ -0,0 +1,47 @@
+import { CommandType, ICurrentUniverService, IMutation } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+
+export interface ISetWorksheetRowHideMutationParams {
+ workbookId: string;
+ worksheetId: string;
+ rowIndex: number;
+ rowCount: number;
+}
+
+export const SetWorksheetRowHideMutationFactory = (accessor: IAccessor, params: ISetWorksheetRowHideMutationParams) => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ throw new Error('universheet is null error!');
+ }
+
+ return {
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ rowIndex: params.rowIndex,
+ rowCount: params.rowCount,
+ };
+};
+
+export const SetWorksheetRowHideMutation: IMutation<ISetWorksheetRowHideMutationParams> = {
+ id: 'sheet.mutation.set-worksheet-row-hide',
+ type: CommandType.MUTATION,
+ handler: async (accessor, params) => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ throw new Error('universheet is null error!');
+ }
+
+ const manager = universheet.getWorkBook().getSheetBySheetId(params.worksheetId)!.getRowManager();
+ for (let i = params.rowIndex; i < params.rowIndex + params.rowCount; i++) {
+ const row = manager.getRowOrCreate(i);
+ if (row != null) {
+ row.hd = 1;
+ }
+ }
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Mutations/set-worksheet-row-show.mutation.ts b/packages/base-sheets/src/Commands/Mutations/set-worksheet-row-show.mutation.ts
new file mode 100644
index 0000000000..ae0d938d76
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Mutations/set-worksheet-row-show.mutation.ts
@@ -0,0 +1,47 @@
+import { CommandType, ICurrentUniverService, IMutation } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+
+export interface ISetWorksheetRowShowMutationParams {
+ workbookId: string;
+ worksheetId: string;
+ rowIndex: number;
+ rowCount: number;
+}
+
+export const SetWorksheetRowShowMutationFactory = (accessor: IAccessor, params: ISetWorksheetRowShowMutationParams) => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ throw new Error('universheet is null error!');
+ }
+
+ return {
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ rowIndex: params.rowIndex,
+ rowCount: params.rowCount,
+ };
+};
+
+export const SetWorksheetRowShowMutation: IMutation<ISetWorksheetRowShowMutationParams> = {
+ id: 'sheet.mutation.set-worksheet-row-show',
+ type: CommandType.MUTATION,
+ handler: async (accessor, params) => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ throw new Error('universheet is null error!');
+ }
+
+ const manager = universheet.getWorkBook().getSheetBySheetId(params.worksheetId)!.getRowManager();
+ for (let i = params.rowIndex; i < params.rowIndex + params.rowCount; i++) {
+ const row = manager.getRowOrCreate(i);
+ if (row != null) {
+ row.hd = 0;
+ }
+ }
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Mutations/set-worksheet-status.mutation.ts b/packages/base-sheets/src/Commands/Mutations/set-worksheet-status.mutation.ts
new file mode 100644
index 0000000000..85b64abd4c
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Mutations/set-worksheet-status.mutation.ts
@@ -0,0 +1,24 @@
+import { BooleanNumber, CommandType, ICurrentUniverService, IMutation } from '@univerjs/core';
+
+export interface ISetWorksheetStatusMutationParams {
+ workbookId: string;
+ worksheetId: string;
+ sheetStatus: BooleanNumber;
+}
+
+export const SetWorksheetStatusMutation: IMutation<ISetWorksheetStatusMutationParams> = {
+ id: 'sheet.mutation.set-worksheet-status',
+ type: CommandType.MUTATION,
+ handler: async (accessor, params) => {
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const universheet = currentUniverService.getUniverSheetInstance(params.workbookId);
+
+ if (universheet == null) {
+ throw new Error('universheet is null error!');
+ }
+
+ const config = universheet.getWorkBook().getSheetBySheetId(params.worksheetId)!.getConfig()!;
+ config.status = params.sheetStatus;
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/Commands/Operations/selection.operation.ts b/packages/base-sheets/src/Commands/Operations/selection.operation.ts
new file mode 100644
index 0000000000..e0dcd1c33d
--- /dev/null
+++ b/packages/base-sheets/src/Commands/Operations/selection.operation.ts
@@ -0,0 +1,25 @@
+// This file provide operations to change selecction of sheets.
+
+import { ISelectionManager } from '@Services/tokens';
+import { CommandType, ICellInfo, IOperation, ISelection, Nullable } from '@univerjs/core';
+
+export interface ISelectionModelValue {
+ selection: ISelection;
+ cell: Nullable<ICellInfo>;
+}
+
+export interface ISetSelectionsOperationParams {
+ sheetId: string;
+ selections: ISelectionModelValue[];
+}
+
+export const SetSelectionsOperation: IOperation<ISetSelectionsOperationParams> = {
+ id: 'sheet.operation.set-selections',
+ type: CommandType.OPERATION,
+ handler: async (accessor, params) => {
+ const selectionManager = accessor.get(ISelectionManager);
+ selectionManager.setModels(params.selections);
+ selectionManager.renderCurrentControls(false);
+ return true;
+ },
+};
\ No newline at end of file
diff --git a/packages/base-sheets/src/Controller/Selection/selection.operation.ts b/packages/base-sheets/src/Commands/Operations/worksheet.operation.ts
similarity index 100%
rename from packages/base-sheets/src/Controller/Selection/selection.operation.ts
rename to packages/base-sheets/src/Commands/Operations/worksheet.operation.ts
diff --git a/packages/base-sheets/src/Controller/BasicWorkbook.controller.ts b/packages/base-sheets/src/Controller/BasicWorkbook.controller.ts
new file mode 100644
index 0000000000..0e507e98fc
--- /dev/null
+++ b/packages/base-sheets/src/Controller/BasicWorkbook.controller.ts
@@ -0,0 +1,48 @@
+import { IDisposable, Inject, SkipSelf } from '@wendellhu/redi';
+import { Disposable, ICommandService, IWorksheetConfig, ObserverManager } from '@univerjs/core';
+
+import { InsertSheetCommand } from '../Commands/Commands/insert-sheet.command';
+import { RemoveSheetCommand } from '../Commands/Commands/remove-sheet.command';
+import { InsertSheetMutation } from '../Commands/Mutations/insert-sheet.mutation';
+import { RemoveSheetMutation } from '../Commands/Mutations/remove-sheet.mutation';
+
+/**
+ * The controller to provide the most basic sheet CRUD methods to other modules of sheet modules.
+ */
+export class BasicWorkbookController extends Disposable implements IDisposable {
+ constructor(@ICommandService private readonly _commandService: ICommandService, @SkipSelf() @Inject(ObserverManager) private readonly _globalObserverManager: ObserverManager) {
+ super();
+
+ this.disposeWithMe(_commandService.registerCommand(InsertSheetCommand));
+ this.disposeWithMe(_commandService.registerCommand(InsertSheetMutation));
+ this.disposeWithMe(_commandService.registerCommand(RemoveSheetCommand));
+ this.disposeWithMe(_commandService.registerCommand(RemoveSheetMutation));
+ }
+
+ 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 5a474806e0..62ed24ef83 100644
--- a/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts
+++ b/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts
@@ -1,8 +1,45 @@
import { IDisposable } from '@wendellhu/redi';
-import { Disposable, ICommandService } from '@univerjs/core';
+import { Disposable, ICellData, ICellV, ICommandService, IRangeData, IStyleData, ObjectMatrix, ObjectMatrixPrimitiveType } from '@univerjs/core';
import { ClearSelectionContentCommand } from '../Commands/Commands/clear-selection-content.command';
import { SetRangeValuesMutation } from '../Commands/Mutations/set-range-values.mutation';
+import { SetWorksheetNameCommand } from '../Commands/Commands/set-worksheet-name.command';
+import { SetWorksheetNameMutation } from '../Commands/Mutations/set-worksheet-name.mutation';
+import { SetWorksheetActivateCommand } from '../Commands/Commands/set-worksheet-activate.command';
+import { SetWorksheetActivateMutation } from '../Commands/Mutations/set-worksheet-activate.mutation';
+import { ISetStyleParams, SetStyleCommand } from '../Commands/Commands/set-style.command';
+import { SetRangeStyleMutation } from '../Commands/Mutations/set-range-styles.mutation';
+import { ISetRangeFormattedValueParams, SetRangeFormattedValueCommand } from '../Commands/Commands/set-range-formatted-value.command';
+import { TrimWhitespaceCommand } from '../Commands/Commands/trim-whitespace.command';
+import { ISetRangeValuesCommandParams, SetRangeValuesCommand } from '../Commands/Commands/set-range-values.command';
+import { SetWorksheetHideCommand } from '../Commands/Commands/set-worksheet-hide.command';
+import { SetWorksheetHideMutation } from '../Commands/Mutations/set-worksheet-hide.mutation';
+import { InsertColCommand, InsertRowCommand } from '../Commands/Commands/insert-row-col.command';
+import { InsertColMutation, InsertRowMutation } from '../Commands/Mutations/insert-row-col.mutation';
+import { RemoveColCommand, RemoveRowCommand } from '../Commands/Commands/remove-row-col.command';
+import { RemoveColMutation, RemoveRowMutation } from '../Commands/Mutations/remove-row-col.mutation';
+import { SetWorksheetColWidthCommand } from '../Commands/Commands/set-worksheet-col-width.command';
+import { SetWorksheetColWidthMutation } from '../Commands/Mutations/set-worksheet-col-width.mutation';
+import { SetWorksheetRowHeightCommand } from '../Commands/Commands/set-worksheet-row-height.command';
+import { SetWorksheetRowHeightMutation } from '../Commands/Mutations/set-worksheet-row-height.mutation';
+import { SetWorksheetRowHideCommand } from '../Commands/Commands/set-worksheet-row-hide.command';
+import { SetWorksheetRowHideMutation } from '../Commands/Mutations/set-worksheet-row-hide.mutation';
+import { SetWorksheetRowShowCommand } from '../Commands/Commands/set-worksheet-row-show.command';
+import { SetWorksheetRowShowMutation } from '../Commands/Mutations/set-worksheet-row-show.mutation';
+import { InsertRangeMutation } from '../Commands/Mutations/insert-range.mutation';
+import { DeleteRangeMutation } from '../Commands/Mutations/delete-range.mutation';
+import { SetRangeFormattedValueMutation } from '../Commands/Mutations/set-range-formatted-value.mutation';
+import { IInsertRangeMoveRightParams, InsertRangeMoveRightCommand } from '../Commands/Commands/insert-range-move-right.command';
+import { DeleteRangeMoveLeftCommand, IDeleteRangeMoveLeftParams } from '../Commands/Commands/delete-range-move-left.command';
+import { DeleteRangeMoveTopCommand, IDeleteRangeMoveTopParams } from '../Commands/Commands/delete-range-move-top.command';
+import { IInsertRangeMoveBottomParams, InsertRangeMoveBottomCommand } from '../Commands/Commands/insert-range-move-bottom.command';
+import { SetWorksheetOrderCommand } from '../Commands/Commands/set-worksheet-order.command';
+import { SetWorksheetOrderMutation } from '../Commands/Mutations/set-worksheet-order.mutation';
+
+export interface IStyleTypeValue<T> {
+ type: keyof IStyleData;
+ value: T | T[][];
+}
/**
* The controller to provide the most basic sheet CRUD methods to other modules of sheet modules.
@@ -11,13 +48,50 @@ export class BasicWorksheetController extends Disposable implements IDisposable
constructor(@ICommandService private readonly _commandService: ICommandService) {
super();
- this.disposeWithMe(_commandService.registerCommand(ClearSelectionContentCommand));
- this.disposeWithMe(_commandService.registerCommand(SetRangeValuesMutation));
- }
+ [
+ ClearSelectionContentCommand,
+ SetRangeValuesMutation,
+ SetWorksheetNameCommand,
+ SetWorksheetNameMutation,
+ SetWorksheetActivateCommand,
+ SetWorksheetActivateMutation,
+ SetStyleCommand,
+ SetRangeStyleMutation,
+ SetWorksheetHideCommand,
+ SetWorksheetHideMutation,
- onInitialize() {}
+ InsertRowCommand,
+ InsertRowMutation,
+ RemoveRowCommand,
+ RemoveRowMutation,
+ InsertColCommand,
+ InsertColMutation,
+ RemoveColCommand,
+ RemoveColMutation,
- // TODO: @Dushusir: add other basic mutation methods here.
+ SetWorksheetColWidthCommand,
+ SetWorksheetColWidthMutation,
+ SetWorksheetRowHeightCommand,
+ SetWorksheetRowHeightMutation,
+ SetWorksheetRowHideCommand,
+ SetWorksheetRowHideMutation,
+ SetWorksheetRowShowCommand,
+ SetWorksheetRowShowMutation,
+ SetWorksheetOrderCommand,
+ SetWorksheetOrderMutation,
+
+ SetRangeValuesCommand,
+ TrimWhitespaceCommand,
+ InsertRangeMoveRightCommand,
+ InsertRangeMoveBottomCommand,
+ InsertRangeMutation,
+ DeleteRangeMoveLeftCommand,
+ DeleteRangeMoveTopCommand,
+ DeleteRangeMutation,
+ SetRangeFormattedValueCommand,
+ SetRangeFormattedValueMutation,
+ ].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
+ }
/**
* Clear contents in the current selected ranges.
@@ -25,4 +99,114 @@ export class BasicWorksheetController extends Disposable implements IDisposable
async clearSelectionContent(): Promise<boolean> {
return this._commandService.executeCommand(ClearSelectionContentCommand.id);
}
+
+ async setStyle<T>(workbookId: string, worksheetId: string, style: IStyleTypeValue<T>, range: IRangeData[]): Promise<boolean> {
+ const options: ISetStyleParams<T> = {
+ workbookId,
+ worksheetId,
+ style,
+ ranges: range,
+ };
+ return this._commandService.executeCommand(SetStyleCommand.id, options);
+ }
+
+ /**
+ * Trims the whitespace (such as spaces, tabs, or new lines) in every cell in this range. Removes all whitespace from the start and end of each cell's text, and reduces any subsequence of remaining whitespace characters to a single space.
+ */
+ async trimWhitespace(workbookId: string, worksheetId: string, range: IRangeData[]): Promise<boolean> {
+ const options = {
+ workbookId,
+ worksheetId,
+ range,
+ };
+ return this._commandService.executeCommand(TrimWhitespaceCommand.id, options);
+ }
+
+ /**
+ * Sets a rectangular grid of values (must match dimensions of this range).
+ */
+ async setValue(workbookId: string, worksheetId: string, value: ICellV | ICellV[][] | ObjectMatrix<ICellV>, range: IRangeData[]): Promise<boolean> {
+ const options: ISetRangeFormattedValueParams = {
+ workbookId,
+ worksheetId,
+ value,
+ range,
+ };
+ return this._commandService.executeCommand(SetRangeFormattedValueCommand.id, options);
+ }
+
+ /**
+ * Sets a rectangular grid of cell obejct data (must match dimensions of this range).
+ * @param value A two-dimensional array of cell object data.
+ */
+ async setRangeValues(workbookId: string, worksheetId: string, value: ICellData | ICellData[][] | ObjectMatrixPrimitiveType<ICellData>, range: IRangeData): Promise<boolean> {
+ const options: ISetRangeValuesCommandParams = {
+ workbookId,
+ worksheetId,
+ value,
+ range,
+ };
+ return this._commandService.executeCommand(SetRangeValuesCommand.id, options);
+ }
+
+ /**
+ * Deletes this range of cells. Existing data in the sheet along the provided dimension is shifted towards the deleted range.
+ *
+ * solution: Clear the range to be deleted, and then set the new value of the cell content at the bottom using setValue
+ */
+ async deleteRangeMoveLeft(workbookId: string, worksheetId: string, range: IRangeData): Promise<boolean> {
+ const options: IDeleteRangeMoveLeftParams = {
+ workbookId,
+ worksheetId,
+ range,
+ };
+ return this._commandService.executeCommand(DeleteRangeMoveLeftCommand.id, options);
+ }
+
+ async deleteRangeMoveTop(workbookId: string, worksheetId: string, range: IRangeData): Promise<boolean> {
+ const options: IDeleteRangeMoveTopParams = {
+ workbookId,
+ worksheetId,
+ range,
+ };
+ return this._commandService.executeCommand(DeleteRangeMoveTopCommand.id, options);
+ }
+
+ /**
+ * Inserts empty cells into this range. The new cells retain any formatting present in the cells previously occupying this range. Existing data in the sheet along the provided dimension is shifted away from the inserted range.
+ */
+ async insertRangeMoveRight(workbookId: string, worksheetId: string, range: IRangeData, destination?: IRangeData): Promise<boolean> {
+ const options: IInsertRangeMoveRightParams = {
+ workbookId,
+ worksheetId,
+ range,
+ destination,
+ };
+ return this._commandService.executeCommand(InsertRangeMoveRightCommand.id, options);
+ }
+
+ async insertRangeMoveBottom(workbookId: string, worksheetId: string, range: IRangeData, destination?: IRangeData): Promise<boolean> {
+ const options: IInsertRangeMoveBottomParams = {
+ workbookId,
+ worksheetId,
+ range,
+ destination,
+ };
+ return this._commandService.executeCommand(InsertRangeMoveBottomCommand.id, options);
+ }
+
+ /**
+ * Cut and paste (both format and values) from this range to the target range.
+ * @param target A target range to copy this range to; only the top-left cell position is relevant.
+ */
+ // async moveTo(workbookId: string, worksheetId: string, range: IRangeData): Promise<boolean> {
+ // const options: IInsertRangeParams = {
+ // workbookId,
+ // worksheetId,
+ // shiftDimension,
+ // range,
+ // destination,
+ // };
+ // return this._commandService.executeCommand(SetRangeFormattedValueCommand.id, options);
+ // }
}
diff --git a/packages/base-sheets/src/Controller/RightMenuController.ts b/packages/base-sheets/src/Controller/RightMenuController.ts
index 34f68c9cd3..68f554ace2 100644
--- a/packages/base-sheets/src/Controller/RightMenuController.ts
+++ b/packages/base-sheets/src/Controller/RightMenuController.ts
@@ -13,7 +13,7 @@ export class RightMenuController {
@ISelectionManager private readonly _selectionManager: SelectionManager,
@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
@Inject(HideColumnController) private readonly _hideColumnController: HideColumnController,
- @ICommandService private readonly _commandService: ICommandService,
+ @ICommandService private readonly _commandService: ICommandService
) {}
listenEventManager() {
@@ -144,4 +144,4 @@ export class RightMenuController {
});
return selections;
}
-}
\ No newline at end of file
+}
diff --git a/packages/base-sheets/src/Controller/Selection/SelectionControlDragDrop.ts b/packages/base-sheets/src/Controller/Selection/SelectionControlDragDrop.ts
index e79072591e..415c03cb91 100644
--- a/packages/base-sheets/src/Controller/Selection/SelectionControlDragDrop.ts
+++ b/packages/base-sheets/src/Controller/Selection/SelectionControlDragDrop.ts
@@ -78,16 +78,17 @@ export class SelectionControlDragAndDrop {
// TODO ...
}
+ // eslint-disable-next-line max-lines-per-function
dragDown(evt: IPointerEvent | IMouseEvent, direction: Direction) {
const main = this._canvasView.getSheetView().getSpreadsheet();
// reset model
const selection = this._model.getValue().selection;
this._model = this._injector.createInstance(SelectionModel, SELECTION_TYPE.NORMAL);
- this._model.setValue(selection);
+ // this._model.setValue(selection);
// update control
- this._updateControl();
+ // this._updateControl();
const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
this._startOffsetX = evtOffsetX;
@@ -100,13 +101,13 @@ export class SelectionControlDragAndDrop {
case Direction.LEFT:
cellInfo = main.calculateCellIndexByPosition(evtOffsetX + DEFAULT_SELECTION_CONFIG.strokeWidth, evtOffsetY, scrollXY);
break;
- case Direction.TOP:
+ case Direction.UP:
cellInfo = main.calculateCellIndexByPosition(evtOffsetX, evtOffsetY + DEFAULT_SELECTION_CONFIG.strokeWidth, scrollXY);
break;
case Direction.RIGHT:
cellInfo = main.calculateCellIndexByPosition(evtOffsetX - DEFAULT_SELECTION_CONFIG.strokeWidth, evtOffsetY, scrollXY);
break;
- case Direction.BOTTOM:
+ case Direction.DOWN:
cellInfo = main.calculateCellIndexByPosition(evtOffsetX, evtOffsetY - DEFAULT_SELECTION_CONFIG.strokeWidth, scrollXY);
break;
@@ -226,7 +227,7 @@ export class SelectionControlDragAndDrop {
this._model.setValue(newSelectionPosition);
- this._updateControl();
+ // this._updateControl();
}
}
@@ -326,7 +327,7 @@ export class SelectionControlDragAndDrop {
});
bottomControl.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent) => {
- this.dragDown(evt, Direction.BOTTOM);
+ this.dragDown(evt, Direction.DOWN);
});
bottomControl.onPointerUpObserver.add((evt: IPointerEvent | IMouseEvent) => {
diff --git a/packages/base-sheets/src/Controller/Selection/SelectionManager.ts b/packages/base-sheets/src/Controller/Selection/SelectionManager.ts
index 59141ed623..d9b851cb42 100644
--- a/packages/base-sheets/src/Controller/Selection/SelectionManager.ts
+++ b/packages/base-sheets/src/Controller/Selection/SelectionManager.ts
@@ -1,12 +1,12 @@
+import { SetSelectionsOperation } from '@Commands/Operations/selection.operation';
import { IMouseEvent, IPointerEvent, Rect, ScrollTimer, Spreadsheet, SpreadsheetColumnTitle, SpreadsheetRowTitle } from '@univerjs/base-render';
import {
- ActionOperation,
- Command,
CommandManager,
DEFAULT_CELL,
DEFAULT_SELECTION,
Direction,
ICellInfo,
+ ICommandService,
ICurrentUniverService,
IGridRange,
IRangeCellData,
@@ -23,8 +23,8 @@ import {
} from '@univerjs/core';
import { Inject, Injector } from '@wendellhu/redi';
-import { ACTION_NAMES, ISelectionsConfig, ISheetPluginConfig } from '../../Basics';
-import { ISelectionModelValue, ISetSelectionValueActionData, SetSelectionValueAction } from '../../Model/Action/SetSelectionValueAction';
+import { ISelectionsConfig, ISheetPluginConfig } from '../../Basics';
+import { ISelectionModelValue } from '../../Model/Action/SetSelectionValueAction';
import { SelectionModel } from '../../Model/SelectionModel';
import { SheetView } from '../../View/Views/SheetView';
import { ColumnTitleController } from './ColumnTitleController';
@@ -71,7 +71,9 @@ export class SelectionManager {
private readonly _sheetView: SheetView,
private readonly _config: ISheetPluginConfig,
@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
+ /** @deprecated use ICommandService instead */
@Inject(CommandManager) private readonly _commandManager: CommandManager,
+ @ICommandService private readonly _commandService: ICommandService,
@Inject(Injector) private readonly _injector: Injector,
@Inject(ObserverManager) private readonly _observerManager: ObserverManager,
/** @deprecated this should be divided into smaller pieces */
@@ -81,6 +83,8 @@ export class SelectionManager {
) {
this._initialize();
this._initializeObserver();
+
+ this._commandService.registerCommand(SetSelectionsOperation);
}
/** @deprecated */
@@ -113,6 +117,18 @@ export class SelectionManager {
return this._selectionControls;
}
+ getCurrentSelections() {
+ return this._selectionControls.map((control) => {
+ const model = control.model;
+ return {
+ startRow: model.startRow,
+ startColumn: model.startColumn,
+ endRow: model.endRow,
+ endColumn: model.endColumn,
+ };
+ });
+ }
+
getCurrentControl() {
const controls = this.getCurrentControls();
if (controls && controls.length > 0) {
@@ -169,7 +185,7 @@ export class SelectionManager {
return [];
}
const selectionModelsValue = [];
- for (let model of models) {
+ for (const model of models) {
selectionModelsValue.push(model.getValue());
}
return selectionModelsValue;
@@ -184,7 +200,7 @@ export class SelectionManager {
if (worksheetId) {
if (this._selectionControls) {
// clear old controls
- for (let control of this._selectionControls) {
+ for (const control of this._selectionControls) {
control.dispose();
}
}
@@ -280,10 +296,10 @@ export class SelectionManager {
}
clearSelectionControls() {
- let curControls = this.getCurrentControls();
+ const curControls = this.getCurrentControls();
if (curControls.length > 0) {
- for (let control of curControls) {
+ for (const control of curControls) {
control.dispose();
}
@@ -292,73 +308,22 @@ export class SelectionManager {
}
/**
- * update all current controls data in model
+ * Update all current controls data in model
*/
setSelectionModel(models?: ISelectionModelValue[]) {
- if (!this._worksheet) return;
+ if (!this._worksheet) {
+ return;
+ }
- // get models from current control
if (!models) {
models = this._selectionControls.map((control) => control.model.getValue());
}
- const workbook = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
-
- let action: ISetSelectionValueActionData = {
+ this._commandService.executeCommand(SetSelectionsOperation.id, {
+ workbookId: this._currentUniverService.getCurrentUniverSheetInstance().getUnitId(),
sheetId: this._worksheet.getSheetId(),
- actionName: SetSelectionValueAction.NAME,
selections: models,
- injector: this._injector,
- };
-
- // TODO@wzhudev: this design is bad, leaking implementation details to its users. Will redesign command system and refactor this.
- action = ActionOperation.make<ISetSelectionValueActionData>(action).removeUndo().getAction();
-
- const command = new Command(
- {
- WorkBookUnit: workbook,
- },
- action
- );
- this._commandManager.invoke(command);
- }
-
- /**
- * update current control in model
- */
- updateSelectionModel(selection: ISelection, cell: Nullable<ICellInfo>, index: number) {
- const worksheetId = this.getWorksheetId();
-
- if (!this._worksheet || !worksheetId) return;
-
- // Collect constituency data for the entire current sheet
- const selectionModels = this._selectionModels.get(worksheetId);
- const selectionModelsValue: ISelectionModelValue[] = [];
- selectionModels?.forEach((model, i) => {
- if (i === index) {
- selectionModelsValue.push({ selection, cell });
- } else {
- selectionModelsValue.push(model.getValue());
- }
});
-
- const workbook = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
-
- let action: ISetSelectionValueActionData = {
- sheetId: this._worksheet.getSheetId(),
- actionName: ACTION_NAMES.SET_SELECTION_VALUE_ACTION,
- selections: selectionModelsValue,
- };
-
- action = ActionOperation.make<ISetSelectionValueActionData>(action).removeUndo().getAction();
-
- const command = new Command(
- {
- WorkBookUnit: workbook,
- },
- action
- );
- this._commandManager.invoke(command);
}
setModels(selections: ISelectionModelValue[]) {
@@ -395,7 +360,7 @@ export class SelectionManager {
const rowCount = this._worksheet?.getRowCount() || 1000;
const columnCount = this._worksheet?.getColumnCount() || 50;
switch (direction) {
- case Direction.TOP:
+ case Direction.UP:
if (currentCell.isMerged || currentCell.isMergedMainCell) {
row = --mergeStartRow;
} else {
@@ -405,7 +370,7 @@ export class SelectionManager {
row = 0;
}
break;
- case Direction.BOTTOM:
+ case Direction.DOWN:
if (currentCell.isMerged || currentCell.isMergedMainCell) {
row = ++mergeEndRow;
} else {
@@ -460,13 +425,13 @@ export class SelectionManager {
const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = newBounding;
- let rangeData: IRangeData = {
+ const rangeData: IRangeData = {
startRow: finalStartRow,
endRow: finalEndRow,
startColumn: finalStartColumn,
endColumn: finalEndColumn,
};
- let currentCellData: IRangeCellData = {
+ const currentCellData: IRangeCellData = {
row: startRow,
column: startColumn,
};
@@ -505,13 +470,13 @@ export class SelectionManager {
const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = newBounding;
- let rangeData: IRangeData = {
+ const rangeData: IRangeData = {
startRow: finalStartRow,
endRow: finalEndRow,
startColumn: finalStartColumn,
endColumn: finalEndColumn,
};
- let currentCellData: IRangeCellData = {
+ const currentCellData: IRangeCellData = {
row: startRow,
column: startColumn,
};
@@ -617,7 +582,7 @@ export class SelectionManager {
}
updatePreviousSelection() {
- let selectionControl: Nullable<SelectionController> = this.getCurrentControl();
+ const selectionControl: Nullable<SelectionController> = this.getCurrentControl();
if (!selectionControl) return;
@@ -763,6 +728,7 @@ export class SelectionManager {
const main = this._mainComponent;
// eslint-disable-next-line max-lines-per-function
main.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent) => {
+ // NOTE: handle mousedown event to update selections
const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
this._startOffsetX = evtOffsetX;
this._startOffsetY = evtOffsetY;
@@ -790,13 +756,13 @@ export class SelectionManager {
let selectionControl: Nullable<SelectionController> = this.getCurrentControl();
- let curControls = this.getCurrentControls();
+ const curControls = this.getCurrentControls();
if (!curControls) {
return false;
}
- for (let control of curControls) {
+ for (const control of curControls) {
// right click
if (evt.button === 2 && control.model.isInclude(startSelectionRange)) {
selectionControl = control;
@@ -816,7 +782,7 @@ export class SelectionManager {
// In addition to pressing the ctrl or shift key, we must clear the previous selection
if (curControls.length > 0 && !evt.ctrlKey && !evt.shiftKey) {
- for (let control of curControls) {
+ for (const control of curControls) {
control.dispose();
}
@@ -907,15 +873,6 @@ export class SelectionManager {
scrollTimer.stopScroll();
});
-
- // document.addEventListener('pointerup', () => {
- // this.up();
- // scene.onPointerMoveObserver.remove(this._moveObserver);
- // scene.onPointerUpObserver.remove(this._upObserver);
- // scene.enableEvent();
-
- // scrollTimer.stopScroll();
- // });
});
}
@@ -1052,6 +1009,8 @@ export class SelectionManager {
* Initialize the observer
*/
private _initializeObserver() {
+ // NOTE: on these circumstances should re-render selections controlls
+ // kind of verbose to me though
this._observerManager.requiredObserver('onAfterChangeActiveSheetObservable', 'core').add(() => {
this.renderCurrentControls();
});
@@ -1064,4 +1023,4 @@ export class SelectionManager {
private getWorksheetId(): string {
return this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
}
-}
+}
\ No newline at end of file
diff --git a/packages/base-sheets/src/Controller/SheetBarController.ts b/packages/base-sheets/src/Controller/SheetBarController.ts
index 2528bfe733..b3b68b03cb 100644
--- a/packages/base-sheets/src/Controller/SheetBarController.ts
+++ b/packages/base-sheets/src/Controller/SheetBarController.ts
@@ -1,12 +1,15 @@
-import { UIObserver, ObserverManager, LocaleService, ICurrentUniverService, GenName } from '@univerjs/core';
+import { UIObserver, ObserverManager, LocaleService, ICurrentUniverService, GenName, ICommandService } from '@univerjs/core';
import { Inject, SkipSelf } from '@wendellhu/redi';
+import { SetWorksheetNameCommand } from '../Commands/Commands/set-worksheet-name.command';
+import { InsertSheetCommand } from '../Commands/Commands/insert-sheet.command';
export class SheetBarController {
constructor(
@SkipSelf() @Inject(ObserverManager) private readonly _globalObserverManager: ObserverManager,
@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
@Inject(LocaleService) private readonly _localeService: LocaleService,
- @Inject(GenName) private _genName: GenName
+ @Inject(GenName) private _genName: GenName,
+ @ICommandService private readonly _commandService: ICommandService
) {}
listenEventManager(): void {
@@ -31,21 +34,23 @@ export class SheetBarController {
}
case 'renameSheet': {
const { sheetId, sheetName } = value as { sheetId: string; sheetName: string };
- const worksheet = workbook.getSheetBySheetId(sheetId);
- if (worksheet && sheetName !== worksheet.getName()) {
- worksheet.setName(sheetName);
- }
+ this._commandService.executeCommand(SetWorksheetNameCommand.id, {
+ workbookId: workbook.getUnitId(),
+ name: sheetName,
+ worksheetId: sheetId,
+ });
break;
}
case 'addSheet': {
- workbook.insertSheet();
-
- const size = workbook.getSheetSize();
- const sheets = workbook.getSheets();
- const lastSheet = sheets[size - 1];
- if (lastSheet) {
- lastSheet.activate();
- }
+ // workbook.insertSheet();
+ // const size = workbook.getSheetSize();
+ // const sheets = workbook.getSheets();
+ // const lastSheet = sheets[size - 1];
+ // if (lastSheet) {
+ // lastSheet.activate();
+ // }
+ // TODO 待处理...
+ this._commandService.executeCommand(InsertSheetCommand.id, {});
break;
}
case 'unHideSheet': {
diff --git a/packages/base-sheets/src/Controller/ToolbarController.ts b/packages/base-sheets/src/Controller/ToolbarController.ts
index a0b62b88ac..9e307f011f 100644
--- a/packages/base-sheets/src/Controller/ToolbarController.ts
+++ b/packages/base-sheets/src/Controller/ToolbarController.ts
@@ -9,6 +9,7 @@ import {
ICommandService,
UndoCommand,
RedoCommand,
+ IColorStyle,
} from '@univerjs/core';
import { Inject, SkipSelf } from '@wendellhu/redi';
@@ -18,6 +19,7 @@ import { SelectionModel } from '../Model';
import { ISelectionManager } from '../Services/tokens';
import { CellEditorController } from './CellEditorController';
import { SelectionManager } from './Selection';
+import { BasicWorksheetController, IStyleTypeValue } from './BasicWorksheet.controller';
export interface BorderInfo {
type: BorderType;
@@ -31,7 +33,8 @@ export class ToolbarController {
@ICommandService private readonly _commandService: ICommandService,
@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
@ISelectionManager private readonly _selectionManager: SelectionManager,
- @Inject(CellEditorController) private readonly _cellEditorController: CellEditorController
+ @Inject(CellEditorController) private readonly _cellEditorController: CellEditorController,
+ @Inject(BasicWorksheetController) private readonly _basicWorksheetController: BasicWorksheetController
) {
this._initialize();
}
@@ -150,11 +153,30 @@ export class ToolbarController {
}
private setBackground(value: string) {
- this._selectionManager.getActiveRangeList()?.setBackground(value);
+ const range = this._selectionManager.getActiveRangeData();
+ if (!range) return;
+ const workbookId = this._currentUniverService.getCurrentUniverSheetInstance().getUnitId();
+ const worksheetId = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
+ const style: IStyleTypeValue<IColorStyle> = {
+ type: 'bg',
+ value: {
+ rgb: value,
+ },
+ };
+ this._basicWorksheetController.setStyle(workbookId, worksheetId, style, [range]);
}
private setFontSize(value: number) {
- this._selectionManager.getActiveRangeList()?.setFontSize(value);
+ const range = this._selectionManager.getActiveRangeData();
+ if (!range) return;
+ const workbookId = this._currentUniverService.getCurrentUniverSheetInstance().getUnitId();
+ const worksheetId = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
+ // const style: IStyleTypeValue<number> = {
+ // type: 'fs',
+ // value,
+ // };
+ // this._basicWorksheetController.setStyle(workbookId, worksheetId, style, [range]);
+ this._basicWorksheetController.trimWhitespace(workbookId, worksheetId, [range]);
}
private setFontFamily(value: string) {
diff --git a/packages/base-sheets/src/Controller/index.ts b/packages/base-sheets/src/Controller/index.ts
index 7a80dc7000..5898f55120 100644
--- a/packages/base-sheets/src/Controller/index.ts
+++ b/packages/base-sheets/src/Controller/index.ts
@@ -9,4 +9,6 @@ export * from './SheetContainerController';
export * from './ToolbarController';
export * from './EditTooltipsController';
export * from './HideColumnController';
+export * from './BasicWorksheet.controller';
+export * from './BasicWorkbook.controller';
// @endindex
diff --git a/packages/base-sheets/src/Model/Action/SetSelectionValueAction.ts b/packages/base-sheets/src/Model/Action/SetSelectionValueAction.ts
deleted file mode 100644
index 85aa0089b8..0000000000
--- a/packages/base-sheets/src/Model/Action/SetSelectionValueAction.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-import { SheetActionBase, ActionObservers, ActionType, ISheetActionData, ICellInfo, ISelection, Nullable, CommandUnit, CommandManager } from '@univerjs/core';
-
-import { ACTION_NAMES } from '../../Basics/Enum/ACTION_NAMES';
-import { SetSelectionValue } from '../Apply/SetSelectionValue';
-import { ISelectionManager } from '../../Services/tokens';
-
-export interface ISelectionModelValue {
- selection: ISelection;
- cell: Nullable<ICellInfo>;
-}
-
-export interface ISetSelectionValueActionData extends ISheetActionData {
- selections: ISelectionModelValue[];
-}
-
-export class SetSelectionValueAction extends SheetActionBase<ISetSelectionValueActionData, ISetSelectionValueActionData, ISelectionModelValue[]> {
- static NAME = 'SetSelectionValueAction';
-
- constructor(actionData: ISetSelectionValueActionData, commandUnit: CommandUnit, observers: ActionObservers) {
- super(actionData, commandUnit, observers);
-
- this._doActionData = {
- ...actionData,
- };
-
- const selections = this.do();
-
- this._oldActionData = {
- ...actionData,
- selections,
- };
-
- this.validate();
- }
-
- do(): ISelectionModelValue[] {
- const { selections, injector } = this._doActionData;
- const worksheet = this.getWorkSheet();
-
- const result = SetSelectionValue(worksheet, selections, injector!.get(ISelectionManager));
-
- this._observers.notifyObservers({
- type: ActionType.REDO,
- data: this._doActionData,
- action: this,
- });
-
- return result;
- }
-
- redo(): void {
- // update pre data
- const { sheetId } = this._doActionData;
- const selections = this.do();
- this._oldActionData = {
- actionName: ACTION_NAMES.SET_SELECTION_VALUE_ACTION,
- sheetId,
- selections,
- };
- }
-
- undo(): void {
- const { selections, sheetId, injector } = this._oldActionData;
- const worksheet = this.getWorkSheet();
-
- // update current data
- this._doActionData = {
- actionName: ACTION_NAMES.SET_SELECTION_VALUE_ACTION,
- sheetId,
- selections: SetSelectionValue(worksheet, selections, injector!.get(ISelectionManager)),
- };
-
- this._observers.notifyObservers({
- type: ActionType.UNDO,
- data: this._oldActionData,
- action: this,
- });
- }
-
- validate(): boolean {
- return false;
- }
-}
-
-CommandManager.register(SetSelectionValueAction.NAME, SetSelectionValueAction);
diff --git a/packages/base-sheets/src/Model/Action/index.ts b/packages/base-sheets/src/Model/Action/index.ts
deleted file mode 100644
index 55a3824ed7..0000000000
--- a/packages/base-sheets/src/Model/Action/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-// @index('./*.ts', f => `export * from '${f.path}'`)
-export * from './SetSelectionValueAction';
-// @endindex
diff --git a/packages/base-sheets/src/Model/Apply/SetSelectionValue.ts b/packages/base-sheets/src/Model/Apply/SetSelectionValue.ts
deleted file mode 100644
index 3397425493..0000000000
--- a/packages/base-sheets/src/Model/Apply/SetSelectionValue.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { Worksheet } from '@univerjs/core';
-import { SelectionManager } from '../..';
-import { ISelectionModelValue } from '../Action/SetSelectionValueAction';
-
-/**
- * The rendering component has been initialized with default data in SelectionControl, and the data is stored separately here
- * @param worksheet
- * @param activeRangeList
- * @param activeRange
- * @param currentCell
- * @returns
- *
- * @internal
- */
-export function SetSelectionValue(_worksheet: Worksheet, selections: ISelectionModelValue[], _selectionManager: SelectionManager): ISelectionModelValue[] {
- const result = _selectionManager.getCurrentModelsValue();
- _selectionManager.setModels(selections);
- return result;
-}
diff --git a/packages/base-sheets/src/Model/Apply/index.ts b/packages/base-sheets/src/Model/Apply/index.ts
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/packages/base-sheets/src/Model/index.ts b/packages/base-sheets/src/Model/index.ts
index 532af94f94..f762348c4f 100644
--- a/packages/base-sheets/src/Model/index.ts
+++ b/packages/base-sheets/src/Model/index.ts
@@ -1,5 +1,4 @@
// @index('./*.ts', f => `export * from '${f.path}'`)
export * from './AntLineModel';
export * from './SelectionModel';
-export * from './Action';
-// @endindex
+// @endindex
\ No newline at end of file
diff --git a/packages/base-sheets/src/Services/tokens.ts b/packages/base-sheets/src/Services/tokens.ts
index 7ac094a3d1..ff3016f27b 100644
--- a/packages/base-sheets/src/Services/tokens.ts
+++ b/packages/base-sheets/src/Services/tokens.ts
@@ -3,7 +3,7 @@ import { createIdentifier } from '@wendellhu/redi';
import { SelectionManager } from '../Controller';
import { CanvasView } from '../View';
-/** @deprecated temporary solution, we should inject SelectionManager directly */
+/** @deprecated temporary solution, we should inject SelectionManager directly. And it should be renamed to `ISelectionService`. */
export const ISelectionManager = createIdentifier<SelectionManager>('deprecated.univer.sheet.selection-manager');
export const ICanvasView = createIdentifier<CanvasView>('univer.sheet.canvas-view');
diff --git a/packages/base-sheets/src/SheetPlugin.ts b/packages/base-sheets/src/SheetPlugin.ts
index 2fe7b601c7..d44fa0c931 100644
--- a/packages/base-sheets/src/SheetPlugin.ts
+++ b/packages/base-sheets/src/SheetPlugin.ts
@@ -14,6 +14,7 @@ import {
EditTooltipsController,
SelectionManager,
HideColumnController,
+ BasicWorkbookController,
} from './Controller';
import { DEFAULT_SPREADSHEET_PLUGIN_DATA, install, ISheetPluginConfig } from './Basics';
import { FormulaBarController } from './Controller/FormulaBarController';
@@ -198,6 +199,7 @@ export class SheetPlugin extends Plugin<SheetPluginObserve> {
[ColumnRulerManager],
[BasicWorksheetController],
+ [BasicWorkbookController],
];
dependencies.forEach((d) => {
diff --git a/packages/base-sheets/src/index.ts b/packages/base-sheets/src/index.ts
index 2d77bf2f08..7def216f0f 100644
--- a/packages/base-sheets/src/index.ts
+++ b/packages/base-sheets/src/index.ts
@@ -3,4 +3,38 @@ export * from './Model';
export * from './Controller';
export * from './Basics';
export * from './View';
-export { ICanvasView, ISelectionManager } from './Services/tokens';
\ No newline at end of file
+export { ICanvasView, ISelectionManager } from './Services/tokens';
+
+// mutations
+export { RemoveSheetMutation, RemoveSheetUndoMutationFactory } from './Commands/Mutations/remove-sheet.mutation';
+export { InsertSheetMutation, InsertSheetUndoMutationFactory } from './Commands/Mutations/insert-sheet.mutation';
+export { InsertRowMutation, InsertColMutation, InsertRowMutationFactory, InsertColMutationFactory } from './Commands/Mutations/insert-row-col.mutation';
+export { ISetRangeStyleMutationParams, SetRangeStyleMutation } from './Commands/Mutations/set-range-styles.mutation';
+
+// operations
+export { SetSelectionsOperation } from './Commands/Operations/selection.operation';
+
+// commands
+export { ChangeSelectionCommand, IChangeSelectionCommandParams, ExpandSelectionCommand, IExpandSelectionCommandParams } from './Commands/Commands/set-selections.command';
+export {
+ SetBoldCommand,
+ SetItalicCommand,
+ SetStrikeThroughCommand,
+ SetStyleCommand,
+ SetUnderlineCommand,
+ SetFontFamilyCommand,
+ SetFontSizeCommand,
+ SetTextColorCommand,
+ SetBackgroundColorCommand,
+ SetCellBorderCommand,
+ SetTextRotationCommand,
+ SetHorizontalTextAlignCommand,
+ SetSpanCommand,
+ SetTextWrapCommand,
+ SetVerticalTextAlignCommand,
+} from './Commands/Commands/set-style.command';
+export { InsertSheetCommand } from './Commands/Commands/insert-sheet.command';
+export { ClearSelectionContentCommand } from './Commands/Commands/clear-selection-content.command';
+export { InsertRowCommand, InsertColCommand } from './Commands/Commands/insert-row-col.command';
+export { SetWorksheetActivateCommand } from './Commands/Commands/set-worksheet-activate.command';
+export { SetWorksheetOrderCommand } from './Commands/Commands/set-worksheet-order.command';
diff --git a/packages/base-ui/src/Components/Button/Button.tsx b/packages/base-ui/src/Components/Button/Button.tsx
index c654189131..0849063b32 100644
--- a/packages/base-ui/src/Components/Button/Button.tsx
+++ b/packages/base-ui/src/Components/Button/Button.tsx
@@ -101,7 +101,7 @@ class Button extends Component<BaseButtonProps, IState> {
);
};
- componentWillReceiveProps(props: BaseButtonProps) {
+ override componentWillReceiveProps(props: BaseButtonProps) {
this.setState({
isActive: props.active,
});
diff --git a/packages/base-ui/src/Components/Menu/Menu.tsx b/packages/base-ui/src/Components/Menu/Menu.tsx
index 2ff2ab05a9..281a22808d 100644
--- a/packages/base-ui/src/Components/Menu/Menu.tsx
+++ b/packages/base-ui/src/Components/Menu/Menu.tsx
@@ -1,8 +1,11 @@
-import { Component, createRef } from 'preact';
+import { Component, ComponentChild, createRef } from 'preact';
+import { Subscription } from 'rxjs';
+import { ICommandService } from '@univerjs/core';
import { BaseMenuProps, BaseMenuState, BaseMenuItem, BaseMenuStyle } from '../../Interfaces';
import { joinClassNames } from '../../Utils';
import { CustomLabel } from '../CustomLabel';
import styles from './index.module.less';
+import { IDisplayMenuItem } from '../../services/menu/menu.service';
export class Menu extends Component<BaseMenuProps, BaseMenuState> {
private _MenuRef = createRef<HTMLUListElement>();
@@ -103,11 +106,12 @@ export class Menu extends Component<BaseMenuProps, BaseMenuState> {
};
render() {
- const { className = '', style = '', menu, deep = 0 } = this.props;
+ const { className = '', style = '', menu, menuItems, deep = 0 } = this.props;
const { show, posStyle } = this.state;
return (
<ul className={joinClassNames(styles.colsMenu, className)} style={{ ...style, ...posStyle, display: show ? 'block' : 'none' }} ref={this._MenuRef}>
+ {/* NOTE: this will be dropped after we complete migrating to new UI system. */}
{menu?.map((item: BaseMenuItem, index: number) => {
if (item.show === false) return;
return (
@@ -142,6 +146,9 @@ export class Menu extends Component<BaseMenuProps, BaseMenuState> {
</>
);
})}
+ {menuItems?.map((item, index) => (
+ <MenuItem menuItem={item} onClick={() => this.showMenu(false)} />
+ ))}
</ul>
);
}
@@ -153,3 +160,44 @@ export class Menu extends Component<BaseMenuProps, BaseMenuState> {
};
}
}
+
+export class MenuItem extends Component<{ menuItem: IDisplayMenuItem; onClick: () => void }, { disabled: boolean }> {
+ private disabledSubscription: Subscription | undefined;
+
+ constructor() {
+ super();
+
+ this.state = {
+ disabled: false,
+ };
+ }
+
+ override componentDidMount(): void {
+ this.disabledSubscription = this.props.menuItem.disabled$?.subscribe((disabled) => {
+ this.setState({ disabled });
+ });
+ }
+
+ override componentWillUnmount(): void {
+ this.disabledSubscription?.unsubscribe();
+ }
+
+ override render(): ComponentChild {
+ const { menuItem: item } = this.props;
+ const commandService: ICommandService = this.context.injector.get(ICommandService);
+ const { disabled } = this.state;
+
+ return (
+ <li
+ className={joinClassNames(styles.colsMenuitem, disabled ? styles.colsMenuitemDisabled : '')}
+ onClick={() => {
+ this.props.onClick();
+ commandService.executeCommand(item.id);
+ }}
+ >
+ <CustomLabel label={item.title}></CustomLabel>
+ {item.shortcut && ` (${item.shortcut})`}
+ </li>
+ );
+ }
+}
diff --git a/packages/base-ui/src/Interfaces/Menu.ts b/packages/base-ui/src/Interfaces/Menu.ts
index e625d2a785..a1764e9621 100644
--- a/packages/base-ui/src/Interfaces/Menu.ts
+++ b/packages/base-ui/src/Interfaces/Menu.ts
@@ -1,5 +1,6 @@
import { ComponentChildren, JSX } from 'preact';
import { BaseComponent, JSXComponent } from '../BaseComponent';
+import { IDisplayMenuItem } from '../services/menu/menu.service';
export interface BaseMenuItem {
className?: string;
@@ -14,7 +15,9 @@ export interface BaseMenuItem {
}
export interface BaseMenuProps {
+ /** @deprecated this is legacy menu mechanism. Do not use it. Use `menuItems` instead. */
menu?: BaseMenuItem[];
+ menuItems?: IDisplayMenuItem[];
onClick?: (...arg: any) => void;
className?: string;
style?: JSX.CSSProperties;
diff --git a/packages/base-ui/src/controllers/shared.controller.ts b/packages/base-ui/src/controllers/shared-shortcut.controller.ts
similarity index 100%
rename from packages/base-ui/src/controllers/shared.controller.ts
rename to packages/base-ui/src/controllers/shared-shortcut.controller.ts
diff --git a/packages/base-ui/src/hooks/use-dependency.ts b/packages/base-ui/src/hooks/use-dependency.ts
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/packages/base-ui/src/index.ts b/packages/base-ui/src/index.ts
index e8c65d7b76..f05aa731de 100644
--- a/packages/base-ui/src/index.ts
+++ b/packages/base-ui/src/index.ts
@@ -8,9 +8,9 @@ export * from './Components';
export * from './BaseComponent';
export * from './UIPlugin';
-export { IMenuService, IMenuItem, MenuPosition, DesktopMenuService } from './services/menu/menu.service';
+export { IMenuService, IMenuItem, MenuPosition, DesktopMenuService, IDisplayMenuItem } from './services/menu/menu.service';
export { KeyCode, MetaKeys } from './services/shortcut/keycode';
export { IShortcutService, IShortcutItem, DesktopShortcutService } from './services/shortcut/shorcut.service';
export { IPlatformService, DesktopPlatformService } from './services/platform/platform.service';
-export { SharedController } from './controllers/shared.controller';
+export { SharedController } from './controllers/shared-shortcut.controller';
diff --git a/packages/base-ui/src/services/menu/menu.service.ts b/packages/base-ui/src/services/menu/menu.service.ts
index 86ba3d93ad..c135797f64 100644
--- a/packages/base-ui/src/services/menu/menu.service.ts
+++ b/packages/base-ui/src/services/menu/menu.service.ts
@@ -1,6 +1,7 @@
import { Disposable, toDisposable } from '@univerjs/core';
import { createIdentifier, IDisposable } from '@wendellhu/redi';
import { Observable } from 'rxjs';
+import { IShortcutService } from '../shortcut/shorcut.service';
export type OneOrMany<T> = T | T[];
@@ -21,17 +22,21 @@ export interface IMenuItemState {
export interface IMenuItem {
id: string;
menu: OneOrMany<MenuPosition>;
- title: string;
+ subMenus?: string[];
+ title: string;
icon?: string;
tooltip?: string;
description?: string;
+ hidden$?: Observable<boolean>;
+ activated$?: Observable<boolean>;
disabled$?: Observable<boolean>;
- hidden?: Observable<boolean>;
- checked?: Observable<boolean>; // TODO: @wzhudev: maybe we should add a `data` property here instead of `checked` property?
+}
- handler?: () => void;
+export interface IDisplayMenuItem extends IMenuItem {
+ /** MenuService should get responsible shortcut and display on the UI. */
+ shortcut?: string;
}
export const IMenuService = createIdentifier<IMenuService>('univer.menu-service');
@@ -48,6 +53,10 @@ export class DesktopMenuService extends Disposable implements IMenuService {
private readonly _menuByPositions = new Map<MenuPosition, Map<string, IMenuItem>>();
+ constructor(@IShortcutService private readonly _shortcutService: IShortcutService) {
+ super();
+ }
+
override dispose(): void {
this._menuItemMap.clear();
}
@@ -74,12 +83,12 @@ export class DesktopMenuService extends Disposable implements IMenuService {
});
}
- getMenuItems(positions: MenuPosition): IMenuItem[] {
+ getMenuItems(positions: MenuPosition): IDisplayMenuItem[] {
if (this._menuByPositions.has(positions)) {
- return [...this._menuByPositions.get(positions)!.values()];
+ return [...this._menuByPositions.get(positions)!.values()].map((menu) => this.getDisplayMenuItems(menu));
}
- return [] as IMenuItem[];
+ return [] as IDisplayMenuItem[];
}
getMenuItem(id: string): IMenuItem | null {
@@ -90,6 +99,18 @@ export class DesktopMenuService extends Disposable implements IMenuService {
return null;
}
+ private getDisplayMenuItems(menuItem: IMenuItem): IDisplayMenuItem {
+ const shortcut = this._shortcutService.getCommandShortcut(menuItem.id);
+ if (!shortcut) {
+ return menuItem;
+ }
+
+ return {
+ ...menuItem,
+ shortcut,
+ };
+ }
+
private appendMenuToPosition(menu: IMenuItem, position: MenuPosition) {
if (!this._menuByPositions.has(position)) {
this._menuByPositions.set(position, new Map<string, IMenuItem>());
@@ -102,4 +123,4 @@ export class DesktopMenuService extends Disposable implements IMenuService {
menuSet.set(menu.id, menu);
}
-}
\ No newline at end of file
+}
diff --git a/packages/base-ui/src/services/shortcut/keycode.ts b/packages/base-ui/src/services/shortcut/keycode.ts
index 3974331a16..5909b9a004 100644
--- a/packages/base-ui/src/services/shortcut/keycode.ts
+++ b/packages/base-ui/src/services/shortcut/keycode.ts
@@ -10,10 +10,11 @@ export const enum KeyCode {
TAB = 17,
ESC = 27,
SPACE = 32,
- LEFT = 37,
- UP = 38,
- RIGHT = 39,
- DOWN = 40,
+
+ ARROW_LEFT = 37,
+ ARROW_UP = 38,
+ ARROW_RIGHT = 39,
+ ARROW_DOWN = 40,
INSERT = 45,
Digit0 = 48,
@@ -80,4 +81,4 @@ export const enum MetaKeys {
/** Command key on MacOS. Ctrl key on other systems. */
CTRL_COMMAND = 1 << 12,
MAC_CTRL = 1 << 13,
-}
+}
\ No newline at end of file
diff --git a/packages/base-ui/src/services/shortcut/shorcut.service.ts b/packages/base-ui/src/services/shortcut/shorcut.service.ts
index ab61d40bab..fb71a5acae 100644
--- a/packages/base-ui/src/services/shortcut/shorcut.service.ts
+++ b/packages/base-ui/src/services/shortcut/shorcut.service.ts
@@ -5,21 +5,25 @@ import { fromDocumentEvent } from '../../Common/lifecycle';
import { IPlatformService } from '../platform/platform.service';
import { MetaKeys } from './keycode';
-export interface IShortcutItem {
+export interface IShortcutItem<P extends object = object> {
/** This should reuse the corresponding command's id. */
id: string;
+ description?: string;
+ /** A command can be bound to several bindings, with different static parameters perhaps. */
binding: number;
-
mac?: number;
win?: number;
linux?: number;
+
+ /** Static parameters of this shortcut. Would be send to `CommandService.executeCommand`. */
+ staticParameters?: P;
}
export interface IShortcutService {
registerShortcut(shortcut: IShortcutItem): IDisposable;
- getCommandShortcut(id: string): string;
+ getCommandShortcut(id: string): string | null;
}
export const IShortcutService = createIdentifier<IShortcutService>('univer.shortcut');
@@ -29,6 +33,8 @@ export class DesktopShortcutService extends Disposable implements IShortcutServi
private readonly _shortCutMapping = new Map<number, IShortcutItem>();
+ private readonly _idToShortcut = new Map<string, number>();
+
constructor(@ICommandService private readonly _commandService: ICommandService, @IPlatformService private readonly _platformService: IPlatformService) {
super();
@@ -43,14 +49,29 @@ export class DesktopShortcutService extends Disposable implements IShortcutServi
// first map shortcut to a number, so it could be converted and fetched quickly
const binding = this.getBindingFromItem(shortcut);
this._shortCutMapping.set(binding, shortcut);
+ this._idToShortcut.set(shortcut.id, binding);
return toDisposable(() => {
+ this._idToShortcut.delete(shortcut.id);
this._shortCutMapping.delete(binding);
});
}
- getCommandShortcut(id: string): string {
- return '';
+ getCommandShortcut(id: string): string | null {
+ const binding = this._idToShortcut.get(id);
+ if (!binding) {
+ return null;
+ }
+
+ const ctrlKey = binding & MetaKeys.CTRL_COMMAND;
+ const shiftKey = binding & MetaKeys.SHIFT;
+ const altKey = binding & MetaKeys.ALT;
+ const macCtrl = binding & MetaKeys.MAC_CTRL;
+
+ if (this._platformService.isMac) {
+ return `${ctrlKey ? '⌘' : ''}${shiftKey ? '⇧' : ''}${altKey ? '⌥' : ''}${macCtrl ? '⌃' : ''}${String.fromCharCode(binding & 0xff)}`;
+ }
+ return `${ctrlKey ? 'Ctrl+' : ''}${shiftKey ? 'Shift+' : ''}${altKey ? 'Alt+' : ''}${String.fromCharCode(binding & 0xff)}`;
}
private resolveMouseEvent(e: KeyboardEvent): void {
@@ -71,7 +92,8 @@ export class DesktopShortcutService extends Disposable implements IShortcutServi
return false;
}
- this._commandService.executeCommand(shortcut.id);
+ // shortcut could support static parameters
+ this._commandService.executeCommand(shortcut.id, shortcut.staticParameters);
return true;
}
@@ -115,4 +137,4 @@ export class DesktopShortcutService extends Disposable implements IShortcutServi
return binding;
}
-}
\ No newline at end of file
+}
diff --git a/packages/core/src/Basics/Univer.ts b/packages/core/src/Basics/Univer.ts
index 1ae71992fc..9588c44404 100644
--- a/packages/core/src/Basics/Univer.ts
+++ b/packages/core/src/Basics/Univer.ts
@@ -13,6 +13,8 @@ import { CurrentUniverService, ICurrentUniverService } from '../Service/Current.
import { UniverSlide } from './UniverSlide';
import { CommandService, ICommandService } from '../Service/Command/Command.service';
import { IUndoRedoService, LocalUndoRedoService } from '../Service/UndoRedo/undoRedo.service';
+import { DesktopLogService, ILogService } from '../Service/log/log.service';
+import { DesktopPermissionService, IPermissionService } from '../Service/permission/perimission.service';
/**
* Univer.
@@ -138,8 +140,10 @@ export class Univer {
[CommandManager],
[LocaleService],
[UndoManager],
- [ICommandService, { useClass: CommandService }],
+ [ILogService, { useClass: DesktopLogService, lazy: true }],
+ [ICommandService, { useClass: CommandService, lazy: true }],
[IUndoRedoService, { useClass: LocalUndoRedoService, lazy: true }],
+ [IPermissionService, { useClass: DesktopPermissionService }],
]);
}
diff --git a/packages/core/src/Basics/WorkBookObserver.ts b/packages/core/src/Basics/WorkBookObserver.ts
index 9156e8dd07..71a0045233 100644
--- a/packages/core/src/Basics/WorkBookObserver.ts
+++ b/packages/core/src/Basics/WorkBookObserver.ts
@@ -32,7 +32,4 @@ export type WorkBookObserver = {
onBeforeChangeSheetNameObservable: Observable<void>;
onAfterChangeSheetNameObservable: Observable<{ name: string; sheet: Worksheet }>;
-
- onBeforeRemoveSheetObservable: Observable<{ index: number }>;
- onAfterRemoveSheetObservable: Observable<{ index: number; sheetId: string }>;
};
diff --git a/packages/core/src/Basics/WorkBookObserverImpl.ts b/packages/core/src/Basics/WorkBookObserverImpl.ts
index e8c6d63cfc..0b14947920 100644
--- a/packages/core/src/Basics/WorkBookObserverImpl.ts
+++ b/packages/core/src/Basics/WorkBookObserverImpl.ts
@@ -18,9 +18,6 @@ export class WorkBookObserverImpl {
manager.addObserver('onBeforeInsertSheetObservable', 'core', new Observable());
manager.addObserver('onAfterInsertSheetObservable', 'core', new Observable());
- manager.addObserver('onBeforeRemoveSheetObservable', 'core', new Observable());
- manager.addObserver('onAfterRemoveSheetObservable', 'core', new Observable());
-
manager.addObserver('onBeforeChangeSheetColorObservable', 'core', new Observable());
manager.addObserver('onAfterChangeSheetColorObservable', 'core', new Observable());
diff --git a/packages/core/src/Observer/ObserverManager.ts b/packages/core/src/Observer/ObserverManager.ts
index 9f801d6fa3..2ab5fe9810 100644
--- a/packages/core/src/Observer/ObserverManager.ts
+++ b/packages/core/src/Observer/ObserverManager.ts
@@ -21,6 +21,8 @@ export class PathObservable<T = any> {
/**
* Manage a set of PathObservables, Get, remove, add WorkBookObserver
+ *
+ * @deprecated ObserverManager is not necessary. Each service should manage its own observables.
*/
export class ObserverManager {
private _observableArray: PathObservable[] = [];
@@ -113,4 +115,4 @@ export class ObserverManager {
this._observableArray.push(new PathObservable<T>(name, namespace, observable));
}
}
-}
+}
\ No newline at end of file
diff --git a/packages/core/src/Service/Command/Command.service.ts b/packages/core/src/Service/Command/Command.service.ts
index ae2997c804..8210f2a5d5 100644
--- a/packages/core/src/Service/Command/Command.service.ts
+++ b/packages/core/src/Service/Command/Command.service.ts
@@ -1,6 +1,7 @@
import { createIdentifier, IAccessor, IDisposable, Inject, Injector, Optional, SkipSelf } from '@wendellhu/redi';
import { ActionType, CommandManager, IActionData } from '../../Command';
import { toDisposable } from '../../Shared/Lifecycle';
+import { ILogService } from '../log/log.service';
export const enum CommandType {
/** Command could generate some operations or mutations. */
@@ -16,10 +17,9 @@ export interface ICommand<P extends object = object, R = boolean> {
* ${businessName}.${type}.${name}
*/
readonly id: string;
-
readonly type: CommandType;
- handler(accessor: IAccessor, params: P): Promise<R>;
+ handler(accessor: IAccessor, params?: P): Promise<R>;
}
/**
@@ -27,13 +27,14 @@ export interface ICommand<P extends object = object, R = boolean> {
*/
export interface IMutation<P extends object = object, R = boolean> extends ICommand<P, R> {
type: CommandType.MUTATION;
+ handler(accessor: IAccessor, params: P): Promise<R>; // mutations must have params
}
/**
* Operation would change the state of Univer applications. State should only be in memory and does not
- * require data confliction.
+ * require confliction resolution.
*/
-export interface IOperation<P extends object = object> extends ICommand<P> {
+export interface IOperation<P extends object = object, R = boolean> extends ICommand<P, R> {
type: CommandType.OPERATION;
}
@@ -57,7 +58,8 @@ export interface IExecutionOptions {
export type CommandListener = (commandInfo: Readonly<ICommandInfo>) => void;
export interface ICommandService {
- registerCommand<P extends object>(command: ICommand<P>): IDisposable;
+ registerCommand(command: ICommand): IDisposable;
+
executeCommand(id: string, params?: object, options?: IExecutionOptions): Promise<boolean> | boolean;
/**
@@ -91,13 +93,14 @@ export const ICommandService = createIdentifier<ICommandService>('anywhere.comma
* The registry of commands.
*/
class CommandRegistry {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
private readonly commands = new Map<string, ICommand>();
private readonly commandInjector = new Map<string, Injector>();
registerCommand(command: ICommand, injector: Injector): IDisposable {
if (this.commands.has(command.id) || this.commandInjector.has(command.id)) {
- throw new Error();
+ throw new Error(`Command ${command.id} has registered before!`);
}
this.commands.set(command.id, command);
@@ -125,7 +128,13 @@ export class CommandService implements ICommandService {
private readonly _commandExecutedListeners: CommandListener[] = [];
- constructor(@SkipSelf() @Optional(ICommandService) private readonly _parentCommandService: CommandService, @Inject(Injector) private readonly _injector: Injector) {
+ private _commandExecutingLevel = 0;
+
+ constructor(
+ @SkipSelf() @Optional(ICommandService) private readonly _parentCommandService: CommandService,
+ @Inject(Injector) private readonly _injector: Injector,
+ @ILogService private readonly _log: ILogService
+ ) {
this._commandRegistry = new CommandRegistry();
}
@@ -213,7 +222,7 @@ export class CommandService implements ICommandService {
throw new Error(`Command "${id}" is not registered.`);
}
- private _registerCommand<P extends object>(command: ICommand<P>, injector: Injector): IDisposable {
+ private _registerCommand(command: ICommand, injector: Injector): IDisposable {
if (this._parentCommandService) {
return this._parentCommandService._registerCommand(command, injector);
}
@@ -222,14 +231,25 @@ export class CommandService implements ICommandService {
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- private async _execute(command: ICommand<any>, injector: Injector, params?: object): Promise<boolean> {
- const result = await injector.invoke(command.handler, params);
+ private async _execute(command: ICommand, injector: Injector, params?: object): Promise<boolean> {
+ this._log.log(`%c${' | '.repeat(this._commandExecutingLevel)}[ICommandService]: executing command "${command.id}".`, 'color:cyan');
+
+ this._commandExecutingLevel++;
+ let result: boolean;
+ try {
+ result = await injector.invoke(command.handler, params);
+ this._commandExecutingLevel--;
+ } catch (e) {
+ result = false;
+ this._commandExecutingLevel = 0;
+ }
- // MOTE: remove from old command manager
+ // TODO: remove from old command manager
if (command.type === CommandType.MUTATION) {
CommandManager.getActionObservers().notifyObservers({
type: ActionType.REDO,
data: result as unknown as IActionData,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
action: null as any,
});
}
diff --git a/packages/core/src/Service/log/log.service.ts b/packages/core/src/Service/log/log.service.ts
index 9d45683ca0..270ea23a1a 100644
--- a/packages/core/src/Service/log/log.service.ts
+++ b/packages/core/src/Service/log/log.service.ts
@@ -1,7 +1,45 @@
-import { createIdentifier } from "@wendellhu/redi";
+/* eslint-disable @typescript-eslint/no-explicit-any */
+
+import { createIdentifier } from '@wendellhu/redi';
+import { Disposable } from '../../Shared/Lifecycle';
export interface ILogService {
+ log(...args: any[]): void;
+ warn(...args: any[]): void;
+ error(...args: any[]): void;
+ toggleLogEnabled(enabled: boolean): void;
+ getLogEnabled(): boolean;
}
export const ILogService = createIdentifier<ILogService>('univer.log');
+
+export class DesktopLogService extends Disposable implements ILogService {
+ private logEnabled = true;
+
+ log(...args: any[]): void {
+ if (this.logEnabled) {
+ console.log(...args);
+ }
+ }
+
+ warn(...args: any[]): void {
+ if (this.logEnabled) {
+ console.warn(...args);
+ }
+ }
+
+ error(...args: any[]): void {
+ if (this.logEnabled) {
+ console.error(...args);
+ }
+ }
+
+ toggleLogEnabled(enabled: boolean): void {
+ this.logEnabled = enabled;
+ }
+
+ getLogEnabled(): boolean {
+ return this.logEnabled;
+ }
+}
diff --git a/packages/core/src/Service/permission/perimission.service.ts b/packages/core/src/Service/permission/perimission.service.ts
new file mode 100644
index 0000000000..b8a04a2a9c
--- /dev/null
+++ b/packages/core/src/Service/permission/perimission.service.ts
@@ -0,0 +1,28 @@
+import { createIdentifier } from '@wendellhu/redi';
+import { BehaviorSubject, Observable } from 'rxjs';
+import { Disposable } from '../../Shared/Lifecycle';
+
+export interface IPermissionService {
+ readonly editable$: Observable<boolean>;
+
+ setEditable(editable: boolean): void;
+}
+
+export const IPermissionService = createIdentifier<IPermissionService>('univer.permission-service');
+
+export class DesktopPermissionService extends Disposable implements IPermissionService {
+ readonly editable$: Observable<boolean>;
+
+ private readonly _editable$: BehaviorSubject<boolean>;
+
+ constructor() {
+ super();
+
+ this._editable$ = new BehaviorSubject(true);
+ this.editable$ = this._editable$.asObservable();
+ }
+
+ setEditable(editable: boolean): void {
+ this._editable$.next(true);
+ }
+}
diff --git a/packages/core/src/Shared/ObjectMatrix.ts b/packages/core/src/Shared/ObjectMatrix.ts
index c40379dcb0..3fd304fb15 100644
--- a/packages/core/src/Shared/ObjectMatrix.ts
+++ b/packages/core/src/Shared/ObjectMatrix.ts
@@ -73,16 +73,16 @@ export class ObjectMatrix<T> {
}
getRow(rowIndex: number): Nullable<ObjectArray<T>> {
- let element = this._option.get(rowIndex);
+ const element = this._option.get(rowIndex);
if (element) {
return new ObjectArray(element);
}
}
getRowOrCreate(rowIndex: number): ObjectArray<T> {
- let row = this.getRow(rowIndex);
+ const row = this.getRow(rowIndex);
if (row == null) {
- let row = {};
+ const row = {};
this._option.set(rowIndex, row as ObjectArrayPrimitiveType<T>);
return new ObjectArray(row);
}
@@ -128,6 +128,11 @@ export class ObjectMatrix<T> {
return new ObjectMatrix(splice.toJSON() as ObjectMatrixPrimitiveType<T>);
}
+ sliceRows(start: number, count: number): ObjectMatrix<T> {
+ const slice = this._option.slice(start, count);
+ return new ObjectMatrix(slice.toJSON() as ObjectMatrixPrimitiveType<T>);
+ }
+
pushRow(row: ObjectArray<T>): void {
this._option.push(row.toJSON() as ObjectArrayPrimitiveType<T>);
}
@@ -136,6 +141,10 @@ export class ObjectMatrix<T> {
this._option.insert(rowIndex, row.toJSON() as ObjectArrayPrimitiveType<T>);
}
+ insertRowCount(rowIndex: number, rowCount: number): void {
+ this._option.inserts(rowIndex, new ObjectArray(rowCount));
+ }
+
insertRows(rowIndex: number, matrix: ObjectMatrix<T>) {
this._option.inserts(rowIndex, matrix._option);
console.dir(this._option);
@@ -147,12 +156,21 @@ export class ObjectMatrix<T> {
for (let i = start; i < start + count; i++) {
columnData.setValue(index, i - start, this.getValue(index, i));
}
- let row = this._option.get(index);
+ const row = this._option.get(index);
if (row) {
new ObjectArray(row).splice(start, count);
}
});
+ return columnData;
+ }
+ sliceColumns(start: number, count: number): ObjectMatrix<T> {
+ const columnData = new ObjectMatrix<T>();
+ this._option.forEach((index, value) => {
+ for (let i = start; i < start + count; i++) {
+ columnData.setValue(index, i - start, this.getValue(index, i));
+ }
+ });
return columnData;
}
@@ -165,7 +183,6 @@ export class ObjectMatrix<T> {
return false;
}
});
-
this.forEach((index, value) => {
for (let i = columnIndex; i < columnIndex + count; i++) {
const data = columnData.getRow(index)?.get(i - columnIndex);
@@ -174,6 +191,12 @@ export class ObjectMatrix<T> {
});
}
+ insertColumnCount(columnIndex: number, columnCount: number) {
+ this.forEach((index, value) => {
+ value.inserts(columnIndex, new ObjectArray<T>(columnCount));
+ });
+ }
+
getFragments(startRow: number, endRow: number, startColumn: number, endColumn: number): ObjectMatrix<T> {
const objectMatrix = new ObjectMatrix<T>();
for (let r = startRow; r <= endRow; r++) {
@@ -299,4 +322,4 @@ export class ObjectMatrix<T> {
this._matrix = matrix;
this._option = new ObjectArray<ObjectArrayPrimitiveType<T>>(matrix);
}
-}
\ No newline at end of file
+}
diff --git a/packages/core/src/Shared/Tools.ts b/packages/core/src/Shared/Tools.ts
index 5efc8815c7..211e7bd615 100644
--- a/packages/core/src/Shared/Tools.ts
+++ b/packages/core/src/Shared/Tools.ts
@@ -7,34 +7,7 @@ import { ObjectArray, ObjectArrayPrimitiveType } from './ObjectArray';
const rmsPrefix = /^-ms-/;
const rDashAlpha = /-([a-z])/g;
-const alphabets = [
- 'A',
- 'B',
- 'C',
- 'D',
- 'E',
- 'F',
- 'G',
- 'H',
- 'I',
- 'J',
- 'K',
- 'L',
- 'M',
- 'N',
- 'O',
- 'P',
- 'Q',
- 'R',
- 'S',
- 'T',
- 'U',
- 'V',
- 'W',
- 'X',
- 'Y',
- 'Z',
-];
+const alphabets = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
/**
* Universal tool library
@@ -85,46 +58,27 @@ export class Tools {
static getSystemType(): string {
const sUserAgent = navigator.userAgent;
- const isWin =
- navigator.platform === 'Win32' || navigator.platform === 'Windows';
- const isMac =
- navigator.platform === 'Mac68K' ||
- navigator.platform === 'MacPPC' ||
- navigator.platform === 'Macintosh' ||
- navigator.platform === 'MacIntel';
+ const isWin = navigator.platform === 'Win32' || navigator.platform === 'Windows';
+ const isMac = navigator.platform === 'Mac68K' || navigator.platform === 'MacPPC' || navigator.platform === 'Macintosh' || navigator.platform === 'MacIntel';
if (isMac) return 'Mac';
const isUnix = navigator.platform === 'X11' && !isWin && !isMac;
if (isUnix) return 'Unix';
const isLinux = String(navigator.platform).indexOf('Linux') > -1;
if (isLinux) return 'Linux';
if (isWin) {
- const isWin2K =
- sUserAgent.indexOf('Windows NT 5.0') > -1 ||
- sUserAgent.indexOf('Windows 2000') > -1;
+ const isWin2K = sUserAgent.indexOf('Windows NT 5.0') > -1 || sUserAgent.indexOf('Windows 2000') > -1;
if (isWin2K) return 'Windows 2000';
- const isWinXP =
- sUserAgent.indexOf('Windows NT 5.1') > -1 ||
- sUserAgent.indexOf('Windows XP') > -1;
+ const isWinXP = sUserAgent.indexOf('Windows NT 5.1') > -1 || sUserAgent.indexOf('Windows XP') > -1;
if (isWinXP) return 'Windows XP';
- const isWin2003 =
- sUserAgent.indexOf('Windows NT 5.2') > -1 ||
- sUserAgent.indexOf('Windows 2003') > -1;
+ const isWin2003 = sUserAgent.indexOf('Windows NT 5.2') > -1 || sUserAgent.indexOf('Windows 2003') > -1;
if (isWin2003) return 'Windows 2003';
- const isWinVista =
- sUserAgent.indexOf('Windows NT 6.0') > -1 ||
- sUserAgent.indexOf('Windows Vista') > -1;
+ const isWinVista = sUserAgent.indexOf('Windows NT 6.0') > -1 || sUserAgent.indexOf('Windows Vista') > -1;
if (isWinVista) return 'Windows Vista';
- const isWin7 =
- sUserAgent.indexOf('Windows NT 6.1') > -1 ||
- sUserAgent.indexOf('Windows 7') > -1;
+ const isWin7 = sUserAgent.indexOf('Windows NT 6.1') > -1 || sUserAgent.indexOf('Windows 7') > -1;
if (isWin7) return 'Windows 7';
- const isWin10 =
- sUserAgent.indexOf('Windows NT 10') > -1 ||
- sUserAgent.indexOf('Windows 10') > -1;
+ const isWin10 = sUserAgent.indexOf('Windows NT 10') > -1 || sUserAgent.indexOf('Windows 10') > -1;
if (isWin10) return 'Windows 10';
- const isWin11 =
- sUserAgent.indexOf('Windows NT 11') > -1 ||
- sUserAgent.indexOf('Windows 11') > -1;
+ const isWin11 = sUserAgent.indexOf('Windows NT 11') > -1 || sUserAgent.indexOf('Windows 11') > -1;
if (isWin11) return 'Windows 11';
}
return 'Unknown system';
@@ -133,18 +87,12 @@ export class Tools {
static getBrowserType(): string {
const userAgent = navigator.userAgent;
const isOpera = userAgent.indexOf('Opera') > -1;
- const isIE =
- userAgent.indexOf('compatible') > -1 &&
- userAgent.indexOf('MSIE') > -1 &&
- !isOpera;
- const isIE11 =
- userAgent.indexOf('Trident') > -1 && userAgent.indexOf('rv:11.0') > -1;
+ const isIE = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 && !isOpera;
+ const isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf('rv:11.0') > -1;
const isEdge = userAgent.indexOf('Edge') > -1;
const isFF = userAgent.indexOf('Firefox') > -1;
- const isSafari =
- userAgent.indexOf('Safari') > -1 && userAgent.indexOf('Chrome') === -1;
- const isChrome =
- userAgent.indexOf('Chrome') > -1 && userAgent.indexOf('Safari') > -1;
+ const isSafari = userAgent.indexOf('Safari') > -1 && userAgent.indexOf('Chrome') === -1;
+ const isChrome = userAgent.indexOf('Chrome') > -1 && userAgent.indexOf('Safari') > -1;
if (isIE) {
const reIE = new RegExp('MSIE (\\d+\\.\\d+);');
reIE.test(userAgent);
@@ -275,10 +223,7 @@ export class Tools {
return (oneValue as Date).getTime() === towValue.getTime();
}
if (Tools.isRegExp(oneValue)) {
- return (
- (oneValue as unknown as string).toString() ===
- towValue.toString()
- );
+ return (oneValue as unknown as string).toString() === towValue.toString();
}
return oneValue === towValue;
}
@@ -351,11 +296,7 @@ export class Tools {
static getLanguage(): string {
const defaultValue = 'en-US';
if (globalThis.navigator) {
- return (
- (navigator.languages && navigator.languages[0]) ||
- navigator.language ||
- defaultValue
- );
+ return (navigator.languages && navigator.languages[0]) || navigator.language || defaultValue;
}
return defaultValue;
}
@@ -442,25 +383,16 @@ export class Tools {
if (document.body.clientHeight) {
clientHeight = document.body.clientHeight;
}
- return (
- this.isAndroid() ||
- this.isIPhone() ||
- this.isTablet() ||
- (clientWidth < 350 && clientHeight < 500)
- );
+ return this.isAndroid() || this.isIPhone() || this.isTablet() || (clientWidth < 350 && clientHeight < 500);
}
static isTablet(): boolean {
- return /ipad|android|android 3.0|xoom|sch-i800|playbook|tablet|kindle/i.test(
- navigator.userAgent.toLowerCase()
- );
+ return /ipad|android|android 3.0|xoom|sch-i800|playbook|tablet|kindle/i.test(navigator.userAgent.toLowerCase());
}
static isWeChat(): boolean {
const userAgent = navigator.userAgent.toLowerCase();
- return String(userAgent.match(/MicroMessenger/i)) === 'micromessenger'
- ? !0
- : !1;
+ return String(userAgent.match(/MicroMessenger/i)) === 'micromessenger' ? !0 : !1;
}
static isAndroid(): boolean {
@@ -538,14 +470,8 @@ export class Tools {
* @param value value to be set
* @returns
*/
- static fillTwoDimensionalArray(
- rows: number,
- columns: number,
- value: any
- ): any[][] {
- return new Array(rows)
- .fill(value)
- .map((item) => new Array(columns).fill(value));
+ static fillTwoDimensionalArray(rows: number, columns: number, value: any): any[][] {
+ return new Array(rows).fill(value).map((item) => new Array(columns).fill(value));
}
/**
@@ -555,11 +481,7 @@ export class Tools {
* @param value value to be set
* @returns
*/
- static fillObjectMatrix<T>(
- rows: number,
- columns: number,
- value: T
- ): ObjectMatrixPrimitiveType<T> {
+ static fillObjectMatrix<T>(rows: number, columns: number, value: T): ObjectMatrixPrimitiveType<T> {
const matrix = new ObjectMatrix<T>();
for (let r = 0; r < rows; r++) {
for (let c = 0; c < columns; c++) {
@@ -654,13 +576,13 @@ export class Tools {
* @returns
*/
static commonExtend<T>(originJson: IKeyValue, extendJson: IKeyValue): T {
- let resultJsonObject: IKeyValue = {};
+ const resultJsonObject: IKeyValue = {};
- for (let attr in originJson) {
+ for (const attr in originJson) {
resultJsonObject[attr] = originJson[attr];
}
- for (let attr in extendJson) {
+ for (const attr in extendJson) {
// undefined is equivalent to no setting
if (extendJson[attr] == null) {
continue;
@@ -672,7 +594,7 @@ export class Tools {
}
static commonExtend1<T>(originJson: IKeyValue, extendJson: IKeyValue): T {
- for (let attr in originJson) {
+ for (const attr in originJson) {
if (extendJson[attr] == null) {
extendJson[attr] = originJson[attr];
}
@@ -691,9 +613,7 @@ export class Tools {
return obj;
}
- static createObjectArray<T>(
- array: ObjectArrayPrimitiveType<T> | ObjectArray<T>
- ): ObjectArray<T> {
+ static createObjectArray<T>(array: ObjectArrayPrimitiveType<T> | ObjectArray<T>): ObjectArray<T> {
if (array instanceof ObjectArray) {
return new ObjectArray<T>(array.toJSON());
}
diff --git a/packages/core/src/Sheets/Action/InsertRangeAction.ts b/packages/core/src/Sheets/Action/InsertRangeAction.ts
index 2c35d1d390..32a353b173 100644
--- a/packages/core/src/Sheets/Action/InsertRangeAction.ts
+++ b/packages/core/src/Sheets/Action/InsertRangeAction.ts
@@ -22,17 +22,10 @@ export interface IInsertRangeActionData extends ISheetActionData {
*
* @internal
*/
-export class InsertRangeAction extends SheetActionBase<
- IInsertRangeActionData,
- IDeleteRangeActionData
-> {
+export class InsertRangeAction extends SheetActionBase<IInsertRangeActionData, IDeleteRangeActionData> {
static NAME = 'InsertRangeAction';
- constructor(
- actionData: IInsertRangeActionData,
- commandUnit: CommandUnit,
- observers: ActionObservers
- ) {
+ constructor(actionData: IInsertRangeActionData, commandUnit: CommandUnit, observers: ActionObservers) {
super(actionData, commandUnit, observers);
this._doActionData = {
...actionData,
diff --git a/packages/core/src/Sheets/Action/SetRangeFormattedValueAction.ts b/packages/core/src/Sheets/Action/SetRangeFormattedValueAction.ts
index 1663b5ea86..b84dffa426 100644
--- a/packages/core/src/Sheets/Action/SetRangeFormattedValueAction.ts
+++ b/packages/core/src/Sheets/Action/SetRangeFormattedValueAction.ts
@@ -17,18 +17,10 @@ export interface ISetRangeFormattedValueActionData extends ISheetActionData {
/**
*
*/
-export class SetRangeFormattedValueAction extends SheetActionBase<
- ISetRangeFormattedValueActionData,
- ISetRangeFormattedValueActionData,
- ObjectMatrixPrimitiveType<ICellV>
-> {
+export class SetRangeFormattedValueAction extends SheetActionBase<ISetRangeFormattedValueActionData, ISetRangeFormattedValueActionData, ObjectMatrixPrimitiveType<ICellV>> {
static NAME = 'SetRangeFormattedValueAction';
- constructor(
- actionData: ISetRangeFormattedValueActionData,
- commandUnit: CommandUnit,
- observers: ActionObservers
- ) {
+ constructor(actionData: ISetRangeFormattedValueActionData, commandUnit: CommandUnit, observers: ActionObservers) {
super(actionData, commandUnit, observers);
this._doActionData = {
@@ -45,11 +37,7 @@ export class SetRangeFormattedValueAction extends SheetActionBase<
do(): ObjectMatrixPrimitiveType<ICellV> {
const worksheet = this.getWorkSheet();
- const result = SetRangeFormattedValue(
- worksheet.getCellMatrix(),
- this._doActionData.cellValue,
- this._doActionData.rangeData
- );
+ const result = SetRangeFormattedValue(worksheet.getCellMatrix(), this._doActionData.cellValue, this._doActionData.rangeData);
this._observers.notifyObservers({
type: ActionType.REDO,
@@ -81,11 +69,7 @@ export class SetRangeFormattedValueAction extends SheetActionBase<
// actionName: ACTION_NAMES.SET_RANGE_DATA_ACTION,
actionName: SetRangeDataAction.NAME,
sheetId,
- cellValue: SetRangeFormattedValue(
- worksheet.getCellMatrix(),
- cellValue,
- rangeData
- ),
+ cellValue: SetRangeFormattedValue(worksheet.getCellMatrix(), cellValue, rangeData),
rangeData,
};
@@ -102,7 +86,4 @@ export class SetRangeFormattedValueAction extends SheetActionBase<
}
}
-CommandManager.register(
- SetRangeFormattedValueAction.NAME,
- SetRangeFormattedValueAction
-);
+CommandManager.register(SetRangeFormattedValueAction.NAME, SetRangeFormattedValueAction);
diff --git a/packages/core/src/Sheets/Action/SetSelectionActivateAction.ts b/packages/core/src/Sheets/Action/SetSelectionActivateAction.ts
index 76b91dc535..f8b840e0b8 100644
--- a/packages/core/src/Sheets/Action/SetSelectionActivateAction.ts
+++ b/packages/core/src/Sheets/Action/SetSelectionActivateAction.ts
@@ -25,18 +25,10 @@ export interface ISetSelectionActivateServiceData {
/**
* @internal
*/
-export class SetSelectionActivateAction extends SheetActionBase<
- ISetSelectionActivateActionData,
- ISetSelectionActivateActionData,
- ISetSelectionActivateServiceData
-> {
+export class SetSelectionActivateAction extends SheetActionBase<ISetSelectionActivateActionData, ISetSelectionActivateActionData, ISetSelectionActivateServiceData> {
static NAME = 'SetSelectionActivateAction';
- constructor(
- actionData: ISetSelectionActivateActionData,
- commandUnit: CommandUnit,
- observers: ActionObservers
- ) {
+ constructor(actionData: ISetSelectionActivateActionData, commandUnit: CommandUnit, observers: ActionObservers) {
super(actionData, commandUnit, observers);
this._doActionData = {
@@ -59,12 +51,7 @@ export class SetSelectionActivateAction extends SheetActionBase<
const { activeRangeList, activeRange, currentCell } = this._doActionData;
const worksheet = this.getWorkSheet();
- const result = SetSelectionActivate(
- worksheet,
- activeRangeList,
- activeRange,
- currentCell
- );
+ const result = SetSelectionActivate(worksheet, activeRangeList, activeRange, currentCell);
this._observers.notifyObservers({
type: ActionType.REDO,
@@ -90,16 +77,10 @@ export class SetSelectionActivateAction extends SheetActionBase<
}
undo(): void {
- const { activeRangeList, activeRange, currentCell, sheetId } =
- this._oldActionData;
+ const { activeRangeList, activeRange, currentCell, sheetId } = this._oldActionData;
const worksheet = this.getWorkSheet();
- const doData = SetSelectionActivate(
- worksheet,
- activeRangeList,
- activeRange,
- currentCell
- );
+ const doData = SetSelectionActivate(worksheet, activeRangeList, activeRange, currentCell);
// update current data
this._doActionData = {
// actionName: ACTION_NAMES.SET_SELECTION_ACTION,
@@ -122,4 +103,4 @@ export class SetSelectionActivateAction extends SheetActionBase<
}
}
-CommandManager.register(SetSelectionActivateAction.NAME, SetSelectionActivateAction);
+CommandManager.register(SetSelectionActivateAction.NAME, SetSelectionActivateAction);
\ No newline at end of file
diff --git a/packages/core/src/Sheets/Apply/AddMerge.ts b/packages/core/src/Sheets/Apply/AddMerge.ts
index 08bc0bcd3c..319eaccedc 100644
--- a/packages/core/src/Sheets/Apply/AddMerge.ts
+++ b/packages/core/src/Sheets/Apply/AddMerge.ts
@@ -12,7 +12,7 @@ import { IAddMergeActionData } from '../Action';
* @internal
*/
export function addMerge(merges: Merges, rectangles: IRangeData[]): IRangeData[] {
- let remove: IRangeData[] = [];
+ const remove: IRangeData[] = [];
for (let i = 0; i < rectangles.length; i++) {
merges.add(rectangles[i]);
// remove = remove.concat(merges.add(rectangles[i]));
@@ -20,15 +20,12 @@ export function addMerge(merges: Merges, rectangles: IRangeData[]): IRangeData[]
return remove;
}
-export function addMergeApply(
- unit: CommandUnit,
- data: IAddMergeActionData
-): IRangeData[] {
- let worksheet = unit?.WorkBookUnit?.getSheetBySheetId(data.sheetId);
+export function addMergeApply(unit: CommandUnit, data: IAddMergeActionData): IRangeData[] {
+ const worksheet = unit?.WorkBookUnit?.getSheetBySheetId(data.sheetId);
if (worksheet) {
- let config = worksheet.getConfig();
- let mergeConfigData = config.mergeData;
- let mergeAppendData = data.rectangles;
+ const config = worksheet.getConfig();
+ const mergeConfigData = config.mergeData;
+ const mergeAppendData = data.rectangles;
for (let i = 0; i < mergeAppendData.length; i++) {
mergeConfigData.push(mergeAppendData[i]);
}
diff --git a/packages/core/src/Sheets/Apply/DeleteRange.ts b/packages/core/src/Sheets/Apply/DeleteRange.ts
index 3274299223..ec4fa325e9 100644
--- a/packages/core/src/Sheets/Apply/DeleteRange.ts
+++ b/packages/core/src/Sheets/Apply/DeleteRange.ts
@@ -96,10 +96,7 @@ export function DeleteRange(
return result.getData();
}
-export function DeleteRangeApply(
- unit: CommandUnit,
- data: IDeleteRangeActionData
-): ObjectMatrixPrimitiveType<ICellData> {
+export function DeleteRangeApply(unit: CommandUnit, data: IDeleteRangeActionData): ObjectMatrixPrimitiveType<ICellData> {
const worksheet = unit.WorkBookUnit?.getSheetBySheetId(data.sheetId);
const cellMatrix = worksheet?.getCellMatrix();
const count = {
diff --git a/packages/core/src/Sheets/Apply/InsertColumn.ts b/packages/core/src/Sheets/Apply/InsertColumn.ts
index d4b4c7de36..00693bb399 100644
--- a/packages/core/src/Sheets/Apply/InsertColumn.ts
+++ b/packages/core/src/Sheets/Apply/InsertColumn.ts
@@ -11,19 +11,12 @@ import { IRemoveColumnAction } from '../Action';
*
* @internal
*/
-export function InsertColumn(
- columnIndex: number = 0,
- columnCount: number = 1,
- primitiveData: ObjectArrayPrimitiveType<IColumnData>
-) {
+export function InsertColumn(columnIndex: number = 0, columnCount: number = 1, primitiveData: ObjectArrayPrimitiveType<IColumnData>) {
const wrapper = new ObjectArray(primitiveData);
wrapper.inserts(columnIndex, new ObjectArray(columnCount));
}
-export function InsertColumnApply(
- unit: CommandUnit,
- data: IRemoveColumnAction
-): void {
+export function InsertColumnApply(unit: CommandUnit, data: IRemoveColumnAction): void {
const worksheet = unit.WorkBookUnit!.getSheetBySheetId(data.sheetId);
const columnManager = worksheet!.getColumnManager();
const primitiveData = columnManager.getColumnData().toJSON();
diff --git a/packages/core/src/Sheets/Apply/InsertDataColumn.ts b/packages/core/src/Sheets/Apply/InsertDataColumn.ts
index 3dc77890ec..cc56c7a4a8 100644
--- a/packages/core/src/Sheets/Apply/InsertDataColumn.ts
+++ b/packages/core/src/Sheets/Apply/InsertDataColumn.ts
@@ -11,19 +11,12 @@ import { IInsertColumnDataActionData } from '../Action';
*
* @internal
*/
-export function InsertDataColumn(
- columnIndex: number,
- columnData: ObjectMatrixPrimitiveType<ICellData>,
- primitiveData: ObjectMatrixPrimitiveType<ICellData>
-) {
+export function InsertDataColumn(columnIndex: number, columnData: ObjectMatrixPrimitiveType<ICellData>, primitiveData: ObjectMatrixPrimitiveType<ICellData>) {
const wrapper = new ObjectMatrix(primitiveData);
wrapper.insertColumns(columnIndex, new ObjectMatrix(columnData));
}
-export function InsertDataColumnApply(
- unit: CommandUnit,
- data: IInsertColumnDataActionData
-) {
+export function InsertDataColumnApply(unit: CommandUnit, data: IInsertColumnDataActionData) {
const worksheet = unit.WorkBookUnit!.getSheetBySheetId(data.sheetId);
const primitiveData = worksheet!.getCellMatrix().toJSON();
diff --git a/packages/core/src/Sheets/Apply/RemoveColumn.ts b/packages/core/src/Sheets/Apply/RemoveColumn.ts
index 38d120cf78..7736c40538 100644
--- a/packages/core/src/Sheets/Apply/RemoveColumn.ts
+++ b/packages/core/src/Sheets/Apply/RemoveColumn.ts
@@ -11,11 +11,7 @@ import { IRemoveColumnAction } from '../Action';
*
* @internal
*/
-export function RemoveColumn(
- columnIndex: number,
- columnCount: number,
- primitiveData: ObjectArrayPrimitiveType<IColumnData>
-): number {
+export function RemoveColumn(columnIndex: number, columnCount: number, primitiveData: ObjectArrayPrimitiveType<IColumnData>): number {
const wrapper = new ObjectArray(primitiveData);
const result = new ObjectArray<IColumnData>();
const start = columnIndex;
diff --git a/packages/core/src/Sheets/Apply/RemoveColumnData.ts b/packages/core/src/Sheets/Apply/RemoveColumnData.ts
index 389bbfb472..315521bfbc 100644
--- a/packages/core/src/Sheets/Apply/RemoveColumnData.ts
+++ b/packages/core/src/Sheets/Apply/RemoveColumnData.ts
@@ -12,23 +12,12 @@ import { IRemoveColumnDataAction } from '../Action';
*
* @internal
*/
-export function RemoveColumnData(
- columnIndex: number,
- columnCount: number,
- primitiveData: ObjectMatrixPrimitiveType<ICellData>
-): ObjectMatrixPrimitiveType<ICellData> {
- return new ObjectMatrix(primitiveData)
- .spliceColumns(columnIndex, columnCount)
- .toJSON();
+export function RemoveColumnData(columnIndex: number, columnCount: number, primitiveData: ObjectMatrixPrimitiveType<ICellData>): ObjectMatrixPrimitiveType<ICellData> {
+ return new ObjectMatrix(primitiveData).spliceColumns(columnIndex, columnCount).toJSON();
}
-export function RemoveColumnDataApply(
- unit: CommandUnit,
- data: IRemoveColumnDataAction
-): ObjectMatrixPrimitiveType<ICellData> {
+export function RemoveColumnDataApply(unit: CommandUnit, data: IRemoveColumnDataAction): ObjectMatrixPrimitiveType<ICellData> {
const worksheet = unit.WorkBookUnit!.getSheetBySheetId(data.sheetId);
const primitiveData = worksheet!.getCellMatrix().toJSON();
- return new ObjectMatrix(primitiveData)
- .spliceColumns(data.columnIndex, data.columnCount)
- .toJSON();
+ return new ObjectMatrix(primitiveData).spliceColumns(data.columnIndex, data.columnCount).toJSON();
}
diff --git a/packages/core/src/Sheets/Apply/RemoveMerge.ts b/packages/core/src/Sheets/Apply/RemoveMerge.ts
index 0f3eb04843..c9ca50cee5 100644
--- a/packages/core/src/Sheets/Apply/RemoveMerge.ts
+++ b/packages/core/src/Sheets/Apply/RemoveMerge.ts
@@ -3,20 +3,17 @@ import { CommandUnit } from '../../Command';
import { IRemoveMergeActionData } from '../Action';
import { Rectangle } from '../../Shared';
-export function RemoveMergeApply(
- unit: CommandUnit,
- data: IRemoveMergeActionData
-): IRangeData[] {
- let worksheet = unit.WorkBookUnit!.getSheetBySheetId(data.sheetId);
+export function RemoveMergeApply(unit: CommandUnit, data: IRemoveMergeActionData): IRangeData[] {
+ const worksheet = unit.WorkBookUnit!.getSheetBySheetId(data.sheetId);
if (worksheet) {
- let config = worksheet.getConfig();
- let remove: IRangeData[] = [];
- let mergeConfigData = config.mergeData;
- let mergeRemoveData = data.rectangles;
+ const config = worksheet.getConfig();
+ const remove: IRangeData[] = [];
+ const mergeConfigData = config.mergeData;
+ const mergeRemoveData = data.rectangles;
for (let j = 0; j < mergeRemoveData.length; j++) {
for (let i = mergeConfigData.length - 1; i >= 0; i--) {
- let configMerge = mergeConfigData[i];
- let removeMerge = mergeRemoveData[j];
+ const configMerge = mergeConfigData[i];
+ const removeMerge = mergeRemoveData[j];
if (Rectangle.intersects(configMerge, removeMerge)) {
remove.push(mergeConfigData.splice(i, 1)[0]);
}
diff --git a/packages/core/src/Sheets/Apply/RemoveRow.ts b/packages/core/src/Sheets/Apply/RemoveRow.ts
index 637d35b354..1859d9eebc 100644
--- a/packages/core/src/Sheets/Apply/RemoveRow.ts
+++ b/packages/core/src/Sheets/Apply/RemoveRow.ts
@@ -11,11 +11,7 @@ import { IRemoveRowActionData } from '../Action';
*
* @internal
*/
-export function RemoveRow(
- rowIndex: number,
- rowCount: number,
- primitiveData: ObjectArrayPrimitiveType<IRowData>
-): number {
+export function RemoveRow(rowIndex: number, rowCount: number, primitiveData: ObjectArrayPrimitiveType<IRowData>): number {
const wrapper = new ObjectArray(primitiveData);
const result = new ObjectArray<IRowData>();
const start = rowIndex;
@@ -29,10 +25,7 @@ export function RemoveRow(
return result.getLength();
}
-export function RemoveRowApply(
- unit: CommandUnit,
- data: IRemoveRowActionData
-): number {
+export function RemoveRowApply(unit: CommandUnit, data: IRemoveRowActionData): number {
const worksheet = unit.WorkBookUnit!.getSheetBySheetId(data.sheetId);
const rowManager = worksheet!.getRowManager();
const primitiveData = rowManager.getRowData().toJSON();
diff --git a/packages/core/src/Sheets/Apply/RemoveRowData.ts b/packages/core/src/Sheets/Apply/RemoveRowData.ts
index f09cd01cd2..0cfeccd28d 100644
--- a/packages/core/src/Sheets/Apply/RemoveRowData.ts
+++ b/packages/core/src/Sheets/Apply/RemoveRowData.ts
@@ -12,19 +12,12 @@ import { IRemoveRowDataActionData } from '../Action';
*
* @internal
*/
-export function RemoveRowData(
- rowIndex: number,
- rowCount: number,
- primitiveData: ObjectMatrixPrimitiveType<ICellData>
-): ObjectMatrixPrimitiveType<ICellData> {
+export function RemoveRowData(rowIndex: number, rowCount: number, primitiveData: ObjectMatrixPrimitiveType<ICellData>): ObjectMatrixPrimitiveType<ICellData> {
const wrapper = new ObjectMatrix(primitiveData);
return wrapper.spliceRows(rowIndex, rowCount).toJSON();
}
-export function RemoveRowDataApply(
- unit: CommandUnit,
- data: IRemoveRowDataActionData
-) {
+export function RemoveRowDataApply(unit: CommandUnit, data: IRemoveRowDataActionData) {
const worksheet = unit.WorkBookUnit!.getSheetBySheetId(data.sheetId);
const primitiveData = worksheet!.getCellMatrix().toJSON();
const wrapper = new ObjectMatrix(primitiveData);
diff --git a/packages/core/src/Sheets/Apply/SetColumnWidth.ts b/packages/core/src/Sheets/Apply/SetColumnWidth.ts
index fad29a369f..2d2d066242 100644
--- a/packages/core/src/Sheets/Apply/SetColumnWidth.ts
+++ b/packages/core/src/Sheets/Apply/SetColumnWidth.ts
@@ -11,11 +11,7 @@ import { ISetColumnWidthActionData } from '../Action';
*
* @internal
*/
-export function SetColumnWidth(
- columnIndex: number = 0,
- columnWidth: number[],
- columnManager: ColumnManager
-) {
+export function SetColumnWidth(columnIndex: number = 0, columnWidth: number[], columnManager: ColumnManager) {
const result: number[] = [];
for (let i = columnIndex; i < columnIndex + columnWidth.length; i++) {
const column = columnManager.getColumnOrCreate(i);
@@ -25,10 +21,7 @@ export function SetColumnWidth(
return result;
}
-export function SetColumnWidthApply(
- unit: CommandUnit,
- data: ISetColumnWidthActionData
-) {
+export function SetColumnWidthApply(unit: CommandUnit, data: ISetColumnWidthActionData) {
const workbook = unit.WorkBookUnit;
const worksheet = workbook!.getSheetBySheetId(data.sheetId);
const columnIndex = data.columnIndex;
diff --git a/packages/core/src/Sheets/Apply/SetHideRows.ts b/packages/core/src/Sheets/Apply/SetHideRows.ts
index 75682251d1..ebc9e798e6 100644
--- a/packages/core/src/Sheets/Apply/SetHideRows.ts
+++ b/packages/core/src/Sheets/Apply/SetHideRows.ts
@@ -10,11 +10,7 @@ import { ISetRowHideActionData } from '../Action';
*
* @internal
*/
-export function SetHideRow(
- rowIndex: number = 0,
- rowCount: number,
- rowManager: RowManager
-) {
+export function SetHideRow(rowIndex: number = 0, rowCount: number, rowManager: RowManager) {
for (let i = rowIndex; i < rowIndex + rowCount; i++) {
const row = rowManager.getRowOrCreate(i);
if (row) {
diff --git a/packages/core/src/Sheets/Apply/SetRightToLeft.ts b/packages/core/src/Sheets/Apply/SetRightToLeft.ts
index a157838626..e3269c9c64 100644
--- a/packages/core/src/Sheets/Apply/SetRightToLeft.ts
+++ b/packages/core/src/Sheets/Apply/SetRightToLeft.ts
@@ -11,10 +11,7 @@ import { ISetRightToLeftActionData } from '../Action';
*
* @internal
*/
-export function SetRightToLeft(
- worksheet: Worksheet,
- rightToLeft: BooleanNumber
-): BooleanNumber {
+export function SetRightToLeft(worksheet: Worksheet, rightToLeft: BooleanNumber): BooleanNumber {
// get config
const config = worksheet.getConfig();
@@ -28,10 +25,7 @@ export function SetRightToLeft(
return oldState;
}
-export function SetRightToLeftApply(
- unit: CommandUnit,
- data: ISetRightToLeftActionData
-) {
+export function SetRightToLeftApply(unit: CommandUnit, data: ISetRightToLeftActionData) {
const workbook = unit.WorkBookUnit;
const worksheet = workbook!.getSheetBySheetId(data.sheetId)!;
const rightToLeft = data.rightToLeft;
diff --git a/packages/core/src/Sheets/Apply/SetRowHeight.ts b/packages/core/src/Sheets/Apply/SetRowHeight.ts
index b4e8a71c7a..ccd491ca7c 100644
--- a/packages/core/src/Sheets/Apply/SetRowHeight.ts
+++ b/packages/core/src/Sheets/Apply/SetRowHeight.ts
@@ -11,11 +11,7 @@ import { ISetRowHeightActionData } from '../Action';
*
* @internal
*/
-export function SetRowHeight(
- rowIndex: number = 0,
- rowHeight: number[],
- rowManager: RowManager
-) {
+export function SetRowHeight(rowIndex: number = 0, rowHeight: number[], rowManager: RowManager) {
const result: number[] = [];
for (let i = rowIndex; i < rowIndex + rowHeight.length; i++) {
const row = rowManager.getRowOrCreate(i);
diff --git a/packages/core/src/Sheets/Apply/SetShowRow.ts b/packages/core/src/Sheets/Apply/SetShowRow.ts
index fb46efbc46..83e0aa4b44 100644
--- a/packages/core/src/Sheets/Apply/SetShowRow.ts
+++ b/packages/core/src/Sheets/Apply/SetShowRow.ts
@@ -8,11 +8,7 @@ import { RowManager } from '../Domain/RowManager';
*
* @internal
*/
-export function SetShowRow(
- rowIndex: number = 0,
- rowCount: number,
- rowManager: RowManager
-) {
+export function SetShowRow(rowIndex: number = 0, rowCount: number, rowManager: RowManager) {
for (let i = rowIndex; i < rowIndex + rowCount; i++) {
const row = rowManager.getRow(i);
if (row) {
diff --git a/packages/core/src/Sheets/Domain/Range.ts b/packages/core/src/Sheets/Domain/Range.ts
index 05c4f816e8..784fdf7604 100644
--- a/packages/core/src/Sheets/Domain/Range.ts
+++ b/packages/core/src/Sheets/Domain/Range.ts
@@ -552,14 +552,14 @@ export class Range {
const { startRow, endRow, startColumn, endColumn } = this._rangeData;
const maxRow = _worksheet.getMaxRows();
const maxColumn = _worksheet.getMaxColumns();
- if (direction === Direction.BOTTOM) {
+ if (direction === Direction.DOWN) {
for (let i = 0; i < maxRow - startColumn; i++) {
const value = this._worksheet.getCellMatrix().getValue(startRow + i, startColumn);
if (value) _worksheet.getRange(startRow + i, startColumn, startRow + i, startColumn);
}
return _worksheet.getRange(maxRow, startColumn, maxRow, startColumn);
}
- if (direction === Direction.TOP) {
+ if (direction === Direction.UP) {
for (let i = 0; i < startRow; i++) {
const value = this._worksheet.getCellMatrix().getValue(startRow - i, startColumn);
if (value) _worksheet.getRange(startRow - i, startColumn, startRow - i, startRow);
@@ -947,17 +947,6 @@ export class Range {
return this;
}
- /**
- * Sets the font line style of the given range
- *
- * @param fontLine The font line style; a null value resets the font line style
- * @returns This range, for chaining.
- */
- setUnderline(fontLine: Nullable<ITextDecoration>): Range {
- this._setStyle(fontLine, 'ul');
- return this;
- }
-
/**
* Sets the font line style of the given range
*
@@ -980,17 +969,6 @@ export class Range {
return this;
}
- /**
- * Sets the font line style of the given range
- *
- * @param fontLines A two-dimensional array of font line styles ; null values reset the font line style.
- * @returns This range, for chaining.
- */
- setUnderlines(fontLines: Array<Array<Nullable<ITextDecoration>>>): Range {
- this._setStyles(fontLines, 'ul');
- return this;
- }
-
/**
* Sets the font line style of the given range
*
@@ -1002,17 +980,6 @@ export class Range {
return this;
}
- /**
- * Sets the font line style of the given range
- *
- * @param fontLines A two-dimensional array of font line styles ; null values reset the font line style.
- * @returns This range, for chaining.
- */
- setStrikeThroughs(fontLines: Array<Array<Nullable<ITextDecoration>>>): Range {
- this._setStyles(fontLines, 'st');
- return this;
- }
-
/**
* Sets a rectangular grid of font sizes (must match dimensions of this range).
*
@@ -1046,28 +1013,6 @@ export class Range {
return this;
}
- /**
- * Set the font weight for the given range (normal/bold).
- *
- * @param fontWeight The font weight, either 'bold' or 'normal'; a null value resets the font weight.
- * @returns This range, for chaining.
- */
- setFontWeight(fontWeight: Nullable<FontWeight>): Range {
- this._setStyle(fontWeight, 'bl');
- return this;
- }
-
- /**
- * Sets a rectangular grid of font weights (must match dimensions of this range).
- *
- * @param fontWeights A two-dimensional array of font weights, either 'bold' or 'normal'; null values reset the font weight.
- * @returns This range, for chaining.
- */
- setFontWeights(fontWeights: Array<Array<Nullable<FontWeight>>>): Range {
- this._setStyles(fontWeights, 'bl');
- return this;
- }
-
/**
* Sets a rectangular grid of horizontal alignments.
*
@@ -1079,135 +1024,6 @@ export class Range {
return this;
}
- /**
- * Sets the note to the given value.
- *
- * @param note The note value to set for the range; a null value removes the note.
- * @returns This range, for chaining.
- */
- // setNote(note: string): Range {
- // const { _rangeData, _context, _commandManager, _worksheet } = this;
- // const { startRow, startColumn, endRow, endColumn } = _rangeData;
- // const cellValue = new ObjectMatrix<string>();
- // for (let r = startRow; r <= endRow; r++) {
- // for (let c = startColumn; c <= endColumn; c++) {
- // cellValue.setValue(r, c, note);
- // }
- // }
- // const setValue: ISetRangeNoteActionData = {
- // sheetId: _worksheet.getSheetId(),
- // actionName: ACTION_NAMES.SET_RANGE_NOTE_ACTION,
- // cellNote: cellValue.getData(),
- // rangeData: this._rangeData,
- // };
- // const command = new Command(this._currentUniverSheet.getCurrentUniverSheetInstance().getWorkBook(), setValue);
- // _commandManager.invoke(command);
-
- // return this;
- // }
-
- /**
- * Sets the note to the given value.
- *
- * @param notes A two-dimensional array of notes; null values remove the note.
- * @returns This range, for chaining.
- */
- // setNotes(notes: string[][]): Range {
- // const { _rangeData, _context, _commandManager, _worksheet } = this;
-
- // const { startRow, startColumn, endRow, endColumn } = _rangeData;
-
- // const cellValue = new ObjectMatrix<string>();
- // for (let r = 0; r <= endRow - startRow; r++) {
- // for (let c = 0; c <= endColumn - startColumn; c++) {
- // cellValue.setValue(r + startRow, c + startColumn, notes[r][c]);
- // }
- // }
-
- // const setValue: ISetRangeNoteActionData = {
- // sheetId: _worksheet.getSheetId(),
- // actionName: ACTION_NAMES.SET_RANGE_NOTE_ACTION,
- // cellNote: cellValue.getData(),
- // rangeData: this._rangeData,
- // };
- // const command = new Command(this._currentUniverSheet.getCurrentUniverSheetInstance().getWorkBook(), setValue);
- // _commandManager.invoke(command);
-
- // return this;
- // }
-
- /**
- * Sets the number or date format to the given formatting string.
- *
- * @param numberFormat A number format string.
- * @returns This range, for chaining.
- */
- // setNumberFormat(numberFormat: string): Range {
- // const { _rangeData, _context, _commandManager, _worksheet } = this;
-
- // const { startRow, startColumn, endRow, endColumn } = _rangeData;
-
- // const cellValue = new ObjectMatrix<string>();
- // for (let r = 0; r <= endRow - startRow; r++) {
- // for (let c = 0; c <= endColumn - startColumn; c++) {
- // const fm = {
- // f: numberFormat,
- // t: FormatType.NUMBER,
- // };
- // cellValue.setValue(r + startRow, c + startColumn, JSON.stringify(fm));
- // }
- // }
-
- // const setValue: ISetRangeFormatActionData = {
- // sheetId: _worksheet.getSheetId(),
- // actionName: ACTION_NAMES.SET_RANGE_FORMAT_ACTION,
- // cellFormat: cellValue.getData(),
- // rangeData: this._rangeData,
- // };
- // const command = new Command(this._currentUniverSheet.getCurrentUniverSheetInstance().getWorkBook(), setValue);
- // _commandManager.invoke(command);
-
- // return this;
- // }
-
- /**
- * Sets a rectangular grid of number or date formats (must match dimensions of this range).
- *
- * @param numberFormats A two-dimensional array of number formats.
- * @returns This range, for chaining.
- */
- // setNumberFormats(numberFormats: string[][]): Range {
- // const { _rangeData, _context, _commandManager, _worksheet } = this;
-
- // const { startRow, startColumn, endRow, endColumn } = _rangeData;
-
- // const cellValue = new ObjectMatrix<string>();
- // for (let r = 0; r <= endRow - startRow; r++) {
- // for (let c = 0; c <= endColumn - startColumn; c++) {
- // const fm = {
- // f: numberFormats[r][c],
- // t: FormatType.NUMBER,
- // };
- // cellValue.setValue(r + startRow, c + startColumn, JSON.stringify(fm));
- // }
- // }
-
- // const setValue: ISetRangeFormatActionData = {
- // sheetId: _worksheet.getSheetId(),
- // actionName: ACTION_NAMES.SET_RANGE_FORMAT_ACTION,
- // cellFormat: cellValue.getData(),
- // rangeData: this._rangeData,
- // };
- // const command = new Command(this._currentUniverSheet.getCurrentUniverSheetInstance().getWorkBook(), setValue);
- // _commandManager.invoke(command);
-
- // return this;
- // }
-
- // setRichTextValue(value) {}
- // setRichTextValues(values) {}
- // setShowHyperlink(showHyperlink) {}
-
/**
* Sets a rectangular grid of text directions.
*
@@ -1445,126 +1261,6 @@ export class Range {
return this;
}
- /**
- * Fills the destinationRange with data based on the data in this range. The new values are also determined by the specified series type. The destination range must contain this range and extend it in only one direction. For example, the following fills A1:A20 with a series of increasing numbers based on the current values in A1:A4:
- *
- * @param destination The range to be auto-filled with values. The destination range should contain this range and extend it in only one direction (upwards, downwards, left, or right).
- * @param series The type of autoFill series that should be used to calculate new values. The effect of this series differs based on the type and amount of source data.
- * @returns This range, for chaining.
- */
- // autoFill(destination: Range, series: AutoFillSeries): Range {
- // const { _worksheet, _context, _commandManager } = this;
- // const { startRow, endRow, startColumn, endColumn } = this._rangeData;
- // const {
- // startRow: Dsr,
- // endRow: Der,
- // startColumn: Dsc,
- // endColumn: Dec,
- // } = destination._rangeData;
- // let direction = Direction.BOTTOM;
- // let csLen: number = 0;
- // let asLen: number = 0;
-
- // // 复制范围
- // const copy_str_r = startRow;
- // const copy_end_r = endRow;
- // const copy_str_c = startColumn;
- // const copy_end_c = endColumn;
-
- // // 应用范围
- // const apply_str_r = Dsr;
- // const apply_end_r = Der;
- // const apply_str_c = Dsc;
- // const apply_end_c = Dec;
-
- // const matrix = new ObjectMatrix<ICellData>();
-
- // if (apply_str_c === copy_str_c && apply_end_c === copy_end_c) {
- // if (apply_end_r > copy_end_r) {
- // direction = Direction.BOTTOM;
- // } else {
- // direction = Direction.TOP;
- // }
- // } else if (apply_end_c > copy_end_c) {
- // direction = Direction.RIGHT;
- // } else {
- // direction = Direction.LEFT;
- // }
-
- // if (direction === Direction.BOTTOM || direction === Direction.TOP) {
- // // 列
- // csLen = copy_end_r - copy_str_r + 1;
- // asLen = apply_end_r - apply_str_r + 1;
-
- // for (let i = 0; i <= endColumn - startColumn; i++) {
- // const sourceRange = this.getColumnMatrix(i).toArray();
-
- // const copydata = DropCell.getCopyData(
- // sourceRange,
- // copy_str_r,
- // copy_end_r,
- // copy_str_c,
- // copy_end_c,
- // direction
- // );
- // copydata.forEach((item) => {
- // const data = DropCell.getApplyData(
- // item,
- // csLen,
- // asLen,
- // series,
- // direction
- // );
- // data.forEach((dataItem, j) => {
- // matrix.setValue(j, i, dataItem);
- // });
- // });
- // }
- // } else if (direction === Direction.RIGHT || direction === Direction.LEFT) {
- // asLen = apply_end_c - apply_str_c;
- // csLen = copy_end_c - copy_str_c;
- // // 行
- // for (let i = 0; i <= endRow - startRow; i++) {
- // const sourceRange = this.getRowMatrix(i).toArray();
-
- // const copydata = DropCell.getCopyData(
- // sourceRange,
- // copy_str_r,
- // copy_end_r,
- // copy_str_c,
- // copy_end_c,
- // direction
- // );
- // copydata.forEach((item) => {
- // const data = DropCell.getApplyData(
- // item,
- // csLen,
- // asLen,
- // series,
- // direction
- // );
- // });
- // }
- // }
-
- // const setValue: ISetRangeDataActionData = {
- // sheetId: _worksheet.getSheetId(),
- // actionName: ACTION_NAMES.SET_RANGE_DATA_ACTION,
- // cellValue: matrix.getData(),
- // };
- // const command = new Command(
- // {
- // WorkBookUnit: this._currentUniverSheet.getCurrentUniverSheetInstance().getWorkBook(),
- // },
- // setValue
- // );
- // _commandManager.invoke(command);
- // return this;
- // }
-
- // TODO
- // autoFillToNeighbor(series: AutoFillSeries) {}
-
/**
* Returns a copy of the range expanded in the four cardinal Directions to cover all adjacent cells with data in them.
*
@@ -3565,135 +3261,4 @@ export class Range {
_commandManager.invoke(command);
return this;
}
-
- // /**
- // * Applies a default row banding theme to the range. By default, the banding has header and no footer color.
- // */
- // applyRowBanding(): Nullable<Banding>;
-
- // /**
- // * Applies a specified row banding theme to the range. By default, the banding has header and no footer color.
- // * @param bandingTheme
- // */
- // applyRowBanding(bandingTheme: BandingTheme | IBandingProperties): Nullable<Banding>;
-
- // /**
- // * Applies a specified row banding theme to the range with specified header and footer settings.
- // * @param bandingTheme
- // * @param showHeader
- // * @param showFooter
- // */
- // applyRowBanding(
- // bandingTheme: BandingTheme | IBandingProperties,
- // showHeader: boolean,
- // showFooter: boolean
- // ): Nullable<Banding>;
- // applyRowBanding(...argument: any): Nullable<Banding> {
-
- // // default argument
- // const bandedRangeId = 'banded-range-' + Tools.generateRandomId(6);
- // const rangeData = this.getRangeData()
- // let rowProperties:IBanding = {
- // bandingTheme:argument[0] || BandingTheme.LIGHT_GRAY,
- // showHeader:argument[1] || true,
- // showFooter:argument[2] || false,
- // }
-
- // const { _commandManager } = this;
- // // Check whether the incoming range has been set to alternate colors
- // const bandings = this.getSheet().getBandings();
- // const isIntersection =
- // bandings &&
- // bandings.find((banding: Banding) =>
- // banding.getRange().isIntersection(this)
- // );
- // if (isIntersection) {
- // console.error(
- // 'You cannot add alternating background colors to a range that already has alternating background colors.'
- // );
- // return
- // }
-
- // // Organize action data
- // const actionData: IAddBandingActionData = {
- // actionName: ACTION_NAMES.ADD_BANDING_ACTION,
- // bandedRange:{
- // bandedRangeId,
- // rangeData,
- // rowProperties
- // },
- // sheetId: this.getSheet().getSheetId(),
- // };
-
- // // Execute action
- // const command = new Command(this._currentUniverSheet.getCurrentUniverSheetInstance().getWorkBook(), actionData);
- // _commandManager.invoke(command);
-
- // return this.getSheet().getBandingById(bandedRangeId)
- // }
- // /**
- // * Applies a default row banding theme to the range. By default, the banding has header and no footer color.
- // */
- // applyRowBanding(): Nullable<Banding>;
-
- // /**
- // * Applies a specified row banding theme to the range. By default, the banding has header and no footer color.
- // * @param bandingTheme
- // */
- // applyRowBanding(
- // bandingTheme: BandingTheme | IBandingProperties
- // ): Nullable<Banding>;
-
- // /**
- // * Applies a specified row banding theme to the range with specified header and footer settings.
- // * @param bandingTheme
- // * @param showHeader
- // * @param showFooter
- // */
- // applyRowBanding(
- // bandingTheme: BandingTheme | IBandingProperties,
- // showHeader: boolean,
- // showFooter: boolean
- // ): Nullable<Banding>;
- // applyRowBanding(...argument: any): Nullable<Banding> {
- // // default argument
- // const bandedRangeId = 'banded-range-' + Tools.generateRandomId(6);
- // const rangeData = this.getRangeData();
- // let rowProperties: IBanding = {
- // bandingTheme: argument[0] || BandingTheme.LIGHT_GRAY,
- // showHeader: argument[1] || true,
- // showFooter: argument[2] || false,
- // };
-
- // const { _worksheet } = this;
- // // Check whether the incoming range has been set to alternate colors
- // const bandedRanges = _worksheet.getConfig().bandedRanges;
- // const isIntersection =
- // bandedRanges &&
- // bandedRanges.find((bandedRange: IBandedRange) =>
- // _worksheet.getRange(bandedRange.rangeData).isIntersection(this)
- // );
- // if (isIntersection) {
- // console.error(
- // 'You cannot add alternating background colors to a range that already has alternating background colors.'
- // );
- // return;
- // }
-
- // return new Banding(this._worksheet).addRowBanding({
- // bandedRangeId,
- // rangeData,
- // rowProperties,
- // });
- // }
-
- /**
- * Creates a filter applied to the range. There can be at most one filter in a sheet.
- * @returns The new filter.
- */
- // createFilter(): Filter {
- // return new Filter(this);
- // }
}
-
-// Alternating Colors = bandingIns, range.applyRowBanding() bandingIns.setRowBanding(XXX) // bandingIns.remove(id)
diff --git a/packages/core/src/Sheets/Domain/RangeList.ts b/packages/core/src/Sheets/Domain/RangeList.ts
index 6d5b29022c..9a2808faa7 100644
--- a/packages/core/src/Sheets/Domain/RangeList.ts
+++ b/packages/core/src/Sheets/Domain/RangeList.ts
@@ -325,20 +325,6 @@ export class RangeList {
setFontFamily(fontFamily: Nullable<string>): RangeList {
return this._setStyle(fontFamily, 'ff');
}
- // setFontLine(fontLine) {}
-
- /**
- * Sets the underline for each Range in the range list.
- *
- * @param fontLine The underline to set; a null value resets the underline.
- * @returns This range list, for chaining.
- */
- setUnderline(fontLine: Nullable<boolean | BooleanNumber>): RangeList {
- const textDecoration: ITextDecoration = {
- s: fontLine ? BooleanNumber.TRUE : BooleanNumber.FALSE,
- };
- return this._setStyle(textDecoration, 'ul');
- }
/**
* Sets the Overline for each Range in the range list.
@@ -353,19 +339,6 @@ export class RangeList {
return this._setStyle(textDecoration, 'ol');
}
- /**
- * Sets the StrikeThrough for each Range in the range list.
- *
- * @param fontLine The StrikeThrough to set; a null value resets the StrikeThrough.
- * @returns This range list, for chaining.
- */
- setStrikeThrough(fontLine: Nullable<boolean | BooleanNumber>): RangeList {
- const textDecoration: ITextDecoration = {
- s: fontLine ? BooleanNumber.TRUE : BooleanNumber.FALSE,
- };
- return this._setStyle(textDecoration, 'st');
- }
-
/**
* Sets the font size (in points) for each Range in the range list.
*
@@ -387,17 +360,6 @@ export class RangeList {
return this._setStyle(fontBoolean, 'it');
}
- /**
- * Set the font style for each Range in the range list.
- *
- * @param fontWeight The font weight, either 'bold' or 'normal'; a null value resets the font weight.
- * @returns This range list, for chaining.
- */
- setFontWeight(fontWeight: Nullable<boolean | BooleanNumber>): RangeList {
- const fontBoolean = fontWeight ? BooleanNumber.TRUE : BooleanNumber.FALSE;
- return this._setStyle(fontBoolean, 'bl');
- }
-
/**
* Set the horizontal alignment for each Range in the range list.
*
@@ -408,84 +370,6 @@ export class RangeList {
return this._setStyle(alignment, 'ht');
}
- /**
- * Sets the note text for each Range in the range list.
- *
- * @param note The note text to set; a null value removes the note.
- * @returns This range list, for chaining.
- */
- // setNote(note: Nullable<string>): RangeList {
- // let { _rangeList, _context, _commandManager, _worksheet } = this;
-
- // const setList = _rangeList.map((range) => {
- // let { startRow, startColumn, endRow, endColumn } = range;
-
- // let cellValue = new ObjectMatrix<string>();
- // for (let r = startRow; r <= endRow; r++) {
- // for (let c = startColumn; c <= endColumn; c++) {
- // cellValue.setValue(r, c, note);
- // }
- // }
-
- // let setValue: ISetRangeNoteActionData = {
- // sheetId: _worksheet.getSheetId(),
- // actionName: ACTION_NAMES.SET_RANGE_NOTE_ACTION,
- // cellNote: cellValue.getData(),
- // rangeData: range,
- // };
-
- // return setValue;
- // });
-
- // let command = new Command(_context.getWorkBook(), ...setList);
- // _commandManager.invoke(command);
- // return this;
- // }
-
- /**
- * Sets the note text for each Range in the range list.
- *
- * @param numberFormat A number format string.
- * @returns This range list, for chaining.
- */
- // setNumberFormat(numberFormat: string): RangeList {
- // let { _rangeList, _context, _commandManager, _worksheet } = this;
-
- // const setList = _rangeList.map((range) => {
- // let { startRow, startColumn, endRow, endColumn } = range;
-
- // let cellValue = new ObjectMatrix<string>();
- // for (let r = 0; r <= endRow - startRow; r++) {
- // for (let c = 0; c <= endColumn - startColumn; c++) {
- // const fm = {
- // f: numberFormat,
- // t: FormatType.NUMBER,
- // };
- // cellValue.setValue(r + startRow, c + startColumn, JSON.stringify(fm));
- // }
- // }
-
- // let setValue: ISetRangeFormatActionData = {
- // sheetId: _worksheet.getSheetId(),
- // actionName: ACTION_NAMES.SET_RANGE_FORMAT_ACTION,
- // cellFormat: cellValue.getData(),
- // rangeData: range,
- // };
-
- // return setValue;
- // });
-
- // let command = new Command(_context.getWorkBook(), ...setList);
- // _commandManager.invoke(command);
- // return this;
- // }
-
- /**
- * Sets the note text for each Range in the range list.
- */
- // TODO
- // setShowHyperlink(showHyperlink) {}
-
/**
* Sets the text direction for the cells in each Range in the range list.
*
diff --git a/packages/core/src/Sheets/Domain/Selection.ts b/packages/core/src/Sheets/Domain/Selection.ts
index dfd194d576..c488e6624d 100644
--- a/packages/core/src/Sheets/Domain/Selection.ts
+++ b/packages/core/src/Sheets/Domain/Selection.ts
@@ -498,7 +498,7 @@ export class Selection {
endColumn: endColumn !== undefined ? endColumn : range.endColumn,
};
}
- if (direction === Direction.TOP) {
+ if (direction === Direction.UP) {
let startRow;
let endRow;
if (currentCell.endRow === range.endRow) {
@@ -578,7 +578,7 @@ export class Selection {
endColumn: range.endColumn,
};
}
- if (direction === Direction.BOTTOM) {
+ if (direction === Direction.DOWN) {
let startRow;
let endRow;
if (currentCell.startRow === range.startRow) {
diff --git a/packages/core/src/Sheets/Domain/Workbook.ts b/packages/core/src/Sheets/Domain/Workbook.ts
index 1361c821f3..faac851960 100644
--- a/packages/core/src/Sheets/Domain/Workbook.ts
+++ b/packages/core/src/Sheets/Domain/Workbook.ts
@@ -1,9 +1,9 @@
-import { Inject, forwardRef } from '@wendellhu/redi';
+import { Inject, Injector, forwardRef } from '@wendellhu/redi';
import { DEFAULT_RANGE_ARRAY, DEFAULT_WORKBOOK, DEFAULT_WORKSHEET } from '../../Types/Const';
import { Command, CommandManager } from '../../Command';
import { BooleanNumber } from '../../Types/Enum';
-import { InsertSheetAction, ISetSheetOrderActionData, RemoveSheetAction, SetSheetOrderAction, IInsertSheetActionData, IRemoveSheetActionData } from '../Action';
+import { InsertSheetAction, ISetSheetOrderActionData, SetSheetOrderAction, IInsertSheetActionData } from '../Action';
import {
IColumnStartEndData,
IGridRange,
@@ -21,7 +21,6 @@ import { Selection } from './Selection';
import { Styles } from './Styles';
import { Worksheet } from './Worksheet';
import { Range } from './Range';
-import { NamedRange } from './NamedRange';
import { ObserverManager } from '../../Observer';
import { ICurrentUniverService } from '../../Service/Current.service';
@@ -56,7 +55,8 @@ export class Workbook {
@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
@Inject(forwardRef(() => GenName)) private readonly _genName: GenName,
@Inject(CommandManager) private readonly _commandManager: CommandManager,
- @Inject(ObserverManager) private readonly _observerManager: ObserverManager
+ @Inject(ObserverManager) private readonly _observerManager: ObserverManager,
+ @Inject(Injector) readonly _injector: Injector
) {
this._config = Tools.commonExtend(DEFAULT_WORKBOOK, workbookData);
@@ -126,6 +126,9 @@ export class Workbook {
// TODO: @Dushusir: this function has too many function overloads
+ /**
+ * @deprecated
+ */
insertSheet(): Nullable<string>;
insertSheet(index: number): Nullable<string>;
insertSheet(name: string): Nullable<string>;
@@ -392,6 +395,18 @@ export class Workbook {
}
}
+ insertSheetByIndexSheet(index: number, sheet: IWorksheetConfig) {
+ const { sheets, sheetOrder } = this._config;
+ if (sheets[sheet.id]) {
+ throw new Error(`Insert sheet fail ${sheet.id} already exists.`);
+ }
+ sheets[sheet.id] = sheet;
+
+ sheetOrder.splice(index, 0, sheet.id);
+ const worksheet = this._injector.createInstance(Worksheet, sheet);
+ this._worksheets.set(sheet.id, worksheet);
+ }
+
getActiveSpreadsheet(): Workbook {
return this;
}
@@ -576,35 +591,20 @@ export class Workbook {
}
removeSheetBySheetId(sheetId: string): void {
- const { _config } = this;
- const { sheetOrder } = _config;
- const commandManager = this.getCommandManager();
- const sheet = this.getSheetBySheetId(sheetId);
-
- if (sheetOrder.length > 1 && sheet != null) {
- const index = this.getSheetIndex(sheet);
- const before = this._observerManager.getObserver<{ index: number }>('onBeforeRemoveSheetObservable', 'core')!;
- const aftert = this._observerManager.getObserver<{ index: number; sheetId: string }>('onAfterRemoveSheetObservable', 'core')!;
- before.notifyObservers({
- index,
- });
- commandManager.invoke(
- new Command(
- {
- WorkBookUnit: this,
- },
- {
- actionName: RemoveSheetAction.NAME,
- sheetId,
- } as IRemoveSheetActionData
- )
- );
- aftert.notifyObservers({
- index,
- sheetId,
- });
- this.activateSheetByIndex(index);
+ const iSheets = this._worksheets;
+ const config = this._config;
+
+ const { sheets } = config;
+ if (sheets[sheetId] == null) {
+ throw new Error(`Remove sheet fail ${sheetId} does not exist`);
}
+ const findIndex = config.sheetOrder.findIndex((id) => id === sheetId);
+ delete sheets[sheetId];
+
+ config.sheetOrder.splice(findIndex, 1);
+ iSheets.delete(sheetId);
+
+ // this.activateSheetByIndex(index);
}
getSheetBySheetName(name: string): Nullable<Worksheet> {
@@ -762,8 +762,8 @@ export class Workbook {
let firstWorksheet = null;
- for (let sheetId in sheets) {
- let config = sheets[sheetId];
+ for (const sheetId in sheets) {
+ const config = sheets[sheetId];
config.name = this._genName.sheetName(config.name);
const worksheet = new Worksheet(config, this._commandManager, this._observerManager, this._currentUniverService);
_worksheets.set(sheetId, worksheet);
diff --git a/packages/core/src/Sheets/Domain/Worksheet.ts b/packages/core/src/Sheets/Domain/Worksheet.ts
index 27298bb8ad..6bdc52bcca 100644
--- a/packages/core/src/Sheets/Domain/Worksheet.ts
+++ b/packages/core/src/Sheets/Domain/Worksheet.ts
@@ -1199,6 +1199,7 @@ export class Worksheet {
// }
/**
+ * @deprecated
* Sets the BorderStyles
* @param rangeData
* @param style
@@ -1303,7 +1304,7 @@ export class Worksheet {
const actions: ISheetActionData[] = [];
- if (directions.includes(Direction.TOP)) {
+ if (directions.includes(Direction.UP)) {
const setBottomData: BorderStyleData = {
sheetId: _sheetId,
actionName: SetBorderAction.NAME,
@@ -1311,7 +1312,7 @@ export class Worksheet {
};
actions.push(setBottomData);
}
- if (directions.includes(Direction.BOTTOM)) {
+ if (directions.includes(Direction.DOWN)) {
const setTopData: BorderStyleData = {
sheetId: _sheetId,
actionName: SetBorderAction.NAME,
diff --git a/packages/core/src/Types/Enum/Direction.ts b/packages/core/src/Types/Enum/Direction.ts
index d66faee318..6acf2f6ea5 100644
--- a/packages/core/src/Types/Enum/Direction.ts
+++ b/packages/core/src/Types/Enum/Direction.ts
@@ -4,6 +4,6 @@
export enum Direction {
LEFT,
RIGHT,
- TOP,
- BOTTOM,
+ UP,
+ DOWN,
}
diff --git a/packages/core/src/Types/Enum/TextStyle.ts b/packages/core/src/Types/Enum/TextStyle.ts
index 3ecca08f69..8d0df2f65a 100644
--- a/packages/core/src/Types/Enum/TextStyle.ts
+++ b/packages/core/src/Types/Enum/TextStyle.ts
@@ -1,128 +1,128 @@
-/**
- * Direction of text
- */
-export enum TextDirection {
- UNSPECIFIED,
- LEFT_TO_RIGHT,
- RIGHT_TO_LEFT,
-}
-
-// 17.18.99 ST_Underline (Underline Patterns)
-/**
- * Types of text decoration
- */
-export enum TextDecoration {
- DASH,
- DASH_DOT_DOT_HEAVY,
- DASH_DOT_HEAVY,
- DASHED_HEAVY,
- DASH_LONG,
- DASH_LONG_HEAVY,
- DOT_DASH,
- DOT_DOT_DASH,
- DOTTED,
- DOTTED_HEAVY,
- DOUBLE,
- NONE,
- SINGLE,
- THICK,
- WAVE,
- WAVY_DOUBLE,
- WAVY_HEAVY,
- WORDS,
-}
-
-/**
- * An enum that specifies the horizontal alignment of text.
- */
-export enum HorizontalAlign {
- UNSPECIFIED, // The horizontal alignment is not specified. Do not use this.
- LEFT, // The text is explicitly aligned to the left of the cell.
- CENTER, // The text is explicitly aligned to the center of the cell.
- RIGHT, // The text is explicitly aligned to the right of the cell.
- JUSTIFIED, // The paragraph is justified.
-}
-
-/**
- * An enum that specifies the vertical alignment of text.
- */
-export enum VerticalAlign {
- UNSPECIFIED,
- TOP, // The text is explicitly aligned to the top of the cell.
- MIDDLE, // The text is explicitly aligned to the middle of the cell.
- BOTTOM, // The text is explicitly aligned to the bottom of the cell.
-}
-
-/**
- * An enumeration of the strategies used to handle cell text wrapping.
- */
-export enum WrapStrategy {
- UNSPECIFIED,
- /**
- * Lines that are longer than the cell width will be written in the next cell over, so long as that cell is empty. If the next cell over is non-empty, this behaves the same as CLIP . The text will never wrap to the next line unless the user manually inserts a new line. Example:
-
-
- | First sentence. |
- | Manual newline that is very long. <- Text continues into next cell
- | Next newline. |
- */
- OVERFLOW,
- /**
- * Lines that are longer than the cell width will be clipped. The text will never wrap to the next line unless the user manually inserts a new line. Example:
-
-
- | First sentence. |
- | Manual newline t| <- Text is clipped
- | Next newline. |
- */
- CLIP,
- /**
- * Words that are longer than a line are wrapped at the character level rather than clipped. Example:
-
-
- | Cell has a |
- | loooooooooo| <- Word is broken.
- | ong word. |
- */
- WRAP,
-}
-
-/**
- * FontItalic
- */
-export enum FontItalic {
- NORMAL,
- ITALIC,
-}
-
-/**
- * FontWeight
- */
-export enum FontWeight {
- NORMAL,
- BOLD,
-}
-
-export enum BaselineOffset {
- NORMAL,
- SUBSCRIPT,
- SUPERSCRIPT,
-}
-
-/**
- * General Boolean Enum
- */
-export enum BooleanNumber {
- FALSE,
- TRUE,
-}
-
-/**
- * General Boolean Enum
- */
-export enum CellValueType {
- STRING,
- NUMBER,
- BOOLEAN,
- FORCE_STRING,
-}
+/**
+ * Direction of text
+ */
+export enum TextDirection {
+ UNSPECIFIED,
+ LEFT_TO_RIGHT,
+ RIGHT_TO_LEFT,
+}
+
+// 17.18.99 ST_Underline (Underline Patterns)
+/**
+ * Types of text decoration
+ */
+export enum TextDecoration {
+ DASH,
+ DASH_DOT_DOT_HEAVY,
+ DASH_DOT_HEAVY,
+ DASHED_HEAVY,
+ DASH_LONG,
+ DASH_LONG_HEAVY,
+ DOT_DASH,
+ DOT_DOT_DASH,
+ DOTTED,
+ DOTTED_HEAVY,
+ DOUBLE,
+ NONE,
+ SINGLE,
+ THICK,
+ WAVE,
+ WAVY_DOUBLE,
+ WAVY_HEAVY,
+ WORDS,
+}
+
+/**
+ * An enum that specifies the horizontal alignment of text.
+ */
+export enum HorizontalAlign {
+ UNSPECIFIED, // The horizontal alignment is not specified. Do not use this.
+ LEFT, // The text is explicitly aligned to the left of the cell.
+ CENTER, // The text is explicitly aligned to the center of the cell.
+ RIGHT, // The text is explicitly aligned to the right of the cell.
+ JUSTIFIED, // The paragraph is justified.
+}
+
+/**
+ * An enum that specifies the vertical alignment of text.
+ */
+export enum VerticalAlign {
+ UNSPECIFIED,
+ TOP, // The text is explicitly aligned to the top of the cell.
+ MIDDLE, // The text is explicitly aligned to the middle of the cell.
+ BOTTOM, // The text is explicitly aligned to the bottom of the cell.
+}
+
+/**
+ * An enumeration of the strategies used to handle cell text wrapping.
+ */
+export enum WrapStrategy {
+ UNSPECIFIED,
+ /**
+ * Lines that are longer than the cell width will be written in the next cell over, so long as that cell is empty. If the next cell over is non-empty, this behaves the same as CLIP . The text will never wrap to the next line unless the user manually inserts a new line. Example:
+
+
+ | First sentence. |
+ | Manual newline that is very long. <- Text continues into next cell
+ | Next newline. |
+ */
+ OVERFLOW,
+ /**
+ * Lines that are longer than the cell width will be clipped. The text will never wrap to the next line unless the user manually inserts a new line. Example:
+
+
+ | First sentence. |
+ | Manual newline t| <- Text is clipped
+ | Next newline. |
+ */
+ CLIP,
+ /**
+ * Words that are longer than a line are wrapped at the character level rather than clipped. Example:
+
+
+ | Cell has a |
+ | loooooooooo| <- Word is broken.
+ | ong word. |
+ */
+ WRAP,
+}
+
+/**
+ * FontItalic
+ */
+export enum FontItalic {
+ NORMAL,
+ ITALIC,
+}
+
+/**
+ * FontWeight
+ */
+export enum FontWeight {
+ NORMAL,
+ BOLD,
+}
+
+export enum BaselineOffset {
+ NORMAL,
+ SUBSCRIPT,
+ SUPERSCRIPT,
+}
+
+/**
+ * General Boolean Enum
+ */
+export enum BooleanNumber {
+ FALSE,
+ TRUE,
+}
+
+/**
+ * General Boolean Enum
+ */
+export enum CellValueType {
+ STRING,
+ NUMBER,
+ BOOLEAN,
+ FORCE_STRING,
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 6e71493a21..989d945fb8 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -32,5 +32,7 @@ export * from './Slides/Domain';
export { ICurrentUniverService } from './Service/Current.service';
export { LocaleService } from './Service/Locale.service';
-export { ICommandService, ICommand, CommandType, IMutation } from './Service/Command/Command.service';
+export { ICommandService, ICommand, CommandType, IMutation, IOperation } from './Service/Command/Command.service';
export { IUndoRedoService, LocalUndoRedoService, UndoCommand, RedoCommand } from './Service/UndoRedo/undoRedo.service';
+export { ILogService, DesktopLogService } from './Service/log/log.service';
+export { IPermissionService, DesktopPermissionService } from './Service/permission/perimission.service';
diff --git a/packages/core/test/Domain/Range.test.ts b/packages/core/test/Domain/Range.test.ts
index 0067eaa0d9..42ee5b505c 100644
--- a/packages/core/test/Domain/Range.test.ts
+++ b/packages/core/test/Domain/Range.test.ts
@@ -6048,10 +6048,10 @@ test('Test getNextDataCell', () => {
const range = worksheet.getRange('C3:D3');
- const cellTop = range.getNextDataCell(Direction.TOP).getA1Notation();
+ const cellTop = range.getNextDataCell(Direction.UP).getA1Notation();
expect(cellTop).toEqual('C1');
- const cellBottom = range.getNextDataCell(Direction.BOTTOM).getA1Notation();
+ const cellBottom = range.getNextDataCell(Direction.DOWN).getA1Notation();
expect(cellBottom).toEqual('C31');
const cellLeft = range.getNextDataCell(Direction.LEFT).getA1Notation();
diff --git a/packages/core/test/Domain/Selection.test.ts b/packages/core/test/Domain/Selection.test.ts
index 302b46e506..4d924c5a96 100644
--- a/packages/core/test/Domain/Selection.test.ts
+++ b/packages/core/test/Domain/Selection.test.ts
@@ -582,7 +582,7 @@ test('Test getNextDataRange:top1', () => {
};
worksheet.getSelection().setSelection({ selection: rangeData });
- const activeRange = worksheet.getSelection().getNextDataRange(Direction.TOP);
+ const activeRange = worksheet.getSelection().getNextDataRange(Direction.UP);
if (activeRange) {
expect(activeRange.getRangeData()).toEqual({
startRow: 1,
@@ -814,7 +814,7 @@ test('Test getNextDataRange:top2', () => {
};
worksheet.getSelection().setSelection({ selection: rangeData });
- const activeRange = worksheet.getSelection().getNextDataRange(Direction.TOP);
+ const activeRange = worksheet.getSelection().getNextDataRange(Direction.UP);
if (activeRange) {
expect(activeRange.getRangeData()).toEqual({
startRow: 1,
@@ -1043,7 +1043,7 @@ test('Test getNextDataRange:top2.1', () => {
};
worksheet.getSelection().setSelection({ selection: rangeData });
- const activeRange = worksheet.getSelection().getNextDataRange(Direction.TOP);
+ const activeRange = worksheet.getSelection().getNextDataRange(Direction.UP);
if (activeRange) {
expect(activeRange.getRangeData()).toEqual({
startRow: 1,
@@ -1273,7 +1273,7 @@ test('Test getNextDataRange:top2.2', () => {
};
worksheet.getSelection().setSelection({ selection: rangeData });
- const activeRange = worksheet.getSelection().getNextDataRange(Direction.TOP);
+ const activeRange = worksheet.getSelection().getNextDataRange(Direction.UP);
if (activeRange) {
expect(activeRange.getRangeData()).toEqual({
startRow: 2,
@@ -1408,7 +1408,7 @@ test('Test getNextDataRange:top2.3', () => {
};
worksheet.getSelection().setSelection({ selection: rangeData });
- const activeRange = worksheet.getSelection().getNextDataRange(Direction.TOP);
+ const activeRange = worksheet.getSelection().getNextDataRange(Direction.UP);
if (activeRange) {
expect(activeRange.getRangeData()).toEqual({
startRow: 0,
@@ -1639,7 +1639,7 @@ test('Test getNextDataRange:top2.4', () => {
};
worksheet.getSelection().setSelection({ selection: rangeData });
- const activeRange = worksheet.getSelection().getNextDataRange(Direction.TOP);
+ const activeRange = worksheet.getSelection().getNextDataRange(Direction.UP);
if (activeRange) {
expect(activeRange.getRangeData()).toEqual({
startRow: 1,
@@ -1879,7 +1879,7 @@ test('Test getNextDataRange:top2.5', () => {
endColumn: 3,
},
});
- const activeRange = worksheet.getSelection().getNextDataRange(Direction.TOP);
+ const activeRange = worksheet.getSelection().getNextDataRange(Direction.UP);
if (activeRange) {
expect(activeRange.getRangeData()).toEqual({
startRow: 0,
@@ -2119,7 +2119,7 @@ test('Test getNextDataRange:top3', () => {
endColumn: 1,
},
});
- const activeRange = worksheet.getSelection().getNextDataRange(Direction.TOP);
+ const activeRange = worksheet.getSelection().getNextDataRange(Direction.UP);
if (activeRange) {
expect(activeRange.getRangeData()).toEqual({
startRow: 2,
@@ -2359,7 +2359,7 @@ test('Test getNextDataRange:top4', () => {
endColumn: 3,
},
});
- const activeRange = worksheet.getSelection().getNextDataRange(Direction.TOP);
+ const activeRange = worksheet.getSelection().getNextDataRange(Direction.UP);
if (activeRange) {
expect(activeRange.getRangeData()).toEqual({
startRow: 3,
@@ -2530,7 +2530,7 @@ test('Test getNextDataRange:bottom1', () => {
worksheet.getSelection().setSelection({
selection: rangeData,
});
- const activeRange = worksheet.getSelection().getNextDataRange(Direction.BOTTOM);
+ const activeRange = worksheet.getSelection().getNextDataRange(Direction.DOWN);
if (activeRange) {
expect(activeRange.getRangeData()).toEqual({
startRow: 0,
@@ -2698,7 +2698,7 @@ test('Test getNextDataRange:bottom1.1', () => {
worksheet.getSelection().setSelection({
selection: rangeData,
});
- const activeRange = worksheet.getSelection().getNextDataRange(Direction.BOTTOM);
+ const activeRange = worksheet.getSelection().getNextDataRange(Direction.DOWN);
if (activeRange) {
expect(activeRange.getRangeData()).toEqual({
startRow: 0,
@@ -2900,7 +2900,7 @@ test('Test getNextDataRange:bottom2.1', () => {
worksheet.getSelection().setSelection({
selection: rangeData,
});
- const activeRange = worksheet.getSelection().getNextDataRange(Direction.BOTTOM);
+ const activeRange = worksheet.getSelection().getNextDataRange(Direction.DOWN);
if (activeRange) {
expect(activeRange.getRangeData()).toEqual({
startRow: 0,
@@ -3100,7 +3100,7 @@ test('Test getNextDataRange:bottom2.2', () => {
worksheet.getSelection().setSelection({
selection: rangeData,
});
- const activeRange = worksheet.getSelection().getNextDataRange(Direction.BOTTOM);
+ const activeRange = worksheet.getSelection().getNextDataRange(Direction.DOWN);
if (activeRange) {
expect(activeRange.getRangeData()).toEqual({
startRow: 0,
@@ -3306,7 +3306,7 @@ test('Test getNextDataRange:bottom3.1', () => {
endColumn: 1,
},
});
- const activeRange = worksheet.getSelection().getNextDataRange(Direction.BOTTOM);
+ const activeRange = worksheet.getSelection().getNextDataRange(Direction.DOWN);
if (activeRange) {
expect(activeRange.getRangeData()).toEqual({
startRow: 2,
@@ -3511,7 +3511,7 @@ test('Test getNextDataRange:bottom3.2', () => {
endColumn: 1,
},
});
- const activeRange = worksheet.getSelection().getNextDataRange(Direction.BOTTOM);
+ const activeRange = worksheet.getSelection().getNextDataRange(Direction.DOWN);
if (activeRange) {
expect(activeRange.getRangeData()).toEqual({
startRow: 3,
@@ -3717,7 +3717,7 @@ test('Test getNextDataRange:bottom4.1', () => {
endColumn: 1,
},
});
- const activeRange = worksheet.getSelection().getNextDataRange(Direction.BOTTOM);
+ const activeRange = worksheet.getSelection().getNextDataRange(Direction.DOWN);
if (activeRange) {
expect(activeRange.getRangeData()).toEqual({
startRow: 1,
@@ -3924,7 +3924,7 @@ test('Test getNextDataRange:bottom4.2', () => {
endColumn: 1,
},
});
- const activeRange = worksheet.getSelection().getNextDataRange(Direction.BOTTOM);
+ const activeRange = worksheet.getSelection().getNextDataRange(Direction.DOWN);
if (activeRange) {
expect(activeRange.getRangeData()).toEqual({
startRow: 3,
diff --git a/packages/sheets-plugin-import-xlsx/src/Controller/ImportXlsxController.ts b/packages/sheets-plugin-import-xlsx/src/Controller/ImportXlsxController.ts
index 2ab74ce3cd..57c543ddf6 100644
--- a/packages/sheets-plugin-import-xlsx/src/Controller/ImportXlsxController.ts
+++ b/packages/sheets-plugin-import-xlsx/src/Controller/ImportXlsxController.ts
@@ -4,6 +4,7 @@ import { BaseComponentRender } from '@univerjs/base-ui';
import { IToolbarItemProps, SheetContainerUIController } from '@univerjs/ui-plugin-sheets';
import * as LuckyExcel from 'luckyexcel';
+import { BasicWorkbookController } from '@univerjs/base-sheets';
import { IMPORT_XLSX_PLUGIN_NAME } from '../Basics/Const';
export class ImportXlsxController {
@@ -13,7 +14,8 @@ export class ImportXlsxController {
constructor(
@Inject(SheetContainerUIController) private readonly _sheetContainerUIController: SheetContainerUIController,
- @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService
+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
+ @Inject(BasicWorkbookController) private readonly _basicWorkbookController: BasicWorkbookController
) {
this._toolButton = {
name: IMPORT_XLSX_PLUGIN_NAME,
@@ -76,18 +78,22 @@ export class ImportXlsxController {
}
const workbook = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
-
+ const workbookId = workbook.getUnitId();
const order = Tools.deepClone(workbook.getConfig().sheetOrder);
// add new sheets
- Object.keys(sheets).forEach((sheetId) => {
+ Object.keys(sheets).forEach((sheetId, i) => {
const sheetData = sheets[sheetId];
- workbook.insertSheet(sheetData);
+ // workbook.insertSheet(sheetData);
+ const index = order.length - 1 + i;
+ this._basicWorkbookController.insertSheet(index, sheetData, workbookId);
});
// remove other sheets
order.forEach((sheetId: string) => {
- workbook.removeSheetBySheetId(sheetId);
+ // workbook.removeSheetBySheetId(sheetId);
+ // workbook.removeSheetBySheetId(sheetId);
+ this._basicWorkbookController.removeSheet(sheetId, workbookId);
});
});
}
diff --git a/packages/sheets-plugin-operation/src/Domain/Paste.ts b/packages/sheets-plugin-operation/src/Domain/Paste.ts
index 8391f3772a..adef5d0768 100644
--- a/packages/sheets-plugin-operation/src/Domain/Paste.ts
+++ b/packages/sheets-plugin-operation/src/Domain/Paste.ts
@@ -1,4 +1,4 @@
-import { ISetSelectionValueActionData, SelectionModel, SetSelectionValueAction, ISelectionManager, SelectionManager, SelectionController } from '@univerjs/base-sheets';
+import { SelectionModel, ISelectionManager, SelectionManager, SelectionController } from '@univerjs/base-sheets';
import {
Nullable,
IRemoveMergeActionData,
@@ -14,8 +14,6 @@ import {
ISetColumnWidthActionData,
ISetRowHeightActionData,
SetRowHeightAction,
- DEFAULT_SELECTION,
- DEFAULT_CELL,
ICurrentUniverService,
} from '@univerjs/core';
import { handleTableMergeData } from '@univerjs/base-ui';
@@ -199,22 +197,4 @@ export class UniverPaste extends Paste {
return actionDataList;
}
-
- private _getSelectionActionData(sheetId: string) {
- // TODO 从粘贴的表格中解析出来 @tony
- const selectionRange = DEFAULT_SELECTION;
- const curCellRange = DEFAULT_CELL;
- this._selectionManager.clearSelectionControls();
- const models = this._selectionManager.addControlToCurrentByRangeData(selectionRange, curCellRange, false);
- this._selectionManager.updatePreviousSelection();
- if (!models) return;
-
- const actionData: ISetSelectionValueActionData = {
- sheetId,
- actionName: SetSelectionValueAction.NAME,
- selections: models,
- };
-
- return actionData;
- }
-}
+}
\ No newline at end of file
diff --git a/packages/ui-plugin-sheets/src/Controller/CellEditorUIController.ts b/packages/ui-plugin-sheets/src/Controller/CellEditorUIController.ts
index 430d2d841a..4899761eff 100644
--- a/packages/ui-plugin-sheets/src/Controller/CellEditorUIController.ts
+++ b/packages/ui-plugin-sheets/src/Controller/CellEditorUIController.ts
@@ -285,7 +285,7 @@ export class CellEditorUIController {
const currentCell = selectionManager.getCurrentCellModel();
if (!currentCell?.isMerged) {
// move to cell below
- selectionManager.move(Direction.BOTTOM);
+ selectionManager.move(Direction.DOWN);
}
} else {
this.enterEditMode();
@@ -300,13 +300,13 @@ export class CellEditorUIController {
case 'ArrowUp':
if (!this.isEditMode) {
- selectionManager.move(Direction.TOP);
+ selectionManager.move(Direction.UP);
}
break;
case 'ArrowDown':
if (!this.isEditMode) {
- selectionManager.move(Direction.BOTTOM);
+ selectionManager.move(Direction.DOWN);
}
break;
diff --git a/packages/ui-plugin-sheets/src/Controller/RightMenuUIController.ts b/packages/ui-plugin-sheets/src/Controller/RightMenuUIController.ts
index 8a79026c82..66b14e7739 100644
--- a/packages/ui-plugin-sheets/src/Controller/RightMenuUIController.ts
+++ b/packages/ui-plugin-sheets/src/Controller/RightMenuUIController.ts
@@ -1,11 +1,12 @@
import { IMouseEvent, IPointerEvent } from '@univerjs/base-render';
-import { BaseMenuItem, BaseSelectChildrenProps, ComponentChildren, ComponentManager } from '@univerjs/base-ui';
-import { ICurrentUniverService, ObserverManager, Tools, UIObserver } from '@univerjs/core';
-import { Inject, SkipSelf } from '@wendellhu/redi';
+import { BaseMenuItem, BaseSelectChildrenProps, ComponentChildren, ComponentManager, IMenuService, MenuPosition } from '@univerjs/base-ui';
+import { Disposable, ICurrentUniverService, ObserverManager, Tools, UIObserver } from '@univerjs/core';
+import { Inject, Injector, SkipSelf } from '@wendellhu/redi';
import { CanvasView } from '@univerjs/base-sheets';
import { DefaultRightMenuConfig, SheetRightMenuConfig } from '../Basics';
import { RightMenu, RightMenuInput, RightMenuItem } from '../View';
import styles from '../View/RightMenu/index.module.less';
+import { ClearSelectionMenuItemFactory, InsertColMenuItemFactory, InsertRowMenuItemFactory } from './menu';
interface CustomLabelProps {
prefix?: string[] | string;
@@ -28,7 +29,7 @@ export interface RightMenuProps extends BaseMenuItem {
border?: boolean;
}
-export class RightMenuUIController {
+export class RightMenuUIController extends Disposable {
private _rightMenu: RightMenu;
private _menuList: RightMenuProps[];
@@ -38,12 +39,16 @@ export class RightMenuUIController {
// eslint-disable-next-line max-lines-per-function
constructor(
config: SheetRightMenuConfig | undefined,
+ @Inject(Injector) private readonly _injector: Injector,
@Inject(CanvasView) private readonly _sheetCanvasView: CanvasView,
@Inject(ComponentManager) private readonly _componentManager: ComponentManager,
@SkipSelf() @Inject(ObserverManager) private readonly _globalObserverManager: ObserverManager,
@Inject(ObserverManager) private readonly _observerManager: ObserverManager,
- @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService
+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
+ @IMenuService private readonly _menuService: IMenuService
) {
+ super();
+
this._config = Tools.deepMerge({}, DefaultRightMenuConfig, config);
this._menuList = [
@@ -171,124 +176,16 @@ export class RightMenuUIController {
},
],
},
- {
- label: 'rightClick.clearContent',
- onClick: () => this.clearContent(),
- border: true,
- show: this._config.ClearContent,
- },
// {
- // show: this._config.hideMatrix,
- // label: {
- // name: RightMenuItem.name,
- // props: {
- // label: 'rightClick.matrix',
- // },
- // },
- // children: [
- // {
- // label: {
- // name: RightMenuButton.name,
- // props: {
- // label: 'rightClick.flip',
- // children: [
- // {
- // label: 'rightClick.upAndDown',
- // },
- // {
- // label: 'rightClick.leftAndRight',
- // },
- // ],
- // },
- // },
- // },
- // {
- // label: {
- // name: RightMenuButton.name,
- // props: {
- // label: 'rightClick.flip',
- // children: [
- // {
- // label: 'rightClick.clockwise',
- // },
- // {
- // label: 'rightClick.counterclockwise',
- // },
- // ],
- // },
- // },
- // },
- // {
- // label: ['rightClick.transpose'],
- // },
- // {
- // label: {
- // name: RightMenuSelect.name,
- // props: {
- // label: 'rightClick.matrixCalculation',
- // options: [
- // {
- // label: 'rightClick.plus',
- // },
- // {
- // label: 'rightClick.minus',
- // },
- // {
- // label: 'rightClick.multiply',
- // },
- // {
- // label: 'rightClick.divided',
- // },
- // {
- // label: 'rightClick.power',
- // },
- // {
- // label: 'rightClick.root',
- // },
- // {
- // label: 'rightClick.log',
- // },
- // ],
- // },
- // },
- // },
- // {
- // label: {
- // name: RightMenuButton.name,
- // props: {
- // label: 'rightClick.delete0',
- // children: [
- // {
- // label: 'rightClick.byRow',
- // },
- // {
- // label: 'rightClick.byCol',
- // },
- // ],
- // },
- // },
- // },
- // {
- // label: {
- // name: RightMenuButton.name,
- // props: {
- // label: 'rightClick.removeDuplicate',
- // children: [
- // {
- // label: 'rightClick.byRow',
- // },
- // {
- // label: 'rightClick.byCol',
- // },
- // ],
- // },
- // },
- // },
- // ],
+ // label: 'rightClick.clearContent',
+ // onClick: () => this.clearContent(),
+ // border: true,
+ // show: this._config.ClearContent,
// },
];
this._initialize();
+ this._initializeContextMenu();
}
// 获取RightMenu组件
@@ -300,6 +197,7 @@ export class RightMenuUIController {
// 刷新
setMenuList() {
this._rightMenu?.setMenuList(this._menuList);
+ this._rightMenu?.setMenuListNeo(this._menuService.getMenuItems(MenuPosition.CONTEXT_MENU));
}
setUIObserve<T>(msg: UIObserver<T>) {
@@ -406,4 +304,10 @@ export class RightMenuUIController {
}
});
}
-}
+
+ private _initializeContextMenu() {
+ [ClearSelectionMenuItemFactory, InsertRowMenuItemFactory, InsertColMenuItemFactory].forEach((factory) => {
+ this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(factory)));
+ });
+ }
+}
\ No newline at end of file
diff --git a/packages/ui-plugin-sheets/src/Controller/SheetBarUIContruller.ts b/packages/ui-plugin-sheets/src/Controller/SheetBarUIContruller.ts
index 2ad1c82a6d..4c38ffd2d7 100644
--- a/packages/ui-plugin-sheets/src/Controller/SheetBarUIContruller.ts
+++ b/packages/ui-plugin-sheets/src/Controller/SheetBarUIContruller.ts
@@ -14,12 +14,15 @@ import {
RemoveSheetAction,
ICurrentUniverService,
ObserverManager,
+ Disposable,
+ ICommandService,
} from '@univerjs/core';
-import { Inject } from '@wendellhu/redi';
+import { InsertSheetMutation, RemoveSheetMutation, SetWorksheetActivateCommand, SetWorksheetOrderCommand } from '@univerjs/base-sheets';
+import { Inject, SkipSelf } from '@wendellhu/redi';
import { SheetBar } from '../View/SheetBar';
import styles from '../View/SheetBar/index.module.less';
import { SheetBarMenuItem } from '../View/SheetBar/SheetBarMenu';
-import { SHEET_UI_PLUGIN_NAME } from '../Basics';
+import { SHEET_UI_PLUGIN_NAME } from '../Basics/Const';
interface SheetUl extends BaseMenuItem {
label?: CustomComponent | string;
@@ -32,7 +35,7 @@ export interface SheetUlProps extends BaseUlProps {
sheetId: string;
}
-export class SheetBarUIController {
+export class SheetBarUIController extends Disposable {
protected _sheetBar: SheetBar;
protected _sheetUl: SheetUl[];
@@ -49,10 +52,11 @@ export class SheetBarUIController {
constructor(
@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
@Inject(ComponentManager) private readonly _componentManager: ComponentManager,
- @Inject(ObserverManager) private readonly _observerManager: ObserverManager
+ @SkipSelf() @Inject(ObserverManager) private readonly _observerManager: ObserverManager,
+ @ICommandService private readonly _commandService: ICommandService
) {
+ super();
const that = this;
-
this._sheetUl = [
{
label: 'sheetConfig.delete',
@@ -113,6 +117,25 @@ export class SheetBarUIController {
this._componentManager.register(SHEET_UI_PLUGIN_NAME + ColorPicker.name, ColorPicker);
+ this.disposeWithMe(
+ this._commandService.onCommandExecuted((params) => {
+ const { id } = params;
+ switch (id) {
+ case InsertSheetMutation.id:
+ case RemoveSheetMutation.id:
+ // update data;
+ this._refreshSheetData();
+ // set ui bar sheetList;
+ this._refreshSheetBarUI();
+
+ break;
+
+ default:
+ break;
+ }
+ })
+ );
+
CommandManager.getActionObservers().add((event) => {
const action = event.action as SheetActionBase<any>;
const data = event.data;
@@ -221,8 +244,9 @@ export class SheetBarUIController {
}
dragEnd = (element: HTMLDivElement[]): void => {
- let list: SheetUlProps[] = [];
- let sheetId = this._dataId;
+ const list: SheetUlProps[] = [];
+ const sheetId = this._dataId;
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
Array.from(element).forEach((node: any) => {
const item = this._sheetList.find((ele) => ele.sheetId === node.dataset.id);
if (item) {
@@ -231,7 +255,11 @@ export class SheetBarUIController {
});
list.forEach((ele, index) => {
if (ele.sheetId === sheetId) {
- this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().setSheetOrder(ele.sheetId, index);
+ this._commandService.executeCommand(SetWorksheetOrderCommand.id, {
+ workbookId: workbook.getUnitId(),
+ worksheetId: ele.sheetId,
+ order: index,
+ });
}
});
};
@@ -243,9 +271,14 @@ export class SheetBarUIController {
menuList: this._menuList,
selectSheet: (event: Event, data: { item: SheetUlProps }) => {
this._dataId = data.item.sheetId;
- const sheet = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getSheetBySheetId(this._dataId);
+ const currentWorkbook = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
+ const sheet = currentWorkbook.getSheetBySheetId(this._dataId);
if (sheet) {
- sheet.activate();
+ // sheet.activate();
+ this._commandService.executeCommand(SetWorksheetActivateCommand.id, {
+ workbookId: currentWorkbook.getUnitId(),
+ worksheetId: sheet.getSheetId(),
+ });
}
},
contextMenu: (e: MouseEvent) => {
@@ -263,6 +296,7 @@ export class SheetBarUIController {
protected _refreshSheetData(): void {
const workbook = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
const sheets = workbook.getSheets();
+
this._menuList = sheets.map((sheet, index) => ({
label: sheet.getName(),
index: String(index),
@@ -274,10 +308,15 @@ export class SheetBarUIController {
const target = e.currentTarget as HTMLDivElement;
this._dataId = target.dataset.id as string;
sheet.showSheet();
- sheet.activate();
+ // sheet.activate();
+ this._commandService.executeCommand(SetWorksheetActivateCommand.id, {
+ workbookId: workbook.getUnitId(),
+ worksheetId: sheet.getSheetId(),
+ });
}
},
}));
+
this._sheetList = sheets
.filter((sheet) => !sheet.isSheetHidden())
.map((sheet, index) => ({
@@ -293,8 +332,11 @@ export class SheetBarUIController {
onClick: (e: MouseEvent) => {
const target = e.currentTarget as HTMLDivElement;
this._dataId = target.dataset.id as string;
-
- sheet.activate();
+ // sheet.activate();
+ this._commandService.executeCommand(SetWorksheetActivateCommand.id, {
+ workbookId: workbook.getUnitId(),
+ worksheetId: sheet.getSheetId(),
+ });
},
}));
this._sheetIndex = sheets.findIndex((sheet) => sheet.getStatus() === 1);
diff --git a/packages/ui-plugin-sheets/src/Controller/ToolbarUIController.ts b/packages/ui-plugin-sheets/src/Controller/ToolbarUIController.ts
index bacdace6c5..df85ca1660 100644
--- a/packages/ui-plugin-sheets/src/Controller/ToolbarUIController.ts
+++ b/packages/ui-plugin-sheets/src/Controller/ToolbarUIController.ts
@@ -14,8 +14,6 @@ import {
VerticalAlign,
WrapStrategy,
Range,
- FontWeight,
- FontItalic,
ITextRotation,
ICurrentUniverService,
ObserverManager,
@@ -36,7 +34,7 @@ import {
} from '../View/Toolbar/Const';
import styles from '../View/Toolbar/index.module.less';
-import { RedoMenuItemFactory, UndoMenuItemFactory } from './menu';
+import { BoldMenuItemFactory, ItalicMenuItemFactory, RedoMenuItemFactory, StrikeThroughMenuItemFactory, UnderlineMenuItemFactory, UndoMenuItemFactory } from './menu';
export interface BaseToolbarSelectProps extends BaseSelectProps {
children?: BaseSelectChildrenProps[];
@@ -134,68 +132,7 @@ export class ToolbarUIController extends Disposable {
},
children: FONT_SIZE_CHILDREN,
},
- {
- toolbarType: 1,
- tooltip: 'toolbar.bold',
- label: {
- name: 'BoldIcon',
- },
- unActive: false,
- name: 'bold',
- show: this._config.bold,
- onClick: (e, isBold: boolean) => {
- this.setFontWeight(isBold);
- this.hideTooltip();
- },
- },
- {
- toolbarType: 1,
- tooltip: 'toolbar.italic',
- label: {
- name: 'ItalicIcon',
- },
- unActive: false,
- name: 'italic',
- show: this._config.italic,
- onClick: (e, isItalic: boolean) => {
- this.setFontStyle(isItalic);
- this.hideTooltip();
- },
- },
- {
- toolbarType: 1,
- tooltip: 'toolbar.strikethrough',
- label: {
- name: 'DeleteLineIcon',
- },
- unActive: false,
- name: 'strikethrough',
- show: this._config.strikethrough,
- onClick: (e, isStrikethrough: boolean) => {
- this.hideTooltip();
- const strikethroughItem = this._toolList.find((item) => item.name === 'strikethrough');
- if (!strikethroughItem) return;
- strikethroughItem.active = isStrikethrough;
- this.setStrikeThrough(isStrikethrough);
- },
- },
- {
- toolbarType: 1,
- tooltip: 'toolbar.underline',
- label: {
- name: 'UnderLineIcon',
- },
- unActive: false,
- name: 'underline',
- show: this._config.underline,
- onClick: (e, isUnderLine: boolean) => {
- this.hideTooltip();
- const underlineItem = this._toolList.find((item) => item.name === 'underline');
- if (!underlineItem) return;
- underlineItem.active = isUnderLine; // huh? 如果是数据加载呢?
- this.setUnderline(isUnderLine);
- },
- },
+
{
type: 5,
tooltip: 'toolbar.textColor.main',
@@ -620,50 +557,28 @@ export class ToolbarUIController extends Disposable {
// eslint-disable-next-line max-lines-per-function
private _changeToolbarState(range: Range): void {
+ // FIXME@wzhudev: this is anti-pattern too, it should not compose all the toolbar items here
const workbook = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
const worksheet = workbook.getActiveSheet();
if (worksheet) {
- const isBold = range.getFontWeight();
- const IsItalic = range.getFontStyle();
- const strikeThrough = range.getStrikeThrough();
const fontSize = range.getFontSize();
const fontWeight = range.getFontWeight();
const fontName = range.getFontFamily();
const fontItalic = range.getFontStyle();
- // const fontColor = range.getFontColor();
- // const background = range.getBackground();
- const underline = range.getUnderline();
const horizontalAlign = range.getHorizontalAlignment() ?? HorizontalAlign.LEFT;
const verticalAlign = range.getVerticalAlignment() ?? VerticalAlign.BOTTOM;
const rotation = range.getTextRotation() as ITextRotation;
const warp = range.getWrapStrategy() ?? WrapStrategy.CLIP;
- const bold = this._toolList.find((item) => item.name === 'bold');
- const italic = this._toolList.find((item) => item.name === 'italic');
const textRotateModeItem = this._toolList.find((item) => item.name === 'textRotateMode');
const fontSizeItem = this._toolList.find((item) => item.name === 'fontSize');
const fontNameItem = this._toolList.find((item) => item.name === 'font');
const fontBoldItem = this._toolList.find((item) => item.name === 'bold');
const fontItalicItem = this._toolList.find((item) => item.name === 'italic');
- // const textColor = this._toolList.find((item) => item.name === 'textColor')
- // const fillColor = this._toolList.find((item) => item.name === 'fillColor')
- const strikethroughItem = this._toolList.find((item) => item.name === 'strikethrough');
- const underlineItem = this._toolList.find((item) => item.name === 'underline');
const horizontalAlignModeItem = this._toolList.find((item) => item.name === 'horizontalAlignMode');
const verticalAlignModeItem = this._toolList.find((item) => item.name === 'verticalAlignMode');
const textWrapMode = this._toolList.find((item) => item.name === 'textWrapMode');
- if (bold) {
- bold.active = isBold === FontWeight.BOLD;
- }
-
- if (italic) {
- italic.active = IsItalic === FontItalic.ITALIC;
- }
-
- if (strikethroughItem) {
- strikethroughItem.active = !!(strikeThrough && strikeThrough.s);
- }
if (fontNameItem) {
fontNameItem.children?.forEach((item) => {
item.selected = fontName === item.value;
@@ -678,21 +593,6 @@ export class ToolbarUIController extends Disposable {
if (fontItalicItem) {
fontItalicItem.active = !!fontItalic;
}
- // if (textColor) {
- // const label = textColor.label
- // if (label && label.props) {
- // label.props.color = fontColor
- // }
- // }
- // if (fillColor) {
- // const label = fillColor.label
- // if (label && label.props) {
- // label.props.color = background
- // }
- // }
- if (underlineItem) {
- underlineItem.active = !!(underline && underline.s);
- }
if (horizontalAlignModeItem) {
horizontalAlignModeItem.children?.forEach((item) => {
item.selected = horizontalAlign === item.value;
@@ -723,7 +623,9 @@ export class ToolbarUIController extends Disposable {
}
private _initializeToolbar(): void {
- [UndoMenuItemFactory, RedoMenuItemFactory].forEach((factory) => {
+ // NOTE@wzhudev: now we register menu items that only display in the toolbar here. In fact we should register all commands and menu items and shortcuts
+ // in a single controller. I will do that layer.
+ [UndoMenuItemFactory, RedoMenuItemFactory, BoldMenuItemFactory, ItalicMenuItemFactory, UnderlineMenuItemFactory, StrikeThroughMenuItemFactory].forEach((factory) => {
this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(factory)));
});
}
@@ -752,10 +654,6 @@ export class ToolbarUIController extends Disposable {
if (currentUnitId !== actionUnitId) return;
- // 所有功能的 UI 耦合在一起?
- // 不同的环境下的 UI 需要全部重新写一遍?
- // UI 没有可扩展性
- // 这里有点问题的…… 每次都去全量获取状态?
const manager = this._selectionManager;
const range = manager.getCurrentCell();
if (range) {
@@ -763,4 +661,4 @@ export class ToolbarUIController extends Disposable {
}
});
}
-}
\ No newline at end of file
+}
diff --git a/packages/ui-plugin-sheets/src/Controller/menu.ts b/packages/ui-plugin-sheets/src/Controller/menu.ts
index b3857cdd2a..4f82e99127 100644
--- a/packages/ui-plugin-sheets/src/Controller/menu.ts
+++ b/packages/ui-plugin-sheets/src/Controller/menu.ts
@@ -1,6 +1,19 @@
+import {
+ ClearSelectionContentCommand,
+ ISelectionManager,
+ InsertColCommand,
+ InsertRowCommand,
+ SetBoldCommand,
+ SetItalicCommand,
+ SetSelectionsOperation,
+ SetStrikeThroughCommand,
+ SetUnderlineCommand,
+ SetRangeStyleMutation,
+} from '@univerjs/base-sheets';
import { IMenuItem, MenuPosition } from '@univerjs/base-ui';
-import { IUndoRedoService, RedoCommand, UndoCommand } from '@univerjs/core';
+import { FontItalic, FontWeight, ICommandService, IPermissionService, IUndoRedoService, RedoCommand, UndoCommand } from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
+import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
export function UndoMenuItemFactory(accessor: IAccessor): IMenuItem {
@@ -10,7 +23,7 @@ export function UndoMenuItemFactory(accessor: IAccessor): IMenuItem {
id: UndoCommand.id,
icon: 'ForwardIcon',
title: 'Undo',
- menu: [MenuPosition.TOOLBAR, MenuPosition.CONTEXT_MENU],
+ menu: [MenuPosition.TOOLBAR],
disabled$: undoRedoService.undoRedoStatus$.pipe(map((v) => v.undos <= 0)),
};
}
@@ -24,9 +37,234 @@ export function RedoMenuItemFactory(accessor: IAccessor): IMenuItem {
title: 'Redo',
menu: [MenuPosition.TOOLBAR],
disabled$: undoRedoService.undoRedoStatus$.pipe(map((v) => v.redos <= 0)),
- }
+ };
+}
+
+export function BoldMenuItemFactory(accessor: IAccessor): IMenuItem {
+ const commandService = accessor.get(ICommandService);
+ const permissionService = accessor.get(IPermissionService);
+ const selectionManager = accessor.get(ISelectionManager);
+
+ return {
+ id: SetBoldCommand.id,
+ icon: 'BoldIcon',
+ title: 'Set bold',
+ menu: [MenuPosition.TOOLBAR],
+ disabled$: new Observable<boolean>((subscriber) => {
+ let editable = false;
+ function update() {
+ subscriber.next(!editable);
+ }
+
+ update();
+
+ // it can hook in other business logic via permissionService and sheet business logic
+ const permission$ = permissionService.editable$.subscribe((e) => {
+ editable = e;
+ update();
+ });
+
+ return () => {
+ permission$.unsubscribe();
+ };
+ }),
+ activated$: new Observable<boolean>((subscriber) => {
+ commandService.onCommandExecuted((c) => {
+ const id = c.id;
+ if (id !== SetRangeStyleMutation.id && id !== SetSelectionsOperation.id) {
+ return;
+ }
+
+ // FIXME: range is undefined when moving selection with cursor
+ const range = selectionManager.getCurrentCell();
+ const isBold = range?.getFontWeight();
+
+ subscriber.next(isBold === FontWeight.BOLD);
+ });
+ subscriber.next(false);
+ }),
+ };
+}
+
+export function ItalicMenuItemFactory(accessor: IAccessor): IMenuItem {
+ const permissionService = accessor.get(IPermissionService);
+ const commandService = accessor.get(ICommandService);
+ const selectionManager = accessor.get(ISelectionManager);
+
+ return {
+ id: SetItalicCommand.id,
+ icon: 'ItalicIcon',
+ title: 'Set italic',
+ menu: [MenuPosition.TOOLBAR],
+ disabled$: new Observable<boolean>((subscriber) => {
+ let editable = false;
+ function update() {
+ subscriber.next(!editable);
+ }
+
+ update();
+
+ const permission$ = permissionService.editable$.subscribe((e) => {
+ editable = e;
+ update();
+ });
+
+ return () => {
+ permission$.unsubscribe();
+ };
+ }),
+ activated$: new Observable<boolean>((subscriber) => {
+ commandService.onCommandExecuted((c) => {
+ const id = c.id;
+ if (id !== SetRangeStyleMutation.id && id !== SetSelectionsOperation.id) {
+ return;
+ }
+
+ const range = selectionManager.getCurrentCell();
+ const isItalic = range?.getFontStyle();
+
+ subscriber.next(isItalic === FontItalic.ITALIC);
+ });
+ subscriber.next(false);
+ }),
+ };
+}
+
+export function UnderlineMenuItemFactory(accessor: IAccessor): IMenuItem {
+ const permissionService = accessor.get(IPermissionService);
+ const commandService = accessor.get(ICommandService);
+ const selectionManager = accessor.get(ISelectionManager);
+
+ return {
+ id: SetUnderlineCommand.id,
+ icon: 'UnderLineIcon',
+ title: 'Set underline',
+ menu: [MenuPosition.TOOLBAR],
+ disabled$: new Observable<boolean>((subscriber) => {
+ let editable = false;
+ function update() {
+ subscriber.next(!editable);
+ }
+
+ update();
+
+ const permission$ = permissionService.editable$.subscribe((e) => {
+ editable = e;
+ update();
+ });
+
+ return () => {
+ permission$.unsubscribe();
+ };
+ }),
+ activated$: new Observable<boolean>((subscriber) => {
+ commandService.onCommandExecuted((c) => {
+ const id = c.id;
+ if (id !== SetRangeStyleMutation.id && id !== SetSelectionsOperation.id) {
+ return;
+ }
+
+ const range = selectionManager.getCurrentCell();
+ const isUnderline = range?.getUnderline();
+
+ subscriber.next(!!(isUnderline && isUnderline.s));
+ });
+ subscriber.next(false);
+ }),
+ };
}
-// export function FontSelectorMenuItemFactory(accessor: IAccessor): IMenuItem {
-//
-// }
+export function StrikeThroughMenuItemFactory(accessor: IAccessor): IMenuItem {
+ const permissionService = accessor.get(IPermissionService);
+ const commandService = accessor.get(ICommandService);
+ const selectionManager = accessor.get(ISelectionManager);
+
+ return {
+ id: SetStrikeThroughCommand.id,
+ icon: 'DeleteLineIcon',
+ title: 'Set strike through',
+ menu: [MenuPosition.TOOLBAR],
+ disabled$: new Observable<boolean>((subscriber) => {
+ let editable = false;
+ function update() {
+ subscriber.next(!editable);
+ }
+
+ update();
+
+ const permission$ = permissionService.editable$.subscribe((e) => {
+ editable = e;
+ update();
+ });
+
+ return () => {
+ permission$.unsubscribe();
+ };
+ }),
+ activated$: new Observable<boolean>((subscriber) => {
+ commandService.onCommandExecuted((c) => {
+ const id = c.id;
+ if (id !== SetRangeStyleMutation.id && id !== SetSelectionsOperation.id) {
+ return;
+ }
+
+ const range = selectionManager.getCurrentCell();
+ const st = range?.getStrikeThrough();
+
+ subscriber.next(!!(st && st.s));
+ });
+ subscriber.next(false);
+ }),
+ };
+}
+
+export function FontFamilySelectorMenuItemFactory(accessor: IAccessor): IMenuItem {}
+
+export function FontSizeSelectorMenuItemFactory(accessor: IAccessor): IMenuItem {}
+
+export function FontColorSelectorMenuItemFactory(accessor: IAccessor): IMenuItem {}
+
+export function BackgroundColorSelectorMenuItemFactory(accessor: IAccessor): IMenuItem {}
+
+export function CellBorderSelectorMenuItemFactory(accessor: IAccessor): IMenuItem {}
+
+export function MergeCellMenuItemFactory(accessor: IAccessor): IMenuItem {}
+
+export function HorizontalAlignMenuItemFactory(accessor: IAccessor): IMenuItem {}
+
+export function VerticalAlignMenuItemFactory(accessor: IAccessor): IMenuItem {}
+
+export function WrapTextMenuItemFactory(accessor: IAccessor): IMenuItem {}
+
+export function TextRotateMenuItemFactory(accessor: IAccessor): IMenuItem {}
+
+export function NumberFormatMenuItemFactory(accessor: IAccessor): IMenuItem {}
+
+// NOTE: these menu icons should be registered by plugins not defined here.
+// export function SearchReplaceMenuItemFactory(accessor: IAccessor): IMenuItem {}
+// export function ImportMenuItemFactory(accessor: IAccessor): IMenuItem {}
+// export function ImageMenuItemFactory(accessor: IAccessor): IMenuItem {}
+
+export function ClearSelectionMenuItemFactory(accessor: IAccessor): IMenuItem {
+ return {
+ id: ClearSelectionContentCommand.id,
+ title: 'rightClick.clearContent',
+ menu: [MenuPosition.CONTEXT_MENU],
+ };
+}
+
+export function InsertRowMenuItemFactory(accessor: IAccessor): IMenuItem {
+ return {
+ id: InsertRowCommand.id,
+ menu: [MenuPosition.CONTEXT_MENU],
+ title: 'rightClick.insertRow',
+ };
+}
+
+export function InsertColMenuItemFactory(accessor: IAccessor): IMenuItem {
+ return {
+ id: InsertColCommand.id,
+ menu: [MenuPosition.CONTEXT_MENU],
+ title: 'rightClick.insertColumn',
+ };
+}
diff --git a/packages/ui-plugin-sheets/src/Controller/shortcut.controller.ts b/packages/ui-plugin-sheets/src/Controller/shortcut.controller.ts
new file mode 100644
index 0000000000..9754d107d3
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/Controller/shortcut.controller.ts
@@ -0,0 +1,58 @@
+import { ChangeSelectionCommand, ExpandSelectionCommand, SetBoldCommand, SetItalicCommand, SetStrikeThroughCommand, SetUnderlineCommand } from '@univerjs/base-sheets';
+import { IShortcutService } from '@univerjs/base-ui';
+import { Disposable, ICommandService } from '@univerjs/core';
+import {
+ ExpandSelectionDownShortcutItem,
+ ExpandSelectionEndDownShortcutItem,
+ ExpandSelectionEndLeftShortcutItem,
+ ExpandSelectionEndRightShortcutItem,
+ ExpandSelectionEndUpShortcutItem,
+ ExpandSelectionLeftShortcutItem,
+ ExpandSelectionRightShortcutItem,
+ ExpandSelectionUpShortcutItem,
+ MoveSelectionDownShortcutItem,
+ MoveSelectionEndDownShortcutItem,
+ MoveSelectionEndLeftShortcutItem,
+ MoveSelectionEndRightShortcutItem,
+ MoveSelectionEndUpShortcutItem,
+ MoveSelectionLeftShortcutItem,
+ MoveSelectionRightShortcutItem,
+ MoveSelectionUpShortcutItem,
+} from './shortcuts/selection.shortcut';
+import { SetBoldShortcutItem, SetItalicShortcutItem, SetStrikeThroughShortcutItem, SetUnderlineShortcutItem } from './shortcuts/style.shortcut';
+
+export class DesktopSheetShortcutController extends Disposable {
+ constructor(@IShortcutService private readonly _shortcutService: IShortcutService, @ICommandService private readonly _commandService: ICommandService) {
+ super();
+
+ [ChangeSelectionCommand, ExpandSelectionCommand, SetBoldCommand, SetItalicCommand, SetStrikeThroughCommand, SetUnderlineCommand].forEach((c) => {
+ this.disposeWithMe(this._commandService.registerCommand(c));
+ });
+
+ [
+ MoveSelectionDownShortcutItem,
+ MoveSelectionUpShortcutItem,
+ MoveSelectionLeftShortcutItem,
+ MoveSelectionRightShortcutItem,
+ MoveSelectionEndDownShortcutItem,
+ MoveSelectionEndUpShortcutItem,
+ MoveSelectionEndLeftShortcutItem,
+ MoveSelectionEndRightShortcutItem,
+ ExpandSelectionDownShortcutItem,
+ ExpandSelectionUpShortcutItem,
+ ExpandSelectionLeftShortcutItem,
+ ExpandSelectionRightShortcutItem,
+ ExpandSelectionEndDownShortcutItem,
+ ExpandSelectionEndUpShortcutItem,
+ ExpandSelectionEndLeftShortcutItem,
+ ExpandSelectionEndRightShortcutItem,
+
+ SetBoldShortcutItem,
+ SetItalicShortcutItem,
+ SetUnderlineShortcutItem,
+ SetStrikeThroughShortcutItem,
+ ].forEach((item) => {
+ this.disposeWithMe(this._shortcutService.registerShortcut(item));
+ });
+ }
+}
diff --git a/packages/ui-plugin-sheets/src/Controller/shortcuts/selection.shortcut.ts b/packages/ui-plugin-sheets/src/Controller/shortcuts/selection.shortcut.ts
new file mode 100644
index 0000000000..5f3bb6854b
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/Controller/shortcuts/selection.shortcut.ts
@@ -0,0 +1,145 @@
+import { ChangeSelectionCommand, ExpandSelectionCommand, IChangeSelectionCommandParams, IExpandSelectionCommandParams } from '@univerjs/base-sheets';
+import { IShortcutItem, KeyCode, MetaKeys } from '@univerjs/base-ui';
+import { Direction } from '@univerjs/core';
+
+export const MoveSelectionDownShortcutItem: IShortcutItem<IChangeSelectionCommandParams> = {
+ id: ChangeSelectionCommand.id,
+ binding: KeyCode.ARROW_DOWN,
+ staticParameters: {
+ direction: Direction.DOWN,
+ },
+};
+
+export const MoveSelectionUpShortcutItem: IShortcutItem<IChangeSelectionCommandParams> = {
+ id: ChangeSelectionCommand.id,
+ binding: KeyCode.ARROW_UP,
+ staticParameters: {
+ direction: Direction.UP,
+ },
+};
+
+export const MoveSelectionLeftShortcutItem: IShortcutItem<IChangeSelectionCommandParams> = {
+ id: ChangeSelectionCommand.id,
+ binding: KeyCode.ARROW_LEFT,
+ staticParameters: {
+ direction: Direction.LEFT,
+ },
+};
+
+export const MoveSelectionRightShortcutItem: IShortcutItem<IChangeSelectionCommandParams> = {
+ id: ChangeSelectionCommand.id,
+ binding: KeyCode.ARROW_RIGHT,
+ staticParameters: {
+ direction: Direction.RIGHT,
+ },
+};
+
+// move selection to continuous end
+
+export const MoveSelectionEndDownShortcutItem: IShortcutItem<IChangeSelectionCommandParams> = {
+ id: ChangeSelectionCommand.id,
+ binding: KeyCode.ARROW_DOWN | MetaKeys.CTRL_COMMAND,
+ staticParameters: {
+ direction: Direction.LEFT,
+ toEnd: true,
+ },
+};
+
+export const MoveSelectionEndUpShortcutItem: IShortcutItem<IChangeSelectionCommandParams> = {
+ id: ChangeSelectionCommand.id,
+ binding: KeyCode.ARROW_UP | MetaKeys.CTRL_COMMAND,
+ staticParameters: {
+ direction: Direction.UP,
+ toEnd: true,
+ },
+};
+
+export const MoveSelectionEndLeftShortcutItem: IShortcutItem<IChangeSelectionCommandParams> = {
+ id: ChangeSelectionCommand.id,
+ binding: KeyCode.ARROW_LEFT | MetaKeys.CTRL_COMMAND,
+ staticParameters: {
+ direction: Direction.LEFT,
+ toEnd: true,
+ },
+};
+
+export const MoveSelectionEndRightShortcutItem: IShortcutItem<IChangeSelectionCommandParams> = {
+ id: ChangeSelectionCommand.id,
+ binding: KeyCode.ARROW_RIGHT | MetaKeys.CTRL_COMMAND,
+ staticParameters: {
+ direction: Direction.RIGHT,
+ toEnd: true,
+ },
+};
+
+// continuous selection by cell
+
+export const ExpandSelectionDownShortcutItem: IShortcutItem<IExpandSelectionCommandParams> = {
+ id: ExpandSelectionCommand.id,
+ binding: KeyCode.ARROW_DOWN | MetaKeys.SHIFT,
+ staticParameters: {
+ direction: Direction.DOWN,
+ },
+};
+
+export const ExpandSelectionUpShortcutItem: IShortcutItem<IExpandSelectionCommandParams> = {
+ id: ExpandSelectionCommand.id,
+ binding: KeyCode.ARROW_UP | MetaKeys.SHIFT,
+ staticParameters: {
+ direction: Direction.UP,
+ },
+};
+
+export const ExpandSelectionLeftShortcutItem: IShortcutItem<IExpandSelectionCommandParams> = {
+ id: ExpandSelectionCommand.id,
+ binding: KeyCode.ARROW_LEFT | MetaKeys.SHIFT,
+ staticParameters: {
+ direction: Direction.LEFT,
+ },
+};
+
+export const ExpandSelectionRightShortcutItem: IShortcutItem<IExpandSelectionCommandParams> = {
+ id: ExpandSelectionCommand.id,
+ binding: KeyCode.ARROW_RIGHT | MetaKeys.SHIFT,
+ staticParameters: {
+ direction: Direction.RIGHT,
+ },
+};
+
+// continuous selection to continuous end
+
+export const ExpandSelectionEndDownShortcutItem: IShortcutItem<IExpandSelectionCommandParams> = {
+ id: ExpandSelectionCommand.id,
+ binding: KeyCode.ARROW_DOWN | MetaKeys.SHIFT | MetaKeys.CTRL_COMMAND,
+ staticParameters: {
+ direction: Direction.DOWN,
+ toEnd: true,
+ },
+};
+
+export const ExpandSelectionEndUpShortcutItem: IShortcutItem<IExpandSelectionCommandParams> = {
+ id: ExpandSelectionCommand.id,
+ binding: KeyCode.ARROW_UP | MetaKeys.SHIFT | MetaKeys.CTRL_COMMAND,
+ staticParameters: {
+ direction: Direction.UP,
+ toEnd: true,
+ },
+};
+
+export const ExpandSelectionEndLeftShortcutItem: IShortcutItem<IExpandSelectionCommandParams> = {
+ id: ExpandSelectionCommand.id,
+ binding: KeyCode.ARROW_LEFT | MetaKeys.SHIFT | MetaKeys.CTRL_COMMAND,
+ staticParameters: {
+ direction: Direction.LEFT,
+ toEnd: true,
+ },
+};
+
+export const ExpandSelectionEndRightShortcutItem: IShortcutItem<IExpandSelectionCommandParams> = {
+ id: ExpandSelectionCommand.id,
+ binding: KeyCode.ARROW_RIGHT | MetaKeys.SHIFT | MetaKeys.CTRL_COMMAND,
+ staticParameters: {
+ direction: Direction.RIGHT,
+ toEnd: true,
+ },
+};
diff --git a/packages/ui-plugin-sheets/src/Controller/shortcuts/style.shortcut.ts b/packages/ui-plugin-sheets/src/Controller/shortcuts/style.shortcut.ts
new file mode 100644
index 0000000000..db76db2dba
--- /dev/null
+++ b/packages/ui-plugin-sheets/src/Controller/shortcuts/style.shortcut.ts
@@ -0,0 +1,22 @@
+import { SetBoldCommand, SetItalicCommand, SetStrikeThroughCommand, SetUnderlineCommand } from '@univerjs/base-sheets';
+import { IShortcutItem, KeyCode, MetaKeys } from '@univerjs/base-ui';
+
+export const SetBoldShortcutItem: IShortcutItem = {
+ id: SetBoldCommand.id,
+ binding: KeyCode.B | MetaKeys.CTRL_COMMAND,
+};
+
+export const SetItalicShortcutItem: IShortcutItem = {
+ id: SetItalicCommand.id,
+ binding: KeyCode.I | MetaKeys.CTRL_COMMAND,
+};
+
+export const SetUnderlineShortcutItem: IShortcutItem = {
+ id: SetUnderlineCommand.id,
+ binding: KeyCode.U | MetaKeys.CTRL_COMMAND,
+};
+
+export const SetStrikeThroughShortcutItem: IShortcutItem = {
+ id: SetStrikeThroughCommand.id,
+ binding: KeyCode.X | MetaKeys.SHIFT | MetaKeys.CTRL_COMMAND,
+};
diff --git a/packages/ui-plugin-sheets/src/SheetUIPlugin.ts b/packages/ui-plugin-sheets/src/SheetUIPlugin.ts
index 123afb7151..d5331c00f1 100644
--- a/packages/ui-plugin-sheets/src/SheetUIPlugin.ts
+++ b/packages/ui-plugin-sheets/src/SheetUIPlugin.ts
@@ -24,6 +24,7 @@ import { Fx } from './View/FormulaBar';
import { SlotComponentProps } from './Controller/SlotController';
import { IToolbarItemProps } from './Controller/ToolbarUIController';
import { zh, en } from './Locale';
+import { DesktopSheetShortcutController } from './Controller/shortcut.controller';
export class SheetUIPlugin extends Plugin<SheetUIPluginObserve> {
static override type = PluginType.Sheet;
@@ -175,6 +176,7 @@ export class SheetUIPlugin extends Plugin<SheetUIPluginObserve> {
[IPlatformService, { useClass: DesktopPlatformService }],
[SharedController],
[IMenuService, { useClass: DesktopMenuService }],
+ [DesktopSheetShortcutController],
];
dependencies.forEach((d) => this._injector.add(d));
@@ -189,5 +191,6 @@ export class SheetUIPlugin extends Plugin<SheetUIPluginObserve> {
this._injector.get(IUndoRedoService);
this._injector.get(SharedController);
+ this._injector.get(DesktopSheetShortcutController);
}
}
diff --git a/packages/ui-plugin-sheets/src/View/RightMenu/RightMenu.tsx b/packages/ui-plugin-sheets/src/View/RightMenu/RightMenu.tsx
index b5432d0e7e..abf20f75ad 100644
--- a/packages/ui-plugin-sheets/src/View/RightMenu/RightMenu.tsx
+++ b/packages/ui-plugin-sheets/src/View/RightMenu/RightMenu.tsx
@@ -1,5 +1,5 @@
import { IMouseEvent } from '@univerjs/base-render';
-import { BaseRightMenuProps, Menu } from '@univerjs/base-ui';
+import { BaseRightMenuProps, IDisplayMenuItem, Menu } from '@univerjs/base-ui';
import { Component, createRef } from 'preact';
import { RightMenuProps } from '../../Controller';
import Style from './index.module.less';
@@ -9,6 +9,7 @@ interface IState {
srcElement: any;
eventType: string | null;
children: RightMenuProps[];
+ menuItems: IDisplayMenuItem[];
}
export class RightMenu extends Component<BaseRightMenuProps, IState> {
@@ -27,6 +28,7 @@ export class RightMenu extends Component<BaseRightMenuProps, IState> {
srcElement: null,
eventType: null,
children: [],
+ menuItems: [],
};
}
@@ -36,6 +38,12 @@ export class RightMenu extends Component<BaseRightMenuProps, IState> {
});
}
+ setMenuListNeo = (menuItems: IDisplayMenuItem[]) => {
+ this.setState({
+ menuItems,
+ });
+ };
+
// TODO:添加到具体的元素
override componentDidMount() {
this.props.getComponent?.(this);
@@ -134,7 +142,7 @@ export class RightMenu extends Component<BaseRightMenuProps, IState> {
e.preventDefault();
}}
>
- <Menu ref={this.ulRef} menu={this.state.children} onClick={this.handleClick}></Menu>
+ <Menu ref={this.ulRef} menuItems={this.state.menuItems} menu={this.state.children} onClick={this.handleClick}></Menu>
</div>
)
);
diff --git a/packages/ui-plugin-sheets/src/View/RightMenu/index.ts b/packages/ui-plugin-sheets/src/View/RightMenu/index.ts
index caa1ab04bc..5b953c9cb0 100644
--- a/packages/ui-plugin-sheets/src/View/RightMenu/index.ts
+++ b/packages/ui-plugin-sheets/src/View/RightMenu/index.ts
@@ -2,4 +2,5 @@ export * from './RightMenu';
export * from './RightMenuButton';
export * from './RightMenuInput';
export * from './RightMenuItem';
-// export * from './RightMenuSelect';
+
+// TODO: RightMenu should be renamed to ContextMenu. RightMenu is not a common name.
diff --git a/packages/ui-plugin-sheets/src/View/Toolbar/Toolbar.tsx b/packages/ui-plugin-sheets/src/View/Toolbar/Toolbar.tsx
index fc31326b14..9a66b57d20 100644
--- a/packages/ui-plugin-sheets/src/View/Toolbar/Toolbar.tsx
+++ b/packages/ui-plugin-sheets/src/View/Toolbar/Toolbar.tsx
@@ -1,4 +1,4 @@
-import { AppContext, BaseComponentProps, Button, Container, CustomLabel, debounce, IMenuItem, Select, Tooltip } from '@univerjs/base-ui';
+import { AppContext, BaseComponentProps, Button, Container, CustomLabel, debounce, IDisplayMenuItem, Select, Tooltip } from '@univerjs/base-ui';
import { Component, createRef } from 'preact';
import { IToolbarItemProps, SheetContainerUIController } from '../../Controller';
import styles from './index.module.less';
@@ -15,7 +15,7 @@ interface IState {
defaultToolList: IToolbarItemProps[];
showMore: boolean;
toolbarListWidths: number[];
- menuItems: IMenuItem[];
+ menuItems: IDisplayMenuItem[];
}
export class Toolbar extends Component<IProps, IState> {
@@ -150,7 +150,7 @@ export class Toolbar extends Component<IProps, IState> {
}
};
- setToolbarNeo = (menuItems: IMenuItem[]) => {
+ setToolbarNeo = (menuItems: IDisplayMenuItem[]) => {
this.setState(
{
menuItems,
diff --git a/packages/ui-plugin-sheets/src/View/Toolbar/ToolbarItem.tsx b/packages/ui-plugin-sheets/src/View/Toolbar/ToolbarItem.tsx
index a72f02ea25..0e10bffaa2 100644
--- a/packages/ui-plugin-sheets/src/View/Toolbar/ToolbarItem.tsx
+++ b/packages/ui-plugin-sheets/src/View/Toolbar/ToolbarItem.tsx
@@ -1,24 +1,29 @@
import { ComponentChild, Component } from 'preact';
import { Subscription } from 'rxjs';
-import { AppContext, IMenuItem, Button, Tooltip, CustomLabel } from '@univerjs/base-ui';
+import { AppContext, Button, Tooltip, CustomLabel } from '@univerjs/base-ui';
import { ICommandService } from '@univerjs/core';
import styles from './index.module.less';
export interface IToolbarItemStatus {
disabled: boolean;
+ activated: boolean;
}
-export class ToolbarItem extends Component<IMenuItem, IToolbarItemStatus> {
+export class ToolbarItem extends Component<IDisplayMenuItem, IToolbarItemStatus> {
static override contextType = AppContext;
+
private disabledSubscription: Subscription | undefined;
+ private activatedSubscription: Subscription | undefined;
+
constructor() {
super();
this.state = {
- disabled: true,
+ disabled: false,
+ activated: false,
};
}
@@ -26,6 +31,10 @@ export class ToolbarItem extends Component<IMenuItem, IToolbarItemStatus> {
this.disabledSubscription = this.props.disabled$?.subscribe((disabled) => {
this.setState({ disabled });
});
+
+ this.activatedSubscription = this.props.activated$?.subscribe((activated) => {
+ this.setState({ activated });
+ });
}
override componentWillMount() {
@@ -35,11 +44,11 @@ export class ToolbarItem extends Component<IMenuItem, IToolbarItemStatus> {
render(): ComponentChild {
const { props, context } = this;
const commandService: ICommandService = context.injector.get(ICommandService);
- const { disabled } = this.state;
+ const { disabled, activated } = this.state;
return (
- <Tooltip title={props.title} placement="bottom">
- <Button className={styles.textButton} type="text" disabled={disabled} onClick={() => commandService.executeCommand(props.id)}>
+ <Tooltip title={props.title + (props.shortcut ? ` (${props.shortcut})` : '')} placement="bottom">
+ <Button active={activated} className={styles.textButton} type="text" disabled={disabled} onClick={() => commandService.executeCommand(props.id)}>
<CustomLabel label={{ name: props.icon }} />
</Button>
</Tooltip>