Skip to content

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

refactor(sheet): refactor sheet selection manager (#143)

Univera561a9930825
diff --git a/packages/base-render/package.json b/packages/base-render/package.json
index 08ec169612..e9494d2794 100644
--- a/packages/base-render/package.json
+++ b/packages/base-render/package.json
@@ -56,6 +56,7 @@
"@univerjs/core": "workspace:^0.0.1",
"@wendellhu/redi": "^0.12.7",
"react": "^18.2.0",
- "react-dom": "^18.2.0"
+ "react-dom": "^18.2.0",
+ "rxjs": "^7.8.1"
}
-}
\ No newline at end of file
+}
diff --git a/packages/base-render/src/BaseObject.ts b/packages/base-render/src/BaseObject.ts
index 79b556303c..e7d4566d65 100644
--- a/packages/base-render/src/BaseObject.ts
+++ b/packages/base-render/src/BaseObject.ts
@@ -1,15 +1,11 @@
-import { EventState, IKeyValue, Observable, Observer, Nullable } from '@univerjs/core';
-import { IBoundRect, Vector2 } from './Basics/Vector2';
-
-import { Transform } from './Basics/Transform';
+import { EventState, IKeyValue, Nullable, Observable, Observer } from '@univerjs/core';
+import { CURSOR_TYPE, EVENT_TYPE, RENDER_CLASS_TYPE } from './Basics/Const';
import { IMouseEvent, IPointerEvent, IWheelEvent } from './Basics/IEvents';
-
-import { generateRandomKey, toPx } from './Basics/Tools';
-
-import { EVENT_TYPE, CURSOR_TYPE, RENDER_CLASS_TYPE } from './Basics/Const';
-
import { IObjectFullState, ITransformChangeState, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from './Basics/Interfaces';
+import { generateRandomKey, toPx } from './Basics/Tools';
+import { Transform } from './Basics/Transform';
+import { IBoundRect, Vector2 } from './Basics/Vector2';
export const BASE_OBJECT_ARRAY = ['top', 'left', 'width', 'height', 'angle', 'scaleX', 'scaleY', 'skewX', 'skewY', 'flipX', 'flipY', 'strokeWidth'];
diff --git a/packages/base-render/src/Basics/Selection.ts b/packages/base-render/src/Basics/Selection.ts
new file mode 100644
index 0000000000..4835d53a7b
--- /dev/null
+++ b/packages/base-render/src/Basics/Selection.ts
@@ -0,0 +1,78 @@
+import { ISelectionData, ISelectionRange, Nullable } from '@univerjs/core';
+
+/**
+ * Whether to display the controller that modifies the selection, distributed in 8 locations
+ * tl top_left_corner
+ * tc top_center_corner
+ * tr top_right_corner
+ * ml middle_left_corner
+ * mr middle_right_corner
+ * bl bottom_left_corner
+ * bc bottom_center_corner
+ * br bottom_right_corner
+ */
+export interface ISelectionControlConfig {
+ tl?: boolean;
+ tc?: boolean;
+ tr?: boolean;
+ ml?: boolean;
+ mr?: boolean;
+ bl?: boolean;
+ bc?: boolean;
+ br?: boolean;
+}
+
+export interface ISelectionStyle {
+ strokeDashArray: number[];
+ strokeWidth: number;
+ stroke: string;
+ fill: string;
+ controls: ISelectionControlConfig;
+ hasAutoFill: boolean;
+}
+
+export interface ISelectionDataWithStyle extends ISelectionData {
+ style: Nullable<ISelectionStyle>;
+}
+
+export interface ISelectionRangeWithStyle extends ISelectionRange {
+ style: Nullable<ISelectionStyle>;
+}
+
+export const NORMAL_SELECTION_PLUGIN_STYLE = {
+ strokeDashArray: [],
+ strokeWidth: 2,
+ stroke: '#FFF000',
+ fill: 'rgba(0, 0, 0, 0.2)',
+ controls: { tr: true, tl: true, br: true, bl: true },
+ hasAutoFill: false,
+};
+
+export function convertSelectionDataToRange(selectionDataWithStyle: ISelectionDataWithStyle): ISelectionRangeWithStyle {
+ const { selection, cellInfo, style } = selectionDataWithStyle;
+ const result: ISelectionRangeWithStyle = {
+ rangeData: {
+ startRow: selection.startRow,
+ startColumn: selection.startColumn,
+ endRow: selection.endRow,
+ endColumn: selection.endColumn,
+ },
+ cellRange: null,
+ style,
+ };
+ if (cellInfo != null) {
+ const { row, column, isMerged, isMergedMainCell } = cellInfo;
+ const { startRow, startColumn, endRow, endColumn } = cellInfo.mergeInfo;
+ result.cellRange = {
+ row,
+ column,
+ isMerged,
+ isMergedMainCell,
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
+ };
+ }
+ return result;
+}
diff --git a/packages/base-render/src/Basics/Tools.ts b/packages/base-render/src/Basics/Tools.ts
index d52d00ac33..574d64259a 100644
--- a/packages/base-render/src/Basics/Tools.ts
+++ b/packages/base-render/src/Basics/Tools.ts
@@ -1,8 +1,9 @@
-import { FontStyleType, ICellInfo, ISelection, IStyleBase, Nullable, ObjectMatrix, Tools, IRangeData, BaselineOffset, IScale } from '@univerjs/core';
+import { BaselineOffset, FontStyleType, ICellInfo, IRangeData, IScale, ISelection, IStyleBase, Nullable, Tools } from '@univerjs/core';
+
import { DEFAULT_FONTFACE_PLANE } from './Const';
-import { IBoundRectNoAngle } from './Vector2';
-import { IFontLocale } from './Interfaces';
import { FontCache } from './FontCache';
+import { IFontLocale } from './Interfaces';
+import { IBoundRectNoAngle } from './Vector2';
const OBJECT_ARRAY = '[object Array]';
const OBJECT_NUMBER = '[object Number]';
@@ -469,34 +470,28 @@ export function getCellPositionByIndex(row: number, column: number, rowHeightAcc
};
}
-export function getCellByIndex(
- row: number,
- column: number,
- rowHeightAccumulation: number[],
- columnWidthAccumulation: number[],
- dataMergeCache: ObjectMatrix<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);
- const { isMerged, isMergedMainCell, newEndRow, newEndColumn, mergeRow, mergeColumn } = mergeCellHandler(row, column, dataMergeCache);
+ const { isMerged, isMergedMainCell, startRow, startColumn, endRow, endColumn } = mergeCellHandler(row, column, mergeData);
let mergeInfo = {
- startRow: mergeRow,
- startColumn: mergeColumn,
- endRow: newEndRow,
- endColumn: newEndColumn,
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
startY: 0,
endY: 0,
startX: 0,
endX: 0,
};
- if (isMerged && mergeRow !== -1 && mergeColumn !== -1) {
- const mergeStartY = rowHeightAccumulation[mergeRow - 1] || 0;
- const mergeEndY = rowHeightAccumulation[newEndRow];
+ if (isMerged && startRow !== -1 && startColumn !== -1) {
+ const mergeStartY = rowHeightAccumulation[startRow - 1] || 0;
+ const mergeEndY = rowHeightAccumulation[endRow];
- const mergeStartX = columnWidthAccumulation[mergeColumn - 1] || 0;
- const mergeEndX = columnWidthAccumulation[newEndColumn];
+ const mergeStartX = columnWidthAccumulation[startColumn - 1] || 0;
+ const mergeEndX = columnWidthAccumulation[endColumn];
mergeInfo = {
...mergeInfo,
startY: mergeStartY,
@@ -504,9 +499,9 @@ export function getCellByIndex(
startX: mergeStartX,
endX: mergeEndX,
};
- } else if (!isMerged && newEndRow !== -1 && newEndColumn !== -1) {
- endY = rowHeightAccumulation[newEndRow] || 0;
- endX = columnWidthAccumulation[newEndColumn] || 0;
+ } else if (!isMerged && endRow !== -1 && endColumn !== -1) {
+ endY = rowHeightAccumulation[endRow] || 0;
+ endX = columnWidthAccumulation[endColumn] || 0;
}
return {
@@ -522,49 +517,84 @@ export function getCellByIndex(
};
}
-export function mergeCellHandler(row: number, column: number, dataMergeCache?: ObjectMatrix<IRangeData>) {
+export function mergeCellHandler(row: number, column: number, mergeData?: IRangeData[]) {
let isMerged = false; // The upper left cell only renders the content
let isMergedMainCell = false;
let newEndRow = -1;
let newEndColumn = -1;
let mergeRow = -1;
let mergeColumn = -1;
- 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;
- }
- });
+ if (mergeData == null) {
+ return {
+ row,
+ column,
+ isMergedMainCell,
+ isMerged,
+ endRow: newEndRow,
+ endColumn: newEndColumn,
+ startRow: mergeRow,
+ startColumn: mergeColumn,
+ };
+ }
+ for (let i = 0; i < mergeData.length; i++) {
+ const { startRow: startRowMarge, endRow: endRowMarge, startColumn: startColumnMarge, endColumn: endColumnMarge } = mergeData[i];
+ if (row === startRowMarge && column === startColumnMarge) {
+ newEndRow = endRowMarge;
+ newEndColumn = endColumnMarge;
+ mergeRow = startRowMarge;
+ mergeColumn = startColumnMarge;
+
+ isMergedMainCell = true;
+ break;
+ }
+ if (row >= startRowMarge && row <= endRowMarge && column >= startColumnMarge && column <= endColumnMarge) {
+ newEndRow = endRowMarge;
+ newEndColumn = endColumnMarge;
+ mergeRow = startRowMarge;
+ mergeColumn = startColumnMarge;
+
+ isMerged = true;
+ break;
+ }
+ }
+ // 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,
isMergedMainCell,
isMerged,
- newEndRow,
- newEndColumn,
- mergeRow,
- mergeColumn,
+ endRow: newEndRow,
+ endColumn: newEndColumn,
+ startRow: mergeRow,
+ startColumn: mergeColumn,
};
}
diff --git a/packages/base-render/src/Basics/index.ts b/packages/base-render/src/Basics/index.ts
index fa4f1c2218..6ee48f80ba 100644
--- a/packages/base-render/src/Basics/index.ts
+++ b/packages/base-render/src/Basics/index.ts
@@ -1,13 +1,14 @@
export * from './Const';
+export * from './DocumentNodeTools';
+export * from './Draw';
export * from './FontCache';
export * from './IDocumentSkeletonCached';
export * from './IEvents';
export * from './Interfaces';
+export * from './Path2';
export * from './PerformanceMonitor';
+export * from './ScrollXY';
+export * from './Selection';
+export * from './Tools';
export * from './Transform';
-export * from './Draw';
export * from './Vector2';
-export * from './Path2';
-export * from './Tools';
-export * from './ScrollXY';
-export * from './DocumentNodeTools';
diff --git a/packages/base-render/src/Component/Component.ts b/packages/base-render/src/Component/Component.ts
index cf42a130e0..065ba8011a 100644
--- a/packages/base-render/src/Component/Component.ts
+++ b/packages/base-render/src/Component/Component.ts
@@ -1,6 +1,7 @@
import { sortRules } from '@univerjs/core';
-import { IBoundRect } from '../Basics/Vector2';
+
import { BaseObject } from '../BaseObject';
+import { IBoundRect } from '../Basics/Vector2';
import { ComponentExtension } from './Extension';
export class RenderComponent<T, U> extends BaseObject {
@@ -11,14 +12,14 @@ export class RenderComponent<T, U> extends BaseObject {
}
register(...extensions: Array<ComponentExtension<T, U>>) {
- for (let extension of extensions) {
+ for (const extension of extensions) {
extension.parent = this;
this._extensions.set(extension.uKey, extension);
}
}
unRegister(...uKeys: string[]) {
- for (let uKey of uKeys) {
+ for (const uKey of uKeys) {
this._extensions.delete(uKey);
}
}
diff --git a/packages/base-render/src/Component/Docs/Common/Page.ts b/packages/base-render/src/Component/Docs/Common/Page.ts
index aada725234..648cb69e73 100644
--- a/packages/base-render/src/Component/Docs/Common/Page.ts
+++ b/packages/base-render/src/Component/Docs/Common/Page.ts
@@ -1,9 +1,10 @@
import { DocumentBodyModel, Nullable, PageOrientType } from '@univerjs/core';
-import { createSkeletonSection } from './Section';
+
import { BreakType, IDocumentSkeletonFooter, IDocumentSkeletonHeader, IDocumentSkeletonPage, ISkeletonResourceReference } from '../../../Basics/IDocumentSkeletonCached';
import { ISectionBreakConfig } from '../../../Basics/Interfaces';
// eslint-disable-next-line import/no-cycle
import { dealWithSections } from '../Block/Section';
+import { createSkeletonSection } from './Section';
import { updateBlockIndex } from './Tools';
// 新增数据结构框架
diff --git a/packages/base-render/src/Component/Docs/DocComponent.ts b/packages/base-render/src/Component/Docs/DocComponent.ts
index 240e9a53b6..4da09b0a97 100644
--- a/packages/base-render/src/Component/Docs/DocComponent.ts
+++ b/packages/base-render/src/Component/Docs/DocComponent.ts
@@ -1,13 +1,14 @@
import { Nullable } from '@univerjs/core';
-import { IBoundRect } from '../../Basics/Vector2';
+
+import { RENDER_CLASS_TYPE } from '../../Basics/Const';
+import { IDocumentSkeletonLine, IDocumentSkeletonSpan, PageLayoutType, SpanType } from '../../Basics/IDocumentSkeletonCached';
import { INodeInfo, INodePosition, INodeSearch, ITransformChangeState } from '../../Basics/Interfaces';
+import { IBoundRect } from '../../Basics/Vector2';
import { Canvas } from '../../Canvas';
-import { RenderComponent } from '../Component';
-import { DocumentSkeleton } from './DocSkeleton';
import { Scene } from '../../Scene';
+import { RenderComponent } from '../Component';
import { DOCS_EXTENSION_TYPE } from './DocExtension';
-import { IDocumentSkeletonLine, IDocumentSkeletonSpan, PageLayoutType, SpanType } from '../../Basics/IDocumentSkeletonCached';
-import { RENDER_CLASS_TYPE } from '../../Basics/Const';
+import { DocumentSkeleton } from './DocSkeleton';
export class DocComponent extends RenderComponent<IDocumentSkeletonSpan | IDocumentSkeletonLine, DOCS_EXTENSION_TYPE> {
pageWidth: number;
diff --git a/packages/base-render/src/Component/Docs/DocSkeleton.ts b/packages/base-render/src/Component/Docs/DocSkeleton.ts
index 214ce2e7b3..7669faff97 100644
--- a/packages/base-render/src/Component/Docs/DocSkeleton.ts
+++ b/packages/base-render/src/Component/Docs/DocSkeleton.ts
@@ -12,18 +12,15 @@ import {
VerticalAlign,
WrapStrategy,
} from '@univerjs/core';
-import { getLastPage, updateBlockIndex } from './Common/Tools';
-
-import { createSkeletonPage } from './Common/Page';
-
-import { createSkeletonSection } from './Common/Section';
-
-import { dealWithSections } from './Block/Section';
import { IDocumentSkeletonCached, IDocumentSkeletonPage, ISkeletonResourceReference } from '../../Basics/IDocumentSkeletonCached';
import { IDocsConfig, ISectionBreakConfig } from '../../Basics/Interfaces';
-import { Skeleton } from '../Skeleton';
import { IBoundRect } from '../../Basics/Vector2';
+import { Skeleton } from '../Skeleton';
+import { dealWithSections } from './Block/Section';
+import { createSkeletonPage } from './Common/Page';
+import { createSkeletonSection } from './Common/Section';
+import { getLastPage, updateBlockIndex } from './Common/Tools';
const DEFAULT_SECTION_BREAK: ISectionBreak = {
columnProperties: [],
diff --git a/packages/base-render/src/Component/Docs/Extensions/FontAndBaseLine.ts b/packages/base-render/src/Component/Docs/Extensions/FontAndBaseLine.ts
index fd52d3697a..bac2edee71 100644
--- a/packages/base-render/src/Component/Docs/Extensions/FontAndBaseLine.ts
+++ b/packages/base-render/src/Component/Docs/Extensions/FontAndBaseLine.ts
@@ -1,9 +1,10 @@
import { BaselineOffset, getColorStyle, IScale } from '@univerjs/core';
-import { DocumentsSpanAndLineExtensionRegistry } from '../../Extension';
-import { docExtension } from '../DocExtension';
-import { IDocumentSkeletonSpan } from '../../../Basics/IDocumentSkeletonCached';
+
import { COLOR_BLACK_RGB } from '../../../Basics/Const';
+import { IDocumentSkeletonSpan } from '../../../Basics/IDocumentSkeletonCached';
import { Vector2 } from '../../../Basics/Vector2';
+import { DocumentsSpanAndLineExtensionRegistry } from '../../Extension';
+import { docExtension } from '../DocExtension';
const UNIQUE_KEY = 'DefaultDocsFontAndBaseLineExtension';
diff --git a/packages/base-render/src/Component/Sheets/Extensions/Background.ts b/packages/base-render/src/Component/Sheets/Extensions/Background.ts
index 0589d1e24e..4752698e54 100644
--- a/packages/base-render/src/Component/Sheets/Extensions/Background.ts
+++ b/packages/base-render/src/Component/Sheets/Extensions/Background.ts
@@ -1,19 +1,19 @@
// import { fixLineWidthByScale, getColor, IScale } from '@Basics';
import { IScale } from '@univerjs/core';
-import { SpreadsheetSkeleton } from '../SheetSkeleton';
-import { SheetExtension } from './SheetExtension';
-import { SpreadsheetExtensionRegistry } from '../../Extension';
import { fixLineWidthByScale, getColor } from '../../../Basics/Tools';
+import { SpreadsheetExtensionRegistry } from '../../Extension';
+import { SpreadsheetSkeleton } from '../SheetSkeleton';
+import { SheetExtension } from './SheetExtension';
const UNIQUE_KEY = 'DefaultBackgroundExtension';
export class Background extends SheetExtension {
- uKey = UNIQUE_KEY;
+ override uKey = UNIQUE_KEY;
- zIndex = 20;
+ override zIndex = 20;
- draw(ctx: CanvasRenderingContext2D, parentScale: IScale, spreadsheetSkeleton: SpreadsheetSkeleton) {
+ override draw(ctx: CanvasRenderingContext2D, parentScale: IScale, spreadsheetSkeleton: SpreadsheetSkeleton) {
const { rowTitleWidth, columnTitleHeight, dataMergeCache, stylesCache } = spreadsheetSkeleton;
const { background } = stylesCache;
if (!spreadsheetSkeleton) {
@@ -35,8 +35,9 @@ export class Background extends SheetExtension {
ctx.beginPath();
backgroundCache.forEach((rowIndex, backgroundRow) => {
backgroundRow.forEach((columnIndex) => {
- let { isMerged, startY, endY, startX, endX } = this.getCellIndex(rowIndex, columnIndex, rowHeightAccumulation, columnWidthAccumulation, dataMergeCache);
-
+ const cellInfo = this.getCellIndex(rowIndex, columnIndex, rowHeightAccumulation, columnWidthAccumulation, dataMergeCache);
+ let { startY, endY, startX, endX } = cellInfo;
+ const { isMerged } = cellInfo;
if (isMerged) {
return true;
}
diff --git a/packages/base-render/src/Component/Sheets/Extensions/Border.ts b/packages/base-render/src/Component/Sheets/Extensions/Border.ts
index 64a495b97e..ca790ac55f 100644
--- a/packages/base-render/src/Component/Sheets/Extensions/Border.ts
+++ b/packages/base-render/src/Component/Sheets/Extensions/Border.ts
@@ -1,20 +1,21 @@
-import { BorderStyleTypes, IRangeData, ObjectMatrix, IScale } from '@univerjs/core';
-import { BorderCacheItem } from '../Interfaces';
+import { BorderStyleTypes, IRangeData, IScale, ObjectMatrix } from '@univerjs/core';
+
+import { BORDER_TYPE, COLOR_BLACK_RGB } from '../../../Basics/Const';
+import { drawLineByBorderType, getLineWidth, setLineType } from '../../../Basics/Draw';
import { fixLineWidthByScale } from '../../../Basics/Tools';
+import { SpreadsheetExtensionRegistry } from '../../Extension';
+import { BorderCacheItem } from '../Interfaces';
import { SpreadsheetSkeleton } from '../SheetSkeleton';
import { SheetExtension } from './SheetExtension';
-import { BORDER_TYPE, COLOR_BLACK_RGB } from '../../../Basics/Const';
-import { SpreadsheetExtensionRegistry } from '../../Extension';
-import { drawLineByBorderType, getLineWidth, setLineType } from '../../../Basics/Draw';
const UNIQUE_KEY = 'DefaultBorderExtension';
export class Border extends SheetExtension {
- uKey = UNIQUE_KEY;
+ override uKey = UNIQUE_KEY;
- zIndex = 30;
+ override zIndex = 30;
- draw(ctx: CanvasRenderingContext2D, parentScale: IScale, spreadsheetSkeleton: SpreadsheetSkeleton) {
+ override draw(ctx: CanvasRenderingContext2D, parentScale: IScale, spreadsheetSkeleton: SpreadsheetSkeleton) {
const { rowColumnSegment, rowTitleWidth, columnTitleHeight, dataMergeCache, stylesCache, overflowCache } = spreadsheetSkeleton;
const { border } = stylesCache;
if (!spreadsheetSkeleton) {
@@ -40,9 +41,11 @@ export class Border extends SheetExtension {
return true;
}
- let { isMerged, startY, endY, startX, endX } = this.getCellIndex(rowIndex, columnIndex, rowHeightAccumulation, columnWidthAccumulation, dataMergeCache);
+ const cellInfo = this.getCellIndex(rowIndex, columnIndex, rowHeightAccumulation, columnWidthAccumulation, dataMergeCache);
+
+ let { startY, endY, startX, endX } = cellInfo;
- if (isMerged) {
+ if (cellInfo.isMerged) {
return true;
}
@@ -51,7 +54,7 @@ export class Border extends SheetExtension {
startX = fixLineWidthByScale(startX, scaleX);
endX = fixLineWidthByScale(endX, scaleX);
- for (let key in borderCaches) {
+ for (const key in borderCaches) {
const { type, style, color } = borderCaches[key] as BorderCacheItem;
if (this._getOverflowExclusion(overflowCache, type, rowIndex, columnIndex)) {
diff --git a/packages/base-render/src/Component/Sheets/Extensions/BorderAuxiliary.ts b/packages/base-render/src/Component/Sheets/Extensions/BorderAuxiliary.ts
index 44775b5e4a..8ba2a915c9 100644
--- a/packages/base-render/src/Component/Sheets/Extensions/BorderAuxiliary.ts
+++ b/packages/base-render/src/Component/Sheets/Extensions/BorderAuxiliary.ts
@@ -1,17 +1,18 @@
-import { BooleanNumber, IRangeData, IScale, ObjectMatrix } from '@univerjs/core';
+import { BooleanNumber, IRangeData, IScale } from '@univerjs/core';
+
import { fixLineWidthByScale, getColor } from '../../../Basics/Tools';
+import { SpreadsheetExtensionRegistry } from '../../Extension';
import { SpreadsheetSkeleton } from '../SheetSkeleton';
import { SheetExtension } from './SheetExtension';
-import { SpreadsheetExtensionRegistry } from '../../Extension';
const UNIQUE_KEY = 'DefaultBorderAuxiliaryExtension';
export class BorderAuxiliary extends SheetExtension {
- uKey = UNIQUE_KEY;
+ override uKey = UNIQUE_KEY;
- zIndex = 10;
+ override zIndex = 10;
- draw(ctx: CanvasRenderingContext2D, parentScale: IScale, spreadsheetSkeleton: SpreadsheetSkeleton) {
+ override draw(ctx: CanvasRenderingContext2D, parentScale: IScale, spreadsheetSkeleton: SpreadsheetSkeleton) {
const { rowColumnSegment, rowTitleWidth = 0, columnTitleHeight = 0, dataMergeCache, overflowCache, stylesCache, showGridlines } = spreadsheetSkeleton;
const { startRow, endRow, startColumn, endColumn } = rowColumnSegment;
@@ -30,8 +31,8 @@ export class BorderAuxiliary extends SheetExtension {
ctx.beginPath();
ctx.lineWidth = 1 / scale;
ctx.strokeStyle = getColor([217, 217, 217])!;
- let width = fixLineWidthByScale(columnTotalWidth, scale);
- let height = fixLineWidthByScale(rowTotalHeight, scale);
+ const width = fixLineWidthByScale(columnTotalWidth, scale);
+ const height = fixLineWidthByScale(rowTotalHeight, scale);
const columnWidthAccumulationLength = columnWidthAccumulation.length;
const rowHeightAccumulationLength = rowHeightAccumulation.length;
for (let r = startRow - 1; r <= endRow; r++) {
@@ -57,40 +58,41 @@ export class BorderAuxiliary extends SheetExtension {
this._clearRectangle(ctx, scale, rowHeightAccumulation, columnWidthAccumulation, dataMergeCache);
- this._clearRectangle(ctx, scale, rowHeightAccumulation, columnWidthAccumulation, overflowCache);
+ this._clearRectangle(ctx, scale, rowHeightAccumulation, columnWidthAccumulation, overflowCache.toNativeArray());
ctx.restore();
}
- private _clearRectangle(
- ctx: CanvasRenderingContext2D,
- scale: number,
- rowHeightAccumulation: number[],
- columnWidthAccumulation: number[],
- dataMergeCache?: ObjectMatrix<IRangeData>
- ) {
- dataMergeCache?.forEach((r, dataMergeRow) => {
- dataMergeRow?.forEach((c, dataCache) => {
- const { startRow, endRow, startColumn, endColumn } = dataCache;
-
- const startY = fixLineWidthByScale(rowHeightAccumulation[startRow - 1] || 0, scale);
- const endY = fixLineWidthByScale(rowHeightAccumulation[endRow], scale);
-
- const startX = fixLineWidthByScale(columnWidthAccumulation[startColumn - 1] || 0, scale);
- const endX = fixLineWidthByScale(columnWidthAccumulation[endColumn], scale);
-
- ctx.clearRect(startX, startY, endX - startX, endY - startY);
-
- // After ClearRect, the lines will become thinner, and the lines will be repaired below.
- ctx.beginPath();
- ctx.moveTo(startX, startY);
- ctx.lineTo(endX, startY);
- ctx.lineTo(endX, endY);
- ctx.lineTo(startX, endY);
- ctx.lineTo(startX, startY);
- ctx.stroke();
- ctx.closePath();
- });
- });
+ private _clearRectangle(ctx: CanvasRenderingContext2D, scale: number, rowHeightAccumulation: number[], columnWidthAccumulation: number[], dataMergeCache?: IRangeData[]) {
+ if (dataMergeCache == null) {
+ return;
+ }
+ for (const dataCache of dataMergeCache) {
+ const { startRow, endRow, startColumn, endColumn } = dataCache;
+
+ const startY = fixLineWidthByScale(rowHeightAccumulation[startRow - 1] || 0, scale);
+ const endY = fixLineWidthByScale(rowHeightAccumulation[endRow], scale);
+
+ const startX = fixLineWidthByScale(columnWidthAccumulation[startColumn - 1] || 0, scale);
+ const endX = fixLineWidthByScale(columnWidthAccumulation[endColumn], scale);
+
+ ctx.clearRect(startX, startY, endX - startX, endY - startY);
+
+ // After ClearRect, the lines will become thinner, and the lines will be repaired below.
+ ctx.beginPath();
+ ctx.moveTo(startX, startY);
+ ctx.lineTo(endX, startY);
+ ctx.lineTo(endX, endY);
+ ctx.lineTo(startX, endY);
+ ctx.lineTo(startX, startY);
+ ctx.stroke();
+ ctx.closePath();
+ }
+
+ // dataMergeCache?.forEach((r, dataMergeRow) => {
+ // dataMergeRow?.forEach((c, dataCache) => {
+
+ // });
+ // });
}
}
diff --git a/packages/base-render/src/Component/Sheets/Extensions/ColumnTitleLayout.ts b/packages/base-render/src/Component/Sheets/Extensions/ColumnTitleLayout.ts
index 59493d05b7..eed170b12f 100644
--- a/packages/base-render/src/Component/Sheets/Extensions/ColumnTitleLayout.ts
+++ b/packages/base-render/src/Component/Sheets/Extensions/ColumnTitleLayout.ts
@@ -1,18 +1,19 @@
-import { numberToABC, IScale } from '@univerjs/core';
-import { fixLineWidthByScale, getColor } from '../../../Basics/Tools';
+import { IScale, numberToABC } from '@univerjs/core';
+
import { MIDDLE_CELL_POS_MAGIC_NUMBER } from '../../../Basics/Const';
+import { fixLineWidthByScale, getColor } from '../../../Basics/Tools';
+import { SheetColumnTitleExtensionRegistry } from '../../Extension';
import { SpreadsheetSkeleton } from '../SheetSkeleton';
import { SheetExtension } from './SheetExtension';
-import { SheetColumnTitleExtensionRegistry } from '../../Extension';
const UNIQUE_KEY = 'DefaultColumnTitleLayoutExtension';
export class ColumnTitleLayout extends SheetExtension {
- uKey = UNIQUE_KEY;
+ override uKey = UNIQUE_KEY;
- zIndex = 10;
+ override zIndex = 10;
- draw(ctx: CanvasRenderingContext2D, parentScale: IScale, spreadsheetSkeleton: SpreadsheetSkeleton) {
+ override draw(ctx: CanvasRenderingContext2D, parentScale: IScale, spreadsheetSkeleton: SpreadsheetSkeleton) {
const { rowColumnSegment, rowTitleWidth = 0, columnTitleHeight = 0 } = spreadsheetSkeleton;
const { startRow, endRow, startColumn, endColumn } = rowColumnSegment;
if (!spreadsheetSkeleton) {
diff --git a/packages/base-render/src/Component/Sheets/Extensions/Font.ts b/packages/base-render/src/Component/Sheets/Extensions/Font.ts
index 269be2c972..d8d8b3768e 100644
--- a/packages/base-render/src/Component/Sheets/Extensions/Font.ts
+++ b/packages/base-render/src/Component/Sheets/Extensions/Font.ts
@@ -1,10 +1,11 @@
-import { HorizontalAlign, IColorStyle, ObjectMatrix, WrapStrategy, IScale } from '@univerjs/core';
-import { SpreadsheetSkeleton } from '../SheetSkeleton';
-import { SheetExtension } from './SheetExtension';
-import { SpreadsheetExtensionRegistry } from '../../Extension';
-import { SheetComponent } from '../SheetComponent';
+import { HorizontalAlign, IColorStyle, IScale, ObjectMatrix, WrapStrategy } from '@univerjs/core';
+
import { fixLineWidthByScale } from '../../../Basics/Tools';
+import { SpreadsheetExtensionRegistry } from '../../Extension';
import { fontCacheItem } from '../Interfaces';
+import { SheetComponent } from '../SheetComponent';
+import { SpreadsheetSkeleton } from '../SheetSkeleton';
+import { SheetExtension } from './SheetExtension';
const UNIQUE_KEY = 'DefaultFontExtension';
export class Font extends SheetExtension {
@@ -44,13 +45,9 @@ export class Font extends SheetExtension {
const fontObjectArray = fontList[fontFormat];
fontObjectArray.forEach((rowIndex, fontArray) => {
fontArray.forEach((columnIndex, docsConfig) => {
- let { isMerged, isMergedMainCell, startY, endY, startX, endX, mergeInfo } = this.getCellIndex(
- rowIndex,
- columnIndex,
- rowHeightAccumulation,
- columnWidthAccumulation,
- dataMergeCache
- );
+ const cellInfo = this.getCellIndex(rowIndex, columnIndex, rowHeightAccumulation, columnWidthAccumulation, dataMergeCache);
+ let { startY, endY, startX, endX } = cellInfo;
+ const { isMerged, isMergedMainCell, mergeInfo } = cellInfo;
if (isMerged) {
return true;
diff --git a/packages/base-render/src/Component/Sheets/Extensions/RowTitleLayout.ts b/packages/base-render/src/Component/Sheets/Extensions/RowTitleLayout.ts
index 83169ece27..d61dd85004 100644
--- a/packages/base-render/src/Component/Sheets/Extensions/RowTitleLayout.ts
+++ b/packages/base-render/src/Component/Sheets/Extensions/RowTitleLayout.ts
@@ -1,18 +1,19 @@
import { IScale } from '@univerjs/core';
-import { fixLineWidthByScale, getColor } from '../../../Basics/Tools';
+
import { MIDDLE_CELL_POS_MAGIC_NUMBER } from '../../../Basics/Const';
+import { fixLineWidthByScale, getColor } from '../../../Basics/Tools';
+import { SheetRowTitleExtensionRegistry } from '../../Extension';
import { SpreadsheetSkeleton } from '../SheetSkeleton';
import { SheetExtension } from './SheetExtension';
-import { SheetRowTitleExtensionRegistry } from '../../Extension';
const UNIQUE_KEY = 'DefaultRowTitleLayoutExtension';
export class RowTitleLayout extends SheetExtension {
- uKey = UNIQUE_KEY;
+ override uKey = UNIQUE_KEY;
- zIndex = 10;
+ override zIndex = 10;
- draw(ctx: CanvasRenderingContext2D, parentScale: IScale, spreadsheetSkeleton: SpreadsheetSkeleton) {
+ override draw(ctx: CanvasRenderingContext2D, parentScale: IScale, spreadsheetSkeleton: SpreadsheetSkeleton) {
const { rowColumnSegment, rowTitleWidth = 0, columnTitleHeight = 0 } = spreadsheetSkeleton;
const { startRow, endRow, startColumn, endColumn } = rowColumnSegment;
if (!spreadsheetSkeleton) {
diff --git a/packages/base-render/src/Component/Sheets/Extensions/SheetExtension.ts b/packages/base-render/src/Component/Sheets/Extensions/SheetExtension.ts
index 663f5c22ca..6e57aafaf0 100644
--- a/packages/base-render/src/Component/Sheets/Extensions/SheetExtension.ts
+++ b/packages/base-render/src/Component/Sheets/Extensions/SheetExtension.ts
@@ -1,4 +1,5 @@
-import { IRangeData, ObjectMatrix } from '@univerjs/core';
+import { IRangeData } from '@univerjs/core';
+
import { getCellByIndex } from '../../../Basics/Tools';
import { ComponentExtension } from '../../Extension';
import { SpreadsheetSkeleton } from '../SheetSkeleton';
@@ -8,9 +9,9 @@ export enum SHEET_EXTENSION_TYPE {
}
export class SheetExtension extends ComponentExtension<SpreadsheetSkeleton, SHEET_EXTENSION_TYPE> {
- type = SHEET_EXTENSION_TYPE.GRID;
+ override type = SHEET_EXTENSION_TYPE.GRID;
- getCellIndex(rowIndex: number, columnIndex: number, rowHeightAccumulation: number[], columnWidthAccumulation: number[], dataMergeCache: ObjectMatrix<IRangeData>) {
+ getCellIndex(rowIndex: number, columnIndex: number, rowHeightAccumulation: number[], columnWidthAccumulation: number[], dataMergeCache: IRangeData[]) {
return getCellByIndex(rowIndex, columnIndex, rowHeightAccumulation, columnWidthAccumulation, dataMergeCache);
}
}
diff --git a/packages/base-render/src/Component/Sheets/Selection/SelectionManager.ts b/packages/base-render/src/Component/Sheets/Selection/SelectionManager.ts
deleted file mode 100644
index 4f143e7b4a..0000000000
--- a/packages/base-render/src/Component/Sheets/Selection/SelectionManager.ts
+++ /dev/null
@@ -1,419 +0,0 @@
-import { Nullable, Observer, ISelection, makeCellToSelection, IRangeData, IRangeCellData } from '@univerjs/core';
-import { SelectionControl } from './SelectionControl';
-import { ScrollTimer } from '../../../ScrollTimer';
-import { IMouseEvent, IPointerEvent } from '../../../Basics/IEvents';
-import { SheetComponent } from '../SheetComponent';
-import { SelectionModel } from './SelectionModel';
-import { Vector2 } from '../../../Basics/Vector2';
-import { Scene } from '../../../Scene';
-
-/**
- * TODO 注册selection拦截,可能在有公式ArrayObject时,fx公式栏显示不同
- *
- * SelectionManager 维护model数据list,action也是修改这一层数据,obs监听到数据变动后,自动刷新(control仍然可以持有数据)
- */
-export class SelectionManager {
- hasSelection: boolean = false;
-
- private _moveObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
- private _upObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
- private _selectionControls: SelectionControl[] = []; // sheetID:Controls
-
- private _startSelectionRange: ISelection;
-
- private _startOffsetX: number = 0;
-
- private _startOffsetY: number = 0;
-
- private _scrollTimer: ScrollTimer;
-
- private _cancelDownObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
- private _cancelUpObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
- constructor(private _spreadsheet: SheetComponent) {
- this._mainEventInitial();
- }
-
- static create(spreadsheet: SheetComponent) {
- return new SelectionManager(spreadsheet);
- }
-
- /**
- * add a selection
- * @param selectionRange
- * @param curCellRange
- * @returns
- */
- addControlToCurrentByRangeData(selectionRange: IRangeData, curCellRange: Nullable<IRangeCellData>) {
- const currentControls = this.getCurrentControls();
- if (!currentControls) {
- return;
- }
- const main = this._spreadsheet;
-
- const control = SelectionControl.create(this.getScene(), currentControls.length);
-
- let cellInfo = null;
- if (curCellRange) {
- cellInfo = main.getCellByIndex(curCellRange.row, curCellRange.column);
- }
-
- const { startRow, startColumn, endRow, endColumn } = selectionRange;
- const startCell = main.getNoMergeCellPositionByIndex(startRow, startColumn);
- const endCell = main.getNoMergeCellPositionByIndex(endRow, endColumn);
-
- // update control
- control.update(
- {
- startColumn,
- startRow,
- endColumn,
- endRow,
- startY: startCell?.startY || 0,
- endY: endCell?.endY || 0,
- startX: startCell?.startX || 0,
- endX: endCell?.endX || 0,
- },
- cellInfo
- );
-
- currentControls.push(control);
- }
-
- getSpreadsheet() {
- return this._spreadsheet;
- }
-
- getMaxIndex() {
- return this._spreadsheet.zIndex + 1;
- }
-
- getScene() {
- return this._spreadsheet.getScene() as Scene;
- }
-
- getSkeleton() {
- return this._spreadsheet.getSkeleton();
- }
-
- getRowAndColumnCount() {
- const skeleton = this.getSkeleton();
- return {
- rowCount: skeleton?.getRowCount() || 1000,
- columnCount: skeleton?.getColumnCount() || 50,
- };
- }
-
- getCurrentControls() {
- return this._selectionControls;
- }
-
- getCurrentControl() {
- const controls = this.getCurrentControls();
- if (controls && controls.length > 0) {
- for (const control of controls) {
- const currentCell = control.model.currentCell;
- if (currentCell) {
- return control;
- }
- }
- }
- }
-
- clearSelectionControls() {
- const curControls = this.getCurrentControls();
-
- if (curControls.length > 0) {
- for (const control of curControls) {
- control.dispose();
- }
-
- curControls.length = 0; // clear currentSelectionControls
- }
- }
-
- /**
- * Returns the list of active ranges in the active sheet or null if there are no active ranges.
- * If there is a single range selected, this behaves as a getActiveRange() call.
- *
- * @returns
- */
- getActiveRangeList(): Nullable<IRangeData[]> {
- const controls = this.getCurrentControls();
- if (controls && controls.length > 0) {
- const selections = controls?.map((control: SelectionControl) => {
- const model: SelectionModel = control.model;
- return {
- startRow: model.startRow,
- startColumn: model.startColumn,
- endRow: model.endRow,
- endColumn: model.endColumn,
- };
- });
- return selections;
- }
- }
-
- /**
- * Returns the selected range in the active sheet, or null if there is no active range. If multiple ranges are selected this method returns only the last selected range.
- * TODO: 默认最后一个选区为当前激活选区,或者当前激活单元格所在选区为激活选区
- * @returns
- */
- getActiveRange(): Nullable<IRangeData> {
- const controls = this.getCurrentControls();
- const model = controls && controls[controls.length - 1].model;
- return (
- model && {
- startRow: model.startRow,
- startColumn: model.startColumn,
- endRow: model.endRow,
- endColumn: model.endColumn,
- }
- );
- }
-
- /**
- * get active selection control
- * @returns
- */
- getActiveSelection(): Nullable<SelectionControl> {
- const controls = this.getCurrentControls();
- return controls && controls[controls.length - 1];
- }
-
- dispose() {
- this.clearSelectionControls();
- this._moveObserver = null;
- this._upObserver = null;
- }
-
- /**
- * When mousedown and mouseup need to go to the coordination and undo stack, when mousemove does not need to go to the coordination and undo stack
- * @param moveEvt
- * @param selectionControl
- * @returns
- */
- private _moving(moveOffsetX: number, moveOffsetY: number, selectionControl: Nullable<SelectionControl>) {
- // console.log('moving');
- const main = this._spreadsheet;
- // const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
- const { startRow, startColumn, endRow, endColumn } = this._startSelectionRange;
-
- // const scrollXY = main.getAncestorScrollXY(this._startOffsetX, this._startOffsetY);
- // const scene = this.getScene() as Scene;
-
- // const coord = scene.getRelativeCoord(Vector2.FromArray([moveOffsetX, moveOffsetY]));
- // const { x: newMoveOffsetX, y: newMoveOffsetY } = coord;
-
- const scrollXY = main.getScrollXYByRelativeCoords(Vector2.FromArray([this._startOffsetX, this._startOffsetY]));
-
- const moveCellInfo = main.calculateCellIndexByPosition(moveOffsetX, moveOffsetY, scrollXY);
- const moveActualSelection = makeCellToSelection(moveCellInfo);
-
- if (!moveActualSelection) {
- return false;
- }
- const { startRow: moveStartRow, startColumn: moveStartColumn, endColumn: moveEndColumn, endRow: moveEndRow } = moveActualSelection;
-
- const newStartRow = Math.min(moveStartRow, startRow);
- const newStartColumn = Math.min(moveStartColumn, startColumn);
- const newEndRow = Math.max(moveEndRow, endRow);
- const newEndColumn = Math.max(moveEndColumn, endColumn);
- const newBounding = main.getSelectionBounding(newStartRow, newStartColumn, newEndRow, newEndColumn);
-
- if (!newBounding) {
- return false;
- }
- const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = newBounding;
-
- const startCell = main.getNoMergeCellPositionByIndex(finalStartRow, finalStartColumn);
- const endCell = main.getNoMergeCellPositionByIndex(finalEndRow, finalEndColumn);
-
- const newSelectionRange: ISelection = {
- startColumn: finalStartColumn,
- startRow: finalStartRow,
- endColumn: finalEndColumn,
- endRow: finalEndRow,
- startY: startCell?.startY || 0,
- endY: endCell?.endY || 0,
- startX: startCell?.startX || 0,
- endX: endCell?.endX || 0,
- };
- // Only notify when the selection changes
- const {
- startRow: oldStartRow,
- endRow: oldEndRow,
- startColumn: oldStartColumn,
- endColumn: oldEndColumn,
- } = selectionControl?.model || { startRow: -1, endRow: -1, startColumn: -1, endColumn: -1 };
-
- if (oldStartColumn !== finalStartColumn || oldStartRow !== finalStartRow || oldEndColumn !== finalEndColumn || oldEndRow !== finalEndRow) {
- selectionControl && selectionControl.update(newSelectionRange);
- }
- }
-
- private _endSelection(scene: Scene) {
- scene.onPointerMoveObserver.remove(this._moveObserver);
- scene.onPointerUpObserver.remove(this._upObserver);
- scene.enableEvent();
-
- this._scrollTimer?.stopScroll();
-
- const mainScene = scene.getEngine()?.activeScene;
- mainScene?.onPointerDownObserver.remove(this._cancelDownObserver);
- mainScene?.onPointerUpObserver.remove(this._cancelUpObserver);
- }
-
- private _addCancelObserver() {
- const scene = this.getScene() as Scene;
- const mainScene = scene.getEngine()?.activeScene;
- if (mainScene == null || mainScene === scene) {
- return;
- }
- mainScene.onPointerDownObserver.remove(this._cancelDownObserver);
- mainScene.onPointerUpObserver.remove(this._cancelUpObserver);
- this._cancelDownObserver = mainScene.onPointerDownObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
- this._endSelection(scene);
- });
-
- this._cancelUpObserver = mainScene.onPointerUpObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
- this._endSelection(scene);
- });
- }
-
- // eslint-disable-next-line max-lines-per-function
- private _mainEventInitial() {
- const main = this._spreadsheet;
- // eslint-disable-next-line max-lines-per-function
- main.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {
- const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
-
- const scene = this.getScene() as Scene;
-
- const relativeCoords = scene.getRelativeCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
-
- const { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
-
- this._startOffsetX = newEvtOffsetX;
- this._startOffsetY = newEvtOffsetY;
-
- const scrollXY = main.getScrollXYByRelativeCoords(relativeCoords);
-
- const cellInfo = main.calculateCellIndexByPosition(newEvtOffsetX, newEvtOffsetY, scrollXY);
- const actualSelection = makeCellToSelection(cellInfo);
- if (!actualSelection) {
- return false;
- }
-
- const { startRow, startColumn, endColumn, endRow, startY, endY, startX, endX } = actualSelection;
-
- const startSelectionRange = {
- startColumn,
- startRow,
- endColumn,
- endRow,
- startY,
- endY,
- startX,
- endX,
- };
-
- this._startSelectionRange = startSelectionRange;
-
- let selectionControl: Nullable<SelectionControl> = this.getCurrentControl();
-
- const curControls = this.getCurrentControls();
-
- if (!curControls) {
- return false;
- }
-
- for (const control of curControls) {
- // right click
- if (evt.button === 2 && control.model.isInclude(startSelectionRange)) {
- selectionControl = control;
- return;
- }
- // Click to an existing selection
- if (control.model.isEqual(startSelectionRange)) {
- selectionControl = control;
- break;
- }
-
- // There can only be one highlighted cell, so clear the highlighted cell of the existing selection
- if (!evt.shiftKey) {
- control.clearHighlight();
- }
- }
-
- // In addition to pressing the ctrl or shift key, we must clear the previous selection
- if (curControls.length > 0 && !evt.ctrlKey && !evt.shiftKey) {
- for (const control of curControls) {
- control.dispose();
- }
-
- curControls.length = 0; // clear currentSelectionControls
- }
-
- const currentCell = selectionControl && selectionControl.model.currentCell;
-
- if (selectionControl && evt.shiftKey && currentCell) {
- const { row, column } = currentCell;
-
- // TODO startCell position calculate error
- const startCell = main.getNoMergeCellPositionByIndex(row, column);
- const endCell = main.getNoMergeCellPositionByIndex(endRow, endColumn);
-
- const newSelectionRange = {
- startColumn: column,
- startRow: row,
- endColumn: startSelectionRange.startColumn,
- endRow: startSelectionRange.startRow,
- startY: startCell?.startY || 0,
- endY: endCell?.endY || 0,
- startX: startCell?.startX || 0,
- endX: endCell?.endX || 0,
- };
- selectionControl.update(newSelectionRange, currentCell);
- } else {
- selectionControl = SelectionControl.create(scene, curControls.length + this.getMaxIndex());
- selectionControl.update(startSelectionRange, cellInfo);
- curControls.push(selectionControl);
- }
-
- this.hasSelection = true;
-
- scene.disableEvent();
-
- this._endSelection(scene);
-
- const scrollTimer = ScrollTimer.create(this.getScene());
- scrollTimer.startScroll(newEvtOffsetX, newEvtOffsetY);
-
- this._scrollTimer = scrollTimer;
-
- this._addCancelObserver();
-
- this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
- const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
-
- const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeCoord(Vector2.FromArray([moveOffsetX, moveOffsetY]));
-
- this._moving(newMoveOffsetX, newMoveOffsetY, selectionControl);
-
- scrollTimer.scrolling(newMoveOffsetX, newMoveOffsetY, () => {
- this._moving(newMoveOffsetX, newMoveOffsetY, selectionControl);
- });
- });
-
- this._upObserver = scene.onPointerUpObserver.add((upEvt: IPointerEvent | IMouseEvent) => {
- this._endSelection(scene);
- });
-
- state.stopPropagation();
- });
- }
-}
diff --git a/packages/base-render/src/Component/Sheets/Selection/SelectionModel.ts b/packages/base-render/src/Component/Sheets/Selection/selection-transformer-model.ts
similarity index 85%
rename from packages/base-render/src/Component/Sheets/Selection/SelectionModel.ts
rename to packages/base-render/src/Component/Sheets/Selection/selection-transformer-model.ts
index 0a0ae7d7fa..8aba9f033d 100644
--- a/packages/base-render/src/Component/Sheets/Selection/SelectionModel.ts
+++ b/packages/base-render/src/Component/Sheets/Selection/selection-transformer-model.ts
@@ -1,7 +1,8 @@
-import { ICellInfo, ISelection, Nullable, makeCellToSelection } from '@univerjs/core';
+import { ICellInfo, ISelection, makeCellToSelection, Nullable } from '@univerjs/core';
+
import { SELECTION_TYPE } from '../../../Basics/Const';
-export class SelectionModel implements ISelection {
+export class SelectionTransformerModel implements ISelection {
private _startColumn: number;
private _startRow: number;
@@ -96,6 +97,24 @@ export class SelectionModel implements ISelection {
return makeCellToSelection(this._currentCell);
}
+ getSelection() {
+ return {
+ startColumn: this._startColumn,
+ startRow: this._startRow,
+ endColumn: this._endColumn,
+ endRow: this._endRow,
+
+ startX: this._startX,
+ startY: this._startY,
+ endX: this._endX,
+ endY: this._endY,
+ };
+ }
+
+ getCell() {
+ return this._currentCell;
+ }
+
getValue() {
return {
selection: {
@@ -109,7 +128,7 @@ export class SelectionModel implements ISelection {
endX: this._endX,
endY: this._endY,
},
- cell: this._currentCell,
+ cellInfo: this._currentCell,
};
}
diff --git a/packages/base-render/src/Component/Sheets/Selection/selection-transformer-shape-manager.ts b/packages/base-render/src/Component/Sheets/Selection/selection-transformer-shape-manager.ts
new file mode 100644
index 0000000000..e1db9056cf
--- /dev/null
+++ b/packages/base-render/src/Component/Sheets/Selection/selection-transformer-shape-manager.ts
@@ -0,0 +1,547 @@
+import {
+ DEFAULT_WORKSHEET_COLUMN_COUNT,
+ DEFAULT_WORKSHEET_ROW_COUNT,
+ ICellInfo,
+ ICellRange,
+ IRangeData,
+ ISelection,
+ makeCellToSelection,
+ Nullable,
+ Observer,
+} from '@univerjs/core';
+import { createIdentifier } from '@wendellhu/redi';
+import { BehaviorSubject, Observable } from 'rxjs';
+
+import { IMouseEvent, IPointerEvent } from '../../../Basics/IEvents';
+import { ISelectionDataWithStyle, ISelectionRangeWithStyle, NORMAL_SELECTION_PLUGIN_STYLE } from '../../../Basics/Selection';
+import { Vector2 } from '../../../Basics/Vector2';
+import { Scene } from '../../../Scene';
+import { ScrollTimer } from '../../../ScrollTimer';
+import { SpreadsheetSkeleton } from '../SheetSkeleton';
+import { SelectionTransformerModel } from './selection-transformer-model';
+import { SelectionTransformerShape } from './selection-transformer-shape';
+
+export interface ISelectionTransformerShapeManager {
+ readonly selectionRangeWithStyle$: Observable<ISelectionDataWithStyle[]>;
+ addControlToCurrentByRangeData(data: ISelectionDataWithStyle): void;
+ changeRuntime(skeleton: SpreadsheetSkeleton, scene: Scene): void;
+ // getSpreadsheet(): void;
+ // getMaxIndex(): void;
+ getScene(): void;
+ getSkeleton(): void;
+ getRowAndColumnCount(): void;
+ getCurrentControls(): void;
+ getCurrentControl(): void;
+ clearSelectionControls(): void;
+ getActiveRangeList(): Nullable<IRangeData[]>;
+ getActiveRange(): Nullable<IRangeData>;
+ getActiveSelection(): Nullable<SelectionTransformerShape>;
+ convertSelectionRangeToData(selectionRange: ISelectionRangeWithStyle): ISelectionDataWithStyle;
+ convertRangeDataToSelection(rangeData: IRangeData): ISelection;
+ convertCellRangeToInfo(cellRange: Nullable<ICellRange>): Nullable<ICellInfo>;
+ eventTrigger(evt: IPointerEvent | IMouseEvent, zIndex: number): void;
+ // getMoveCellInfo(direction: Direction, selectionData: Nullable<ISelectionData>): Nullable<ISelectionData>;
+ // transformCellDataToSelectionData(row: number, column: number): Nullable<ISelectionData>;
+ reset(): void;
+}
+
+/**
+ * TODO 注册selection拦截,可能在有公式ArrayObject时,fx公式栏显示不同
+ *
+ * SelectionManager 维护model数据list,action也是修改这一层数据,obs监听到数据变动后,自动刷新(control仍然可以持有数据)
+ */
+export class SelectionTransformerShapeManager implements ISelectionTransformerShapeManager {
+ hasSelection: boolean = false;
+
+ private _downObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
+
+ private _moveObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
+
+ private _upObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
+
+ private _selectionControls: SelectionTransformerShape[] = []; // sheetID:Controls
+
+ private _startSelectionRange: ISelection;
+
+ private _startOffsetX: number = 0;
+
+ private _startOffsetY: number = 0;
+
+ private _scrollTimer: ScrollTimer;
+
+ private _cancelDownObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
+
+ private _cancelUpObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
+
+ private _skeleton: SpreadsheetSkeleton;
+
+ private _scene: Scene;
+
+ private readonly _selectionRangeWithStyle$ = new BehaviorSubject<ISelectionDataWithStyle[]>([]);
+
+ // eslint-disable-next-line @typescript-eslint/member-ordering
+ readonly selectionRangeWithStyle$ = this._selectionRangeWithStyle$.asObservable();
+
+ static create() {
+ return new SelectionTransformerShapeManager();
+ }
+
+ /**
+ * add a selection
+ * @param selectionRange
+ * @param curCellRange
+ * @returns
+ */
+ addControlToCurrentByRangeData(data: ISelectionDataWithStyle) {
+ const currentControls = this.getCurrentControls();
+ if (!currentControls) {
+ return;
+ }
+ const { selection, cellInfo } = data;
+
+ let style = data.style;
+
+ if (style == null) {
+ style = NORMAL_SELECTION_PLUGIN_STYLE;
+ }
+
+ const { strokeDashArray, strokeWidth, stroke, fill, controls, hasAutoFill } = style;
+
+ const control = SelectionTransformerShape.create(this.getScene(), currentControls.length);
+
+ // update control
+ control.update(selection, cellInfo);
+
+ currentControls.push(control);
+ }
+
+ changeRuntime(skeleton: SpreadsheetSkeleton, scene: Scene) {
+ this._skeleton = skeleton;
+ this._scene = scene;
+ }
+
+ // getSpreadsheet() {
+ // return this._sheetComponent;
+ // }
+
+ // getMaxIndex() {
+ // return this._sheetComponent.zIndex + 1;
+ // }
+
+ getScene() {
+ return this._scene;
+ }
+
+ getSkeleton() {
+ return this._skeleton;
+ }
+
+ getRowAndColumnCount() {
+ const skeleton = this.getSkeleton();
+ return {
+ rowCount: skeleton?.getRowCount() || DEFAULT_WORKSHEET_ROW_COUNT,
+ columnCount: skeleton?.getColumnCount() || DEFAULT_WORKSHEET_COLUMN_COUNT,
+ };
+ }
+
+ getSelectionDataWithStyle() {
+ const selectionControls = this._selectionControls;
+ return selectionControls.map((control) => control.getValue());
+ }
+
+ getCurrentControls() {
+ return this._selectionControls;
+ }
+
+ getCurrentControl() {
+ const controls = this.getCurrentControls();
+ if (controls && controls.length > 0) {
+ for (const control of controls) {
+ const currentCell = control.model.currentCell;
+ if (currentCell) {
+ return control;
+ }
+ }
+ }
+ }
+
+ clearSelectionControls() {
+ const curControls = this.getCurrentControls();
+
+ if (curControls.length > 0) {
+ for (const control of curControls) {
+ control.dispose();
+ }
+
+ curControls.length = 0; // clear currentSelectionControls
+ }
+ }
+
+ /**
+ * Returns the list of active ranges in the active sheet or null if there are no active ranges.
+ * If there is a single range selected, this behaves as a getActiveRange() call.
+ *
+ * @returns
+ */
+ getActiveRangeList(): Nullable<IRangeData[]> {
+ const controls = this.getCurrentControls();
+ if (controls && controls.length > 0) {
+ const selections = controls?.map((control: SelectionTransformerShape) => {
+ const model: SelectionTransformerModel = control.model;
+ return {
+ startRow: model.startRow,
+ startColumn: model.startColumn,
+ endRow: model.endRow,
+ endColumn: model.endColumn,
+ };
+ });
+ return selections;
+ }
+ }
+
+ /**
+ * Returns the selected range in the active sheet, or null if there is no active range. If multiple ranges are selected this method returns only the last selected range.
+ * TODO: 默认最后一个选区为当前激活选区,或者当前激活单元格所在选区为激活选区
+ * @returns
+ */
+ getActiveRange(): Nullable<IRangeData> {
+ const controls = this.getCurrentControls();
+ const model = controls && controls[controls.length - 1].model;
+ return (
+ model && {
+ startRow: model.startRow,
+ startColumn: model.startColumn,
+ endRow: model.endRow,
+ endColumn: model.endColumn,
+ }
+ );
+ }
+
+ /**
+ * get active selection control
+ * @returns
+ */
+ getActiveSelection(): Nullable<SelectionTransformerShape> {
+ const controls = this.getCurrentControls();
+ return controls && controls[controls.length - 1];
+ }
+
+ endSelection() {
+ this._endSelection();
+ }
+
+ reset() {
+ this.clearSelectionControls();
+ this._moveObserver = null;
+ this._upObserver = null;
+ this._downObserver = null;
+ }
+
+ resetAndEndSelection() {
+ this.endSelection();
+ this.reset();
+ }
+
+ // eslint-disable-next-line max-lines-per-function
+ eventTrigger(evt: IPointerEvent | IMouseEvent, zIndex = 0) {
+ const skeleton = this._skeleton;
+
+ const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
+
+ const scene = this.getScene();
+
+ const relativeCoords = scene.getRelativeCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+
+ const { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
+
+ this._startOffsetX = newEvtOffsetX;
+ this._startOffsetY = newEvtOffsetY;
+
+ const scrollXY = scene.getScrollXYByRelativeCoords(relativeCoords);
+
+ const { scaleX, scaleY } = scene.getAncestorScale();
+
+ const cellInfo = skeleton.calculateCellIndexByPosition(newEvtOffsetX, newEvtOffsetY, scaleX, scaleY, scrollXY);
+ const actualSelection = makeCellToSelection(cellInfo);
+ if (!actualSelection) {
+ return false;
+ }
+
+ const { startRow, startColumn, endColumn, endRow, startY, endY, startX, endX } = actualSelection;
+
+ const startSelectionRange = {
+ startColumn,
+ startRow,
+ endColumn,
+ endRow,
+ startY,
+ endY,
+ startX,
+ endX,
+ };
+
+ this._startSelectionRange = startSelectionRange;
+
+ let selectionControl: Nullable<SelectionTransformerShape> = this.getCurrentControl();
+
+ const curControls = this.getCurrentControls();
+
+ if (!curControls) {
+ return false;
+ }
+
+ for (const control of curControls) {
+ // right click
+ if (evt.button === 2 && control.model.isInclude(startSelectionRange)) {
+ selectionControl = control;
+ return;
+ }
+ // Click to an existing selection
+ if (control.model.isEqual(startSelectionRange)) {
+ selectionControl = control;
+ break;
+ }
+
+ // There can only be one highlighted cell, so clear the highlighted cell of the existing selection
+ if (!evt.shiftKey) {
+ control.clearHighlight();
+ }
+ }
+
+ // In addition to pressing the ctrl or shift key, we must clear the previous selection
+ if (curControls.length > 0 && !evt.ctrlKey && !evt.shiftKey) {
+ for (const control of curControls) {
+ control.dispose();
+ }
+
+ curControls.length = 0; // clear currentSelectionControls
+ }
+
+ const currentCell = selectionControl && selectionControl.model.currentCell;
+
+ if (selectionControl && evt.shiftKey && currentCell) {
+ const { row, column } = currentCell;
+
+ // TODO startCell position calculate error
+ const startCell = skeleton.getNoMergeCellPositionByIndex(row, column, scaleX, scaleY);
+ const endCell = skeleton.getNoMergeCellPositionByIndex(endRow, endColumn, scaleX, scaleY);
+
+ const newSelectionRange = {
+ startColumn: column,
+ startRow: row,
+ endColumn: startSelectionRange.startColumn,
+ endRow: startSelectionRange.startRow,
+ startY: startCell?.startY || 0,
+ endY: endCell?.endY || 0,
+ startX: startCell?.startX || 0,
+ endX: endCell?.endX || 0,
+ };
+ selectionControl.update(newSelectionRange, currentCell);
+ } else {
+ selectionControl = SelectionTransformerShape.create(scene, curControls.length + zIndex);
+ selectionControl.update(startSelectionRange, cellInfo);
+ curControls.push(selectionControl);
+ }
+
+ this.hasSelection = true;
+
+ scene.disableEvent();
+
+ this._endSelection();
+
+ const scrollTimer = ScrollTimer.create(this.getScene());
+ scrollTimer.startScroll(newEvtOffsetX, newEvtOffsetY);
+
+ this._scrollTimer = scrollTimer;
+
+ this._addCancelObserver();
+
+ this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
+ const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
+
+ const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeCoord(Vector2.FromArray([moveOffsetX, moveOffsetY]));
+
+ this._moving(newMoveOffsetX, newMoveOffsetY, selectionControl);
+
+ scrollTimer.scrolling(newMoveOffsetX, newMoveOffsetY, () => {
+ this._moving(newMoveOffsetX, newMoveOffsetY, selectionControl);
+ });
+ });
+
+ this._upObserver = scene.onPointerUpObserver.add((upEvt: IPointerEvent | IMouseEvent) => {
+ this._endSelection();
+ this._selectionRangeWithStyle$.next(this.getSelectionDataWithStyle());
+ });
+
+ // state.stopPropagation();
+ }
+
+ convertSelectionRangeToData(selectionRange: ISelectionRangeWithStyle): ISelectionDataWithStyle {
+ const { rangeData, cellRange, style } = selectionRange;
+
+ return {
+ selection: this.convertRangeDataToSelection(rangeData),
+ cellInfo: this.convertCellRangeToInfo(cellRange),
+ style,
+ };
+ }
+
+ convertRangeDataToSelection(rangeData: IRangeData): ISelection {
+ const { startRow, startColumn, endRow, endColumn } = rangeData;
+ const { scaleX, scaleY } = this._scene.getAncestorScale();
+ const startCell = this._skeleton.getNoMergeCellPositionByIndex(startRow, startColumn, scaleX, scaleY);
+ const endCell = this._skeleton.getNoMergeCellPositionByIndex(endRow, endColumn, scaleX, scaleY);
+
+ return {
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
+ startY: startCell?.startY || 0,
+ endY: endCell?.endY || 0,
+ startX: startCell?.startX || 0,
+ endX: endCell?.endX || 0,
+ };
+ }
+
+ convertCellRangeToInfo(cellRange: Nullable<ICellRange>): Nullable<ICellInfo> {
+ if (cellRange == null) {
+ return;
+ }
+ const { row, column, isMerged, isMergedMainCell, startRow, startColumn, endRow, endColumn } = cellRange;
+ const { scaleX, scaleY } = this._scene.getAncestorScale();
+
+ const cellPosition = this._skeleton.getNoMergeCellPositionByIndex(row, column, scaleX, scaleY);
+
+ const startCell = this._skeleton.getNoMergeCellPositionByIndex(startRow, startColumn, scaleX, scaleY);
+ const endCell = this._skeleton.getNoMergeCellPositionByIndex(endRow, endColumn, scaleX, scaleY);
+
+ return {
+ row,
+ column,
+ isMerged,
+ isMergedMainCell,
+ startX: cellPosition.startX,
+ startY: cellPosition.startY,
+ endX: cellPosition.endX,
+ endY: cellPosition.endY,
+ mergeInfo: {
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
+ startY: startCell?.startY || 0,
+ endY: endCell?.endY || 0,
+ startX: startCell?.startX || 0,
+ endX: endCell?.endX || 0,
+ },
+ };
+ }
+
+ /**
+ * When mousedown and mouseup need to go to the coordination and undo stack, when mousemove does not need to go to the coordination and undo stack
+ * @param moveEvt
+ * @param selectionControl
+ * @returns
+ */
+ private _moving(moveOffsetX: number, moveOffsetY: number, selectionControl: Nullable<SelectionTransformerShape>) {
+ // console.log('moving');
+ const main = this._skeleton;
+
+ const scene = this._scene;
+ // const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
+ const { startRow, startColumn, endRow, endColumn } = this._startSelectionRange;
+
+ // const scrollXY = main.getAncestorScrollXY(this._startOffsetX, this._startOffsetY);
+ // const scene = this.getScene() as Scene;
+
+ // const coord = scene.getRelativeCoord(Vector2.FromArray([moveOffsetX, moveOffsetY]));
+ // const { x: newMoveOffsetX, y: newMoveOffsetY } = coord;
+
+ const scrollXY = scene.getScrollXYByRelativeCoords(Vector2.FromArray([this._startOffsetX, this._startOffsetY]));
+
+ const { scaleX, scaleY } = scene.getAncestorScale();
+
+ const moveCellInfo = main.calculateCellIndexByPosition(moveOffsetX, moveOffsetY, scaleX, scaleY, scrollXY);
+ const moveActualSelection = makeCellToSelection(moveCellInfo);
+
+ if (!moveActualSelection) {
+ return false;
+ }
+ const { startRow: moveStartRow, startColumn: moveStartColumn, endColumn: moveEndColumn, endRow: moveEndRow } = moveActualSelection;
+
+ const newStartRow = Math.min(moveStartRow, startRow);
+ const newStartColumn = Math.min(moveStartColumn, startColumn);
+ const newEndRow = Math.max(moveEndRow, endRow);
+ const newEndColumn = Math.max(moveEndColumn, endColumn);
+ const newBounding = main.getSelectionBounding(newStartRow, newStartColumn, newEndRow, newEndColumn);
+
+ if (!newBounding) {
+ return false;
+ }
+ const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = newBounding;
+
+ const startCell = main.getNoMergeCellPositionByIndex(finalStartRow, finalStartColumn, scaleX, scaleY);
+ const endCell = main.getNoMergeCellPositionByIndex(finalEndRow, finalEndColumn, scaleX, scaleY);
+
+ const newSelectionRange: ISelection = {
+ startColumn: finalStartColumn,
+ startRow: finalStartRow,
+ endColumn: finalEndColumn,
+ endRow: finalEndRow,
+ startY: startCell?.startY || 0,
+ endY: endCell?.endY || 0,
+ startX: startCell?.startX || 0,
+ endX: endCell?.endX || 0,
+ };
+ // Only notify when the selection changes
+ const {
+ startRow: oldStartRow,
+ endRow: oldEndRow,
+ startColumn: oldStartColumn,
+ endColumn: oldEndColumn,
+ } = selectionControl?.model || { startRow: -1, endRow: -1, startColumn: -1, endColumn: -1 };
+
+ if (oldStartColumn !== finalStartColumn || oldStartRow !== finalStartRow || oldEndColumn !== finalEndColumn || oldEndRow !== finalEndRow) {
+ selectionControl && selectionControl.update(newSelectionRange);
+ }
+ }
+
+ private _endSelection() {
+ const scene = this.getScene();
+ if (scene == null) {
+ return;
+ }
+ scene.onPointerMoveObserver.remove(this._moveObserver);
+ scene.onPointerUpObserver.remove(this._upObserver);
+ scene.enableEvent();
+
+ this._scrollTimer?.stopScroll();
+
+ const mainScene = scene.getEngine()?.activeScene;
+ mainScene?.onPointerDownObserver.remove(this._cancelDownObserver);
+ mainScene?.onPointerUpObserver.remove(this._cancelUpObserver);
+ }
+
+ private _addCancelObserver() {
+ const scene = this.getScene();
+ if (scene == null) {
+ return;
+ }
+ const mainScene = scene.getEngine()?.activeScene;
+ if (mainScene == null || mainScene === scene) {
+ return;
+ }
+ mainScene.onPointerDownObserver.remove(this._cancelDownObserver);
+ mainScene.onPointerUpObserver.remove(this._cancelUpObserver);
+ this._cancelDownObserver = mainScene.onPointerDownObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
+ this._endSelection();
+ });
+
+ this._cancelUpObserver = mainScene.onPointerUpObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
+ this._endSelection();
+ });
+ }
+}
+
+export const ISelectionTransformerShapeManager = createIdentifier<SelectionTransformerShapeManager>('deprecated.univer.sheet.selection-transformer-manager');
diff --git a/packages/base-render/src/Component/Sheets/Selection/SelectionControl.ts b/packages/base-render/src/Component/Sheets/Selection/selection-transformer-shape.ts
similarity index 91%
rename from packages/base-render/src/Component/Sheets/Selection/SelectionControl.ts
rename to packages/base-render/src/Component/Sheets/Selection/selection-transformer-shape.ts
index 9f5de63ac1..dc1008a01a 100644
--- a/packages/base-render/src/Component/Sheets/Selection/SelectionControl.ts
+++ b/packages/base-render/src/Component/Sheets/Selection/selection-transformer-shape.ts
@@ -1,9 +1,11 @@
-import { Nullable, ISelection, ICellInfo } from '@univerjs/core';
-import { SelectionModel } from './SelectionModel';
-import { Rect } from '../../../Shape/Rect';
+import { ICellInfo, ISelection, Nullable } from '@univerjs/core';
+
+import { SELECTION_TYPE } from '../../../Basics/Const';
+import { ISelectionDataWithStyle, ISelectionStyle, NORMAL_SELECTION_PLUGIN_STYLE } from '../../../Basics/Selection';
import { Group } from '../../../Group';
import { Scene } from '../../../Scene';
-import { SELECTION_TYPE } from '../../../Basics/Const';
+import { Rect } from '../../../Shape/Rect';
+import { SelectionTransformerModel } from './selection-transformer-model';
// export enum DEFAULT_SELECTION_CONFIG {
// strokeColor = 'rgb(1,136,251)',
@@ -41,7 +43,7 @@ enum SELECTION_MANAGER_KEY {
/**
* The main selection canvas component
*/
-export class SelectionControl {
+export class SelectionTransformerShape {
private _leftControl: Rect;
private _rightControl: Rect;
@@ -62,7 +64,9 @@ export class SelectionControl {
private _selectionShape: Group;
- private _selectionModel: SelectionModel;
+ private _selectionModel: SelectionTransformerModel;
+
+ private _selectionStyle: Nullable<ISelectionStyle>;
constructor(private _scene: Scene, private _zIndex: number) {
this._initialize();
@@ -120,9 +124,10 @@ export class SelectionControl {
return new this(scene, zIndex);
}
- static fromJson(scene: Scene, zIndex: number, newSelectionRange: ISelection) {
- const control = SelectionControl.create(scene, zIndex);
- control.update(newSelectionRange);
+ static fromJson(scene: Scene, zIndex: number, newSelectionData: ISelectionDataWithStyle) {
+ const { selection, cellInfo, style } = newSelectionData;
+ const control = SelectionTransformerShape.create(scene, zIndex);
+ control.update(selection, cellInfo, style);
return control;
}
@@ -131,7 +136,7 @@ export class SelectionControl {
*
* inner update
*/
- _updateControl() {
+ _updateControl(style: Nullable<ISelectionStyle>) {
const { startX, startY, endX, endY } = this._selectionModel;
this.leftControl.resize(undefined, endY - startY);
@@ -152,12 +157,14 @@ export class SelectionControl {
this.selectionShape.show();
this.selectionShape.translate(startX, startY);
+ this._selectionStyle = style;
+
this.selectionShape.makeDirty(true);
}
- update(newSelectionRange: ISelection, highlight: Nullable<ICellInfo>) {
+ update(newSelectionRange: ISelection, highlight: Nullable<ICellInfo>, style: Nullable<ISelectionStyle> = NORMAL_SELECTION_PLUGIN_STYLE) {
this._selectionModel.setValue(newSelectionRange, highlight);
- this._updateControl();
+ this._updateControl(style);
}
clearHighlight() {
@@ -222,8 +229,15 @@ export class SelectionControl {
}
}
+ getValue(): ISelectionDataWithStyle {
+ return {
+ ...this._selectionModel.getValue(),
+ style: this._selectionStyle,
+ };
+ }
+
private _initialize() {
- this._selectionModel = new SelectionModel(SELECTION_TYPE.NORMAL);
+ this._selectionModel = new SelectionTransformerModel(SELECTION_TYPE.NORMAL);
const zIndex = this._zIndex;
this._leftControl = new Rect(SELECTION_MANAGER_KEY.left + zIndex, {
top: 0,
diff --git a/packages/base-render/src/Component/Sheets/SheetComponent.ts b/packages/base-render/src/Component/Sheets/SheetComponent.ts
index b9b3ca22be..9dd519f5a9 100644
--- a/packages/base-render/src/Component/Sheets/SheetComponent.ts
+++ b/packages/base-render/src/Component/Sheets/SheetComponent.ts
@@ -1,9 +1,10 @@
import { ICellInfo, Nullable, searchArray } from '@univerjs/core';
+
+import { RENDER_CLASS_TYPE } from '../../Basics/Const';
import { IBoundRect, Vector2 } from '../../Basics/Vector2';
import { RenderComponent } from '../Component';
-import { SpreadsheetSkeleton } from './SheetSkeleton';
import { SHEET_EXTENSION_TYPE } from './Extensions/SheetExtension';
-import { RENDER_CLASS_TYPE } from '../../Basics/Const';
+import { SpreadsheetSkeleton } from './SheetSkeleton';
export class SheetComponent extends RenderComponent<SpreadsheetSkeleton, SHEET_EXTENSION_TYPE> {
// protected _cacheCanvas = new Canvas();
diff --git a/packages/base-render/src/Component/Sheets/SheetSkeleton.ts b/packages/base-render/src/Component/Sheets/SheetSkeleton.ts
index 553d3061f9..1f86589df2 100644
--- a/packages/base-render/src/Component/Sheets/SheetSkeleton.ts
+++ b/packages/base-render/src/Component/Sheets/SheetSkeleton.ts
@@ -1,42 +1,43 @@
import {
BooleanNumber,
+ DocumentModelSimple,
+ getColorStyle,
HorizontalAlign,
IBorderStyleData,
ICellData,
+ ICellInfo,
+ IColumnData,
IDocumentData,
+ IDocumentRenderConfig,
IPaddingData,
IRangeData,
+ IRowData,
+ isEmptyCell,
IStyleBase,
IStyleData,
ITextRotation,
ITextStyle,
- ObjectArray,
+ IWorksheetConfig,
+ LocaleService,
+ Nullable,
+ ObjectArrayType,
ObjectMatrix,
+ searchArray,
Styles,
TextDirection,
TextDirectionType,
+ Tools,
VerticalAlign,
WrapStrategy,
- IRowData,
- IColumnData,
- ObjectArrayType,
- IWorksheetConfig,
- searchArray,
- isEmptyCell,
- Nullable,
- getColorStyle,
- IDocumentRenderConfig,
- DocumentModelSimple,
- Tools,
- LocaleService,
} from '@univerjs/core';
+
import { BORDER_TYPE, COLOR_BLACK_RGB } from '../../Basics/Const';
-import { IStylesCache, BorderCache } from './Interfaces';
-import { getFontStyleString, getCellPositionByIndex, isRectIntersect } from '../../Basics/Tools';
import { IFontLocale } from '../../Basics/Interfaces';
+import { fixLineWidthByScale, getCellByIndex, getCellPositionByIndex, getFontStyleString, isRectIntersect, mergeInfoOffset } from '../../Basics/Tools';
import { IBoundRect } from '../../Basics/Vector2';
-import { Skeleton } from '../Skeleton';
import { DocumentSkeleton } from '../Docs/DocSkeleton';
+import { Skeleton } from '../Skeleton';
+import { BorderCache, IStylesCache } from './Interfaces';
interface ISetCellCache {
cache: IStylesCache;
@@ -94,9 +95,9 @@ export class SpreadsheetSkeleton extends Skeleton {
private _rowColumnSegment: IRowColumnSegment;
- private _dataMergeCache: ObjectMatrix<IRangeData>;
+ private _dataMergeCache: IRangeData[];
- private _dataMergeCacheAll: ObjectMatrix<IRangeData>;
+ // private _dataMergeCacheAll: ObjectMatrix<IRangeData>;
private _overflowCache: ObjectMatrix<IRangeData>;
@@ -108,7 +109,7 @@ export class SpreadsheetSkeleton extends Skeleton {
super(_localeService);
this.updateLayout();
- this.updateDataMerge();
+ // this.updateDataMerge();
}
get rowHeightAccumulation() {
@@ -155,10 +156,14 @@ export class SpreadsheetSkeleton extends Skeleton {
return this._showGridlines;
}
- get dataMergeCacheAll() {
- return this._dataMergeCacheAll;
+ get mergeData() {
+ return this._config.mergeData;
}
+ // get dataMergeCacheAll() {
+ // return this._dataMergeCacheAll;
+ // }
+
static create(config: IWorksheetConfig, cellData: ObjectMatrix<ICellData>, styles: Styles, LocaleService: LocaleService) {
return new SpreadsheetSkeleton(config, cellData, styles, LocaleService);
}
@@ -221,18 +226,19 @@ export class SpreadsheetSkeleton extends Skeleton {
return this;
}
- updateDataMerge() {
- const { mergeData } = this._config;
- this._dataMergeCacheAll = mergeData && this._getMergeCells(mergeData);
- }
+ // updateDataMerge() {
+ // const { mergeData } = this._config;
+ // this._dataMergeCacheAll = mergeData && this._getMergeCells(mergeData);
+ // }
getRowColumnSegment(bounds?: IBoundRect) {
return this._getBounding(this._rowHeightAccumulation, this._columnWidthAccumulation, bounds);
}
+ // eslint-disable-next-line max-lines-per-function
getMergeBounding(startRow: number, startColumn: number, endRow: number, endColumn: number) {
- const dataMergeCache = this._dataMergeCacheAll;
- if (!dataMergeCache) {
+ const mergeData = this._config.mergeData;
+ if (!mergeData) {
return {
startRow,
startColumn,
@@ -242,39 +248,72 @@ export class SpreadsheetSkeleton extends Skeleton {
}
let isSearching = true;
const searchedMarge = new ObjectMatrix<boolean>();
+ // const dataMergeCache = this._getMergeCells(mergeData);
while (isSearching) {
isSearching = false;
- 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;
- }
- });
- });
+
+ for (let i = 0; i < mergeData.length; i++) {
+ const { startRow: mainStartRow, startColumn: mainStartColumn, endRow: mainEndRow, endColumn: mainEndColumn } = mergeData[i];
+
+ if (searchedMarge.getValue(mainStartRow, mainStartColumn)) {
+ continue;
+ }
+
+ 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(mainStartRow, mainStartColumn, true);
+ 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 {
@@ -325,6 +364,161 @@ 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);
+
+ startY = fixLineWidthByScale(startY + columnTitleHeight, scaleY);
+ endY = fixLineWidthByScale(endY + columnTitleHeight, scaleY);
+ startX = fixLineWidthByScale(startX + rowTitleWidth, scaleX);
+ endX = fixLineWidthByScale(endX + rowTitleWidth, scaleX);
+
+ return {
+ startY,
+ endY,
+ startX,
+ endX,
+ };
+ }
+
+ 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)
+ const { rowHeightAccumulation, columnWidthAccumulation, rowTitleWidth, columnTitleHeight } = this;
+
+ // so we should map physical positions to ideal positions
+ offsetX = offsetX / scaleX + scrollX - rowTitleWidth;
+ offsetY = offsetY / scaleY + scrollY - columnTitleHeight;
+
+ let row = searchArray(rowHeightAccumulation, offsetY);
+ let column = searchArray(columnWidthAccumulation, offsetX);
+
+ if (row === -1) {
+ const rowLength = rowHeightAccumulation.length - 1;
+ const lastRowValue = rowHeightAccumulation[rowLength];
+ if (lastRowValue <= offsetY) {
+ row = rowHeightAccumulation.length - 1;
+ } else {
+ row = 0;
+ }
+ }
+
+ if (column === -1) {
+ const columnLength = columnWidthAccumulation.length - 1;
+ const lastColumnValue = columnWidthAccumulation[columnLength];
+ if (lastColumnValue <= offsetX) {
+ column = columnWidthAccumulation.length - 1;
+ } else {
+ column = 0;
+ }
+ }
+
+ const cellInfo = getCellByIndex(row, column, rowHeightAccumulation, columnWidthAccumulation, this._config.mergeData);
+ const { isMerged, isMergedMainCell } = cellInfo;
+ let { startY, endY, startX, endX, mergeInfo } = cellInfo;
+
+ startY = fixLineWidthByScale(startY + columnTitleHeight, scaleY);
+ endY = fixLineWidthByScale(endY + columnTitleHeight, scaleY);
+ startX = fixLineWidthByScale(startX + rowTitleWidth, scaleX);
+ endX = fixLineWidthByScale(endX + rowTitleWidth, scaleX);
+
+ mergeInfo = mergeInfoOffset(mergeInfo, rowTitleWidth, columnTitleHeight, scaleX, scaleY);
+
+ // let endRow = row;
+ // let endColumn = column;
+ // if (isMerged && mergeInfo) {
+ // endRow = mergeInfo.endRow;
+ // endColumn = mergeInfo.endColumn;
+ // }
+
+ return {
+ row,
+ column,
+ startY,
+ endY,
+ startX,
+ endX,
+ isMerged,
+ isMergedMainCell,
+ mergeInfo,
+ };
+ }
+
+ 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 { isMerged, isMergedMainCell } = cellInfo;
+ let { startY, endY, startX, endX, mergeInfo } = cellInfo;
+
+ startY = fixLineWidthByScale(startY + columnTitleHeight, scaleY);
+ endY = fixLineWidthByScale(endY + columnTitleHeight, scaleY);
+ startX = fixLineWidthByScale(startX + rowTitleWidth, scaleX);
+ endX = fixLineWidthByScale(endX + rowTitleWidth, scaleX);
+
+ mergeInfo = mergeInfoOffset(mergeInfo, rowTitleWidth, columnTitleHeight, scaleX, scaleY);
+
+ return {
+ row,
+ column,
+ startY,
+ endY,
+ startX,
+ endX,
+ isMerged,
+ isMergedMainCell,
+ mergeInfo,
+ };
+ }
+
+ // getScrollXYByRelativeCoords(coord: Vector2) {
+ // const scene = this.getParent() as Scene;
+ // let x = 0;
+ // let y = 0;
+ // const viewPort = scene.getActiveViewportByRelativeCoord(coord);
+ // if (viewPort) {
+ // const actualX = viewPort.actualScrollX || 0;
+ // const actualY = viewPort.actualScrollY || 0;
+ // x += actualX;
+ // y += actualY;
+ // }
+ // return {
+ // x,
+ // y,
+ // };
+ // }
+
+ // getAncestorScrollXY(offsetX: number, offsetY: number) {
+ // let parent: any = this.getParent();
+
+ // let x = 0;
+ // let y = 0;
+ // const coord = Vector2.FromArray([offsetX, offsetY]);
+ // while (parent) {
+ // if (parent.classType === RENDER_CLASS_TYPE.SCENE) {
+ // const scene = parent as Scene;
+ // const viewPort = scene.getActiveViewportByCoord(coord);
+ // if (viewPort) {
+ // const actualX = viewPort.actualScrollX || 0;
+ // const actualY = viewPort.actualScrollY || 0;
+ // x += actualX;
+ // y += actualY;
+ // }
+ // }
+ // parent = parent?.getParent && parent?.getParent();
+ // }
+ // return {
+ // x,
+ // y,
+ // };
+ // }
+
+ getSelectionBounding(startRow: number, startColumn: number, endRow: number, endColumn: number) {
+ return this.getMergeBounding(startRow, startColumn, endRow, endColumn);
+ }
+
/**
*
* @param rowHeightAccumulation Row layout information
@@ -555,15 +749,18 @@ export class SpreadsheetSkeleton extends Skeleton {
private _intersectMergeRange(row: number, column: number) {
const dataMergeCache = this.dataMergeCache;
let isIntersected = false;
- dataMergeCache?.forEach((r, dataMergeRow) => {
- dataMergeRow?.forEach((c, dataCache) => {
- const { startRow: startRowMargeIndex, endRow: endRowMargeIndex, startColumn: startColumnMargeIndex, endColumn: endColumnMargeIndex } = dataCache;
- if (row >= startRowMargeIndex && row <= endRowMargeIndex && column >= startColumnMargeIndex && column <= endColumnMargeIndex) {
- isIntersected = true;
- return 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) {
+ isIntersected = true;
+ return false;
+ }
+ }
+ // dataMergeCache?.forEach((r, dataMergeRow) => {
+ // dataMergeRow?.forEach((c, dataCache) => {
+
+ // });
+ // });
return isIntersected;
}
@@ -645,26 +842,40 @@ export class SpreadsheetSkeleton extends Skeleton {
}
}
- dataMergeCache &&
- dataMergeCache.forEach((rowIndex: number, row: ObjectArray<IRangeData>) => {
- row.forEach((columnIndex: number, mainCell: IRangeData) => {
- if (!mainCell) {
- return true;
- }
+ for (const data of dataMergeCache) {
+ this.__setCellCache(
+ data.startRow,
+ data.startColumn,
+ {
+ cache,
+ styles,
+ cellData,
+ skipBackgroundAndBorder: false,
+ },
+ fontLocale
+ );
+ }
- this.__setCellCache(
- rowIndex,
- columnIndex,
- {
- cache,
- styles,
- cellData,
- skipBackgroundAndBorder: false,
- },
- fontLocale
- );
- });
- });
+ // dataMergeCache &&
+ // dataMergeCache.forEach((rowIndex: number, row: ObjectArray<IRangeData>) => {
+ // row.forEach((columnIndex: number, mainCell: IRangeData) => {
+ // if (!mainCell) {
+ // return true;
+ // }
+
+ // this.__setCellCache(
+ // rowIndex,
+ // columnIndex,
+ // {
+ // cache,
+ // styles,
+ // cellData,
+ // skipBackgroundAndBorder: false,
+ // },
+ // fontLocale
+ // );
+ // });
+ // });
return cache;
}
@@ -939,14 +1150,14 @@ export class SpreadsheetSkeleton extends Skeleton {
rowColumnSegment = { startRow: rowColumnSegment.startRow, endRow: rowColumnSegment.endRow, endColumn: endColumnLast, startColumn: 0 };
}
const { startRow, startColumn, endRow, endColumn } = rowColumnSegment;
- const cacheDataMerge = new ObjectMatrix<IRangeData>();
+ const cacheDataMerge: IRangeData[] = [];
for (let i = 0; i < mergeData.length; 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++) {
if (r >= mergeStartRow && r <= mergeEndRow && c >= mergeStartColumn && c <= mergeEndColumn) {
- cacheDataMerge.setValue(mergeStartRow, mergeStartColumn, {
+ cacheDataMerge.push({
startRow: mergeStartRow,
endRow: mergeEndRow,
startColumn: mergeStartColumn,
diff --git a/packages/base-render/src/Component/Sheets/Spreadsheet.ts b/packages/base-render/src/Component/Sheets/Spreadsheet.ts
index d5abba10ab..96ab005f46 100644
--- a/packages/base-render/src/Component/Sheets/Spreadsheet.ts
+++ b/packages/base-render/src/Component/Sheets/Spreadsheet.ts
@@ -1,27 +1,27 @@
-import { CellValueType, HorizontalAlign, ICellInfo, IRangeData, Nullable, ObjectMatrix, searchArray, WrapStrategy, sortRules } from '@univerjs/core';
-import { Background } from './Extensions/Background';
-import { Border } from './Extensions/Border';
-import { Font } from './Extensions/Font';
-import { BorderAuxiliary } from './Extensions/BorderAuxiliary';
+import { CellValueType, HorizontalAlign, ICellInfo, IRangeData, Nullable, ObjectMatrix, searchArray, sortRules, WrapStrategy } from '@univerjs/core';
+
+import { BaseObject } from '../../BaseObject';
+import { ORIENTATION_TYPE, RENDER_CLASS_TYPE } from '../../Basics/Const';
+import { getRotateOffsetAndFarthestHypotenuse, getRotateOrientation } from '../../Basics/Draw';
+import { IDocumentSkeletonColumn } from '../../Basics/IDocumentSkeletonCached';
+import { ITransformChangeState } from '../../Basics/Interfaces';
+import { fixLineWidthByScale, getCellByIndex, getCellPositionByIndex, getScale, mergeInfoOffset } from '../../Basics/Tools';
import { IBoundRect, Vector2 } from '../../Basics/Vector2';
-import { SpreadsheetSkeleton } from './SheetSkeleton';
-import { SheetComponent } from './SheetComponent';
-import { SpreadsheetExtensionRegistry } from '../Extension';
import { Canvas } from '../../Canvas';
import { Engine } from '../../Engine';
import { Scene } from '../../Scene';
import { SceneViewer } from '../../SceneViewer';
import { Viewport } from '../../Viewport';
-import { fixLineWidthByScale, getCellByIndex, getCellPositionByIndex, getScale, mergeInfoOffset } from '../../Basics/Tools';
-import { ITransformChangeState } from '../../Basics/Interfaces';
-import { BaseObject } from '../../BaseObject';
-import { Documents } from '../Docs/Document';
-import { ORIENTATION_TYPE, RENDER_CLASS_TYPE } from '../../Basics/Const';
import { columnIterator } from '../Docs/Common/Tools';
import { DocumentSkeleton } from '../Docs/DocSkeleton';
-import { IDocumentSkeletonColumn } from '../../Basics/IDocumentSkeletonCached';
-import { getRotateOffsetAndFarthestHypotenuse, getRotateOrientation } from '../../Basics/Draw';
-import { SelectionManager } from './Selection/SelectionManager';
+import { Documents } from '../Docs/Document';
+import { SpreadsheetExtensionRegistry } from '../Extension';
+import { Background } from './Extensions/Background';
+import { Border } from './Extensions/Border';
+import { BorderAuxiliary } from './Extensions/BorderAuxiliary';
+import { Font } from './Extensions/Font';
+import { SheetComponent } from './SheetComponent';
+import { SpreadsheetSkeleton } from './SheetSkeleton';
const OBJECT_KEY = '__SHEET_EXTENSION_FONT_DOCUMENT_INSTANCE__';
@@ -44,8 +44,6 @@ export class Spreadsheet extends SheetComponent {
private _hasSelection = false;
- private _selection: SelectionManager;
-
private _documents: Documents = new Documents(OBJECT_KEY, undefined, {
pageMarginLeft: 0,
pageMarginTop: 0,
@@ -163,7 +161,7 @@ export class Spreadsheet extends SheetComponent {
const { x: scrollX, y: scrollY } = scrollXY;
// these values are not affected by zooming (ideal positions)
- const { rowHeightAccumulation, columnWidthAccumulation, rowTitleWidth, columnTitleHeight, dataMergeCacheAll } = spreadsheetSkeleton;
+ const { rowHeightAccumulation, columnWidthAccumulation, rowTitleWidth, columnTitleHeight, mergeData } = spreadsheetSkeleton;
// so we should map physical positions to ideal positions
offsetX = offsetX / scaleX + scrollX - rowTitleWidth;
@@ -192,7 +190,7 @@ export class Spreadsheet extends SheetComponent {
}
}
- const cellInfo = getCellByIndex(row, column, rowHeightAccumulation, columnWidthAccumulation, dataMergeCacheAll);
+ const cellInfo = getCellByIndex(row, column, rowHeightAccumulation, columnWidthAccumulation, mergeData);
const { isMerged, isMergedMainCell } = cellInfo;
let { startY, endY, startX, endX, mergeInfo } = cellInfo;
@@ -229,9 +227,9 @@ export class Spreadsheet extends SheetComponent {
return;
}
const { scaleX = 1, scaleY = 1 } = this.getParentScale();
- const { rowHeightAccumulation, columnWidthAccumulation, rowTitleWidth, columnTitleHeight, dataMergeCacheAll } = spreadsheetSkeleton;
+ const { rowHeightAccumulation, columnWidthAccumulation, rowTitleWidth, columnTitleHeight, mergeData } = spreadsheetSkeleton;
- const cellInfo = getCellByIndex(row, column, rowHeightAccumulation, columnWidthAccumulation, dataMergeCacheAll);
+ const cellInfo = getCellByIndex(row, column, rowHeightAccumulation, columnWidthAccumulation, mergeData);
const { isMerged, isMergedMainCell } = cellInfo;
let { startY, endY, startX, endX, mergeInfo } = cellInfo;
@@ -364,18 +362,18 @@ export class Spreadsheet extends SheetComponent {
this.makeDirty(true);
}
- enableSelection() {
- if (this._hasSelection) {
- return;
- }
- this._selection = SelectionManager.create(this);
- this._hasSelection = true;
- }
+ // enableSelection() {
+ // if (this._hasSelection) {
+ // return;
+ // }
+ // this._selection = SelectionManager.create(this);
+ // this._hasSelection = true;
+ // }
- disableSelection() {
- this._selection?.dispose();
- this._hasSelection = false;
- }
+ // disableSelection() {
+ // this._selection?.dispose();
+ // this._hasSelection = false;
+ // }
getDocsSkeletonPageSize(documentSkeleton: DocumentSkeleton, angle: number = 0) {
const skeletonData = documentSkeleton?.getSkeletonData();
@@ -580,7 +578,7 @@ export class Spreadsheet extends SheetComponent {
return;
}
const columnCount = spreadsheetSkeleton.getColumnCount();
- const { stylesCache, rowHeightAccumulation, columnWidthAccumulation, dataMergeCache } = spreadsheetSkeleton;
+ const { stylesCache, rowHeightAccumulation, columnWidthAccumulation, dataMergeCache, mergeData } = spreadsheetSkeleton;
const { font: fontList } = stylesCache;
fontList &&
Object.keys(fontList).forEach((fontFormat: string) => {
@@ -611,7 +609,7 @@ export class Spreadsheet extends SheetComponent {
}
if (angle !== 0) {
- const { startY, endY, startX, endX } = getCellByIndex(row, column, rowHeightAccumulation, columnWidthAccumulation, dataMergeCache);
+ const { startY, endY, startX, endX } = getCellByIndex(row, column, rowHeightAccumulation, columnWidthAccumulation, mergeData);
const cellWidth = endX - startX;
const cellHeight = endY - startY;
@@ -639,7 +637,7 @@ export class Spreadsheet extends SheetComponent {
endColumn,
});
} else if (wrapStrategy === WrapStrategy.WRAP && angle !== 0) {
- const { startY, endY } = getCellByIndex(row, column, rowHeightAccumulation, columnWidthAccumulation, dataMergeCache);
+ const { startY, endY } = getCellByIndex(row, column, rowHeightAccumulation, columnWidthAccumulation, mergeData);
const cellHeight = endY - startY;
documentSkeleton.getModel().updateDocumentDataPageSize(cellHeight);
diff --git a/packages/base-render/src/Component/Sheets/index.ts b/packages/base-render/src/Component/Sheets/index.ts
index b7a2429c2d..e7b9149492 100644
--- a/packages/base-render/src/Component/Sheets/index.ts
+++ b/packages/base-render/src/Component/Sheets/index.ts
@@ -1,7 +1,10 @@
-export * from './Interfaces';
-export * from './SheetComponent';
+export * from './ColumnTitle';
export * from './Extensions';
-export * from './Spreadsheet';
+export * from './Interfaces';
export * from './RowTitle';
-export * from './ColumnTitle';
+export * from './Selection/selection-transformer-model';
+export * from './Selection/selection-transformer-shape';
+export * from './Selection/selection-transformer-shape-manager';
+export * from './SheetComponent';
export * from './SheetSkeleton';
+export * from './Spreadsheet';
diff --git a/packages/base-render/src/Component/Skeleton.ts b/packages/base-render/src/Component/Skeleton.ts
index f5c063fc3e..5af637bdbb 100644
--- a/packages/base-render/src/Component/Skeleton.ts
+++ b/packages/base-render/src/Component/Skeleton.ts
@@ -1,7 +1,8 @@
import { LocaleService } from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
-import { en, zh } from '../Locale';
+
import { IFontLocale } from '../Basics/Interfaces';
+import { en, zh } from '../Locale';
export class Skeleton {
private _fontLocale: IFontLocale;
diff --git a/packages/base-render/src/Scene.ts b/packages/base-render/src/Scene.ts
index 099f53b999..801e966aa4 100644
--- a/packages/base-render/src/Scene.ts
+++ b/packages/base-render/src/Scene.ts
@@ -1,30 +1,19 @@
-import { sortRules, sortRulesByDesc, Nullable, IKeyValue } from '@univerjs/core';
-import { IKeyboardEvent, IMouseEvent, IPointerEvent, IWheelEvent } from './Basics/IEvents';
-
-import { requestNewFrame, precisionTo } from './Basics/Tools';
-
-import { IBoundRect, Vector2 } from './Basics/Vector2';
+import { IKeyValue, Nullable, sortRules, sortRulesByDesc } from '@univerjs/core';
+import { BaseObject } from './BaseObject';
import { CURSOR_TYPE, RENDER_CLASS_TYPE } from './Basics/Const';
-
+import { IKeyboardEvent, IMouseEvent, IPointerEvent, IWheelEvent } from './Basics/IEvents';
import { IObjectFullState, ISceneTransformState, ITransformChangeState, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from './Basics/Interfaces';
-
+import { precisionTo, requestNewFrame } from './Basics/Tools';
import { Transform } from './Basics/Transform';
-
-import { ThinEngine } from './ThinEngine';
-
-import { BaseObject } from './BaseObject';
-
-import { Viewport } from './Viewport';
-
+import { IBoundRect, Vector2 } from './Basics/Vector2';
import { Layer } from './Layer';
-
+import { InputManager } from './Scene.inputManager';
+import { ITransformerConfig, Transformer } from './Scene.Transformer';
import { SceneViewer } from './SceneViewer';
-
-import { Transformer, ITransformerConfig } from './Scene.Transformer';
-
+import { ThinEngine } from './ThinEngine';
import { ThinScene } from './ThinScene';
-import { InputManager } from './Scene.inputManager';
+import { Viewport } from './Viewport';
export class Scene extends ThinScene {
private _layers: Layer[] = [];
@@ -272,7 +261,7 @@ export class Scene extends ThinScene {
}
getLayer(zIndex: number = 1) {
- for (let layer of this._layers) {
+ for (const layer of this._layers) {
if (layer.zIndex === zIndex) {
return layer;
}
@@ -340,7 +329,7 @@ export class Scene extends ThinScene {
return;
}
const layers = this.getLayers();
- for (let layer of layers) {
+ for (const layer of layers) {
layer.removeObject(object);
}
return this;
@@ -351,7 +340,7 @@ export class Scene extends ThinScene {
return;
}
const layers = this.getLayers();
- for (let layer of layers) {
+ for (const layer of layers) {
layer.removeObjects(objects);
}
return this;
@@ -374,7 +363,7 @@ export class Scene extends ThinScene {
getAllObjects() {
const objects: BaseObject[] = [];
this._layers.sort(sortRules);
- for (let layer of this._layers) {
+ for (const layer of this._layers) {
objects.push(...layer.getObjectsByOrder());
}
return objects;
@@ -384,7 +373,7 @@ export class Scene extends ThinScene {
const objects: BaseObject[] = [];
const useSortRules = isDesc ? sortRulesByDesc : sortRules;
this._layers.sort(useSortRules);
- for (let layer of this._layers) {
+ for (const layer of this._layers) {
objects.push(...layer.getObjectsByOrder().sort(useSortRules));
}
return objects;
@@ -394,16 +383,16 @@ export class Scene extends ThinScene {
const objects: BaseObject[] = [];
const useSortRules = isDesc ? sortRulesByDesc : sortRules;
this._layers.sort(useSortRules);
- for (let layer of this._layers) {
+ for (const layer of this._layers) {
objects.push(...layer.getObjectsByOrderForPick().sort(useSortRules));
}
return objects;
}
override getObject(oKey: string) {
- for (let layer of this._layers) {
+ for (const layer of this._layers) {
const objects = layer.getObjectsByOrder();
- for (let object of objects) {
+ for (const object of objects) {
if (object.oKey === oKey) {
return object;
}
@@ -413,9 +402,9 @@ export class Scene extends ThinScene {
fuzzyMathObjects(oKey: string) {
const objects: BaseObject[] = [];
- for (let layer of this._layers) {
+ for (const layer of this._layers) {
const objects = layer.getObjectsByOrder();
- for (let object of objects) {
+ for (const object of objects) {
if (object.oKey.indexOf(oKey) > -1) {
objects.push(object);
}
@@ -437,7 +426,7 @@ export class Scene extends ThinScene {
}
getViewport(key: string) {
- for (let viewport of this._viewports) {
+ for (const viewport of this._viewports) {
if (viewport.viewPortKey === key) {
return viewport;
}
@@ -515,6 +504,22 @@ export class Scene extends ThinScene {
return this.getActiveViewportByRelativeCoord(coord);
}
+ getScrollXYByRelativeCoords(coord: Vector2) {
+ let x = 0;
+ let y = 0;
+ const viewPort = this.getActiveViewportByRelativeCoord(coord);
+ if (viewPort) {
+ const actualX = viewPort.actualScrollX || 0;
+ const actualY = viewPort.actualScrollY || 0;
+ x += actualX;
+ y += actualY;
+ }
+ return {
+ x,
+ y,
+ };
+ }
+
getRelativeCoord(coord: Vector2) {
let parent: any = this.getParent();
@@ -529,7 +534,7 @@ export class Scene extends ThinScene {
parentList.reverse();
- for (let parent of parentList) {
+ for (const parent of parentList) {
if (parent.classType === RENDER_CLASS_TYPE.SCENE) {
const scene = parent as Scene;
const viewPort = scene.getActiveViewportByCoord(coord);
@@ -561,6 +566,20 @@ export class Scene extends ThinScene {
this._viewports = [];
}
+ getAncestorScale() {
+ let { scaleX = 1, scaleY = 1 } = this;
+
+ if (this.classType === RENDER_CLASS_TYPE.SCENE_VIEWER) {
+ scaleX = this.ancestorScaleX || 1;
+ scaleY = this.ancestorScaleY || 1;
+ }
+
+ return {
+ scaleX,
+ scaleY,
+ };
+ }
+
override dispose() {
this.getLayers().forEach((layer) => {
layer.dispose();
diff --git a/packages/base-sheets/src/Basics/Observer.ts b/packages/base-sheets/src/Basics/Observer.ts
index 8fb467dc84..13a760104d 100644
--- a/packages/base-sheets/src/Basics/Observer.ts
+++ b/packages/base-sheets/src/Basics/Observer.ts
@@ -1,5 +1,4 @@
-import { Observable, Plugin } from '@univerjs/core';
-import { SelectionController } from '../Controller/Selection/SelectionController';
+import { ISelectionRange, Observable, Plugin } from '@univerjs/core';
interface ISelectionControlFillConfig {
//TODO ...
@@ -31,7 +30,7 @@ export type SheetPluginObserve = {
onFillEndObserver: Observable<ISelectionControlFillConfig>;
- onChangeSelectionObserver: Observable<SelectionController>;
+ onChangeSelectionObserver: Observable<ISelectionRange>;
onChangeCurrentSheetObserver: Observable<string>;
diff --git a/packages/base-sheets/src/Commands/Commands/add-worksheet-merge.command.ts b/packages/base-sheets/src/Commands/Commands/add-worksheet-merge.command.ts
index e708874f69..c088857c8a 100644
--- a/packages/base-sheets/src/Commands/Commands/add-worksheet-merge.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/add-worksheet-merge.command.ts
@@ -1,8 +1,8 @@
-import { CommandType, Dimension, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService } from '@univerjs/core';
+import { CommandType, Dimension, ICommand, ICommandService, ICurrentUniverService, IRangeData, IUndoRedoService } from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
import { IAddWorksheetMergeMutationParams, IRemoveWorksheetMergeMutationParams } from '../../Basics/Interfaces/MutationInterface';
-import { ISelectionManager } from '../../Services/tokens';
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { AddWorksheetMergeMutation, AddWorksheetMergeMutationFactory } from '../Mutations/add-worksheet-merge.mutation';
import { RemoveWorksheetMergeMutation, RemoveWorksheetMergeMutationFactory } from '../Mutations/remove-worksheet-merge.mutation';
@@ -13,13 +13,14 @@ interface addMergeCommandParams {
export const AddWorksheetMergeCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.add-worksheet-merge',
+ // eslint-disable-next-line max-lines-per-function
handler: async (accessor: IAccessor, params?: addMergeCommandParams) => {
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selections = selectionManager.getCurrentSelections();
- if (!selections.length) return false;
+ const selections = selectionManagerService.getRangeDatas();
+ if (!selections?.length) return false;
const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
const workbook = currentUniverService.getUniverSheetInstance(workbookId)?.getWorkBook();
@@ -29,7 +30,7 @@ export const AddWorksheetMergeCommand: ICommand = {
let ranges = selections;
if (params && params.value != null) {
- const rectangles = [];
+ const rectangles: IRangeData[] = [];
for (let i = 0; i < ranges.length; i++) {
const { startRow, endRow, startColumn, endColumn } = ranges[i];
if (params.value === Dimension.ROWS) {
diff --git a/packages/base-sheets/src/Commands/Commands/clear-selection-content.command.ts b/packages/base-sheets/src/Commands/Commands/clear-selection-content.command.ts
index 881ab514c6..a30d0f6d54 100644
--- a/packages/base-sheets/src/Commands/Commands/clear-selection-content.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/clear-selection-content.command.ts
@@ -1,7 +1,7 @@
import { CommandType, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService } from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
-import { ISelectionManager } from '../../Services/tokens';
+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';
@@ -14,13 +14,13 @@ export const ClearSelectionContentCommand: ICommand = {
handler: async (accessor: IAccessor) => {
const currentUniverService = accessor.get(ICurrentUniverService);
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const undoRedoService = accessor.get(IUndoRedoService);
const workbook = currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
const worksheet = workbook.getActiveSheet();
- const selections = selectionManager.getCurrentSelections();
- if (!selections.length) {
+ const selections = selectionManagerService.getRangeDatas();
+ if (!selections?.length) {
return false;
}
diff --git a/packages/base-sheets/src/Commands/Commands/copy-format-to-range.command.ts b/packages/base-sheets/src/Commands/Commands/copy-format-to-range.command.ts
index 4ae3239b40..ad284533ae 100644
--- a/packages/base-sheets/src/Commands/Commands/copy-format-to-range.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/copy-format-to-range.command.ts
@@ -12,8 +12,9 @@ import {
ObjectMatrix,
} from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
+
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { ISetRangeStyleMutationParams, SetRangeStyleMutation, SetRangeStyleUndoMutationFactory } from '../Mutations/set-range-styles.mutation';
-import { ISelectionManager } from '../../Services/tokens';
export interface ICopyFormatToRangeCommandParams {
destinationRange: IRangeData;
@@ -23,13 +24,13 @@ export const CopyFormatToRangeCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.copy-format-to-range',
handler: async (accessor: IAccessor, params: ICopyFormatToRangeCommandParams) => {
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selections = selectionManager.getCurrentSelections();
- if (!selections.length) return false;
+ const selections = selectionManagerService.getRangeDatas();
+ if (!selections?.length) return false;
const originRange = selections[0];
const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
diff --git a/packages/base-sheets/src/Commands/Commands/copy-range-to.command.ts b/packages/base-sheets/src/Commands/Commands/copy-range-to.command.ts
index e8247a7dbf..de677e28a2 100644
--- a/packages/base-sheets/src/Commands/Commands/copy-range-to.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/copy-range-to.command.ts
@@ -12,8 +12,9 @@ import {
ObjectMatrix,
} from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
+
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { ISetRangeValuesMutationParams, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../Mutations/set-range-values.mutation';
-import { ISelectionManager } from '../../Services/tokens';
export interface ICopyRangeToCommandParams {
destinationRange: IRangeData;
@@ -24,13 +25,13 @@ export const CopyRangeToCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.copy-range-to',
handler: async (accessor: IAccessor, params: ICopyRangeToCommandParams) => {
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selections = selectionManager.getCurrentSelections();
- if (!selections.length) return false;
+ const selections = selectionManagerService.getRangeDatas();
+ if (!selections?.length) return false;
const originRange = selections[0];
const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
diff --git a/packages/base-sheets/src/Commands/Commands/copy-values-to-range.command.ts b/packages/base-sheets/src/Commands/Commands/copy-values-to-range.command.ts
index 68b09a09ce..1e76f2647c 100644
--- a/packages/base-sheets/src/Commands/Commands/copy-values-to-range.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/copy-values-to-range.command.ts
@@ -12,8 +12,9 @@ import {
ObjectMatrix,
} from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
+
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { ISetRangeFormattedValueMutationParams, SetRangeFormattedValueMutation, SetRangeFormattedValueUndoMutationFactory } from '../Mutations/set-range-formatted-value.mutation';
-import { ISelectionManager } from '../../Services/tokens';
export interface ICopyValuesToRangeCommandParams {
destinationRange: IRangeData;
@@ -23,13 +24,13 @@ export const CopyValuesToRangeCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.copy-values-to-range',
handler: async (accessor: IAccessor, params: ICopyValuesToRangeCommandParams) => {
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selections = selectionManager.getCurrentSelections();
- if (!selections.length) return false;
+ const selections = selectionManagerService.getRangeDatas();
+ if (!selections?.length) return false;
const originRange = selections[0];
const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
diff --git a/packages/base-sheets/src/Commands/Commands/delete-range-move-left.command.ts b/packages/base-sheets/src/Commands/Commands/delete-range-move-left.command.ts
index 9d7409b000..3e487817b1 100644
--- a/packages/base-sheets/src/Commands/Commands/delete-range-move-left.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/delete-range-move-left.command.ts
@@ -2,7 +2,7 @@ import { CommandType, Dimension, ICommand, ICommandService, ICurrentUniverServic
import { IAccessor } from '@wendellhu/redi';
import { IDeleteRangeMutationParams, IInsertRangeMutationParams } from '../../Basics/Interfaces/MutationInterface';
-import { ISelectionManager } from '../../Services/tokens';
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { DeleteRangeMutation, DeleteRangeUndoMutationFactory } from '../Mutations/delete-range.mutation';
import { InsertRangeMutation } from '../Mutations/insert-range.mutation';
@@ -17,12 +17,12 @@ export const DeleteRangeMoveLeftCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
- const range = selectionManager.getCurrentSelections();
- if (!range.length) return false;
+ const range = selectionManagerService.getRangeDatas();
+ if (!range?.length) return false;
const workbook = currentUniverService.getUniverSheetInstance(workbookId)?.getWorkBook();
if (!workbook) return false;
diff --git a/packages/base-sheets/src/Commands/Commands/delete-range-move-up.command.ts b/packages/base-sheets/src/Commands/Commands/delete-range-move-up.command.ts
index 89a2225a9b..42be253e97 100644
--- a/packages/base-sheets/src/Commands/Commands/delete-range-move-up.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/delete-range-move-up.command.ts
@@ -2,7 +2,7 @@ import { CommandType, Dimension, ICommand, ICommandService, ICurrentUniverServic
import { IAccessor } from '@wendellhu/redi';
import { IDeleteRangeMutationParams, IInsertRangeMutationParams } from '../../Basics/Interfaces/MutationInterface';
-import { ISelectionManager } from '../../Services/tokens';
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { DeleteRangeMutation, DeleteRangeUndoMutationFactory } from '../Mutations/delete-range.mutation';
import { InsertRangeMutation } from '../Mutations/insert-range.mutation';
@@ -17,12 +17,12 @@ export const DeleteRangeMoveUpCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
- const range = selectionManager.getCurrentSelections();
- if (!range.length) return false;
+ const range = selectionManagerService.getRangeDatas();
+ if (!range?.length) return false;
const workbook = currentUniverService.getUniverSheetInstance(workbookId)?.getWorkBook();
if (!workbook) return false;
diff --git a/packages/base-sheets/src/Commands/Commands/insert-range-move-down.command.ts b/packages/base-sheets/src/Commands/Commands/insert-range-move-down.command.ts
index d443865503..c7b6713715 100644
--- a/packages/base-sheets/src/Commands/Commands/insert-range-move-down.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/insert-range-move-down.command.ts
@@ -2,7 +2,7 @@ import { CommandType, Dimension, ICellData, ICommand, ICommandService, ICurrentU
import { IAccessor } from '@wendellhu/redi';
import { IDeleteRangeMutationParams, IInsertRangeMutationParams } from '../../Basics/Interfaces/MutationInterface';
-import { ISelectionManager } from '../../Services/tokens';
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { DeleteRangeMutation } from '../Mutations/delete-range.mutation';
import { InsertRangeMutation, InsertRangeUndoMutationFactory } from '../Mutations/insert-range.mutation';
@@ -17,12 +17,12 @@ export const InsertRangeMoveDownCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
- const range = selectionManager.getCurrentSelections();
- if (!range.length) return false;
+ const range = selectionManagerService.getRangeDatas();
+ if (!range?.length) return false;
const workbook = currentUniverService.getUniverSheetInstance(workbookId)?.getWorkBook();
if (!workbook) return false;
diff --git a/packages/base-sheets/src/Commands/Commands/insert-range-move-right.command.ts b/packages/base-sheets/src/Commands/Commands/insert-range-move-right.command.ts
index 8fce64d7a9..dbd9207d7c 100644
--- a/packages/base-sheets/src/Commands/Commands/insert-range-move-right.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/insert-range-move-right.command.ts
@@ -1,10 +1,10 @@
-import { IAccessor } from '@wendellhu/redi';
import { CommandType, Dimension, ICellData, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService, ObjectMatrix } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { IDeleteRangeMutationParams, IInsertRangeMutationParams } from '../../Basics/Interfaces/MutationInterface';
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { DeleteRangeMutation } from '../Mutations/delete-range.mutation';
import { InsertRangeMutation, InsertRangeUndoMutationFactory } from '../Mutations/insert-range.mutation';
-import { IDeleteRangeMutationParams, IInsertRangeMutationParams } from '../../Basics/Interfaces/MutationInterface';
-import { ISelectionManager } from '../../Services/tokens';
/**
* The command to insert range.
@@ -17,12 +17,12 @@ export const InsertRangeMoveRightCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
- const range = selectionManager.getCurrentSelections();
- if (!range.length) return false;
+ const range = selectionManagerService.getRangeDatas();
+ if (!range?.length) return false;
const workbook = currentUniverService.getUniverSheetInstance(workbookId)?.getWorkBook();
if (!workbook) return false;
diff --git a/packages/base-sheets/src/Commands/Commands/insert-row-col.command.ts b/packages/base-sheets/src/Commands/Commands/insert-row-col.command.ts
index b76a53c991..af5f85d3cd 100644
--- a/packages/base-sheets/src/Commands/Commands/insert-row-col.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/insert-row-col.command.ts
@@ -11,7 +11,7 @@ import {
IRemoveRowMutationParams,
IRemoveWorksheetMergeMutationParams,
} from '../../Basics/Interfaces/MutationInterface';
-import { ISelectionManager } from '../../Services/tokens';
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { AddWorksheetMergeMutation, AddWorksheetMergeMutationFactory } from '../Mutations/add-worksheet-merge.mutation';
import { DeleteRangeMutation } from '../Mutations/delete-range.mutation';
import { InsertRangeMutation, InsertRangeUndoMutationFactory } from '../Mutations/insert-range.mutation';
@@ -32,6 +32,7 @@ export interface InsertRowCommandBaseParams {
export const InsertRowCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.insert-row',
+ // eslint-disable-next-line max-lines-per-function
handler: async (accessor: IAccessor, params: InsertRowCommandBaseParams) => {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
@@ -70,7 +71,7 @@ export const InsertRowCommand: ICommand = {
if (!deleteRangeMutationParams) return false;
const deleteResult = commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);
- const mergeData = Tools.deepClone(worksheet.getConfig().mergeData);
+ const mergeData = Tools.deepClone(worksheet.getMergeData());
for (let i = 0; i < mergeData.length; i++) {
const merge = mergeData[i];
const count = endRow - startRow + 1;
@@ -87,7 +88,7 @@ export const InsertRowCommand: ICommand = {
const removeMergeMutationParams: IRemoveWorksheetMergeMutationParams = {
workbookId: params.workbookId,
worksheetId: params.worksheetId,
- ranges: Tools.deepClone(worksheet.getConfig().mergeData),
+ ranges: Tools.deepClone(worksheet.getMergeData()),
};
const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = RemoveWorksheetMergeMutationFactory(accessor, removeMergeMutationParams);
const removeResult = commandService.executeCommand(RemoveWorksheetMergeMutation.id, removeMergeMutationParams);
@@ -115,7 +116,7 @@ export const InsertRowCommand: ICommand = {
})
.then((res) => {
if (res) return commandService.executeCommand(AddWorksheetMergeMutation.id, undoRemoveMergeMutationParams);
- return fase;
+ return false;
});
},
redo() {
@@ -147,12 +148,12 @@ export const InsertRowBeforeCommand: ICommand<InsertRowCommandParams> = {
handler: async (accessor: IAccessor, params?: InsertRowCommandParams) => {
const commandService = accessor.get(ICommandService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
let range: IRangeData;
- const selections = selectionManager.getCurrentSelections();
+ const selections = selectionManagerService.getRangeDatas();
if (selections && selections.length === 1) {
range = selections[0];
} else {
@@ -190,12 +191,12 @@ export const InsertRowAfterCommand: ICommand<InsertRowCommandParams> = {
handler: async (accessor: IAccessor, params: InsertRowCommandParams) => {
const commandService = accessor.get(ICommandService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
let range: IRangeData;
- const selections = selectionManager.getCurrentSelections();
+ const selections = selectionManagerService.getRangeDatas();
if (selections && selections.length === 1) {
range = selections[0];
} else {
@@ -240,6 +241,7 @@ export interface InsertColCommandBaseParams {
export const InsertColCommand: ICommand<InsertColCommandBaseParams> = {
type: CommandType.COMMAND,
id: 'sheet.command.insert-col',
+ // eslint-disable-next-line max-lines-per-function
handler: async (accessor: IAccessor, params: InsertColCommandBaseParams) => {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
@@ -278,7 +280,7 @@ export const InsertColCommand: ICommand<InsertColCommandBaseParams> = {
if (!deleteRangeMutationParams) return false;
const deleteResult = commandService.executeCommand(InsertRangeMutation.id, insertRangeMutationParams);
- const mergeData = Tools.deepClone(worksheet.getConfig().mergeData);
+ const mergeData = Tools.deepClone(worksheet.getMergeData());
for (let i = 0; i < mergeData.length; i++) {
const merge = mergeData[i];
const count = endColumn - startColumn + 1;
@@ -295,7 +297,7 @@ export const InsertColCommand: ICommand<InsertColCommandBaseParams> = {
const removeMergeMutationParams: IRemoveWorksheetMergeMutationParams = {
workbookId: params.workbookId,
worksheetId: params.worksheetId,
- ranges: Tools.deepClone(worksheet.getConfig().mergeData),
+ ranges: Tools.deepClone(worksheet.getMergeData()),
};
const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = RemoveWorksheetMergeMutationFactory(accessor, removeMergeMutationParams);
const removeResult = commandService.executeCommand(RemoveWorksheetMergeMutation.id, removeMergeMutationParams);
@@ -323,7 +325,7 @@ export const InsertColCommand: ICommand<InsertColCommandBaseParams> = {
})
.then((res) => {
if (res) return commandService.executeCommand(AddWorksheetMergeMutation.id, undoRemoveMergeMutationParams);
- return fase;
+ return false;
});
},
redo() {
@@ -355,12 +357,12 @@ export const InsertColBeforeCommand: ICommand<InsertColCommandParams> = {
handler: async (accessor: IAccessor, params?: InsertColCommandParams) => {
const commandService = accessor.get(ICommandService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
let range: IRangeData;
- const selections = selectionManager.getCurrentSelections();
+ const selections = selectionManagerService.getRangeDatas();
if (selections && selections.length === 1) {
range = selections[0];
} else {
@@ -398,12 +400,12 @@ export const InsertColAfterCommand: ICommand<InsertColCommandParams> = {
handler: async (accessor: IAccessor, params?: InsertColCommandParams) => {
const commandService = accessor.get(ICommandService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
let range: IRangeData;
- const selections = selectionManager.getCurrentSelections();
+ const selections = selectionManagerService.getRangeDatas();
if (selections && selections.length === 1) {
range = selections[0];
} else {
diff --git a/packages/base-sheets/src/Commands/Commands/move-columns-to.command.ts b/packages/base-sheets/src/Commands/Commands/move-columns-to.command.ts
index e7f9e1cb40..6d89683d3a 100644
--- a/packages/base-sheets/src/Commands/Commands/move-columns-to.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/move-columns-to.command.ts
@@ -2,7 +2,7 @@ import { CommandType, ICommand, ICommandService, ICurrentUniverService, IUndoRed
import { IAccessor } from '@wendellhu/redi';
import { IInsertColMutationParams, IRemoveColMutationParams } from '../../Basics/Interfaces/MutationInterface';
-import { ISelectionManager } from '../../Services/tokens';
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { InsertColMutation, InsertColMutationFactory } from '../Mutations/insert-row-col.mutation';
import { IRemoveColMutationFactory, RemoveColMutation } from '../Mutations/remove-row-col.mutation';
@@ -17,9 +17,9 @@ export const MoveColumnsToCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
- const originRange = selectionManager.getCurrentSelections()[0];
+ const originRange = selectionManagerService.getRangeDatas()?.[0];
if (!originRange) {
return false;
}
diff --git a/packages/base-sheets/src/Commands/Commands/move-range-to.command.ts b/packages/base-sheets/src/Commands/Commands/move-range-to.command.ts
index 9cc57924d1..b1c3910cd8 100644
--- a/packages/base-sheets/src/Commands/Commands/move-range-to.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/move-range-to.command.ts
@@ -1,7 +1,7 @@
import { CommandType, ICellData, ICommand, ICommandService, ICurrentUniverService, IRangeData, IUndoRedoService, ObjectMatrix } from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
-import { ISelectionManager } from '../../Services/tokens';
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { ISetRangeValuesMutationParams, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../Mutations/set-range-values.mutation';
export interface IMoveRangeToCommandParams {
@@ -15,9 +15,9 @@ export const MoveRangeToCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
- const originRange = selectionManager.getCurrentSelections()[0];
+ const originRange = selectionManagerService.getRangeDatas()?.[0];
if (!originRange) {
return false;
}
diff --git a/packages/base-sheets/src/Commands/Commands/move-rows-to.command.ts b/packages/base-sheets/src/Commands/Commands/move-rows-to.command.ts
index 3b78c978bb..53a850679b 100644
--- a/packages/base-sheets/src/Commands/Commands/move-rows-to.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/move-rows-to.command.ts
@@ -2,7 +2,7 @@ import { CommandType, ICommand, ICommandService, ICurrentUniverService, IUndoRed
import { IAccessor } from '@wendellhu/redi';
import { IInsertRowMutationParams, IRemoveRowMutationParams } from '../../Basics/Interfaces/MutationInterface';
-import { ISelectionManager } from '../../Services/tokens';
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { InsertRowMutation, InsertRowMutationFactory } from '../Mutations/insert-row-col.mutation';
import { IRemoveRowMutationFactory, RemoveRowMutation } from '../Mutations/remove-row-col.mutation';
@@ -17,9 +17,9 @@ export const MoveRowsToCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
- const originRange = selectionManager.getCurrentSelections()[0];
+ const originRange = selectionManagerService.getRangeDatas()?.[0];
if (!originRange) {
return false;
}
diff --git a/packages/base-sheets/src/Commands/Commands/remove-row-col.command.ts b/packages/base-sheets/src/Commands/Commands/remove-row-col.command.ts
index 935cf64a39..c5c3473594 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
@@ -11,7 +11,7 @@ import {
IRemoveRowMutationParams,
IRemoveWorksheetMergeMutationParams,
} from '../../Basics/Interfaces/MutationInterface';
-import { ISelectionManager } from '../../Services/tokens';
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { AddWorksheetMergeMutation, AddWorksheetMergeMutationFactory } from '../Mutations/add-worksheet-merge.mutation';
import { DeleteRangeMutation, DeleteRangeUndoMutationFactory } from '../Mutations/delete-range.mutation';
import { InsertRangeMutation } from '../Mutations/insert-range.mutation';
@@ -22,16 +22,17 @@ import { RemoveWorksheetMergeMutation, RemoveWorksheetMergeMutationFactory } fro
export const RemoveRowCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.remove-row',
+ // eslint-disable-next-line max-lines-per-function
handler: async (accessor: IAccessor) => {
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selections = selectionManager.getCurrentSelections();
+ const selections = selectionManagerService.getRangeDatas();
const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
- if (!selections.length) return false;
+ if (!selections?.length) return false;
const workbook = currentUniverService.getUniverSheetInstance(workbookId)?.getWorkBook();
if (!workbook) return false;
const worksheet = workbook.getSheetBySheetId(worksheetId);
@@ -62,7 +63,7 @@ export const RemoveRowCommand: ICommand = {
if (!insertRangeMutationParams) return false;
const deleteResult = commandService.executeCommand(DeleteRangeMutation.id, deleteRangeValueMutationParams);
- const mergeData = Tools.deepClone(worksheet.getConfig().mergeData);
+ const mergeData = Tools.deepClone(worksheet.getMergeData());
for (let i = 0; i < mergeData.length; i++) {
const merge = mergeData[i];
for (let j = 0; j < selections.length; j++) {
@@ -91,7 +92,7 @@ export const RemoveRowCommand: ICommand = {
const removeMergeMutationParams: IRemoveWorksheetMergeMutationParams = {
workbookId,
worksheetId,
- ranges: Tools.deepClone(worksheet.getConfig().mergeData),
+ ranges: Tools.deepClone(worksheet.getMergeData()),
};
const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = RemoveWorksheetMergeMutationFactory(accessor, removeMergeMutationParams);
const removeResult = commandService.executeCommand(RemoveWorksheetMergeMutation.id, removeMergeMutationParams);
@@ -119,7 +120,7 @@ export const RemoveRowCommand: ICommand = {
})
.then((res) => {
if (res) return commandService.executeCommand(AddWorksheetMergeMutation.id, undoRemoveMergeMutationParams);
- return fase;
+ return false;
});
},
redo() {
@@ -147,16 +148,17 @@ export const RemoveRowCommand: ICommand = {
export const RemoveColCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.remove-col',
+ // eslint-disable-next-line max-lines-per-function
handler: async (accessor: IAccessor) => {
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selections = selectionManager.getCurrentSelections();
+ const selections = selectionManagerService.getRangeDatas();
const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
- if (!selections.length) return false;
+ if (!selections?.length) return false;
const workbook = currentUniverService.getUniverSheetInstance(workbookId)?.getWorkBook();
if (!workbook) return false;
const worksheet = workbook.getSheetBySheetId(worksheetId);
@@ -186,7 +188,7 @@ export const RemoveColCommand: ICommand = {
if (!insertRangeMutationParams) return false;
const deleteResult = commandService.executeCommand(DeleteRangeMutation.id, deleteRangeValueMutationParams);
- const mergeData = Tools.deepClone(worksheet.getConfig().mergeData);
+ const mergeData = Tools.deepClone(worksheet.getMergeData());
for (let i = 0; i < mergeData.length; i++) {
const merge = mergeData[i];
for (let j = 0; j < selections.length; j++) {
@@ -216,7 +218,7 @@ export const RemoveColCommand: ICommand = {
const removeMergeMutationParams: IRemoveWorksheetMergeMutationParams = {
workbookId,
worksheetId,
- ranges: Tools.deepClone(worksheet.getConfig().mergeData),
+ ranges: Tools.deepClone(worksheet.getMergeData()),
};
const undoRemoveMergeMutationParams: IAddWorksheetMergeMutationParams = RemoveWorksheetMergeMutationFactory(accessor, removeMergeMutationParams);
const removeResult = commandService.executeCommand(RemoveWorksheetMergeMutation.id, removeMergeMutationParams);
@@ -244,7 +246,7 @@ export const RemoveColCommand: ICommand = {
})
.then((res) => {
if (res) return commandService.executeCommand(AddWorksheetMergeMutation.id, undoRemoveMergeMutationParams);
- return fase;
+ return false;
});
},
redo() {
diff --git a/packages/base-sheets/src/Commands/Commands/remove-worksheet-merge.command.ts b/packages/base-sheets/src/Commands/Commands/remove-worksheet-merge.command.ts
index 5c9b054ebd..398cd17502 100644
--- a/packages/base-sheets/src/Commands/Commands/remove-worksheet-merge.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/remove-worksheet-merge.command.ts
@@ -2,7 +2,7 @@ import { CommandType, ICommand, ICommandService, ICurrentUniverService, IUndoRed
import { IAccessor } from '@wendellhu/redi';
import { IAddWorksheetMergeMutationParams, IRemoveWorksheetMergeMutationParams } from '../../Basics/Interfaces/MutationInterface';
-import { ISelectionManager } from '../../Services/tokens';
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { AddWorksheetMergeMutation } from '../Mutations/add-worksheet-merge.mutation';
import { RemoveWorksheetMergeMutation, RemoveWorksheetMergeMutationFactory } from '../Mutations/remove-worksheet-merge.mutation';
@@ -10,13 +10,13 @@ export const RemoveWorksheetMergeCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.remove-worksheet-merge',
handler: async (accessor: IAccessor) => {
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selections = selectionManager.getCurrentSelections();
- if (!selections.length) return false;
+ const selections = selectionManagerService.getRangeDatas();
+ if (!selections?.length) return false;
const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
diff --git a/packages/base-sheets/src/Commands/Commands/set-border-command.ts b/packages/base-sheets/src/Commands/Commands/set-border-command.ts
index e58b286149..1be3921a2d 100644
--- a/packages/base-sheets/src/Commands/Commands/set-border-command.ts
+++ b/packages/base-sheets/src/Commands/Commands/set-border-command.ts
@@ -17,7 +17,7 @@ import {
import { IAccessor } from '@wendellhu/redi';
import { BorderStyleManagerService } from '../../Services/border-style-manager.service';
-import { ISelectionManager } from '../../Services/tokens';
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { ISetBorderStylesMutationParams, SetBorderStylesMutation, SetBorderStylesUndoMutationFactory } from '../Mutations/set-border-styles.mutatio';
function forEach(rangeData: IRangeData, action: (row: number, column: number) => void): void {
@@ -39,12 +39,12 @@ export const SetBorderPositionCommand: ICommand<ISetBorderPositionCommandParams>
handler: async (accessor: IAccessor, params: ISetBorderPositionCommandParams) => {
const commandService = accessor.get(ICommandService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const borderStyleManagerService = accessor.get(BorderStyleManagerService);
- const selections = selectionManager.getCurrentSelections();
+ const selections = selectionManagerService.getRangeDatas();
const workbook = currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
- if (!selections.length) {
+ if (!selections?.length) {
return false;
}
diff --git a/packages/base-sheets/src/Commands/Commands/set-border-styles-command.ts b/packages/base-sheets/src/Commands/Commands/set-border-styles-command.ts
index b8a058d9cd..cc5d0604fe 100644
--- a/packages/base-sheets/src/Commands/Commands/set-border-styles-command.ts
+++ b/packages/base-sheets/src/Commands/Commands/set-border-styles-command.ts
@@ -16,7 +16,7 @@ import {
import { IAccessor } from '@wendellhu/redi';
import { BorderStyleManagerService } from '../../Services/border-style-manager.service';
-import { ISelectionManager } from '../../Services/tokens';
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { ISetBorderStylesMutationParams, SetBorderStylesMutation, SetBorderStylesUndoMutationFactory } from '../Mutations/set-border-styles.mutatio';
export interface ISetBorderCommandParams {
@@ -53,9 +53,9 @@ export const SetBorderCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
- const range = params.range || selectionManager.getCurrentSelections()[0];
+ const range = params.range || selectionManagerService.getRangeDatas()?.[0];
if (!range) {
return false;
}
diff --git a/packages/base-sheets/src/Commands/Commands/set-range-formatted-value.command.ts b/packages/base-sheets/src/Commands/Commands/set-range-formatted-value.command.ts
index 671c76e2b4..5b9c43ec6d 100644
--- a/packages/base-sheets/src/Commands/Commands/set-range-formatted-value.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/set-range-formatted-value.command.ts
@@ -1,8 +1,8 @@
-import { IAccessor } from '@wendellhu/redi';
import { CommandType, ICellV, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService, ObjectMatrix, Tools } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { ISetRangeFormattedValueMutationParams, SetRangeFormattedValueMutation, SetRangeFormattedValueUndoMutationFactory } from '../Mutations/set-range-formatted-value.mutation';
-import { ISelectionManager } from '../../Services/tokens';
export interface ISetRangeFormattedValueParams {
value: ICellV | ICellV[][] | ObjectMatrix<ICellV>;
@@ -19,10 +19,10 @@ export const SetRangeFormattedValueCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
- const ranges = selectionManager.getCurrentSelections();
- if (!ranges.length) {
+ const ranges = selectionManagerService.getRangeDatas();
+ if (!ranges?.length) {
return false;
}
diff --git a/packages/base-sheets/src/Commands/Commands/set-range-values.command.ts b/packages/base-sheets/src/Commands/Commands/set-range-values.command.ts
index 637fea2fd7..46960c48d5 100644
--- a/packages/base-sheets/src/Commands/Commands/set-range-values.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/set-range-values.command.ts
@@ -1,7 +1,8 @@
import { CommandType, ICellData, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService, ObjectMatrix, ObjectMatrixPrimitiveType, Tools } from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
+
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { ISetRangeValuesMutationParams, SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../Mutations/set-range-values.mutation';
-import { ISelectionManager } from '../../Services/tokens';
export interface ISetRangeValuesCommandParams {
worksheetId?: string;
@@ -19,10 +20,10 @@ export const SetRangeValuesCommand: ICommand = {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
- const range = selectionManager.getCurrentSelections();
- if (!range.length) {
+ const range = selectionManagerService.getRangeDatas();
+ if (!range?.length) {
return false;
}
diff --git a/packages/base-sheets/src/Commands/Commands/set-selections.command.ts b/packages/base-sheets/src/Commands/Commands/set-selections.command.ts
index 0341448592..28bdfc770f 100644
--- a/packages/base-sheets/src/Commands/Commands/set-selections.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/set-selections.command.ts
@@ -1,7 +1,7 @@
import { SetSelectionsOperation } from '@Commands/Operations/selection.operation';
import { CommandType, Direction, ICommand, ICommandService, ICurrentUniverService, IRangeData } from '@univerjs/core';
-import { ISelectionManager } from '../../Services/tokens';
+import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../Services/selection-manager.service';
export interface IChangeSelectionCommandParams {
direction: Direction;
@@ -13,12 +13,13 @@ export const ChangeSelectionCommand: ICommand<IChangeSelectionCommandParams> = {
type: CommandType.COMMAND,
handler: async (accessor, params) => {
const currentUniverService = accessor.get(ICurrentUniverService);
- const currentWorksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
- const selectionManager = accessor.get(ISelectionManager);
+ const currentWorkbook = currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
+ const currentWorksheet = currentWorkbook.getActiveSheet();
+ const selectionManagerService = accessor.get(SelectionManagerService);
const commandService = accessor.get(ICommandService);
- const selections = selectionManager.getCurrentSelections();
- if (!selections.length) {
+ const selections = selectionManagerService.getRangeDatas();
+ if (!selections?.length || params == null) {
return false;
}
@@ -51,10 +52,22 @@ export const ChangeSelectionCommand: ICommand<IChangeSelectionCommandParams> = {
// TODO: deal with `toEnd` parameter here
commandService.executeCommand(SetSelectionsOperation.id, {
+ unitId: currentWorkbook.getUnitId(),
sheetId: currentWorksheet.getSheetId(),
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
selections: [
{
- selection: destRange,
+ rangeData: destRange,
+ cellRange: {
+ row: destRange.startRow,
+ column: destRange.startColumn,
+ isMerged: false,
+ isMergedMainCell: false,
+ startRow: destRange.startRow,
+ startColumn: destRange.startColumn,
+ endRow: destRange.endRow,
+ endColumn: destRange.endColumn,
+ },
},
],
});
diff --git a/packages/base-sheets/src/Commands/Commands/set-style.command.ts b/packages/base-sheets/src/Commands/Commands/set-style.command.ts
index 2fdcd37443..3e55ea43c6 100644
--- a/packages/base-sheets/src/Commands/Commands/set-style.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/set-style.command.ts
@@ -19,7 +19,7 @@ import {
} from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
-import { ISelectionManager } from '../../Services/tokens';
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { ISetRangeStyleMutationParams, SetRangeStyleMutation, SetRangeStyleUndoMutationFactory } from '../Mutations/set-range-styles.mutation';
export interface IStyleTypeValue<T> {
@@ -44,11 +44,11 @@ export const SetStyleCommand: ICommand<ISetStyleParams<unknown>> = {
handler: async <T>(accessor: IAccessor, params: ISetStyleParams<T>) => {
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const ranges = selectionManager.getCurrentSelections();
- if (!ranges.length) {
+ const ranges = selectionManagerService.getRangeDatas();
+ if (!ranges?.length) {
return false;
}
@@ -119,8 +119,14 @@ export const SetBoldCommand: ICommand = {
id: 'sheet.command.set-bold',
handler: async (accessor) => {
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
- const currentlyBold = selectionManager.getCurrentCell()?.getFontWeight() === FontWeight.BOLD;
+ const selectionManagerService = accessor.get(SelectionManagerService);
+ const cellRange = selectionManagerService.getLast()?.cellRange;
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+ let currentlyBold = true;
+ if (cellRange) {
+ currentlyBold = worksheet.getRange(cellRange.row, cellRange.column).getFontWeight() === FontWeight.BOLD;
+ }
const setStyleParams: ISetStyleParams<BooleanNumber> = {
style: {
@@ -141,8 +147,15 @@ export const SetItalicCommand: ICommand = {
id: 'sheet.command.set-italic',
handler: async (accessor, params) => {
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
- const currentlyItalic = selectionManager.getCurrentCell()?.getFontStyle() === FontItalic.ITALIC;
+ const selectionManagerService = accessor.get(SelectionManagerService);
+ const cellRange = selectionManagerService.getLast()?.cellRange;
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+
+ let currentlyItalic = true;
+ if (cellRange) {
+ currentlyItalic = worksheet.getRange(cellRange.row, cellRange.column).getFontStyle() === FontItalic.ITALIC;
+ }
const setStyleParams: ISetStyleParams<BooleanNumber> = {
style: {
@@ -163,8 +176,15 @@ export const SetUnderlineCommand: ICommand = {
id: 'sheet.command.set-underline',
handler: async (accessor, params) => {
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
- const currentlyUnderline = !!selectionManager.getCurrentCell()?.getUnderline().s;
+ const selectionManagerService = accessor.get(SelectionManagerService);
+ const cellRange = selectionManagerService.getLast()?.cellRange;
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+
+ let currentlyUnderline = true;
+ if (cellRange) {
+ currentlyUnderline = !!worksheet.getRange(cellRange.row, cellRange.column).getUnderline().s;
+ }
const setStyleParams: ISetStyleParams<{ s: number }> = {
style: {
@@ -187,8 +207,16 @@ export const SetStrikeThroughCommand: ICommand = {
id: 'sheet.command.set-stroke',
handler: async (accessor, params) => {
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
- const currentlyStrokeThrough = !!selectionManager.getCurrentCell()?.getStrikeThrough().s;
+
+ const selectionManagerService = accessor.get(SelectionManagerService);
+ const cellRange = selectionManagerService.getLast()?.cellRange;
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+
+ let currentlyStrokeThrough = true;
+ if (cellRange) {
+ currentlyStrokeThrough = !!worksheet.getRange(cellRange.row, cellRange.column).getStrikeThrough().s;
+ }
const setStyleParams: ISetStyleParams<{ s: number }> = {
style: {
diff --git a/packages/base-sheets/src/Commands/Commands/set-worksheet-col-width.command.ts b/packages/base-sheets/src/Commands/Commands/set-worksheet-col-width.command.ts
index 96401a8be6..52a4e967bc 100644
--- a/packages/base-sheets/src/Commands/Commands/set-worksheet-col-width.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/set-worksheet-col-width.command.ts
@@ -1,7 +1,7 @@
import { CommandType, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService } from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
-import { ISelectionManager } from '../../Services/tokens';
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { ISetWorksheetColWidthMutationParams, SetWorksheetColWidthMutation, SetWorksheetColWidthMutationFactory } from '../Mutations/set-worksheet-col-width.mutation';
/**
@@ -16,13 +16,13 @@ export const SetWorksheetColWidthCommand: ICommand = {
id: 'sheet.command.set-worksheet-col-width',
handler: async (accessor: IAccessor, params: SetWorksheetColWidthCommandParams) => {
console.info('sheet.command.set-worksheet-col-width', params);
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selections = selectionManager.getCurrentSelections();
- if (!selections.length) return false;
+ const selections = selectionManagerService.getRangeDatas();
+ if (!selections?.length) return false;
const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
diff --git a/packages/base-sheets/src/Commands/Commands/set-worksheet-column-hide.command.ts b/packages/base-sheets/src/Commands/Commands/set-worksheet-column-hide.command.ts
index d30e2726e1..37610f33b3 100644
--- a/packages/base-sheets/src/Commands/Commands/set-worksheet-column-hide.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/set-worksheet-column-hide.command.ts
@@ -1,20 +1,21 @@
import { CommandType, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService } from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
+
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { ISetWorksheetColumnHideMutationParams, SetWorksheetColumnHideMutation, SetWorksheetColumnHideMutationFactory } from '../Mutations/set-worksheet-column-hide.mutation';
import { SetWorksheetColumnShowMutation } from '../Mutations/set-worksheet-column-show.mutation';
-import { ISelectionManager } from '../../Services/tokens';
export const SetWorksheetColumnHideCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.set-worksheet-column-hide',
handler: async (accessor: IAccessor) => {
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selections = selectionManager.getCurrentSelections();
- if (!selections.length) {
+ const selections = selectionManagerService.getRangeDatas();
+ if (!selections?.length) {
return false;
}
diff --git a/packages/base-sheets/src/Commands/Commands/set-worksheet-column-show.command.ts b/packages/base-sheets/src/Commands/Commands/set-worksheet-column-show.command.ts
index 63f705b08e..ed8fa02f34 100644
--- a/packages/base-sheets/src/Commands/Commands/set-worksheet-column-show.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/set-worksheet-column-show.command.ts
@@ -1,20 +1,21 @@
import { CommandType, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService } from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
-import { ISetWorksheetColumnShowMutationParams, SetWorksheetColumnShowMutation, SetWorksheetColumnShowMutationFactory } from '../Mutations/set-worksheet-column-show.mutation';
+
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { SetWorksheetColumnHideMutation } from '../Mutations/set-worksheet-column-hide.mutation';
-import { ISelectionManager } from '../../Services/tokens';
+import { ISetWorksheetColumnShowMutationParams, SetWorksheetColumnShowMutation, SetWorksheetColumnShowMutationFactory } from '../Mutations/set-worksheet-column-show.mutation';
export const SetWorksheetColumnShowCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.set-worksheet-column-show',
handler: async (accessor: IAccessor) => {
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selections = selectionManager.getCurrentSelections();
- if (!selections.length) {
+ const selections = selectionManagerService.getRangeDatas();
+ if (!selections?.length) {
return false;
}
diff --git a/packages/base-sheets/src/Commands/Commands/set-worksheet-row-height.command.ts b/packages/base-sheets/src/Commands/Commands/set-worksheet-row-height.command.ts
index 486dee7435..c73220cbca 100644
--- a/packages/base-sheets/src/Commands/Commands/set-worksheet-row-height.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/set-worksheet-row-height.command.ts
@@ -1,7 +1,7 @@
import { CommandType, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService } from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
-import { ISelectionManager } from '../../Services/tokens';
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { ISetWorksheetRowHeightMutationParams, SetWorksheetRowHeightMutation, SetWorksheetRowHeightMutationFactory } from '../Mutations/set-worksheet-row-height.mutation';
/**
@@ -16,14 +16,14 @@ export const SetWorksheetRowHeightCommand: ICommand = {
id: 'sheet.command.set-worksheet-row-height',
handler: async (accessor: IAccessor, params: SetWorksheetRowHeightCommandParams) => {
console.info('sheet.command.set-worksheet-row-height==========', params);
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selections = selectionManager.getCurrentSelections();
+ const selections = selectionManagerService.getRangeDatas();
console.info('current selections', selections);
- if (!selections.length) return false;
+ if (!selections?.length) return false;
const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
diff --git a/packages/base-sheets/src/Commands/Commands/set-worksheet-row-hide.command.ts b/packages/base-sheets/src/Commands/Commands/set-worksheet-row-hide.command.ts
index fab197dc51..7d5015bde9 100644
--- a/packages/base-sheets/src/Commands/Commands/set-worksheet-row-hide.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/set-worksheet-row-hide.command.ts
@@ -1,20 +1,21 @@
import { CommandType, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService } from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
+
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { ISetWorksheetRowHideMutationParams, SetWorksheetRowHideMutation, SetWorksheetRowHideMutationFactory } from '../Mutations/set-worksheet-row-hide.mutation';
import { SetWorksheetRowShowMutation } from '../Mutations/set-worksheet-row-show.mutation';
-import { ISelectionManager } from '../../Services/tokens';
export const SetWorksheetRowHideCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.set-worksheet-row-hide',
handler: async (accessor: IAccessor) => {
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selections = selectionManager.getCurrentSelections();
- if (!selections.length) {
+ const selections = selectionManagerService.getRangeDatas();
+ if (!selections?.length) {
return false;
}
diff --git a/packages/base-sheets/src/Commands/Commands/set-worksheet-row-show.command.ts b/packages/base-sheets/src/Commands/Commands/set-worksheet-row-show.command.ts
index a2074e9d1e..bfa81dc2a7 100644
--- a/packages/base-sheets/src/Commands/Commands/set-worksheet-row-show.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/set-worksheet-row-show.command.ts
@@ -1,20 +1,21 @@
import { CommandType, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService } from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
-import { ISetWorksheetRowShowMutationParams, SetWorksheetRowShowMutation, SetWorksheetRowShowMutationFactory } from '../Mutations/set-worksheet-row-show.mutation';
+
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { SetWorksheetRowHideMutation } from '../Mutations/set-worksheet-row-hide.mutation';
-import { ISelectionManager } from '../../Services/tokens';
+import { ISetWorksheetRowShowMutationParams, SetWorksheetRowShowMutation, SetWorksheetRowShowMutationFactory } from '../Mutations/set-worksheet-row-show.mutation';
export const SetWorksheetRowShowCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.set-worksheet-row-show',
handler: async (accessor: IAccessor) => {
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selections = selectionManager.getCurrentSelections();
- if (!selections.length) {
+ const selections = selectionManagerService.getRangeDatas();
+ if (!selections?.length) {
return false;
}
diff --git a/packages/base-sheets/src/Commands/Commands/trim-whitespace.command.ts b/packages/base-sheets/src/Commands/Commands/trim-whitespace.command.ts
index 91bd019525..4e6c6987e1 100644
--- a/packages/base-sheets/src/Commands/Commands/trim-whitespace.command.ts
+++ b/packages/base-sheets/src/Commands/Commands/trim-whitespace.command.ts
@@ -1,8 +1,8 @@
-import { IAccessor } from '@wendellhu/redi';
import { CommandType, ICellV, ICommand, ICommandService, ICurrentUniverService, IUndoRedoService, ObjectMatrix } from '@univerjs/core';
+import { IAccessor } from '@wendellhu/redi';
+import { SelectionManagerService } from '../../Services/selection-manager.service';
import { ISetRangeFormattedValueMutationParams, SetRangeFormattedValueMutation, SetRangeFormattedValueUndoMutationFactory } from '../Mutations/set-range-formatted-value.mutation';
-import { ISelectionManager } from '../../Services/tokens';
/**
* The command to trim whitespace.
@@ -12,13 +12,13 @@ export const TrimWhitespaceCommand: ICommand = {
id: 'sheet.command.trim-whitespace',
handler: async (accessor: IAccessor) => {
- const selectionManager = accessor.get(ISelectionManager);
+ const selectionManagerService = accessor.get(SelectionManagerService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
const currentUniverService = accessor.get(ICurrentUniverService);
- const selections = selectionManager.getCurrentSelections();
- if (!selections.length) return false;
+ const selections = selectionManagerService.getRangeDatas();
+ if (!selections?.length) return false;
const workbookId = currentUniverService.getCurrentUniverSheetInstance().getUnitId();
const worksheetId = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
diff --git a/packages/base-sheets/src/Commands/Operations/selection.operation.ts b/packages/base-sheets/src/Commands/Operations/selection.operation.ts
index 54c60697da..21384e31da 100644
--- a/packages/base-sheets/src/Commands/Operations/selection.operation.ts
+++ b/packages/base-sheets/src/Commands/Operations/selection.operation.ts
@@ -1,27 +1,26 @@
-// This file provide operations to change selecction of sheets.
+// This file provide operations to change selection of sheets.
-import { ISelectionManager } from '@Services/tokens';
-import { CommandType, ICellInfo, IOperation, ISelection, Nullable } from '@univerjs/core';
+import { ISelectionRangeWithStyle } from '@univerjs/base-render';
+import { CommandType, IOperation } from '@univerjs/core';
-export interface ISelectionModelValue {
- selection: ISelection;
- cell: Nullable<ICellInfo>;
-}
+import { SelectionManagerService } from '../../Services/selection-manager.service';
export interface ISetSelectionsOperationParams {
+ unitId: string;
sheetId: string;
- selections: ISelectionModelValue[];
+ pluginName: string;
+ selections: ISelectionRangeWithStyle[];
}
export const SetSelectionsOperation: IOperation<ISetSelectionsOperationParams> = {
id: 'sheet.operation.set-selections',
type: CommandType.OPERATION,
handler: async (accessor, params) => {
- const selectionManager = accessor.get(ISelectionManager);
- selectionManager.setModels(params!.selections);
- const models = selectionManager.getCurrentModels();
- models?.forEach((m) => m.setCurrentCell());
- selectionManager.renderCurrentControls(false);
+ const selectionManagerService = accessor.get(SelectionManagerService);
+ selectionManagerService.replace(params!.selections);
+ // const models = selectionManager.getCurrentModels();
+ // models?.forEach((m) => m.setCurrentCell());
+ // selectionManager.renderCurrentControls(false);
return true;
},
};
diff --git a/packages/base-sheets/src/Controller/AntLineController.ts b/packages/base-sheets/src/Controller/AntLineController.ts
deleted file mode 100644
index 99bd354d96..0000000000
--- a/packages/base-sheets/src/Controller/AntLineController.ts
+++ /dev/null
@@ -1,191 +0,0 @@
-import { Inject } from '@wendellhu/redi';
-import { ICurrentUniverService, ObserverManager } from '@univerjs/core';
-import { Rect, Scene } from '@univerjs/base-render';
-
-import { AntLine, AntLineModel, IAntLineRange } from '../Model/AntLineModel';
-import { CanvasView } from '../View';
-
-enum ANT_LINE_MANAGER_KEY {
- AntLine = '__AntLineShape__',
-}
-
-/**
- * Ant Line Controller
- */
-export class AntLineControl {
- private _antLineModelList: AntLineModel[];
-
- private _activeSheetId: string;
-
- /**
- * Create AntLineController
- */
- constructor(
- @Inject(ObserverManager) private readonly _observerManager: ObserverManager,
- @ICurrentUniverService private readonly _currentUniverSheet: ICurrentUniverService,
- @Inject(CanvasView) private readonly _canvasView: CanvasView
- ) {
- this._antLineModelList = [];
-
- this._observerManager.requiredObserver('onAfterChangeActiveSheetObservable', 'core').add(() => {
- this._activeSheetId = this._currentUniverSheet.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
- this._makeUpdateSceneAntLineRect();
- });
- this._observerManager.requiredObserver('onSheetRenderDidMountObservable', 'core').add(() => {
- this._activeSheetId = this._currentUniverSheet.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
- this._makeUpdateSceneAntLineRect();
- });
- }
-
- /**
- * Remove AntLine By SheetId
- * @param sheetId
- */
- removeSheetAntLine(sheetId: string = this._activeSheetId): void {
- this._removeAntLineModelBySheetId(sheetId);
- this._makeUpdateSceneAntLineRect();
- }
-
- /**
- * Add New AntLine By SheetId
- * @param sheetId
- * @param range
- */
- addAntLineToSheet(range: IAntLineRange, sheetId: string = this._activeSheetId): void {
- const antLineModel = this._findAntLineModelBySheetId(sheetId, new AntLineModel(sheetId));
- antLineModel.addAntLine(new AntLine(range));
- this._saveOrUpdateAntLineModel(antLineModel);
- this._makeUpdateSceneAntLineRect();
- }
-
- /**
- * Return SheetView Scene
- * @returns
- */
- private getSheetViewScene(): Scene {
- return this._canvasView.getSheetView().getScene();
- }
-
- /**
- * Remove AntLineModel By SheetId
- * @param sheetId
- */
- private _removeAntLineModelBySheetId(sheetId: string): void {
- const index = this._antLineModelList.findIndex((model) => model.getSheetId() !== sheetId);
- if (index > -1) {
- this._antLineModelList.splice(index, 1);
- }
- }
-
- /**
- * Find AntLineModel By SheetId
- * @param sheetId
- * @returns
- */
- private _findAntLineModelBySheetId(sheetId: string, defaultValue: AntLineModel): AntLineModel {
- return this._antLineModelList.find((model) => model.getSheetId() === sheetId) ?? defaultValue;
- }
-
- /**
- * Save Or Update AntLineModel By SheetId
- * @param model
- * @returns
- */
- private _saveOrUpdateAntLineModel(model: AntLineModel): void {
- for (let i = 0; i < this._antLineModelList.length; i++) {
- const itemModel = this._antLineModelList[i];
- if (itemModel.getSheetId() === model.getSheetId()) {
- this._antLineModelList[i] = model;
- return;
- }
- }
- this._antLineModelList.push(model);
- }
-
- /**
- * Create A Sheet AntLine Rect
- * @param sheetId
- * @param range
- */
- private _createAntLineRectBySheetIdAndRange(sheetId: string, range: IAntLineRange): Rect {
- let workbook = this._currentUniverSheet.getCurrentUniverSheetInstance().getWorkBook();
- let worksheet = workbook.getSheetBySheetId(sheetId);
-
- if (worksheet == null) {
- throw new Error(`not found sheet from id: ${sheetId}`);
- }
-
- let rowTitleWidth = worksheet.getConfig().rowTitle.width;
- let columnTitleHeight = worksheet.getConfig().columnTitle.height;
-
- let rowManager = worksheet.getRowManager();
- let columnManager = worksheet.getColumnManager();
-
- let totalHeight = 0;
- let totalWidth = 0;
- for (let i = range.startRow; i < range.endRow; i++) {
- totalHeight += rowManager.getRowHeight(i);
- }
- for (let i = range.startColumn; i < range.endColumn; i++) {
- totalWidth += columnManager.getColumnWidth(i);
- }
-
- let offsetLeft = 0;
- let offsetTop = 0;
- for (let i = 0; i <= range.startRow - 1; i++) {
- offsetTop += rowManager.getRowHeight(i);
- }
- for (let i = 0; i <= range.startColumn - 1; i++) {
- offsetLeft += columnManager.getColumnWidth(i);
- }
-
- return new Rect(ANT_LINE_MANAGER_KEY.AntLine, {
- stroke: 'red',
- strokeWidth: 2,
- left: offsetLeft + rowTitleWidth,
- top: offsetTop + columnTitleHeight,
- height: totalHeight,
- width: totalWidth,
- strokeDashArray: [5],
- evented: false,
- });
- }
-
- /**
- * Delete AntLine Canvas UI
- */
- private _deleteSceneAllAntLineRect(): void {
- for (let i = 0; i < this._antLineModelList.length; i++) {
- let antLineModel = this._antLineModelList[i];
- let antLineList = antLineModel.getAntLineList();
- for (let j = 0; j < antLineList.length; j++) {
- let antLine = antLineList[j];
- let antRect = antLine.getRect();
- if (antRect) {
- this.getSheetViewScene().removeObject(antRect);
- }
- }
- }
- }
-
- /**
- * Make Update AntLine Canvas UI
- */
- private _makeUpdateSceneAntLineRect(): void {
- this._deleteSceneAllAntLineRect();
- for (let i = 0; i < this._antLineModelList.length; i++) {
- let antLineModel = this._antLineModelList[i];
- let antLineList = antLineModel.getAntLineList();
- if (antLineModel.getSheetId() !== this._activeSheetId) {
- continue;
- }
- for (let j = 0; j < antLineList.length; j++) {
- let antLine = antLineList[j];
- let antRect = this._createAntLineRectBySheetIdAndRange(antLineModel.getSheetId(), antLine.getRange());
- antLine.setRect(antRect);
- console.log(antRect);
- this.getSheetViewScene().addObject(antRect);
- }
- }
- }
-}
diff --git a/packages/base-sheets/src/Controller/CellEditorController.ts b/packages/base-sheets/src/Controller/CellEditorController.ts
index 40a7fe0fa4..7fe8a725d6 100644
--- a/packages/base-sheets/src/Controller/CellEditorController.ts
+++ b/packages/base-sheets/src/Controller/CellEditorController.ts
@@ -1,7 +1,8 @@
-import { Direction, handleJsonToDom, ICellData, ICurrentUniverService, IDocumentData, IRangeData, IStyleData, Nullable } from '@univerjs/core';
+import { Direction, handleJsonToDom, ICellData, ICommandService, ICurrentUniverService, IDocumentData, IRangeData, IStyleData, Nullable } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
-import { ISelectionManager } from '../Services/tokens';
-import { SelectionManager } from './Selection';
+import { SetSelectionsOperation } from '../Commands/Operations/selection.operation';
+import { SelectionManagerService } from '../Services/selection-manager.service';
/**
* Cell Editor
@@ -12,7 +13,13 @@ export class CellEditorController {
// current edit cell
currentEditRangeData: IRangeData;
- constructor(@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService, @ISelectionManager private readonly _selectionManager: SelectionManager) {}
+ constructor(
+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @ICommandService private readonly _commandService: ICommandService
+ ) {
+ this._commandService.registerCommand(SetSelectionsOperation);
+ }
setEditMode(value: boolean) {
this.isEditMode = value;
@@ -23,16 +30,15 @@ export class CellEditorController {
}
setCurrentEditRangeData() {
- const currentCell = this._selectionManager.getCurrentCellModel();
+ const currentCell = this._selectionManagerService.getLast()?.cellRange;
if (!currentCell) return;
let row;
let column;
if (currentCell.isMerged) {
- const mergeInfo = currentCell.mergeInfo;
- row = mergeInfo.startRow;
- column = mergeInfo.startColumn;
+ row = currentCell.startRow;
+ column = currentCell.startColumn;
} else {
row = currentCell.row;
column = currentCell.column;
@@ -52,6 +58,9 @@ export class CellEditorController {
setCurrentEditRangeValue(cell: ICellData) {
// only one selection
+ if (this.currentEditRangeData == null) {
+ return;
+ }
const { startRow, startColumn, endRow, endColumn } = this.currentEditRangeData;
const range = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getRange(startRow, startColumn, endRow, endColumn);
@@ -59,8 +68,7 @@ export class CellEditorController {
}
getSelectionValue(): string {
- const range = this._selectionManager.getActiveRange();
- if (!range) return '';
+ const range = this.getActiveRange();
const value = range && range.getDisplayValue();
if (typeof value === 'string') {
@@ -73,11 +81,11 @@ export class CellEditorController {
}
getSelectionStyle(): Nullable<IStyleData> {
- return this._selectionManager.getActiveRange()?.getTextStyle();
+ return this.getActiveRange()?.getTextStyle();
}
setSelectionValue(value: IDocumentData | string) {
- const range = this._selectionManager.getActiveRange();
+ const range = this.getActiveRange();
if (!range) return;
if (typeof value === 'string') {
@@ -88,6 +96,19 @@ export class CellEditorController {
}
}
+ getActiveRange() {
+ const cellRange = this._selectionManagerService.getLast()?.cellRange;
+ if (!cellRange) return;
+ let { row, column } = cellRange;
+
+ if (cellRange.isMerged) {
+ row = cellRange.startRow;
+ column = cellRange.startColumn;
+ }
+
+ return this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getRange(row, column);
+ }
+
handleBackSpace() {}
handleDirection(direction: Direction) {
diff --git a/packages/base-sheets/src/Controller/Selection/ColumnTitleController.ts b/packages/base-sheets/src/Controller/Selection/ColumnTitleController.ts
deleted file mode 100644
index d4214d85d4..0000000000
--- a/packages/base-sheets/src/Controller/Selection/ColumnTitleController.ts
+++ /dev/null
@@ -1,196 +0,0 @@
-import { Inject } from '@wendellhu/redi';
-import { ICurrentUniverService, Nullable } from '@univerjs/core';
-import { CURSOR_TYPE, Group, IMouseEvent, IPointerEvent, Rect } from '@univerjs/base-render';
-import { DragLineController, DragLineDirection } from './DragLineController';
-import { CanvasView } from '../../View';
-import { IColumnTitleControllerHandlers } from './Shared';
-
-export class ColumnTitleController {
- private _leftTopWidth: number;
-
- private _startOffsetX: number = 0;
-
- private _startOffsetY: number = 0;
-
- private _index: number = 0;
-
- private _currentWidth: number = 0;
-
- private _highlightItem: Group;
-
- private _content: Rect;
-
- private _Item: Rect;
-
- private handlers: IColumnTitleControllerHandlers | null = null;
-
- constructor(
- @Inject(CanvasView) private readonly _canvasView: CanvasView,
- @Inject(DragLineController) private readonly _dragLineController: DragLineController,
- @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService
- ) {
- const sheetView = this._canvasView.getSheetView();
- this._leftTopWidth = sheetView.getSpreadsheetLeftTopPlaceholder().getState().width;
- // 创建高亮item
- this._content = new Rect('HighLightContent', {
- width: 0,
- height: sheetView.getSpreadsheetSkeleton().columnTitleHeight,
- left: 0,
- fill: 'rgb(220,220,220,0.5)',
- });
- this._Item = new Rect('HighLightItem', {
- width: 5,
- height: sheetView.getSpreadsheetSkeleton().columnTitleHeight,
- left: 0,
- fill: 'rgb(220,220,220,0.5)',
- });
- this._highlightItem = new Group('HighLightColumnTitle', this._content, this._Item);
- this._highlightItem.hide();
-
- const scene = sheetView.getScene();
-
- scene.addObject(this._highlightItem, 3);
-
- this._initialize();
- }
-
- pointerDown(e: IPointerEvent | IMouseEvent) {
- const main = this._canvasView.getSheetView().getSpreadsheet();
- const { offsetX: evtOffsetX, offsetY: evtOffsetY } = e;
- this._startOffsetX = evtOffsetX;
- this._startOffsetY = evtOffsetY;
- const scrollXY = main.getAncestorScrollXY(this._startOffsetX, this._startOffsetY);
-
- // TODO 配合selection改造 @tony
- // const contentRef = this._manager.getPlugin().getSheetContainerControl().getContentRef();
- // const clientX = e.clientX + scrollXY.x - this._leftTopWidth - contentRef.current!.getBoundingClientRect().left;
- const clientX = 100;
- const columnWidthAccumulation = main.getSkeleton()?.columnWidthAccumulation ?? [];
-
- for (let i = 0; i < columnWidthAccumulation?.length; i++) {
- if (columnWidthAccumulation[i] >= clientX) {
- this._index = i;
- break;
- }
- }
- // 当前列宽度
- this._currentWidth = columnWidthAccumulation[0];
- if (this._index) {
- this._currentWidth = columnWidthAccumulation[this._index] - columnWidthAccumulation[this._index - 1];
- }
- // 显示拖动线
- if (columnWidthAccumulation[this._index] - clientX <= 5) {
- const end = columnWidthAccumulation[this._index] + this._leftTopWidth;
- const start = (this._index ? columnWidthAccumulation[this._index - 1] : 0) + this._leftTopWidth;
-
- this._dragLineController.create({
- direction: DragLineDirection.VERTICAL,
- end,
- start,
- dragUp: (width, e) => {
- this.setColumnWidth(width);
- this.highlightColumnTitle(e);
- },
- });
- this._dragLineController.dragDown(e);
- }
- // 高亮当前列
- this.highlightColumn();
- }
-
- setColumnWidth(width: Nullable<number>) {
- const sheet = this._currentUniverService.getCurrentUniverSheetInstance()?.getWorkBook().getActiveSheet();
- if (width === null) {
- sheet.setColumnWidth(this._index, 1, 5);
- } else {
- sheet.setColumnWidth(this._index, 1, width! + this._currentWidth);
- }
- this.highlightColumn();
- }
-
- setHandlers(handlers: IColumnTitleControllerHandlers): void {
- this.handlers = handlers;
- }
-
- highlightColumn() {
- this.handlers?.clearSelectionControls();
- const sheet = this._currentUniverService.getCurrentUniverSheetInstance()?.getWorkBook().getActiveSheet();
- this.handlers?.addControlToCurrentByRangeData(
- {
- startRow: 0,
- startColumn: this._index,
- endColumn: this._index,
- endRow: sheet.getRowCount() - 1,
- },
- {
- row: 0,
- column: this._index,
- }
- );
- }
-
- highlightColumnTitle(e: IPointerEvent | IMouseEvent) {
- const main = this._canvasView.getSheetView().getSpreadsheet();
- const { offsetX: evtOffsetX, offsetY: evtOffsetY } = e;
- this._startOffsetX = evtOffsetX;
- this._startOffsetY = evtOffsetY;
- const scrollXY = main.getAncestorScrollXY(this._startOffsetX, this._startOffsetY);
-
- // TODO 配合selection改造 @tony
- // const contentRef = this._manager.getPlugin().getSheetContainerControl().getContentRef();
- // const clientX = e.clientX + scrollXY.x - this._leftTopWidth - contentRef.current!.getBoundingClientRect().left;
- const clientX = 100;
- const columnWidthAccumulation = main.getSkeleton()?.columnWidthAccumulation ?? [];
-
- for (let i = 0; i < columnWidthAccumulation?.length; i++) {
- if (columnWidthAccumulation[i] >= clientX) {
- this._index = i;
- break;
- }
- }
-
- // 当前列宽度
- this._currentWidth = columnWidthAccumulation[0];
- let left = this._leftTopWidth;
- if (this._index) {
- this._currentWidth = columnWidthAccumulation[this._index] - columnWidthAccumulation[this._index - 1];
- left = this._leftTopWidth + columnWidthAccumulation[this._index - 1];
- }
-
- this._content.transformByState({
- width: this._currentWidth - 5,
- });
-
- this._Item.transformByState({
- left: this._currentWidth - 5,
- });
-
- this._highlightItem.transformByState({
- width: this._currentWidth,
- left,
- });
- this._highlightItem.show();
- }
-
- // 拖拽图标
- private _initialize() {
- this._highlightItem.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {
- this._highlightItem.show();
- });
- this._highlightItem.onPointerMoveObserver.add((evt: IPointerEvent | IMouseEvent) => {
- this._highlightItem.show();
- });
- this._highlightItem.onPointerLeaveObserver.add((evt: IPointerEvent | IMouseEvent) => {
- this._highlightItem.hide();
- });
- this._Item.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {
- this._Item.cursor = CURSOR_TYPE.COLUMN_RESIZE;
- });
- this._Item.onPointerLeaveObserver.add((evt: IPointerEvent | IMouseEvent) => {
- this._Item.resetCursor();
- });
- this._Item.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent) => {
- this.pointerDown(evt);
- });
- }
-}
diff --git a/packages/base-sheets/src/Controller/Selection/DragLineController.ts b/packages/base-sheets/src/Controller/Selection/DragLineController.ts
deleted file mode 100644
index fbb0745a4b..0000000000
--- a/packages/base-sheets/src/Controller/Selection/DragLineController.ts
+++ /dev/null
@@ -1,179 +0,0 @@
-import { CURSOR_TYPE, Group, IMouseEvent, IPointerEvent, Rect } from '@univerjs/base-render';
-import { Nullable, Observer } from '@univerjs/core';
-import { Inject } from '@wendellhu/redi';
-import { CanvasView } from '../../View';
-
-enum DRAG_LINE_KEY {
- lineMain = '__SpreadsheetDragLineMain__',
- lineContent = '__SpreadsheetDragLineContent__',
- line = '__SpreadsheetDragLine__',
-}
-
-const DEFAULT_DRAG_LINE_CONFIG = {
- strokeColor: 'rgb(1,136,251)',
- strokeWidth: 1,
- fillStrokeWidth: 5,
-};
-
-export enum DragLineDirection {
- VERTICAL,
- HORIZONTAL,
-}
-
-interface State {
- left?: number;
- top?: number;
- distance: number;
-}
-
-interface Option {
- direction: DragLineDirection;
- end: number; // 当前列/行尾距离屏幕距离
- start: number; //当前列/行首距离屏幕距离
- dragUp: (distance: Nullable<number>, e: IPointerEvent | IMouseEvent) => void;
-}
-
-export class DragLineController {
- private _dragLineControlMain: Rect;
-
- private _dragLineControlContent: Rect;
-
- private _dragLine: Group;
-
- private _moveObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
- private _upObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
- private _state: State;
-
- private _direction: DragLineDirection;
-
- private _end: number; // 初始线距离屏幕的距离
-
- private _start: number;
-
- private _dragUp: (distance: Nullable<number>, e: IPointerEvent | IMouseEvent) => void;
-
- constructor(@Inject(CanvasView) private readonly _canvasView: CanvasView) {}
-
- getDragLine() {
- return this._dragLine;
- }
-
- create(option: Option) {
- const { direction, end, dragUp, start } = option;
- this._direction = direction;
- this._end = end;
- this._start = start;
- this._dragUp = dragUp;
-
- const skeleton = this._canvasView.getSheetView().getSpreadsheetColumnTitle().getSkeleton();
- if (direction) {
- const width = skeleton?.rowTitleWidth;
- const contentWidth = skeleton?.columnTotalWidth;
- this._dragLineControlMain = new Rect(DRAG_LINE_KEY.lineMain, {
- width,
- height: 5,
- top: this._end - 5,
- fill: DEFAULT_DRAG_LINE_CONFIG.strokeColor,
- });
-
- this._dragLineControlContent = new Rect(DRAG_LINE_KEY.lineContent, {
- width: contentWidth,
- height: 1,
- top: this._end - 1,
- left: width,
- fill: DEFAULT_DRAG_LINE_CONFIG.strokeColor,
- });
- } else {
- const height = skeleton?.columnTitleHeight;
- const contentHeight = skeleton?.rowTotalHeight;
- this._dragLineControlMain = new Rect(DRAG_LINE_KEY.lineMain, {
- width: DEFAULT_DRAG_LINE_CONFIG.fillStrokeWidth,
- height,
- left: this._end - 5,
- fill: DEFAULT_DRAG_LINE_CONFIG.strokeColor,
- });
-
- this._dragLineControlContent = new Rect(DRAG_LINE_KEY.lineContent, {
- width: DEFAULT_DRAG_LINE_CONFIG.strokeWidth,
- height: contentHeight,
- top: height,
- left: this._end - 1,
- fill: DEFAULT_DRAG_LINE_CONFIG.strokeColor,
- });
- }
-
- this._dragLine = new Group(DRAG_LINE_KEY.line, this._dragLineControlMain, this._dragLineControlContent);
-
- this._dragLine.hide();
-
- this._dragLine.evented = false;
-
- const scene = this._canvasView.getSheetView().getScene();
-
- scene.addObject(this._dragLine, 3);
- }
-
- dragDown(e: IPointerEvent | IMouseEvent) {
- const scene = this._canvasView.getSheetView().getScene();
-
- scene.disableEvent();
-
- this._state = {
- distance: this._direction ? e.clientY : e.clientX,
- };
-
- this._dragLine.show();
-
- this._moveObserver = scene.onPointerMoveObserver.add((e: IPointerEvent | IMouseEvent) => {
- this.dragMoving(e);
- });
-
- this._upObserver = scene.onPointerUpObserver.add((e: IPointerEvent | IMouseEvent) => {
- this.dragUp(e);
- scene.onPointerMoveObserver.remove(this._moveObserver);
- scene.onPointerUpObserver.remove(this._upObserver);
- scene.enableEvent();
- });
- }
-
- dragMoving(e: IPointerEvent | IMouseEvent) {
- if (this._direction) {
- this._dragLine.cursor = CURSOR_TYPE.ROW_RESIZE;
- if (e.clientY < this._state.distance && this._state.distance - e.clientY >= this._end - this._start - 5) {
- //留一丝空隙
- return;
- }
- this._dragLine.transformByState({
- top: e.clientY - this._state.distance,
- });
- } else {
- this._dragLine.cursor = CURSOR_TYPE.COLUMN_RESIZE;
- if (e.clientX < this._state.distance && this._state.distance - e.clientX >= this._end - this._start - 5) {
- //留一丝空隙
- return;
- }
- this._dragLine.transformByState({
- left: e.clientX - this._state.distance,
- });
- }
- }
-
- dragUp(e: IPointerEvent | IMouseEvent) {
- let distance;
- if (this._direction) {
- distance = e.clientY - this._state.distance;
- if (e.clientY < this._state.distance && this._state.distance - e.clientY >= this._end - this._start - 5) {
- distance = null;
- }
- } else {
- distance = e.clientX - this._state.distance;
- if (e.clientX < this._state.distance && this._state.distance - e.clientX >= this._end - this._start - 5) {
- distance = null;
- }
- }
- this._dragUp(distance, e);
- this._dragLine.dispose();
- }
-}
\ No newline at end of file
diff --git a/packages/base-sheets/src/Controller/Selection/RowTitleController.ts b/packages/base-sheets/src/Controller/Selection/RowTitleController.ts
deleted file mode 100644
index 82a6875126..0000000000
--- a/packages/base-sheets/src/Controller/Selection/RowTitleController.ts
+++ /dev/null
@@ -1,196 +0,0 @@
-import { CURSOR_TYPE, Group, IMouseEvent, IPointerEvent, Rect } from '@univerjs/base-render';
-import { ICurrentUniverService, Nullable } from '@univerjs/core';
-import { Inject } from '@wendellhu/redi';
-import { DragLineController, DragLineDirection } from './DragLineController';
-import { CanvasView } from '../../View';
-import { IColumnTitleControllerHandlers } from './Shared';
-
-export class RowTitleController {
- private _leftTopHeight: number;
-
- private _startOffsetX: number = 0;
-
- private _startOffsetY: number = 0;
-
- private _index: number = 0;
-
- private _currentHeight: number = 0;
-
- private _highlightItem: Group;
-
- private _content: Rect;
-
- private _Item: Rect;
-
- private handlers: IColumnTitleControllerHandlers | null = null;
-
- constructor(
- @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
- @Inject(CanvasView) private readonly _canvasView: CanvasView,
- @Inject(DragLineController) private readonly _dragLineController: DragLineController
- ) {
- const sheetView = this._canvasView.getSheetView();
- this._leftTopHeight = sheetView.getSpreadsheetLeftTopPlaceholder().getState().height;
-
- const width = sheetView.getSpreadsheetSkeleton().rowTitleWidth;
- // 创建高亮item
- this._content = new Rect('RowTitleContent', {
- width,
- height: 0,
- top: 0,
- fill: 'rgb(220,220,220,0.5)',
- });
- this._Item = new Rect('RowTitleItem', {
- width,
- height: 5,
- top: 0,
- fill: 'rgb(220,220,220,0.5)',
- });
- this._highlightItem = new Group('RowTitleGroup', this._content, this._Item);
- this._highlightItem.hide();
-
- const scene = sheetView.getScene();
-
- scene.addObject(this._highlightItem, 3);
-
- this._initialize();
- }
-
- setHandlers(handlers: IColumnTitleControllerHandlers): void {
- this.handlers = handlers;
- }
-
- pointerDown(e: IPointerEvent | IMouseEvent) {
- const main = this._canvasView.getSheetView().getSpreadsheet();
- const { offsetX: evtOffsetX, offsetY: evtOffsetY } = e;
- this._startOffsetX = evtOffsetX;
- this._startOffsetY = evtOffsetY;
- const scrollXY = main.getAncestorScrollXY(this._startOffsetX, this._startOffsetY);
-
- // TODO 配合selection改造 @tony
- // const contentRef = this._manager.getPlugin().getSheetContainerControl().getContentRef();
- // const clientY = e.clientY + scrollXY.y - this._leftTopHeight - contentRef.current!.getBoundingClientRect().top;
- const clientY = 100;
- const rowHeightAccumulation = main.getSkeleton()?.rowHeightAccumulation ?? [];
-
- for (let i = 0; i < rowHeightAccumulation?.length; i++) {
- if (rowHeightAccumulation[i] >= clientY) {
- this._index = i;
- break;
- }
- }
- // 当前列宽度
- this._currentHeight = rowHeightAccumulation[0];
- if (this._index) {
- this._currentHeight = rowHeightAccumulation[this._index] - rowHeightAccumulation[this._index - 1];
- }
-
- // 显示拖动线
- if (rowHeightAccumulation[this._index] - clientY <= 5) {
- const end = rowHeightAccumulation[this._index] + this._leftTopHeight;
- const start = (this._index ? rowHeightAccumulation[this._index - 1] : 0) + this._leftTopHeight;
-
- this._dragLineController.create({
- direction: DragLineDirection.HORIZONTAL,
- end,
- start,
- dragUp: this.setRowHeight.bind(this),
- });
- this._dragLineController.dragDown(e);
- }
- // 高亮当前行
- this.highlightRow();
- }
-
- setRowHeight(height: Nullable<number>) {
- const sheet = this._currentUniverService.getCurrentUniverSheetInstance()?.getWorkBook().getActiveSheet();
- if (height === null) {
- sheet.setRowHeights(this._index, 1, 5);
- } else {
- sheet.setRowHeights(this._index, 1, height! + this._currentHeight);
- }
- this.highlightRow();
- }
-
- highlightRow() {
- this.handlers?.clearSelectionControls();
- const sheet = this._currentUniverService.getCurrentUniverSheetInstance()?.getWorkBook().getActiveSheet();
- this.handlers?.addControlToCurrentByRangeData(
- {
- startRow: this._index,
- startColumn: 0,
- endColumn: sheet.getColumnCount() - 1,
- endRow: this._index,
- },
- {
- row: this._index,
- column: 0,
- }
- );
- }
-
- highlightRowTitle(e: IPointerEvent | IMouseEvent) {
- const main = this._canvasView.getSheetView().getSpreadsheet();
- const { offsetX: evtOffsetX, offsetY: evtOffsetY } = e;
- this._startOffsetX = evtOffsetX;
- this._startOffsetY = evtOffsetY;
- const scrollXY = main.getAncestorScrollXY(this._startOffsetX, this._startOffsetY);
-
- // TODO 配合selection改造 @tony
- // const contentRef = this._manager.getPlugin().getSheetContainerControl().getContentRef();
- // const clientY = e.clientY + scrollXY.y - this._leftTopHeight - contentRef.current!.getBoundingClientRect().top;
- const clientY = 100;
- const rowHeightAccumulation = main.getSkeleton()?.rowHeightAccumulation ?? [];
-
- for (let i = 0; i < rowHeightAccumulation?.length; i++) {
- if (rowHeightAccumulation[i] >= clientY) {
- this._index = i;
- break;
- }
- }
- // 当前行高
- this._currentHeight = rowHeightAccumulation[0];
- let top = this._leftTopHeight;
- if (this._index) {
- this._currentHeight = rowHeightAccumulation[this._index] - rowHeightAccumulation[this._index - 1];
- top = this._leftTopHeight + rowHeightAccumulation[this._index - 1];
- }
-
- this._content.transformByState({
- height: this._currentHeight - 5,
- });
-
- this._Item.transformByState({
- top: this._currentHeight - 5,
- });
-
- this._highlightItem.transformByState({
- height: this._currentHeight,
- top,
- });
-
- this._highlightItem.show();
- }
-
- // 拖拽图标
- private _initialize() {
- this._highlightItem.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {
- this._highlightItem.show();
- });
- this._highlightItem.onPointerMoveObserver.add((evt: IPointerEvent | IMouseEvent) => {
- this._highlightItem.show();
- });
- this._highlightItem.onPointerLeaveObserver.add((evt: IPointerEvent | IMouseEvent) => {
- this._highlightItem.hide();
- });
- this._Item.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {
- this._Item.cursor = CURSOR_TYPE.ROW_RESIZE;
- });
- this._Item.onPointerLeaveObserver.add((evt: IPointerEvent | IMouseEvent) => {
- this._Item.resetCursor();
- });
- this._Item.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent) => {
- this.pointerDown(evt);
- });
- }
-}
diff --git a/packages/base-sheets/src/Controller/Selection/SelectionControlDragDrop.ts b/packages/base-sheets/src/Controller/Selection/SelectionControlDragDrop.ts
deleted file mode 100644
index 415c03cb91..0000000000
--- a/packages/base-sheets/src/Controller/Selection/SelectionControlDragDrop.ts
+++ /dev/null
@@ -1,376 +0,0 @@
-import { CURSOR_TYPE, Group, IMouseEvent, IPointerEvent, Rect, ScrollTimer } from '@univerjs/base-render';
-import { Inject, Injector } from '@wendellhu/redi';
-import { Direction, ICellInfo, ISelection, makeCellToSelection, Nullable, Observer } from '@univerjs/core';
-import { SelectionModel } from '../../Model';
-import { DEFAULT_SELECTION_CONFIG, SELECTION_TYPE } from './SelectionController';
-import { CanvasView } from '../../View';
-
-enum SELECTION_DRAG_KEY {
- Selection = '__SelectionDragShape__',
- top = '__TopDragControl__',
- bottom = '__BottomDragControl__',
- left = '__LeftDragControl__',
- right = '__RightDragControl__',
-}
-
-interface IPositionOffset {
- left: number;
- right: number;
- top: number;
- bottom: number;
-}
-
-export interface ISelectionControlDragDropHandler {
- leftControl: Rect;
- rightControl: Rect;
- topControl: Rect;
- bottomControl: Rect;
- fillControl: Rect;
-
- update(newSelectionRange: ISelection, highlight: Nullable<ICellInfo>): void;
-}
-
-export class SelectionControlDragAndDrop {
- private _leftDragControl: Rect;
-
- private _rightDragControl: Rect;
-
- private _topDragControl: Rect;
-
- private _bottomDragControl: Rect;
-
- private _selectionDragShape: Group;
-
- private _zIndex: number;
-
- private _model: SelectionModel;
-
- private _oldSelectionRange: ISelection;
-
- private _startOffsetX: number = 0;
-
- private _startOffsetY: number = 0;
-
- private _cellPositionOffset: IPositionOffset;
-
- private _moveObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
- private _upObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
- constructor(
- zIndex: number,
- model: SelectionModel,
- private readonly _handlers: ISelectionControlDragDropHandler,
- @Inject(Injector) private readonly _injector: Injector,
- @Inject(CanvasView) private readonly _canvasView: CanvasView
- ) {
- this._zIndex = zIndex + 1;
- this._model = model;
-
- this._initialize();
- }
-
- static create(injector: Injector, zIndex: number, model: SelectionModel, handler: ISelectionControlDragDropHandler) {
- return injector.createInstance(SelectionControlDragAndDrop, zIndex, model, handler);
- }
-
- dragEventInitial() {
- // TODO ...
- }
-
- // eslint-disable-next-line max-lines-per-function
- dragDown(evt: IPointerEvent | IMouseEvent, direction: Direction) {
- const main = this._canvasView.getSheetView().getSpreadsheet();
-
- // reset model
- const selection = this._model.getValue().selection;
- this._model = this._injector.createInstance(SelectionModel, SELECTION_TYPE.NORMAL);
- // this._model.setValue(selection);
-
- // update control
- // this._updateControl();
-
- const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
- this._startOffsetX = evtOffsetX;
- this._startOffsetY = evtOffsetY;
- const scrollXY = main.getAncestorScrollXY(this._startOffsetX, this._startOffsetY);
-
- // Subtract the border width to make the calculation of selected cells more accurate
- let cellInfo = null;
- switch (direction) {
- case Direction.LEFT:
- cellInfo = main.calculateCellIndexByPosition(evtOffsetX + DEFAULT_SELECTION_CONFIG.strokeWidth, evtOffsetY, scrollXY);
- break;
- case Direction.UP:
- cellInfo = main.calculateCellIndexByPosition(evtOffsetX, evtOffsetY + DEFAULT_SELECTION_CONFIG.strokeWidth, scrollXY);
- break;
- case Direction.RIGHT:
- cellInfo = main.calculateCellIndexByPosition(evtOffsetX - DEFAULT_SELECTION_CONFIG.strokeWidth, evtOffsetY, scrollXY);
- break;
- case Direction.DOWN:
- cellInfo = main.calculateCellIndexByPosition(evtOffsetX, evtOffsetY - DEFAULT_SELECTION_CONFIG.strokeWidth, scrollXY);
- break;
-
- default:
- break;
- }
-
- const actualSelection = makeCellToSelection(cellInfo);
- if (!actualSelection) {
- return false;
- }
-
- const { startRow, startColumn, endColumn, endRow, startY, endY, startX, endX } = actualSelection;
-
- const startSelectionRange = {
- startColumn,
- startRow,
- endColumn,
- endRow,
- startY,
- endY,
- startX,
- endX,
- };
-
- this._oldSelectionRange = startSelectionRange;
-
- // calculate active cell in selection position
- this._cellPositionOffset = {
- top: startSelectionRange.startRow - this._model.startRow,
- bottom: this._model.endRow - startSelectionRange.endRow,
- left: startSelectionRange.startColumn - this._model.startColumn,
- right: this._model.endColumn - startSelectionRange.endColumn,
- };
-
- const scene = this._canvasView.getSheetView().getScene();
-
- scene.disableEvent();
-
- const scrollTimer = ScrollTimer.create(scene);
- scrollTimer.startScroll(evtOffsetX, evtOffsetY);
-
- this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
- this.dragMoving(moveEvt);
- const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
- scrollTimer.scrolling(moveOffsetX, moveOffsetY, () => {
- this.dragMoving(moveEvt);
- });
- });
-
- this._upObserver = scene.onPointerUpObserver.add((upEvt: IPointerEvent | IMouseEvent) => {
- this.dragUp();
- scene.onPointerMoveObserver.remove(this._moveObserver);
- scene.onPointerUpObserver.remove(this._upObserver);
- scene.enableEvent();
- scrollTimer.stopScroll();
- });
- }
-
- dragMoving(moveEvt: IPointerEvent | IMouseEvent) {
- const main = this._canvasView.getSheetView().getSpreadsheet();
- const { offsetX: moveOffsetX, offsetY: moveOffsetY, clientX, clientY } = moveEvt;
-
- const scrollXY = main.getAncestorScrollXY(this._startOffsetX, this._startOffsetY);
- const moveCellInfo = main.calculateCellIndexByPosition(moveOffsetX, moveOffsetY, scrollXY);
- const moveActualSelection = makeCellToSelection(moveCellInfo);
-
- if (!moveActualSelection) {
- return false;
- }
- const { startRow: moveStartRow, startColumn: moveStartColumn, endColumn: moveEndColumn, endRow: moveEndRow, startX, startY, endX, endY } = moveActualSelection;
-
- const newSelectionRange: ISelection = {
- startColumn: moveStartColumn,
- startRow: moveStartRow,
- endColumn: moveEndColumn,
- endRow: moveEndRow,
- startY: startY || 0,
- endY: endY || 0,
- startX: startX || 0,
- endX: endX || 0,
- };
- // when the selection changes
- const { startRow: oldStartRow, endRow: oldEndRow, startColumn: oldStartColumn, endColumn: oldEndColumn } = this._oldSelectionRange;
-
- if (oldStartColumn !== moveStartColumn || oldStartRow !== moveStartRow || oldEndColumn !== moveEndColumn || oldEndRow !== moveEndRow) {
- this._oldSelectionRange = newSelectionRange;
-
- // Calculate the position of the selection based on the position of the cell selected when clicking
- const { left, right, top, bottom } = this._cellPositionOffset;
-
- const startRowTop = moveStartRow - top;
- const endRowBottom = moveEndRow + bottom;
- const startColumnLeft = moveStartColumn - left;
- const endColumnRight = moveEndColumn + right;
-
- // Boundary detection
- if (startRowTop < 0 || endRowBottom < 0 || startColumnLeft < 0 || endColumnRight < 0) {
- return;
- }
- const newSelection = {
- startRow: startRowTop,
- endRow: endRowBottom,
- startColumn: startColumnLeft,
- endColumn: endColumnRight,
- };
-
- const startCell = main.getNoMergeCellPositionByIndex(newSelection.startRow, newSelection.startColumn);
- const endCell = main.getNoMergeCellPositionByIndex(newSelection.endRow, newSelection.endColumn);
-
- const newSelectionPosition = Object.assign(newSelection, {
- startY: startCell?.startY || 0,
- endY: endCell?.endY || 0,
- startX: startCell?.startX || 0,
- endX: endCell?.endX || 0,
- });
-
- this._model.setValue(newSelectionPosition);
-
- // this._updateControl();
- }
- }
-
- dragUp() {
- const main = this._canvasView.getSheetView().getSpreadsheet();
-
- this.hide();
-
- const { selection } = this._model.getValue();
-
- // By default, the upper left corner is the active cell
- const cell = main.getCellByIndex(selection.startRow, selection.startColumn);
-
- // TODO@huwenzhao: add a handler here
- this._handlers.update(selection, cell);
- }
-
- _updateControl() {
- const { startX, startY, endX, endY } = this._model;
-
- this._leftDragControl.resize(undefined, endY - startY);
- this._rightDragControl.transformByState({
- height: endY - startY,
- left: endX - startX - DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
- });
- this._topDragControl.resize(endX - startX + DEFAULT_SELECTION_CONFIG.strokeWidth);
- this._bottomDragControl.transformByState({
- width: endX - startX + DEFAULT_SELECTION_CONFIG.strokeWidth,
- top: endY - startY - DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
- });
-
- this._selectionDragShape.show();
- this._selectionDragShape.translate(startX, startY);
-
- this._selectionDragShape.makeDirty(true);
- }
-
- hide() {
- this._selectionDragShape.hide();
- this._selectionDragShape.makeDirty(true);
- }
-
- dispose() {
- this._leftDragControl.dispose();
- this._rightDragControl.dispose();
- this._topDragControl.dispose();
- this._bottomDragControl.dispose();
- this._selectionDragShape.dispose();
- }
-
- remove() {
- const { leftControl, rightControl, topControl, bottomControl } = this._handlers;
-
- leftControl.onPointerEnterObserver.clear();
- leftControl.onPointerLeaveObserver.clear();
- rightControl.onPointerEnterObserver.clear();
- rightControl.onPointerLeaveObserver.clear();
- topControl.onPointerEnterObserver.clear();
- topControl.onPointerLeaveObserver.clear();
- bottomControl.onPointerEnterObserver.clear();
- bottomControl.onPointerLeaveObserver.clear();
- }
-
- private _initialize() {
- const { leftControl, rightControl, topControl, bottomControl, fillControl } = this._handlers;
-
- leftControl.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {
- leftControl.cursor = CURSOR_TYPE.MOVE;
- });
-
- leftControl.onPointerLeaveObserver.add((evt: IPointerEvent | IMouseEvent) => {
- leftControl.resetCursor();
- });
-
- rightControl.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {
- rightControl.cursor = CURSOR_TYPE.MOVE;
- });
-
- rightControl.onPointerLeaveObserver.add((evt: IPointerEvent | IMouseEvent) => {
- rightControl.resetCursor();
- });
-
- topControl.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {
- topControl.cursor = CURSOR_TYPE.MOVE;
- });
-
- topControl.onPointerLeaveObserver.add((evt: IPointerEvent | IMouseEvent) => {
- topControl.resetCursor();
- });
-
- bottomControl.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {
- bottomControl.cursor = CURSOR_TYPE.MOVE;
- });
-
- bottomControl.onPointerLeaveObserver.add((evt: IPointerEvent | IMouseEvent) => {
- bottomControl.resetCursor();
- });
-
- bottomControl.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent) => {
- this.dragDown(evt, Direction.DOWN);
- });
-
- bottomControl.onPointerUpObserver.add((evt: IPointerEvent | IMouseEvent) => {
- bottomControl.resetCursor();
- });
-
- // init drag render box
- const zIndex = this._zIndex;
- this._leftDragControl = new Rect(SELECTION_DRAG_KEY.left + zIndex, {
- top: 0,
- left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
- width: DEFAULT_SELECTION_CONFIG.strokeWidth * 2,
- fill: DEFAULT_SELECTION_CONFIG.strokeColor,
- zIndex,
- });
- this._rightDragControl = new Rect(SELECTION_DRAG_KEY.right + zIndex, {
- width: DEFAULT_SELECTION_CONFIG.strokeWidth * 2,
- fill: DEFAULT_SELECTION_CONFIG.strokeColor,
- zIndex,
- });
- this._topDragControl = new Rect(SELECTION_DRAG_KEY.top + zIndex, {
- top: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
- left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
- height: DEFAULT_SELECTION_CONFIG.strokeWidth * 2,
- fill: DEFAULT_SELECTION_CONFIG.strokeColor,
- zIndex,
- });
- this._bottomDragControl = new Rect(SELECTION_DRAG_KEY.bottom + zIndex, {
- height: DEFAULT_SELECTION_CONFIG.strokeWidth * 2,
- fill: DEFAULT_SELECTION_CONFIG.strokeColor,
- left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
- zIndex,
- });
-
- this._selectionDragShape = new Group(SELECTION_DRAG_KEY.Selection + zIndex, this._leftDragControl, this._rightDragControl, this._topDragControl, this._bottomDragControl);
-
- // this._selectionDragShape.visible = false;
-
- this._selectionDragShape.evented = false;
-
- this._selectionDragShape.zIndex = zIndex;
-
- const scene = this._canvasView.getSheetView().getScene();
- scene.addObject(this._selectionDragShape);
- }
-}
\ No newline at end of file
diff --git a/packages/base-sheets/src/Controller/Selection/SelectionControlFill.ts b/packages/base-sheets/src/Controller/Selection/SelectionControlFill.ts
deleted file mode 100644
index eb10438a5a..0000000000
--- a/packages/base-sheets/src/Controller/Selection/SelectionControlFill.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { CURSOR_TYPE, IMouseEvent, IPointerEvent, Rect } from '@univerjs/base-render';
-import { Injector } from '@univerjs/core';
-
-export interface ISelectionControlHandler {
- fillControl: Rect;
-}
-
-export class SelectionControlFill {
- constructor(private readonly _handler: ISelectionControlHandler) {
- this._initialize();
- }
-
- static create(injector: Injector, handler: ISelectionControlHandler) {
- return injector.createInstance(SelectionControlFill, handler);
- }
-
- remove() {
- const { fillControl } = this._handler;
- fillControl.onPointerEnterObserver.clear();
- fillControl.onPointerLeaveObserver.clear();
- }
-
- private _initialize() {
- const { fillControl } = this._handler;
- fillControl.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {
- fillControl.cursor = CURSOR_TYPE.CROSSHAIR;
- });
-
- fillControl.onPointerLeaveObserver.add((evt: IPointerEvent | IMouseEvent) => {
- fillControl.resetCursor();
- });
- }
-}
diff --git a/packages/base-sheets/src/Controller/Selection/SelectionController.ts b/packages/base-sheets/src/Controller/Selection/SelectionController.ts
deleted file mode 100644
index 7b3134b838..0000000000
--- a/packages/base-sheets/src/Controller/Selection/SelectionController.ts
+++ /dev/null
@@ -1,457 +0,0 @@
-import { Rect, Group } from '@univerjs/base-render';
-import { Inject, Injector } from '@wendellhu/redi';
-import { Nullable, ISelection, ICellInfo } from '@univerjs/core';
-import { SelectionModel } from '../../Model/SelectionModel';
-import { SelectionControlDragAndDrop } from './SelectionControlDragDrop';
-import { SelectionControlFill } from './SelectionControlFill';
-import { CanvasView } from '../../View';
-
-// export enum DEFAULT_SELECTION_CONFIG {
-// strokeColor = 'rgb(1,136,251)',
-// backgroundColor = 'rgba(1,136,251, 0.1)',
-// strokeWidth = 2,
-// fillSideLength = 6,
-// fillStrokeLength = 1,
-// fillStrokeColor = 'rgb(255,255,255)',
-// }
-export const DEFAULT_SELECTION_CONFIG = {
- strokeColor: 'rgb(1,136,251)',
- backgroundColor: 'rgba(1,136,251, 0.1)',
- strokeWidth: 2,
- fillSideLength: 6,
- fillStrokeLength: 1,
- fillStrokeColor: 'rgb(255,255,255)',
-};
-
-export enum SELECTION_TYPE {
- NORMAL,
- ROW,
- COLUMN,
-}
-
-enum SELECTION_MANAGER_KEY {
- Selection = '__SpreadsheetSelectionShape__',
- top = '__SpreadsheetSelectionTopControl__',
- bottom = '__SpreadsheetSelectionBottomControl__',
- left = '__SpreadsheetSelectionShapeLeftControl__',
- right = '__SpreadsheetSelectionShapeRightControl__',
- backgroundTop = '__SpreadsheetSelectionBackgroundControlTop__',
- backgroundMiddleLeft = '__SpreadsheetSelectionBackgroundControlMiddleLeft__',
- backgroundMiddleRight = '__SpreadsheetSelectionBackgroundControlMiddleRight__',
- backgroundBottom = '__SpreadsheetSelectionBackgroundControlBottom__',
- fill = '__SpreadsheetSelectionFillControl__',
- lineMain = '__SpreadsheetDragLineMainControl__',
- lineContent = '__SpreadsheetDragLineContentControl__',
- line = '__SpreadsheetDragLineControl__',
-}
-
-/**
- * The main selection canvas component
- */
-export class SelectionController {
- private _leftControl: Rect;
-
- private _rightControl: Rect;
-
- private _topControl: Rect;
-
- private _bottomControl: Rect;
-
- private _backgroundControlTop: Rect;
-
- private _backgroundControlBottom: Rect;
-
- private _backgroundControlMiddleLeft: Rect;
-
- private _backgroundControlMiddleRight: Rect;
-
- private _fillControl: Rect;
-
- private _selectionShape: Group;
-
- private _selectionModel: SelectionModel;
-
- private _selectionDragAndDrop: SelectionControlDragAndDrop;
-
- private _selectionControlFill: SelectionControlFill;
-
- constructor(private _zIndex: number, @Inject(Injector) private readonly _injector: Injector, @Inject(CanvasView) private readonly _canvasView: CanvasView) {
- this._initialize();
- }
-
- get zIndex() {
- return this._zIndex;
- }
-
- get leftControl() {
- return this._leftControl;
- }
-
- get rightControl() {
- return this._rightControl;
- }
-
- get topControl() {
- return this._topControl;
- }
-
- get bottomControl() {
- return this._bottomControl;
- }
-
- get fillControl() {
- return this._fillControl;
- }
-
- get backgroundControlTop() {
- return this._backgroundControlTop;
- }
-
- get backgroundControlBottom() {
- return this._backgroundControlBottom;
- }
-
- get backgroundControlMiddleLeft() {
- return this._backgroundControlMiddleLeft;
- }
-
- get backgroundControlMiddleRight() {
- return this._backgroundControlMiddleRight;
- }
-
- get selectionShape() {
- return this._selectionShape;
- }
-
- get model() {
- return this._selectionModel;
- }
-
- static create(injector: Injector, zIndex: number) {
- return injector.createInstance(this, zIndex);
- }
-
- // static fromJson(zIndex: number, newSelectionRange: ISelection) {
- // const control = SelectionController.create(zIndex);
- // control.update(newSelectionRange);
- // return control;
- // }
-
- /**
- * just handle the view
- *
- * inner update
- */
- _updateControl() {
- const { startX, startY, endX, endY } = this._selectionModel;
-
- this.leftControl.resize(undefined, endY - startY);
- this.rightControl.transformByState({
- height: endY - startY,
- left: endX - startX - DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
- });
- this.topControl.resize(endX - startX + DEFAULT_SELECTION_CONFIG.strokeWidth);
- this.bottomControl.transformByState({
- width: endX - startX + DEFAULT_SELECTION_CONFIG.strokeWidth,
- top: endY - startY - DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
- });
-
- this.fillControl.translate(endX - startX - DEFAULT_SELECTION_CONFIG.fillSideLength / 2, endY - startY - DEFAULT_SELECTION_CONFIG.fillSideLength / 2);
-
- this._updateBackgroundControl();
- this._updateDragAndFill();
-
- this.selectionShape.show();
- this.selectionShape.translate(startX, startY);
-
- this.selectionShape.makeDirty(true);
- }
-
- update(newSelectionRange: ISelection, highlight: Nullable<ICellInfo>) {
- this._selectionModel.setValue(newSelectionRange, highlight);
- this._updateControl();
- }
-
- // /**
- // *When switching to the current sheet
- // *
- // * 1. Reinitialize the rendering component
- // * 2. Calculate the position based on the current skeleton
- // * 3. Update data
- // * 4. Trigger rendering
- // */
- // render() {
- // this._initialize();
-
- // let cellInfo = null;
- // const main = this._manager.getMainComponent();
- // const curCellRange = this._selectionModel.currentCell;
-
- // if (curCellRange) {
- // cellInfo = main.getCellByIndex(curCellRange.row, curCellRange.column);
- // }
-
- // const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = this._selectionModel;
- // const startCell = main.getNoMergeCellPositionByIndex(finalStartRow, finalStartColumn);
- // const endCell = main.getNoMergeCellPositionByIndex(finalEndRow, finalEndColumn);
-
- // this._manager.updateSelectionValue(
- // this,
- // {
- // startColumn: finalStartColumn,
- // startRow: finalStartRow,
- // endColumn: finalEndColumn,
- // endRow: finalEndRow,
- // startY: startCell?.startY || 0,
- // endY: endCell?.endY || 0,
- // startX: startCell?.startX || 0,
- // endX: endCell?.endX || 0,
- // },
- // cellInfo
- // );
-
- // this._updateControl();
- // }
-
- clearHighlight() {
- this._selectionModel.clearCurrentCell();
- this._updateControl();
- }
-
- dispose() {
- this._leftControl?.dispose();
- this._rightControl?.dispose();
- this._topControl?.dispose();
- this._bottomControl?.dispose();
- this._backgroundControlTop?.dispose();
- this._backgroundControlMiddleLeft?.dispose();
- this._backgroundControlMiddleRight?.dispose();
- this._backgroundControlBottom?.dispose();
- this._fillControl?.dispose();
- this._selectionShape?.dispose();
-
- this._selectionDragAndDrop.dispose();
- }
-
- /**
- * Get the cell information of the current selection, considering the case of merging cells
- */
- getCurrentCellInfo(): Nullable<ISelection> {
- const currentCell = this.model.currentCell;
-
- if (currentCell) {
- let currentRangeData;
-
- if (currentCell.isMerged) {
- const mergeInfo = currentCell.mergeInfo;
-
- currentRangeData = {
- startRow: mergeInfo.startRow,
- endRow: mergeInfo.endRow,
- startColumn: mergeInfo.startColumn,
- endColumn: mergeInfo.endColumn,
- startX: mergeInfo.startX,
- endX: mergeInfo.endX,
- startY: mergeInfo.startY,
- endY: mergeInfo.endY,
- };
- } else {
- const { row, column, startX, endX, startY, endY } = currentCell;
- currentRangeData = {
- startRow: row,
- endRow: row,
- startColumn: column,
- endColumn: column,
- startX,
- endX,
- startY,
- endY,
- };
- }
-
- return currentRangeData;
- }
- }
-
- private _initialize() {
- this._selectionModel = this._injector.createInstance(SelectionModel, SELECTION_TYPE.NORMAL);
- const zIndex = this._zIndex;
- this._leftControl = new Rect(SELECTION_MANAGER_KEY.left + zIndex, {
- top: 0,
- left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
- width: DEFAULT_SELECTION_CONFIG.strokeWidth,
- fill: DEFAULT_SELECTION_CONFIG.strokeColor,
- zIndex,
- });
- this._rightControl = new Rect(SELECTION_MANAGER_KEY.right + zIndex, {
- width: DEFAULT_SELECTION_CONFIG.strokeWidth,
- fill: DEFAULT_SELECTION_CONFIG.strokeColor,
- zIndex,
- });
- this._topControl = new Rect(SELECTION_MANAGER_KEY.top + zIndex, {
- top: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
- left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
- height: DEFAULT_SELECTION_CONFIG.strokeWidth,
- fill: DEFAULT_SELECTION_CONFIG.strokeColor,
- zIndex,
- });
- this._bottomControl = new Rect(SELECTION_MANAGER_KEY.bottom + zIndex, {
- height: DEFAULT_SELECTION_CONFIG.strokeWidth,
- fill: DEFAULT_SELECTION_CONFIG.strokeColor,
- left: -DEFAULT_SELECTION_CONFIG.strokeWidth / 2,
- zIndex,
- });
- this._backgroundControlTop = new Rect(SELECTION_MANAGER_KEY.backgroundTop + zIndex, {
- fill: DEFAULT_SELECTION_CONFIG.backgroundColor,
- zIndex: zIndex - 1,
- evented: false,
- });
- this._backgroundControlBottom = new Rect(SELECTION_MANAGER_KEY.backgroundBottom + zIndex, {
- fill: DEFAULT_SELECTION_CONFIG.backgroundColor,
- zIndex: zIndex - 1,
- evented: false,
- });
- this._backgroundControlMiddleLeft = new Rect(SELECTION_MANAGER_KEY.backgroundMiddleLeft + zIndex, {
- fill: DEFAULT_SELECTION_CONFIG.backgroundColor,
- zIndex: zIndex - 1,
- evented: false,
- });
- this._backgroundControlMiddleRight = new Rect(SELECTION_MANAGER_KEY.backgroundMiddleRight + zIndex, {
- fill: DEFAULT_SELECTION_CONFIG.backgroundColor,
- zIndex: zIndex - 1,
- evented: false,
- });
- const fillSideLength = DEFAULT_SELECTION_CONFIG.fillSideLength - DEFAULT_SELECTION_CONFIG.fillStrokeLength;
- this._fillControl = new Rect(SELECTION_MANAGER_KEY.fill + zIndex, {
- width: fillSideLength,
- height: fillSideLength,
- fill: DEFAULT_SELECTION_CONFIG.strokeColor,
- strokeWidth: DEFAULT_SELECTION_CONFIG.fillStrokeLength,
- stroke: DEFAULT_SELECTION_CONFIG.fillStrokeColor,
- zIndex: zIndex + 1,
- });
- this._selectionShape = new Group(
- SELECTION_MANAGER_KEY.Selection + zIndex,
- this._fillControl,
- this._leftControl,
- this._rightControl,
- this._topControl,
- this._bottomControl,
- this._backgroundControlTop,
- this._backgroundControlMiddleLeft,
- this._backgroundControlMiddleRight,
- this._backgroundControlBottom
- );
-
- this._selectionShape.hide();
-
- this._selectionShape.evented = false;
-
- this._selectionShape.zIndex = zIndex;
-
- this._selectionDragAndDrop = SelectionControlDragAndDrop.create(this._injector, this._zIndex, this._selectionModel, {
- leftControl: this.leftControl,
- rightControl: this.rightControl,
- topControl: this.topControl,
- bottomControl: this.bottomControl,
- fillControl: this.fillControl,
- update: this.update.bind(this),
- });
-
- this._selectionControlFill = SelectionControlFill.create(this._injector, {
- fillControl: this.fillControl,
- });
-
- this._canvasView.getSheetView().getScene().addObject(this._selectionShape);
- }
-
- private _updateBackgroundControl() {
- const {
- startColumn,
- startRow,
- endColumn,
- endRow,
-
- startX,
- startY,
- endX,
- endY,
- } = this._selectionModel;
-
- const highlightSelection = this._selectionModel.highlightToSelection();
-
- if (!highlightSelection) {
- this._backgroundControlTop.resize(endX - startX, endY - startY);
- this._backgroundControlBottom.resize(0, 0);
- this._backgroundControlMiddleLeft.resize(0, 0);
- this._backgroundControlMiddleRight.resize(0, 0);
- return;
- }
-
- const { startX: h_startX, startY: h_startY, endX: h_endX, endY: h_endY } = highlightSelection;
-
- const strokeOffset = DEFAULT_SELECTION_CONFIG.strokeWidth / 2;
-
- const topConfig = {
- left: -strokeOffset,
- top: -strokeOffset,
- width: endX - startX + strokeOffset * 2,
- height: h_startY - startY + strokeOffset,
- };
- if (topConfig.height < 0) {
- topConfig.width = 0;
- topConfig.height = 0;
- }
- this._backgroundControlTop.transformByState(topConfig);
-
- const middleLeftConfig = {
- left: -strokeOffset,
- top: h_startY - startY,
- width: h_startX - startX + strokeOffset,
- height: h_endY - h_startY,
- };
- if (middleLeftConfig.width < 0) {
- middleLeftConfig.width = 0;
- middleLeftConfig.height = 0;
- }
- this._backgroundControlMiddleLeft.transformByState(middleLeftConfig);
-
- const middleRightConfig = {
- left: h_endX - startX - strokeOffset,
- top: h_startY - startY,
- width: endX - h_endX + strokeOffset * 2,
- height: h_endY - h_startY,
- };
- if (middleRightConfig.width < 0) {
- middleRightConfig.width = 0;
- middleRightConfig.height = 0;
- }
- this._backgroundControlMiddleRight.transformByState(middleRightConfig);
-
- const middleBottomConfig = {
- left: -strokeOffset,
- top: h_endY - startY,
- width: endX - startX + strokeOffset * 2,
- height: endY - h_endY + strokeOffset,
- };
- if (middleBottomConfig.height < 0) {
- middleBottomConfig.width = 0;
- middleBottomConfig.height = 0;
- }
- this._backgroundControlBottom.transformByState(middleBottomConfig);
- }
-
- /**
- * Updated DragAndDrop and fill controls, inactive selections need to hide them
- */
- private _updateDragAndFill() {
- const highlightSelection = this._selectionModel.highlightToSelection();
-
- if (!highlightSelection) {
- this._selectionDragAndDrop.remove();
-
- this._fillControl.resize(0, 0);
- this._selectionControlFill.remove();
- }
- }
-}
\ No newline at end of file
diff --git a/packages/base-sheets/src/Controller/Selection/SelectionManager.ts b/packages/base-sheets/src/Controller/Selection/SelectionManager.ts
deleted file mode 100644
index 596073eabf..0000000000
--- a/packages/base-sheets/src/Controller/Selection/SelectionManager.ts
+++ /dev/null
@@ -1,1020 +0,0 @@
-import { SetSelectionsOperation } from '@Commands/Operations/selection.operation';
-import { IMouseEvent, IPointerEvent, Rect, ScrollTimer, Spreadsheet, SpreadsheetColumnTitle, SpreadsheetRowTitle } from '@univerjs/base-render';
-import {
- DEFAULT_CELL,
- DEFAULT_SELECTION,
- Direction,
- ICellInfo,
- ICommandService,
- ICurrentUniverService,
- IGridRange,
- IRangeCellData,
- IRangeData,
- ISelection,
- ISelectionData,
- makeCellToSelection,
- Nullable,
- Observer,
- ObserverManager,
- Range,
- RangeList,
- Worksheet,
-} from '@univerjs/core';
-import { Inject, Injector } from '@wendellhu/redi';
-
-import { ISelectionsConfig, ISheetPluginConfig } from '../../Basics';
-import { ISelectionModelValue } from '../../Model/Action/SetSelectionValueAction';
-import { SelectionModel } from '../../Model/SelectionModel';
-import { SheetView } from '../../View/Views/SheetView';
-import { ColumnTitleController } from './ColumnTitleController';
-import { DragLineController } from './DragLineController';
-import { RowTitleController } from './RowTitleController';
-import { SELECTION_TYPE, SelectionController } from './SelectionController';
-
-/**
- * TODO 注册selection拦截,可能在有公式ArrayObject时,fx公式栏显示不同
- *
- * SelectionManager 维护model数据list,action也是修改这一层数据,obs监听到数据变动后,自动刷新(control仍然可以持有数据)
- */
-export class SelectionManager {
- hasSelection: boolean = false;
-
- private _mainComponent: Spreadsheet;
-
- private _rowComponent: SpreadsheetRowTitle;
-
- private _columnComponent: SpreadsheetColumnTitle;
-
- private _leftTopComponent: Rect;
-
- private _moveObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
- private _upObserver: Nullable<Observer<IPointerEvent | IMouseEvent>>;
-
- private _selectionControls: SelectionController[] = []; // sheetID:Controls
-
- private _selectionModels = new Map<string, SelectionModel[]>(); // sheetID:Models
-
- private _startSelectionRange: ISelection;
-
- private _startOffsetX: number = 0;
-
- private _startOffsetY: number = 0;
-
- private _worksheet: Nullable<Worksheet>;
-
- private _previousSelection: ISelectionData;
-
- constructor(
- /** @deprecated this should be divided into smaller pieces */
- private readonly _sheetView: SheetView,
- private readonly _config: ISheetPluginConfig,
- @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
- /** @deprecated use ICommandService instead */
- @ICommandService private readonly _commandService: ICommandService,
- @Inject(Injector) private readonly _injector: Injector,
- @Inject(ObserverManager) private readonly _observerManager: ObserverManager,
- /** @deprecated this should be divided into smaller pieces */
- @Inject(DragLineController) private readonly _dragLineController: DragLineController,
- @Inject(ColumnTitleController) private readonly _columnTitleController: ColumnTitleController,
- @Inject(RowTitleController) private readonly _rowTitleController: RowTitleController
- ) {
- this._initialize();
- this._initializeObserver();
-
- this._commandService.registerCommand(SetSelectionsOperation);
- }
-
- /** @deprecated */
- getSheetView() {
- return this._sheetView;
- }
-
- /** @deprecated */
- getScene() {
- return this._sheetView.getScene();
- }
-
- /** @deprecated */
- getMainComponent() {
- return this._mainComponent;
- }
-
- updateToSheet(worksheet: Worksheet) {
- this._worksheet = worksheet;
- const worksheetId = this.getWorksheetId();
- if (worksheetId) {
- const models = this._selectionModels.get(worksheetId);
- if (!models) {
- this._selectionModels.set(worksheetId, []);
- }
- }
- }
-
- getCurrentControls() {
- return this._selectionControls;
- }
-
- getCurrentSelections() {
- return this._selectionControls.map((control) => {
- const model = control.model;
- return {
- startRow: model.startRow,
- startColumn: model.startColumn,
- endRow: model.endRow,
- endColumn: model.endColumn,
- };
- });
- }
-
- getCurrentControl() {
- const controls = this.getCurrentControls();
- if (controls && controls.length > 0) {
- for (const control of controls) {
- const currentCell = control.model.currentCell;
- if (currentCell) {
- return control;
- }
- }
- }
- }
-
- getCurrentModels() {
- const worksheetId = this.getWorksheetId();
- if (!worksheetId) {
- return;
- }
-
- const models = this._selectionModels.get(worksheetId);
-
- if (!models) {
- this._selectionModels.set(worksheetId, []);
- }
- return this._selectionModels.get(worksheetId);
- }
-
- getCurrentCellModel(): Nullable<ICellInfo> {
- const models = this.getCurrentModels();
- if (models && models.length > 0) {
- for (const model of models) {
- const currentCell = model.currentCell;
- if (currentCell) {
- return currentCell;
- }
- }
- }
- }
-
- getCurrentModel(): Nullable<SelectionModel> {
- const models = this.getCurrentModels();
- if (models && models.length > 0) {
- for (const model of models) {
- const currentCell = model.currentCell;
- if (currentCell) {
- return model;
- }
- }
- }
- }
-
- getCurrentModelsValue(): ISelectionModelValue[] {
- const models = this.getCurrentModels();
- if (!models) {
- return [];
- }
- const selectionModelsValue = [];
- for (const model of models) {
- selectionModelsValue.push(model.getValue());
- }
- return selectionModelsValue;
- }
-
- /**
- * Renders all controls of the currently active sheet
- * @returns
- */
- renderCurrentControls(command: boolean = true, models?: SelectionModel[]) {
- const worksheetId = this.getWorksheetId();
- if (worksheetId) {
- if (this._selectionControls) {
- // clear old controls
- for (const control of this._selectionControls) {
- control.dispose();
- }
- }
-
- // render current control
- const selectionModels = models || this._selectionModels.get(worksheetId);
- this._selectionControls = [];
- selectionModels?.forEach((model) => {
- const curCellRange = model.currentCell;
- const main = this._mainComponent;
-
- const control = SelectionController.create(this._injector, this._selectionControls.length);
-
- let cellInfo = null;
- if (curCellRange) {
- cellInfo = main.getCellByIndex(curCellRange.row, curCellRange.column);
- }
-
- const { startRow, startColumn, endRow, endColumn } = model;
- const startCell = main.getNoMergeCellPositionByIndex(startRow, startColumn);
- const endCell = main.getNoMergeCellPositionByIndex(endRow, endColumn);
-
- // update control model and view
- control.update(
- {
- startColumn,
- startRow,
- endColumn,
- endRow,
- startY: startCell?.startY || 0,
- endY: endCell?.endY || 0,
- startX: startCell?.startX || 0,
- endX: endCell?.endX || 0,
- },
- cellInfo
- );
- this._selectionControls.push(control);
- });
-
- command && this.setSelectionModel();
- }
- }
-
- /**
- * add a selection
- * @param selectionRange
- * @param curCellRange
- * @returns
- */
- addControlToCurrentByRangeData(selectionRange: IRangeData, curCellRange: Nullable<IRangeCellData>, command: boolean = true) {
- const currentControls = this.getCurrentControls();
- if (!currentControls) {
- return;
- }
- const main = this._mainComponent;
-
- const control = SelectionController.create(this._injector, currentControls.length);
-
- let cellInfo = null;
- if (curCellRange) {
- cellInfo = main.getCellByIndex(curCellRange.row, curCellRange.column);
- }
-
- const { startRow, startColumn, endRow, endColumn } = selectionRange;
- const startCell = main.getNoMergeCellPositionByIndex(startRow, startColumn);
- const endCell = main.getNoMergeCellPositionByIndex(endRow, endColumn);
-
- // update control
- control.update(
- {
- startColumn,
- startRow,
- endColumn,
- endRow,
- startY: startCell?.startY || 0,
- endY: endCell?.endY || 0,
- startX: startCell?.startX || 0,
- endX: endCell?.endX || 0,
- },
- cellInfo
- );
-
- currentControls.push(control);
-
- // this.setSelectionModel();
-
- if (command) {
- this.setSelectionModel();
- } else {
- const models = this._selectionControls.map((control) => control.model.getValue());
- return models;
- }
- }
-
- clearSelectionControls() {
- const curControls = this.getCurrentControls();
-
- if (curControls.length > 0) {
- for (const control of curControls) {
- control.dispose();
- }
-
- curControls.length = 0; // clear currentSelectionControls
- }
- }
-
- /**
- * Update all current controls data in model
- */
- setSelectionModel(models?: ISelectionModelValue[]) {
- if (!this._worksheet) {
- return;
- }
-
- if (!models) {
- models = this._selectionControls.map((control) => control.model.getValue());
- }
-
- this._commandService.executeCommand(SetSelectionsOperation.id, {
- workbookId: this._currentUniverService.getCurrentUniverSheetInstance().getUnitId(),
- sheetId: this._worksheet.getSheetId(),
- selections: models,
- });
- }
-
- setModels(selections: ISelectionModelValue[]) {
- const worksheetId = this.getWorksheetId();
- if (!worksheetId) {
- return;
- }
-
- const models = selections.map(({ selection, cell }) => {
- const model = this._injector.createInstance(SelectionModel, SELECTION_TYPE.NORMAL);
- model.setValue(selection, cell);
- return model;
- });
-
- this._selectionModels.set(worksheetId, models);
- }
-
- // recreateControlsByRangeData() { }
-
- /**
- * Move the selection according to different directions, usually used for the shortcut key operation of ↑ ↓ ← →
- * @param direction
- * @returns
- */
- // eslint-disable-next-line max-lines-per-function
- move(direction: Direction): void {
- const currentCell = this.getCurrentCellModel();
-
- if (!currentCell) return;
-
- let { startRow: mergeStartRow, startColumn: mergeStartColumn, endRow: mergeEndRow, endColumn: mergeEndColumn } = currentCell.mergeInfo;
-
- let { row, column } = currentCell;
- const rowCount = this._worksheet?.getRowCount() || 1000;
- const columnCount = this._worksheet?.getColumnCount() || 50;
- switch (direction) {
- case Direction.UP:
- if (currentCell.isMerged || currentCell.isMergedMainCell) {
- row = --mergeStartRow;
- } else {
- row--;
- }
- if (row < 0) {
- row = 0;
- }
- break;
- case Direction.DOWN:
- if (currentCell.isMerged || currentCell.isMergedMainCell) {
- row = ++mergeEndRow;
- } else {
- row++;
- }
-
- if (row > rowCount) {
- row = rowCount;
- }
- break;
- case Direction.LEFT:
- if (currentCell.isMerged || currentCell.isMergedMainCell) {
- column = --mergeStartColumn;
- } else {
- column--;
- }
-
- if (column < 0) {
- column = 0;
- }
- break;
- case Direction.RIGHT:
- if (currentCell.isMerged || currentCell.isMergedMainCell) {
- column = ++mergeEndColumn;
- } else {
- column++;
- }
-
- if (column > columnCount) {
- column = columnCount;
- }
- break;
-
- default:
- break;
- }
-
- const cellInfo = this._mainComponent.getCellByIndex(row, column);
-
- const selectionData = makeCellToSelection(cellInfo);
-
- if (!selectionData) return;
-
- const { startRow, endRow, startColumn, endColumn } = selectionData;
-
- const main = this._mainComponent;
- const newBounding = main.getSelectionBounding(startRow, startColumn, endRow, endColumn);
-
- if (!newBounding) {
- return;
- }
-
- const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = newBounding;
-
- const rangeData: IRangeData = {
- startRow: finalStartRow,
- endRow: finalEndRow,
- startColumn: finalStartColumn,
- endColumn: finalEndColumn,
- };
- const currentCellData: IRangeCellData = {
- row: startRow,
- column: startColumn,
- };
-
- this.clearSelectionControls();
- this.addControlToCurrentByRangeData(rangeData, currentCellData);
- this.updatePreviousSelection();
- }
-
- setCurrentCell(gridData: IGridRange): void {
- const { rangeData: girdRangeData, sheetId } = gridData;
- const { startRow: row, startColumn: column } = girdRangeData;
-
- // active new target sheet
- const currentSheetId = this.getWorksheetId();
- if (sheetId !== currentSheetId) {
- const sheetIndex = this._worksheet?.getIndex();
- if (sheetIndex == null) return;
- this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().activateSheetByIndex(sheetIndex);
- }
-
- const cellInfo = this._mainComponent.getCellByIndex(row, column);
-
- const selectionData = makeCellToSelection(cellInfo);
-
- if (!selectionData) return;
-
- const { startRow, endRow, startColumn, endColumn } = selectionData;
-
- const main = this._mainComponent;
- const newBounding = main.getSelectionBounding(startRow, startColumn, endRow, endColumn);
-
- if (!newBounding) {
- return;
- }
-
- const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = newBounding;
-
- const rangeData: IRangeData = {
- startRow: finalStartRow,
- endRow: finalEndRow,
- startColumn: finalStartColumn,
- endColumn: finalEndColumn,
- };
- const currentCellData: IRangeCellData = {
- row: startRow,
- column: startColumn,
- };
-
- this.clearSelectionControls();
- this.addControlToCurrentByRangeData(rangeData, currentCellData);
- this.updatePreviousSelection();
- }
-
- /**
- * When mousedown and mouseup need to go to the coordination and undo stack, when mousemove does not need to go to the coordination and undo stack
- * @param moveEvt
- * @param selectionControl
- * @returns
- */
- moving(moveEvt: IPointerEvent | IMouseEvent, selectionControl: Nullable<SelectionController>, setModel: boolean = false) {
- // console.log('moving');
- const main = this._mainComponent;
- const { offsetX: moveOffsetX, offsetY: moveOffsetY, clientX, clientY } = moveEvt;
- const { startRow, startColumn, endRow, endColumn } = this._startSelectionRange;
-
- // moveOffsetX and moveOffsetY is relative to the top left corner of the canvas
- const scrollXY = main.getAncestorScrollXY(this._startOffsetX, this._startOffsetY);
- const moveCellInfo = main.calculateCellIndexByPosition(moveOffsetX, moveOffsetY, scrollXY); // scrollXY is canvas content scrolling
- const moveActualSelection = makeCellToSelection(moveCellInfo);
-
- if (!moveActualSelection) {
- return false;
- }
- const { startRow: moveStartRow, startColumn: moveStartColumn, endColumn: moveEndColumn, endRow: moveEndRow } = moveActualSelection;
-
- const newStartRow = Math.min(moveStartRow, startRow);
- const newStartColumn = Math.min(moveStartColumn, startColumn);
- const newEndRow = Math.max(moveEndRow, endRow);
- const newEndColumn = Math.max(moveEndColumn, endColumn);
- const newBounding = main.getSelectionBounding(newStartRow, newStartColumn, newEndRow, newEndColumn);
-
- if (!newBounding) {
- return false;
- }
- const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = newBounding;
-
- const startCell = main.getNoMergeCellPositionByIndex(finalStartRow, finalStartColumn);
- const endCell = main.getNoMergeCellPositionByIndex(finalEndRow, finalEndColumn);
-
- const newSelectionRange: ISelection = {
- startColumn: finalStartColumn,
- startRow: finalStartRow,
- endColumn: finalEndColumn,
- endRow: finalEndRow,
- startY: startCell?.startY || 0,
- endY: endCell?.endY || 0,
- startX: startCell?.startX || 0,
- endX: endCell?.endX || 0,
- };
- // Only notify when the selection changes
- const { startRow: oldStartRow, endRow: oldEndRow, startColumn: oldStartColumn, endColumn: oldEndColumn } = selectionControl?.model || DEFAULT_SELECTION;
- const { row: oldRow, column: oldColumn } = selectionControl?.model.currentCell || DEFAULT_CELL;
-
- if (oldStartColumn !== finalStartColumn || oldStartRow !== finalStartRow || oldEndColumn !== finalEndColumn || oldEndRow !== finalEndRow) {
- selectionControl && selectionControl.update(newSelectionRange);
- selectionControl && this._observerManager.getObserver('onChangeSelectionObserver')?.notifyObservers(selectionControl);
- }
-
- if (setModel) {
- if (!this._previousSelection) {
- this.setSelectionModel();
- } else {
- // If it is different from the range when clicked, you need to update the model
- const {
- startRow: mouseDownStartRow,
- endRow: mouseDownEndRow,
- startColumn: mouseDownStartColumn,
- endColumn: mouseDownEndColumn,
- } = (this._previousSelection.selection as IRangeData) || DEFAULT_SELECTION;
- const { row: mouseDownRow, column: mouseDownColumn } = (this._previousSelection.cell as IRangeCellData) || DEFAULT_CELL;
- if (
- mouseDownStartColumn !== finalStartColumn ||
- mouseDownStartRow !== finalStartRow ||
- mouseDownEndColumn !== finalEndColumn ||
- mouseDownEndRow !== finalEndRow ||
- mouseDownRow !== oldRow ||
- mouseDownColumn !== oldColumn
- ) {
- this.setSelectionModel();
- }
- }
-
- this.updatePreviousSelection();
- }
- }
-
- /**
- * pointer up event
- * @param moveEvt
- * @param selectionControl
- * @returns
- */
- up(upEvt: IPointerEvent | IMouseEvent, selectionControl: Nullable<SelectionController>) {
- // update model
-
- this.moving(upEvt, selectionControl, true);
- }
-
- updatePreviousSelection() {
- const selectionControl: Nullable<SelectionController> = this.getCurrentControl();
-
- if (!selectionControl) return;
-
- // this.setSelectionModel();
- const { startRow, endRow, startColumn, endColumn } = selectionControl.model;
- const { row, column } = selectionControl.model.currentCell || DEFAULT_CELL;
- this._previousSelection = {
- selection: {
- startRow,
- endRow,
- startColumn,
- endColumn,
- },
- cell: {
- row,
- column,
- },
- };
- }
-
- /**
- * Get all range data of the current selection
- * @returns
- */
- getActiveRangeListData(): Nullable<IRangeData[]> {
- const models = this.getCurrentModels();
- if (models && models.length > 0) {
- const selections = models?.map((model: SelectionModel) => ({
- startRow: model.startRow,
- startColumn: model.startColumn,
- endRow: model.endRow,
- endColumn: model.endColumn,
- }));
-
- return selections;
- }
- }
-
- /**
- * Returns the list of active ranges in the active sheet or null if there are no active ranges.
- * If there is a single range selected, this behaves as a getActiveRange() call.
- *
- * @returns
- */
- getActiveRangeList(): Nullable<RangeList> {
- const rangeListData = this.getActiveRangeListData();
- return rangeListData && this._worksheet?.getRangeList(rangeListData);
- }
-
- /**
- * Get the range of the currently active cell
- * @returns
- */
- getActiveRangeData(): Nullable<IRangeData> {
- const models = this.getCurrentModels();
- if (models && models.length > 0) {
- for (const model of models) {
- if (model.currentCell) {
- return {
- startRow: model.startRow,
- startColumn: model.startColumn,
- endRow: model.endRow,
- endColumn: model.endColumn,
- };
- }
- }
- }
- }
-
- /**
- * Returns the selected range in the active sheet, or null if there is no active range. If multiple ranges are selected this method returns only the last selected range.
- * @returns
- */
- getActiveRange(): Nullable<Range> {
- const rangeData = this.getActiveRangeData();
- return rangeData && this._worksheet?.getRange(rangeData);
- }
-
- /**
- * get active selection control
- * @returns
- */
- getCurrentCellData(): Nullable<IRangeData> {
- const models = this.getCurrentModels();
- if (models && models.length > 0) {
- for (const model of models) {
- const currentCell = model.currentCell;
- if (currentCell) {
- return {
- startRow: currentCell.row,
- startColumn: currentCell.column,
- endRow: currentCell.row,
- endColumn: currentCell.column,
- };
- }
- }
- }
- }
-
- /**
- * get active selection control
- * @returns
- */
- getCurrentCell(): Nullable<Range> {
- const rangeData = this.getCurrentCellData();
- return rangeData && this._worksheet?.getRange(rangeData);
- }
-
- getDragLineControl() {
- return this._dragLineController;
- }
-
- private _initialize() {
- this._mainComponent = this._sheetView.getSpreadsheet();
- this._rowComponent = this._sheetView.getSpreadsheetRowTitle();
- this._columnComponent = this._sheetView.getSpreadsheetColumnTitle();
- this._leftTopComponent = this._sheetView.getSpreadsheetLeftTopPlaceholder();
-
- this._mainEventInitial();
-
- this._rowEventInitial();
-
- this._columnEventInitial();
-
- this._leftTopEventInitial();
-
- this._worksheet = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
-
- this._initModels();
-
- const handler = {
- clearSelectionControls: () => this.clearSelectionControls(),
- addControlToCurrentByRangeData: (selectionRange: IRangeData, curCellRange: Nullable<IRangeCellData>, command: boolean = true) =>
- this.addControlToCurrentByRangeData(selectionRange, curCellRange, command),
- };
-
- this._columnTitleController.setHandlers(handler);
- this._rowTitleController.setHandlers(handler);
- }
-
- // eslint-disable-next-line max-lines-per-function
- private _mainEventInitial() {
- const main = this._mainComponent;
- // eslint-disable-next-line max-lines-per-function
- main.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent) => {
- // NOTE: handle mousedown event to update selections
- const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
- this._startOffsetX = evtOffsetX;
- this._startOffsetY = evtOffsetY;
- const scrollXY = main.getAncestorScrollXY(this._startOffsetX, this._startOffsetY);
- const cellInfo = main.calculateCellIndexByPosition(evtOffsetX, evtOffsetY, scrollXY);
- const actualSelection = makeCellToSelection(cellInfo);
- if (!actualSelection || !this._worksheet) {
- return false;
- }
-
- const { startRow, startColumn, endColumn, endRow, startY, endY, startX, endX } = actualSelection;
-
- const startSelectionRange = {
- startColumn,
- startRow,
- endColumn,
- endRow,
- startY,
- endY,
- startX,
- endX,
- };
-
- this._startSelectionRange = startSelectionRange;
-
- let selectionControl: Nullable<SelectionController> = this.getCurrentControl();
-
- const controls = this.getCurrentControls();
-
- if (!controls) {
- return false;
- }
-
- for (const control of controls) {
- // right click
- if (evt.button === 2 && control.model.isInclude(startSelectionRange)) {
- selectionControl = control;
- return;
- }
- // Click to an existing selection
- if (control.model.isEqual(startSelectionRange)) {
- selectionControl = control;
- break;
- }
-
- // There can only be one highlighted cell, so clear the highlighted cell of the existing selection
- if (!evt.shiftKey) {
- control.clearHighlight();
- }
- }
-
- // if ctrl key and shift key is not holding, we must clear the previous selections
- if (controls.length > 0 && !evt.ctrlKey && !evt.shiftKey) {
- for (const control of controls) {
- control.dispose();
- }
- controls.length = 0;
- }
-
- // if shift key is held, extend the current selection control
- const currentCell = selectionControl && selectionControl.model.currentCell;
- if (selectionControl && evt.shiftKey && currentCell) {
- const { row, column } = currentCell;
- const startCell = main.getNoMergeCellPositionByIndex(row, column);
- const endCell = main.getNoMergeCellPositionByIndex(endRow, endColumn);
- const newSelectionRange = {
- startColumn: column,
- startRow: row,
- endColumn: startSelectionRange.startColumn,
- endRow: startSelectionRange.startRow,
- startY: startCell?.startY || 0,
- endY: endCell?.endY || 0,
- startX: startCell?.startX || 0,
- endX: endCell?.endX || 0,
- };
- selectionControl.update(newSelectionRange, currentCell);
- } else {
- selectionControl = SelectionController.create(this._injector, controls.length);
- selectionControl.update(startSelectionRange, cellInfo);
- controls.push(selectionControl);
- }
-
- this.hasSelection = true;
-
- const scene = this.getScene();
-
- scene.disableEvent();
-
- const scrollTimer = ScrollTimer.create(this.getScene());
- scrollTimer.startScroll(evtOffsetX, evtOffsetY);
-
- // In edit mode, click other cells, you need to update the current model, otherwise when updating the cell value, the old active range will be redrawn
- const currentModel = selectionControl.getCurrentCellInfo();
- if (!this._previousSelection) {
- // this.setSelectionModel();
- const models = this._selectionControls.map((control) => control.model.getValue());
- this.setModels(models);
- } else {
- // If it is different from the range when clicked, you need to update the model
- const {
- startRow: mouseDownStartRow,
- endRow: mouseDownEndRow,
- startColumn: mouseDownStartColumn,
- endColumn: mouseDownEndColumn,
- } = (this._previousSelection.selection as IRangeData) || DEFAULT_SELECTION;
- const { row: mouseDownRow, column: mouseDownColumn } = (this._previousSelection.cell as IRangeCellData) || DEFAULT_CELL;
- if (
- mouseDownStartColumn !== currentModel?.startColumn ||
- mouseDownStartRow !== currentModel?.startRow ||
- mouseDownEndColumn !== currentModel?.endColumn ||
- mouseDownEndRow !== currentModel?.endRow ||
- mouseDownRow !== currentModel?.startRow ||
- mouseDownColumn !== currentModel?.startColumn
- ) {
- // this.setSelectionModel();
- const models = this._selectionControls.map((control) => control.model.getValue());
- this.setModels(models);
- }
- }
-
- // Notification toolbar updates button state and value
- this._observerManager.getObserver('onChangeSelectionObserver')?.notifyObservers(selectionControl);
-
- this._moveObserver = scene.onPointerMoveObserver.add((moveEvt: IPointerEvent | IMouseEvent) => {
- this.moving(moveEvt, selectionControl);
- const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
-
- scrollTimer.scrolling(moveOffsetX, moveOffsetY, () => {
- this.moving(moveEvt, selectionControl);
- });
- });
-
- this._upObserver = scene.onPointerUpObserver.add((upEvt: IPointerEvent | IMouseEvent) => {
- this.up(upEvt, selectionControl);
- scene.onPointerMoveObserver.remove(this._moveObserver);
- scene.onPointerUpObserver.remove(this._upObserver);
- scene.enableEvent();
-
- scrollTimer.stopScroll();
- });
- });
- }
-
- private _rowEventInitial() {
- const row = this._rowComponent;
- row.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {
- // this._rowTitleControl.highlightRowTitle(evt);
- });
- }
-
- private _columnEventInitial() {
- const column = this._columnComponent;
- column.onPointerEnterObserver.add((evt: IPointerEvent | IMouseEvent) => {
- // this._columnTitleControl.highlightColumnTitle(evt);
- });
- }
-
- private _leftTopEventInitial() {
- const leftTop = this._leftTopComponent;
- leftTop.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent) => {
- // console.log('leftTop_moveObserver', evt);
- });
- }
-
- /**
- * Initialize selection model based on user configuration
- * @param selections
- */
- private _initModels() {
- const selections: ISelectionsConfig = this._config.selections;
-
- Object.keys(selections).forEach((worksheetId) => {
- const selectionsList = selections[worksheetId];
- const currentModels: SelectionModel[] = [];
-
- selectionsList.forEach((selectionConfig) => {
- const { startColumn, startRow, endColumn, endRow } = selectionConfig.selection;
- const cell = selectionConfig.cell;
-
- const model = this._injector.createInstance(SelectionModel, SELECTION_TYPE.NORMAL);
-
- const cellInfo = cell
- ? {
- row: cell.row,
- column: cell.column,
- isMerged: false,
- isMergedMainCell: false,
- startY: 0,
- endY: 0,
- startX: 0,
- endX: 0,
- mergeInfo: {
- startColumn,
- startRow,
- endColumn,
- endRow,
- startY: 0,
- endY: 0,
- startX: 0,
- endX: 0,
- },
- }
- : null;
-
- // Only update data, not render
- model.setValue(
- {
- startColumn,
- startRow,
- endColumn,
- endRow,
- startY: 0,
- endY: 0,
- startX: 0,
- endX: 0,
- },
- cellInfo
- );
- currentModels.push(model);
- });
-
- this._selectionModels.set(worksheetId, currentModels);
- });
- }
-
- /**
- * Initialize selection based on user configuration
- * @param selections
- */
- private _initControls() {
- const selections: ISelectionsConfig = this._config.selections;
- Object.keys(selections).forEach((worksheetId) => {
- const selectionsList = selections[worksheetId];
- const currentControls: SelectionController[] = [];
-
- selectionsList.forEach((selectionConfig) => {
- const selectionRange = selectionConfig.selection;
- const curCellRange = selectionConfig.cell;
- const main = this._mainComponent;
-
- const control = SelectionController.create(this._injector, currentControls.length);
-
- let cellInfo = null;
- if (curCellRange) {
- cellInfo = main.getCellByIndex(curCellRange.row, curCellRange.column);
- }
-
- const { startRow: finalStartRow, startColumn: finalStartColumn, endRow: finalEndRow, endColumn: finalEndColumn } = selectionRange;
- const startCell = main.getNoMergeCellPositionByIndex(finalStartRow, finalStartColumn);
- const endCell = main.getNoMergeCellPositionByIndex(finalEndRow, finalEndColumn);
-
- // Only update data, not render
- control.model.setValue(
- {
- startColumn: finalStartColumn,
- startRow: finalStartRow,
- endColumn: finalEndColumn,
- endRow: finalEndRow,
- startY: startCell?.startY || 0,
- endY: endCell?.endY || 0,
- startX: startCell?.startX || 0,
- endX: endCell?.endX || 0,
- },
- cellInfo
- );
- currentControls.push(control);
- });
-
- // this._selectionControls.set(worksheetId, currentControls);
- });
- }
-
- /**
- * Initialize the observer
- */
- private _initializeObserver() {
- // NOTE: on these circumstances should re-render selections controlls
- // kind of verbose to me though
- this._observerManager.requiredObserver('onAfterChangeActiveSheetObservable', 'core').add(() => {
- this.renderCurrentControls();
- });
-
- this._observerManager.requiredObserver('onSheetRenderDidMountObservable', 'core').add(() => {
- this.renderCurrentControls();
- });
- }
-
- private getWorksheetId(): string {
- return this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet().getSheetId();
- }
-}
diff --git a/packages/base-sheets/src/Controller/Selection/Shared.ts b/packages/base-sheets/src/Controller/Selection/Shared.ts
deleted file mode 100644
index 3ec40f8c91..0000000000
--- a/packages/base-sheets/src/Controller/Selection/Shared.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { IRangeCellData, IRangeData, Nullable } from '@univerjs/core';
-
-export interface IColumnTitleControllerHandlers {
- clearSelectionControls: () => void;
- addControlToCurrentByRangeData: (selectionRange: IRangeData, curCellRange: Nullable<IRangeCellData>, command?: boolean) => any;
-}
diff --git a/packages/base-sheets/src/Controller/Selection/index.ts b/packages/base-sheets/src/Controller/Selection/index.ts
deleted file mode 100644
index f9d5b50059..0000000000
--- a/packages/base-sheets/src/Controller/Selection/index.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-// @index('./*.ts', f => `export * from '${f.path}'`)
-export * from './SelectionControlDragDrop';
-export * from './SelectionControlFill';
-export * from './SelectionController';
-export * from './SelectionManager';
-// @endindex
diff --git a/packages/base-sheets/src/Controller/SheetContainerController.ts b/packages/base-sheets/src/Controller/SheetContainerController.ts
index d9ba24f5c8..25aa3c37af 100644
--- a/packages/base-sheets/src/Controller/SheetContainerController.ts
+++ b/packages/base-sheets/src/Controller/SheetContainerController.ts
@@ -4,15 +4,14 @@ import { Inject } from '@wendellhu/redi';
import { SetWorksheetActivateMutation } from '../Commands/Mutations/set-worksheet-activate.mutation';
import { SetWorksheetColWidthMutation } from '../Commands/Mutations/set-worksheet-col-width.mutation';
import { SetWorksheetRowHeightMutation } from '../Commands/Mutations/set-worksheet-row-height.mutation';
-import { ISelectionManager } from '../Services/tokens';
+import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../Services/selection-manager.service';
import { CanvasView } from '../View';
-import { SelectionManager } from './Selection';
const updateCommandList = [SetWorksheetRowHeightMutation.id, SetWorksheetColWidthMutation.id, SetWorksheetActivateMutation.id];
export class SheetContainerController extends Disposable {
constructor(
- @ISelectionManager private readonly _selectionManager: SelectionManager,
+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
@Inject(CanvasView) private readonly canvasView: CanvasView,
@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
@ICommandService private readonly _commandService: ICommandService
@@ -27,10 +26,19 @@ export class SheetContainerController extends Disposable {
this._commandService.onCommandExecuted((command: ICommandInfo) => {
// refresh selection and worksheet canvas view
if (updateCommandList.includes(command.id)) {
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
+ const unitId = workbook.getUnitId();
const worksheet = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
- this._selectionManager.updateToSheet(worksheet);
+ const sheetId = worksheet.getSheetId();
+ // this._selectionManager.updateToSheet(worksheet);
+
+ this._selectionManagerService.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId,
+ sheetId,
+ });
+
this.canvasView.updateToSheet(worksheet);
- this._selectionManager.renderCurrentControls(false);
}
this.canvasView.getSheetView().getSpreadsheet().makeDirty(true);
diff --git a/packages/base-sheets/src/Controller/index.ts b/packages/base-sheets/src/Controller/index.ts
index 2e1d2b4318..5205d75bf4 100644
--- a/packages/base-sheets/src/Controller/index.ts
+++ b/packages/base-sheets/src/Controller/index.ts
@@ -1,11 +1,9 @@
// @index(['./*.ts','./**/index.ts'], f => `export * from '${f.path}'`)
-export * from './AntLineController';
export * from './BasicWorkbook.controller';
export * from './BasicWorksheet.controller';
export * from './CellEditorController';
export * from './CountBarController';
// export * from './EditTooltipsController';
-export * from './Selection/index';
export * from './SheetBarController';
export * from './SheetContainerController';
// @endindex
diff --git a/packages/base-sheets/src/Model/AntLineModel.ts b/packages/base-sheets/src/Model/AntLineModel.ts
deleted file mode 100644
index ecfa23a957..0000000000
--- a/packages/base-sheets/src/Model/AntLineModel.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { Rect } from '@univerjs/base-render';
-import { IRangeData, Nullable } from '@univerjs/core';
-
-export interface IAntLineRange extends IRangeData {
- id?: string;
-}
-
-export class AntLine {
- private _range: IAntLineRange;
-
- private _rect: Nullable<Rect>;
-
- constructor(range: IAntLineRange) {
- this._range = range;
- }
-
- getRange(): IAntLineRange {
- return this._range;
- }
-
- getRect(): Nullable<Rect> {
- return this._rect;
- }
-
- setRect(rect: Rect): void {
- this._rect = rect;
- }
-
- setRange(range: IAntLineRange): void {
- this._range = range;
- }
-}
-
-export class AntLineModel {
- private _sheetId: string;
-
- private _antLineList: AntLine[];
-
- constructor(sheetId: string) {
- this._sheetId = sheetId;
- this._antLineList = [];
- }
-
- deleteAntLineById(id: string): void {
- const index = this._antLineList.findIndex((antLine) => antLine.getRange().id === id);
- if (index > -1) {
- this._antLineList.splice(index, 1);
- }
- }
-
- addAntLine(antLine: AntLine): void {
- this._antLineList.push(antLine);
- }
-
- getSheetId(): string {
- return this._sheetId;
- }
-
- getAntLineList(): AntLine[] {
- return this._antLineList;
- }
-
- getAntLineById(id: string): Nullable<AntLine> {
- const index = this._antLineList.findIndex((antLine) => antLine.getRange().id === id);
- if (index > -1) {
- return this._antLineList[index];
- }
- }
-}
diff --git a/packages/base-sheets/src/Model/SelectionModel.ts b/packages/base-sheets/src/Model/SelectionModel.ts
deleted file mode 100644
index d53fe1b73b..0000000000
--- a/packages/base-sheets/src/Model/SelectionModel.ts
+++ /dev/null
@@ -1,178 +0,0 @@
-import { ICellInfo, ICurrentUniverService, ISelection, makeCellToSelection, Nullable } from '@univerjs/core';
-
-import { SELECTION_TYPE } from '../Controller/Selection/SelectionController';
-
-export class SelectionModel implements ISelection {
- private _startColumn: number;
-
- private _startRow: number;
-
- private _endColumn: number;
-
- private _endRow: number;
-
- private _startX: number;
-
- private _startY: number;
-
- private _endX: number;
-
- private _endY: number;
-
- private _type: SELECTION_TYPE;
-
- private _currentCell: Nullable<ICellInfo>;
-
- constructor(type: SELECTION_TYPE = SELECTION_TYPE.NORMAL, @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService) {
- this._type = type;
- }
-
- get startColumn() {
- return this._startColumn;
- }
-
- get startRow() {
- return this._startRow;
- }
-
- get endColumn() {
- return this._endColumn;
- }
-
- get endRow() {
- return this._endRow;
- }
-
- get startX() {
- return this._startX;
- }
-
- get startY() {
- return this._startY;
- }
-
- get endX() {
- return this._endX;
- }
-
- get endY() {
- return this._endY;
- }
-
- get type() {
- return this._type;
- }
-
- get currentCell() {
- return this._currentCell;
- }
-
- isEqual(selectionRange: ISelection) {
- const { startColumn, startRow, endColumn, endRow, type } = this;
- const { startColumn: newStartColumn, startRow: newStartRow, endColumn: newEndColumn, endRow: newEndRow } = selectionRange;
- // if (type !== newType) {
- // return false;
- // }
- if (startColumn === newStartColumn && startRow === newStartRow && endColumn === newEndColumn && endRow === newEndRow) {
- return true;
- }
- return false;
- }
-
- isInclude(selectionRange: ISelection) {
- const { startColumn, startRow, endColumn, endRow, type } = this;
- const { startColumn: newStartColumn, startRow: newStartRow, endColumn: newEndColumn, endRow: newEndRow } = selectionRange;
-
- // if (type !== newType) {
- // return false;
- // }
-
- if (!(newEndColumn < startColumn || newStartColumn > endColumn || newStartRow > endRow || newEndRow < startRow)) {
- return true;
- }
- return false;
- }
-
- highlightToSelection() {
- return makeCellToSelection(this._currentCell);
- }
-
- getValue() {
- return {
- selection: {
- startColumn: this._startColumn,
- startRow: this._startRow,
- endColumn: this._endColumn,
- endRow: this._endRow,
-
- startX: this._startX,
- startY: this._startY,
- endX: this._endX,
- endY: this._endY,
- },
- cell: this._currentCell,
- };
- }
-
- setValue(newSelectionRange: ISelection, currentCell: Nullable<ICellInfo>) {
- const {
- startColumn,
- startRow,
- endColumn,
- endRow,
-
- startX,
- startY,
- endX,
- endY,
- } = newSelectionRange;
-
- this._startColumn = startColumn;
-
- this._startRow = startRow;
-
- this._endColumn = endColumn;
-
- this._endRow = endRow;
-
- this._startX = startX;
-
- this._startY = startY;
-
- this._endX = endX;
-
- this._endY = endY;
-
- this.setTypeByData();
-
- this.setCurrentCell(currentCell);
- }
-
- setCurrentCell(currentCell: Nullable<ICellInfo>) {
- if (currentCell) {
- this._currentCell = currentCell;
- }
- }
-
- clearCurrentCell() {
- this._currentCell = null;
- }
-
- /**
- * Determine the type type based on the data
- */
- setTypeByData() {
- const workbook = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
- const rowCount = workbook.getActiveSheet().getConfig().rowCount;
- const columnCount = workbook.getActiveSheet().getConfig().columnCount;
-
- if (this._startRow === 0 && this._endRow === rowCount - 1) {
- return (this._type = SELECTION_TYPE.COLUMN);
- }
- if (this._startColumn === 0 && this._endColumn === columnCount - 1) {
- return (this._type = SELECTION_TYPE.ROW);
- }
-
- return (this._type = SELECTION_TYPE.NORMAL);
- }
-}
diff --git a/packages/base-sheets/src/Model/index.ts b/packages/base-sheets/src/Model/index.ts
deleted file mode 100644
index f762348c4f..0000000000
--- a/packages/base-sheets/src/Model/index.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-// @index('./*.ts', f => `export * from '${f.path}'`)
-export * from './AntLineModel';
-export * from './SelectionModel';
-// @endindex
\ No newline at end of file
diff --git a/packages/base-sheets/src/Services/selection-manager.service.ts b/packages/base-sheets/src/Services/selection-manager.service.ts
new file mode 100644
index 0000000000..93a4ab00fc
--- /dev/null
+++ b/packages/base-sheets/src/Services/selection-manager.service.ts
@@ -0,0 +1,267 @@
+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';
+
+export const NORMAL_SELECTION_PLUGIN_NAME = 'normalSelectionPluginName';
+
+export interface ISelectionManagerSearchParam {
+ pluginName: string;
+ unitId: string;
+ sheetId: string;
+}
+
+export interface ISelectionManagerInsertParam extends ISelectionManagerSearchParam {
+ selectionDatas: ISelectionRangeWithStyle[];
+}
+
+//{ [pluginName: string]: { [unitId: string]: { [sheetId: string]: ISelectionData[] } } }
+export type ISelectionInfo = Map<string, Map<string, Map<string, ISelectionRangeWithStyle[]>>>;
+
+/**
+ * This service is for managing settings border style status.
+ */
+export class SelectionManagerService implements IDisposable {
+ private readonly _selectionInfo: ISelectionInfo = new Map();
+
+ private _currentSelection: Nullable<ISelectionManagerSearchParam> = null;
+
+ private readonly _selectionInfo$ = new BehaviorSubject<Nullable<ISelectionRangeWithStyle[]>>(null);
+
+ // eslint-disable-next-line @typescript-eslint/member-ordering
+ readonly selectionInfo$ = this._selectionInfo$.asObservable();
+
+ dispose(): void {
+ this._selectionInfo$.complete();
+ // this._currentSelection$.complete();
+ }
+
+ setCurrentSelection(param: ISelectionManagerSearchParam) {
+ this._currentSelection = param;
+
+ this.refresh(param);
+ }
+
+ setCurrentSelectionNotRefresh(param: ISelectionManagerSearchParam) {
+ this._currentSelection = param;
+ }
+
+ getSelectionInfo(): Readonly<ISelectionInfo> {
+ return this._selectionInfo;
+ }
+
+ getSelectionDatasByParam(param: Nullable<ISelectionManagerSearchParam>): Readonly<Nullable<ISelectionRangeWithStyle[]>> {
+ return this._getSelectionDatas(param);
+ }
+
+ getSelectionDatas(): Readonly<Nullable<ISelectionRangeWithStyle[]>> {
+ return this._getSelectionDatas(this._currentSelection);
+ }
+
+ getRangeDatas(): Nullable<IRangeData[]> {
+ const selectionDataList = this.getSelectionDatas();
+ if (selectionDataList == null) {
+ return;
+ }
+ return selectionDataList.map((selectionData: ISelectionRangeWithStyle) => {
+ const rangeData = selectionData.rangeData;
+ const { startRow, startColumn, endRow, endColumn } = rangeData;
+ return {
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
+ };
+ });
+ }
+
+ getFirst(): Readonly<Nullable<ISelectionRangeWithStyle>> {
+ return this._getFirstByParam(this._currentSelection);
+ }
+
+ getLast(): Readonly<Nullable<ISelectionRangeWithStyle>> {
+ return this._getLastByParam(this._currentSelection);
+ }
+
+ add(selectionDatas: ISelectionRangeWithStyle[]) {
+ if (this._currentSelection == null) {
+ return;
+ }
+ this._addByParam({
+ ...this._currentSelection,
+ selectionDatas,
+ });
+ }
+
+ replace(selectionDatas: ISelectionRangeWithStyle[]) {
+ if (this._currentSelection == null) {
+ return;
+ }
+ this._replaceByParam({
+ ...this._currentSelection,
+ selectionDatas,
+ });
+ this.refresh(this._currentSelection);
+ }
+
+ replaceWithNoRefresh(selectionDatas: ISelectionRangeWithStyle[]) {
+ if (this._currentSelection == null) {
+ return;
+ }
+ this._replaceByParam({
+ ...this._currentSelection,
+ selectionDatas,
+ });
+ }
+
+ clear(): void {
+ if (this._currentSelection == null) {
+ return;
+ }
+ this._clearByParam(this._currentSelection);
+ }
+
+ remove(index: number): void {
+ if (this._currentSelection == null) {
+ return;
+ }
+
+ this._removeByParam(index, this._currentSelection);
+ }
+
+ createDefaultAutoFillSelection(): ISelectionStyle {
+ return {
+ strokeDashArray: [],
+ strokeWidth: 2,
+ stroke: '#FFF000',
+ fill: 'rgba(0, 0, 0, 0.2)',
+ controls: {},
+ hasAutoFill: true,
+ };
+ }
+
+ createCopyPasteSelection(): ISelectionStyle {
+ return {
+ strokeDashArray: [1, 0, 1, 1],
+ strokeWidth: 2,
+ stroke: '#FFF000',
+ fill: 'rgba(0, 0, 0, 0.2)',
+ controls: {},
+ hasAutoFill: false,
+ };
+ }
+
+ createDefaultSelection(): ISelectionStyle {
+ return NORMAL_SELECTION_PLUGIN_STYLE;
+ }
+
+ transformCellDataToSelectionData(row: number, column: number, mergeData: IRangeData[]): Nullable<ISelectionRangeWithStyle> {
+ const newCellRange = mergeCellHandler(row, column, mergeData);
+
+ const newSelectionData = makeCellRangeToRangeData(newCellRange);
+
+ if (!newSelectionData) {
+ return;
+ }
+
+ return {
+ rangeData: newSelectionData,
+ cellRange: newCellRange,
+ style: NORMAL_SELECTION_PLUGIN_STYLE,
+ };
+ }
+
+ private _getSelectionDatas(param: Nullable<ISelectionManagerSearchParam>) {
+ if (param == null) {
+ return;
+ }
+ const { pluginName, unitId, sheetId } = param;
+ return this._selectionInfo.get(pluginName)?.get(unitId)?.get(sheetId);
+ }
+
+ private refresh(param: ISelectionManagerSearchParam): void {
+ this._selectionInfo$.next(this._getSelectionDatas(param));
+ }
+
+ private _getFirstByParam(param: Nullable<ISelectionManagerSearchParam>): Readonly<Nullable<ISelectionRangeWithStyle>> {
+ const selectionData = this._getSelectionDatas(param);
+
+ return selectionData?.[0];
+ }
+
+ private _getLastByParam(param: Nullable<ISelectionManagerSearchParam>): Readonly<Nullable<ISelectionRangeWithStyle>> {
+ const selectionData = this._getSelectionDatas(param);
+
+ return selectionData?.[selectionData.length - 1];
+ }
+
+ private _addByParam(insertParam: ISelectionManagerInsertParam): void {
+ const { pluginName, unitId, sheetId, selectionDatas } = insertParam;
+
+ if (!this._selectionInfo.has(pluginName)) {
+ this._selectionInfo.set(pluginName, new Map());
+ }
+
+ const unitSelectionData = this._selectionInfo.get(pluginName)!;
+
+ if (!unitSelectionData.has(unitId)) {
+ unitSelectionData.set(unitId, new Map());
+ }
+
+ const sheetSelectionData = unitSelectionData.get(unitId)!;
+
+ if (!sheetSelectionData.has(sheetId)) {
+ sheetSelectionData.set(sheetId, [...selectionDatas]);
+ } else {
+ const OldSelectionDatas = sheetSelectionData.get(sheetId)!;
+ OldSelectionDatas.push(...selectionDatas);
+ }
+
+ this.refresh({ pluginName, unitId, sheetId });
+ }
+
+ private _replaceByParam(insertParam: ISelectionManagerInsertParam) {
+ const { pluginName, unitId, sheetId, selectionDatas } = insertParam;
+
+ if (!this._selectionInfo.has(pluginName)) {
+ this._selectionInfo.set(pluginName, new Map());
+ }
+
+ const unitSelectionData = this._selectionInfo.get(pluginName)!;
+
+ if (!unitSelectionData.has(unitId)) {
+ unitSelectionData.set(unitId, new Map());
+ }
+
+ const sheetSelectionData = unitSelectionData.get(unitId)!;
+
+ if (!sheetSelectionData.has(sheetId)) {
+ sheetSelectionData.set(sheetId, selectionDatas);
+ } else {
+ const OldSelectionDatas = sheetSelectionData.get(sheetId)!;
+ OldSelectionDatas.splice(0, OldSelectionDatas.length, ...selectionDatas);
+ }
+
+ // this.refresh({ pluginName, unitId, sheetId });
+ }
+
+ private _clearByParam(param: ISelectionManagerSearchParam): void {
+ const selectionData = this._getSelectionDatas(param);
+
+ selectionData?.splice(0);
+
+ this.refresh(param);
+ }
+
+ private _removeByParam(index: number, param: ISelectionManagerSearchParam): void {
+ const selectionData = this._getSelectionDatas(param);
+
+ selectionData?.splice(index, 1);
+
+ this.refresh(param);
+ }
+
+ // private refreshCurrentSelection(): void {
+ // this._currentSelection$.next(this._currentSelection);
+ // }
+}
diff --git a/packages/base-sheets/src/Services/tokens.ts b/packages/base-sheets/src/Services/tokens.ts
index ff3016f27b..d49bb5cf4f 100644
--- a/packages/base-sheets/src/Services/tokens.ts
+++ b/packages/base-sheets/src/Services/tokens.ts
@@ -1,9 +1,8 @@
import { createIdentifier } from '@wendellhu/redi';
-import { SelectionManager } from '../Controller';
import { CanvasView } from '../View';
/** @deprecated temporary solution, we should inject SelectionManager directly. And it should be renamed to `ISelectionService`. */
-export const ISelectionManager = createIdentifier<SelectionManager>('deprecated.univer.sheet.selection-manager');
+// export const ISelectionManager = createIdentifier<SelectionManager>('deprecated.univer.sheet.selection-manager');
export const ICanvasView = createIdentifier<CanvasView>('univer.sheet.canvas-view');
diff --git a/packages/base-sheets/src/SheetPlugin.ts b/packages/base-sheets/src/SheetPlugin.ts
index b7350531ac..87ecf87e0f 100644
--- a/packages/base-sheets/src/SheetPlugin.ts
+++ b/packages/base-sheets/src/SheetPlugin.ts
@@ -1,27 +1,15 @@
-import { Engine, IRenderingEngine } from '@univerjs/base-render';
+import { Engine, IRenderingEngine, ISelectionTransformerShapeManager, SelectionTransformerShapeManager } from '@univerjs/base-render';
import { DEFAULT_SELECTION, ICurrentUniverService, LocaleService, Plugin, PLUGIN_NAMES, PluginType } from '@univerjs/core';
import { Dependency, Inject, Injector } from '@wendellhu/redi';
import { DEFAULT_SPREADSHEET_PLUGIN_DATA, install, ISheetPluginConfig } from './Basics';
import { SheetPluginObserve, uninstall } from './Basics/Observer';
-import {
- BasicWorkbookController,
- CellEditorController,
- CountBarController,
- // EditTooltipsController,
- // HideColumnController,
- SelectionManager,
- SheetBarController,
- SheetContainerController,
-} from './Controller';
+import { BasicWorkbookController, CellEditorController, CountBarController, SheetBarController, SheetContainerController } from './Controller';
import { BasicWorksheetController } from './Controller/BasicWorksheet.controller';
import { FormulaBarController } from './Controller/FormulaBarController';
-import { ColumnTitleController } from './Controller/Selection/ColumnTitleController';
-import { DragLineController } from './Controller/Selection/DragLineController';
-import { RowTitleController } from './Controller/Selection/RowTitleController';
import { en, zh } from './Locale';
import { BorderStyleManagerService } from './Services/border-style-manager.service';
-import { ISelectionManager } from './Services/tokens';
+import { SelectionManagerService } from './Services/selection-manager.service';
import { CanvasView } from './View/CanvasView';
/**
@@ -127,9 +115,9 @@ export class SheetPlugin extends Plugin<SheetPluginObserve> {
}
/** @deprecated move to DI system */
- getSelectionManager() {
- return this._injector.get(ISelectionManager);
- }
+ // getSelectionManager() {
+ // return this._injector.get(ISelectionManager);
+ // }
private _initializeDependencies(sheetInjector: Injector) {
const dependencies: Dependency[] = [
@@ -143,22 +131,31 @@ export class SheetPlugin extends Plugin<SheetPluginObserve> {
[CountBarController],
// TODO@huwenzhao: this is a temporary solution
- [
- ISelectionManager,
- {
- useFactory: (injector: Injector, canvasView: CanvasView) => injector.createInstance(SelectionManager, canvasView.getSheetView(), this._config),
- deps: [Injector, CanvasView],
- },
- ],
- [RowTitleController],
- [ColumnTitleController],
- [DragLineController],
+ // [
+ // ISelectionManager,
+ // {
+ // useFactory: (injector: Injector, canvasView: CanvasView) => injector.createInstance(SelectionManager, canvasView.getSheetView(), this._config),
+ // deps: [Injector, CanvasView],
+ // },
+ // ],
+ // [RowTitleController],
+ // [ColumnTitleController],
+ // [DragLineController],
// [HideColumnController],
[BasicWorksheetController],
[BasicWorkbookController],
[BorderStyleManagerService],
+
+ [SelectionManagerService],
+
+ [
+ ISelectionTransformerShapeManager,
+ {
+ useClass: SelectionTransformerShapeManager,
+ },
+ ],
];
dependencies.forEach((d) => {
diff --git a/packages/base-sheets/src/View/BaseView.ts b/packages/base-sheets/src/View/BaseView.ts
index ab2ce19ed6..f7987463cb 100644
--- a/packages/base-sheets/src/View/BaseView.ts
+++ b/packages/base-sheets/src/View/BaseView.ts
@@ -5,6 +5,8 @@ import { Injector } from '@wendellhu/redi';
export class BaseView {
viewKey = '';
+ zIndex = 0;
+
protected _injector: Injector;
private _scene: Scene;
@@ -13,7 +15,7 @@ export class BaseView {
return this._scene;
}
- updateToSheet(worksheet: Worksheet) {}
+ onSheetChange(worksheet: Worksheet) {}
initialize(scene: Scene) {
this._scene = scene;
@@ -34,6 +36,14 @@ export enum CANVAS_VIEW_KEY {
VIEW_LEFT_TOP = 'viewLeftTop',
SHEET_VIEW = 'sheetView',
DRAG_LINE_VIEW = 'dragLineView',
+ SELECTION_VIEW = 'selectionView',
+}
+
+export enum SHEET_VIEW_KEY {
+ MAIN = '__SpreadsheetRender__',
+ ROW = '__SpreadsheetRowTitle__',
+ COLUMN = '__SpreadsheetColumnTitle__',
+ LEFT_TOP = '__SpreadsheetLeftTopPlaceholder__',
}
export const CanvasViewRegistry = Registry.create();
diff --git a/packages/base-sheets/src/View/CanvasView.ts b/packages/base-sheets/src/View/CanvasView.ts
index d7550f1d0c..04f6cbd77e 100644
--- a/packages/base-sheets/src/View/CanvasView.ts
+++ b/packages/base-sheets/src/View/CanvasView.ts
@@ -1,10 +1,11 @@
-import { Inject, Injector } from '@wendellhu/redi';
-import { EventState, ICurrentUniverService, ObserverManager, Worksheet } from '@univerjs/core';
+import './Views';
import { Engine, EVENT_TYPE, IRenderingEngine, IScrollObserverParam, IWheelEvent, Layer, Scene, ScrollBar, Viewport } from '@univerjs/base-render';
+import { EventState, ICurrentUniverService, ObserverManager, sortRules, Worksheet } from '@univerjs/core';
+import { Inject, Injector } from '@wendellhu/redi';
+
import { BaseView, CANVAS_VIEW_KEY, CanvasViewRegistry } from './BaseView';
import { SheetView } from './Views/SheetView';
-import './Views';
// workbook
export class CanvasView {
@@ -36,7 +37,7 @@ export class CanvasView {
updateToSheet(worksheet: Worksheet) {
for (const view of this._views) {
- view.updateToSheet(worksheet);
+ view.onSheetChange(worksheet);
}
}
@@ -128,7 +129,7 @@ export class CanvasView {
const currentRatio = sheet.getZoomRatio();
let nextRatio = +parseFloat(`${currentRatio + ratioDelta}`).toFixed(1);
nextRatio = nextRatio >= 4 ? 4 : nextRatio <= 0.1 ? 0.1 : nextRatio;
- sheet.setZoomRatio(nextRatio);
+ // sheet.setZoomRatio(nextRatio);
e.preventDefault();
} else {
@@ -153,8 +154,10 @@ export class CanvasView {
}
private _viewLoader(scene: Scene) {
- CanvasViewRegistry.getData().forEach((viewFactory) => {
- this._views.push(viewFactory.create(scene, this._injector));
- });
+ CanvasViewRegistry.getData()
+ .sort(sortRules)
+ .forEach((viewFactory) => {
+ this._views.push(viewFactory.create(scene, this._injector));
+ });
}
}
diff --git a/packages/base-sheets/src/View/Views/SelectionView.ts b/packages/base-sheets/src/View/Views/SelectionView.ts
new file mode 100644
index 0000000000..5993b61a68
--- /dev/null
+++ b/packages/base-sheets/src/View/Views/SelectionView.ts
@@ -0,0 +1,141 @@
+import {
+ convertSelectionDataToRange,
+ IMouseEvent,
+ IPointerEvent,
+ ISelectionTransformerShapeManager,
+ Rect,
+ Scene,
+ Spreadsheet,
+ SpreadsheetColumnTitle,
+ SpreadsheetRowTitle,
+} from '@univerjs/base-render';
+import { ICurrentUniverService, ISelectionRange, LocaleService, ObserverManager, Worksheet } from '@univerjs/core';
+import { Inject, Injector } from '@wendellhu/redi';
+
+import { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from '../../Services/selection-manager.service';
+import { BaseView, CANVAS_VIEW_KEY, CanvasViewRegistry, SHEET_VIEW_KEY } from '../BaseView';
+
+export class SelectionView extends BaseView {
+ override viewKey = CANVAS_VIEW_KEY.SELECTION_VIEW;
+
+ constructor(
+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
+ @ISelectionTransformerShapeManager private readonly _selectionTransformerShapeManager: ISelectionTransformerShapeManager,
+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @Inject(ObserverManager) private readonly _observerManager: ObserverManager,
+ @Inject(LocaleService) private readonly _localeService: LocaleService
+ ) {
+ super();
+ }
+
+ override onSheetChange(worksheet: Worksheet) {
+ this._update(worksheet);
+ }
+
+ protected override _initialize() {
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
+ let worksheet = workbook.getActiveSheet();
+ if (!worksheet) {
+ worksheet = workbook.getSheets()[0];
+ }
+
+ const { spreadsheet, spreadsheetRowTitle, spreadsheetColumnTitle, spreadsheetLeftTopPlaceholder, spreadsheetSkeleton } = this._getSheetObject();
+
+ if (spreadsheet == null) {
+ return;
+ }
+
+ this._selectionManagerService.selectionInfo$.subscribe((param) => {
+ this._selectionTransformerShapeManager.reset();
+ if (param == null) {
+ return;
+ }
+
+ for (const selectionRange of param) {
+ const selectionData = this._selectionTransformerShapeManager.convertSelectionRangeToData(selectionRange);
+ this._selectionTransformerShapeManager.addControlToCurrentByRangeData(selectionData);
+ }
+ });
+
+ spreadsheet?.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent, state) => {
+ this._selectionTransformerShapeManager.eventTrigger(evt, spreadsheet.zIndex + 1);
+ state.stopPropagation();
+ });
+
+ spreadsheetRowTitle?.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent) => {});
+
+ spreadsheetColumnTitle?.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent) => {});
+
+ spreadsheetLeftTopPlaceholder?.onPointerDownObserver.add((evt: IPointerEvent | IMouseEvent) => {});
+
+ this._selectionTransformerShapeManager.selectionRangeWithStyle$.subscribe((selectionDataWithStyleList) => {
+ this._selectionManagerService.replaceWithNoRefresh(selectionDataWithStyleList.map((selectionDataWithStyle) => convertSelectionDataToRange(selectionDataWithStyle)));
+ const current = selectionDataWithStyleList[selectionDataWithStyleList.length - 1];
+ if (current == null) {
+ return;
+ }
+ const selectionRange = convertSelectionDataToRange(current);
+ this._observerManager.getObserver<ISelectionRange>('onChangeSelectionObserver')?.notifyObservers({
+ rangeData: selectionRange.rangeData,
+ cellRange: selectionRange.cellRange,
+ });
+ });
+
+ this._update(worksheet);
+ }
+
+ private _update(worksheet: Worksheet) {
+ const { spreadsheet, spreadsheetRowTitle, spreadsheetColumnTitle, spreadsheetLeftTopPlaceholder, spreadsheetSkeleton } = this._getSheetObject();
+ if (spreadsheetSkeleton == null) {
+ return;
+ }
+ const scene = this.getScene();
+ this._selectionTransformerShapeManager.changeRuntime(spreadsheetSkeleton, scene);
+
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
+
+ const unitId = workbook.getUnitId();
+
+ const sheetId = worksheet.getSheetId();
+
+ this._selectionManagerService.setCurrentSelection({
+ pluginName: NORMAL_SELECTION_PLUGIN_NAME,
+ unitId,
+ sheetId,
+ });
+ }
+
+ private _getSheetObject() {
+ const scene = this.getScene();
+ const spreadsheet = scene.getObject(SHEET_VIEW_KEY.MAIN) as Spreadsheet;
+ const spreadsheetRowTitle = scene.getObject(SHEET_VIEW_KEY.ROW) as SpreadsheetRowTitle;
+ const spreadsheetColumnTitle = scene.getObject(SHEET_VIEW_KEY.COLUMN) as SpreadsheetColumnTitle;
+ const spreadsheetLeftTopPlaceholder = scene.getObject(SHEET_VIEW_KEY.LEFT_TOP) as Rect;
+
+ return {
+ spreadsheet,
+ spreadsheetRowTitle,
+ spreadsheetColumnTitle,
+ spreadsheetLeftTopPlaceholder,
+ spreadsheetSkeleton: spreadsheet.getSkeleton(),
+ };
+ }
+}
+
+export class SelectionViewFactory {
+ zIndex = 1;
+
+ /**
+ * Generate SheetView Instance
+ * @param scene
+ * @param injector
+ * @returns
+ */
+ create(scene: Scene, injector: Injector): SelectionView {
+ const selectionView = injector.createInstance(SelectionView);
+ selectionView.initialize(scene);
+ return selectionView;
+ }
+}
+
+CanvasViewRegistry.add(new SelectionViewFactory());
diff --git a/packages/base-sheets/src/View/Views/SheetView.ts b/packages/base-sheets/src/View/Views/SheetView.ts
index 7e4a2857a3..512e1890ee 100644
--- a/packages/base-sheets/src/View/Views/SheetView.ts
+++ b/packages/base-sheets/src/View/Views/SheetView.ts
@@ -1,14 +1,8 @@
import { getColor, Rect, Scene, Spreadsheet, SpreadsheetColumnTitle, SpreadsheetRowTitle, SpreadsheetSkeleton } from '@univerjs/base-render';
import { ICurrentUniverService, LocaleService, Worksheet } from '@univerjs/core';
import { Inject, Injector } from '@wendellhu/redi';
-import { BaseView, CANVAS_VIEW_KEY, CanvasViewRegistry } from '../BaseView';
-export enum SHEET_VIEW_KEY {
- MAIN = '__SpreadsheetRender__',
- ROW = '__SpreadsheetRowTitle__',
- COLUMN = '__SpreadsheetColumnTitle__',
- LEFT_TOP = '__SpreadsheetLeftTopPlaceholder__',
-}
+import { BaseView, CANVAS_VIEW_KEY, CanvasViewRegistry, SHEET_VIEW_KEY } from '../BaseView';
export class SheetView extends BaseView {
override viewKey = CANVAS_VIEW_KEY.SHEET_VIEW;
@@ -47,7 +41,7 @@ export class SheetView extends BaseView {
return this._spreadsheetLeftTopPlaceholder;
}
- override updateToSheet(worksheet: Worksheet) {
+ override onSheetChange(worksheet: Worksheet) {
const scene = this.getScene();
const spreadsheetSkeleton = this._buildSkeleton(worksheet);
const { rowTotalHeight, columnTotalWidth, rowTitleWidth, columnTitleHeight } = spreadsheetSkeleton;
@@ -166,6 +160,8 @@ export class SheetView extends BaseView {
}
export class SheetViewFactory {
+ zIndex = 0;
+
/**
* Generate SheetView Instance
* @param scene
diff --git a/packages/base-sheets/src/View/Views/index.ts b/packages/base-sheets/src/View/Views/index.ts
index f9bf6051e1..d577b025d7 100644
--- a/packages/base-sheets/src/View/Views/index.ts
+++ b/packages/base-sheets/src/View/Views/index.ts
@@ -1,2 +1,3 @@
-export * from './SheetView';
export * from './EditTooltipsView';
+export * from './SelectionView';
+export * from './SheetView';
diff --git a/packages/base-sheets/src/index.ts b/packages/base-sheets/src/index.ts
index f169800c08..a6eae71919 100644
--- a/packages/base-sheets/src/index.ts
+++ b/packages/base-sheets/src/index.ts
@@ -1,13 +1,13 @@
export * from './Basics';
export * from './Controller';
-export * from './Model';
export * from './SheetPlugin';
export * from './View';
// #region services
export { BorderStyleManagerService } from './Services/border-style-manager.service';
-export { ICanvasView, ISelectionManager } from './Services/tokens';
+export { NORMAL_SELECTION_PLUGIN_NAME, SelectionManagerService } from './Services/selection-manager.service';
+export { ICanvasView } from './Services/tokens';
// #endregion
diff --git a/packages/base-slides/src/View/Render/CanvasView.ts b/packages/base-slides/src/View/Render/CanvasView.ts
index c8ebb8025a..5d35631f92 100644
--- a/packages/base-slides/src/View/Render/CanvasView.ts
+++ b/packages/base-slides/src/View/Render/CanvasView.ts
@@ -1,6 +1,7 @@
import { Engine, EVENT_TYPE, IRenderingEngine, IWheelEvent, Rect, Scene, ScrollBar, Slide, Viewport } from '@univerjs/base-render';
import { EventState, getColorStyle, IColorStyle, ICurrentUniverService, ISlidePage, Nullable, ObserverManager } from '@univerjs/core';
import { Inject, Injector } from '@wendellhu/redi';
+
import { ObjectProvider } from './ObjectProvider';
export enum SLIDE_KEY {
diff --git a/packages/common-plugin-data/src/Docs/DEFAULT_DOCUMENT_DATA_EN.ts b/packages/common-plugin-data/src/Docs/DEFAULT_DOCUMENT_DATA_EN.ts
index 4f56d81836..62c2e8c6c6 100644
--- a/packages/common-plugin-data/src/Docs/DEFAULT_DOCUMENT_DATA_EN.ts
+++ b/packages/common-plugin-data/src/Docs/DEFAULT_DOCUMENT_DATA_EN.ts
@@ -1,4 +1,5 @@
import { BooleanNumber, ColumnSeparatorType, IDocumentData, ObjectRelativeFromH, ObjectRelativeFromV, PositionedObjectLayoutType, SectionType, WrapTextType } from '@univerjs/core';
+
import { DEFAULT_LIST_TEST } from './DEFAULT_LIST';
export const DEFAULT_DOCUMENT_DATA_EN: IDocumentData = {
diff --git a/packages/common-plugin-data/src/Sheets/Demo/DEFAULT_WORKBOOK_DATA_DEMO.ts b/packages/common-plugin-data/src/Sheets/Demo/DEFAULT_WORKBOOK_DATA_DEMO.ts
index a7ea6e8800..fd45797a71 100644
--- a/packages/common-plugin-data/src/Sheets/Demo/DEFAULT_WORKBOOK_DATA_DEMO.ts
+++ b/packages/common-plugin-data/src/Sheets/Demo/DEFAULT_WORKBOOK_DATA_DEMO.ts
@@ -1,4 +1,5 @@
import { BooleanNumber, IDocumentData, IWorkbookConfig, LocaleType, SheetTypes } from '@univerjs/core';
+
import { PAGE5_RICHTEXT_1 } from '../../Slides/RichText/PAGE5_RICHTEXT_1';
const richTextDemo: IDocumentData = {
diff --git a/packages/core/src/Docs/Domain/DocumentBodyModel.ts b/packages/core/src/Docs/Domain/DocumentBodyModel.ts
index de89b8354a..c2fcda599a 100644
--- a/packages/core/src/Docs/Domain/DocumentBodyModel.ts
+++ b/packages/core/src/Docs/Domain/DocumentBodyModel.ts
@@ -1,6 +1,5 @@
-import { IDocumentBody, ITextRun } from '../../Types/Interfaces/IDocumentData';
-
import { Nullable } from '../../Shared/Types';
+import { IDocumentBody, ITextRun } from '../../Types/Interfaces/IDocumentData';
import { DataStreamTreeNode } from './DataStreamTreeNode';
import { DataStreamTreeNodeType, DataStreamTreeTokenType } from './Types';
diff --git a/packages/core/src/Shared/Common.ts b/packages/core/src/Shared/Common.ts
index d2dcaef380..eec053e645 100644
--- a/packages/core/src/Shared/Common.ts
+++ b/packages/core/src/Shared/Common.ts
@@ -1,11 +1,12 @@
-import { Tools } from './Tools';
-import { Nullable } from './Types';
-import { IDocumentData } from '../Types/Interfaces/IDocumentData';
+import { ColorBuilder } from '../Sheets/Domain';
+import { BaselineOffset, BorderStyleTypes, HorizontalAlign, TextDirection, VerticalAlign, WrapStrategy } from '../Types/Enum';
+import { IRangeData } from '../Types/Interfaces';
import { ICellData } from '../Types/Interfaces/ICellData';
+import { IDocumentData } from '../Types/Interfaces/IDocumentData';
+import { ICellInfo, ICellRange, ISelection } from '../Types/Interfaces/ISelectionData';
import { IColorStyle, IStyleData } from '../Types/Interfaces/IStyleData';
-import { ICellInfo, ISelection } from '../Types/Interfaces/ISelectionData';
-import { ColorBuilder } from '../Sheets/Domain';
-import { BaselineOffset, TextDirection, HorizontalAlign, VerticalAlign, WrapStrategy, BorderStyleTypes } from '../Types/Enum';
+import { Tools } from './Tools';
+import { Nullable } from './Types';
export function makeCellToSelection(cellInfo: Nullable<ICellInfo>): Nullable<ISelection> {
if (!cellInfo) {
@@ -50,6 +51,30 @@ export function makeCellToSelection(cellInfo: Nullable<ICellInfo>): Nullable<ISe
};
}
+export function makeCellRangeToRangeData(cellInfo: Nullable<ICellRange>): Nullable<IRangeData> {
+ if (!cellInfo) {
+ return;
+ }
+ const { row, column, isMerged, startRow: mergeStartRow, startColumn: mergeStartColumn, endRow: mergeEndRow, endColumn: mergeEndColumn } = cellInfo;
+ let startRow = row;
+ let startColumn = column;
+ let endRow = row;
+ let endColumn = column;
+ if (isMerged) {
+ startRow = mergeStartRow;
+ startColumn = mergeStartColumn;
+ endRow = mergeEndRow;
+ endColumn = mergeEndColumn;
+ }
+
+ return {
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
+ };
+}
+
export function isEmptyCell(cell: Nullable<ICellData>) {
if (!cell) {
return true;
diff --git a/packages/core/src/Shared/ObjectMatrix.ts b/packages/core/src/Shared/ObjectMatrix.ts
index 3fd304fb15..944e4cf142 100644
--- a/packages/core/src/Shared/ObjectMatrix.ts
+++ b/packages/core/src/Shared/ObjectMatrix.ts
@@ -241,6 +241,14 @@ export class ObjectMatrix<T> {
};
}
+ toNativeArray(): T[] {
+ const native = new Array<T>();
+ this.forValue((row: number, col: number, value: T) => {
+ native.push(value);
+ });
+ return native;
+ }
+
toArray(): T[][] {
return this._option.toArray().map((item) => new ObjectArray(item).toArray()) as T[][];
}
diff --git a/packages/core/src/Sheets/Domain/Worksheet.ts b/packages/core/src/Sheets/Domain/Worksheet.ts
index e7664d54fa..745fa21832 100644
--- a/packages/core/src/Sheets/Domain/Worksheet.ts
+++ b/packages/core/src/Sheets/Domain/Worksheet.ts
@@ -5,7 +5,7 @@ import { ICurrentUniverService } from '../../services/current.service';
import { Nullable, ObjectMatrix, Tools } from '../../Shared';
import { DEFAULT_WORKSHEET } from '../../Types/Const';
import { BooleanNumber, SheetTypes } from '../../Types/Enum';
-import { ICellData, IRangeStringData, IRangeType, IWorksheetConfig } from '../../Types/Interfaces';
+import { ICellData, IRangeData, IRangeStringData, IRangeType, IWorksheetConfig } from '../../Types/Interfaces';
import { ColumnManager } from './ColumnManager';
import { Merges } from './Merges';
import { Range } from './Range';
@@ -252,6 +252,10 @@ export class Worksheet {
return this._config.zoomRatio || 1;
}
+ getMergeData(): IRangeData[] {
+ return this._config.mergeData;
+ }
+
/**
* Returns WorkSheet Configures
* @returns WorkSheet Configures
diff --git a/packages/core/src/Types/Const/CONST.ts b/packages/core/src/Types/Const/CONST.ts
index feb7af0651..b9d37d9c01 100644
--- a/packages/core/src/Types/Const/CONST.ts
+++ b/packages/core/src/Types/Const/CONST.ts
@@ -1,12 +1,4 @@
-import {
- BooleanNumber,
- HorizontalAlign,
- LocaleType,
- SheetTypes,
- TextDirection,
- VerticalAlign,
- WrapStrategy,
-} from '../Enum';
+import { BooleanNumber, HorizontalAlign, LocaleType, SheetTypes, TextDirection, VerticalAlign, WrapStrategy } from '../Enum';
import { IStyleData, IWorkbookConfig, IWorksheetConfig } from '../Interfaces';
/**
@@ -74,6 +66,18 @@ export const DEFAULT_WORKBOOK: IWorkbookConfig = {
namedRanges: [],
};
+export const DEFAULT_WORKSHEET_ROW_COUNT = 1000;
+
+export const DEFAULT_WORKSHEET_COLUMN_COUNT = 20;
+
+export const DEFAULT_WORKSHEET_ROW_HEIGHT = 19;
+
+export const DEFAULT_WORKSHEET_COLUMN_WIDTH = 73;
+
+export const DEFAULT_WORKSHEET_ROW_TITLE_WIDTH = 46;
+
+export const DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT = 20;
+
/**
* Used as an init worksheet return value
*/
@@ -84,14 +88,14 @@ export const DEFAULT_WORKSHEET: IWorksheetConfig = {
tabColor: '',
hidden: BooleanNumber.FALSE,
freezeColumn: -1,
- rowCount: 1000,
- columnCount: 100,
+ rowCount: DEFAULT_WORKSHEET_ROW_COUNT,
+ columnCount: DEFAULT_WORKSHEET_COLUMN_COUNT,
freezeRow: -1,
zoomRatio: 1,
scrollTop: 0,
scrollLeft: 0,
- defaultColumnWidth: 73,
- defaultRowHeight: 19,
+ defaultColumnWidth: DEFAULT_WORKSHEET_COLUMN_WIDTH,
+ defaultRowHeight: DEFAULT_WORKSHEET_ROW_HEIGHT,
mergeData: [],
hideRow: [],
hideColumn: [],
@@ -101,11 +105,11 @@ export const DEFAULT_WORKSHEET: IWorksheetConfig = {
status: BooleanNumber.FALSE,
showGridlines: BooleanNumber.TRUE,
rowTitle: {
- width: 46,
+ width: DEFAULT_WORKSHEET_ROW_TITLE_WIDTH,
hidden: BooleanNumber.FALSE,
},
columnTitle: {
- height: 20,
+ height: DEFAULT_WORKSHEET_COLUMN_TITLE_HEIGHT,
hidden: BooleanNumber.FALSE,
},
selections: ['A1'],
diff --git a/packages/core/src/Types/Interfaces/ICellData.ts b/packages/core/src/Types/Interfaces/ICellData.ts
index 0003698b71..00a8c4c89e 100644
--- a/packages/core/src/Types/Interfaces/ICellData.ts
+++ b/packages/core/src/Types/Interfaces/ICellData.ts
@@ -1,7 +1,7 @@
-import { IDocumentData } from './index';
+import { Nullable } from '../../Shared/Types';
import { FormatType } from '../Enum/FormatType';
import { CellValueType } from '../Enum/TextStyle';
-import { Nullable } from '../../Shared/Types';
+import { IDocumentData } from './IDocumentData';
import { IStyleData } from './IStyleData';
/**
@@ -73,4 +73,4 @@ export type ICellDataType = Nullable<ICellData> | Nullable<IStyleData> | string
/**
* Cell data matrix type
*/
-export type ICellDataMatrix = ICellDataType[][];
\ No newline at end of file
+export type ICellDataMatrix = ICellDataType[][];
diff --git a/packages/core/src/Types/Interfaces/IDocumentData.ts b/packages/core/src/Types/Interfaces/IDocumentData.ts
index f2d57a96ba..2edd4304dd 100644
--- a/packages/core/src/Types/Interfaces/IDocumentData.ts
+++ b/packages/core/src/Types/Interfaces/IDocumentData.ts
@@ -1,7 +1,7 @@
-import { IColorStyle, IStyleBase } from './IStyleData';
import { BooleanNumber, HorizontalAlign, LocaleType, TextDirection, VerticalAlign, WrapStrategy } from '../Enum';
import { IImageProperties } from './IImageProperties';
import { IShapeProperties } from './IShapeProperties';
+import { IColorStyle, IStyleBase } from './IStyleData';
// 注意:所有的尺寸单位,若无特殊说明,都是指pt,1 pt = 1 / 72 in
/**
diff --git a/packages/core/src/Types/Interfaces/ISelectionData.ts b/packages/core/src/Types/Interfaces/ISelectionData.ts
index b052011632..03316664ce 100644
--- a/packages/core/src/Types/Interfaces/ISelectionData.ts
+++ b/packages/core/src/Types/Interfaces/ISelectionData.ts
@@ -1,14 +1,9 @@
-import { Range } from '../../Sheets/Domain';
-import { IRangeData, IRangeType } from './IRangeData';
+import { Nullable } from '../../Shared/Types';
+import { IRangeData } from './IRangeData';
/**
* Properties of selection data
*/
-export interface ISelectionData {
- selection?: IRangeType | IRangeType[] | Range;
- cell?: IRangeType;
-}
-
export interface IPosition {
startX: number;
startY: number;
@@ -16,6 +11,15 @@ export interface IPosition {
endY: number;
}
+export interface ICellRange extends IRangeData {
+ row: number; // current cell, if cell is in merge, isMerged is true, If the cell is in the upper left corner, isMergedMainCell is true.
+ column: number;
+
+ isMerged: boolean;
+
+ isMergedMainCell: boolean;
+}
+
export interface ICellInfo extends IPosition {
row: number; // current cell, if cell is in merge, isMerged is true, If the cell is in the upper left corner, isMergedMainCell is true.
column: number;
@@ -27,6 +31,16 @@ export interface ICellInfo extends IPosition {
mergeInfo: ISelection; // merge cell, start and end is upper left cell
}
+export interface ISelectionRange {
+ rangeData: IRangeData;
+ cellRange: Nullable<ICellRange>;
+}
+
+export interface ISelectionData {
+ selection: ISelection;
+ cellInfo: Nullable<ICellInfo>;
+}
+
export interface ISelection extends IPosition, IRangeData {}
export interface ITextSelectionRangeStart {
diff --git a/packages/core/src/Types/Interfaces/IStyleData.ts b/packages/core/src/Types/Interfaces/IStyleData.ts
index 7705682692..a8d8679be1 100644
--- a/packages/core/src/Types/Interfaces/IStyleData.ts
+++ b/packages/core/src/Types/Interfaces/IStyleData.ts
@@ -1,7 +1,7 @@
+import { Nullable } from '../../Shared/Types';
import { BorderStyleTypes } from '../Enum/BorderStyleTypes';
-import { BooleanNumber, HorizontalAlign, TextDecoration, TextDirection, BaselineOffset, VerticalAlign, WrapStrategy } from '../Enum/TextStyle';
+import { BaselineOffset, BooleanNumber, HorizontalAlign, TextDecoration, TextDirection, VerticalAlign, WrapStrategy } from '../Enum/TextStyle';
import { ThemeColorType } from '../Enum/ThemeColorType';
-import { Nullable } from '../../Shared/Types';
/**
* Properties of text decoration
diff --git a/packages/sheets-plugin-find/src/Domain/TextFind.ts b/packages/sheets-plugin-find/src/Domain/TextFind.ts
index 474932a44e..8469ca620b 100644
--- a/packages/sheets-plugin-find/src/Domain/TextFind.ts
+++ b/packages/sheets-plugin-find/src/Domain/TextFind.ts
@@ -1,7 +1,10 @@
-import { Range, FormatType, IGridRange, ObjectMatrix, ICellData, Nullable, Worksheet, ICurrentUniverService } from '@univerjs/core';
-import { ISelectionManager, SelectionManager } from '@univerjs/base-sheets';
-import { getRegExpStr } from '../Util/util';
+import { ISelectionTransformerShapeManager } from '@univerjs/base-render';
+import { SelectionManagerService } from '@univerjs/base-sheets';
+import { FormatType, ICellData, ICurrentUniverService, IGridRange, Nullable, ObjectMatrix, Range, Worksheet } from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
+
import { FindType } from '../IData';
+import { getRegExpStr } from '../Util/util';
import { SelectSearch } from '../View/UI/FindModal';
export class TextFinder {
@@ -27,7 +30,11 @@ export class TextFinder {
private _startRange: Nullable<Range>; // 从这个位置后开始找
- constructor(@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService, @ISelectionManager private readonly _selectionManager: SelectionManager) {}
+ constructor(
+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @ISelectionTransformerShapeManager private readonly _selectionTransformerShapeManager: ISelectionTransformerShapeManager
+ ) {}
/**
* Returns all cells matching the search criteria.
@@ -297,7 +304,22 @@ export class TextFinder {
// 高亮匹配单元格
private _highlightCell(range: IGridRange) {
if (!range) return;
- this._selectionManager.setCurrentCell(range);
+ const workbook = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
+ const unitId = workbook.getUnitId();
+ const sheetId = range.sheetId;
+ const mergeData = workbook.getActiveSheet().getMergeData();
+
+ const selectionRange = this._selectionManagerService.transformCellDataToSelectionData(range.rangeData.startColumn, range.rangeData.endColumn, mergeData);
+ if (selectionRange == null) {
+ return;
+ }
+
+ this._selectionManagerService.replace([
+ {
+ ...selectionRange,
+ ...this._selectionManagerService.createDefaultSelection(),
+ },
+ ]);
}
private _replaceText(sheet: Worksheet, range: IGridRange, text: string) {
@@ -310,9 +332,9 @@ export class TextFinder {
match = 'g';
}
const reg = new RegExp(getRegExpStr(this._text as string), match);
- sheet.getRange(range.rangeData).setValue(value.m.replace(reg, text));
+ // sheet.getRange(range.rangeData).setValue(value.m.replace(reg, text));
} else {
- sheet.getRange(range.rangeData).setValue(text);
+ // sheet.getRange(range.rangeData).setValue(text);
}
}
}
diff --git a/packages/sheets-plugin-formula/src/Controller/FormulaController.ts b/packages/sheets-plugin-formula/src/Controller/FormulaController.ts
index c9d74aa4a4..9cfb3542da 100644
--- a/packages/sheets-plugin-formula/src/Controller/FormulaController.ts
+++ b/packages/sheets-plugin-formula/src/Controller/FormulaController.ts
@@ -1,5 +1,5 @@
import { ArrayFormulaDataType, FormulaEngineService, IInterpreterDatasetConfig, SheetDataType, SheetNameMapType, UnitDataType } from '@univerjs/base-formula-engine';
-import { ISelectionManager, SelectionManager } from '@univerjs/base-sheets';
+import { SelectionManagerService } from '@univerjs/base-sheets';
import { ICurrentUniverService } from '@univerjs/core';
import { Inject, Injector } from '@wendellhu/redi';
@@ -20,7 +20,7 @@ export class FormulaController {
constructor(
config: IFormulaConfig,
- @ISelectionManager private readonly _selectionManager: SelectionManager,
+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
@Inject(Injector) private readonly _sheetInjector: Injector
) {
@@ -126,12 +126,12 @@ export class FormulaController {
const arrayFormula = arrayFormulaData[this._activeSheetId];
if (!arrayFormula) return;
- const currentCellData = this._selectionManager.getCurrentCellData();
+ const currentCellData = this._selectionManagerService.getLast()?.cellInfo;
arrayFormula.forValue((r, c, v) => {
const { startRow, startColumn, endRow, endColumn } = v;
if (currentCellData) {
- const { startRow: row, startColumn: column } = currentCellData;
+ const { row, column } = currentCellData;
if (row >= startRow && row < endRow && column >= startColumn && column < endColumn) {
const arrayFormulaLineControl = this._sheetInjector.createInstance(ArrayFormulaLineControl, this._activeSheetId, v);
this._arrayFormulaLineControls.push(arrayFormulaLineControl);
diff --git a/packages/sheets-plugin-formula/src/Controller/SearchFormulaModalController.ts b/packages/sheets-plugin-formula/src/Controller/SearchFormulaModalController.ts
index 480d0d5c93..758ffa69d3 100644
--- a/packages/sheets-plugin-formula/src/Controller/SearchFormulaModalController.ts
+++ b/packages/sheets-plugin-formula/src/Controller/SearchFormulaModalController.ts
@@ -1,9 +1,9 @@
import { ComponentManager } from '@univerjs/base-ui';
-import { ObserverManager } from '@univerjs/core';
+import { ISelectionRange, ObserverManager } from '@univerjs/core';
import { SheetContainerUIController } from '@univerjs/ui-plugin-sheets';
import { Inject } from '@wendellhu/redi';
-import { SelectionControl } from '@univerjs/base-render/src/Component/Sheets/Selection/SelectionControl';
-import { FormulaType, FORMULA_PLUGIN_NAME, FunList, SelectCategoryType, FunParams, SearchFormulaModalData } from '../Basics';
+
+import { FORMULA_PLUGIN_NAME, FormulaType, FunList, FunParams, SearchFormulaModalData, SelectCategoryType } from '../Basics';
import { SearchFormulaContent } from '../View/UI/SearchFormulaModal/SearchFormulaContent';
import { SearchFormulaModal } from '../View/UI/SearchFormulaModal/SearchFormulaModal';
import { SearchItem } from '../View/UI/SearchFormulaModal/SearchItem';
@@ -129,8 +129,8 @@ export class SearchFormulaController {
private _initialize() {
this._initRegisterComponent();
- this._observerManager.getObserver<SelectionControl>('onChangeSelectionObserver')?.add((selection) => {
- const info = selection.getCurrentCellInfo();
+ this._observerManager.getObserver<ISelectionRange>('onChangeSelectionObserver')?.add((selection) => {
+ const info = selection.cellRange;
// this._searchItem.changeRange(info?.startColumn.toString() ?? '');
});
}
diff --git a/packages/sheets-plugin-image/src/services/upload.service.ts b/packages/sheets-plugin-image/src/services/upload.service.ts
index e095fc45b2..3e627f6a65 100644
--- a/packages/sheets-plugin-image/src/services/upload.service.ts
+++ b/packages/sheets-plugin-image/src/services/upload.service.ts
@@ -1,4 +1,4 @@
-import { ISelectionManager, SelectionManager } from '@univerjs/base-sheets';
+import { SelectionManagerService } from '@univerjs/base-sheets';
import { ICurrentUniverService } from '@univerjs/core';
import { Inject, Injector } from '@wendellhu/redi';
@@ -8,13 +8,19 @@ export class UploadService {
constructor(
@Inject(Injector) readonly _injector: Injector,
@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
- @ISelectionManager private readonly _selectionManager: SelectionManager
+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService
) {}
upload() {
- const { _selectionManager, _currentUniverService, _injector } = this;
- const rowIndex = _selectionManager.getActiveRange()?.getRowIndex();
- const columnIndex = _selectionManager.getActiveRange()?.getColumn();
+ const { _selectionManagerService, _currentUniverService, _injector } = this;
+ const selection = _selectionManagerService.getLast()?.selection;
+ const worksheet = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+ if (selection == null) {
+ return;
+ }
+ const activeRange = worksheet.getRange(selection);
+ const rowIndex = activeRange.getRowIndex();
+ const columnIndex = activeRange.getColumn();
const workbook = _currentUniverService.getCurrentUniverSheetInstance().getWorkBook();
FileSelected.chooseImage().then((file) => {
const reader = new FileReader();
diff --git a/packages/sheets-plugin-numfmt/src/Controller/menu.ts b/packages/sheets-plugin-numfmt/src/Controller/menu.ts
index 38d3878b59..3757ccd0c0 100644
--- a/packages/sheets-plugin-numfmt/src/Controller/menu.ts
+++ b/packages/sheets-plugin-numfmt/src/Controller/menu.ts
@@ -1,4 +1,3 @@
-import { ISelectionManager } from '@univerjs/base-sheets';
import { DisplayTypes, IMenuSelectorItem, MenuItemType, MenuPosition, SelectTypes } from '@univerjs/base-ui';
import { ICommandService, IPermissionService } from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
@@ -10,7 +9,7 @@ import { ShowModalOperation } from '../commands/operations/show-modal.operation'
export function NumfmtRangeDataMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string> {
const permissionService = accessor.get(IPermissionService);
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
+ // const selectionManager = accessor.get(ISelectionManager);
return {
id: SetNumfmtRangeDataCommand.id,
@@ -63,7 +62,7 @@ export function NumfmtRangeDataMenuItemFactory(accessor: IAccessor): IMenuSelect
export function OpenMoreFormatsModalMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string> {
const permissionService = accessor.get(IPermissionService);
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
+ // const selectionManager = accessor.get(ISelectionManager);
return {
// 2. suffix
id: ShowModalOperation.id,
diff --git a/packages/sheets-plugin-operation/src/Domain/Copy.ts b/packages/sheets-plugin-operation/src/Domain/Copy.ts
index 6c2b4ef97b..26e8ec0e28 100644
--- a/packages/sheets-plugin-operation/src/Domain/Copy.ts
+++ b/packages/sheets-plugin-operation/src/Domain/Copy.ts
@@ -1,7 +1,8 @@
-import { Tools, handleJsonToDom, handleStyleToString, IKeyValue, ICurrentUniverService } from '@univerjs/core';
-import { SelectionModel, SelectionController, ISelectionManager, SelectionManager } from '@univerjs/base-sheets';
-import { RightMenuItem } from '@univerjs/ui-plugin-sheets';
+import { SelectionManagerService } from '@univerjs/base-sheets';
import { Clipboard } from '@univerjs/base-ui';
+import { handleJsonToDom, handleStyleToString, ICurrentUniverService, IKeyValue, Tools } from '@univerjs/core';
+import { RightMenuItem } from '@univerjs/ui-plugin-sheets';
+import { Inject } from '@wendellhu/redi';
// import { ClipboardInput } from '../UI/ClipboardInput';
export abstract class Copy {
@@ -19,7 +20,10 @@ export abstract class Copy {
}
export class UniverCopy extends Copy {
- constructor(@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService, @ISelectionManager private readonly _selectionManager: SelectionManager) {
+ constructor(
+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService
+ ) {
const copyList = [
{
label: 'rightClick.copy',
@@ -240,10 +244,11 @@ export class UniverCopy extends Copy {
* TODO 加入univerId,sheetId,rangeData等 @tony
* @returns
*/
+ // eslint-disable-next-line max-lines-per-function
getCopyContent() {
- const { sheet, spreadsheet, selections } = this._getSheetInfo();
- if (selections.length > 1) return;
-
+ const { sheet, selections } = this._getSheetInfo();
+ if (!selections?.length) return;
+ const mergeData = sheet.getMergeData();
const rowManager = sheet.getRowManager().getRowData();
const colManager = sheet.getColumnManager().getColumnData();
const rowIndexArr: number[] = [];
@@ -327,12 +332,10 @@ export class UniverCopy extends Copy {
}
}
- const cellInfo = spreadsheet?.getCellByIndex(r, c);
- if (cellInfo?.isMerged || (!cellInfo?.isMerged && cellInfo?.isMergedMainCell)) {
- if (cellInfo.isMergedMainCell) {
- span = `rowSpan="${cellInfo.mergeInfo.endRow - cellInfo.mergeInfo.startRow + 1}" colSpan="${
- cellInfo.mergeInfo.endColumn - cellInfo.mergeInfo.startColumn + 1
- }"`;
+ const cellRange = this._selectionManagerService.transformCellDataToSelectionData(r, c, mergeData)?.cellRange;
+ if (cellRange?.isMerged || (!cellRange?.isMerged && cellRange?.isMergedMainCell)) {
+ if (cellRange.isMergedMainCell) {
+ span = `rowSpan="${cellRange.endRow - cellRange.startRow + 1}" colSpan="${cellRange.endColumn - cellRange.startColumn + 1}"`;
} else {
continue;
}
@@ -382,22 +385,13 @@ export class UniverCopy extends Copy {
private _getSheetInfo() {
const sheet = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
- const controls = this._selectionManager.getCurrentControls();
- const selections: any = controls?.map((control: SelectionController) => {
- const model: SelectionModel = control.model;
- return {
- startRow: model.startRow,
- startColumn: model.startColumn,
- endRow: model.endRow,
- endColumn: model.endColumn,
- };
- });
+ const selections = this._selectionManagerService.getRangeDatas();
return { sheet, selections };
}
private _getRangeInfo() {
const { sheet, selections } = this._getSheetInfo();
- if (!selections.length) return;
+ if (!selections?.length) return;
const range = sheet.getRange(selections[0]);
const rangeData = range.getValues();
if (!rangeData.length) return;
diff --git a/packages/sheets-plugin-operation/src/Domain/Paste.ts b/packages/sheets-plugin-operation/src/Domain/Paste.ts
index 4de8a53609..859ab52d37 100644
--- a/packages/sheets-plugin-operation/src/Domain/Paste.ts
+++ b/packages/sheets-plugin-operation/src/Domain/Paste.ts
@@ -1,22 +1,11 @@
-import { ISelectionManager, SelectionController, SelectionManager, SelectionModel } from '@univerjs/base-sheets';
-import { handleTableMergeData } from '@univerjs/base-ui';
+import { SelectionManagerService } from '@univerjs/base-sheets';
import {
- ACTION_NAMES,
- // AddMergeAction,
- IActionData,
- // IAddMergeActionData,
- ICellData,
ICurrentUniverService,
- IRangeData,
- // IRemoveMergeActionData,
- // ISetColumnWidthActionData,
- // ISetRangeDataActionData,
- // ISetRowHeightActionData,
Nullable,
- ObjectMatrix,
// RemoveMergeAction,
// SetRowHeightAction,
} from '@univerjs/core';
+import { Inject } from '@wendellhu/redi';
export interface PasteInfo {
data: Nullable<Array<[]>>;
@@ -31,7 +20,10 @@ export abstract class Paste {
}
export class UniverPaste extends Paste {
- constructor(@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService, @ISelectionManager private readonly _selectionManager: SelectionManager) {
+ constructor(
+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService
+ ) {
const pasteList = [
{
label: 'rightClick.paste',
@@ -44,152 +36,144 @@ export class UniverPaste extends Paste {
super();
}
- pasteTo(info: PasteInfo): IActionData[] {
- let actionDataList: IActionData[] = [];
- const { data, colInfo, rowInfo } = info;
- // const data = await this.pasteResolver(e);
- // if (data.length === 0) return;
- if (!data || !data.length) return [];
- const sheet = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
- if (!sheet) return [];
- const sheetId = sheet.getSheetId();
- const controls = this._selectionManager.getCurrentControls();
- const selections: any = controls?.map((control: SelectionController) => {
- const model: SelectionModel = control.model;
- return {
- startRow: model.startRow,
- startColumn: model.startColumn,
- endRow: model.endRow,
- endColumn: model.endColumn,
- };
- });
-
- if (!selections.length) {
- return [];
- }
-
- if (selections.length > 1) {
- return [];
- }
-
- const selection = selections[0];
-
- const copyH = data.length;
- const copyC = data[0].length;
-
- const minH = selection.startRow; //应用范围首尾行
- const maxH = minH + copyH - 1;
- const minC = selection.startColumn; //应用范围首尾列
- const maxC = minC + copyC - 1;
- const isMerge = sheet.getMerges().getByRowColumn(minH, maxH, minC, maxC);
- if (isMerge) {
- // const prompt = this.getContext()
- // .getUniver()
- // .getGlobalContext()
- // .getPluginManager()
- // .getRequirePluginByName<SheetUIPlugin>(SHEET_UI_PLUGIN_NAME)
- // .getSlot(SHEET_UI_PLUGIN_NAME + Prompt.name);
- // prompt.props.title = 'info.tooltip';
- // prompt.props.content = 'info.notChangeMerge';
- // prompt.showModal(true);
-
- return [];
- }
- // 最终渲染数据
- const tableData = handleTableMergeData(data, selection);
- const mergeData = tableData.mergeData;
- for (let i = 0; i < mergeData.length; i++) {
- // sheet.getMerges().add(mergeData[i]);
-
- // Don't trigger the API, return to the ExtensionManager after collection and trigger it in one Command, which is convenient for undo
- const mergeActionDataList = this._getMergeActionData(sheetId, mergeData[i]);
- actionDataList = actionDataList.concat(mergeActionDataList);
- }
- // sheet.getRange(minH, minC, maxH, maxC).setRangeDatas(tableData.data);
- const rangeActionData = this._getRangeActionData(sheetId, minH, minC, maxH, maxC, tableData.data);
- actionDataList.push(rangeActionData);
-
- const columnWidthActionDataList = this._getColumnWidthActionData(sheetId, colInfo, minC);
- actionDataList = actionDataList.concat(columnWidthActionDataList);
-
- const rowHeightActionDataList = this._getRowHeightActionData(sheetId, rowInfo, minH);
- actionDataList = actionDataList.concat(rowHeightActionDataList);
-
- // TODO
- // const selectionActionData = this._getSelectionActionData(sheetId);
- // selectionActionData && actionDataList.push(selectionActionData)
-
- return actionDataList;
- }
-
- private _getMergeActionData(sheetId: string, mergeData: IRangeData) {
- const removeAction: IRemoveMergeActionData = {
- actionName: RemoveMergeAction.NAME,
- sheetId,
- rectangles: [mergeData],
- };
- const appendAction: IAddMergeActionData = {
- actionName: AddMergeAction.NAME,
- sheetId,
- rectangles: [mergeData],
- };
- return [removeAction, appendAction];
- }
-
- private _getRangeActionData(sheetId: string, startRow: number, startColumn: number, endRow: number, endColumn: number, values: ICellData[][]) {
- const cellValue = new ObjectMatrix<ICellData>();
- for (let r = 0; r <= endRow - startRow; r++) {
- for (let c = 0; c <= endColumn - startColumn; c++) {
- cellValue.setValue(r + startRow, c + startColumn, values[r][c]);
- }
- }
-
- const setValue: ISetRangeDataActionData = {
- sheetId,
- actionName: ACTION_NAMES.SET_RANGE_DATA_ACTION,
- cellValue: cellValue.getData(),
- };
-
- return setValue;
- }
-
- private _getColumnWidthActionData(sheetId: string, colInfo: Nullable<number[]>, minC: number) {
- const actionDataList: ISetColumnWidthActionData[] = [];
- if (colInfo && colInfo.length) {
- for (let i = 0; i < colInfo.length; i++) {
- const columnIndex = minC + i;
- const columnWidth = [colInfo[i]];
- const setColumnWidth: ISetColumnWidthActionData = {
- sheetId,
- actionName: ACTION_NAMES.SET_COLUMN_WIDTH_ACTION,
- columnIndex,
- columnWidth,
- };
-
- actionDataList.push(setColumnWidth);
- }
- }
-
- return actionDataList;
- }
-
- private _getRowHeightActionData(sheetId: string, rowInfo: Nullable<number[]>, minH: number) {
- const actionDataList: ISetRowHeightActionData[] = [];
-
- if (rowInfo && rowInfo.length) {
- for (let i = 0; i < rowInfo.length; i++) {
- const rowIndex = minH + i;
- const rowHeight = [rowInfo[i]];
- const setRowHeight: ISetRowHeightActionData = {
- sheetId,
- actionName: SetRowHeightAction.NAME,
- rowIndex,
- rowHeight,
- };
- actionDataList.push(setRowHeight);
- }
- }
-
- return actionDataList;
- }
+ // pasteTo(info: PasteInfo): IActionData[] {
+ // let actionDataList: IActionData[] = [];
+ // const { data, colInfo, rowInfo } = info;
+ // // const data = await this.pasteResolver(e);
+ // // if (data.length === 0) return;
+ // if (!data || !data.length) return [];
+ // const sheet = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+ // if (!sheet) return [];
+ // const sheetId = sheet.getSheetId();
+
+ // const selections = this._selectionManagerService.getRangeDatas();
+
+ // if (!selections?.length) {
+ // return [];
+ // }
+
+ // if (selections.length > 1) {
+ // return [];
+ // }
+
+ // const selection = selections[0];
+
+ // const copyH = data.length;
+ // const copyC = data[0].length;
+
+ // const minH = selection.startRow; //应用范围首尾行
+ // const maxH = minH + copyH - 1;
+ // const minC = selection.startColumn; //应用范围首尾列
+ // const maxC = minC + copyC - 1;
+ // const isMerge = sheet.getMerges().getByRowColumn(minH, maxH, minC, maxC);
+ // if (isMerge) {
+ // // const prompt = this.getContext()
+ // // .getUniver()
+ // // .getGlobalContext()
+ // // .getPluginManager()
+ // // .getRequirePluginByName<SheetUIPlugin>(SHEET_UI_PLUGIN_NAME)
+ // // .getSlot(SHEET_UI_PLUGIN_NAME + Prompt.name);
+ // // prompt.props.title = 'info.tooltip';
+ // // prompt.props.content = 'info.notChangeMerge';
+ // // prompt.showModal(true);
+
+ // return [];
+ // }
+ // // 最终渲染数据
+ // const tableData = handleTableMergeData(data, selection);
+ // const mergeData = tableData.mergeData;
+ // for (let i = 0; i < mergeData.length; i++) {
+ // // sheet.getMerges().add(mergeData[i]);
+
+ // // Don't trigger the API, return to the ExtensionManager after collection and trigger it in one Command, which is convenient for undo
+ // const mergeActionDataList = this._getMergeActionData(sheetId, mergeData[i]);
+ // actionDataList = actionDataList.concat(mergeActionDataList);
+ // }
+ // // sheet.getRange(minH, minC, maxH, maxC).setRangeDatas(tableData.data);
+ // const rangeActionData = this._getRangeActionData(sheetId, minH, minC, maxH, maxC, tableData.data);
+ // actionDataList.push(rangeActionData);
+
+ // const columnWidthActionDataList = this._getColumnWidthActionData(sheetId, colInfo, minC);
+ // actionDataList = actionDataList.concat(columnWidthActionDataList);
+
+ // const rowHeightActionDataList = this._getRowHeightActionData(sheetId, rowInfo, minH);
+ // actionDataList = actionDataList.concat(rowHeightActionDataList);
+
+ // // TODO
+ // // const selectionActionData = this._getSelectionActionData(sheetId);
+ // // selectionActionData && actionDataList.push(selectionActionData)
+
+ // return actionDataList;
+ // }
+
+ // private _getMergeActionData(sheetId: string, mergeData: IRangeData) {
+ // const removeAction: IRemoveMergeActionData = {
+ // actionName: RemoveMergeAction.NAME,
+ // sheetId,
+ // rectangles: [mergeData],
+ // };
+ // const appendAction: IAddMergeActionData = {
+ // actionName: AddMergeAction.NAME,
+ // sheetId,
+ // rectangles: [mergeData],
+ // };
+ // return [removeAction, appendAction];
+ // }
+
+ // private _getRangeActionData(sheetId: string, startRow: number, startColumn: number, endRow: number, endColumn: number, values: ICellData[][]) {
+ // const cellValue = new ObjectMatrix<ICellData>();
+ // for (let r = 0; r <= endRow - startRow; r++) {
+ // for (let c = 0; c <= endColumn - startColumn; c++) {
+ // cellValue.setValue(r + startRow, c + startColumn, values[r][c]);
+ // }
+ // }
+
+ // const setValue: ISetRangeDataActionData = {
+ // sheetId,
+ // actionName: ACTION_NAMES.SET_RANGE_DATA_ACTION,
+ // cellValue: cellValue.getData(),
+ // };
+
+ // return setValue;
+ // }
+
+ // private _getColumnWidthActionData(sheetId: string, colInfo: Nullable<number[]>, minC: number) {
+ // const actionDataList: ISetColumnWidthActionData[] = [];
+ // if (colInfo && colInfo.length) {
+ // for (let i = 0; i < colInfo.length; i++) {
+ // const columnIndex = minC + i;
+ // const columnWidth = [colInfo[i]];
+ // const setColumnWidth: ISetColumnWidthActionData = {
+ // sheetId,
+ // actionName: ACTION_NAMES.SET_COLUMN_WIDTH_ACTION,
+ // columnIndex,
+ // columnWidth,
+ // };
+
+ // actionDataList.push(setColumnWidth);
+ // }
+ // }
+
+ // return actionDataList;
+ // }
+
+ // private _getRowHeightActionData(sheetId: string, rowInfo: Nullable<number[]>, minH: number) {
+ // const actionDataList: ISetRowHeightActionData[] = [];
+
+ // if (rowInfo && rowInfo.length) {
+ // for (let i = 0; i < rowInfo.length; i++) {
+ // const rowIndex = minH + i;
+ // const rowHeight = [rowInfo[i]];
+ // const setRowHeight: ISetRowHeightActionData = {
+ // sheetId,
+ // actionName: SetRowHeightAction.NAME,
+ // rowIndex,
+ // rowHeight,
+ // };
+ // actionDataList.push(setRowHeight);
+ // }
+ // }
+
+ // return actionDataList;
+ // }
}
diff --git a/packages/ui-plugin-sheets/src/Controller/CellEditorUIController.ts b/packages/ui-plugin-sheets/src/Controller/CellEditorUIController.ts
index 35d4d8f1ef..f0cd841b0a 100644
--- a/packages/ui-plugin-sheets/src/Controller/CellEditorUIController.ts
+++ b/packages/ui-plugin-sheets/src/Controller/CellEditorUIController.ts
@@ -1,7 +1,19 @@
-import { Engine, IMouseEvent, IPointerEvent, IRenderingEngine } from '@univerjs/base-render';
-import { CANVAS_VIEW_KEY, CanvasView, CellEditorController, ISelectionManager, SelectionManager } from '@univerjs/base-sheets';
+import { Engine, IMouseEvent, IPointerEvent, IRenderingEngine, ISelectionRangeWithStyle, ISelectionTransformerShapeManager, mergeCellHandler } from '@univerjs/base-render';
+import { CANVAS_VIEW_KEY, CanvasView, CellEditorController, SelectionManagerService } from '@univerjs/base-sheets';
import { $$, CellEditExtensionManager, handleDomToJson, handleStringToStyle, isCtrlPressed, KeyboardManager, setLastCaretPosition } from '@univerjs/base-ui';
-import { Direction, handleStyleToString, ICellData, isKeyPrintable, ObserverManager, Tools, UIObserver } from '@univerjs/core';
+import {
+ Direction,
+ handleStyleToString,
+ ICellData,
+ ICurrentUniverService,
+ IRangeData,
+ isKeyPrintable,
+ makeCellRangeToRangeData,
+ Nullable,
+ ObserverManager,
+ Tools,
+ UIObserver,
+} from '@univerjs/core';
import { Inject, SkipSelf } from '@wendellhu/redi';
import { RefObject } from 'react';
@@ -21,12 +33,15 @@ export class CellEditorUIController {
constructor(
private readonly _currentRefFetcher: () => RefObject<HTMLDivElement>,
+ @ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
@SkipSelf() @Inject(ObserverManager) private readonly _globalObserverManager: ObserverManager,
@IRenderingEngine private readonly _renderingEngine: Engine,
@Inject(CanvasView) private readonly _sheetCanvasView: CanvasView,
@Inject(ObserverManager) private readonly _selfObserverManager: ObserverManager,
- @Inject(CellEditorController) private readonly _cellEditorContorller: CellEditorController,
- @ISelectionManager private readonly _selectionManager: SelectionManager,
+ @Inject(CellEditorController) private readonly _cellEditorController: CellEditorController,
+ // @ISelectionManager private readonly _selectionManager: SelectionManager,
+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
+ @ISelectionTransformerShapeManager private readonly _selectionTransformerShapeManager: ISelectionTransformerShapeManager,
@Inject(KeyboardManager) private readonly _keyboardManager: KeyboardManager
) {
this._initialize();
@@ -92,9 +107,11 @@ export class CellEditorUIController {
}, 1);
this.isEditMode = true;
- this._cellEditorContorller.setEditMode(this.isEditMode);
+ this._cellEditorController.setEditMode(this.isEditMode);
- const currentCell = this._selectionManager.getCurrentCellModel();
+ const cellRange = this._selectionManagerService.getLast()?.cellRange;
+
+ const currentCell = this._selectionTransformerShapeManager.convertCellRangeToInfo(cellRange);
if (!currentCell) {
return false;
@@ -140,7 +157,7 @@ export class CellEditorUIController {
this._richTextEle.style.transform = '';
// this._plugin.showMainByName('cellEditor', true).then(() => {
- let cellValue = this._cellEditorContorller.getSelectionValue();
+ let cellValue = this._cellEditorController.getSelectionValue();
// Intercept, the formula needs to modify the value of the edit state
const cell = this._cellEditExtensionManager.handle({
@@ -158,7 +175,7 @@ export class CellEditorUIController {
}
this._richText.setValue(cellValue);
- const style = this._cellEditorContorller.getSelectionStyle();
+ const style = this._cellEditorController.getSelectionStyle();
this._richTextEditEle.style.cssText = '';
@@ -168,7 +185,7 @@ export class CellEditorUIController {
}
// });
- this._cellEditorContorller.setCurrentEditRangeData();
+ this._cellEditorController.setCurrentEditRangeData();
}
exitEditMode() {
@@ -177,7 +194,7 @@ export class CellEditorUIController {
if (!this.isEditMode) return;
this.isEditMode = false;
- this._cellEditorContorller.setEditMode(this.isEditMode);
+ this._cellEditorController.setEditMode(this.isEditMode);
// this._plugin.showMainByName('cellEditor', false).then(() => {
const value = handleDomToJson(this._richTextEditEle);
const text = this._richTextEditEle.innerText;
@@ -201,7 +218,7 @@ export class CellEditorUIController {
if (Tools.isPlainObject(style)) {
cell.s = style;
}
- this._cellEditorContorller.setCurrentEditRangeValue(cell);
+ this._cellEditorController.setCurrentEditRangeValue(cell);
this.hideEditContainer();
}
@@ -272,7 +289,7 @@ export class CellEditorUIController {
const onKeyDownObservable = this._globalObserverManager.getObserver<KeyboardEvent>('onKeyDownObservable', 'core');
const onKeyCompositionStartObservable = this._globalObserverManager.getObserver<CompositionEvent>('onKeyCompositionStartObservable', 'core');
- const selectionManager = this._selectionManager;
+ const selectionManager = this._selectionManagerService;
if (onKeyDownObservable && !onKeyDownObservable.hasObservers()) {
onKeyDownObservable.add((evt: KeyboardEvent) => {
if (!isCtrlPressed(evt) && isKeyPrintable(evt.key)) {
@@ -285,11 +302,7 @@ export class CellEditorUIController {
if (this.isEditMode) {
this.exitEditMode();
- const currentCell = selectionManager.getCurrentCellModel();
- if (!currentCell?.isMerged) {
- // move to cell below
- selectionManager.move(Direction.DOWN);
- }
+ this._move(Direction.DOWN);
} else {
this.enterEditMode();
}
@@ -303,31 +316,31 @@ export class CellEditorUIController {
case 'ArrowUp':
if (!this.isEditMode) {
- selectionManager.move(Direction.UP);
+ this._move(Direction.UP);
}
break;
case 'ArrowDown':
if (!this.isEditMode) {
- selectionManager.move(Direction.DOWN);
+ this._move(Direction.DOWN);
}
break;
case 'ArrowLeft':
if (!this.isEditMode) {
- selectionManager.move(Direction.LEFT);
+ this._move(Direction.LEFT);
}
break;
case 'ArrowRight':
if (!this.isEditMode) {
- selectionManager.move(Direction.RIGHT);
+ this._move(Direction.RIGHT);
}
break;
case 'Tab':
if (!this.isEditMode) {
- selectionManager.move(Direction.RIGHT);
+ this._move(Direction.RIGHT);
}
evt.preventDefault();
break;
@@ -347,4 +360,107 @@ export class CellEditorUIController {
});
}
}
+
+ private _move(direction: Direction) {
+ const worksheet = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+ const rowCount = worksheet.getRowCount();
+ const columnCount = worksheet.getColumnCount();
+ const mergeData = worksheet.getMergeData();
+ const selectionData = this._selectionManagerService.getLast();
+
+ const moveSelectionData = this._getMoveCellInfo(direction, rowCount, columnCount, mergeData, selectionData);
+
+ if (moveSelectionData != null) {
+ // move to cell below
+ this._selectionManagerService.replace([moveSelectionData]);
+ }
+ }
+
+ /**
+ * Move the selection according to different directions, usually used for the shortcut key operation of ↑ ↓ ← →
+ * @param direction
+ * @returns
+ */
+ // eslint-disable-next-line max-lines-per-function
+ private _getMoveCellInfo(
+ direction: Direction,
+ rowCount: number,
+ columnCount: number,
+ mergeData: IRangeData[],
+ selectionData: Nullable<ISelectionRangeWithStyle>
+ ): Nullable<ISelectionRangeWithStyle> {
+ const cellRange = selectionData?.cellRange;
+
+ const style = selectionData?.style;
+
+ if (!cellRange) return;
+
+ let { startRow: mergeStartRow, startColumn: mergeStartColumn, endRow: mergeEndRow, endColumn: mergeEndColumn } = cellRange;
+
+ let { row, column } = cellRange;
+ // const rowCount = this._skeleton?.getRowCount() || DEFAULT_WORKSHEET_ROW_COUNT;
+ // const columnCount = this._skeleton?.getColumnCount() || DEFAULT_WORKSHEET_COLUMN_COUNT;
+ switch (direction) {
+ case Direction.UP:
+ if (cellRange.isMerged || cellRange.isMergedMainCell) {
+ row = --mergeStartRow;
+ } else {
+ row--;
+ }
+ if (row < 0) {
+ row = 0;
+ }
+ break;
+ case Direction.DOWN:
+ if (cellRange.isMerged || cellRange.isMergedMainCell) {
+ row = ++mergeEndRow;
+ } else {
+ row++;
+ }
+
+ if (row > rowCount) {
+ row = rowCount;
+ }
+ break;
+ case Direction.LEFT:
+ if (cellRange.isMerged || cellRange.isMergedMainCell) {
+ column = --mergeStartColumn;
+ } else {
+ column--;
+ }
+
+ if (column < 0) {
+ column = 0;
+ }
+ break;
+ case Direction.RIGHT:
+ if (cellRange.isMerged || cellRange.isMergedMainCell) {
+ column = ++mergeEndColumn;
+ } else {
+ column++;
+ }
+
+ if (column > columnCount) {
+ column = columnCount;
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ const newCellRange = mergeCellHandler(row, column, mergeData);
+
+ const newSelectionData = makeCellRangeToRangeData(newCellRange);
+
+ if (!newSelectionData) {
+ return;
+ }
+
+ return {
+ rangeData: newSelectionData,
+ cellRange: newCellRange,
+ style,
+ };
+ }
}
diff --git a/packages/ui-plugin-sheets/src/Controller/CountBarUIController.ts b/packages/ui-plugin-sheets/src/Controller/CountBarUIController.ts
index c376c96835..05e2b550f0 100644
--- a/packages/ui-plugin-sheets/src/Controller/CountBarUIController.ts
+++ b/packages/ui-plugin-sheets/src/Controller/CountBarUIController.ts
@@ -1,4 +1,4 @@
-import { ISelectionManager, SelectionManager } from '@univerjs/base-sheets';
+import { SelectionManagerService } from '@univerjs/base-sheets';
import { ICurrentUniverService, ObserverManager, RangeList, Tools, UIObserver } from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
@@ -9,7 +9,7 @@ export class CountBarUIController {
constructor(
@ICurrentUniverService private readonly _currentUniverService: ICurrentUniverService,
- @ISelectionManager private readonly _selectionManager: SelectionManager,
+ @Inject(SelectionManagerService) private readonly _selectionManagerService: SelectionManagerService,
@Inject(ObserverManager) private readonly _observerManager: ObserverManager
) {
// CommandManager.getActionObservers().add((event) => {
@@ -38,9 +38,10 @@ export class CountBarUIController {
// });
this._observerManager.getObserver('onChangeSelectionObserver')?.add(() => {
- const rangeList = this._selectionManager.getActiveRangeList();
+ const rangeList = this._selectionManagerService.getRangeDatas();
+ const worksheet = this._currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
if (rangeList && this._countBar) {
- this._totalRangeList(rangeList);
+ this._totalRangeList(worksheet.getRangeList(rangeList));
}
});
}
diff --git a/packages/ui-plugin-sheets/src/Controller/FormulaBarUIController.ts b/packages/ui-plugin-sheets/src/Controller/FormulaBarUIController.ts
index f5f9118e1b..41066e10b3 100644
--- a/packages/ui-plugin-sheets/src/Controller/FormulaBarUIController.ts
+++ b/packages/ui-plugin-sheets/src/Controller/FormulaBarUIController.ts
@@ -1,8 +1,7 @@
+import { CellInputExtensionManager } from '@univerjs/base-ui';
+import { ICurrentUniverService, INamedRange, ISelectionRange, ObserverManager } from '@univerjs/core';
import { Inject } from '@wendellhu/redi';
-import { SelectionControl } from '@univerjs/base-render/src/Component/Sheets/Selection/SelectionControl';
-import { CellInputExtensionManager } from '@univerjs/base-ui';
-import { ICurrentUniverService, INamedRange, ObserverManager } from '@univerjs/core';
import { FormulaBar } from '../View/FormulaBar';
export class FormulaBarUIController {
@@ -28,20 +27,18 @@ export class FormulaBarUIController {
}
private _initialize() {
- this._observerManager.getObserver<SelectionControl>('onChangeSelectionObserver')?.add((selectionControl: SelectionControl) => {
- const currentCell = selectionControl.model.currentCell;
+ this._observerManager.getObserver<ISelectionRange>('onChangeSelectionObserver')?.add((selectionRange: ISelectionRange) => {
+ const currentCell = selectionRange.cellRange;
if (currentCell) {
let currentRangeData;
if (currentCell.isMerged) {
- const mergeInfo = currentCell.mergeInfo;
-
currentRangeData = {
- startRow: mergeInfo.startRow,
- endRow: mergeInfo.endRow,
- startColumn: mergeInfo.startColumn,
- endColumn: mergeInfo.endColumn,
+ startRow: currentCell.startRow,
+ endRow: currentCell.endRow,
+ startColumn: currentCell.startColumn,
+ endColumn: currentCell.endColumn,
};
} else {
const { row, column } = currentCell;
diff --git a/packages/ui-plugin-sheets/src/Controller/menu.ts b/packages/ui-plugin-sheets/src/Controller/menu.ts
index 14427d8135..d96eb86b3c 100644
--- a/packages/ui-plugin-sheets/src/Controller/menu.ts
+++ b/packages/ui-plugin-sheets/src/Controller/menu.ts
@@ -5,12 +5,12 @@ import {
DeleteRangeMoveUpCommand,
InsertColAfterCommand,
InsertRowAfterCommand,
- ISelectionManager,
RemoveColCommand,
RemoveRowCommand,
RemoveSheetCommand,
ResetBackgroundColorCommand,
ResetTextColorCommand,
+ SelectionManagerService,
SetBackgroundColorCommand,
SetBoldCommand,
SetFontFamilyCommand,
@@ -38,6 +38,7 @@ import {
FontWeight,
HorizontalAlign,
ICommandService,
+ ICurrentUniverService,
IPermissionService,
IUndoRedoService,
RedoCommand,
@@ -88,7 +89,8 @@ export function RedoMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
export function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
const commandService = accessor.get(ICommandService);
const permissionService = accessor.get(IPermissionService);
- const selectionManager = accessor.get(ISelectionManager);
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const selectionManagerService = accessor.get(SelectionManagerService);
return {
id: SetBoldCommand.id,
@@ -121,8 +123,13 @@ export function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
return;
}
- const range = selectionManager.getCurrentCell();
- const isBold = range?.getFontWeight();
+ const cellRange = selectionManagerService.getLast()?.cellRange;
+ const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+ let isBold = FontWeight.NORMAL;
+ if (cellRange != null) {
+ const range = worksheet.getRange(cellRange.row, cellRange.column);
+ isBold = range?.getFontWeight();
+ }
subscriber.next(isBold === FontWeight.BOLD);
});
@@ -136,7 +143,8 @@ export function BoldMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
export function ItalicMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
const permissionService = accessor.get(IPermissionService);
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const selectionManagerService = accessor.get(SelectionManagerService);
return {
id: SetItalicCommand.id,
@@ -168,8 +176,13 @@ export function ItalicMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
return;
}
- const range = selectionManager.getCurrentCell();
- const isItalic = range?.getFontStyle();
+ const cellRange = selectionManagerService.getLast()?.cellRange;
+ const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+ let isItalic = FontItalic.NORMAL;
+ if (cellRange != null) {
+ const range = worksheet.getRange(cellRange.row, cellRange.column);
+ isItalic = range?.getFontStyle();
+ }
subscriber.next(isItalic === FontItalic.ITALIC);
});
@@ -183,7 +196,8 @@ export function ItalicMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
export function UnderlineMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
const permissionService = accessor.get(IPermissionService);
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const selectionManagerService = accessor.get(SelectionManagerService);
return {
id: SetUnderlineCommand.id,
@@ -215,8 +229,13 @@ export function UnderlineMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
return;
}
- const range = selectionManager.getCurrentCell();
- const isUnderline = range?.getUnderline();
+ const cellRange = selectionManagerService.getLast()?.cellRange;
+ const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+ let isUnderline;
+ if (cellRange != null) {
+ const range = worksheet.getRange(cellRange.row, cellRange.column);
+ isUnderline = range?.getUnderline();
+ }
subscriber.next(!!(isUnderline && isUnderline.s));
});
@@ -230,7 +249,8 @@ export function UnderlineMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
export function StrikeThroughMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
const permissionService = accessor.get(IPermissionService);
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const selectionManagerService = accessor.get(SelectionManagerService);
return {
id: SetStrikeThroughCommand.id,
@@ -262,8 +282,13 @@ export function StrikeThroughMenuItemFactory(accessor: IAccessor): IMenuButtonIt
return;
}
- const range = selectionManager.getCurrentCell();
- const st = range?.getStrikeThrough();
+ const cellRange = selectionManagerService.getLast()?.cellRange;
+ const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+ let st;
+ if (cellRange != null) {
+ const range = worksheet.getRange(cellRange.row, cellRange.column);
+ st = range?.getStrikeThrough();
+ }
subscriber.next(!!(st && st.s));
});
@@ -277,7 +302,8 @@ export function StrikeThroughMenuItemFactory(accessor: IAccessor): IMenuButtonIt
export function FontFamilySelectorMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string> {
const permissionService = accessor.get(IPermissionService);
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const selectionManagerService = accessor.get(SelectionManagerService);
return {
id: SetFontFamilyCommand.id,
@@ -314,8 +340,13 @@ export function FontFamilySelectorMenuItemFactory(accessor: IAccessor): IMenuSel
return;
}
- const range = selectionManager.getCurrentCell();
- const ff = range?.getFontFamily();
+ const cellRange = selectionManagerService.getLast()?.cellRange;
+ const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+ let ff;
+ if (cellRange != null) {
+ const range = worksheet.getRange(cellRange.row, cellRange.column);
+ ff = range?.getFontFamily();
+ }
subscriber.next(ff ?? defaultValue);
});
@@ -329,7 +360,8 @@ export function FontFamilySelectorMenuItemFactory(accessor: IAccessor): IMenuSel
export function FontSizeSelectorMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<number> {
const permissionService = accessor.get(IPermissionService);
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const selectionManagerService = accessor.get(SelectionManagerService);
return {
id: SetFontSizeCommand.id,
@@ -365,10 +397,15 @@ export function FontSizeSelectorMenuItemFactory(accessor: IAccessor): IMenuSelec
return;
}
- const range = selectionManager.getCurrentCell();
- const fs = range?.getFontSize() ?? DEFAULT_SIZE;
+ const cellRange = selectionManagerService.getLast()?.cellRange;
+ const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+ let fs;
+ if (cellRange != null) {
+ const range = worksheet.getRange(cellRange.row, cellRange.column);
+ fs = range?.getFontSize();
+ }
- subscriber.next(fs);
+ subscriber.next(fs ?? DEFAULT_SIZE);
});
subscriber.next(DEFAULT_SIZE);
@@ -389,7 +426,6 @@ export function ResetTextColorMenuItemFactory(accessor: IAccessor): IMenuButtonI
export function TextColorSelectorMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string> {
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
return {
id: SetTextColorCommand.id,
@@ -431,7 +467,6 @@ export function ResetBackgroundColorMenuItemFactory(accessor: IAccessor): IMenuB
export function BackgroundColorSelectorMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string> {
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
return {
id: SetBackgroundColorCommand.id,
@@ -469,7 +504,8 @@ export function BackgroundColorSelectorMenuItemFactory(accessor: IAccessor): IMe
// }
export function HorizontalAlignMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<HorizontalAlign> {
- const selectionManager = accessor.get(ISelectionManager);
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const selectionManagerService = accessor.get(SelectionManagerService);
return {
id: SetHorizontalTextAlignCommand.id,
title: 'horizontalAlignMode',
@@ -487,8 +523,13 @@ export function HorizontalAlignMenuItemFactory(accessor: IAccessor): IMenuSelect
return;
}
- const range = selectionManager.getCurrentCell();
- const ha = range?.getHorizontalAlignment();
+ const cellRange = selectionManagerService.getLast()?.cellRange;
+ const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+ let ha;
+ if (cellRange != null) {
+ const range = worksheet.getRange(cellRange.row, cellRange.column);
+ ha = range?.getHorizontalAlignment();
+ }
subscriber.next(ha ?? HorizontalAlign.LEFT);
});
@@ -501,7 +542,8 @@ export function HorizontalAlignMenuItemFactory(accessor: IAccessor): IMenuSelect
}
export function VerticalAlignMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<VerticalAlign> {
- const selectionManager = accessor.get(ISelectionManager);
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const selectionManagerService = accessor.get(SelectionManagerService);
return {
id: SetVerticalTextAlignCommand.id,
title: 'verticalAlignMode',
@@ -519,8 +561,13 @@ export function VerticalAlignMenuItemFactory(accessor: IAccessor): IMenuSelector
return;
}
- const range = selectionManager.getCurrentCell();
- const va = range?.getVerticalAlignment();
+ const cellRange = selectionManagerService.getLast()?.cellRange;
+ const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+ let va;
+ if (cellRange != null) {
+ const range = worksheet.getRange(cellRange.row, cellRange.column);
+ va = range?.getVerticalAlignment();
+ }
subscriber.next(va ?? VerticalAlign.TOP);
});
@@ -533,7 +580,8 @@ export function VerticalAlignMenuItemFactory(accessor: IAccessor): IMenuSelector
}
export function WrapTextMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<WrapStrategy> {
- const selectionManager = accessor.get(ISelectionManager);
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const selectionManagerService = accessor.get(SelectionManagerService);
return {
id: SetTextWrapCommand.id,
title: 'textWrapMode',
@@ -551,8 +599,13 @@ export function WrapTextMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<
return;
}
- const range = selectionManager.getCurrentCell();
- const ws = range?.getWrapStrategy();
+ const cellRange = selectionManagerService.getLast()?.cellRange;
+ const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+ let ws;
+ if (cellRange != null) {
+ const range = worksheet.getRange(cellRange.row, cellRange.column);
+ ws = range?.getWrapStrategy();
+ }
subscriber.next(ws ?? WrapStrategy.OVERFLOW);
});
@@ -565,7 +618,8 @@ export function WrapTextMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<
}
export function TextRotateMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<number | string> {
- const selectionManager = accessor.get(ISelectionManager);
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const selectionManagerService = accessor.get(SelectionManagerService);
return {
id: SetTextRotationCommand.id,
title: 'textRotateMode',
@@ -583,8 +637,13 @@ export function TextRotateMenuItemFactory(accessor: IAccessor): IMenuSelectorIte
return;
}
- const range = selectionManager.getCurrentCell();
- const tr = range?.getTextRotation();
+ const cellRange = selectionManagerService.getLast()?.cellRange;
+ const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+ let tr;
+ if (cellRange != null) {
+ const range = worksheet.getRange(cellRange.row, cellRange.column);
+ tr = range?.getTextRotation();
+ }
subscriber.next((tr && tr.a) ?? 0);
});
@@ -661,7 +720,8 @@ export function RemoveColMenuItemFactory(accessor: IAccessor): IMenuButtonItem {
export function SetRowHeightMenuItemFactory(accessor: IAccessor): IMenuButtonItem<number> {
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const selectionManagerService = accessor.get(SelectionManagerService);
return {
id: SetWorksheetRowHeightCommand.id,
@@ -678,8 +738,13 @@ export function SetRowHeightMenuItemFactory(accessor: IAccessor): IMenuButtonIte
},
value$: new Observable((subscriber) => {
function update() {
- const range = selectionManager.getCurrentCell();
- const rowHeight = range?.getHeight();
+ const cellRange = selectionManagerService.getLast()?.cellRange;
+ const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+ let rowHeight;
+ if (cellRange != null) {
+ const range = worksheet.getRange(cellRange.row, cellRange.column);
+ rowHeight = range?.getHeight();
+ }
subscriber.next(rowHeight ?? 0);
}
@@ -699,7 +764,8 @@ export function SetRowHeightMenuItemFactory(accessor: IAccessor): IMenuButtonIte
export function SetColWidthMenuItemFactory(accessor: IAccessor): IMenuButtonItem<number> {
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
+ const currentUniverService = accessor.get(ICurrentUniverService);
+ const selectionManagerService = accessor.get(SelectionManagerService);
return {
id: SetWorksheetColWidthCommand.id,
@@ -716,8 +782,13 @@ export function SetColWidthMenuItemFactory(accessor: IAccessor): IMenuButtonItem
},
value$: new Observable((subscriber) => {
function update() {
- const range = selectionManager.getCurrentCell();
- const rowHeight = range?.getWidth();
+ const cellRange = selectionManagerService.getLast()?.cellRange;
+ const worksheet = currentUniverService.getCurrentUniverSheetInstance().getWorkBook().getActiveSheet();
+ let rowHeight;
+ if (cellRange != null) {
+ const range = worksheet.getRange(cellRange.row, cellRange.column);
+ rowHeight = range?.getWidth();
+ }
subscriber.next(rowHeight ?? 0);
}
diff --git a/packages/ui-plugin-sheets/src/Controller/menu/border.menu.ts b/packages/ui-plugin-sheets/src/Controller/menu/border.menu.ts
index cbe43daac9..6ab74e2082 100644
--- a/packages/ui-plugin-sheets/src/Controller/menu/border.menu.ts
+++ b/packages/ui-plugin-sheets/src/Controller/menu/border.menu.ts
@@ -1,4 +1,4 @@
-import { BorderStyleManagerService, ISelectionManager, SetBorderColorCommand, SetBorderPositionCommand, SetBorderStyleCommand } from '@univerjs/base-sheets';
+import { BorderStyleManagerService, SetBorderColorCommand, SetBorderPositionCommand, SetBorderStyleCommand } from '@univerjs/base-sheets';
import { ColorPicker, DisplayTypes, IMenuSelectorItem, MenuItemType, MenuPosition, SelectTypes } from '@univerjs/base-ui';
import { BorderStyleTypes, ICommandService, IPermissionService } from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
@@ -114,7 +114,7 @@ export const BORDER_SIZE_CHILDREN = [
export function CellBorderSelectorMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string> {
const permissionService = accessor.get(IPermissionService);
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
+
const borderStyleManagerService = accessor.get(BorderStyleManagerService);
return {
id: SetBorderPositionCommand.id,
@@ -132,7 +132,7 @@ export function CellBorderSelectorMenuItemFactory(accessor: IAccessor): IMenuSel
export function SetBorderColorMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string> {
const permissionService = accessor.get(IPermissionService);
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
+
const borderStyleManagerService = accessor.get(BorderStyleManagerService);
return {
id: SetBorderColorCommand.id,
@@ -153,7 +153,7 @@ export function SetBorderColorMenuItemFactory(accessor: IAccessor): IMenuSelecto
export function SetBorderStyleMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<BorderStyleTypes> {
const permissionService = accessor.get(IPermissionService);
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
+
const borderStyleManagerService = accessor.get(BorderStyleManagerService);
return {
id: SetBorderStyleCommand.id,
diff --git a/packages/ui-plugin-sheets/src/Controller/menu/merge.menu.ts b/packages/ui-plugin-sheets/src/Controller/menu/merge.menu.ts
index 586a5350f4..cd8746abb5 100644
--- a/packages/ui-plugin-sheets/src/Controller/menu/merge.menu.ts
+++ b/packages/ui-plugin-sheets/src/Controller/menu/merge.menu.ts
@@ -3,7 +3,6 @@ import {
AddWorksheetMergeCommand,
AddWorksheetMergeHorizontalCommand,
AddWorksheetMergeVerticalCommand,
- ISelectionManager,
RemoveWorksheetMergeCommand,
} from '@univerjs/base-sheets';
import { DisplayTypes, IMenuButtonItem, IMenuSelectorItem, MenuItemType, MenuPosition, SelectTypes } from '@univerjs/base-ui';
@@ -32,7 +31,7 @@ export const MERGE_CHILDREN = [
// export function CellMergeSelectorMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string> {
// const permissionService = accessor.get(IPermissionService);
// const commandService = accessor.get(ICommandService);
-// const selectionManager = accessor.get(ISelectionManager);
+
// return {
// id: AddWorksheetMergeCommand.id,
// title: 'merge',
@@ -48,7 +47,7 @@ export const MERGE_CHILDREN = [
export function CellMergeMenuItemFactory(accessor: IAccessor): IMenuSelectorItem<string> {
const permissionService = accessor.get(IPermissionService);
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
+
return {
id: AddWorksheetMergeCommand.id,
title: 'merge',
@@ -63,7 +62,7 @@ export function CellMergeMenuItemFactory(accessor: IAccessor): IMenuSelectorItem
export function CellMergeAllMenuItemFactory(accessor: IAccessor): IMenuButtonItem<string> {
const permissionService = accessor.get(IPermissionService);
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
+
return {
id: AddWorksheetMergeAllCommand.id,
type: MenuItemType.BUTTON,
@@ -74,7 +73,7 @@ export function CellMergeAllMenuItemFactory(accessor: IAccessor): IMenuButtonIte
export function CellMergeVerticalMenuItemFactory(accessor: IAccessor): IMenuButtonItem<string> {
const permissionService = accessor.get(IPermissionService);
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
+
return {
id: AddWorksheetMergeVerticalCommand.id,
type: MenuItemType.BUTTON,
@@ -85,7 +84,7 @@ export function CellMergeVerticalMenuItemFactory(accessor: IAccessor): IMenuButt
export function CellMergeHorizontalMenuItemFactory(accessor: IAccessor): IMenuButtonItem<string> {
const permissionService = accessor.get(IPermissionService);
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
+
return {
id: AddWorksheetMergeHorizontalCommand.id,
type: MenuItemType.BUTTON,
@@ -96,7 +95,7 @@ export function CellMergeHorizontalMenuItemFactory(accessor: IAccessor): IMenuBu
export function CellMergeCancelMenuItemFactory(accessor: IAccessor): IMenuButtonItem<string> {
const permissionService = accessor.get(IPermissionService);
const commandService = accessor.get(ICommandService);
- const selectionManager = accessor.get(ISelectionManager);
+
return {
id: RemoveWorksheetMergeCommand.id,
type: MenuItemType.BUTTON,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 3266bd3f89..f58c65c502 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -561,6 +561,9 @@ importers:
react-dom:
specifier: ^18.2.0
version: 18.2.0([email protected])
+ rxjs:
+ specifier: ^7.8.1
+ version: 7.8.1
devDependencies:
'@types/jest':
specifier: ^29.5.4