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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(cliboard): add clipboard services and multi command (#158)
Wenzhao Hu4f9c3adf875c
diff --git a/.prettierrc.js b/.prettierrc.jsindex 6d1a9e66d9..dde2feddd8 100644--- a/.prettierrc.js+++ b/.prettierrc.js@@ -1,5 +1,5 @@module.exports = {- printWidth: 180, // TODO: change this to 120+ printWidth: 120,semi: true,singleQuote: true,tabWidth: 4,diff --git a/.vscode/settings.json b/.vscode/settings.jsonindex 57af63f226..8e87c81dd3 100644--- a/.vscode/settings.json+++ b/.vscode/settings.json@@ -66,4 +66,5 @@"Xingkai","Xinwei"],-}\ No newline at end of file+ "vsicons.presets.angular": false+}diff --git a/packages/base-docs/src/DocPlugin.ts b/packages/base-docs/src/DocPlugin.tsindex f1722d3e1b..e5c3b1c18a 100644--- a/packages/base-docs/src/DocPlugin.ts+++ b/packages/base-docs/src/DocPlugin.ts@@ -1,5 +1,5 @@import { Engine } from '@univerjs/base-render';-import { ContextService, DesktopPlatformService, IContextService, IPlatformService, IShortcutService } from '@univerjs/base-ui';+import { DesktopPlatformService, IPlatformService, IShortcutService } from '@univerjs/base-ui';import { ICommand, ICommandService, ICurrentUniverService, LocaleService, Plugin, PLUGIN_NAMES, PluginType } from '@univerjs/core';import { Dependency, Inject, Injector, SkipSelf } from '@wendellhu/redi';@@ -164,7 +164,6 @@ export class DocPlugin extends Plugin<DocPluginObserve> {[[CanvasView, { useFactory: () => docInjector.createInstance(CanvasView, this._config.standalone ?? true) }], // FIXME: CanvasView shouldn't be a dependency of DocPlugin. Because it maybe created dynamically.[IPlatformService, { useClass: DesktopPlatformService }],- [IContextService, { useClass: ContextService }],] as Dependency[]).forEach((d) => docInjector.add(d));diff --git a/packages/base-docs/src/shortcuts/core-editing.shortcut.ts b/packages/base-docs/src/shortcuts/core-editing.shortcut.tsindex 77a65f8371..45c5a3f27e 100644--- a/packages/base-docs/src/shortcuts/core-editing.shortcut.ts+++ b/packages/base-docs/src/shortcuts/core-editing.shortcut.ts@@ -1,4 +1,5 @@-import { FOCUSING_DOC, IShortcutItem, KeyCode } from '@univerjs/base-ui';+import { IShortcutItem, KeyCode } from '@univerjs/base-ui';+import { FOCUSING_DOC } from '@univerjs/core';import { BreakLineCommand, DeleteLeftCommand } from '../commands/commands/core-editing.command';diff --git a/packages/base-docs/src/shortcuts/cursor.shortcut.ts b/packages/base-docs/src/shortcuts/cursor.shortcut.tsindex 0d56988797..49d39a3897 100644--- a/packages/base-docs/src/shortcuts/cursor.shortcut.ts+++ b/packages/base-docs/src/shortcuts/cursor.shortcut.ts@@ -1,5 +1,5 @@-import { FOCUSING_DOC, IShortcutItem, KeyCode } from '@univerjs/base-ui';-import { Direction } from '@univerjs/core';+import { IShortcutItem, KeyCode } from '@univerjs/base-ui';+import { Direction, FOCUSING_DOC } from '@univerjs/core';import { MoveCursorOperation } from '../commands/operations/cursor.operation';diff --git a/packages/base-render/src/Basics/Tools.ts b/packages/base-render/src/Basics/Tools.tsindex 574d64259a..c1fbc7db09 100644--- a/packages/base-render/src/Basics/Tools.ts+++ b/packages/base-render/src/Basics/Tools.ts@@ -1,4 +1,14 @@-import { BaselineOffset, FontStyleType, ICellInfo, IRangeData, IScale, ISelection, IStyleBase, Nullable, Tools } from '@univerjs/core';+import {+ BaselineOffset,+ FontStyleType,+ ICellInfo,+ IRangeData,+ IScale,+ ISelection,+ IStyleBase,+ Nullable,+ Tools,+} from '@univerjs/core';import { DEFAULT_FONTFACE_PLANE } from './Const';import { FontCache } from './FontCache';@@ -226,7 +236,11 @@ export function getFontStyleString(textStyle?: IStyleBase, fontLocale?: IFontLocconst { fontList, defaultFontSize } = fontLocale;if (!textStyle) {- return { fontString: `${defaultFontSize}px ${fontList[0]}`, fontSize: defaultFontSize, fontFamily: fontList[0] };+ return {+ fontString: `${defaultFontSize}px ${fontList[0]}`,+ fontSize: defaultFontSize,+ fontFamily: fontList[0],+ };}// font-style@@ -452,7 +466,12 @@ export function getScale(parentScale: IScale) {return Math.max(scaleX, scaleY);}-export function getCellPositionByIndex(row: number, column: number, rowHeightAccumulation: number[], columnWidthAccumulation: number[]) {+export function getCellPositionByIndex(+ row: number,+ column: number,+ rowHeightAccumulation: number[],+ columnWidthAccumulation: number[]+) {const startRow = row - 1;const startColumn = column - 1;@@ -470,11 +489,26 @@ export function getCellPositionByIndex(row: number, column: number, rowHeightAcc};}-export function getCellByIndex(row: number, column: number, rowHeightAccumulation: number[], columnWidthAccumulation: number[], mergeData: IRangeData[]): ICellInfo {+export function getCellByIndex(+ row: number,+ column: number,+ rowHeightAccumulation: number[],+ columnWidthAccumulation: number[],+ mergeData: IRangeData[]+): ICellInfo {// eslint-disable-next-line prefer-const- let { startY, endY, startX, endX } = getCellPositionByIndex(row, column, rowHeightAccumulation, columnWidthAccumulation);+ let { startY, endY, startX, endX } = getCellPositionByIndex(+ row,+ column,+ rowHeightAccumulation,+ columnWidthAccumulation+ );- const { isMerged, isMergedMainCell, startRow, startColumn, endRow, endColumn } = mergeCellHandler(row, column, mergeData);+ const { isMerged, isMergedMainCell, startRow, startColumn, endRow, endColumn } = mergeCellHandler(+ row,+ column,+ mergeData+ );let mergeInfo = {startRow,startColumn,@@ -517,6 +551,7 @@ export function getCellByIndex(row: number, column: number, rowHeightAccumulatio};}+// WTF: this name doesn't express any useful information about what is this used forexport function mergeCellHandler(row: number, column: number, mergeData?: IRangeData[]) {let isMerged = false; // The upper left cell only renders the contentlet isMergedMainCell = false;@@ -538,7 +573,12 @@ export function mergeCellHandler(row: number, column: number, mergeData?: IRange};}for (let i = 0; i < mergeData.length; i++) {- const { startRow: startRowMarge, endRow: endRowMarge, startColumn: startColumnMarge, endColumn: endColumnMarge } = mergeData[i];+ const {+ startRow: startRowMarge,+ endRow: endRowMarge,+ startColumn: startColumnMarge,+ endColumn: endColumnMarge,+ } = mergeData[i];if (row === startRowMarge && column === startColumnMarge) {newEndRow = endRowMarge;newEndColumn = endColumnMarge;@@ -558,34 +598,7 @@ export function mergeCellHandler(row: number, column: number, mergeData?: IRangebreak;}}- // dataMergeCache?.forEach((r, dataMergeRow) => {- // let isSuspended = false;- // dataMergeRow?.forEach((c, dataCache) => {- // const { startRow: startRowMarge, endRow: endRowMarge, startColumn: startColumnMarge, endColumn: endColumnMarge } = dataCache;- // if (row === startRowMarge && column === startColumnMarge) {- // newEndRow = endRowMarge;- // newEndColumn = endColumnMarge;- // mergeRow = startRowMarge;- // mergeColumn = startColumnMarge;- // isSuspended = true;- // isMergedMainCell = true;- // return false;- // }- // if (row >= startRowMarge && row <= endRowMarge && column >= startColumnMarge && column <= endColumnMarge) {- // newEndRow = endRowMarge;- // newEndColumn = endColumnMarge;- // mergeRow = startRowMarge;- // mergeColumn = startColumnMarge;- // isSuspended = true;- // isMerged = true;- // return false;- // }- // });-- // if (isSuspended) {- // return false;- // }- // });+return {row,column,@@ -598,7 +611,13 @@ export function mergeCellHandler(row: number, column: number, mergeData?: IRange};}-export function mergeInfoOffset(mergeInfo: ISelection, offsetX: number, offsetY: number, scaleX: number, scaleY: number) {+export function mergeInfoOffset(+ mergeInfo: ISelection,+ offsetX: number,+ offsetY: number,+ scaleX: number,+ scaleY: number+) {const { startY, endY, startX, endX } = mergeInfo;mergeInfo.startY = fixLineWidthByScale(startY + offsetY, scaleY);mergeInfo.endY = fixLineWidthByScale(endY + offsetY, scaleY);@@ -611,7 +630,12 @@ export function mergeInfoOffset(mergeInfo: ISelection, offsetX: number, offsetY:}export function isRectIntersect(rect1: IBoundRectNoAngle, rect2: IBoundRectNoAngle) {- return !(rect1.left > rect2.right || rect1.top > rect2.bottom || rect2.left > rect1.right || rect2.top > rect1.bottom);+ return !(+ rect1.left > rect2.right ||+ rect1.top > rect2.bottom ||+ rect2.left > rect1.right ||+ rect2.top > rect1.bottom+ );}export function injectStyle(styles: string[]) {diff --git a/packages/base-render/src/Component/Docs/Document.ts b/packages/base-render/src/Component/Docs/Document.tsindex 74c69b5a1c..6d89cc232f 100644--- a/packages/base-render/src/Component/Docs/Document.ts+++ b/packages/base-render/src/Component/Docs/Document.ts@@ -1,9 +1,22 @@import './Extensions';-import { BooleanNumber, HorizontalAlign, Nullable, Observable, Observer, VerticalAlign, WrapStrategy } from '@univerjs/core';+import {+ BooleanNumber,+ HorizontalAlign,+ Nullable,+ Observable,+ Observer,+ VerticalAlign,+ WrapStrategy,+} from '@univerjs/core';import { calculateRectRotate, getRotateOffsetAndFarthestHypotenuse } from '../../Basics/Draw';-import { IDocumentSkeletonCached, IDocumentSkeletonPage, LineType, PageLayoutType } from '../../Basics/IDocumentSkeletonCached';+import {+ IDocumentSkeletonCached,+ IDocumentSkeletonPage,+ LineType,+ PageLayoutType,+} from '../../Basics/IDocumentSkeletonCached';import { INodeInfo } from '../../Basics/Interfaces';import { degToRad, fixLineWidthByScale, getScale } from '../../Basics/Tools';import { IBoundRect, Vector2 } from '../../Basics/Vector2';@@ -175,9 +188,22 @@ export class Documents extends DocComponent {if (!this._hasEditor) {return;}- const { onInputObservable, onCompositionstartObservable, onCompositionupdateObservable, onCompositionendObservable, onKeydownObservable, onSelectionStartObservable } =- this._editor;- return { onInputObservable, onCompositionstartObservable, onCompositionupdateObservable, onCompositionendObservable, onKeydownObservable, onSelectionStartObservable };+ const {+ onInputObservable,+ onCompositionstartObservable,+ onCompositionupdateObservable,+ onCompositionendObservable,+ onKeydownObservable,+ onSelectionStartObservable,+ } = this._editor;+ return {+ onInputObservable,+ onCompositionstartObservable,+ onCompositionupdateObservable,+ onCompositionendObservable,+ onKeydownObservable,+ onSelectionStartObservable,+ };}override remainActiveSelection() {@@ -217,11 +243,6 @@ export class Documents extends DocComponent {return;}- const isDrawingCellEditor = documentSkeleton.getModel().snapshot.id === 'sheet.model.cell-editor';- if (isDrawingCellEditor) {- console.log('drawing', documentSkeleton, documentSkeleton.getModel().snapshot);- }-// if (this.isCalculateSkeleton) {// documentSkeleton.calculate(bounds);// }@@ -263,8 +284,18 @@ export class Documents extends DocComponent {isRotateNonEastAsian = BooleanNumber.FALSE,} = renderConfig;- const horizontalOffsetNoAngle = this._horizontalHandler(pageWidth, pagePaddingLeft, pagePaddingRight, horizontalAlign);- const verticalOffsetNoAngle = this._verticalHandler(pageHeight, pagePaddingTop, pagePaddingBottom, verticalAlign);+ const horizontalOffsetNoAngle = this._horizontalHandler(+ pageWidth,+ pagePaddingLeft,+ pagePaddingRight,+ horizontalAlign+ );+ const verticalOffsetNoAngle = this._verticalHandler(+ pageHeight,+ pagePaddingTop,+ pagePaddingBottom,+ verticalAlign+ );const alignOffsetNoAngle = Vector2.create(horizontalOffsetNoAngle, verticalOffsetNoAngle);const centerAngle = degToRad(centerAngleDeg);@@ -297,11 +328,14 @@ export class Documents extends DocComponent {let alignOffset;let rotateTranslateXListApply = null;if (vertexAngle !== 0) {- const { rotateTranslateXList, rotatedHeight, rotatedWidth, fixOffsetX, fixOffsetY, rotateTranslateY } = getRotateOffsetAndFarthestHypotenuse(- lines,- columnWidth,- vertexAngle- );+ const {+ rotateTranslateXList,+ rotatedHeight,+ rotatedWidth,+ fixOffsetX,+ fixOffsetY,+ rotateTranslateY,+ } = getRotateOffsetAndFarthestHypotenuse(lines, columnWidth, vertexAngle);let exceedWidthFix = rotatedWidth;if (rotatedHeight > this.height && wrapStrategy !== WrapStrategy.WRAP) {@@ -310,9 +344,19 @@ export class Documents extends DocComponent {}}- const horizontalOffset = this._horizontalHandler(exceedWidthFix, pagePaddingLeft, pagePaddingRight, horizontalAlign);+ const horizontalOffset = this._horizontalHandler(+ exceedWidthFix,+ pagePaddingLeft,+ pagePaddingRight,+ horizontalAlign+ );- const verticalOffset = this._verticalHandler(rotatedHeight, pagePaddingTop, pagePaddingBottom, verticalAlign);+ const verticalOffset = this._verticalHandler(+ rotatedHeight,+ pagePaddingTop,+ pagePaddingBottom,+ verticalAlign+ );let exceedHeightFix = verticalOffset - fixOffsetY;if (rotatedHeight > this.height) {@@ -376,10 +420,19 @@ export class Documents extends DocComponent {const { width: spanWidth, left: spanLeft, paddingLeft } = span;const { x: translateX, y: translateY } = this._drawLiquid;- const originTranslate = Vector2.create(fixLineWidthByScale(translateX, scale), fixLineWidthByScale(translateY, scale));- const centerPoint = Vector2.create(fixLineWidthByScale(spanWidth / 2, scale), fixLineWidthByScale(lineHeight / 2, scale));+ const originTranslate = Vector2.create(+ fixLineWidthByScale(translateX, scale),+ fixLineWidthByScale(translateY, scale)+ );+ const centerPoint = Vector2.create(+ fixLineWidthByScale(spanWidth / 2, scale),+ fixLineWidthByScale(lineHeight / 2, scale)+ );const spanStartPoint = calculateRectRotate(- originTranslate.addByPoint(fixLineWidthByScale(spanLeft + paddingLeft, scale), 0),+ originTranslate.addByPoint(+ fixLineWidthByScale(spanLeft + paddingLeft, scale),+ 0+ ),centerPoint,centerAngle,vertexAngle,@@ -387,7 +440,10 @@ export class Documents extends DocComponent {);const spanPointWithFont = calculateRectRotate(- originTranslate.addByPoint(fixLineWidthByScale(spanLeft + maxLineAscSin + paddingLeft, scale), fixLineWidthByScale(maxLineAscCos, scale)),+ originTranslate.addByPoint(+ fixLineWidthByScale(spanLeft + maxLineAscSin + paddingLeft, scale),+ fixLineWidthByScale(maxLineAscCos, scale)+ ),centerPoint,centerAngle,vertexAngle,@@ -420,7 +476,12 @@ export class Documents extends DocComponent {this._resetRotation(ctx, finalAngle);- const { x, y } = this._drawLiquid.translatePage(page, this.pageLayoutType, this.pageMarginLeft, this.pageMarginTop);+ const { x, y } = this._drawLiquid.translatePage(+ page,+ this.pageLayoutType,+ this.pageMarginLeft,+ this.pageMarginTop+ );pageLeft += x;pageTop += y;}@@ -651,7 +712,12 @@ export class Documents extends DocComponent {return nearestNodeList[miniValueIndex];}- private _horizontalHandler(pageWidth: number, pagePaddingLeft: number, pagePaddingRight: number, horizontalAlign: HorizontalAlign) {+ private _horizontalHandler(+ pageWidth: number,+ pagePaddingLeft: number,+ pagePaddingRight: number,+ horizontalAlign: HorizontalAlign+ ) {let offsetLeft = 0;if (horizontalAlign === HorizontalAlign.CENTER) {offsetLeft = (this.width - pageWidth) / 2;@@ -664,7 +730,12 @@ export class Documents extends DocComponent {return offsetLeft;}- private _verticalHandler(pageHeight: number, pagePaddingTop: number, pagePaddingBottom: number, verticalAlign: VerticalAlign) {+ private _verticalHandler(+ pageHeight: number,+ pagePaddingTop: number,+ pagePaddingBottom: number,+ verticalAlign: VerticalAlign+ ) {let offsetTop = 0;if (verticalAlign === VerticalAlign.MIDDLE) {offsetTop = (this.height - pageHeight) / 2;diff --git a/packages/base-render/src/Component/Sheets/SheetSkeleton.ts b/packages/base-render/src/Component/Sheets/SheetSkeleton.tsindex 1f86589df2..dbe9794d34 100644--- a/packages/base-render/src/Component/Sheets/SheetSkeleton.ts+++ b/packages/base-render/src/Component/Sheets/SheetSkeleton.ts@@ -33,7 +33,14 @@ import {import { BORDER_TYPE, COLOR_BLACK_RGB } from '../../Basics/Const';import { IFontLocale } from '../../Basics/Interfaces';-import { fixLineWidthByScale, getCellByIndex, getCellPositionByIndex, getFontStyleString, isRectIntersect, mergeInfoOffset } from '../../Basics/Tools';+import {+ fixLineWidthByScale,+ getCellByIndex,+ getCellPositionByIndex,+ getFontStyleString,+ isRectIntersect,+ mergeInfoOffset,+} from '../../Basics/Tools';import { IBoundRect } from '../../Basics/Vector2';import { DocumentSkeleton } from '../Docs/DocSkeleton';import { Skeleton } from '../Skeleton';@@ -105,7 +112,12 @@ export class SpreadsheetSkeleton extends Skeleton {private _showGridlines: BooleanNumber;- constructor(private _config: IWorksheetConfig, private _cellData: ObjectMatrix<ICellData>, private _styles: Styles, _localeService: LocaleService) {+ constructor(+ private _config: IWorksheetConfig,+ private _cellData: ObjectMatrix<ICellData>,+ private _styles: Styles,+ _localeService: LocaleService+ ) {super(_localeService);this.updateLayout();@@ -164,7 +176,12 @@ export class SpreadsheetSkeleton extends Skeleton {// return this._dataMergeCacheAll;// }- static create(config: IWorksheetConfig, cellData: ObjectMatrix<ICellData>, styles: Styles, LocaleService: LocaleService) {+ static create(+ config: IWorksheetConfig,+ cellData: ObjectMatrix<ICellData>,+ styles: Styles,+ LocaleService: LocaleService+ ) {return new SpreadsheetSkeleton(config, cellData, styles, LocaleService);}@@ -208,9 +225,27 @@ export class SpreadsheetSkeleton extends Skeleton {if (!this.dirty) {return;}- const { rowData, columnData, defaultRowHeight, defaultColumnWidth, rowCount, columnCount, rowTitle, columnTitle, showGridlines } = this._config;- const { rowTotalHeight, rowHeightAccumulation } = this._generateRowMatrixCache(rowCount, rowData, defaultRowHeight);- const { columnTotalWidth, columnWidthAccumulation } = this._generateColumnMatrixCache(columnCount, columnData, defaultColumnWidth);+ const {+ rowData,+ columnData,+ defaultRowHeight,+ defaultColumnWidth,+ rowCount,+ columnCount,+ rowTitle,+ columnTitle,+ showGridlines,+ } = this._config;+ const { rowTotalHeight, rowHeightAccumulation } = this._generateRowMatrixCache(+ rowCount,+ rowData,+ defaultRowHeight+ );+ const { columnTotalWidth, columnWidthAccumulation } = this._generateColumnMatrixCache(+ columnCount,+ columnData,+ defaultColumnWidth+ );this._rowTitleWidth = rowTitle.hidden !== BooleanNumber.TRUE ? rowTitle.width : 0;this._columnTitleHeight = columnTitle.hidden !== BooleanNumber.TRUE ? columnTitle.height : 0;@@ -246,14 +281,22 @@ export class SpreadsheetSkeleton extends Skeleton {endColumn,};}+let isSearching = true;const searchedMarge = new ObjectMatrix<boolean>();- // const dataMergeCache = this._getMergeCells(mergeData);++ // the loop breaks when there are not merged cells intersect with the current range+ // NOTE: what about the performance issue?while (isSearching) {isSearching = false;for (let i = 0; i < mergeData.length; i++) {- const { startRow: mainStartRow, startColumn: mainStartColumn, endRow: mainEndRow, endColumn: mainEndColumn } = mergeData[i];+ const {+ startRow: mainStartRow,+ startColumn: mainStartColumn,+ endRow: mainEndRow,+ endColumn: mainEndColumn,+ } = mergeData[i];if (searchedMarge.getValue(mainStartRow, mainStartColumn)) {continue;@@ -282,38 +325,6 @@ export class SpreadsheetSkeleton extends Skeleton {isSearching = true;}}-- // dataMergeCache.forEach((row: number, rowArray: ObjectArray<IRangeData>) => {- // rowArray.forEach((column: number, mainCell: IRangeData) => {- // if (!mainCell || searchedMarge.getValue(row, column)) {- // return true;- // }- // const { startRow: mainStartRow, startColumn: mainStartColumn, endRow: mainEndRow, endColumn: mainEndColumn } = mainCell;-- // const rect1 = {- // left: startColumn,- // top: startRow,- // right: endColumn,- // bottom: endRow,- // };-- // const rect2 = {- // left: mainStartColumn,- // top: mainStartRow,- // right: mainEndColumn,- // bottom: mainEndRow,- // };-- // if (isRectIntersect(rect1, rect2)) {- // startRow = Math.min(startRow, mainStartRow);- // startColumn = Math.min(startColumn, mainStartColumn);- // endRow = Math.max(endRow, mainEndRow);- // endColumn = Math.max(endColumn, mainEndColumn);- // searchedMarge.setValue(row, column, true);- // isSearching = true;- // }- // });- // });}return {@@ -341,7 +352,13 @@ export class SpreadsheetSkeleton extends Skeleton {return this._rowHeightAccumulation.length;}- getOverflowPosition(contentSize: { width: number; height: number }, horizontalAlign: HorizontalAlign, row: number, column: number, columnCount: number) {+ getOverflowPosition(+ contentSize: { width: number; height: number },+ horizontalAlign: HorizontalAlign,+ row: number,+ column: number,+ columnCount: number+ ) {const { width: contentWidth, height: contentHeight } = contentSize;let startColumn = column;@@ -367,7 +384,12 @@ export class SpreadsheetSkeleton extends Skeleton {getNoMergeCellPositionByIndex(rowIndex: number, columnIndex: number, scaleX: number, scaleY: number) {const { rowHeightAccumulation, columnWidthAccumulation, rowTitleWidth, columnTitleHeight } = this;// const { scaleX = 1, scaleY = 1 } = this.getParentScale();- let { startY, endY, startX, endX } = getCellPositionByIndex(rowIndex, columnIndex, rowHeightAccumulation, columnWidthAccumulation);+ let { startY, endY, startX, endX } = getCellPositionByIndex(+ rowIndex,+ columnIndex,+ rowHeightAccumulation,+ columnWidthAccumulation+ );startY = fixLineWidthByScale(startY + columnTitleHeight, scaleY);endY = fixLineWidthByScale(endY + columnTitleHeight, scaleY);@@ -382,7 +404,13 @@ export class SpreadsheetSkeleton extends Skeleton {};}- calculateCellIndexByPosition(offsetX: number, offsetY: number, scaleX: number, scaleY: number, scrollXY: { x: number; y: number }): Nullable<ICellInfo> {+ calculateCellIndexByPosition(+ offsetX: number,+ offsetY: number,+ scaleX: number,+ scaleY: number,+ scrollXY: { x: number; y: number }+ ): Nullable<ICellInfo> {const { x: scrollX, y: scrollY } = scrollXY;// these values are not affected by zooming (ideal positions)@@ -415,7 +443,13 @@ export class SpreadsheetSkeleton extends Skeleton {}}- const cellInfo = getCellByIndex(row, column, rowHeightAccumulation, columnWidthAccumulation, this._config.mergeData);+ const cellInfo = getCellByIndex(+ row,+ column,+ rowHeightAccumulation,+ columnWidthAccumulation,+ this._config.mergeData+ );const { isMerged, isMergedMainCell } = cellInfo;let { startY, endY, startX, endX, mergeInfo } = cellInfo;@@ -449,7 +483,13 @@ export class SpreadsheetSkeleton extends Skeleton {getCellByIndex(row: number, column: number, scaleX: number, scaleY: number) {const { rowHeightAccumulation, columnWidthAccumulation, rowTitleWidth, columnTitleHeight } = this;- const cellInfo = getCellByIndex(row, column, rowHeightAccumulation, columnWidthAccumulation, this._config.mergeData);+ const cellInfo = getCellByIndex(+ row,+ column,+ rowHeightAccumulation,+ columnWidthAccumulation,+ this._config.mergeData+ );const { isMerged, isMergedMainCell } = cellInfo;let { startY, endY, startX, endX, mergeInfo } = cellInfo;@@ -582,7 +622,11 @@ export class SpreadsheetSkeleton extends Skeleton {};}- private _generateRowMatrixCache(rowCount: number, rowData: ObjectArrayType<Partial<IRowData>>, defaultRowHeight: number) {+ private _generateRowMatrixCache(+ rowCount: number,+ rowData: ObjectArrayType<Partial<IRowData>>,+ defaultRowHeight: number+ ) {let rowTotalHeight = 0;const rowHeightAccumulation: number[] = [];const data = Tools.createObjectArray(rowData);@@ -618,7 +662,11 @@ export class SpreadsheetSkeleton extends Skeleton {};}- private _generateColumnMatrixCache(colCount: number, columnData: ObjectArrayType<Partial<IColumnData>>, defaultColumnWidth: number) {+ private _generateColumnMatrixCache(+ colCount: number,+ columnData: ObjectArrayType<Partial<IColumnData>>,+ defaultColumnWidth: number+ ) {let columnTotalWidth = 0;const columnWidthAccumulation: number[] = [];@@ -719,7 +767,12 @@ export class SpreadsheetSkeleton extends Skeleton {}return column + 1 > columnCount ? columnCount : column + 1;}- const { startX, endX } = getCellPositionByIndex(row, column, this.rowHeightAccumulation, this.columnWidthAccumulation);+ const { startX, endX } = getCellPositionByIndex(+ row,+ column,+ this.rowHeightAccumulation,+ this.columnWidthAccumulation+ );cumWidth += endX - startX;if (contentWidth < cumWidth) {return column;@@ -737,7 +790,12 @@ export class SpreadsheetSkeleton extends Skeleton {return column - 1 < 0 ? 0 : column - 1;}- const { startX, endX } = getCellPositionByIndex(row, column, this.rowHeightAccumulation, this.columnWidthAccumulation);+ const { startX, endX } = getCellPositionByIndex(+ row,+ column,+ this.rowHeightAccumulation,+ this.columnWidthAccumulation+ );cumWidth += endX - startX;if (contentWidth < cumWidth) {return column;@@ -750,8 +808,18 @@ export class SpreadsheetSkeleton extends Skeleton {const dataMergeCache = this.dataMergeCache;let isIntersected = false;for (const dataCache of dataMergeCache) {- const { startRow: startRowMargeIndex, endRow: endRowMargeIndex, startColumn: startColumnMargeIndex, endColumn: endColumnMargeIndex } = dataCache;- if (row >= startRowMargeIndex && row <= endRowMargeIndex && column >= startColumnMargeIndex && column <= endColumnMargeIndex) {+ const {+ startRow: startRowMargeIndex,+ endRow: endRowMargeIndex,+ startColumn: startColumnMargeIndex,+ endColumn: endColumnMargeIndex,+ } = dataCache;+ if (+ row >= startRowMargeIndex &&+ row <= endRowMargeIndex &&+ column >= startColumnMargeIndex &&+ column <= endColumnMargeIndex+ ) {isIntersected = true;return false;}@@ -979,7 +1047,11 @@ export class SpreadsheetSkeleton extends Skeleton {}}- private _updateRenderConfigAndHorizon(document: IDocumentData, horizontalAlign: HorizontalAlign, renderConfig?: IDocumentRenderConfig) {+ private _updateRenderConfigAndHorizon(+ document: IDocumentData,+ horizontalAlign: HorizontalAlign,+ renderConfig?: IDocumentRenderConfig+ ) {if (!renderConfig) {return;}@@ -1147,12 +1219,22 @@ export class SpreadsheetSkeleton extends Skeleton {const endRow = this.rowHeightAccumulation.length - 1;rowColumnSegment = { startRow: 0, startColumn: 0, endRow, endColumn: endColumnLast };} else {- rowColumnSegment = { startRow: rowColumnSegment.startRow, endRow: rowColumnSegment.endRow, endColumn: endColumnLast, startColumn: 0 };+ rowColumnSegment = {+ startRow: rowColumnSegment.startRow,+ endRow: rowColumnSegment.endRow,+ endColumn: endColumnLast,+ startColumn: 0,+ };}const { startRow, startColumn, endRow, endColumn } = rowColumnSegment;const cacheDataMerge: IRangeData[] = [];for (let i = 0; i < mergeData.length; i++) {- const { startRow: mergeStartRow, endRow: mergeEndRow, startColumn: mergeStartColumn, endColumn: mergeEndColumn } = mergeData[i];+ const {+ startRow: mergeStartRow,+ endRow: mergeEndRow,+ startColumn: mergeStartColumn,+ endColumn: mergeEndColumn,+ } = mergeData[i];for (let r = startRow; r <= endRow; r++) {let isBreak = false;for (let c = startColumn; c <= endColumn; c++) {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.tsindex 3e5d4657af..a28b15cd8a 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,11 @@ import { CommandType, ICommand, ICommandService, ICurrentUniverService, IUndoRedimport { IAccessor } from '@wendellhu/redi';import { SelectionManagerService } from '../../Services/selection-manager.service';-import { ISetRangeStyleMutationParams, SetRangeStyleMutation, SetRangeStyleUndoMutationFactory } from '../Mutations/set-range-styles.mutation';-import { ISetRangeValuesMutationParams, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../Mutations/set-range-values.mutation';+import {+ ISetRangeValuesMutationParams,+ SetRangeValuesMutation,+ SetRangeValuesUndoMutationFactory,+} from '../Mutations/set-range-values.mutation';/*** The command to clear content in current selected ranges.@@ -18,39 +21,31 @@ export const ClearSelectionContentCommand: ICommand = {const undoRedoService = accessor.get(IUndoRedoService);const workbook = currentUniverService.getCurrentUniverSheetInstance().getWorkBook();+ const workbookId = workbook.getUnitId();const worksheet = workbook.getActiveSheet();const selections = selectionManagerService.getRangeDatas();if (!selections?.length) {return false;}- const cleanStyleMutationParams: ISetRangeStyleMutationParams = {- range: selections,- worksheetId: worksheet.getSheetId(),- workbookId: workbook.getUnitId(),- };- const setStyleMutationParams: ISetRangeStyleMutationParams = SetRangeStyleUndoMutationFactory(accessor, cleanStyleMutationParams);-- const cleanResult = commandService.executeCommand(SetRangeStyleMutation.id, cleanStyleMutationParams);-const clearMutationParams: ISetRangeValuesMutationParams = {rangeData: selections,+ workbookId: workbook.getUnitId(),worksheetId: worksheet.getSheetId(),};- const undoClearMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(accessor, clearMutationParams);+ const undoClearMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(+ accessor,+ clearMutationParams+ );const result = commandService.executeCommand(SetRangeValuesMutation.id, clearMutationParams);-- if (result && cleanResult) {+ if (result) {undoRedoService.pushUndoRedo({// 如果有多个 mutation 构成一个封装项目,那么要封装在同一个 undo redo element 里面// 通过勾子可以 hook 外部 controller 的代码来增加新的 actionURI: workbookId,undo() {- return (commandService.executeCommand(SetRangeValuesMutation.id, undoClearMutationParams) as Promise<boolean>).then((res) => {- if (res) return commandService.executeCommand(SetRangeStyleMutation.id, setStyleMutationParams);- return false;- });+ return commandService.executeCommand(SetRangeValuesMutation.id, undoClearMutationParams);},redo() {return commandService.executeCommand(SetRangeValuesMutation.id, clearMutationParams);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.tsindex 975762b9bd..382b84b85d 100644--- a/packages/base-sheets/src/Commands/Commands/remove-row-col.command.ts+++ b/packages/base-sheets/src/Commands/Commands/remove-row-col.command.ts@@ -1,4 +1,14 @@-import { CommandType, Dimension, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService, Nullable, Rectangle, Tools } from '@univerjs/core';+import {+ CommandType,+ Dimension,+ ICommand,+ ICommandService,+ ICurrentUniverService,+ IUndoRedoService,+ Nullable,+ Rectangle,+ Tools,+} from '@univerjs/core';import { IAccessor } from '@wendellhu/redi';import {@@ -16,8 +26,16 @@ import { AddWorksheetMergeMutation, AddWorksheetMergeMutationFactory } from '../import { DeleteRangeMutation, DeleteRangeUndoMutationFactory } from '../Mutations/delete-range.mutation';import { InsertRangeMutation } from '../Mutations/insert-range.mutation';import { InsertColMutation, InsertRowMutation } from '../Mutations/insert-row-col.mutation';-import { IRemoveColMutationFactory, IRemoveRowMutationFactory, RemoveColMutation, RemoveRowMutation } from '../Mutations/remove-row-col.mutation';-import { RemoveWorksheetMergeMutation, RemoveWorksheetMergeMutationFactory } from '../Mutations/remove-worksheet-merge.mutation';+import {+ IRemoveColMutationFactory,+ IRemoveRowMutationFactory,+ RemoveColMutation,+ RemoveRowMutation,+} from '../Mutations/remove-row-col.mutation';+import {+ RemoveWorksheetMergeMutation,+ RemoveWorksheetMergeMutationFactory,+} from '../Mutations/remove-worksheet-merge.mutation';export const RemoveRowCommand: ICommand = {type: CommandType.COMMAND,@@ -31,7 +49,11 @@ export const RemoveRowCommand: ICommand = {const selections = selectionManagerService.getRangeDatas();const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();- const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();+ const worksheetId = currentUniverService+ .getCurrentUniverSheetInstance()+ .getWorkBook()+ .getActiveSheet()+ .getSheetId();if (!selections?.length) return false;const workbook = currentUniverService.getUniverSheetInstance(workbookId)?.getWorkBook();if (!workbook) return false;@@ -59,7 +81,10 @@ export const RemoveRowCommand: ICommand = {shiftDimension: Dimension.ROWS,};- const insertRangeMutationParams: Nullable<IInsertRangeMutationParams> = DeleteRangeUndoMutationFactory(accessor, deleteRangeValueMutationParams);+ const insertRangeMutationParams: Nullable<IInsertRangeMutationParams> = DeleteRangeUndoMutationFactory(+ accessor,+ deleteRangeValueMutationParams+ );if (!insertRangeMutationParams) return false;const deleteResult = commandService.executeCommand(DeleteRangeMutation.id, deleteRangeValueMutationParams);@@ -94,7 +119,10 @@ export const RemoveRowCommand: ICommand = {worksheetId,ranges: Tools.deepClone(worksheet.getMergeData()),};- const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = RemoveWorksheetMergeMutationFactory(accessor, removeMergeMutationParams);+ const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = RemoveWorksheetMergeMutationFactory(+ accessor,+ removeMergeMutationParams+ );const removeResult = commandService.executeCommand(RemoveWorksheetMergeMutation.id, removeMergeMutationParams);const addMergeMutationParams: IAddWorksheetMergeMutationParams = {@@ -102,7 +130,10 @@ export const RemoveRowCommand: ICommand = {worksheetId,ranges: mergeData,};- const deleteMergeMutationParams: IRemoveWorksheetMergeMutationParams = AddWorksheetMergeMutationFactory(accessor, addMergeMutationParams);+ const deleteMergeMutationParams: IRemoveWorksheetMergeMutationParams = AddWorksheetMergeMutationFactory(+ accessor,+ addMergeMutationParams+ );const mergeResult = commandService.executeCommand(AddWorksheetMergeMutation.id, addMergeMutationParams);if (result && deleteResult && removeResult && mergeResult) {@@ -111,30 +142,51 @@ export const RemoveRowCommand: ICommand = {undo() {return (commandService.executeCommand(InsertRowMutation.id, undoMutationParams) as Promise<boolean>).then((res) => {- if (res) return commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);+ if (res)+ return commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);return false;}).then((res) => {- if (res) return commandService.executeCommand(RemoveWorksheetMergeMutation.id, deleteMergeMutationParams);+ if (res)+ return commandService.executeCommand(+ RemoveWorksheetMergeMutation.id,+ deleteMergeMutationParams+ );return false;}).then((res) => {- if (res) return commandService.executeCommand(AddWorksheetMergeMutation.id, undoRemoveMergeMutationParams);+ if (res)+ return commandService.executeCommand(+ AddWorksheetMergeMutation.id,+ undoRemoveMergeMutationParams+ );return false;});},redo() {return (commandService.executeCommand(RemoveRowMutation.id, redoMutationParams) as Promise<boolean>).then((res) => {- if (res) return commandService.executeCommand(DeleteRangeMutation.id, deleteRangeValueMutationParams);+ if (res)+ return commandService.executeCommand(+ DeleteRangeMutation.id,+ deleteRangeValueMutationParams+ );return false;}).then((res) => {- if (res) return commandService.executeCommand(RemoveWorksheetMergeMutation.id, removeMergeMutationParams);+ if (res)+ return commandService.executeCommand(+ RemoveWorksheetMergeMutation.id,+ removeMergeMutationParams+ );return false;}).then((res) => {- if (res) return commandService.executeCommand(AddWorksheetMergeMutation.id, addMergeMutationParams);+ if (res)+ return commandService.executeCommand(+ AddWorksheetMergeMutation.id,+ addMergeMutationParams+ );return false;});},@@ -157,7 +209,11 @@ export const RemoveColCommand: ICommand = {const selections = selectionManagerService.getRangeDatas();const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();- const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();+ const worksheetId = currentUniverService+ .getCurrentUniverSheetInstance()+ .getWorkBook()+ .getActiveSheet()+ .getSheetId();if (!selections?.length) return false;const workbook = currentUniverService.getUniverSheetInstance(workbookId)?.getWorkBook();if (!workbook) return false;@@ -184,7 +240,10 @@ export const RemoveColCommand: ICommand = {range: selections,shiftDimension: Dimension.COLUMNS,};- const insertRangeMutationParams: Nullable<IInsertRangeMutationParams> = DeleteRangeUndoMutationFactory(accessor, deleteRangeValueMutationParams);+ const insertRangeMutationParams: Nullable<IInsertRangeMutationParams> = DeleteRangeUndoMutationFactory(+ accessor,+ deleteRangeValueMutationParams+ );if (!insertRangeMutationParams) return false;const deleteResult = commandService.executeCommand(DeleteRangeMutation.id, deleteRangeValueMutationParams);@@ -198,7 +257,10 @@ export const RemoveColCommand: ICommand = {merge.startColumn -= count;} else if (startColumn > merge.endColumn) {continue;- } else if ((startColumn < merge.startColumn && endColumn > merge.endColumn) || (startColumn === merge.startColumn && endColumn === merge.endColumn)) {+ } else if (+ (startColumn < merge.startColumn && endColumn > merge.endColumn) ||+ (startColumn === merge.startColumn && endColumn === merge.endColumn)+ ) {mergeData.splice(i);i--;} else {@@ -220,7 +282,10 @@ export const RemoveColCommand: ICommand = {worksheetId,ranges: Tools.deepClone(worksheet.getMergeData()),};- const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = RemoveWorksheetMergeMutationFactory(accessor, removeMergeMutationParams);+ const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = RemoveWorksheetMergeMutationFactory(+ accessor,+ removeMergeMutationParams+ );const removeResult = commandService.executeCommand(RemoveWorksheetMergeMutation.id, removeMergeMutationParams);const addMergeMutationParams: IAddWorksheetMergeMutationParams = {@@ -228,7 +293,10 @@ export const RemoveColCommand: ICommand = {worksheetId,ranges: mergeData,};- const deleteMergeMutationParams: IRemoveWorksheetMergeMutationParams = AddWorksheetMergeMutationFactory(accessor, addMergeMutationParams);+ const deleteMergeMutationParams: IRemoveWorksheetMergeMutationParams = AddWorksheetMergeMutationFactory(+ accessor,+ addMergeMutationParams+ );const mergeResult = commandService.executeCommand(AddWorksheetMergeMutation.id, addMergeMutationParams);if (result && deleteResult && removeResult && mergeResult) {@@ -237,30 +305,51 @@ export const RemoveColCommand: ICommand = {undo() {return (commandService.executeCommand(InsertColMutation.id, undoMutationParams) as Promise<boolean>).then((res) => {- if (res) return commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);+ if (res)+ return commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);return false;}).then((res) => {- if (res) return commandService.executeCommand(RemoveWorksheetMergeMutation.id, deleteMergeMutationParams);+ if (res)+ return commandService.executeCommand(+ RemoveWorksheetMergeMutation.id,+ deleteMergeMutationParams+ );return false;}).then((res) => {- if (res) return commandService.executeCommand(AddWorksheetMergeMutation.id, undoRemoveMergeMutationParams);+ if (res)+ return commandService.executeCommand(+ AddWorksheetMergeMutation.id,+ undoRemoveMergeMutationParams+ );return false;});},redo() {return (commandService.executeCommand(RemoveColMutation.id, redoMutationParams) as Promise<boolean>).then((res) => {- if (res) return commandService.executeCommand(DeleteRangeMutation.id, deleteRangeValueMutationParams);+ if (res)+ return commandService.executeCommand(+ DeleteRangeMutation.id,+ deleteRangeValueMutationParams+ );return false;}).then((res) => {- if (res) return commandService.executeCommand(RemoveWorksheetMergeMutation.id, removeMergeMutationParams);+ if (res)+ return commandService.executeCommand(+ RemoveWorksheetMergeMutation.id,+ removeMergeMutationParams+ );return false;}).then((res) => {- if (res) return commandService.executeCommand(AddWorksheetMergeMutation.id, addMergeMutationParams);+ if (res)+ return commandService.executeCommand(+ AddWorksheetMergeMutation.id,+ addMergeMutationParams+ );return false;});},diff --git a/packages/base-sheets/src/Commands/Mutations/set-range-values.mutation.ts b/packages/base-sheets/src/Commands/Mutations/set-range-values.mutation.tsindex 67770ae94f..ec71b9503b 100644--- a/packages/base-sheets/src/Commands/Mutations/set-range-values.mutation.ts+++ b/packages/base-sheets/src/Commands/Mutations/set-range-values.mutation.ts@@ -1,4 +1,14 @@-import { CommandType, ICellData, ICopyToOptionsData, ICurrentUniverService, IMutation, IRangeData, ObjectMatrix, ObjectMatrixPrimitiveType, Tools } from '@univerjs/core';+import {+ CommandType,+ ICellData,+ ICopyToOptionsData,+ ICurrentUniverService,+ IMutation,+ IRangeData,+ ObjectMatrix,+ ObjectMatrixPrimitiveType,+ Tools,+} from '@univerjs/core';import { IAccessor } from '@wendellhu/redi';/** Params of `SetRangeValuesMutation` */@@ -18,9 +28,15 @@ export interface ISetRangeValuesMutationParams {* @param {ISetRangeValuesMutationParams} params - do mutation params* @returns {ISetRangeValuesMutationParams} undo mutation params*/-export const SetRangeValuesUndoMutationFactory = (accessor: IAccessor, params: ISetRangeValuesMutationParams): ISetRangeValuesMutationParams => {+export const SetRangeValuesUndoMutationFactory = (+ accessor: IAccessor,+ params: ISetRangeValuesMutationParams+): ISetRangeValuesMutationParams => {const currentUniverService = accessor.get(ICurrentUniverService);- const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getSheetBySheetId(params.worksheetId);+ const worksheet = currentUniverService+ .getCurrentUniverSheetInstance()+ .getWorkBook()+ .getSheetBySheetId(params.worksheetId);if (worksheet == null) {throw new Error('worksheet is null error!');}diff --git a/packages/base-sheets/src/Controller/EditTooltipsController.ts b/packages/base-sheets/src/Controller/EditTooltipsController.tsindex 9f5322b02f..7747e43af8 100644--- a/packages/base-sheets/src/Controller/EditTooltipsController.ts+++ b/packages/base-sheets/src/Controller/EditTooltipsController.ts@@ -9,7 +9,10 @@ export class EditTooltipsController {_layer: Layer;- constructor(@IRenderingEngine private readonly _engine: Engine, @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService) {+ constructor(+ @IRenderingEngine private readonly _engine: Engine,+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService+ ) {this._editTooltipsPage = new Map();}@@ -54,18 +57,21 @@ export class EditTooltipsController {}setRowColumn(key: string, sheetId: string, row: number, column: number): void {- const sheet = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getSheetBySheetId(sheetId);+ const sheet = this._currentUniverService+ .getCurrentUniverSheetInstance()+ .getWorkBook()+ .getSheetBySheetId(sheetId);const editTooltips = this.createIfEditTooltips(key, sheetId);if (sheet) {- const merges = sheet.getMerges().getByRowColumn(row, column);+ const mergedCells = sheet.getMergedCells(row, column);const rowTitle = sheet.getConfig().rowTitle;const columnTitle = sheet.getConfig().columnTitle;let left = rowTitle.width ?? 0;let top = columnTitle.height ?? 0;let height = 0;let width = 0;- if (merges) {- const merge = merges[0];+ if (mergedCells) {+ const merge = mergedCells[0];for (let i = merge.startColumn; i <= merge.endColumn; i++) {width += sheet.getColumnWidth(i);}diff --git a/packages/base-sheets/src/Services/selection-manager.service.ts b/packages/base-sheets/src/Services/selection-manager.service.tsindex 93a4ab00fc..84f050ee65 100644--- a/packages/base-sheets/src/Services/selection-manager.service.ts+++ b/packages/base-sheets/src/Services/selection-manager.service.ts@@ -1,4 +1,9 @@-import { ISelectionRangeWithStyle, ISelectionStyle, mergeCellHandler, NORMAL_SELECTION_PLUGIN_STYLE } from '@univerjs/base-render';+import {+ ISelectionRangeWithStyle,+ ISelectionStyle,+ mergeCellHandler,+ NORMAL_SELECTION_PLUGIN_STYLE,+} from '@univerjs/base-render';import { IRangeData, makeCellRangeToRangeData, Nullable } from '@univerjs/core';import { IDisposable } from '@wendellhu/redi';import { BehaviorSubject } from 'rxjs';@@ -50,7 +55,9 @@ export class SelectionManagerService implements IDisposable {return this._selectionInfo;}- getSelectionDatasByParam(param: Nullable<ISelectionManagerSearchParam>): Readonly<Nullable<ISelectionRangeWithStyle[]>> {+ getSelectionDatasByParam(+ param: Nullable<ISelectionManagerSearchParam>+ ): Readonly<Nullable<ISelectionRangeWithStyle[]>> {return this._getSelectionDatas(param);}@@ -155,7 +162,11 @@ export class SelectionManagerService implements IDisposable {return NORMAL_SELECTION_PLUGIN_STYLE;}- transformCellDataToSelectionData(row: number, column: number, mergeData: IRangeData[]): Nullable<ISelectionRangeWithStyle> {+ transformCellDataToSelectionData(+ row: number,+ column: number,+ mergeData: IRangeData[]+ ): Nullable<ISelectionRangeWithStyle> {const newCellRange = mergeCellHandler(row, column, mergeData);const newSelectionData = makeCellRangeToRangeData(newCellRange);@@ -183,13 +194,17 @@ export class SelectionManagerService implements IDisposable {this._selectionInfo$.next(this._getSelectionDatas(param));}- private _getFirstByParam(param: Nullable<ISelectionManagerSearchParam>): Readonly<Nullable<ISelectionRangeWithStyle>> {+ private _getFirstByParam(+ param: Nullable<ISelectionManagerSearchParam>+ ): Readonly<Nullable<ISelectionRangeWithStyle>> {const selectionData = this._getSelectionDatas(param);return selectionData?.[0];}- private _getLastByParam(param: Nullable<ISelectionManagerSearchParam>): Readonly<Nullable<ISelectionRangeWithStyle>> {+ private _getLastByParam(+ param: Nullable<ISelectionManagerSearchParam>+ ): Readonly<Nullable<ISelectionRangeWithStyle>> {const selectionData = this._getSelectionDatas(param);return selectionData?.[selectionData.length - 1];diff --git a/packages/base-ui/src/BaseComponent.ts b/packages/base-ui/src/BaseComponent.tsindex da73392bf1..f95ff993c0 100644--- a/packages/base-ui/src/BaseComponent.ts+++ b/packages/base-ui/src/BaseComponent.ts@@ -1,3 +1,6 @@+/**+ * @deprecated+ */export interface BaseComponentProps {getComponent?: (ref: any) => void; //获取自身组件id?: string; // 组件iddiff --git a/packages/base-ui/src/UIPlugin.ts b/packages/base-ui/src/base-ui-plugin.tssimilarity index 78%rename from packages/base-ui/src/UIPlugin.tsrename to packages/base-ui/src/base-ui-plugin.tsindex 84edba4b11..9d1ff4837b 100644--- a/packages/base-ui/src/UIPlugin.ts+++ b/packages/base-ui/src/base-ui-plugin.ts@@ -6,7 +6,8 @@ import { ZIndexManager } from './Common/ZIndexManager';import { SharedController } from './controllers/shared-shortcut.controller';import { IUIController, IWorkbenchOptions } from './controllers/ui/ui.controller';import { DesktopUIController } from './controllers/ui/ui-desktop.controller';-import { ContextService, IContextService } from './services/context/context.service';+import { DesktopClipboardService, IClipboardService } from './services/clipboard/clipboard.service';+import { BrowserClipboardService, IClipboardInterfaceService } from './services/clipboard/clipboard-interface.service';import { DesktopContextMenuService, IContextMenuService } from './services/contextmenu/contextmenu.service';import { DesktopMenuService, IMenuService } from './services/menu/menu.service';import { DesktopPlatformService, IPlatformService } from './services/platform/platform.service';@@ -32,11 +33,12 @@ export class UIPlugin extends Plugin {}override onMounted(): void {- this.initDependencies();- this.initUI();+ this._initDependencies();+ this._initModules();+ this._initUI();}- private initDependencies(): void {+ private _initDependencies(): void {const dependencies: Dependency[] = [// legacy managers - deprecated[ComponentManager],@@ -46,8 +48,9 @@ export class UIPlugin extends Plugin {[IShortcutService, { useClass: DesktopShortcutService }],[IPlatformService, { useClass: DesktopPlatformService }],[IMenuService, { useClass: DesktopMenuService }],- [IContextService, { useClass: ContextService }],[IContextMenuService, { useClass: DesktopContextMenuService }],+ [IClipboardInterfaceService, { useClass: BrowserClipboardService }],+ [IClipboardService, { useClass: DesktopClipboardService }],// controllers[SharedController],@@ -57,7 +60,11 @@ export class UIPlugin extends Plugin {dependencies.forEach((dependency) => this._injector.add(dependency));}- private initUI(): void {+ private _initModules(): void {+ this._injector.get(SharedController).initialize();+ }++ private _initUI(): void {this._injector.get(IUIController).bootstrapWorkbench(this._config);}}diff --git a/packages/base-ui/src/controllers/shared-shortcut.controller.ts b/packages/base-ui/src/controllers/shared-shortcut.controller.tsindex 0e6ade8e09..2e2a47504e 100644--- a/packages/base-ui/src/controllers/shared-shortcut.controller.ts+++ b/packages/base-ui/src/controllers/shared-shortcut.controller.ts@@ -1,5 +1,7 @@import { Disposable, ICommandService, RedoCommand, UndoCommand } from '@univerjs/core';+import { CopyCommand, CutCommand, PasteCommand } from '../services/clipboard/clipboard.command';+import { CopyShortcutItem, CutShortcutItem, PasteShortcutItem } from '../services/clipboard/clipboard.shortcut';import { KeyCode, MetaKeys } from '../services/shortcut/keycode';import { IShortcutItem, IShortcutService } from '../services/shortcut/shortcut.service';@@ -19,13 +21,20 @@ export const RedoShortcutItem: IShortcutItem = {export class SharedController extends Disposable {constructor(@IShortcutService private readonly _shortcutService: IShortcutService, @ICommandService private readonly _commandService: ICommandService) {super();+ }++ initialize(): void {+ this._registerCommands();+ this._registerShortcuts();+ }- this.registerShortcuts();+ private _registerCommands(): void {+ [CutCommand, CopyCommand, PasteCommand].forEach((command) => this.disposeWithMe(this._commandService.registerAsMultipleCommand(command)));}- private registerShortcuts(): void {- [UndoShortcutItem, RedoShortcutItem].forEach((shortcut) => {- this.disposeWithMe(this._shortcutService.registerShortcut(shortcut));- });+ private _registerShortcuts(): void {+ [UndoShortcutItem, RedoShortcutItem, CutShortcutItem, CopyShortcutItem, PasteShortcutItem].forEach((shortcut) =>+ this.disposeWithMe(this._shortcutService.registerShortcut(shortcut))+ );}}diff --git a/packages/base-ui/src/index.ts b/packages/base-ui/src/index.tsindex 6a6094d877..707932e304 100644--- a/packages/base-ui/src/index.ts+++ b/packages/base-ui/src/index.ts@@ -1,3 +1,4 @@+export { UIPlugin } from './base-ui-plugin';export * from './BaseComponent';export * from './Basics';export * from './Common';@@ -7,8 +8,10 @@ export { IUIController } from './controllers/ui/ui.controller';export { IDesktopUIController } from './controllers/ui/ui-desktop.controller';export * from './Enum';export * from './Helpers';-export { FOCUSING_DOC, FOCUSING_SHEET, FOCUSING_SLIDE } from './services/context/context';-export { ContextService, IContextService } from './services/context/context.service';+export { CopyCommand, CutCommand, PasteCommand } from './services/clipboard/clipboard.command';+export { DesktopClipboardService, IClipboardService } from './services/clipboard/clipboard.service';+export { CopyShortcutItem, CutShortcutItem, PasteShortcutItem } from './services/clipboard/clipboard.shortcut';+export { BrowserClipboardService, IClipboardInterfaceService } from './services/clipboard/clipboard-interface.service';export {ICustomComponentOption,ICustomComponentProps,@@ -27,5 +30,4 @@ export { DesktopMenuService, IMenuService } from './services/menu/menu.service';export { DesktopPlatformService, IPlatformService } from './services/platform/platform.service';export { KeyCode, MetaKeys } from './services/shortcut/keycode';export { DesktopShortcutService, IShortcutItem, IShortcutService } from './services/shortcut/shortcut.service';-export { UIPlugin } from './UIPlugin';export * from './Utils';diff --git a/packages/base-ui/src/services/clipboard/clipboard-interface.service.ts b/packages/base-ui/src/services/clipboard/clipboard-interface.service.tsnew file mode 100644index 0000000000..55310de3ce--- /dev/null+++ b/packages/base-ui/src/services/clipboard/clipboard-interface.service.ts@@ -0,0 +1,93 @@+import { Disposable } from '@univerjs/core';+import { createIdentifier } from '@wendellhu/redi';++/**+ * This interface provides an interface to access system's clipboard.+ */+export interface IClipboardInterfaceService {+ /**+ * Write plain text into clipboard. Use write() to write both plain text and html.+ * @param text+ */+ writeText(text: string): Promise<void>;++ /**+ * Read plain text from clipboard. Use read() to read both plain text and html.+ * @returns plain text+ */+ readText(): Promise<string>;++ /**+ * Write both plain text and html into clipboard.+ * @param text+ * @param html+ */+ write(text: string, html: string): Promise<void>;++ /**+ * Read both plain text and html from clipboard.+ */+ read(): Promise<{ text: string; html: string }>;++ // NOTE: maybe we should add an interface to support image copy+}++export const IClipboardInterfaceService = createIdentifier<IClipboardInterfaceService>('univer.clipboard-interface-service');++export class BrowserClipboardService extends Disposable implements IClipboardInterfaceService {+ async write(text: string, html: string): Promise<void> {+ // try {+ // // write both pure text content and html content to the clipboard+ // return await navigator.clipboard.write();+ // } catch (error) {+ // console.error(error);+ // }+ }++ async writeText(text: string): Promise<void> {+ // use new Clipboard API first+ try {+ return await navigator.clipboard.writeText(text);+ } catch (error) {+ console.error(error);+ }++ // fallback to traditional way+ const activeElement = document.activeElement;+ const container = createCopyPasteContainer();+ container.value = text;+ container.focus();+ container.select();+ document.body.appendChild(container);++ document.execCommand('copy');++ if (activeElement instanceof HTMLElement) {+ activeElement.focus();+ }++ document.removeChild(container);+ }++ read(): Promise<{ text: string; html: string }> {}++ async readText(): Promise<string> {+ try {+ return await navigator.clipboard.readText();+ } catch (e) {+ console.error(e);++ return '';+ }++ // TODO: fallback to traditional way+ }+}++function createCopyPasteContainer() {+ const textArea = document.createElement('textarea');+ textArea.style.position = 'absolute';+ textArea.style.height = '1px';+ textArea.style.width = '1px';+ return textArea;+}diff --git a/packages/base-ui/src/services/clipboard/clipboard.command.ts b/packages/base-ui/src/services/clipboard/clipboard.command.tsnew file mode 100644index 0000000000..8d5b9d2dca--- /dev/null+++ b/packages/base-ui/src/services/clipboard/clipboard.command.ts@@ -0,0 +1,34 @@+import { CommandType, IMultiCommand } from '@univerjs/core';++const CopyCommandName = 'univer.command.copy';+export const CopyCommand: IMultiCommand = {+ id: CopyCommandName,+ name: CopyCommandName,+ multi: true,+ priority: 0,+ type: CommandType.COMMAND,+ preconditions: () => false,+ handler: async () => true,+};++const CutCommandName = 'univer.command.cut';+export const CutCommand: IMultiCommand = {+ id: CutCommandName,+ name: CutCommandName,+ multi: true,+ priority: 0,+ type: CommandType.COMMAND,+ preconditions: () => false,+ handler: async () => true,+};++const PasteCommandName = 'univer.command.paste';+export const PasteCommand: IMultiCommand = {+ id: PasteCommandName,+ name: PasteCommandName,+ multi: true,+ priority: 0,+ type: CommandType.COMMAND,+ preconditions: () => false,+ handler: async () => true,+};diff --git a/packages/base-ui/src/services/clipboard/clipboard.service.ts b/packages/base-ui/src/services/clipboard/clipboard.service.tsindex e69de29bb2..6e7f5886bf 100644--- a/packages/base-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/base-ui/src/services/clipboard/clipboard.service.ts@@ -0,0 +1,20 @@+import { Disposable } from '@univerjs/core';+import { createIdentifier } from '@wendellhu/redi';++import { IClipboardInterfaceService } from './clipboard-interface.service';++// TODO@wzhudev: currently I have no idea if this should be moved to sheet-ui or other places. And it do not have any+// implementation yet.++/**+ * This interface provides an interface for features to hook in copy paste feature.+ */+export interface IClipboardService {}++export const IClipboardService = createIdentifier<IClipboardService>('univer.clipboard-service');++export class DesktopClipboardService extends Disposable implements IClipboardService {+ constructor(@IClipboardInterfaceService private readonly _clipboardInterfaceService: IClipboardInterfaceService) {+ super();+ }+}diff --git a/packages/base-ui/src/services/clipboard/clipboard.shortcut.ts b/packages/base-ui/src/services/clipboard/clipboard.shortcut.tsnew file mode 100644index 0000000000..7b898b1719--- /dev/null+++ b/packages/base-ui/src/services/clipboard/clipboard.shortcut.ts@@ -0,0 +1,18 @@+import { KeyCode, MetaKeys } from '../shortcut/keycode';+import { IShortcutItem } from '../shortcut/shortcut.service';+import { CopyCommand, CutCommand } from './clipboard.command';++export const CopyShortcutItem: IShortcutItem = {+ id: CopyCommand.id,+ binding: KeyCode.C | MetaKeys.CTRL_COMMAND,+};++export const CutShortcutItem: IShortcutItem = {+ id: CutCommand.id,+ binding: KeyCode.X | MetaKeys.CTRL_COMMAND,+};++export const PasteShortcutItem: IShortcutItem = {+ id: CopyCommand.id,+ binding: KeyCode.V | MetaKeys.CTRL_COMMAND,+};diff --git a/packages/base-ui/src/services/shortcut/shortcut.service.ts b/packages/base-ui/src/services/shortcut/shortcut.service.tsindex 1cec80b187..affcc57854 100644--- a/packages/base-ui/src/services/shortcut/shortcut.service.ts+++ b/packages/base-ui/src/services/shortcut/shortcut.service.ts@@ -1,8 +1,7 @@-import { Disposable, ICommandService, toDisposable } from '@univerjs/core';+import { Disposable, ICommandService, IContextService, toDisposable } from '@univerjs/core';import { createIdentifier, IDisposable } from '@wendellhu/redi';import { fromDocumentEvent } from '../../Common/lifecycle';-import { IContextService } from '../context/context.service';import { IPlatformService } from '../platform/platform.service';import { MetaKeys } from './keycode';diff --git a/packages/core/src/Basics/Univer.ts b/packages/core/src/Basics/Univer.tsindex d8af794dc3..8a9b3d71d0 100644--- a/packages/core/src/Basics/Univer.ts+++ b/packages/core/src/Basics/Univer.ts@@ -3,6 +3,7 @@ import { Ctor, Injector } from '@wendellhu/redi';import { ObserverManager } from '../Observer';import { Plugin, PluginCtor, PluginRegistry, PluginStore, PluginType } from '../Plugin';import { CommandService, ICommandService } from '../services/command/command.service';+import { ContextService, IContextService } from '../services/context/context.service';import { CurrentUniverService, ICurrentUniverService } from '../services/current.service';import { LocaleService } from '../services/locale.service';import { DesktopLogService, ILogService } from '../services/log/log.service';@@ -26,7 +27,7 @@ export class Univer {private readonly _univerPluginRegistry = new PluginRegistry();constructor(univerData: Partial<IUniverData> = {}) {- this._univerInjector = this.initializeDependencies();+ this._univerInjector = this._initializeDependencies();this._setObserver();// initialize localization info@@ -132,7 +133,7 @@ export class Univer {new UniverObserverImpl().install(this._univerInjector.get(ObserverManager));}- private initializeDependencies(): Injector {+ private _initializeDependencies(): Injector {return new Injector([[ObserverManager],[@@ -149,6 +150,7 @@ export class Univer {[ICommandService, { useClass: CommandService, lazy: true }],[IUndoRedoService, { useClass: LocalUndoRedoService, lazy: true }],[IPermissionService, { useClass: DesktopPermissionService }],+ [IContextService, { useClass: ContextService }],]);}diff --git a/packages/core/src/Shared/ObjectMatrix.ts b/packages/core/src/Shared/ObjectMatrix.tsindex 944e4cf142..c17dcf9c33 100644--- a/packages/core/src/Shared/ObjectMatrix.ts+++ b/packages/core/src/Shared/ObjectMatrix.ts@@ -9,10 +9,12 @@ export type ObjectMatrixPrimitiveType<T> = {[key: number]: { [key: number]: T };};+// TODO: this is not a good name+/*** A two-dimensional array represented by a two-level deep object and provides an array-like API-- @beta+ *+ * @beta*/export class ObjectMatrix<T> {private _option: ObjectArray<ObjectArrayPrimitiveType<T>>;diff --git a/packages/core/src/Shared/Rectangle.ts b/packages/core/src/Shared/Rectangle.tsindex 1fae11d07d..8e09b0695e 100644--- a/packages/core/src/Shared/Rectangle.ts+++ b/packages/core/src/Shared/Rectangle.ts@@ -2,6 +2,8 @@ import { IRangeData } from '../Types/Interfaces';import { Tools } from './Tools';import { Nullable } from './Types';+// TODO: it seems that this wrapper is not necessary. Only static methods are good.+/*** A square area containing four position information: startRow, startColumn, endRow, and endColumn*/@@ -46,7 +48,12 @@ export class Rectangle implements IRangeData {}static equals(src: IRangeData, target: IRangeData): boolean {- return src.endRow === target.endRow && src.endColumn === target.endColumn && src.startRow === target.startRow && src.startColumn === target.startColumn;+ return (+ src.endRow === target.endRow &&+ src.endColumn === target.endColumn &&+ src.startRow === target.startRow &&+ src.startColumn === target.startColumn+ );}static intersects(src: IRangeData, target: IRangeData): boolean {diff --git a/packages/core/src/Shared/Lifecycle.ts b/packages/core/src/Shared/lifecycle.tssimilarity index 100%rename from packages/core/src/Shared/Lifecycle.tsrename to packages/core/src/Shared/lifecycle.tsdiff --git a/packages/core/src/Sheets/Domain/Merges.ts b/packages/core/src/Sheets/Domain/Merges.tsdeleted file mode 100644index 0625efffe1..0000000000--- a/packages/core/src/Sheets/Domain/Merges.ts+++ /dev/null@@ -1,291 +0,0 @@-import { Nullable, Rectangle, Tuples } from '../../Shared';-import { IRangeData } from '../../Types/Interfaces';-import type { Worksheet } from './Worksheet';--// NOTE: some methods are leaving here for future refactoring--/**- * Manage merged cells- */-export class Merges {- private _rectangleList: IRangeData[];-- private _worksheet: Worksheet;-- // eslint-disable-next-line max-lines-per-function- constructor(worksheet: Worksheet, mergeData: any) {- this._worksheet = worksheet;- this._rectangleList = mergeData ?? [];- // eslint-disable-next-line max-lines-per-function- // CommandManager.getCommandObservers().add(({ actions }) => {- // if (!actions || actions.length === 0) return;-- // const action = actions[0] as SheetActionBase<ISheetActionData, ISheetActionData, void>;-- // // TODO not use try catch- // try {- // action.getWorkBook();- // } catch (error) {- // return;- // }- // const currentUnitId = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getUnitId();- // const actionUnitId = action.getWorkBook().getUnitId();- // if (currentUnitId !== actionUnitId) return;-- // const insertRowAction = actions.find((action) => action instanceof InsertRowAction) as InsertRowAction;- // const insertColumnAction = actions.find((action) => action instanceof InsertColumnAction) as InsertColumnAction;- // const deleteRowAction = actions.find((action) => action instanceof RemoveRowAction) as RemoveRowAction;- // const deleteColumnAction = actions.find((action) => action instanceof RemoveColumnAction) as RemoveColumnAction;- // const deleteRangeAction = actions.find((action) => action instanceof DeleteRangeAction) as DeleteRangeAction;-- // if (insertRowAction) {- // const data = insertRowAction.getDoActionData();- // if (data.sheetId === this._worksheet.getSheetId()) {- // const rectangleList = Tools.deepClone(this._rectangleList);- // for (let i = 0; i < rectangleList.length; i++) {- // const merge = rectangleList[i];- // const count = data.rowCount;- // if (data.rowIndex > merge.endRow) {- // continue;- // } else if (data.rowIndex >= merge.startRow && data.rowIndex <= merge.endRow) {- // merge.endRow += count;- // } else {- // merge.startRow += count;- // merge.endRow += count;- // }- // }- // this.modifyMerge(this._rectangleList, rectangleList);- // }- // }- // if (insertColumnAction) {- // const data = insertColumnAction.getDoActionData();- // if (data.sheetId === this._worksheet.getSheetId()) {- // const rectangleList = Tools.deepClone(this._rectangleList);- // for (let i = 0; i < rectangleList.length; i++) {- // const merge = rectangleList[i];- // const count = data.columnCount;- // if (data.columnIndex > merge.endColumn) {- // continue;- // } else if (data.columnIndex >= merge.startColumn && data.columnIndex <= merge.endColumn) {- // merge.endColumn += count;- // } else {- // merge.startColumn += count;- // merge.endColumn += count;- // }- // }- // this.modifyMerge(this._rectangleList, rectangleList);- // }- // }- // if (deleteRowAction) {- // const data = deleteRowAction.getDoActionData();- // if (data.sheetId === this._worksheet.getSheetId()) {- // const rectangleList = Tools.deepClone(this._rectangleList);- // for (let i = 0; i < rectangleList.length; i++) {- // const merge = rectangleList[i];- // const count = data.rowCount;- // if (data.rowIndex > merge.endRow) {- // continue;- // } else if (data.rowIndex >= merge.startRow && data.rowIndex <= merge.endRow) {- // merge.endRow -= count;- // } else {- // merge.startRow -= count;- // merge.endRow -= count;- // }- // }- // this.modifyMerge(this._rectangleList, rectangleList);- // }- // }- // if (deleteColumnAction) {- // const data = deleteColumnAction.getDoActionData();- // if (data.sheetId === this._worksheet.getSheetId()) {- // const rectangleList = Tools.deepClone(this._rectangleList);- // for (let i = 0; i < rectangleList.length; i++) {- // const merge = rectangleList[i];- // const count = data.columnCount;- // if (data.columnIndex > merge.endColumn) {- // continue;- // } else if (data.columnIndex >= merge.startColumn && data.columnIndex <= merge.endColumn) {- // merge.endColumn -= count;- // } else {- // merge.startColumn -= count;- // merge.endColumn -= count;- // }- // }- // this.modifyMerge(this._rectangleList, rectangleList);- // }- // }- // if (deleteRangeAction) {- // const data = deleteRangeAction.getDoActionData();- // if (data.sheetId === this._worksheet.getSheetId()) {- // const rectangleList = Tools.deepClone(this._rectangleList);- // const hasMerge = this.getByRowColumn(data.rangeData.startRow, data.rangeData.endRow, data.rangeData.startColumn, data.rangeData.endColumn);- // if (hasMerge) {- // hasMerge.forEach((item) => {- // const target = new Rectangle(item);- // for (let i = 0; i < rectangleList.length; i++) {- // const current = rectangleList[i];- // if (target.intersects(new Rectangle(current))) {- // rectangleList.splice(i, 1);- // }- // }- // });- // }- // // 单元格上移- // if (data.shiftDimension) {- // for (let i = 0; i < rectangleList.length; i++) {- // const merge = rectangleList[i];- // if (merge.endRow >= data.rangeData.startRow) {- // if (merge.endColumn < data.rangeData.startColumn) {- // continue;- // } else if (merge.startColumn > data.rangeData.endColumn) {- // continue;- // } else if (merge.startColumn >= data.rangeData.startColumn && merge.endColumn <= data.rangeData.endColumn) {- // const count = data.rangeData.endRow - data.rangeData.startRow;-- // merge.startRow -= count;- // merge.endRow -= count;- // } else {- // return;- // }- // }- // }- // } else {- // // 单元格左移- // for (let i = 0; i < rectangleList.length; i++) {- // const merge = rectangleList[i];- // if (merge.startColumn > data.rangeData.endColumn) {- // if (merge.endRow < data.rangeData.startRow) {- // continue;- // } else if (merge.startRow > data.rangeData.endRow) {- // continue;- // } else if (merge.startRow >= data.rangeData.startRow && merge.endRow <= data.rangeData.endRow) {- // const count = data.rangeData.endColumn - data.rangeData.startColumn;-- // merge.startColumn -= count;- // merge.endColumn -= count;- // } else {- // return;- // }- // }- // }- // }-- // this.modifyMerge(this._rectangleList, rectangleList);- // }- // }- // });- }-- getMergeData(): IRangeData[] {- return this._rectangleList;- }-- getByRowColumn(startRow: number, endRow: number, startColumn: number, endColumn: number): Nullable<IRangeData[]>;- getByRowColumn(row: number, column: number): Nullable<IRangeData[]>;- getByRowColumn(...argument: any): Nullable<IRangeData[]> {- const { _rectangleList } = this;- let target: Rectangle;- if (Tuples.checkup(argument, Tuples.NUMBER_TYPE, Tuples.NUMBER_TYPE, Tuples.NUMBER_TYPE, Tuples.NUMBER_TYPE)) {- target = new Rectangle(argument[0], argument[2], argument[1], argument[3]);- } else if (Tuples.checkup(argument, Tuples.NUMBER_TYPE, Tuples.NUMBER_TYPE)) {- target = new Rectangle(argument[0], argument[1], argument[0], argument[1]);- }- const rectList = [];- for (let i = 0; i < _rectangleList.length; i++) {- const rectangle = _rectangleList[i];- if (target!.intersects(new Rectangle(rectangle))) {- // return rectangle;- rectList.push(rectangle);- }- }-- return rectList.length ? rectList : null;- }-- // remove(rectangle: IRangeData): void {- // const removeAction: IRemoveMergeActionData = {- // actionName: RemoveMergeAction.NAME,- // sheetId: this._worksheet.getSheetId(),- // rectangles: [rectangle],- // };-- // const command = new Command(- // {- // WorkBookUnit: this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook(),- // },- // removeAction- // );- // this._commandManager.invoke(command);- // }-- size() {- return this._rectangleList.length;- }-- // add(rectangle: IRangeData): void {- // const removeAction: IRemoveMergeActionData = {- // actionName: RemoveMergeAction.NAME,- // sheetId: this._worksheet.getSheetId(),- // rectangles: [rectangle],- // };- // const appendAction: IAddMergeActionData = {- // actionName: AddMergeAction.NAME,- // sheetId: this._worksheet.getSheetId(),- // rectangles: [rectangle],- // };- // const command = new Command(- // {- // WorkBookUnit: this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook(),- // },- // removeAction,- // appendAction- // );- // this._commandManager.invoke(command);- // }-- // union(rectangle: IRangeData): IRangeData {- // const { _rectangleList } = this;- // const { length } = _rectangleList;- // let target = new Rectangle(rectangle);- // for (let i = 0; i < length; i++) {- // const element = _rectangleList[i];- // target = target.union(new Rectangle(element));- // }- // return target.getData();- // }-- getMergedRanges(rectangle: IRangeData): IRangeData[] {- const { _rectangleList } = this;- const { length } = _rectangleList;- const result = [];- for (let i = 0; i < length; i++) {- const item = _rectangleList[i];- const target = new Rectangle(rectangle);- if (target.intersects(new Rectangle(item))) {- result.push(item);- }- }- return result;- }-- // modifyMerge(originMerge: IRangeData[], currentMerge: IRangeData[]) {- // const removeAction: IRemoveMergeActionData = {- // actionName: RemoveMergeAction.NAME,- // sheetId: this._worksheet.getSheetId(),- // rectangles: [...originMerge],- // };- // const appendAction: IAddMergeActionData = {- // actionName: AddMergeAction.NAME,- // sheetId: this._worksheet.getSheetId(),- // rectangles: [...currentMerge],- // };- // const command = new Command(- // {- // WorkBookUnit: this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook(),- // },- // removeAction,- // appendAction- // );- // this._commandManager.invoke(command);- // }-}diff --git a/packages/core/src/Sheets/Domain/Range.ts b/packages/core/src/Sheets/Domain/Range.tsindex b31de5830a..8d530bb630 100644--- a/packages/core/src/Sheets/Domain/Range.ts+++ b/packages/core/src/Sheets/Domain/Range.ts@@ -1,8 +1,26 @@import { ICurrentUniverService } from '../../services/current.service';import { Nullable, ObjectMatrix, ObjectMatrixPrimitiveType, Tools } from '../../Shared';import { DEFAULT_RANGE, DEFAULT_STYLES } from '../../Types/Const';-import { BooleanNumber, Dimension, Direction, FontItalic, FontWeight, HorizontalAlign, VerticalAlign, WrapStrategy } from '../../Types/Enum';-import { IBorderData, ICellData, IDocumentData, IRangeData, IRangeType, IStyleData, ITextDecoration, ITextRotation } from '../../Types/Interfaces';+import {+ BooleanNumber,+ Dimension,+ Direction,+ FontItalic,+ FontWeight,+ HorizontalAlign,+ VerticalAlign,+ WrapStrategy,+} from '../../Types/Enum';+import {+ IBorderData,+ ICellData,+ IDocumentData,+ IRangeData,+ IRangeType,+ IStyleData,+ ITextDecoration,+ ITextRotation,+} from '../../Types/Interfaces';import type { Worksheet } from './Worksheet';/**@@ -30,9 +48,16 @@ export class Range {private _worksheet: Worksheet;- constructor(workSheet: Worksheet, range: IRangeType, @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService) {+ constructor(+ workSheet: Worksheet,+ range: IRangeType,+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService+ ) {// Convert the range passed in by the user into a standard format- this._rangeData = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().transformRangeType(range).rangeData;+ this._rangeData = this._currentUniverService+ .getCurrentUniverSheetInstance()+ .getWorkBook()+ .transformRangeType(range).rangeData;this._worksheet = workSheet;// The user entered an invalid range@@ -484,18 +509,6 @@ export class Range {return this._rangeData.endRow;}- /**- * Returns an array of Range objects representing merged cells that either are fully within the current range, or contain at least one cell in the current range.- */- getMergedRanges(): Range[] {- const { startRow, endRow, startColumn, endColumn } = this._rangeData;-- return this._worksheet- .getMerges()- .getMergedRanges({ startRow, endRow, startColumn, endColumn })- .map((rangeData) => new Range(this._worksheet, rangeData, this._currentUniverService));- }-/*** Starting at the cell in the first column and row of the range, returns the next cell in the given direction that is the edge of a contiguous range of cells with data in them or the cell at the edge of the spreadsheet in that direction.* @param direction@@ -721,26 +734,9 @@ export class Range {return data.some((items) => items.some((item) => item?.m === ''));}- // isChecked() {}- // isEndColumnBounded() {}- // isEndRowBounded() {}-- /**- * Returns true if the cells in the current range overlap any merged cells.- */- isPartOfMerge(): boolean {- const { startRow, endRow, startColumn, endColumn } = this._rangeData;-- const data = this._worksheet.getMerges().getByRowColumn(startRow, endRow, startColumn, endColumn);- if (data) {- return true;- }-- return false;- }-/**- * Returns a copy of the range expanded in the four cardinal Directions to cover all adjacent cells with data in them.+ * Returns a copy of the range expanded in the four cardinal Directions to cover all adjacent cells+ * with data in them.** @returns This range, for chaining.*/diff --git a/packages/core/src/Sheets/Domain/RangeList.ts b/packages/core/src/Sheets/Domain/RangeList.tsindex 182da05660..a4aad32499 100644--- a/packages/core/src/Sheets/Domain/RangeList.ts+++ b/packages/core/src/Sheets/Domain/RangeList.ts@@ -14,7 +14,11 @@ import type { Worksheet } from './Worksheet';export class RangeList {private _rangeList: IRangeData[];- constructor(private readonly _worksheet: Worksheet, rangeList: IRangeType[], @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService) {+ constructor(+ private readonly _worksheet: Worksheet,+ rangeList: IRangeType[],+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService+ ) {const workbook = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook();this._rangeList = [];diff --git a/packages/core/src/Sheets/Domain/Worksheet.ts b/packages/core/src/Sheets/Domain/Worksheet.tsindex 745fa21832..4ef16321b3 100644--- a/packages/core/src/Sheets/Domain/Worksheet.ts+++ b/packages/core/src/Sheets/Domain/Worksheet.ts@@ -2,12 +2,11 @@ import { Inject } from '@wendellhu/redi';import { ObserverManager } from '../../Observer';import { ICurrentUniverService } from '../../services/current.service';-import { Nullable, ObjectMatrix, Tools } from '../../Shared';+import { Nullable, ObjectMatrix, Rectangle, Tools } from '../../Shared';import { DEFAULT_WORKSHEET } from '../../Types/Const';import { BooleanNumber, SheetTypes } from '../../Types/Enum';import { ICellData, IRangeData, IRangeStringData, IRangeType, IWorksheetConfig } from '../../Types/Interfaces';import { ColumnManager } from './ColumnManager';-import { Merges } from './Merges';import { Range } from './Range';import { RangeList } from './RangeList';import { RowManager } from './RowManager';@@ -23,12 +22,10 @@ import { RowManager } from './RowManager';* @beta*/export class Worksheet {- protected _config: IWorksheetConfig;+ protected _snapshot: IWorksheetConfig;protected _initialized: boolean;- protected _merges: Merges;-protected _sheetId: string;protected _cellData: ObjectMatrix<ICellData>;@@ -38,11 +35,11 @@ export class Worksheet {protected _columnManager: ColumnManager;constructor(- customConfig: Partial<IWorksheetConfig>,+ snapshot: Partial<IWorksheetConfig>,@Inject(ObserverManager) private readonly _observerManager: ObserverManager,@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService) {- const config: IWorksheetConfig = {+ const mergedSnapshot: IWorksheetConfig = {...DEFAULT_WORKSHEET,mergeData: [],hideRow: [],@@ -61,25 +58,23 @@ export class Worksheet {selections: ['A1'],rightToLeft: BooleanNumber.FALSE,pluginMeta: {},- ...customConfig,+ ...snapshot,};- this._config = config;+ this._snapshot = mergedSnapshot;- const { columnData, rowData, cellData } = this._config;- this._sheetId = this._config.id ?? Tools.generateRandomId(6);+ const { columnData, rowData, cellData } = this._snapshot;+ this._sheetId = this._snapshot.id ?? Tools.generateRandomId(6);this._initialized = false;this._cellData = new ObjectMatrix<ICellData>(cellData);this._rowManager = new RowManager(this, rowData);this._columnManager = new ColumnManager(this, columnData);- this._initialize();}/*** Returns WorkSheet Cell Data Matrix* @returns*/- // TODO: change its name to getWorksheetMatrix?getCellMatrix(): ObjectMatrix<ICellData> {return this._cellData;}@@ -113,7 +108,7 @@ export class Worksheet {* @returns name of the sheet*/getName(): string {- return this._config.name;+ return this._snapshot.name;}/**@@ -122,32 +117,40 @@ export class Worksheet {* @deprecated*/clone(): Worksheet {- const { _config } = this;+ const { _snapshot: _config } = this;const copy = Tools.deepClone(_config);return new Worksheet(copy, this._observerManager, this._currentUniverService);}- /**- * Returns WorkSheet Merges Manage- *- * @returns merge instance- */- getMerges(): Merges {- return this._merges;+ getMergeData(): IRangeData[] {+ return this._snapshot.mergeData;+ }++ getMergedCells(row: number, col: number): Nullable<IRangeData[]> {+ const _rectangleList = this._snapshot.mergeData;+ const rectList = [];+ const target = new Rectangle(row, col, row, col);+ for (let i = 0; i < _rectangleList.length; i++) {+ const rectangle = _rectangleList[i];+ if (target!.intersects(new Rectangle(rectangle))) {+ // return rectangle;+ rectList.push(rectangle);+ }+ }++ return rectList.length ? rectList : null;}/**- * Returns Sheet Data To Array- * @remarks {@link ICellData} data type of cell.- * @returns Sheet Data To Array+ * Get cell matrix from a given range and pick out non-first cells of merged cells.*/- getSheetData(): ICellData[][] {- // TODO: Whether to support multiple types, the length attribute will be used in other methods- // TODO:- // return this._cellData.toArray();- return [];+ getMatrixWithMergedCells(row: number, col: number, endRow: number, endCol: number): ObjectMatrix<ICellData> {+ // TODO@wzhudev: implement this method+ // const mergedCellsInRange = this.}+ // WTF: this function signature is so ridiculous...+/*** Returns User Selection Range* @param range range types@@ -240,7 +243,7 @@ export class Worksheet {* @returns WorkSheet Status*/getStatus() {- const { _config } = this;+ const { _snapshot: _config } = this;return _config.status;}@@ -249,11 +252,7 @@ export class Worksheet {* @return zoomRatio*/getZoomRatio(): number {- return this._config.zoomRatio || 1;- }-- getMergeData(): IRangeData[] {- return this._config.mergeData;+ return this._snapshot.zoomRatio || 1;}/**@@ -261,7 +260,7 @@ export class Worksheet {* @returns WorkSheet Configures*/getConfig(): IWorksheetConfig {- return this._config;+ return this._snapshot;}/**@@ -269,7 +268,7 @@ export class Worksheet {* @returns the number of frozen rows*/getFrozenRows(): number {- return this._config.freezeRow;+ return this._snapshot.freezeRow;}/**@@ -286,7 +285,7 @@ export class Worksheet {* @returns the number of frozen columns*/getFrozenColumns(): number {- return this._config.freezeColumn;+ return this._snapshot.freezeColumn;}/**@@ -294,7 +293,7 @@ export class Worksheet {* @returns the current number of columns in the sheet, regardless of content*/getMaxColumns(): number {- const { _config } = this;+ const { _snapshot: _config } = this;const { columnCount } = _config;return columnCount;}@@ -304,7 +303,7 @@ export class Worksheet {* @returns the current number of rows in the sheet, regardless of content*/getMaxRows(): number {- const { _config } = this;+ const { _snapshot: _config } = this;const { rowCount } = _config;return rowCount;}@@ -314,7 +313,7 @@ export class Worksheet {* @returns the type of the sheet*/getType(): SheetTypes {- const { _config } = this;+ const { _snapshot: _config } = this;const { type } = _config;return type;}@@ -324,7 +323,7 @@ export class Worksheet {* @returns Row Count*/getRowCount(): number {- return this._config.rowCount;+ return this._snapshot.rowCount;}/**@@ -332,7 +331,7 @@ export class Worksheet {* @returns Column Count*/getColumnCount(): number {- return this._config.columnCount;+ return this._snapshot.columnCount;}/**@@ -355,7 +354,7 @@ export class Worksheet {* @returns hidden status of sheet*/isSheetHidden(): BooleanNumber {- return this._config.hidden;+ return this._snapshot.hidden;}/**@@ -363,7 +362,7 @@ export class Worksheet {* @returns Gridlines Hidden Status*/hasHiddenGridlines(): Boolean {- const { _config } = this;+ const { _snapshot: _config } = this;const { showGridlines } = _config;if (showGridlines === 0) {return true;@@ -376,7 +375,7 @@ export class Worksheet {* @returns the sheet tab color or null*/getTabColor(): Nullable<string> {- const { _config } = this;+ const { _snapshot: _config } = this;const { tabColor } = _config;return tabColor;}@@ -404,7 +403,7 @@ export class Worksheet {* @returns true if this sheet layout is right-to-left. Returns false if the sheet uses the default left-to-right layout.*/isRightToLeft(): BooleanNumber {- const { _config } = this;+ const { _snapshot: _config } = this;const { rightToLeft } = _config;return rightToLeft;}@@ -415,7 +414,7 @@ export class Worksheet {* @returns information stored by the plugin*/getPluginMeta<T>(name: string): T {- return this._config.pluginMeta[name];+ return this._snapshot.pluginMeta[name];}/**@@ -425,7 +424,7 @@ export class Worksheet {* @returns*/setPluginMeta<T>(name: string, value: T) {- this._config.pluginMeta[name] = value;+ this._snapshot.pluginMeta[name] = value;}/**@@ -452,7 +451,12 @@ export class Worksheet {* @param numColumns column count* @returns the rectangular grid of values for this range starting at the given coordinates. A -1 value given as the row or column position is equivalent to getting the very last row or column that has data in the sheet.*/- getSheetValues(startRow: number, startColumn: number, numRows: number, numColumns: number): Array<Array<Nullable<ICellData>>> {+ getSheetValues(+ startRow: number,+ startColumn: number,+ numRows: number,+ numColumns: number+ ): Array<Array<Nullable<ICellData>>> {const range = new Range(this,{@@ -474,9 +478,4 @@ export class Worksheet {const range = new Range(this, this._cellData.getRange(), this._currentUniverService);return range;}-- private _initialize(): void {- // this._selection = new Selection(this);- this._merges = new Merges(this, this._config.mergeData);- }}diff --git a/packages/core/src/Sheets/Domain/index.ts b/packages/core/src/Sheets/Domain/index.tsindex 73fd677d7b..804c1eb599 100644--- a/packages/core/src/Sheets/Domain/index.ts+++ b/packages/core/src/Sheets/Domain/index.ts@@ -1,12 +1,9 @@-// @index('./*.ts', f => `export * from '${f.path}'`)export * from './Color';export * from './ColorBuilder';export * from './ColumnManager';-export * from './Merges';export * from './Range';export * from './RangeList';export * from './RowManager';export * from './Styles';export * from './Workbook';export * from './Worksheet';-// @endindexdiff --git a/packages/core/src/Types/Interfaces/ICellData.ts b/packages/core/src/Types/Interfaces/ICellData.tsindex 983cd00788..7a005cdb95 100644--- a/packages/core/src/Types/Interfaces/ICellData.ts+++ b/packages/core/src/Types/Interfaces/ICellData.ts@@ -51,7 +51,12 @@ export interface ICellData {// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport function isICellData(value: any): value is ICellData {- return value && ((value as ICellData).s !== undefined || (value as ICellData).p !== undefined || (value as ICellData).v !== undefined);+ return (+ value &&+ ((value as ICellData).s !== undefined ||+ (value as ICellData).p !== undefined ||+ (value as ICellData).v !== undefined)+ );}/**@@ -76,6 +81,8 @@ export interface IFormatData {*/export type ICellDataType = Nullable<ICellData> | Nullable<IStyleData> | string | number | boolean;+// WTF: other matrix are number indexed objects, but this is an array?+/*** Cell data matrix type*/diff --git a/packages/core/src/Types/Interfaces/IWorksheetData.ts b/packages/core/src/Types/Interfaces/IWorksheetData.tsindex 29cc67d2ea..223c8880b4 100644--- a/packages/core/src/Types/Interfaces/IWorksheetData.ts+++ b/packages/core/src/Types/Interfaces/IWorksheetData.ts@@ -14,6 +14,8 @@ import { IRowData } from './IRowData';// visibility?: DeveloperMetadataVisibility;// };+// TODO: name of the interface is not accurate, should be IWorksheetSnapshot+/*** Properties of a worksheet's configuration*diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex a3e699c0ae..13da6af39c 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -16,14 +16,16 @@ export * from './Basics';export * from './Docs/Domain';export * from './Observer';export * from './Plugin';-export { CommandType, ICommand, ICommandInfo, ICommandService, IMutation, IOperation } from './services/command/command.service';+export { CommandType, ICommand, ICommandInfo, ICommandService, IMultiCommand, IMutation, IOperation } from './services/command/command.service';+export { FOCUSING_DOC, FOCUSING_SHEET, FOCUSING_SLIDE } from './services/context/context';+export { IContextService } from './services/context/context.service';export { ICurrentUniverService } from './services/current.service';export { LocaleService } from './services/locale.service';export { DesktopLogService, ILogService } from './services/log/log.service';export { DesktopPermissionService, IPermissionService } from './services/permission/permission.service';export { IUndoRedoService, LocalUndoRedoService, RedoCommand, UndoCommand } from './services/undoredo/undoredo.service';export * from './Shared';-export { Disposable, DisposableCollection, fromObservable, toDisposable } from './Shared/Lifecycle';+export { Disposable, DisposableCollection, fromObservable, toDisposable } from './Shared/lifecycle';export { createRowColIter, IRowColIter } from './Shared/RowColIter';export * from './Sheets';export * from './Slides/Domain';diff --git a/packages/core/src/services/auth/auth.service.ts b/packages/core/src/services/auth/auth.service.tsnew file mode 100644index 0000000000..bfa7da057b--- /dev/null+++ b/packages/core/src/services/auth/auth.service.ts@@ -0,0 +1 @@+export interface IAuthService {}diff --git a/packages/core/src/services/command/command.service.ts b/packages/core/src/services/command/command.service.tsindex aaef88fc61..632f2471ff 100644--- a/packages/core/src/services/command/command.service.ts+++ b/packages/core/src/services/command/command.service.ts@@ -1,6 +1,8 @@import { createIdentifier, IAccessor, IDisposable, Inject, Injector, Optional, SkipSelf } from '@wendellhu/redi';-import { toDisposable } from '../../Shared/Lifecycle';+import { toDisposable } from '../../Shared/lifecycle';+import { IKeyValue } from '../../Shared/Types';+import { IContextService } from '../context/context.service';import { ILogService } from '../log/log.service';export const enum CommandType {@@ -8,7 +10,7 @@ export const enum CommandType {COMMAND = 0,/** An operation that do not require conflict resolve. */OPERATION = 1,- /** An operation that need to be resolved before applicated on peer client. */+ /** An operation that need to be resolved before applied on peer client. */MUTATION = 2,}@@ -22,6 +24,14 @@ export interface ICommand<P extends object = object, R = boolean> {handler(accessor: IAccessor, params?: P): Promise<R>;}+export interface IMultiCommand<P extends object = object, R = boolean> extends ICommand<P, R> {+ name: string;+ multi: true;+ priority: number;++ preconditions?: (contextService: IContextService) => boolean;+}+/*** Mutation would change the model of Univer applications.*/@@ -32,7 +42,7 @@ export interface IMutation<P extends object = object, R = boolean> extends IComm/*** Operation would change the state of Univer applications. State should only be in memory and does not- * require confliction resolution.+ * require conflicting resolution.*/export interface IOperation<P extends object = object, R = boolean> extends ICommand<P, R> {type: CommandType.OPERATION;@@ -41,8 +51,8 @@ export interface IOperation<P extends object = object, R = boolean> extends ICom/*** The command info, only a command id and responsible params*/+// TODO: change object to serializable interface typeexport interface ICommandInfo<T extends object = object> {- // TODO: change object to serializable interface typeid: string;/**@@ -60,7 +70,13 @@ export type CommandListener = (commandInfo: Readonly<ICommandInfo>) => void;export interface ICommandService {registerCommand(command: ICommand): IDisposable;- executeCommand<P extends object = object, R = boolean>(id: string, params?: P, options?: IExecutionOptions): Promise<R> | R;+ registerAsMultipleCommand(command: ICommand): IDisposable;++ executeCommand<P extends object = object, R = boolean>(+ id: string,+ params?: P,+ options?: IExecutionOptions+ ): Promise<R> | R;/*** Register a hook that will be triggered when the@@ -68,7 +84,10 @@ export interface ICommandService {* @param id the command that will be fired.* @param callback the callback function that would be called*/- onCommandWillExecute<P extends object = object>(id: string, callback: (params?: P) => ICommandInfo[][]): IDisposable;+ onCommandWillExecute<P extends object = object>(+ id: string,+ callback: (params?: P) => ICommandInfo[][]+ ): IDisposable;/*** The method that would be trigger when a command is executing. Gather all interceptors and middlewares.@@ -128,6 +147,8 @@ export class CommandService implements ICommandService {private readonly _commandExecutedListeners: CommandListener[] = [];+ private _multiCommandDisposables = new Map<string, IDisposable>();+private _commandExecutingLevel = 0;constructor(@@ -138,11 +159,19 @@ export class CommandService implements ICommandService {this._commandRegistry = new CommandRegistry();}+ // TODO: support registering to multi commandregisterCommand(command: ICommand): IDisposable {return this._registerCommand(command, this._injector);}- onCommandWillExecute<P extends object = object>(id: string, callback: (params?: P) => ICommandInfo[][]): IDisposable {+ registerAsMultipleCommand(command: ICommand): IDisposable {+ return this._registerMultiCommand(command, this._injector);+ }++ onCommandWillExecute<P extends object = object>(+ id: string,+ callback: (params?: P) => ICommandInfo[][]+ ): IDisposable {if (this._parentCommandService) {return this._parentCommandService.onCommandWillExecute(id, callback);}@@ -230,8 +259,45 @@ export class CommandService implements ICommandService {return this._commandRegistry.registerCommand(command, injector);}- private async _execute<P extends object, R = boolean>(command: ICommand<P, R>, injector: Injector, params?: P): Promise<R> {- this._log.log(`${'|-'.repeat(this._commandExecutingLevel)}[ICommandService]: executing command "${command.id}".`);+ private _registerMultiCommand(command: ICommand, injector: Injector): IDisposable {+ if (this._parentCommandService) {+ return this._parentCommandService._registerMultiCommand(command, injector);+ }++ // compose a multi command and register it+ const registry = this._commandRegistry.getCommand(command.id);+ let multiCommand: MultiCommand;+ if (!registry) {+ multiCommand = new MultiCommand(command.id);+ this._multiCommandDisposables.set(+ command.id,+ this._commandRegistry.registerCommand(multiCommand, this._injector)+ );+ } else {+ if ((registry[0] as IKeyValue).multi !== true) {+ throw new Error('Command has registered as a single command.');+ } else {+ multiCommand = registry[0] as MultiCommand;+ }+ }++ const commandDisposable = multiCommand.registerImplementation(command as IMultiCommand, injector);+ return toDisposable(() => {+ commandDisposable.dispose();+ if (!multiCommand.hasImplementations()) {+ this._multiCommandDisposables.get(command.id)?.dispose();+ }+ });+ }++ private async _execute<P extends object, R = boolean>(+ command: ICommand<P, R>,+ injector: Injector,+ params?: P+ ): Promise<R> {+ this._log.log(+ `${'|-'.repeat(this._commandExecutingLevel)}[ICommandService]: executing command "${command.id}".`+ );this._commandExecutingLevel++;let result: R | boolean;@@ -248,3 +314,56 @@ export class CommandService implements ICommandService {return result;}}++class MultiCommand implements IMultiCommand {+ readonly name: string;++ readonly multi = true;++ readonly type = CommandType.COMMAND;++ readonly priority: number = 0;++ private readonly _implementations: Array<{ command: IMultiCommand; injector: Injector }> = [];++ constructor(readonly id: string) {+ this.name = id;+ }++ registerImplementation(implementation: IMultiCommand, injector: Injector): IDisposable {+ const registry = { command: implementation, injector };+ this._implementations.push(registry);+ this._implementations.sort((a, b) => b.command.priority - a.command.priority);++ return toDisposable(() => {+ const index = this._implementations.indexOf(registry);+ this._implementations.splice(index, 1);+ });+ }++ hasImplementations(): boolean {+ return this._implementations.length > 0;+ }++ handler = async (accessor: IAccessor, params?: object | undefined): Promise<boolean> => {+ if (!this._implementations.length) {+ return false;+ }++ const logService = accessor.get(ILogService);+ const contextService = accessor.get(IContextService);++ for (const item of this._implementations) {+ const preconditions = item.command.preconditions;+ if (preconditions?.(contextService)) {+ logService.log(`[MultiCommand]: executing implementation "${item.command.name}".`);+ const result = await item.injector.invoke(item.command.handler, params);+ if (result) {+ return true;+ }+ }+ }++ return false;+ };+}diff --git a/packages/base-ui/src/services/context/context.service.ts b/packages/core/src/services/context/context.service.tssimilarity index 85%rename from packages/base-ui/src/services/context/context.service.tsrename to packages/core/src/services/context/context.service.tsindex 873d92efbe..100aefa7f9 100644--- a/packages/base-ui/src/services/context/context.service.ts+++ b/packages/core/src/services/context/context.service.ts@@ -1,6 +1,10 @@-import { Disposable, fromObservable, ICurrentUniverService, UniverDoc, UniverSheet, UniverSlide } from '@univerjs/core';import { createIdentifier } from '@wendellhu/redi';+import { UniverDoc } from '../../Basics/UniverDoc';+import { UniverSheet } from '../../Basics/UniverSheet';+import { UniverSlide } from '../../Basics/UniverSlide';+import { Disposable, fromObservable } from '../../Shared/lifecycle';+import { ICurrentUniverService } from '../current.service';import { FOCUSING_DOC, FOCUSING_SHEET, FOCUSING_SLIDE } from './context';export interface IContextService {diff --git a/packages/base-ui/src/services/context/context.ts b/packages/core/src/services/context/context.tssimilarity index 100%rename from packages/base-ui/src/services/context/context.tsrename to packages/core/src/services/context/context.tsdiff --git a/packages/core/src/services/current.service.ts b/packages/core/src/services/current.service.tsindex bed996788b..65b68aa211 100644--- a/packages/core/src/services/current.service.ts+++ b/packages/core/src/services/current.service.ts@@ -5,7 +5,7 @@ import { UniverDoc } from '../Basics/UniverDoc';import { UniverSheet } from '../Basics/UniverSheet';import { UniverSlide } from '../Basics/UniverSlide';import { Nullable } from '../Shared';-import { Disposable } from '../Shared/Lifecycle';+import { Disposable } from '../Shared/lifecycle';import { IDocumentData } from '../Types/Interfaces';export interface IUniverHandler {diff --git a/packages/core/src/services/log/log.service.ts b/packages/core/src/services/log/log.service.tsindex 4e53ecc84f..268dbf24e2 100644--- a/packages/core/src/services/log/log.service.ts+++ b/packages/core/src/services/log/log.service.ts@@ -2,7 +2,7 @@import { createIdentifier } from '@wendellhu/redi';-import { Disposable } from '../../Shared/Lifecycle';+import { Disposable } from '../../Shared/lifecycle';export interface ILogService {log(...args: any[]): void;diff --git a/packages/core/src/services/permission/permission.service.ts b/packages/core/src/services/permission/permission.service.tsindex 9ec26ddaa8..01b6212400 100644--- a/packages/core/src/services/permission/permission.service.ts+++ b/packages/core/src/services/permission/permission.service.ts@@ -1,7 +1,7 @@import { createIdentifier } from '@wendellhu/redi';import { BehaviorSubject, Observable } from 'rxjs';-import { Disposable } from '../../Shared/Lifecycle';+import { Disposable } from '../../Shared/lifecycle';export interface IPermissionService {readonly editable$: Observable<boolean>;diff --git a/packages/core/src/services/undoredo/undoredo.service.ts b/packages/core/src/services/undoredo/undoredo.service.tsindex 0c3a165ae6..16efe70f0f 100644--- a/packages/core/src/services/undoredo/undoredo.service.ts+++ b/packages/core/src/services/undoredo/undoredo.service.ts@@ -1,11 +1,11 @@import { createIdentifier, IAccessor, IDisposable } from '@wendellhu/redi';import { BehaviorSubject, Observable } from 'rxjs';-import { Disposable, toDisposable } from '../../Shared/Lifecycle';+import { Disposable, toDisposable } from '../../Shared/lifecycle';import { CommandService, CommandType, ICommand, ICommandService } from '../command/command.service';import { ICurrentUniverService } from '../current.service';-// TODO:: an undo redo element may be mergable to another undo redo element+// TODO:: an undo redo element may be mergeable to another undo redo elementinterface IUndoRedoItem {/** URI maps to unitId for UniverSheet / UniverDoc / UniverSlide */@@ -51,7 +51,10 @@ export class LocalUndoRedoService extends Disposable implements IUndoRedoServiceprivate readonly _redoStacks = new Map<string, IUndoRedoItem[]>();- constructor(@ICurrentUniverService private readonly _currentUniverSheet: ICurrentUniverService, @ICommandService private readonly _commandService: CommandService) {+ constructor(+ @ICurrentUniverService private readonly _currentUniverSheet: ICurrentUniverService,+ @ICommandService private readonly _commandService: CommandService+ ) {super();this.undoRedoStatus$ = this._undoRedoStatus$.asObservable();diff --git a/packages/ui-plugin-docs/src/Basics/Observer.ts b/packages/ui-plugin-docs/src/Basics/Observer.tsindex a832f6a822..041a3959f8 100644--- a/packages/ui-plugin-docs/src/Basics/Observer.ts+++ b/packages/ui-plugin-docs/src/Basics/Observer.ts@@ -1,6 +1,6 @@import { Observable } from '@univerjs/core';-import { DocUIPlugin } from '../DocUIPlugin';+import { DocUIPlugin } from '../doc-ui-plugin';import { DocContainer } from '../View';export type DocUIPluginObserve = {diff --git a/packages/ui-plugin-docs/src/Controller/clipboard.controller.ts b/packages/ui-plugin-docs/src/Controller/clipboard.controller.tsnew file mode 100644index 0000000000..9130e9c92a--- /dev/null+++ b/packages/ui-plugin-docs/src/Controller/clipboard.controller.ts@@ -0,0 +1,20 @@+import { Disposable, ICommandService, ICurrentUniverService } from '@univerjs/core';++import { DocCopyCommand } from '../commands/commands/clipboard.command';+import { IDocClipboardService } from '../services/clipboard/clipboard.service';++export class DocClipboardController extends Disposable {+ constructor(+ @ICommandService private readonly _commandService: ICommandService,+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,+ @IDocClipboardService private readonly _docClipboardService: IDocClipboardService+ ) {+ super();+ }++ initialize() {+ [DocCopyCommand, DocCopyCommand, DocCopyCommand].forEach((command) =>+ this.disposeWithMe(this._commandService.registerAsMultipleCommand(command))+ );+ }+}diff --git a/packages/ui-plugin-docs/src/commands/commands/clipboard.command.ts b/packages/ui-plugin-docs/src/commands/commands/clipboard.command.tsnew file mode 100644index 0000000000..adda4f043d--- /dev/null+++ b/packages/ui-plugin-docs/src/commands/commands/clipboard.command.ts@@ -0,0 +1,43 @@+import { CopyCommand, CutCommand, PasteCommand } from '@univerjs/base-ui';+import { CommandType, FOCUSING_DOC, IMultiCommand } from '@univerjs/core';++import { IDocClipboardService } from '../../services/clipboard/clipboard.service';++export const DocCopyCommand: IMultiCommand = {+ id: CopyCommand.id,+ name: 'doc.command.copy',+ type: CommandType.COMMAND,+ multi: true,+ priority: 1100,+ preconditions: (contextService) => contextService.getContextValue(FOCUSING_DOC),+ handler: async (accessor, params) => {+ const docClipboardService = accessor.get(IDocClipboardService);+ return docClipboardService.copy();+ },+};++export const DocCutCommand: IMultiCommand = {+ id: CutCommand.id,+ name: 'doc.command.cut',+ type: CommandType.COMMAND,+ multi: true,+ priority: 1100,+ preconditions: (contextService) => contextService.getContextValue(FOCUSING_DOC),+ handler: async (accessor, params) => {+ const docClipboardService = accessor.get(IDocClipboardService);+ return docClipboardService.cut();+ },+};++export const DocPasteCommand: IMultiCommand = {+ id: PasteCommand.id,+ name: 'doc.command.paste',+ type: CommandType.COMMAND,+ multi: true,+ priority: 1100,+ preconditions: (contextService) => contextService.getContextValue(FOCUSING_DOC),+ handler: async (accessor, params) => {+ const docClipboardService = accessor.get(IDocClipboardService);+ return docClipboardService.paste();+ },+};diff --git a/packages/ui-plugin-docs/src/DocUIPlugin.ts b/packages/ui-plugin-docs/src/doc-ui-plugin.tssimilarity index 69%rename from packages/ui-plugin-docs/src/DocUIPlugin.tsrename to packages/ui-plugin-docs/src/doc-ui-plugin.tsindex c0179c0882..ebeeddcf6d 100644--- a/packages/ui-plugin-docs/src/DocUIPlugin.ts+++ b/packages/ui-plugin-docs/src/doc-ui-plugin.ts@@ -4,13 +4,13 @@ import { Dependency, Inject, Injector } from '@wendellhu/redi';import { DefaultDocUiConfig, IDocUIPluginConfig, installObserver } from './Basics';import { DOC_UI_PLUGIN_NAME } from './Basics/Const/PLUGIN_NAME';import { AppUIController } from './Controller';+import { DocClipboardController } from './Controller/clipboard.controller';import { en, zh } from './Locale';+import { DocClipboardService, IDocClipboardService } from './services/clipboard/clipboard.service';export class DocUIPlugin extends Plugin<any> {static override type = PluginType.Doc;- private _appUIController: AppUIController;-constructor(private readonly _config: IDocUIPluginConfig,@Inject(Injector) override _injector: Injector,@@ -19,7 +19,7 @@ export class DocUIPlugin extends Plugin<any> {super(DOC_UI_PLUGIN_NAME);this._config = Tools.deepMerge({}, DefaultDocUiConfig, this._config);- this._initializeDependencies(_injector);+ this._initDependencies(_injector);}override onMounted(): void {@@ -30,14 +30,17 @@ export class DocUIPlugin extends Plugin<any> {installObserver(this);- this._appUIController = this._injector.get(AppUIController);+ this._initModules();}override onDestroy(): void {}- private _initializeDependencies(injector: Injector) {+ private _initDependencies(injector: Injector) {const dependencies: Dependency[] = [+ [IDocClipboardService, { useClass: DocClipboardService }],+ [DocClipboardController],[+ // controllersAppUIController,{useFactory: () => this._injector.createInstance(AppUIController, this._config),@@ -49,4 +52,9 @@ export class DocUIPlugin extends Plugin<any> {injector.add(d);});}++ private _initModules(): void {+ this._injector.get(AppUIController);+ this._injector.get(DocClipboardController).initialize();+ }}diff --git a/packages/ui-plugin-docs/src/index.ts b/packages/ui-plugin-docs/src/index.tsindex e2b8f9692c..9b6f850100 100644--- a/packages/ui-plugin-docs/src/index.ts+++ b/packages/ui-plugin-docs/src/index.ts@@ -1,2 +1,2 @@export * from './Basics';-export * from './DocUIPlugin';+export * from './doc-ui-plugin';diff --git a/packages/ui-plugin-docs/src/services/clipboard/clipboard.service.ts b/packages/ui-plugin-docs/src/services/clipboard/clipboard.service.tsnew file mode 100644index 0000000000..cf989d648d--- /dev/null+++ b/packages/ui-plugin-docs/src/services/clipboard/clipboard.service.ts@@ -0,0 +1,53 @@+import { IClipboardInterfaceService } from '@univerjs/base-ui';+import { Disposable, ICurrentUniverService, toDisposable } from '@univerjs/core';+import { createIdentifier, IDisposable } from '@wendellhu/redi';++export interface IClipboardPropertyItem {}++export interface IDocClipboardHook {+ onCopyProperty?(start: number, end: number): IClipboardPropertyItem;+ onCopyContent?(start: number, end: number): string;+}++export interface IDocClipboardService {+ copy(): Promise<boolean>;+ cut(): Promise<boolean>;+ paste(): Promise<boolean>;++ addClipboardHook(hook: IDocClipboardHook): IDisposable;+}++export const IDocClipboardService = createIdentifier<IDocClipboardService>('doc.clipboard-service');++export class DocClipboardService extends Disposable implements IDocClipboardService {+ private _clipboardHooks: IDocClipboardHook[] = [];++ constructor(+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,+ @IClipboardInterfaceService private readonly _clipboardInterfaceService: IClipboardInterfaceService+ ) {+ super();+ }++ copy(): Promise<boolean> {+ throw new Error('Method not implemented.');+ }++ cut(): Promise<boolean> {+ throw new Error('Method not implemented.');+ }++ paste(): Promise<boolean> {+ throw new Error('Method not implemented.');+ }++ addClipboardHook(hook: IDocClipboardHook): IDisposable {+ this._clipboardHooks.push(hook);+ return toDisposable(() => {+ const index = this._clipboardHooks.indexOf(hook);+ if (index > -1) {+ this._clipboardHooks.splice(index, 1);+ }+ });+ }+}diff --git a/packages/ui-plugin-sheets/src/Basics/Observer.ts b/packages/ui-plugin-sheets/src/Basics/Observer.tsindex 22670d69c9..8d3a11d56c 100644--- a/packages/ui-plugin-sheets/src/Basics/Observer.ts+++ b/packages/ui-plugin-sheets/src/Basics/Observer.ts@@ -1,6 +1,6 @@import { Observable } from '@univerjs/core';-import { SheetUIPlugin } from '../SheetUIPlugin';+import { SheetUIPlugin } from '../sheet-ui-plugin';import { SheetContainer } from '../View';export type SheetUIPluginObserve = {diff --git a/packages/ui-plugin-sheets/src/Controller/clipboard/clipboard.controller.ts b/packages/ui-plugin-sheets/src/Controller/clipboard/clipboard.controller.tsnew file mode 100644index 0000000000..5e6de367c6--- /dev/null+++ b/packages/ui-plugin-sheets/src/Controller/clipboard/clipboard.controller.ts@@ -0,0 +1,52 @@+import { Disposable, ICommandService, ICurrentUniverService, Worksheet } from '@univerjs/core';++import { SheetCopyCommand, SheetCutCommand, SheetPasteCommand } from '../../commands/commands/clipboard.command';+import { ISheetClipboardHook, ISheetClipboardService } from '../../services/clipboard/clipboard.service';++/**+ * This controller add basic clipboard logic for basic features such as text color / BISU / row widths to the clipboard+ * service. You can create a similar clipboard controller to add logic for your own features.+ */+export class SheetClipboardController extends Disposable {+ constructor(+ @ICurrentUniverService private readonly _currentUniverSheet: ICurrentUniverService,+ @ICommandService private readonly _commandService: ICommandService,+ @ISheetClipboardService private readonly _sheetClipboardService: ISheetClipboardService+ ) {+ super();+ }++ initialize() {+ [SheetCopyCommand, SheetCutCommand, SheetPasteCommand].forEach((command) =>+ this.disposeWithMe(this._commandService.registerAsMultipleCommand(command))+ );++ let currentSheet: Worksheet | null = null;++ const self = this;+ const hook: ISheetClipboardHook = {+ onBeforeCopy() {+ // before copy, we should update the current sheet+ // and create necessary cache if needed+ currentSheet = self._currentUniverSheet.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();+ },+ onGetContent(row: number, col: number) {},+ // copy+ onCopy: (row: number, col: number) => ({+ 'data-row': row.toString(),+ 'data-col': col.toString(),+ }),+ onCopyColumn(col: number) {+ return null;+ },+ onCopyRow(row: number) {+ return null;+ },+ onAfterCopy() {+ currentSheet = null;+ },+ };++ this.disposeWithMe(this._sheetClipboardService.addClipboardHook(hook));+ }+}diff --git a/packages/ui-plugin-sheets/src/Controller/shortcut.controller.ts b/packages/ui-plugin-sheets/src/Controller/shortcut.controller.tsindex 994922b266..73fb8b7917 100644--- a/packages/ui-plugin-sheets/src/Controller/shortcut.controller.ts+++ b/packages/ui-plugin-sheets/src/Controller/shortcut.controller.ts@@ -32,11 +32,19 @@ import {MoveSelectionTabShortcutItem,MoveSelectionUpShortcutItem,} from './shortcuts/selection.shortcut';-import { SetBoldShortcutItem, SetItalicShortcutItem, SetStrikeThroughShortcutItem, SetUnderlineShortcutItem } from './shortcuts/style.shortcut';+import {+ SetBoldShortcutItem,+ SetItalicShortcutItem,+ SetStrikeThroughShortcutItem,+ SetUnderlineShortcutItem,+} from './shortcuts/style.shortcut';import { ClearSelectionValueShortcutItem } from './shortcuts/value.shortcut';export class DesktopSheetShortcutController extends Disposable {- constructor(@IShortcutService private readonly _shortcutService: IShortcutService, @ICommandService private readonly _commandService: ICommandService) {+ constructor(+ @IShortcutService private readonly _shortcutService: IShortcutService,+ @ICommandService private readonly _commandService: ICommandService+ ) {super();[diff --git a/packages/ui-plugin-sheets/src/Controller/shortcuts/selection.shortcut.ts b/packages/ui-plugin-sheets/src/Controller/shortcuts/selection.shortcut.tsindex 7f2abffb37..3711cb8db9 100644--- a/packages/ui-plugin-sheets/src/Controller/shortcuts/selection.shortcut.ts+++ b/packages/ui-plugin-sheets/src/Controller/shortcuts/selection.shortcut.ts@@ -1,6 +1,6 @@import { ChangeSelectionCommand, ExpandSelectionCommand, IChangeSelectionCommandParams, IExpandSelectionCommandParams } from '@univerjs/base-sheets';-import { FOCUSING_SHEET, IShortcutItem, KeyCode, MetaKeys } from '@univerjs/base-ui';-import { Direction } from '@univerjs/core';+import { IShortcutItem, KeyCode, MetaKeys } from '@univerjs/base-ui';+import { Direction, FOCUSING_SHEET } from '@univerjs/core';export const MoveSelectionDownShortcutItem: IShortcutItem<IChangeSelectionCommandParams> = {id: ChangeSelectionCommand.id,diff --git a/packages/ui-plugin-sheets/src/Controller/shortcuts/style.shortcut.ts b/packages/ui-plugin-sheets/src/Controller/shortcuts/style.shortcut.tsindex db76db2dba..5479771581 100644--- a/packages/ui-plugin-sheets/src/Controller/shortcuts/style.shortcut.ts+++ b/packages/ui-plugin-sheets/src/Controller/shortcuts/style.shortcut.ts@@ -1,22 +1,29 @@import { SetBoldCommand, SetItalicCommand, SetStrikeThroughCommand, SetUnderlineCommand } from '@univerjs/base-sheets';import { IShortcutItem, KeyCode, MetaKeys } from '@univerjs/base-ui';+import { FOCUSING_SHEET } from '@univerjs/core';++import { FOCUSING_SHEET_CELL_EDITOR } from '../../services/context/context';export const SetBoldShortcutItem: IShortcutItem = {id: SetBoldCommand.id,+ preconditions: (contextService) => contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(FOCUSING_SHEET_CELL_EDITOR),binding: KeyCode.B | MetaKeys.CTRL_COMMAND,};export const SetItalicShortcutItem: IShortcutItem = {id: SetItalicCommand.id,+ preconditions: (contextService) => contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(FOCUSING_SHEET_CELL_EDITOR),binding: KeyCode.I | MetaKeys.CTRL_COMMAND,};export const SetUnderlineShortcutItem: IShortcutItem = {id: SetUnderlineCommand.id,+ preconditions: (contextService) => contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(FOCUSING_SHEET_CELL_EDITOR),binding: KeyCode.U | MetaKeys.CTRL_COMMAND,};export const SetStrikeThroughShortcutItem: IShortcutItem = {id: SetStrikeThroughCommand.id,+ preconditions: (contextService) => contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(FOCUSING_SHEET_CELL_EDITOR),binding: KeyCode.X | MetaKeys.SHIFT | MetaKeys.CTRL_COMMAND,};diff --git a/packages/ui-plugin-sheets/src/Controller/shortcuts/value.shortcut.ts b/packages/ui-plugin-sheets/src/Controller/shortcuts/value.shortcut.tsindex 226c6dd06a..e908342e10 100644--- a/packages/ui-plugin-sheets/src/Controller/shortcuts/value.shortcut.ts+++ b/packages/ui-plugin-sheets/src/Controller/shortcuts/value.shortcut.ts@@ -1,5 +1,6 @@import { ClearSelectionContentCommand } from '@univerjs/base-sheets';-import { FOCUSING_SHEET, IShortcutItem, KeyCode } from '@univerjs/base-ui';+import { IShortcutItem, KeyCode } from '@univerjs/base-ui';+import { FOCUSING_SHEET } from '@univerjs/core';export const ClearSelectionValueShortcutItem: IShortcutItem = {id: ClearSelectionContentCommand.id,diff --git a/packages/ui-plugin-sheets/src/commands/commands/clipboard.command.ts b/packages/ui-plugin-sheets/src/commands/commands/clipboard.command.tsnew file mode 100644index 0000000000..992c0fd0f8--- /dev/null+++ b/packages/ui-plugin-sheets/src/commands/commands/clipboard.command.ts@@ -0,0 +1,46 @@+import { CopyCommand, CutCommand, PasteCommand } from '@univerjs/base-ui';+import { CommandType, FOCUSING_SHEET, IContextService, IMultiCommand } from '@univerjs/core';++import { ISheetClipboardService } from '../../services/clipboard/clipboard.service';+import { FOCUSING_SHEET_EDITOR } from '../../services/context/context';++export const SheetCopyCommand: IMultiCommand = {+ id: CopyCommand.id,+ name: 'sheet.command.copy',+ type: CommandType.COMMAND,+ multi: true,+ priority: 1000,+ preconditions: (contextService: IContextService) =>+ contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(FOCUSING_SHEET_EDITOR),+ handler: async (accessor, params) => {+ const sheetClipboardService = accessor.get(ISheetClipboardService);++ // TODO: permission control here?++ return sheetClipboardService.copy();+ },+};++export const SheetCutCommand: IMultiCommand = {+ id: CutCommand.id,+ name: 'sheet.command.cut',+ type: CommandType.COMMAND,+ multi: true,+ priority: 1000,+ preconditions: (contextService: IContextService) =>+ contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(FOCUSING_SHEET_EDITOR),+ handler: async (accessor, params) =>+ // TODO@wzhudev: the same as SheetCopyCommand but we should dispatch a delete command as well+ true,+};++export const SheetPasteCommand: IMultiCommand = {+ id: PasteCommand.id,+ type: CommandType.COMMAND,+ multi: true,+ name: 'sheet.command.paste',+ priority: 1000,+ preconditions: (contextService: IContextService) =>+ contextService.getContextValue(FOCUSING_SHEET) && !contextService.getContextValue(FOCUSING_SHEET_EDITOR),+ handler: async (accessor, params) => true,+};diff --git a/packages/ui-plugin-sheets/src/commands/commands/utils/copy-util.ts b/packages/ui-plugin-sheets/src/commands/commands/utils/copy-util.tsnew file mode 100644index 0000000000..8512fe1bc2--- /dev/null+++ b/packages/ui-plugin-sheets/src/commands/commands/utils/copy-util.ts@@ -0,0 +1,77 @@+import { IClipboardPropertyItem, ISheetClipboardHook } from '../../../services/clipboard/clipboard.service';++/**+ *+ * @param matrix+ * @param cols+ * @param hooks+ */+export function getTableContent(matrix: number[][], cols: number[], hooks: ISheetClipboardHook[]) {}++export function getSingleCellContent() {}++/**+ * Get content of a single td element.+ * @param row index of the copied cell+ * @param col index of the copied cell+ * @returns+ */+function getTDContent(row: number, col: number, content: string, hooks: ISheetClipboardHook[]) {+ const properties = hooks.map((hook) => hook.onCopy?.(row, col)).filter((v) => !v) as IClipboardPropertyItem[];+ const mergedProperties = mergeProperties(properties);+ const str = zipClipboardPropertyItemToString(mergedProperties);+ return `<td ${str}>${content}</td>`;+}++/**+ *+ * @param row index of the copied row+ * @param cols+ * @param hooks+ * @returns+ */+function getRowContent(row: number, cols: number[], hooks: ISheetClipboardHook[]) {+ const properties = hooks.map((hook) => hook.onCopyRow?.(row)).filter((v) => !v) as IClipboardPropertyItem[];+ const mergedProperties = mergeProperties(properties);+ const str = zipClipboardPropertyItemToString(mergedProperties);+ // TODO: content is not set+ const tds = cols.map((col) => getTDContent(row, col, '', hooks)).join('');++ return `<tr ${str}>${tds}</tr>`;+}++function getColStyle(cols: number[], hooks: ISheetClipboardHook[]) {+ const str = cols+ .map((col) => {+ const properties = hooks+ .map((hook) => hook.onCopyColumn?.(col))+ .filter((v) => !v) as IClipboardPropertyItem[];+ const mergedProperties = mergeProperties(properties);+ const str = zipClipboardPropertyItemToString(mergedProperties);+ return `<col ${str}>`;+ })+ .join('');++ return `<colgroup>${str}</colgroup>`;+}++function mergeProperties(properties: IClipboardPropertyItem[]): IClipboardPropertyItem {+ return properties.reduce((acc, cur) => {+ const keys = Object.keys(cur);+ keys.forEach((key) => {+ if (!acc[key]) {+ acc[key] = cur[key];+ } else {+ acc[key] += `;${cur[key]}`;+ }+ });+ return acc;+ }, {});+}++function zipClipboardPropertyItemToString(item: IClipboardPropertyItem) {+ return Object.keys(item).reduce((acc, cur) => {+ acc += `${cur}="${item[cur]}"`;+ return acc;+ }, '');+}diff --git a/packages/ui-plugin-sheets/src/commands/commands/utils/test/copy-util.spec.ts b/packages/ui-plugin-sheets/src/commands/commands/utils/test/copy-util.spec.tsnew file mode 100644index 0000000000..e69de29bb2diff --git a/packages/ui-plugin-sheets/src/index.ts b/packages/ui-plugin-sheets/src/index.tsindex a5e787140d..4b7b8bb91f 100644--- a/packages/ui-plugin-sheets/src/index.ts+++ b/packages/ui-plugin-sheets/src/index.ts@@ -1,4 +1,4 @@-export * from './Basics';-export * from './Controller';-export * from './SheetUIPlugin';-export * from './View';+export * from './Basics';+export * from './Controller';+export { SheetUIPlugin } from './sheet-ui-plugin';+export * from './View';diff --git a/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor-desktop.service.ts b/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor-desktop.service.tsindex ecd08e928b..3135f1b8f9 100644--- a/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor-desktop.service.ts+++ b/packages/ui-plugin-sheets/src/services/cell-editor/cell-editor-desktop.service.ts@@ -3,13 +3,13 @@ import './desktop.module.less';import { CoverCommand, DocsView, DocsViewManagerService, ICoverCommandParams } from '@univerjs/base-docs';import { DocsEditor, Engine, IMouseEvent, IPointerEvent, IRenderingEngine, ISelectionTransformerShapeManager, Layer, Scene, Viewport } from '@univerjs/base-render';import { CANVAS_VIEW_KEY, CanvasView, ISetRangeValuesCommandParams, SelectionManagerService, SetRangeValuesCommand } from '@univerjs/base-sheets';-import { ContextService, IContextService } from '@univerjs/base-ui';import {createEmptyDocSnapshot,Disposable,handleJsonToDom,ICellRange,ICommandService,+ IContextService,ICurrentUniverService,IDocumentData,IRangeData,@@ -51,7 +51,7 @@ export class DesktopCellEditorService extends Disposable implements ICellEditorS@ICommandService private readonly _commandService: ICommandService,@IRenderingEngine private readonly _renderingEngine: Engine,@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,- @IContextService private readonly _contextService: ContextService+ @IContextService private readonly _contextService: IContextService) {super();}diff --git a/packages/ui-plugin-sheets/src/services/clipboard/README.md b/packages/ui-plugin-sheets/src/services/clipboard/README.mdnew file mode 100644index 0000000000..88d48c9bdd--- /dev/null+++ b/packages/ui-plugin-sheets/src/services/clipboard/README.md@@ -0,0 +1,86 @@+# Sheet Clipboard Module Design++## HTML format++To communicate with other spreadsheet softwares, we support HTML format to store the data in clipboard.++A demo:++```html+<html>+ <body>+ <style type="text/css"></style>+ <table+ xmlns="http://www.w3.org/1999/xhtml"+ cellspacing="0"+ cellpadding="0"+ dir="ltr"+ border="1"+ style="table-layout:fixed;font-size:10pt;font-family:Arial;width:0px;border-collapse:collapse;border:none"+ >+ <!-- col style -->+ <colgroup>+ <col width="100" />+ <col width="100" />+ <col width="100" />+ </colgroup>+ <tbody>+ <!-- row style -->+ <tr style="height:21px;">+ <td style="border-right:1px solid #000000;overflow:hidden;padding:2px 3px 2px 3px;vertical-align:bottom;text-align:right;" data-sheets-value='{"1":3,"3":1}'>+ 1+ </td>+ <td+ style="border-top:1px solid #000000;border-right:1px solid #000000;border-bottom:1px solid #000000;overflow:hidden;padding:2px 3px 2px 3px;vertical-align:bottom;text-align:right;"+ data-sheets-value='{"1":3,"3":4}'+ >+ 4+ </td>+ <td+ style="border-top:1px solid #000000;border-right:1px solid #000000;border-bottom:1px solid #000000;overflow:hidden;padding:2px 3px 2px 3px;vertical-align:bottom;text-align:right;"+ data-sheets-value='{"1":3,"3":5}'+ >+ 5+ </td>+ </tr>+ <tr style="height:21px;">+ <td style="border-right:1px solid #000000;overflow:hidden;padding:2px 3px 2px 3px;vertical-align:bottom;text-align:right;" data-sheets-value='{"1":3,"3":2}'>+ 2+ </td>+ <td+ style="border-right:1px solid #000000;border-bottom:1px solid #000000;overflow:hidden;padding:2px 3px 2px 3px;vertical-align:bottom;text-align:right;"+ data-sheets-value='{"1":3,"3":6}'+ >+ 6+ </td>+ <td+ style="border-right:1px solid #000000;border-bottom:1px solid #000000;overflow:hidden;padding:2px 3px 2px 3px;vertical-align:bottom;text-align:right;"+ data-sheets-value='{"1":3,"3":7}'+ >+ 7+ </td>+ </tr>+ <tr style="height:21px;">+ <td style="border-right:1px solid #000000;overflow:hidden;padding:2px 3px 2px 3px;vertical-align:bottom;text-align:right;" data-sheets-value='{"1":3,"3":3}'>+ 3+ </td>+ <td+ style="border-right:1px solid #000000;border-bottom:1px solid #000000;overflow:hidden;padding:2px 3px 2px 3px;vertical-align:bottom;text-align:right;"+ data-sheets-value='{"1":3,"3":8}'+ >+ 8+ </td>+ <td+ style="border-right:1px solid #000000;border-bottom:1px solid #000000;overflow:hidden;padding:2px 3px 2px 3px;vertical-align:bottom;text-align:right;"+ data-sheets-value='{"1":3,"3":9}'+ >+ 9+ </td>+ </tr>+ </tbody>+ </table>+ </body>+</html>+```++## MSOdiff --git a/packages/ui-plugin-sheets/src/services/clipboard/clipboard.service.ts b/packages/ui-plugin-sheets/src/services/clipboard/clipboard.service.tsnew file mode 100644index 0000000000..9c7b09c774--- /dev/null+++ b/packages/ui-plugin-sheets/src/services/clipboard/clipboard.service.ts@@ -0,0 +1,123 @@+import { SelectionManagerService } from '@univerjs/base-sheets';+import { IClipboardInterfaceService } from '@univerjs/base-ui';+import { Disposable, ICurrentUniverService, toDisposable } from '@univerjs/core';+import { createIdentifier, IDisposable, Inject } from '@wendellhu/redi';++export interface IClipboardPropertyItem {+ [key: string]: string;+}++/**+ * ClipboardHook could:+ * 1. Before copy/cut/paste, decide whether to execute the command and prepare caches if necessary.+ * 1. When copying, decide what content could be written into clipboard.+ * 1. When pasting, get access to the clipboard content and append mutations to the paste command.+ */+export interface ISheetClipboardHook {+ onBeforeCopy?(): void;+ onBeforeCut?(): void;+ onBeforePaste?(): void;++ onGetContent(row: number, col: number): void;++ /**+ * Properties that would be appended to the td element.+ * @param row row of the the copied cell+ * @param col col of the the copied cell+ */+ onCopy?(row: number, col: number): IClipboardPropertyItem | null;+ onCut?(row: number, col: number): IClipboardPropertyItem | null;+ onPaste?(row: number, col: number): void; // TODO: should add raw content here++ onCopyRow?(row: number): IClipboardPropertyItem | null;+ onCutRow?(row: number): IClipboardPropertyItem | null;+ onPasteRow?(row: number): void;++ onCopyColumn?(col: number): IClipboardPropertyItem | null;+ onCutColumn?(row: number): IClipboardPropertyItem | null;+ onPasteColumn?(row: number): void;++ onAfterCopy?(): void;+ onAfterCut?(): void;+ onAfterPaste?(): void;++ getFilteredOutRows?(): number[];+}++/**+ * This service provide hooks for sheet features to supplement content or modify behavior of clipboard.+ */+export interface ISheetClipboardService {+ copy(): Promise<boolean>;+ cut(): Promise<boolean>;+ paste(): Promise<boolean>;++ addClipboardHook(hook: ISheetClipboardHook): IDisposable;+}++export const ISheetClipboardService = createIdentifier<ISheetClipboardService>('sheet.clipboard-service');++export class SheetClipboardService extends Disposable implements ISheetClipboardService {+ private _clipboardHooks: ISheetClipboardHook[] = [];++ constructor(+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,+ @IClipboardInterfaceService private readonly _clipboardInterfaceService: IClipboardInterfaceService+ ) {+ super();+ }++ async copy(): Promise<boolean> {+ const hooks = this._clipboardHooks;+ // steps to copy cells from the sheet++ // 1. get the selected range, the range should be the last one of selected ranges+ const selections = this._selectionManagerService.getLast();+ if (!selections) {+ return false; // maybe we should notify user that there is no selection+ }++ // 2. filtered out rows those are filtered out by plugins (e.g. filter feature)+ const filteredRows = hooks.reduce((acc, cur) => {+ const rows = cur.getFilteredOutRows?.();+ rows?.forEach((r) => acc.add(r));+ return acc;+ }, new Set<number>());++ // 3. calculate selection matrix, span cells would only - maybe warn uses that cells are too may in the future+ // TODO: calculate the selection matrix considering about merged cells and filtered out rows++ // 4. generate html and pure text contents by calling all clipboard hooks++ // 5. write contents to the clipboard interface and done!+ // await this._clipboardInterfaceService.write();++ // FIXME:++ return true;+ }++ async cut(): Promise<boolean> {+ return true;+ }++ async paste(): Promise<boolean> {+ return true;+ }++ addClipboardHook(hook: ISheetClipboardHook): IDisposable {+ this._clipboardHooks.push(hook);++ return toDisposable(() => {+ const index = this._clipboardHooks.indexOf(hook);+ if (index > -1) {+ this._clipboardHooks.splice(index, 1);+ }+ });+ }++ getCellContentClipboardHooks(): Readonly<ISheetClipboardHook[]> {+ return this._clipboardHooks.slice();+ }+}diff --git a/packages/ui-plugin-sheets/src/SheetUIPlugin.ts b/packages/ui-plugin-sheets/src/sheet-ui-plugin.tssimilarity index 68%rename from packages/ui-plugin-sheets/src/SheetUIPlugin.tsrename to packages/ui-plugin-sheets/src/sheet-ui-plugin.tsindex 6a75d13288..6106e03098 100644--- a/packages/ui-plugin-sheets/src/SheetUIPlugin.ts+++ b/packages/ui-plugin-sheets/src/sheet-ui-plugin.ts@@ -1,13 +1,21 @@-import { DragManager, SharedController, SlotManager, ZIndexManager } from '@univerjs/base-ui';+import { DragManager, SlotManager, ZIndexManager } from '@univerjs/base-ui';import { ICurrentUniverService, IUndoRedoService, LocaleService, Plugin, PluginType, Tools } from '@univerjs/core';import { Dependency, Inject, Injector } from '@wendellhu/redi';-import { DefaultSheetUIConfig, installObserver, ISheetUIPluginConfig, SHEET_UI_PLUGIN_NAME, SheetUIPluginObserve } from './Basics';+import {+ DefaultSheetUIConfig,+ installObserver,+ ISheetUIPluginConfig,+ SHEET_UI_PLUGIN_NAME,+ SheetUIPluginObserve,+} from './Basics';import { AppUIController } from './Controller/AppUIController';+import { SheetClipboardController } from './Controller/clipboard/clipboard.controller';import { DesktopSheetShortcutController } from './Controller/shortcut.controller';import { en, zh } from './Locale';import { ICellEditorService } from './services/cell-editor/cell-editor.service';import { DesktopCellEditorService } from './services/cell-editor/cell-editor-desktop.service';+import { ISheetClipboardService, SheetClipboardService } from './services/clipboard/clipboard.service';import { Fx } from './View/FormulaBar';export class SheetUIPlugin extends Plugin<SheetUIPluginObserve> {@@ -21,7 +29,11 @@ export class SheetUIPlugin extends Plugin<SheetUIPluginObserve> {private _dragManager: DragManager;- constructor(config: ISheetUIPluginConfig, @Inject(Injector) override readonly _injector: Injector, @Inject(LocaleService) private readonly _localeService: LocaleService) {+ constructor(+ config: ISheetUIPluginConfig,+ @Inject(Injector) override readonly _injector: Injector,+ @Inject(LocaleService) private readonly _localeService: LocaleService+ ) {super(SHEET_UI_PLUGIN_NAME);this._config = Tools.deepMerge({}, DefaultSheetUIConfig, config);@@ -40,7 +52,8 @@ export class SheetUIPlugin extends Plugin<SheetUIPluginObserve> {en,});- this.initDependencies();+ this._initDependencies();+ this._initModules();this._markSheetAsFocused();}@@ -59,7 +72,11 @@ export class SheetUIPlugin extends Plugin<SheetUIPluginObserve> {* @param str*/setFormulaContent(str: string) {- this._appUIController.getSheetContainerController().getFormulaBarUIController().getFormulaBar().setFormulaContent(str);+ this._appUIController+ .getSheetContainerController()+ .getFormulaBarUIController()+ .getFormulaBar()+ .setFormulaContent(str);}setFx(fx: Fx) {@@ -72,14 +89,21 @@ export class SheetUIPlugin extends Plugin<SheetUIPluginObserve> {currentService.focusUniverInstance(c.getUnitId());}- private initDependencies(): void {+ private _initDependencies(): void {([+ // legacy managers[DragManager],[ZIndexManager],[SlotManager],- [DesktopSheetShortcutController],++ // services[ICellEditorService, { useClass: DesktopCellEditorService }],+ [ISheetClipboardService, { useClass: SheetClipboardService }],++ // controllers+ [DesktopSheetShortcutController],+ [SheetClipboardController],[AppUIController, { useFactory: () => this._injector.createInstance(AppUIController, this._config) }],] as Dependency[]).forEach((d) => this._injector.add(d));@@ -88,9 +112,12 @@ export class SheetUIPlugin extends Plugin<SheetUIPluginObserve> {this._zIndexManager = this._injector.get(ZIndexManager);this._injector.get(IUndoRedoService);- this._injector.get(SharedController);this._injector.get(DesktopSheetShortcutController);this._injector.get(ICellEditorService).initialize();this._injector.get(AppUIController);}++ private _initModules(): void {+ this._injector.get(SheetClipboardController).initialize();+ }}