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.

fix: selection highlight (#3919)

lumix83c8d47c92b8
diff --git a/.vscode/settings.json b/.vscode/settings.json
index be13b55381..953741bc40 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -80,6 +80,7 @@
"LRTBV",
"LTRB",
"Luckysheet",
+ "lumixraku",
"makearray",
"mengshukeji",
"Monoton",
diff --git a/examples-node/src/locales.ts b/examples-node/src/locales.ts
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 2854679399..7196b4fb30 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -164,7 +164,7 @@ export {
} from './sheets/sheet-snapshot-utils';
export { Styles } from './sheets/styles';
export * from './sheets/typedef';
-export { isRangesEqual, isUnitRangesEqual } from './sheets/util';
+export { addLinkToDocumentModel, isRangesEqual, isUnitRangesEqual } from './sheets/util';
export { SheetViewModel } from './sheets/view-model';
// #endregion
diff --git a/packages/core/src/shared/common.ts b/packages/core/src/shared/common.ts
index 7e897ab2d2..f0243cb46c 100644
--- a/packages/core/src/shared/common.ts
+++ b/packages/core/src/shared/common.ts
@@ -14,9 +14,12 @@
* limitations under the License.
*/
-import type { ICellData, ICellDataForSheetInterceptor, IRange, IRangeWithCoord, ISelectionCell, ISelectionCellWithMergeInfo } from '../sheets/typedef';
-import { RANGE_TYPE } from '../sheets/typedef';
+import type { ICellData, ICellDataForSheetInterceptor, ICellWithCoord, IRange, IRangeWithCoord, ISelectionCell } from '../sheets/typedef';
import type { Worksheet } from '../sheets/worksheet';
+import type { IDocumentData } from '../types/interfaces/i-document-data';
+import type { IColorStyle, IStyleData } from '../types/interfaces/i-style-data';
+import type { Nullable } from './types';
+import { RANGE_TYPE } from '../sheets/typedef';
import {
BaselineOffset,
BorderStyleTypes,
@@ -25,13 +28,15 @@ import {
VerticalAlign,
WrapStrategy,
} from '../types/enum';
-import type { IDocumentData } from '../types/interfaces/i-document-data';
-import type { IColorStyle, IStyleData } from '../types/interfaces/i-style-data';
import { ColorBuilder } from './color/color';
import { Tools } from './tools';
-import type { Nullable } from './types';
-export function makeCellToSelection(cellInfo: ISelectionCellWithMergeInfo): IRangeWithCoord {
+/**
+ * Data type convert, convert ICellWithCoord to IRangeWithCoord
+ * @param cellInfo
+ * @returns IRangeWithCoord
+ */
+export function convertCellToRange(cellInfo: ICellWithCoord): IRangeWithCoord {
const { actualRow, actualColumn, isMerged, isMergedMainCell, mergeInfo } = cellInfo;
let { startY, endY, startX, endX } = cellInfo;
let startRow = actualRow;
@@ -65,9 +70,7 @@ export function makeCellToSelection(cellInfo: ISelectionCellWithMergeInfo): IRan
endY = mergeInfo.endY;
startX = mergeInfo.startX;
endX = mergeInfo.endX;
-
endRow = mergeInfo.endRow;
-
endColumn = mergeInfo.endColumn;
}
@@ -83,6 +86,12 @@ export function makeCellToSelection(cellInfo: ISelectionCellWithMergeInfo): IRan
};
}
+/**
+ * @deprecated use `convertCellToRange` instead
+ */
+const makeCellToSelection = convertCellToRange;
+export { makeCellToSelection };
+
export function makeCellRangeToRangeData(cellInfo: Nullable<ISelectionCell>): Nullable<IRange> {
if (!cellInfo) {
return;
diff --git a/packages/core/src/sheets/typedef.ts b/packages/core/src/sheets/typedef.ts
index acf9972636..2c8fe3fb84 100644
--- a/packages/core/src/sheets/typedef.ts
+++ b/packages/core/src/sheets/typedef.ts
@@ -594,12 +594,76 @@ export interface ISingleCell {
export interface IRangeWithCoord extends IPosition, IRange { }
-export interface ISelectionCell extends IRange, ISingleCell { }
-
+/**
+ * @deprecated use ICellWithCoord instead.
+ */
export interface ISelectionCellWithMergeInfo extends IPosition, ISingleCell {
mergeInfo: IRangeWithCoord; // merge cell, start and end is upper left cell
}
+/**
+ * SingleCell & coordinate and mergeRange.
+ */
+// Original name: ISelectionCellWithMergeInfo
+export interface ICellWithCoord extends IPosition, ISingleCell {
+ mergeInfo: IRangeWithCoord; // merge cell, start and end is upper left cell
+
+ /**
+ * Coordinate of the single cell(actual row and column).
+ */
+ startX: number;
+ /**
+ * Coordinate of the single cell(actual row and column).
+ */
+ startY: number;
+ /**
+ * Coordinate of the single cell(actual row and column).
+ */
+ endX: number;
+ /**
+ * Coordinate of the single cell(actual row and column).
+ */
+ endY: number;
+
+ // part of singleCell
+ /**
+ * The raw row index calculated by the offsetX (Without considering merged cells, this value is simply the row index.If there are merged cells, this value refers to the cell where the mouse was clicked.)
+ */
+ actualRow: number;
+
+ /**
+ * The raw col index calculated by the offsetX (Without considering merged cells)
+ */
+ actualColumn: number;
+ /**
+ * Whether the cell is merged. But main merged cell is false.
+ */
+ isMerged: boolean;
+ /**
+ * if Merged and is main merged cell.
+ */
+ isMergedMainCell: boolean;
+}
+
+/**
+ * Range & SingleCell & isMerged.
+ * startRow: number;
+ * startColumn: number;
+ * endRow: number;
+ * endColumn: number;
+ *
+ * actualRow: number;
+ * actualColumn: number;
+ * isMerged: boolean;
+ * isMergedMainCell: boolean;
+ */
+export interface ISelectionCell extends IRange, ISingleCell { }
+
+/**
+ * ICellInfo has the same properties as ISelectionCell, but the name ICellInfo might be more semantically appropriate in some contexts.
+ */
+export interface ICellInfo extends ISelectionCell {}
+
export interface ISelection {
/**
* Sheet selection range.
@@ -608,19 +672,11 @@ export interface ISelection {
/**
* The highlighted cell in the selection range. If there are several selections, only one selection would have a primary cell.
+ *
+ * This cell range should consider the merged cells.
*/
primary: Nullable<ISelectionCell>;
}
-
-/**
- * Selection range Info, contains selection range & primary range
- * primary range is the range of the highlighted cell.
- */
-export interface ISelectionWithCoord {
- rangeWithCoord: IRangeWithCoord;
- primaryWithCoord: Nullable<ISelectionCellWithMergeInfo>;
-}
-
export interface ITextRangeStart {
startOffset: number;
}
diff --git a/packages/core/src/sheets/worksheet.ts b/packages/core/src/sheets/worksheet.ts
index 2e3fad9734..770df7651e 100644
--- a/packages/core/src/sheets/worksheet.ts
+++ b/packages/core/src/sheets/worksheet.ts
@@ -424,29 +424,29 @@ export class Worksheet {
const mergeRange = this.getMergedCell(row, column);
let isMerged = false; // The upper left cell only renders the content
let isMergedMainCell = false;
- let newEndRow = row;
- let newEndColumn = column;
- let mergeRow = row;
- let mergeColumn = column;
+ let mergeEndRow = row;
+ let mergeEndColumn = column;
+ let mergeStartRow = row;
+ let mergeStartColumn = column;
if (mergeRange) {
const {
- startRow: startRowMarge,
- endRow: endRowMarge,
- startColumn: startColumnMarge,
- endColumn: endColumnMarge,
+ startRow: startRowMerge,
+ endRow: endRowMerge,
+ startColumn: startColumnMerge,
+ endColumn: endColumnMerge,
} = mergeRange;
- if (row === startRowMarge && column === startColumnMarge) {
- newEndRow = endRowMarge;
- newEndColumn = endColumnMarge;
- mergeRow = startRowMarge;
- mergeColumn = startColumnMarge;
+ if (row === startRowMerge && column === startColumnMerge) {
+ mergeEndRow = endRowMerge;
+ mergeEndColumn = endColumnMerge;
+ mergeStartRow = startRowMerge;
+ mergeStartColumn = startColumnMerge;
isMergedMainCell = true;
- } else if (row >= startRowMarge && row <= endRowMarge && column >= startColumnMarge && column <= endColumnMarge) {
- newEndRow = endRowMarge;
- newEndColumn = endColumnMarge;
- mergeRow = startRowMarge;
- mergeColumn = startColumnMarge;
+ } else if (row >= startRowMerge && row <= endRowMerge && column >= startColumnMerge && column <= endColumnMerge) {
+ mergeEndRow = endRowMerge;
+ mergeEndColumn = endColumnMerge;
+ mergeStartRow = startRowMerge;
+ mergeStartColumn = startColumnMerge;
isMerged = true;
}
@@ -457,10 +457,10 @@ export class Worksheet {
actualColumn: column,
isMergedMainCell,
isMerged,
- endRow: newEndRow,
- endColumn: newEndColumn,
- startRow: mergeRow,
- startColumn: mergeColumn,
+ endRow: mergeEndRow,
+ endColumn: mergeEndColumn,
+ startRow: mergeStartRow,
+ startColumn: mergeStartColumn,
};
}
@@ -1105,7 +1105,9 @@ export class Worksheet {
return new DocumentDataModel(documentData);
}
- // Only used for cell edit, and no need to rotate text when edit cell content!
+ /**
+ * Only used for cell edit, and no need to rotate text when edit cell content!
+ */
getBlankCellDocumentModel(cell: Nullable<ICellData>): IDocumentLayoutObject {
const documentModelObject = this._getCellDocumentModel(cell, { ignoreTextRotation: true });
diff --git a/packages/core/src/types/interfaces/i-cell-custom-render.ts b/packages/core/src/types/interfaces/i-cell-custom-render.ts
index 66252c0fe3..22924f0893 100644
--- a/packages/core/src/types/interfaces/i-cell-custom-render.ts
+++ b/packages/core/src/types/interfaces/i-cell-custom-render.ts
@@ -17,15 +17,15 @@
/* eslint-disable ts/no-explicit-any */
import type { Nullable } from '../../shared';
-import type { Worksheet } from '../../sheets/worksheet';
+import type { ICellDataForSheetInterceptor, ICellWithCoord } from '../../sheets/typedef';
import type { Workbook } from '../../sheets/workbook';
-import type { ICellDataForSheetInterceptor, ISelectionCellWithMergeInfo } from '../../sheets/typedef';
+import type { Worksheet } from '../../sheets/worksheet';
import type { IStyleData } from './i-style-data';
export interface ICellRenderContext {
data: ICellDataForSheetInterceptor;
style: Nullable<IStyleData>;
- primaryWithCoord: ISelectionCellWithMergeInfo;
+ primaryWithCoord: ICellWithCoord;
unitId: string;
subUnitId: string;
row: number;
diff --git a/packages/engine-render/src/basics/tools.ts b/packages/engine-render/src/basics/tools.ts
index 7cf5c3ddc7..900d4d412c 100644
--- a/packages/engine-render/src/basics/tools.ts
+++ b/packages/engine-render/src/basics/tools.ts
@@ -15,11 +15,12 @@
*/
import type {
+ ICellInfo,
+ ICellWithCoord,
+ IPosition,
IRange,
IRangeWithCoord,
IScale,
- ISelectionCell,
- ISelectionCellWithMergeInfo,
IStyleBase,
Nullable,
} from '@univerjs/core';
@@ -495,7 +496,7 @@ export function getCellPositionByIndex(
column: number,
rowHeightAccumulation: number[],
columnWidthAccumulation: number[]
-) {
+): IPosition {
const startRow = row - 1;
const startColumn = column - 1;
@@ -527,16 +528,16 @@ export function getCellPositionByIndex(
* @param {number} column The column index of the cell
* @param {number[]} rowHeightAccumulation The accumulated height of each row
* @param {number[]} columnWidthAccumulation The accumulated width of each column
- * @param {ISelectionCell} mergeData The merge information of the cell
- * @returns {ISelectionCellWithMergeInfo} The cell position information of the specified row and column, including the position information of the cell and the merge information of the cell
+ * @param {ICellInfo} mergeData The merge information of the cell
+ * @returns {ICellWithCoord} The cell position information of the specified row and column, including the position information of the cell and the merge information of the cell
*/
-export function getCellByIndexWithMergeInfo(
+export function getCellWithCoordByIndexCore(
row: number,
column: number,
rowHeightAccumulation: number[],
columnWidthAccumulation: number[],
- mergeDataInfo: ISelectionCell
-): ISelectionCellWithMergeInfo {
+ mergeDataInfo: ICellInfo
+): ICellWithCoord {
// eslint-disable-next-line prefer-const
let { startY, endY, startX, endX } = getCellPositionByIndex(
row,
@@ -601,88 +602,16 @@ export function getCellByIndexWithMergeInfo(
mergeInfo,
};
}
+
/**
- * @deprecated please use getCellByIndexWithMergeInfo instead
+ * @deprecated please use getCellWithCoordByIndexCore instead
*/
-export function getCellByIndex(
- row: number,
- column: number,
- rowHeightAccumulation: number[],
- columnWidthAccumulation: number[],
- mergeData: IRange[]
-): ISelectionCellWithMergeInfo {
- // eslint-disable-next-line prefer-const
- let { startY, endY, startX, endX } = getCellPositionByIndex(
- row,
- column,
- rowHeightAccumulation,
- columnWidthAccumulation
- );
-
- const { isMerged, isMergedMainCell, startRow, startColumn, endRow, endColumn } = getCellInfoInMergeData(
- row,
- column,
- mergeData
- );
-
- let mergeInfo = {
- startRow,
- startColumn,
- endRow,
- endColumn,
-
- startY: 0,
- endY: 0,
- startX: 0,
- endX: 0,
- };
-
- const rowAccumulationCount = rowHeightAccumulation.length - 1;
-
- const columnAccumulationCount = columnWidthAccumulation.length - 1;
-
- if (isMerged && startRow !== -1 && startColumn !== -1) {
- const mergeStartY = rowHeightAccumulation[startRow - 1] || 0;
- const mergeEndY = rowHeightAccumulation[endRow] || rowHeightAccumulation[rowAccumulationCount];
-
- const mergeStartX = columnWidthAccumulation[startColumn - 1] || 0;
- const mergeEndX = columnWidthAccumulation[endColumn] || columnWidthAccumulation[columnAccumulationCount];
- mergeInfo = {
- ...mergeInfo,
- startY: mergeStartY,
- endY: mergeEndY,
- startX: mergeStartX,
- endX: mergeEndX,
- };
- } else if (!isMerged && endRow !== -1 && endColumn !== -1) {
- const mergeEndY = rowHeightAccumulation[endRow] || rowHeightAccumulation[rowAccumulationCount];
- const mergeEndX = columnWidthAccumulation[endColumn] || columnWidthAccumulation[columnAccumulationCount];
-
- mergeInfo = {
- ...mergeInfo,
- startY,
- endY: mergeEndY,
- startX,
- endX: mergeEndX,
- };
- }
-
- return {
- isMerged,
- isMergedMainCell,
- actualRow: row,
- actualColumn: column,
- startY,
- endY,
- startX,
- endX,
- mergeInfo,
- };
-}
+const getCellByIndexWithMergeInfo = getCellWithCoordByIndexCore;
+export { getCellByIndexWithMergeInfo };
/**
- * @deprecated please use _hasUnMergedCellInRow in SpreadsheetSkeleton
* Determine whether there are any cells in a row that are not in the merged cells, mainly used for the calculation of auto height
+ * @deprecated please use SpreadsheetSkeleton@_hasUnMergedCellInRow
*/
export function hasUnMergedCellInRow(
row: number,
@@ -705,14 +634,12 @@ export function hasUnMergedCellInRow(
}
export function mergeInfoOffset(mergeInfo: IRangeWithCoord, offsetX: number, offsetY: number) {
- const { startY, endY, startX, endX } = mergeInfo;
- mergeInfo.startY = startY + offsetY;
- mergeInfo.endY = endY + offsetY;
- mergeInfo.startX = startX + offsetX;
- mergeInfo.endX = endX + offsetX;
-
return {
...mergeInfo,
+ startY: mergeInfo.startY + offsetY,
+ endY: mergeInfo.endY + offsetY,
+ startX: mergeInfo.startX + offsetX,
+ endX: mergeInfo.endX + offsetX,
};
}
@@ -843,12 +770,12 @@ export function expandRangeIfIntersects(mainRanges: IRange[], ranges: IRange[])
return mainRanges.concat(intersects); // do not use [...mainRanges, ...intersects], because concat is slightly faster than spread
}
-export function clampRange(range: IRange) {
+export function clampRange(range: IRange, maxRow: number, maxColumn: number) {
return {
- startRow: Math.max(0, range.startRow),
- startColumn: Math.max(0, range.startColumn),
- endRow: Math.max(0, range.endRow),
- endColumn: Math.max(0, range.endColumn),
+ startRow: Tools.clamp(range.startRow, 0, maxRow),
+ endRow: Tools.clamp(range.endRow, 0, maxRow),
+ startColumn: Tools.clamp(range.startColumn, 0, maxColumn),
+ endColumn: Tools.clamp(range.endColumn, 0, maxColumn),
};
}
diff --git a/packages/engine-render/src/components/sheets/column-header.ts b/packages/engine-render/src/components/sheets/column-header.ts
index 1a12953020..b351b956b6 100644
--- a/packages/engine-render/src/components/sheets/column-header.ts
+++ b/packages/engine-render/src/components/sheets/column-header.ts
@@ -93,7 +93,7 @@ export class SpreadsheetColumnHeader extends SpreadsheetHeader {
}
/**
- * Custimize column header, such as custom header text and background.
+ * Customize column header, such as custom header text and background.
* @param cfg
*/
setCustomHeader(cfg: IColumnsHeaderCfgParam): void {
diff --git a/packages/engine-render/src/components/sheets/extensions/background.ts b/packages/engine-render/src/components/sheets/extensions/background.ts
index 4610a44367..10358d9d2a 100644
--- a/packages/engine-render/src/components/sheets/extensions/background.ts
+++ b/packages/engine-render/src/components/sheets/extensions/background.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IRange, IScale, ISelectionCellWithMergeInfo, ObjectMatrix } from '@univerjs/core';
+import type { ICellWithCoord, IRange, IScale, ObjectMatrix } from '@univerjs/core';
import type { UniverRenderingContext } from '../../../context';
import type { IDrawInfo } from '../../extension';
import type { SpreadsheetSkeleton } from '../sheet-skeleton';
@@ -36,14 +36,14 @@ const PRINTING_Z_INDEX = 21;
interface IRenderBGContext {
ctx: UniverRenderingContext;
spreadsheetSkeleton: SpreadsheetSkeleton;
- backgroundPositions: ObjectMatrix<ISelectionCellWithMergeInfo>;
+ backgroundPositions: ObjectMatrix<ICellWithCoord>;
checkOutOfViewBound: boolean;
backgroundPaths: Path2D;
scaleX: number;
scaleY: number;
viewRanges: IRange[];
diffRanges: IRange[];
- cellInfo: ISelectionCellWithMergeInfo;
+ cellInfo: ICellWithCoord;
}
export class Background extends SheetExtension {
@@ -147,7 +147,7 @@ export class Background extends SheetExtension {
// bgConfig is requried to be checked in each color loop.
const bgConfig = bgColorMatrix.getValue(range.startRow, range.startColumn);
if (bgConfig) {
- const cellInfo = spreadsheetSkeleton.getCellByIndexWithNoHeader(range.startRow, range.startColumn);
+ const cellInfo = spreadsheetSkeleton.getCellWithCoordByIndex(range.startRow, range.startColumn, false);
if (!cellInfo) return;
renderBGContext.cellInfo = cellInfo;
this.renderBGByCell(renderBGContext, range.startRow, range.startColumn);
diff --git a/packages/engine-render/src/components/sheets/extensions/border.ts b/packages/engine-render/src/components/sheets/extensions/border.ts
index 644083fe8d..d7280f7e22 100644
--- a/packages/engine-render/src/components/sheets/extensions/border.ts
+++ b/packages/engine-render/src/components/sheets/extensions/border.ts
@@ -97,7 +97,7 @@ export class Border extends SheetExtension {
renderBorderByCell(renderBorderContext: IRenderBorderContext, row: number, col: number, borderCacheItem: BorderCache) {
const { ctx, precisionScale, overflowCache, spreadsheetSkeleton, diffRanges } = renderBorderContext;
- const cellInfo = spreadsheetSkeleton.getCellByIndexWithNoHeader(row, col);
+ const cellInfo = spreadsheetSkeleton.getCellWithCoordByIndex(row, col, false);
const { startY: cellStartY, endY: cellEndY, startX: cellStartX, endX: cellEndX } = cellInfo;
const { isMerged, isMergedMainCell, mergeInfo } = cellInfo;
diff --git a/packages/engine-render/src/components/sheets/extensions/custom.ts b/packages/engine-render/src/components/sheets/extensions/custom.ts
index 6fbeffff95..5732ddd4bc 100644
--- a/packages/engine-render/src/components/sheets/extensions/custom.ts
+++ b/packages/engine-render/src/components/sheets/extensions/custom.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-import { Range, sortRules } from '@univerjs/core';
import type { IRange, IScale } from '@univerjs/core';
-import { SpreadsheetExtensionRegistry } from '../../extension';
-import { SheetExtension } from './sheet-extension';
import type { UniverRenderingContext } from '../../../context';
import type { SpreadsheetSkeleton } from '../sheet-skeleton';
+import { Range, sortRules } from '@univerjs/core';
+import { SpreadsheetExtensionRegistry } from '../../extension';
+import { SheetExtension } from './sheet-extension';
const UNIQUE_KEY = 'DefaultCustomExtension';
@@ -52,7 +52,7 @@ export class Custom extends SheetExtension {
return;
}
- let primaryWithCoord = skeleton.getCellByIndexWithNoHeader(row, col);
+ let primaryWithCoord = skeleton.getCellWithCoordByIndex(row, col, false);
const { mergeInfo } = primaryWithCoord;
if (!this.isRenderDiffRangesByRow(mergeInfo.startRow, mergeInfo.endRow, diffRanges)) {
@@ -78,7 +78,7 @@ export class Custom extends SheetExtension {
return;
}
- primaryWithCoord = skeleton.getCellByIndex(mainCell.row, mainCell.col);
+ primaryWithCoord = skeleton.getCellWithCoordByIndex(mainCell.row, mainCell.col);
}
const renderInfo = {
diff --git a/packages/engine-render/src/components/sheets/extensions/font.ts b/packages/engine-render/src/components/sheets/extensions/font.ts
index 629726f53c..f8f2adeea1 100644
--- a/packages/engine-render/src/components/sheets/extensions/font.ts
+++ b/packages/engine-render/src/components/sheets/extensions/font.ts
@@ -17,7 +17,7 @@
/* eslint-disable max-lines-per-function */
/* eslint-disable complexity */
-import type { ICellDataForSheetInterceptor, IRange, IScale, ISelectionCellWithMergeInfo, Nullable, ObjectMatrix } from '@univerjs/core';
+import type { ICellDataForSheetInterceptor, ICellWithCoord, IRange, IScale, Nullable, ObjectMatrix } from '@univerjs/core';
import type { UniverRenderingContext } from '../../../context';
import type { Documents } from '../../docs/document';
import type { IDrawInfo } from '../../extension';
@@ -46,12 +46,12 @@ interface IRenderFontContext {
diffRanges: IRange[];
spreadsheetSkeleton: SpreadsheetSkeleton;
overflowRectangle: Nullable<IRange>;
- cellData: ICellDataForSheetInterceptor;
+ cellData: Nullable<ICellDataForSheetInterceptor>;
startY: number;
endY: number;
startX: number;
endX: number;
- cellInfo: ISelectionCellWithMergeInfo;
+ cellInfo: ICellWithCoord;
}
export class Font extends SheetExtension {
@@ -102,22 +102,20 @@ export class Font extends SheetExtension {
} as IRenderFontContext;
ctx.save();
- // old way, it lags, because it has too many loops, fontMatrix holds all sheet font data.
- // fontMatrix.forValue((row: number, col: number, fontsConfig: IFontCacheItem) => {
- // this.renderFontByCellMatrix(renderFontContext, row, col, fontsConfig);
- // });
-
const uniqueMergeRanges: IRange[] = [];
const mergeRangeIDSet = new Set();
+ const lastRowIndex = spreadsheetSkeleton.getRowCount() - 1;
+ const lastColIndex = spreadsheetSkeleton.getColumnCount() - 1;
+
// Currently, viewRanges has only one range.
viewRanges.forEach((range) => {
range.startColumn -= EXPAND_SIZE_FOR_RENDER_OVERFLOW;
range.endColumn += EXPAND_SIZE_FOR_RENDER_OVERFLOW;
- range = clampRange(range);
+ range = clampRange(range, lastRowIndex, lastColIndex);
// collect unique merge ranges intersect with view range.
- // The ranges in mergeRanges must be unique. Otherwise, the font will rereder, text redrawing causes jagged edges or artifacts.
+ // The ranges in mergeRanges must be unique. Otherwise, the font will render, text redrawing causes jagged edges or artifacts.
const intersectMergeRangesWithViewRanges = spreadsheetSkeleton.worksheet.getMergedCellRange(range.startRow, range.startColumn, range.endRow, range.endColumn);
intersectMergeRangesWithViewRanges.forEach((mergeRange) => {
const mergeRangeIndex = spreadsheetSkeleton.worksheet.getSpanModel().getMergeDataIndex(mergeRange.startRow, mergeRange.startColumn);
@@ -133,24 +131,24 @@ export class Font extends SheetExtension {
if (index !== -1) {
return;
}
- const cellInfo = spreadsheetSkeleton.getCellByIndexWithNoHeader(row, col);
+ const cellInfo = spreadsheetSkeleton.getCellWithCoordByIndex(row, col, false);
if (!cellInfo) return;
renderFontContext.cellInfo = cellInfo;
- this.renderFontEachCell(renderFontContext, row, col, fontMatrix);
+ this._renderFontEachCell(renderFontContext, row, col, fontMatrix);
});
});
uniqueMergeRanges.forEach((range) => {
- const cellInfo = spreadsheetSkeleton.getCellByIndexWithNoHeader(range.startRow, range.startColumn);
+ const cellInfo = spreadsheetSkeleton.getCellWithCoordByIndex(range.startRow, range.startColumn, false);
renderFontContext.cellInfo = cellInfo;
- this.renderFontEachCell(renderFontContext, range.startRow, range.startColumn, fontMatrix);
+ this._renderFontEachCell(renderFontContext, range.startRow, range.startColumn, fontMatrix);
});
ctx.restore();
}
- renderFontEachCell(renderFontCtx: IRenderFontContext, row: number, col: number, fontMatrix: ObjectMatrix<IFontCacheItem>) {
+ _renderFontEachCell(renderFontCtx: IRenderFontContext, row: number, col: number, fontMatrix: ObjectMatrix<IFontCacheItem>) {
const { ctx, viewRanges, diffRanges, spreadsheetSkeleton, cellInfo } = renderFontCtx;
//#region merged cell
@@ -218,6 +216,14 @@ export class Font extends SheetExtension {
ctx.closePath();
ctx.restore();
+
+ renderFontCtx.startX = 0;
+ renderFontCtx.startY = 0;
+ renderFontCtx.endX = 0;
+ renderFontCtx.endY = 0;
+ renderFontCtx.overflowRectangle = null;
+ renderFontCtx.cellData = null;
+ return false;
};
/**
@@ -244,8 +250,8 @@ export class Font extends SheetExtension {
}
}
- const rightOffset = cellData.fontRenderExtension?.rightOffset ?? 0;
- const leftOffset = cellData.fontRenderExtension?.leftOffset ?? 0;
+ const rightOffset = cellData?.fontRenderExtension?.rightOffset ?? 0;
+ const leftOffset = cellData?.fontRenderExtension?.leftOffset ?? 0;
let isOverflow = true;
if (vertexAngle === 0) {
diff --git a/packages/engine-render/src/components/sheets/extensions/marker.ts b/packages/engine-render/src/components/sheets/extensions/marker.ts
index 01fd04fee2..36e92240a4 100644
--- a/packages/engine-render/src/components/sheets/extensions/marker.ts
+++ b/packages/engine-render/src/components/sheets/extensions/marker.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-import { Range } from '@univerjs/core';
import type { IRange, IScale } from '@univerjs/core';
-import { SpreadsheetExtensionRegistry } from '../../extension';
-import { SheetExtension } from './sheet-extension';
import type { UniverRenderingContext } from '../../../context';
import type { SpreadsheetSkeleton } from '../sheet-skeleton';
+import { Range } from '@univerjs/core';
+import { SpreadsheetExtensionRegistry } from '../../extension';
+import { SheetExtension } from './sheet-extension';
const UNIQUE_KEY = 'DefaultMarkerExtension';
@@ -55,7 +55,7 @@ export class Marker extends SheetExtension {
}
let cellData = worksheet.getCell(row, col);
- const cellInfo = skeleton.getCellByIndexWithNoHeader(row, col);
+ const cellInfo = skeleton.getCellWithCoordByIndex(row, col, false);
const { isMerged, isMergedMainCell, mergeInfo } = cellInfo;
let { startY, endY, startX, endX } = cellInfo;
diff --git a/packages/engine-render/src/components/sheets/extensions/sheet-extension.ts b/packages/engine-render/src/components/sheets/extensions/sheet-extension.ts
index 7bd0e5650f..11410d2c65 100644
--- a/packages/engine-render/src/components/sheets/extensions/sheet-extension.ts
+++ b/packages/engine-render/src/components/sheets/extensions/sheet-extension.ts
@@ -14,12 +14,11 @@
* limitations under the License.
*/
-import { Rectangle } from '@univerjs/core';
import type { IRange } from '@univerjs/core';
+import type { SpreadsheetSkeleton } from '../sheet-skeleton';
-import { getCellByIndex } from '../../../basics/tools';
+import { Rectangle } from '@univerjs/core';
import { ComponentExtension } from '../../extension';
-import type { SpreadsheetSkeleton } from '../sheet-skeleton';
export enum SHEET_EXTENSION_TYPE {
GRID,
@@ -33,30 +32,6 @@ export const SHEET_EXTENSION_PREFIX = 'sheet-ext-';
export class SheetExtension extends ComponentExtension<SpreadsheetSkeleton, SHEET_EXTENSION_TYPE, IRange[]> {
override type = SHEET_EXTENSION_TYPE.GRID;
- // cellCache: ObjectMatrix<ISelectionCellWithMergeInfo> = new ObjectMatrix();
- /**
- * @deprecated The function maybe cause performance issue, use spreadsheetSkeleton.getCellByIndexWithNoHeader instead.
- * Get ISelectionCellWithMergeInfo by cell rowIndex and cell columnIndex.
- * The startXY in return value does not include rowHeader and columnHeader.
- * @param rowIndex
- * @param columnIndex
- * @param rowHeightAccumulation
- * @param columnWidthAccumulation
- * @param dataMergeCache
- * @returns {ISelectionCellWithMergeInfo} cell Position & mergeInfo
- */
- getCellByIndex(
- rowIndex: number,
- columnIndex: number,
- rowHeightAccumulation: number[],
- columnWidthAccumulation: number[],
- dataMergeCache: IRange[]
- ) {
- // TODO @lumixraku: there are two coords in sheet!! This one does not include rowHeader and columnHeader. Should keep coord to be only one.
- const cell = getCellByIndex(rowIndex, columnIndex, rowHeightAccumulation, columnWidthAccumulation, dataMergeCache);
- return cell;
- }
-
isRenderDiffRangesByCell(rangeP: IRange, diffRanges?: IRange[]) {
if (diffRanges == null || diffRanges.length === 0) {
return true;
@@ -161,7 +136,7 @@ export class SheetExtension extends ComponentExtension<SpreadsheetSkeleton, SHEE
}
/**
- * 传入的 row 范围和 diffRanges 有相交, 返回 true
+ * Check if row range is in view ranges
* @param curStartRow
* @param curEndRow
* @param viewranges
diff --git a/packages/engine-render/src/components/sheets/interfaces.ts b/packages/engine-render/src/components/sheets/interfaces.ts
index ab3d213ec1..81bcec1df7 100644
--- a/packages/engine-render/src/components/sheets/interfaces.ts
+++ b/packages/engine-render/src/components/sheets/interfaces.ts
@@ -17,7 +17,7 @@
import type {
BorderStyleTypes,
HorizontalAlign,
- ISelectionCellWithMergeInfo,
+ ICellWithCoord,
ObjectMatrix,
VerticalAlign,
WrapStrategy,
@@ -55,7 +55,7 @@ export interface IFontCacheItem {
type colorString = string;
export interface IStylesCache {
background?: Record<colorString, ObjectMatrix<string>>;
- backgroundPositions?: ObjectMatrix<ISelectionCellWithMergeInfo>;
+ backgroundPositions?: ObjectMatrix<ICellWithCoord>;
font?: Record<string, ObjectMatrix<IFontCacheItem>>;
fontMatrix: ObjectMatrix<IFontCacheItem>;
border?: ObjectMatrix<BorderCache>;
diff --git a/packages/engine-render/src/components/sheets/sheet-skeleton.ts b/packages/engine-render/src/components/sheets/sheet-skeleton.ts
index 76078becef..69a0aa45a9 100644
--- a/packages/engine-render/src/components/sheets/sheet-skeleton.ts
+++ b/packages/engine-render/src/components/sheets/sheet-skeleton.ts
@@ -19,6 +19,8 @@ import type {
IBorderStyleData,
ICellData,
ICellDataForSheetInterceptor,
+ ICellInfo,
+ ICellWithCoord,
IColAutoWidthInfo,
IColumnData,
IColumnRange,
@@ -32,25 +34,22 @@ import type {
IRowData,
IRowRange,
ISelectionCell,
- ISelectionCellWithMergeInfo,
ISize,
IStyleData,
ITextRotation,
IWorksheetData,
Nullable,
Styles,
- TextDirection,
VerticalAlign,
Worksheet,
} from '@univerjs/core';
import type { IDocumentSkeletonColumn } from '../../basics/i-document-skeleton-cached';
import type { IBoundRectNoAngle, IViewportInfo } from '../../basics/vector2';
import {
+ addLinkToDocumentModel,
BooleanNumber,
- BuildTextUtils,
CellValueType,
composeStyles,
- CustomRangeType,
DEFAULT_STYLES,
DocumentDataModel,
extractPureTextFromCell,
@@ -66,7 +65,6 @@ import {
LocaleService,
ObjectMatrix,
searchArray,
- TextX,
Tools,
WrapStrategy,
} from '@univerjs/core';
@@ -76,11 +74,10 @@ import { getRotateOffsetAndFarthestHypotenuse } from '../../basics/draw';
import { convertTextRotation, VERTICAL_ROTATE_ANGLE } from '../../basics/text-rotation';
import {
degToRad,
- getCellByIndexWithMergeInfo,
getCellPositionByIndex,
+ getCellWithCoordByIndexCore,
getFontStyleString,
isRectIntersect,
- mergeInfoOffset,
} from '../../basics/tools';
import { DocumentSkeleton } from '../docs/layout/doc-skeleton';
import { columnIterator } from '../docs/layout/tools';
@@ -90,33 +87,6 @@ import { EXPAND_SIZE_FOR_RENDER_OVERFLOW, MEASURE_EXTENT, MEASURE_EXTENT_FOR_PAR
import { type BorderCache, type IFontCacheItem, type IStylesCache, SHEET_VIEWPORT_KEY } from './interfaces';
import { createDocumentModelWithStyle, extractOtherStyle, getFontFormat } from './util';
-function addLinkToDocumentModel(documentModel: DocumentDataModel, linkUrl: string, linkId: string): void {
- const body = documentModel.getBody()!;
- if (body.customRanges?.some((range) => range.rangeType === CustomRangeType.HYPERLINK)) {
- return;
- }
-
- const textX = BuildTextUtils.customRange.add({
- range: {
- startOffset: 0,
- endOffset: body.dataStream.length - 1,
- collapsed: false,
- },
- rangeId: linkId,
- rangeType: CustomRangeType.HYPERLINK,
- body,
- properties: {
- url: linkUrl,
- refId: linkId,
- },
- });
- if (!textX) {
- return;
- }
-
- TextX.apply(body, textX.serialize());
-}
-
/**
* Obtain the height and width of a cell's text, taking into account scenarios with rotated text.
* @param documentSkeleton Data of the document's ViewModel
@@ -172,16 +142,6 @@ export function getDocsSkeletonPageSize(documentSkeleton: DocumentSkeleton, angl
};
}
-interface ICellOtherConfig {
- textRotation?: ITextRotation;
- textDirection?: Nullable<TextDirection>;
- horizontalAlign?: HorizontalAlign;
- verticalAlign?: VerticalAlign;
- wrapStrategy?: WrapStrategy;
- paddingData?: IPaddingData;
- cellValueType?: CellValueType;
-}
-
interface ICellDocumentModelOption {
isDeepClone?: boolean;
displayRawFormula?: boolean;
@@ -222,7 +182,23 @@ export interface ICacheItem {
export interface IGetRowColByPosOptions {
closeFirst?: boolean;
- visibleOnly?: boolean;
+
+ /**
+ * For searchArray(rowHeightAccumulation) & searchArray(colWidthAccumulation)
+ * true means return first matched index in matched sequence.
+ * default return last index in matched sequence.
+ */
+ firstMatch?: boolean;
+}
+
+export interface IGetPosByRowColOptions {
+ closeFirst?: boolean;
+
+ /**
+ * for searchArray(rowHeightAccumulation) & searchArray(colWidthAccumulation)
+ * true means return first matched index in array
+ */
+ firstMatch?: boolean;
}
export class SpreadsheetSkeleton extends Skeleton {
@@ -251,7 +227,7 @@ export class SpreadsheetSkeleton extends Skeleton {
private _overflowCache: ObjectMatrix<IRange> = new ObjectMatrix();
private _stylesCache: IStylesCache = {
background: {},
- backgroundPositions: new ObjectMatrix<ISelectionCellWithMergeInfo>(),
+ backgroundPositions: new ObjectMatrix<ICellWithCoord>(),
font: {} as Record<string, ObjectMatrix<IFontCacheItem>>,
fontMatrix: new ObjectMatrix<IFontCacheItem>(),
border: new ObjectMatrix<BorderCache>(),
@@ -291,7 +267,6 @@ export class SpreadsheetSkeleton extends Skeleton {
this._updateLayout();
this._initContextListener();
- // this.updateDataMerge();
this._isRowStylePrecedeColumnStyle = this._configService.getConfig(IS_ROW_STYLE_PRECEDE_COLUMN_STYLE) ?? false;
}
@@ -376,7 +351,7 @@ export class SpreadsheetSkeleton extends Skeleton {
// this._dataMergeCache = [];
this._stylesCache = {
background: {},
- backgroundPositions: new ObjectMatrix<ISelectionCellWithMergeInfo>(),
+ backgroundPositions: new ObjectMatrix<ICellWithCoord>(),
font: {} as Record<string, ObjectMatrix<IFontCacheItem>>,
fontMatrix: new ObjectMatrix<IFontCacheItem>(),
border: new ObjectMatrix<BorderCache>(),
@@ -529,7 +504,7 @@ export class SpreadsheetSkeleton extends Skeleton {
}
for (let i = startColumn; i <= endColumn; i++) {
- const { isMerged, isMergedMainCell } = this._getCellMergeInfo(rowIndex, i);
+ const { isMerged, isMergedMainCell } = this.worksheet.getCellInfoInMergeData(rowIndex, i);
if (!isMerged && !isMergedMainCell) {
return true;
@@ -593,7 +568,7 @@ export class SpreadsheetSkeleton extends Skeleton {
for (let i = 0; i < columnCount; i++) {
// When calculating the automatic height of a row, if a cell is in a merged cell,
// skip the cell directly, which currently follows the logic of Excel
- const { isMerged, isMergedMainCell } = this._getCellMergeInfo(rowNum, i);
+ const { isMerged, isMergedMainCell } = this.worksheet.getCellInfoInMergeData(rowNum, i);
if (isMerged || isMergedMainCell) {
continue;
@@ -693,6 +668,7 @@ export class SpreadsheetSkeleton extends Skeleton {
* @param colIndex
* @returns {number} width
*/
+
private _calculateColWidth(colIndex: number): number {
const worksheet = this.worksheet;
@@ -965,6 +941,15 @@ export class SpreadsheetSkeleton extends Skeleton {
};
}
+ /**
+ * expand curr range if it's intersect with merge range.
+ * @param range
+ * @returns {IRange} expanded range because merge info.
+ */
+ expandRangeByMerge(range: IRange): IRange {
+ return this.getMergeBounding(range.startRow, range.startColumn, range.endRow, range.endColumn);
+ }
+
appendToOverflowCache(row: number, column: number, startColumn: number, endColumn: number): void {
this._overflowCache.setValue(row, column, {
startRow: row,
@@ -1068,17 +1053,73 @@ export class SpreadsheetSkeleton extends Skeleton {
}
/**
+ * Get cell by pos(offsetX, offsetY).
+ * @deprecated Please use `getCellWithCoordByOffset` instead.
+ */
+ calculateCellIndexByPosition(
+ offsetX: number,
+ offsetY: number,
+ scaleX: number,
+ scaleY: number,
+ scrollXY: { x: number; y: number }
+ ): Nullable<ICellWithCoord> {
+ return this.getCellWithCoordByOffset(offsetX, offsetY, scaleX, scaleY, scrollXY);
+ }
+
+ /**
+ * Get cell by pos(offsetX, offsetY).
*
- * @param offsetX HTML coordinate system, mouse position x.
- * @param offsetY HTML coordinate system, mouse position y.
+ * options.matchFirst true means get cell would skip all invisible cells.
+ * @param offsetX position X in viewport.
+ * @param offsetY position Y in viewport.
+ * @param scaleX render scene scale x-axis, scene.getAncestorScale
+ * @param scaleY render scene scale y-axis, scene.getAncestorScale
+ * @param scrollXY render viewportScroll {x, y}
+ * @param options {IGetRowColByPosOptions}
+ * @returns {ICellWithCoord} Selection data with coordinates
+ */
+ getCellWithCoordByOffset(
+ offsetX: number,
+ offsetY: number,
+ scaleX: number,
+ scaleY: number,
+ scrollXY: { x: number; y: number },
+ options?: IGetRowColByPosOptions
+ ): ICellWithCoord {
+ const { row, column } = this.getCellIndexByOffset(offsetX, offsetY, scaleX, scaleY, scrollXY, options);
+
+ return this.getCellWithCoordByIndex(row, column);
+ }
+
+ /**
+ * This method has the same implementation as `getCellIndexByOffset`,
+ * but uses a different name to maintain backward compatibility with previous calls.
+ *
+ * @deprecated Please use `getCellIndexByOffset` method instead.
+ */
+ getCellPositionByOffset(
+ offsetX: number,
+ offsetY: number,
+ scaleX: number,
+ scaleY: number,
+ scrollXY: { x: number; y: number },
+ options?: IGetRowColByPosOptions
+ ): { row: number; column: number } {
+ return this.getCellIndexByOffset(offsetX, offsetY, scaleX, scaleY, scrollXY, options);
+ }
+
+ /**
+ * Get cell index by offset(o)
+ * @param offsetX position X in viewport.
+ * @param offsetY position Y in viewport.
* @param scaleX render scene scale x-axis, scene.getAncestorScale
* @param scaleY render scene scale y-axis, scene.getAncestorScale
* @param scrollXY render viewport scroll {x, y}, scene.getScrollXYByRelativeCoords, scene.getScrollXY
* @param scrollXY.x
* @param scrollXY.y
- * @returns Hit cell coordinates
+ * @returns cell index
*/
- getCellPositionByOffset(
+ getCellIndexByOffset(
offsetX: number,
offsetY: number,
scaleX: number,
@@ -1086,8 +1127,8 @@ export class SpreadsheetSkeleton extends Skeleton {
scrollXY: { x: number; y: number },
options?: IGetRowColByPosOptions
): { row: number; column: number } {
- const row = this.getRowPositionByOffsetY(offsetY, scaleY, scrollXY, options);
- const column = this.getColumnPositionByOffsetX(offsetX, scaleX, scrollXY, options);
+ const row = this.getRowIndexByOffsetY(offsetY, scaleY, scrollXY, options);
+ const column = this.getColumnIndexByOffsetX(offsetX, scaleX, scrollXY, options);
return {
row,
@@ -1095,16 +1136,51 @@ export class SpreadsheetSkeleton extends Skeleton {
};
}
+ getCellByOffset(
+ offsetX: number,
+ offsetY: number,
+ scaleX: number,
+ scaleY: number,
+ scrollXY: { x: number; y: number }
+ ): Nullable<ICellInfo> {
+ const cellIndex = this?.getCellIndexByOffset(
+ offsetX,
+ offsetY,
+ scaleX,
+ scaleY,
+ scrollXY,
+ { firstMatch: true } // for visible
+ );
+ if (!cellIndex) return null;
+
+ const selectionCell = this.worksheet.getCellInfoInMergeData(cellIndex.row, cellIndex.column);
+ return selectionCell;
+ }
+
+ getCellWithMergeInfoByIndex(row: number, column: number): Nullable<ICellInfo> {
+ const selectionCell = this.worksheet.getCellInfoInMergeData(row, column);
+ return selectionCell;
+ }
+
/**
- * Get column index by offsetX
- * @param offsetX no scaled offset x
- * @param scaleX scale x
- * @param scrollXY
+ * Same as getColumnIndexByOffsetX
+ * @deprecated Please use `getColumnIndexByOffsetX` method instead.
*/
getColumnPositionByOffsetX(offsetX: number, scaleX: number, scrollXY: { x: number; y: number }, options?: IGetRowColByPosOptions): number {
- offsetX = this.getTransformOffsetX(offsetX, scaleX, scrollXY);
+ return this.getColumnIndexByOffsetX(offsetX, scaleX, scrollXY, options);
+ }
+
+ /**
+ * Get column index by offset x.
+ * @param offsetX scaled offset x
+ * @param scaleX scale x
+ * @param scrollXY scrollXY
+ * @returns column index
+ */
+ getColumnIndexByOffsetX(evtOffsetX: number, scaleX: number, scrollXY: { x: number; y: number }, options?: IGetRowColByPosOptions): number {
+ const offsetX = this.getTransformOffsetX(evtOffsetX, scaleX, scrollXY);
const { columnWidthAccumulation } = this;
- let column = searchArray(columnWidthAccumulation, offsetX);
+ let column = searchArray(columnWidthAccumulation, offsetX, options?.firstMatch);
if (options?.closeFirst) {
// check if upper column was closer than current
@@ -1117,21 +1193,29 @@ export class SpreadsheetSkeleton extends Skeleton {
}
/**
- * Get row index by offsetY
+ * Same as getRowIndexByOffsetY
+ * @deprecated Please use `getRowIndexByOffsetY` method instead.
+ */
+ getRowPositionByOffsetY(offsetY: number, scaleY: number, scrollXY: { x: number; y: number }, options?: IGetRowColByPosOptions): number {
+ return this.getRowIndexByOffsetY(offsetY, scaleY, scrollXY, options);
+ }
+
+ /**
+ *
* @param offsetY scaled offset y
* @param scaleY scale y
* @param scrollXY
* @param scrollXY.x
* @param scrollXY.y
*/
- getRowPositionByOffsetY(offsetY: number, scaleY: number, scrollXY: { x: number; y: number }, options?: IGetRowColByPosOptions): number {
+ getRowIndexByOffsetY(offsetY: number, scaleY: number, scrollXY: { x: number; y: number }, options?: IGetRowColByPosOptions): number {
const { rowHeightAccumulation } = this;
offsetY = this.getTransformOffsetY(offsetY, scaleY, scrollXY);
- let row = searchArray(rowHeightAccumulation, offsetY, options?.visibleOnly);
+ let row = searchArray(rowHeightAccumulation, offsetY, options?.firstMatch);
if (options?.closeFirst) {
- // check if next row was closer than current
+ // check if upper row was closer than current
if (Math.abs(rowHeightAccumulation[row] - offsetY) < Math.abs(offsetY - (rowHeightAccumulation[row - 1] ?? 0))) {
row = row + 1;
}
@@ -1144,9 +1228,9 @@ export class SpreadsheetSkeleton extends Skeleton {
const { x: scrollX } = scrollXY;
// so we should map physical positions to ideal positions
- offsetX = offsetX / scaleX + scrollX - this.rowHeaderWidthAndMarginLeft;
+ const afterOffsetX = offsetX / scaleX + scrollX - this.rowHeaderWidthAndMarginLeft;
- return offsetX;
+ return afterOffsetX;
}
getTransformOffsetY(offsetY: number, scaleY: number, scrollXY: { x: number; y: number }): number {
@@ -1189,12 +1273,30 @@ export class SpreadsheetSkeleton extends Skeleton {
return rowHeightAccumulation[lastRowIndex] + columnHeaderHeightAndMarginTop;
}
+ /**
+ * Same as getCellWithCoordByIndex, but uses a different name to maintain backward compatibility with previous calls.
+ * @deprecated Please use `getCellWithCoordByIndex` instead.
+ */
+ getCellByIndex(row: number, column: number): ICellWithCoord {
+ return this.getCellWithCoordByIndex(row, column);
+ }
+
+ /**
+ * @deprecated Please use `getCellWithCoordByIndex(row, col, false)` instead.
+ * @param row
+ * @param column
+ */
+ getCellByIndexWithNoHeader(row: number, column: number) {
+ return this.getCellWithCoordByIndex(row, column, false);
+ }
+
/**
* Return cell information corresponding to the current coordinates, including the merged cell object.
+ *
* @param row Specified Row Coordinate
* @param column Specified Column Coordinate
*/
- getCellByIndex(row: number, column: number): ISelectionCellWithMergeInfo {
+ getCellWithCoordByIndex(row: number, column: number, header: boolean = true): ICellWithCoord {
const {
rowHeightAccumulation,
columnWidthAccumulation,
@@ -1202,30 +1304,42 @@ export class SpreadsheetSkeleton extends Skeleton {
columnHeaderHeightAndMarginTop,
} = this;
- const primary = getCellByIndexWithMergeInfo(
+ const primary: ICellWithCoord = getCellWithCoordByIndexCore(
row,
column,
rowHeightAccumulation,
columnWidthAccumulation,
- this._getCellMergeInfo(row, column)
+ this.worksheet.getCellInfoInMergeData(row, column)
);
const { isMerged, isMergedMainCell } = primary;
let { startY, endY, startX, endX, mergeInfo } = primary;
- startY += columnHeaderHeightAndMarginTop;
- endY += columnHeaderHeightAndMarginTop;
- startX += rowHeaderWidthAndMarginLeft;
- endX += rowHeaderWidthAndMarginLeft;
+ let offsetX = rowHeaderWidthAndMarginLeft;
+ let offsetY = columnHeaderHeightAndMarginTop;
+ if (header === false) {
+ offsetX = 0;
+ offsetY = 0;
+ }
+
+ startY += offsetY;
+ endY += offsetY;
+ startX += offsetX;
+ endX += offsetX;
- mergeInfo = mergeInfoOffset(mergeInfo, rowHeaderWidthAndMarginLeft, columnHeaderHeightAndMarginTop);
+ mergeInfo.startY += offsetY;
+ mergeInfo.endY += offsetY;
+ mergeInfo.startX += offsetX;
+ mergeInfo.endX += offsetX;
+
+ // mergeInfo = mergeInfoOffset(mergeInfo, rowHeaderWidthAndMarginLeft, columnHeaderHeightAndMarginTop);
return {
actualRow: row,
actualColumn: column,
- startY,
- endY,
startX,
+ startY,
endX,
+ endY,
isMerged,
isMergedMainCell,
mergeInfo,
@@ -1233,63 +1347,32 @@ export class SpreadsheetSkeleton extends Skeleton {
}
/**
- * New merge info, but position without header.
- * @param row
- * @param column
- * @returns {ISelectionCellWithMergeInfo} cellInfo with merge info
+ * convert canvas content position to physical position in screen
+ * @param offsetX
+ * @param scaleX
+ * @param scrollXY
*/
- getCellByIndexWithNoHeader(row: number, column: number): ISelectionCellWithMergeInfo {
- const { rowHeightAccumulation, columnWidthAccumulation } = this;
-
- const primary = getCellByIndexWithMergeInfo(
- row,
- column,
- rowHeightAccumulation,
- columnWidthAccumulation,
- this._getCellMergeInfo(row, column)
- );
-
- const { isMerged, isMergedMainCell } = primary;
- const { startY, endY, startX, endX, mergeInfo } = primary;
-
- const newMergeInfo = mergeInfoOffset(mergeInfo, 0, 0);
-
- return {
- actualRow: row,
- actualColumn: column,
- startY,
- endY,
- startX,
- endX,
- isMerged,
- isMergedMainCell,
- mergeInfo: newMergeInfo,
- };
- }
-
- // convert canvas content position to physical position in screen
convertTransformToOffsetX(offsetX: number, scaleX: number, scrollXY: { x: number; y: number }): number {
const { x: scrollX } = scrollXY;
-
- offsetX = (offsetX - scrollX) * scaleX;
-
- return offsetX;
+ return (offsetX - scrollX) * scaleX;
}
- // convert canvas content position to physical position in screen
+ /**
+ * convert canvas content position to physical position in screen
+ * @param offsetY
+ * @param scaleY
+ * @param scrollXY
+ */
convertTransformToOffsetY(offsetY: number, scaleY: number, scrollXY: { x: number; y: number }): number {
const { y: scrollY } = scrollXY;
-
- offsetY = (offsetY - scrollY) * scaleY;
-
- return offsetY;
+ return (offsetY - scrollY) * scaleY;
}
- getSelectionMergeBounding(startRow: number, startColumn: number, endRow: number, endColumn: number): IRange {
- return this.getMergeBounding(startRow, startColumn, endRow, endColumn);
- }
-
- // Only used for cell edit, and no need to rotate text when edit cell content!
+ /**
+ * Only used for cell edit, and no need to rotate text when edit cell content!
+ * @deprecated use same method in worksheet.
+ * @param cell
+ */
getBlankCellDocumentModel(cell: Nullable<ICellData>): IDocumentLayoutObject {
const documentModelObject = this._getCellDocumentModel(cell, { ignoreTextRotation: true });
@@ -1328,7 +1411,11 @@ export class SpreadsheetSkeleton extends Skeleton {
};
}
- // Only used for cell edit, and no need to rotate text when edit cell content!
+ /**
+ * Only used for cell edit, and no need to rotate text when edit cell content!
+ * @deprecated use same method in worksheet.
+ * @param cell
+ */
getCellDocumentModelWithFormula(cell: ICellData): Nullable<IDocumentLayoutObject> {
return this._getCellDocumentModel(cell, {
isDeepClone: true,
@@ -1340,11 +1427,13 @@ export class SpreadsheetSkeleton extends Skeleton {
/**
* This method generates a document model based on the cell's properties and handles the associated styles and configurations.
* If the cell does not exist, it will return null.
+ *
+ * @deprecated use same method in worksheet.
* PS: This method has significant impact on performance.
* @param cell
* @param options
*/
- // eslint-disable-next-line complexity
+ // eslint-disable-next-line complexity, max-lines-per-function
private _getCellDocumentModel(
cell: Nullable<ICellDataForSheetInterceptor>,
options: ICellDocumentModelOption = DEFAULT_CELL_DOCUMENT_MODEL_OPTION
@@ -1466,7 +1555,7 @@ export class SpreadsheetSkeleton extends Skeleton {
* the text content of this cell can be drawn to both sides, not limited by the cell's width.
* Overflow on the left or right is aligned according to the text's horizontal alignment.
*/
- // eslint-disable-next-line complexity
+ // eslint-disable-next-line complexity, max-lines-per-function
private _calculateOverflowCell(row: number, column: number, docsConfig: IFontCacheItem): boolean {
// wrap and angle handler
const { documentSkeleton, vertexAngle = 0, centerAngle = 0, horizontalAlign, wrapStrategy } = docsConfig;
@@ -1506,12 +1595,12 @@ export class SpreadsheetSkeleton extends Skeleton {
}
if (vertexAngle !== 0) {
- const { startY, endY, startX, endX } = getCellByIndexWithMergeInfo(
+ const { startY, endY, startX, endX } = getCellWithCoordByIndexCore(
row,
column,
this.rowHeightAccumulation,
this.columnWidthAccumulation,
- this._getCellMergeInfo(row, column)
+ this.worksheet.getCellInfoInMergeData(row, column)
);
const cellWidth = endX - startX;
const cellHeight = endY - startY;
@@ -1539,12 +1628,12 @@ export class SpreadsheetSkeleton extends Skeleton {
return true;
}
- const { startY, endY } = getCellByIndexWithMergeInfo(
+ const { startY, endY } = getCellWithCoordByIndexCore(
row,
column,
this.rowHeightAccumulation,
this.columnWidthAccumulation,
- this._getCellMergeInfo(row, column)
+ this.worksheet.getCellInfoInMergeData(row, column)
);
const cellHeight = endY - startY;
@@ -1644,7 +1733,7 @@ export class SpreadsheetSkeleton extends Skeleton {
rowTotalHeight += rowHeight;
- rowHeightAccumulation.push(rowTotalHeight); // 行的临时长度分布
+ rowHeightAccumulation.push(rowTotalHeight);
}
return {
@@ -1688,7 +1777,7 @@ export class SpreadsheetSkeleton extends Skeleton {
}
columnTotalWidth += columnWidth;
- columnWidthAccumulation.push(columnTotalWidth); // 列的临时长度分布
+ columnWidthAccumulation.push(columnTotalWidth);
}
return {
@@ -1803,7 +1892,7 @@ export class SpreadsheetSkeleton extends Skeleton {
private _resetCache(): void {
this._stylesCache = {
background: {},
- backgroundPositions: new ObjectMatrix<ISelectionCellWithMergeInfo>(),
+ backgroundPositions: new ObjectMatrix<ICellWithCoord>(),
font: {},
fontMatrix: new ObjectMatrix<IFontCacheItem>(),
border: new ObjectMatrix<BorderCache>(),
@@ -1813,11 +1902,6 @@ export class SpreadsheetSkeleton extends Skeleton {
this._overflowCache.reset();
}
- // private _makeDocumentSkeletonDirty(row: number, col: number): void {
- // if (this._stylesCache.fontMatrix == null) return;
- // this._stylesCache.fontMatrix.getValue(row, col)?.documentSkeleton.makeDirty(true); ;
- // }
-
_setBorderStylesCache(row: number, col: number, style: Nullable<IStyleData>, options: {
mergeRange?: IRange;
cacheItem?: ICacheItem;
@@ -1871,7 +1955,7 @@ export class SpreadsheetSkeleton extends Skeleton {
const bgCache = this._stylesCache.background![rgb];
bgCache.setValue(row, col, rgb);
- const cellInfo = this.getCellByIndexWithNoHeader(row, col);
+ const cellInfo = this.getCellWithCoordByIndex(row, col, false);
this._stylesCache.backgroundPositions?.setValue(row, col, cellInfo);
}
}
@@ -1891,13 +1975,6 @@ export class SpreadsheetSkeleton extends Skeleton {
const { fontString: _fontString, textRotation, wrapStrategy, verticalAlign, horizontalAlign } = modelObject;
- // if (!this._stylesCache.font![fontString]) {
- // this._stylesCache.font![fontString] = new ObjectMatrix();
- // }
-
- // const fontFamilyMatrix: ObjectMatrix<IFontCacheItem> = this._stylesCache.font![fontString];
- // if (fontFamilyMatrix.getValue(row, col)) return;
-
const documentViewModel = new DocumentViewModel(documentModel);
if (documentViewModel) {
const { vertexAngle, centerAngle } = convertTextRotation(textRotation);
@@ -1913,7 +1990,6 @@ export class SpreadsheetSkeleton extends Skeleton {
wrapStrategy,
};
this._stylesCache.fontMatrix.setValue(row, col, config);
- // fontFamilyMatrix.setValue(row, col, config);
this._calculateOverflowCell(row, col, config);
}
}
@@ -1941,7 +2017,7 @@ export class SpreadsheetSkeleton extends Skeleton {
options = { cacheItem: { bg: true, border: true } };
}
- const { isMerged, isMergedMainCell, startRow, startColumn, endRow, endColumn } = this._getCellMergeInfo(row, col);
+ const { isMerged, isMergedMainCell, startRow, startColumn, endRow, endColumn } = this.worksheet.getCellInfoInMergeData(row, col);
options.mergeRange = { startRow, startColumn, endRow, endColumn };
const hidden = this.worksheet.getColVisible(col) === false || this.worksheet.getRowVisible(row) === false;
diff --git a/packages/engine-render/src/components/sheets/spreadsheet.ts b/packages/engine-render/src/components/sheets/spreadsheet.ts
index b059b2a607..212e58ddb3 100644
--- a/packages/engine-render/src/components/sheets/spreadsheet.ts
+++ b/packages/engine-render/src/components/sheets/spreadsheet.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IRange, ISelectionCellWithMergeInfo, Nullable, ObjectMatrix } from '@univerjs/core';
+import type { ICellWithCoord, IRange, Nullable, ObjectMatrix } from '@univerjs/core';
import type { IBoundRectNoAngle, IViewportInfo, Vector2 } from '../../basics/vector2';
import type { Canvas } from '../../canvas';
import type { UniverRenderingContext2D } from '../../context';
@@ -667,7 +667,7 @@ export class Spreadsheet extends SheetComponent {
}
}
- private _clearBackground(ctx: UniverRenderingContext2D, backgroundPositions?: ObjectMatrix<ISelectionCellWithMergeInfo>) {
+ private _clearBackground(ctx: UniverRenderingContext2D, backgroundPositions?: ObjectMatrix<ICellWithCoord>) {
backgroundPositions?.forValue((row, column, cellInfo) => {
let { startY, endY, startX, endX } = cellInfo;
const { isMerged, isMergedMainCell, mergeInfo } = cellInfo;
diff --git a/packages/engine-render/src/components/skeleton.ts b/packages/engine-render/src/components/skeleton.ts
index 3ac47588b2..c959cc3c85 100644
--- a/packages/engine-render/src/components/skeleton.ts
+++ b/packages/engine-render/src/components/skeleton.ts
@@ -15,7 +15,6 @@
*/
import type { IFontLocale } from '../basics/interfaces';
-
import { Disposable, Inject, LocaleService } from '@univerjs/core';
export class Skeleton extends Disposable {
diff --git a/packages/engine-render/src/scene.transformer.ts b/packages/engine-render/src/scene.transformer.ts
index f874b46aca..86481ec489 100644
--- a/packages/engine-render/src/scene.transformer.ts
+++ b/packages/engine-render/src/scene.transformer.ts
@@ -1036,7 +1036,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
topScene.disableObjectsEvent();
- const viewportActualXY = topScene.getVpScrollXYInfoByPosToVp(Vector2.create(evtOffsetX, evtOffsetY));
+ const viewportActualXY = topScene.getScrollXYInfoByViewport(Vector2.create(evtOffsetX, evtOffsetY));
this._viewportScrollX = viewportActualXY.x;
this._viewportScrollY = viewportActualXY.y;
diff --git a/packages/engine-render/src/scene.ts b/packages/engine-render/src/scene.ts
index 60962d4faf..f241dfd257 100644
--- a/packages/engine-render/src/scene.ts
+++ b/packages/engine-render/src/scene.ts
@@ -672,29 +672,36 @@ export class Scene extends ThinScene {
// }
// parent = parent?.getParent && parent?.getParent();
// }
- coord = this.getRelativeToViewportCoord(coord);
+ coord = this.getCoordRelativeToViewport(coord);
return this.findViewportByPosToViewport(coord);
}
+ /**
+ * @deprecated use `getScrollXYInfoByViewport` instead.
+ * @param pos
+ * @param viewPort
+ */
+ getVpScrollXYInfoByPosToVp(pos: Vector2, viewPort?: Viewport) {
+ return this.getScrollXYInfoByViewport(pos, viewPort);
+ }
+
/**
* getViewportScrollXYInfo by viewport under cursor position
* prev getScrollXYByRelativeCoords
* @param pos
* @param viewPort
*/
- getVpScrollXYInfoByPosToVp(pos: Vector2, viewPort?: Viewport) {
- if (!viewPort) {
- viewPort = this.findViewportByPosToViewport(pos);
- }
+ getScrollXYInfoByViewport(pos: Vector2, viewPort?: Viewport) {
if (!viewPort) {
- return {
- x: 0,
- y: 0,
- };
+ viewPort = this.findViewportByPosToViewport(pos) || this.getDefaultViewport();
}
return this.getViewportScrollXY(viewPort);
}
+ getDefaultViewport() {
+ return this.getViewport('viewMain')!;
+ }
+
getViewportScrollXY(viewPort: Viewport) {
let x = 0;
let y = 0;
@@ -711,11 +718,23 @@ export class Scene extends ThinScene {
}
/**
+ * @deprecated use `getCoordRelativeToViewport` instead
+ * @param coord
+ * @returns
+ */
+ getRelativeToViewportCoord(coord: Vector2) {
+ return this.getCoordRelativeToViewport(coord);
+ }
+
+ /**
+ * Get coord to active viewport.
* In a nested scene scenario, it is necessary to obtain the relative offsets layer by layer.
+ *
+ * origin name: getRelativeToViewportCoord
* @param coord Coordinates to be converted.
* @returns
*/
- getRelativeToViewportCoord(coord: Vector2) {
+ getCoordRelativeToViewport(coord: Vector2): Vector2 {
let parent: any = this.getParent();
const parentList: any[] = [];
diff --git a/packages/engine-render/src/viewport.ts b/packages/engine-render/src/viewport.ts
index 1971db19b1..33cd45a7ce 100644
--- a/packages/engine-render/src/viewport.ts
+++ b/packages/engine-render/src/viewport.ts
@@ -545,7 +545,7 @@ export class Viewport {
// 4. changing the viewport size (also include change window size)
// 5. changing the scroll bar position(click at certain pos of scrolltrack)
// Debug
- // window.scene.getViewports()[0].scrollTo({x: 14.2, y: 1.8}, true)
+ // scene.getViewports()[0].scrollTo({x: 14.2, y: 1.8}, true)
scrollToBarPos(pos: Partial<IScrollBarPosition>) {
return this._scrollToBarPosCore(pos);
}
diff --git a/packages/sheets-conditional-formatting/src/render/data-bar.render.ts b/packages/sheets-conditional-formatting/src/render/data-bar.render.ts
index c0165320be..d2221534d0 100644
--- a/packages/sheets-conditional-formatting/src/render/data-bar.render.ts
+++ b/packages/sheets-conditional-formatting/src/render/data-bar.render.ts
@@ -14,11 +14,11 @@
* limitations under the License.
*/
-import { Range } from '@univerjs/core';
-import { FIX_ONE_PIXEL_BLUR_OFFSET, SheetExtension, SpreadsheetExtensionRegistry } from '@univerjs/engine-render';
import type { IRange, IScale } from '@univerjs/core';
import type { SpreadsheetSkeleton, UniverRenderingContext } from '@univerjs/engine-render';
import type { IDataBarCellData } from './type';
+import { Range } from '@univerjs/core';
+import { FIX_ONE_PIXEL_BLUR_OFFSET, SheetExtension, SpreadsheetExtensionRegistry } from '@univerjs/engine-render';
export const dataBarUKey = 'sheet-conditional-rule-data-bar';
export const defaultDataBarPositiveColor = '#ffbe38';
@@ -55,7 +55,7 @@ export class DataBar extends SheetExtension {
const cellData = worksheet.getCell(row, col) as IDataBarCellData;
if (cellData && cellData.dataBar) {
const { color, value, startPoint, isGradient } = cellData.dataBar;
- const cellInfo = spreadsheetSkeleton.getCellByIndexWithNoHeader(row, col);
+ const cellInfo = spreadsheetSkeleton.getCellWithCoordByIndex(row, col, false);
let { isMerged, isMergedMainCell, mergeInfo, startY, endY, startX, endX } = cellInfo;
if (isMerged) {
return;
diff --git a/packages/sheets-conditional-formatting/src/render/icon.render.ts b/packages/sheets-conditional-formatting/src/render/icon.render.ts
index fb25fbc459..7422967a53 100644
--- a/packages/sheets-conditional-formatting/src/render/icon.render.ts
+++ b/packages/sheets-conditional-formatting/src/render/icon.render.ts
@@ -14,13 +14,13 @@
* limitations under the License.
*/
-import { Range } from '@univerjs/core';
-import { SheetExtension, SpreadsheetExtensionRegistry } from '@univerjs/engine-render';
import type { IRange, IScale } from '@univerjs/core';
import type { SpreadsheetSkeleton, UniverRenderingContext } from '@univerjs/engine-render';
-import { EMPTY_ICON_TYPE, iconMap } from '../models/icon-map';
import type { IIconType } from '../models/icon-map';
import type { IIconSetCellData } from './type';
+import { Range } from '@univerjs/core';
+import { SheetExtension, SpreadsheetExtensionRegistry } from '@univerjs/engine-render';
+import { EMPTY_ICON_TYPE, iconMap } from '../models/icon-map';
export const IconUKey = 'sheet-conditional-rule-icon';
const EXTENSION_Z_INDEX = 35;
@@ -68,7 +68,7 @@ export class ConditionalFormattingIcon extends SheetExtension {
if (!icon) {
return;
}
- const cellInfo = spreadsheetSkeleton.getCellByIndexWithNoHeader(row, col);
+ const cellInfo = spreadsheetSkeleton.getCellWithCoordByIndex(row, col, false);
let { isMerged, isMergedMainCell, mergeInfo, startY, endY, startX, endX } = cellInfo;
if (isMerged) {
return;
diff --git a/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts b/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts
index 00daf6e082..16387a374f 100644
--- a/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts
+++ b/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts
@@ -215,7 +215,7 @@ export class SheetsDataValidationRenderController extends RxDisposable {
},
},
style: skeleton.getsStyles().getStyleByCell(cell),
- primaryWithCoord: skeleton.getCellByIndex(mergeCell?.startRow ?? row, mergeCell?.startColumn ?? col),
+ primaryWithCoord: skeleton.getCellWithCoordByIndex(mergeCell?.startRow ?? row, mergeCell?.startColumn ?? col),
unitId,
subUnitId,
row,
@@ -246,7 +246,7 @@ export class SheetsDataValidationRenderController extends RxDisposable {
},
},
style: skeleton.getsStyles().getStyleByCell(cell),
- primaryWithCoord: skeleton.getCellByIndex(mergeCell?.startRow ?? row, mergeCell?.startColumn ?? col),
+ primaryWithCoord: skeleton.getCellWithCoordByIndex(mergeCell?.startRow ?? row, mergeCell?.startColumn ?? col),
unitId,
subUnitId,
row,
@@ -382,7 +382,7 @@ export class SheetsDataValidationMobileRenderController extends RxDisposable {
},
},
style: skeleton.getsStyles().getStyleByCell(cell),
- primaryWithCoord: skeleton.getCellByIndex(mergeCell?.startRow ?? row, mergeCell?.startColumn ?? col),
+ primaryWithCoord: skeleton.getCellWithCoordByIndex(mergeCell?.startRow ?? row, mergeCell?.startColumn ?? col),
unitId,
subUnitId,
row,
diff --git a/packages/sheets-data-validation-ui/src/views/components/item/index.tsx b/packages/sheets-data-validation-ui/src/views/components/item/index.tsx
index 4e941d1d18..f2acd50b55 100644
--- a/packages/sheets-data-validation-ui/src/views/components/item/index.tsx
+++ b/packages/sheets-data-validation-ui/src/views/components/item/index.tsx
@@ -69,7 +69,7 @@ export const DataValidationItem = (props: IDataValidationDetailProps) => {
ids.current = rule.ranges.map((range) => markSelectionService.addShape({
range,
style: {
- hasAutoFill: false,
+ // hasAutoFill: false,
fill: 'rgba(73, 184, 17, 0.05)',
strokeWidth: 1,
stroke: '#49B811',
diff --git a/packages/sheets-drawing-ui/src/basics/transform-position.ts b/packages/sheets-drawing-ui/src/basics/transform-position.ts
index 4f47a2d5b1..2422d44e62 100644
--- a/packages/sheets-drawing-ui/src/basics/transform-position.ts
+++ b/packages/sheets-drawing-ui/src/basics/transform-position.ts
@@ -16,8 +16,8 @@
import type { Nullable } from '@univerjs/core';
import type { ITransformState } from '@univerjs/drawing';
-import { precisionTo } from '@univerjs/engine-render';
import type { ISheetDrawingPosition } from '@univerjs/sheets-drawing';
+import { precisionTo } from '@univerjs/engine-render';
import { attachRangeWithCoord, type ISheetSelectionRenderService, type SheetSkeletonManagerService } from '@univerjs/sheets-ui';
export function drawingPositionToTransform(
@@ -92,7 +92,7 @@ export function drawingPositionToTransform(
export function transformToDrawingPosition(transform: ITransformState, selectionRenderService: ISheetSelectionRenderService): Nullable<ISheetDrawingPosition> {
const { left = 0, top = 0, width = 0, height = 0, flipY = false, flipX = false, angle = 0, skewX = 0, skewY = 0 } = transform;
- const startSelectionCell = selectionRenderService.getSelectionCellByPosition(left, top);
+ const startSelectionCell = selectionRenderService.getCellWithCoordByOffset(left, top);
if (startSelectionCell == null) {
return;
@@ -105,7 +105,7 @@ export function transformToDrawingPosition(transform: ITransformState, selection
rowOffset: precisionTo(top - startSelectionCell.startY, 1),
};
- const endSelectionCell = selectionRenderService.getSelectionCellByPosition(left + width, top + height);
+ const endSelectionCell = selectionRenderService.getCellWithCoordByOffset(left + width, top + height);
if (endSelectionCell == null) {
return;
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-printing.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-printing.controller.ts
index e095aa5091..1561281e13 100644
--- a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-printing.controller.ts
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-printing.controller.ts
@@ -81,8 +81,8 @@ export class SheetDrawingPrintingController extends Disposable {
if (data.length) {
data.forEach((param) => {
if (!param.groupId && param.transform && Tools.isDefine(param.transform.left) && Tools.isDefine(param.transform.top) && Tools.isDefine(param.transform.width) && Tools.isDefine(param.transform.height)) {
- const start = skeleton.skeleton.getCellPositionByOffset(param.transform.left, param.transform.top, scaleX, scaleY, { x: 0, y: 0 });
- const end = skeleton.skeleton.getCellPositionByOffset(param.transform.left + param.transform.width, param.transform.top + param.transform.height, scaleX, scaleY, { x: 0, y: 0 });
+ const start = skeleton.skeleton.getCellIndexByOffset(param.transform.left, param.transform.top, scaleX, scaleY, { x: 0, y: 0 });
+ const end = skeleton.skeleton.getCellIndexByOffset(param.transform.left + param.transform.width, param.transform.top + param.transform.height, scaleX, scaleY, { x: 0, y: 0 });
if (start.column < newRange.startColumn) {
newRange.startColumn = start.column;
}
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-update.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-update.controller.ts
index 80428eb613..0507c33b8d 100644
--- a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-update.controller.ts
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-update.controller.ts
@@ -17,7 +17,7 @@
import type { IRange, Nullable, Workbook } from '@univerjs/core';
import type { IImageData, IImageIoServiceParam } from '@univerjs/drawing';
import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
-import type { WorkbookSelections } from '@univerjs/sheets';
+import type { WorkbookSelectionModel } from '@univerjs/sheets';
import type { ISheetDrawing, ISheetDrawingPosition } from '@univerjs/sheets-drawing';
import type { IInsertDrawingCommandParams, ISetDrawingCommandParams } from '../commands/commands/interfaces';
import type { ISetDrawingArrangeCommandParams } from '../commands/commands/set-drawing-arrange.command';
@@ -36,7 +36,7 @@ import { SetSheetDrawingCommand } from '../commands/commands/set-sheet-drawing.c
import { UngroupSheetDrawingCommand } from '../commands/commands/ungroup-sheet-drawing.command';
export class SheetDrawingUpdateController extends Disposable implements IRenderModule {
- private readonly _workbookSelections: WorkbookSelections;
+ private readonly _workbookSelections: WorkbookSelectionModel;
constructor(
private readonly _context: IRenderContext<Workbook>,
@Inject(SheetSkeletonManagerService) private readonly _skeletonManagerService: SheetSkeletonManagerService,
@@ -204,7 +204,7 @@ export class SheetDrawingUpdateController extends Disposable implements IRenderM
}
if (isChangeStart) {
- const newCoord = this._selectionRenderService.getSelectionCellByPosition(startX, startY);
+ const newCoord = this._selectionRenderService.getCellWithCoordByOffset(startX, startY);
if (newCoord == null) {
return;
}
@@ -221,7 +221,7 @@ export class SheetDrawingUpdateController extends Disposable implements IRenderM
rowOffset: 0,
};
- const endSelectionCell = this._selectionRenderService.getSelectionCellByPosition(startX + imageWidth, startY + imageHeight);
+ const endSelectionCell = this._selectionRenderService.getCellWithCoordByOffset(startX + imageWidth, startY + imageHeight);
if (endSelectionCell == null) {
return;
diff --git a/packages/sheets-drawing-ui/src/services/canvas-float-dom-manager.service.ts b/packages/sheets-drawing-ui/src/services/canvas-float-dom-manager.service.ts
index 400661444a..ce5426607a 100644
--- a/packages/sheets-drawing-ui/src/services/canvas-float-dom-manager.service.ts
+++ b/packages/sheets-drawing-ui/src/services/canvas-float-dom-manager.service.ts
@@ -488,7 +488,7 @@ export class SheetCanvasFloatDomManagerService extends Disposable {
if (selectionRenderService == null) {
return;
}
- const start = selectionRenderService.getSelectionCellByPosition(startX, startY);
+ const start = selectionRenderService.getCellWithCoordByOffset(startX, startY);
if (start == null) {
return;
}
@@ -500,7 +500,7 @@ export class SheetCanvasFloatDomManagerService extends Disposable {
rowOffset: startY - start.startY,
};
- const end = selectionRenderService.getSelectionCellByPosition(endX, endY);
+ const end = selectionRenderService.getCellWithCoordByOffset(endX, endY);
if (end == null) {
return;
diff --git a/packages/sheets-filter-ui/src/views/render-modules/sheets-filter.render-controller.ts b/packages/sheets-filter-ui/src/views/render-modules/sheets-filter.render-controller.ts
index 29b7c05311..d00ac4475a 100644
--- a/packages/sheets-filter-ui/src/views/render-modules/sheets-filter.render-controller.ts
+++ b/packages/sheets-filter-ui/src/views/render-modules/sheets-filter.render-controller.ts
@@ -16,14 +16,14 @@
import type { IDisposable, IRange, Workbook } from '@univerjs/core';
import type { IRenderContext, IRenderModule, SpreadsheetSkeleton } from '@univerjs/engine-render';
-import type { ISelectionStyle, ISheetCommandSharedParams } from '@univerjs/sheets';
+import type { ISheetCommandSharedParams } from '@univerjs/sheets';
import type { FilterModel } from '@univerjs/sheets-filter';
import type { ISheetsFilterButtonShapeProps } from '../widgets/filter-button.shape';
import { CommandType, fromCallback, ICommandService, Inject, Injector, InterceptorEffectEnum, RxDisposable, ThemeService } from '@univerjs/core';
import { INTERCEPTOR_POINT, SetRangeValuesMutation, SheetInterceptorService } from '@univerjs/sheets';
import { FILTER_MUTATIONS, SheetsFilterService } from '@univerjs/sheets-filter';
-import { getCoordByCell, ISheetSelectionRenderService, SelectionShape, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { attachSelectionWithCoord, getCoordByCell, ISheetSelectionRenderService, SelectionControl, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
import { filter, map, of, startWith, switchMap, takeUntil, throttleTime } from 'rxjs';
import { FILTER_ICON_PADDING, FILTER_ICON_SIZE, SheetsFilterButtonShape } from '../widgets/filter-button.shape';
@@ -39,8 +39,11 @@ interface ISheetsFilterRenderParams {
skeleton: SpreadsheetSkeleton;
}
+/**
+ * Show selected range in filter.
+ */
export class SheetsFilterRenderController extends RxDisposable implements IRenderModule {
- private _filterRangeShape: SelectionShape | null = null;
+ private _filterRangeShape: SelectionControl | null = null;
private _buttonRenderDisposable: IDisposable | null = null;
private _filterButtonShapes: SheetsFilterButtonShape[] = [];
@@ -106,19 +109,21 @@ export class SheetsFilterRenderController extends RxDisposable implements IRende
private _renderRange(range: IRange, skeleton: SpreadsheetSkeleton): void {
const { scene } = this._context;
- const { rangeWithCoord, style } = this._selectionRenderService.attachSelectionWithCoord({
+ const { rowHeaderWidth, columnHeaderHeight } = skeleton;
+ const filterRangeShape = this._filterRangeShape = new SelectionControl(
+ scene, DEFAULT_Z_INDEX, this._themeService, {
+ rowHeaderWidth,
+ columnHeaderHeight,
+ enableAutoFill: false,
+ highlightHeader: false,
+ });
+ const selectionWithStyle = {
range,
primary: null,
- style: null,
- });
-
- const { rowHeaderWidth, columnHeaderHeight } = skeleton;
- const filterRangeShape = this._filterRangeShape = new SelectionShape(scene, DEFAULT_Z_INDEX, this._themeService, true);
- filterRangeShape.update(rangeWithCoord, rowHeaderWidth, columnHeaderHeight, {
- hasAutoFill: false,
- fill: 'rgba(0, 0, 0, 0.0)',
- ...style,
- } as ISelectionStyle);
+ style: { fill: 'rgba(0, 0, 0, 0.0)' },
+ };
+ const selectionWithCoord = attachSelectionWithCoord(selectionWithStyle, skeleton);
+ filterRangeShape.updateRangeBySelectionWithCoord(selectionWithCoord);
filterRangeShape.setEvent(false);
scene.makeDirty(true);
diff --git a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts
index c210ea0c76..a21c532c91 100644
--- a/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts
+++ b/packages/sheets-find-replace/src/controllers/sheet-find-replace.controller.ts
@@ -16,7 +16,7 @@
import type { ICellData, IDisposable, IObjectMatrixPrimitiveType, IRange, Nullable, Workbook, Worksheet } from '@univerjs/core';
import type { IFindComplete, IFindMatch, IFindMoveParams, IFindQuery, IFindReplaceProvider, IReplaceAllResult } from '@univerjs/find-replace';
-import type { ISelectionWithStyle, ISetRangeValuesCommandParams, ISetSelectionsOperationParams, ISetWorksheetActivateCommandParams, ISheetCommandSharedParams, WorkbookSelections } from '@univerjs/sheets';
+import type { ISelectionWithStyle, ISetRangeValuesCommandParams, ISetSelectionsOperationParams, ISetWorksheetActivateCommandParams, ISheetCommandSharedParams, WorkbookSelectionModel } from '@univerjs/sheets';
import type { IScrollToCellCommandParams } from '@univerjs/sheets-ui';
import type { ISheetReplaceCommandParams, ISheetReplacement } from '../commands/commands/sheet-replace.command';
import type { ISheetFindReplaceHighlightShapeProps } from '../views/shapes/find-replace-highlight.shape';
@@ -116,7 +116,7 @@ export class SheetFindModel extends FindModel {
get matchesPosition(): number { return this._matchesPosition; }
get currentMatch(): Nullable<ISheetCellMatch> { return this._matchesPosition > 0 ? this._matches[this._matchesPosition - 1] : null; }
- private _workbookSelections: WorkbookSelections;
+ private _workbookSelections: WorkbookSelectionModel;
constructor(
private readonly _workbook: Workbook,
diff --git a/packages/sheets-formula-ui/src/common/selection.ts b/packages/sheets-formula-ui/src/common/selection.ts
index d2a54c5ce7..2150af853b 100644
--- a/packages/sheets-formula-ui/src/common/selection.ts
+++ b/packages/sheets-formula-ui/src/common/selection.ts
@@ -19,7 +19,7 @@ import { ColorKit, type ThemeService } from '@univerjs/core';
export const FORMULA_REF_SELECTION_PLUGIN_NAME = 'formula_reference_selection_plugin_name';
-export function getFormulaRefSelectionStyle(themeService: ThemeService, refColor: string, id: string): ISelectionStyle {
+export function genFormulaRefSelectionStyle(themeService: ThemeService, refColor: string, id: string): ISelectionStyle {
const style = themeService.getCurrentTheme();
const fill = new ColorKit(refColor).setAlpha(0.05).toRgbString();
return {
@@ -31,8 +31,5 @@ export function getFormulaRefSelectionStyle(themeService: ThemeService, refColor
widgetSize: 6,
widgetStrokeWidth: 1,
widgetStroke: style.colorWhite,
- hasAutoFill: false,
- hasRowHeader: false,
- hasColumnHeader: false,
};
}
diff --git a/packages/sheets-formula-ui/src/controllers/formula-editor-show.controller.ts b/packages/sheets-formula-ui/src/controllers/formula-editor-show.controller.ts
index 446da7b3d0..de48b09e1e 100644
--- a/packages/sheets-formula-ui/src/controllers/formula-editor-show.controller.ts
+++ b/packages/sheets-formula-ui/src/controllers/formula-editor-show.controller.ts
@@ -16,7 +16,7 @@
import type { ICellDataForSheetInterceptor, ICommandInfo, IObjectMatrixPrimitiveType, IRange, IRowAutoHeightInfo, Nullable, Workbook, Worksheet } from '@univerjs/core';
import type { IRenderContext, IRenderModule, SpreadsheetSkeleton } from '@univerjs/engine-render';
-import type { ISetWorksheetRowAutoHeightMutationParams } from '@univerjs/sheets';
+import type { ISelectionWithStyle, ISetWorksheetRowAutoHeightMutationParams } from '@univerjs/sheets';
import {
ColorKit, Disposable,
ICommandService,
@@ -35,14 +35,17 @@ import {
import { IRenderManagerService } from '@univerjs/engine-render';
import { BEFORE_CELL_EDIT, SetWorksheetRowAutoHeightMutation, SheetInterceptorService } from '@univerjs/sheets';
import {
- ISheetSelectionRenderService,
+ attachSelectionWithCoord,
SELECTION_SHAPE_DEPTH,
- SelectionShape,
+ SelectionControl,
SheetSkeletonManagerService,
} from '@univerjs/sheets-ui';
+/**
+ * For Array formula in cell editing
+ */
export class FormulaEditorShowController extends Disposable implements IRenderModule {
- private _previousShape: Nullable<SelectionShape>;
+ private _previousShape: Nullable<SelectionControl>;
private _skeleton: SpreadsheetSkeleton;
constructor(
@@ -215,35 +218,32 @@ export class FormulaEditorShowController extends Disposable implements IRenderMo
}
private _createArrayFormulaRangeShape(arrayRange: IRange, unitId: string): void {
- const styleSheet = this._themeService.getCurrentTheme();
- const fill = new ColorKit(styleSheet.colorWhite).setAlpha(0).toString();
- const style = {
- strokeWidth: 1,
- stroke: styleSheet.hyacinth700,
- fill,
- widgets: {},
-
- hasAutoFill: false,
-
- hasRowHeader: false,
-
- hasColumnHeader: false,
- };
-
const renderUnit = this._renderManagerService.getRenderById(unitId);
- if (!renderUnit) return;
+ const skeleton = this._sheetSkeletonManagerService.getCurrentSkeleton();
+ if (!renderUnit || !skeleton) return;
const { scene } = renderUnit;
- const { rangeWithCoord, primaryWithCoord } = renderUnit.with(ISheetSelectionRenderService).attachSelectionWithCoord({
+ if (!scene) return;
+
+ const styleSheet = this._themeService.getCurrentTheme();
+ const selectionWithStyle: ISelectionWithStyle = {
range: arrayRange,
primary: null,
- style,
- });
- const skeleton = this._sheetSkeletonManagerService.getCurrentSkeleton();
- if (!scene || !skeleton) return;
+ style: {
+ strokeWidth: 1,
+ stroke: styleSheet.hyacinth700,
+ fill: new ColorKit(styleSheet.colorWhite).setAlpha(0).toString(),
+ widgets: {},
+ },
+ };
+ const selectionWithCoord = attachSelectionWithCoord(selectionWithStyle, skeleton);
const { rowHeaderWidth, columnHeaderHeight } = skeleton;
- const control = new SelectionShape(scene, SELECTION_SHAPE_DEPTH.FORMULA_EDITOR_SHOW, this._themeService, false);
- control.update(rangeWithCoord, rowHeaderWidth, columnHeaderHeight, style, primaryWithCoord);
+ const control = new SelectionControl(scene, SELECTION_SHAPE_DEPTH.FORMULA_EDITOR_SHOW, this._themeService, {
+ highlightHeader: false,
+ rowHeaderWidth,
+ columnHeaderHeight,
+ });
+ control.updateRangeBySelectionWithCoord(selectionWithCoord);
control.setEvent(false);
this._previousShape = control;
}
diff --git a/packages/sheets-formula-ui/src/controllers/prompt.controller.ts b/packages/sheets-formula-ui/src/controllers/prompt.controller.ts
index 8c17fae1c7..da6f3aa1ef 100644
--- a/packages/sheets-formula-ui/src/controllers/prompt.controller.ts
+++ b/packages/sheets-formula-ui/src/controllers/prompt.controller.ts
@@ -31,7 +31,7 @@ import type { IAbsoluteRefTypeForRange, ISequenceNode } from '@univerjs/engine-f
import type {
ISelectionWithStyle,
} from '@univerjs/sheets';
-import type { EditorBridgeService, SelectionShape } from '@univerjs/sheets-ui';
+import type { EditorBridgeService, SelectionControl } from '@univerjs/sheets-ui';
import type { ISelectEditorFormulaOperationParam } from '../commands/operations/editor-formula.operation';
import { AbsoluteRefType,
Direction,
@@ -103,7 +103,7 @@ import { HelpFunctionOperation } from '../commands/operations/help-function.oper
import { ReferenceAbsoluteOperation } from '../commands/operations/reference-absolute.operation';
import { SearchFunctionOperation } from '../commands/operations/search-function.operation';
import { META_KEY_CTRL_AND_SHIFT } from '../common/prompt';
-import { getFormulaRefSelectionStyle } from '../common/selection';
+import { genFormulaRefSelectionStyle } from '../common/selection';
import { IFormulaPromptService } from '../services/prompt.service';
import { RefSelectionsRenderService } from '../services/render-services/ref-selections.render-service';
@@ -1066,7 +1066,7 @@ export class PromptController extends Disposable {
selectionWithStyle.push({
range,
primary,
- style: getFormulaRefSelectionStyle(this._themeService, themeColor, refIndex.toString()),
+ style: genFormulaRefSelectionStyle(this._themeService, themeColor, refIndex.toString()),
});
}
@@ -1129,7 +1129,7 @@ export class PromptController extends Disposable {
return {
range,
primary,
- style: getFormulaRefSelectionStyle(this._themeService, themeColor, refIndex.toString()),
+ style: genFormulaRefSelectionStyle(this._themeService, themeColor, refIndex.toString()),
};
}
@@ -1473,7 +1473,7 @@ export class PromptController extends Disposable {
const controls = refSelectionRenderService.getSelectionControls();
const [unitId, sheetId] = refSelectionRenderService.getLocation();
- const matchedControls = new Set<SelectionShape>();
+ const matchedControls = new Set<SelectionControl>();
for (let i = 0, len = refSelections.length; i < len; i++) {
const refSelection = refSelections[i];
const { refIndex, themeColor, token } = refSelection;
@@ -1525,16 +1525,18 @@ export class PromptController extends Disposable {
});
if (control) {
- const style = getFormulaRefSelectionStyle(this._themeService, themeColor, refIndex.toString());
+ const style = genFormulaRefSelectionStyle(this._themeService, themeColor, refIndex.toString());
control.updateStyle(style);
matchedControls.add(control);
}
}
}
- private _onSelectionControlChange(toRange: IRangeWithCoord, selectionControl: SelectionShape) {
+ // eslint-disable-next-line max-lines-per-function
+ private _onSelectionControlChange(toRange: IRangeWithCoord, selectionControl: SelectionControl) {
// FIXME: change here
const { skeleton } = this._getCurrentUnitIdAndSheetId();
+ if (!skeleton) return;
// const { unitId, sheetId } = toRange;
this._formulaPromptService.enableLockedSelectionChange();
@@ -1544,7 +1546,6 @@ export class PromptController extends Disposable {
}
let { startRow, endRow, startColumn, endColumn } = toRange;
- // const primary = getCellInfoInMergeData(startRow, startColumn, skeleton?.mergeData);
const primary = skeleton
? skeleton.worksheet.getCellInfoInMergeData(startRow, startColumn)
: {
@@ -1621,7 +1622,7 @@ export class PromptController extends Disposable {
}
this._syncToEditor(sequenceNodes, node.endIndex + 1);
- selectionControl.update(toRange, undefined, undefined, undefined, this._selectionRenderService.attachPrimaryWithCoord(primary));
+ selectionControl.updateRange(toRange, this._selectionRenderService.attachPrimaryWithCoord(primary));
}
private _refreshFormulaAndCellEditor(unitIds: string[]) {
diff --git a/packages/sheets-formula-ui/src/services/render-services/ref-selections.render-service.ts b/packages/sheets-formula-ui/src/services/render-services/ref-selections.render-service.ts
index 93d34bc136..64299eef73 100644
--- a/packages/sheets-formula-ui/src/services/render-services/ref-selections.render-service.ts
+++ b/packages/sheets-formula-ui/src/services/render-services/ref-selections.render-service.ts
@@ -14,15 +14,14 @@
* limitations under the License.
*/
-import type { IDisposable, Nullable, Workbook } from '@univerjs/core';
-import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule, Viewport } from '@univerjs/engine-render';
-import type { ISelectionStyle, ISelectionWithCoordAndStyle, ISelectionWithStyle, SheetsSelectionsService, WorkbookSelections } from '@univerjs/sheets';
+import type { IDisposable, IRangeWithCoord, Nullable, Workbook } from '@univerjs/core';
+import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule, Scene, SpreadsheetSkeleton, Viewport } from '@univerjs/engine-render';
+import type { ISelectionStyle, ISelectionWithCoord, ISelectionWithStyle, SheetsSelectionsService, WorkbookSelectionModel } from '@univerjs/sheets';
import { DisposableCollection, Inject, Injector, RANGE_TYPE, ThemeService, toDisposable } from '@univerjs/core';
import { ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
-import { convertSelectionDataToRange, getNormalSelectionStyle, IRefSelectionsService, SelectionMoveType } from '@univerjs/sheets';
-import { attachSelectionWithCoord, BaseSelectionRenderService, checkInHeaderRanges, getAllSelection, getCoordByOffset, getSheetObject, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { convertSelectionDataToRange, IRefSelectionsService, SelectionMoveType } from '@univerjs/sheets';
+import { attachSelectionWithCoord, BaseSelectionRenderService, checkInHeaderRanges, genNormalSelectionStyle, getAllSelection, getCoordByOffset, getSheetObject, SelectionControl, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
import { IShortcutService } from '@univerjs/ui';
-import { merge } from 'rxjs';
/**
* This service extends the existing `SelectionRenderService` to provide the rendering of prompt selections
@@ -35,7 +34,7 @@ import { merge } from 'rxjs';
*
*/
export class RefSelectionsRenderService extends BaseSelectionRenderService implements IRenderModule {
- private readonly _workbookSelections: WorkbookSelections;
+ private readonly _workbookSelections: WorkbookSelectionModel;
private _eventDisposables: Nullable<IDisposable>;
@@ -62,6 +61,7 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple
this._setSelectionStyle(getDefaultRefSelectionStyle(this._themeService));
this._remainLastEnabled = true; // For ref range selections, we should always remain others.
+ this._highlightHeader = false;
}
getLocation(): [string, string] {
@@ -149,8 +149,7 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple
const skeleton = this._sheetSkeletonManagerService.getCurrent()!.skeleton;
const selectionWithStyle = getAllSelection(skeleton);
- const selectionData = this.attachSelectionWithCoord(selectionWithStyle);
- this._addSelectionControlBySelectionData(selectionData);
+ this._addSelectionControlByModelData(selectionWithStyle);
this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
const dispose = scene.onPointerUp$.subscribeEvent(() => {
dispose.unsubscribe();
@@ -164,6 +163,21 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple
return listenerDisposables;
}
+ /**
+ * Add a selection in spreadsheet, create a new SelectionControl and then update this control by range derives from selection.
+ * For ref selection, create selectionShapeExtension to handle user action.
+ * @param {ISelectionWithCoord} selectionWithStyle
+ */
+ protected override _addSelectionControlByModelData(selectionWithStyle: ISelectionWithStyle): SelectionControl {
+ const skeleton = this._skeleton;
+ const style = selectionWithStyle.style ?? genNormalSelectionStyle(this._themeService);
+ const scene = this._scene;
+
+ selectionWithStyle.style = style;
+ const control = this.newSelectionControl(scene, skeleton, selectionWithStyle);
+ return control;
+ }
+
/**
* Update selectionModel in this._workbookSelections by user action in spreadsheet area.
*/
@@ -179,7 +193,7 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple
}));
}
- private _updateSelections(selectionDataWithStyleList: ISelectionWithCoordAndStyle[], type: SelectionMoveType): void {
+ private _updateSelections(selectionDataWithStyleList: ISelectionWithCoord[], type: SelectionMoveType): void {
const workbook = this._context.unit;
const sheetId = workbook.getActiveSheet()!.getSheetId();
@@ -196,13 +210,13 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple
// Changing the selection area through the 8 control points of the ref selection will not trigger this subscriber.
// beforeSelectionMoveEnd$ & selectionMoveEnd$ would triggered when change skeleton(change sheet).
- this.disposeWithMe(merge(this._workbookSelections.selectionMoveEnd$, this._workbookSelections.selectionSet$).subscribe((selectionsWithStyles) => {
+ this.disposeWithMe(this._workbookSelections.selectionSet$.subscribe((selectionsWithStyles) => {
this._reset();
-
+ const skeleton = this._skeleton;
+ if (!skeleton) return;
// The selections' style would be colorful here. PromptController would change the color of selections later.
for (const selectionWithStyle of selectionsWithStyles) {
- const selectionData = this.attachSelectionWithCoord(selectionWithStyle);
- this._addSelectionControlBySelectionData(selectionData);
+ this._addSelectionControlByModelData(selectionWithStyle);
}
}));
}
@@ -229,18 +243,10 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple
// for col width & row height resize
const currentSelections = this._workbookSelections.getCurrentSelections();
- this._refreshSelectionControl(currentSelections || []);
+ this.resetSelectionsByModelData(currentSelections);
}));
}
- protected override _refreshSelectionControl(selectionsData: readonly ISelectionWithStyle[]): void {
- const selections = selectionsData.map((selectionWithStyle) => {
- const selectionData = attachSelectionWithCoord(selectionWithStyle, this._skeleton);
- return selectionData;
- });
- this.updateControlForCurrentByRangeData(selections);
- }
-
private _getActiveViewport(evt: IPointerEvent | IMouseEvent): Nullable<Viewport> {
const sheetObject = this._getSheetObject();
return sheetObject?.scene.getActiveViewportByCoord(Vector2.FromArray([evt.offsetX, evt.offsetY]));
@@ -249,6 +255,195 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple
private _getSheetObject() {
return getSheetObject(this._context.unit, this._context)!;
}
+
+ /**
+ * Handle pointer down event, bind pointermove & pointerup handler.
+ * then trigger selectionMoveStart$.
+ *
+ * @param evt
+ * @param _zIndex
+ * @param rangeType
+ * @param viewport
+ * @param scrollTimerType
+ */
+ // eslint-disable-next-line max-lines-per-function, complexity
+ protected _onPointerDown(
+ evt: IPointerEvent | IMouseEvent,
+ _zIndex = 0,
+ rangeType: RANGE_TYPE = RANGE_TYPE.NORMAL,
+ viewport: Nullable<Viewport>,
+ scrollTimerType: ScrollTimerType = ScrollTimerType.ALL
+ ): void {
+ this._rangeType = rangeType;
+
+ const skeleton = this._skeleton;
+ const scene = this._scene;
+ if (!scene || !skeleton) {
+ return;
+ }
+
+ if (viewport) {
+ this._activeViewport = viewport;
+ }
+
+ const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
+ const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
+ if (!viewportMain) return;
+ const relativeCoords = scene.getCoordRelativeToViewport(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+
+ const { x: offsetX, y: offsetY } = relativeCoords;
+ this._startViewportPosX = offsetX;
+ this._startViewportPosY = offsetY;
+
+ const scrollXY = scene.getScrollXYInfoByViewport(relativeCoords);
+ const { scaleX, scaleY } = scene.getAncestorScale();
+
+ const selectCell = this._skeleton.getCellByOffset(offsetX, offsetY, scaleX, scaleY, scrollXY);
+ if (!selectCell) return;
+ switch (rangeType) {
+ case RANGE_TYPE.NORMAL:
+ break;
+ case RANGE_TYPE.ROW:
+ selectCell.startColumn = 0;
+ selectCell.endColumn = this._skeleton.getColumnCount() - 1;
+ break;
+ case RANGE_TYPE.COLUMN:
+ selectCell.startRow = 0;
+ selectCell.endRow = this._skeleton.getRowCount() - 1;
+ break;
+ case RANGE_TYPE.ALL:
+ selectCell.startRow = 0;
+ selectCell.startColumn = 0;
+ selectCell.endRow = this._skeleton.getRowCount() - 1;
+ selectCell.endColumn = this._skeleton.getColumnCount() - 1;
+ }
+
+ const selectionWithStyle: ISelectionWithStyle = { range: selectCell, primary: selectCell, style: null };
+ selectionWithStyle.range.rangeType = rangeType;
+ // const selectionCellWithCoord = this._getSelectionWithCoordByOffset(offsetX, offsetY, scaleX, scaleY, scrollXY);
+ const selectionCellWithCoord = attachSelectionWithCoord(selectionWithStyle, this._skeleton);
+ this._startRangeWhenPointerDown = { ...selectionCellWithCoord.rangeWithCoord };
+
+ const cursorCellRangeWithRangeType: IRangeWithCoord = { ...selectionCellWithCoord.rangeWithCoord, rangeType };
+
+ let activeSelectionControl: Nullable<SelectionControl> = this.getActiveSelectionControl();
+ const curControls = this.getSelectionControls();
+ for (const control of curControls) {
+ // right click should not create a new selection, it pops up the context menu.
+ if (evt.button === 2 && control.model.isInclude(cursorCellRangeWithRangeType)) {
+ activeSelectionControl = control;
+ return;
+ }
+ // Click to an existing selection,
+ if (control.model.isEqual(cursorCellRangeWithRangeType)) {
+ activeSelectionControl = control;
+ break;
+ }
+ }
+
+ this._checkClearPreviousControls(evt);
+
+ const currentCell = activeSelectionControl?.model.currentCell;
+ const expandByShiftKey = evt.shiftKey && currentCell;
+ const remainLastEnable = this._remainLastEnabled &&
+ !evt.ctrlKey &&
+ !evt.shiftKey &&
+ !this._skipLastEnabled &&
+ !this._singleSelectionEnabled;
+
+ //#region update selection control
+ if (expandByShiftKey && currentCell) {
+ // Perform pointer down selection.
+ this._makeSelectionByTwoCells(
+ currentCell,
+ cursorCellRangeWithRangeType,
+ skeleton,
+ rangeType,
+ activeSelectionControl! // Get updated in this method
+ );
+ } else if (remainLastEnable && activeSelectionControl) {
+ // Supports the formula ref text selection feature,
+ // under the condition of preserving all previous selections, it modifies the position of the latest selection.
+
+ activeSelectionControl.updateRangeBySelectionWithCoord(selectionCellWithCoord);
+ } else {
+ // In normal situation, pointerdown ---> Create new SelectionControl,
+ activeSelectionControl = this.newSelectionControl(scene, skeleton, selectionWithStyle);
+ }
+ // clear highlight except last one.
+ for (let i = 0; i < this.getSelectionControls().length - 1; i++) {
+ this.getSelectionControls()[i].clearHighlight();
+ }
+ //#endregion
+
+ this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
+
+ scene.disableObjectsEvent();
+ this._clearUpdatingListeners();
+ this._addEndingListeners();
+
+ scene.getTransformer()?.clearSelectedObjects();
+
+ // if (rangeType === RANGE_TYPE.ROW || rangeType === RANGE_TYPE.COLUMN) {
+ // if (rangeType === RANGE_TYPE.ROW) {
+ // offsetX = 0;
+ // } else if (rangeType === RANGE_TYPE.COLUMN) {
+ // offsetY = 0;
+ // }
+ // // TODO @lumixraku. This is so bad! There should be a explicit way to update col&row range. But now depends on the side effect of _movingHandler.
+ // // call _movingHandler to update range, col selection, endRow should be last row of current sheet.
+ // this._movingHandler(offsetX, offsetY, activeSelectionControl, rangeType);
+ // }
+
+ this._setupPointerMoveListener(viewportMain, activeSelectionControl!, rangeType, scrollTimerType, offsetX, offsetY);
+
+ this._escapeShortcutDisposable = this._shortcutService.forceEscape();
+ this._scenePointerUpSub = scene.onPointerUp$.subscribeEvent(() => {
+ this._clearUpdatingListeners();
+
+ // selection control would be disposed in _selectionMoveEnd$.
+ // SelectionRenderService@selectionMoveEnd$ exec SetSelectionsOperation
+ // SheetsSelectionsService@setSelections
+ // SelectionRenderService._workbookSelections.selectionMoveEnd$ call _reset() to clear selectionControl.
+ this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
+ this._escapeShortcutDisposable?.dispose();
+ this._escapeShortcutDisposable = null;
+ });
+ }
+
+ /**
+ * Diff between normal selection, no highlightHeader for ref selections.
+ * @param scene
+ * @param skeleton
+ * @param selectionWithCoord
+ * @returns {SelectionControl} selectionControl just created
+ */
+ override newSelectionControl(scene: Scene, skeleton: SpreadsheetSkeleton, selection: ISelectionWithStyle): SelectionControl {
+ const zIndex = this.getSelectionControls().length;
+ const { rowHeaderWidth, columnHeaderHeight } = skeleton;
+ const control = new SelectionControl(scene, zIndex, this._themeService, {
+ highlightHeader: this._highlightHeader,
+ enableAutoFill: false,
+ rowHeaderWidth,
+ columnHeaderHeight,
+ });
+ const selectionWithCoord = attachSelectionWithCoord(selection, skeleton);
+ control.updateRangeBySelectionWithCoord(selectionWithCoord);
+ this._selectionControls.push(control);
+
+ control.setControlExtension({
+ skeleton,
+ scene,
+ themeService: this._themeService,
+ injector: this._injector,
+ selectionHooks: {
+ selectionMoveEnd: (): void => {
+ this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
+ },
+ },
+ });
+ return control;
+ }
}
/**
@@ -257,10 +452,7 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple
* @returns The selection's style.
*/
function getDefaultRefSelectionStyle(themeService: ThemeService): ISelectionStyle {
- const style = getNormalSelectionStyle(themeService);
- style.hasAutoFill = false;
- style.hasRowHeader = false;
- style.hasColumnHeader = false;
+ const style = genNormalSelectionStyle(themeService);
style.widgets = { tl: true, tc: true, tr: true, ml: true, mr: true, bl: true, bc: true, br: true };
return style;
}
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/useSheetSelectionChange.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useSheetSelectionChange.ts
index ef145f66d3..1ae2f2a23c 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/useSheetSelectionChange.ts
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/useSheetSelectionChange.ts
@@ -19,7 +19,7 @@
import type { Workbook } from '@univerjs/core';
import type { Editor } from '@univerjs/docs-ui';
-import type { ISelectionWithCoordAndStyle } from '@univerjs/sheets';
+import type { ISelectionWithCoord } from '@univerjs/sheets';
import type { INode } from '../../range-selector/utils/filterReferenceNode';
import { DisposableCollection, IUniverInstanceService, useDependency, useObservable } from '@univerjs/core';
import { deserializeRangeWithSheet, sequenceNodeType, serializeRange, serializeRangeWithSheet } from '@univerjs/engine-formula';
@@ -68,7 +68,7 @@ export const useSheetSelectionChange = (
if (refSelectionsRenderService && isNeed) {
let isFirst = true;
// eslint-disable-next-line complexity
- const handleSelectionsChange = (selections: ISelectionWithCoordAndStyle[]) => {
+ const handleSelectionsChange = (selections: ISelectionWithCoord[]) => {
if (isFirst || isScalingRef.current) {
isFirst = false;
return;
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/useHighlight.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/useHighlight.ts
index 5381866ce2..0111c0778d 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/useHighlight.ts
+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/useHighlight.ts
@@ -17,15 +17,16 @@
import type { ITextRun, Workbook } from '@univerjs/core';
import type { Editor } from '@univerjs/docs-ui';
import type { ISequenceNode } from '@univerjs/engine-formula';
-import type { ISelectionStyle, ISelectionWithStyle } from '@univerjs/sheets';
+import type { ISelectionWithStyle } from '@univerjs/sheets';
import type { INode } from './useFormulaToken';
-import { ColorKit, IUniverInstanceService, ThemeService, useDependency } from '@univerjs/core';
+import { IUniverInstanceService, ThemeService, useDependency } from '@univerjs/core';
import { deserializeRangeWithSheet, sequenceNodeType } from '@univerjs/engine-formula';
import { IRenderManagerService } from '@univerjs/engine-render';
import { IRefSelectionsService, setEndForRange } from '@univerjs/sheets';
import { IDescriptionService } from '@univerjs/sheets-formula';
-import { attachRangeWithCoord, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';
import { useMemo } from 'react';
+import { genFormulaRefSelectionStyle } from '../../../common/selection';
import { RefSelectionsRenderService } from '../../../services/render-services/ref-selections.render-service';
interface IRefSelection {
@@ -57,9 +58,12 @@ export function useSheetHighlight(unitId: string) {
refSelectionsService.setSelections(selectionWithStyle);
return;
}
- const currentSheetId = worksheet?.getSheetId();
+ const currentSheetId = worksheet.getSheetId();
const getSheetIdByName = (name: string) => workbook?.getSheetBySheetName(name)?.getSheetId();
+ const skeleton = sheetSkeletonManagerService?.getWorksheetSkeleton(currentSheetId)?.skeleton;
+ if (!skeleton) return;
+
for (let i = 0, len = refSelections.length; i < len; i++) {
const refSelection = refSelections[i];
const { themeColor, token, refIndex } = refSelection;
@@ -77,26 +81,18 @@ export function useSheetHighlight(unitId: string) {
}
const range = setEndForRange(rawRange, worksheet.getRowCount(), worksheet.getColumnCount());
-
selectionWithStyle.push({
range,
primary: null,
- style: getFormulaRefSelectionStyle(themeService, themeColor, refIndex.toString()),
+ style: genFormulaRefSelectionStyle(themeService, themeColor, refIndex.toString()),
});
}
- const skeleton = sheetSkeletonManagerService?.getCurrentSkeleton();
- if (skeleton) {
- const allControls = refSelectionsRenderService?.getSelectionControls() || [];
- if (allControls.length === selectionWithStyle.length) {
- allControls.forEach((control, index) => {
- const selection = selectionWithStyle[index];
- control.updateRange(attachRangeWithCoord(skeleton, selection.range), null);
- control.updateStyle(selection.style!);
- });
- } else {
- refSelectionsService.setSelections(selectionWithStyle);
- }
+ const allControls = refSelectionsRenderService?.getSelectionControls() || [];
+ if (allControls.length === selectionWithStyle.length) {
+ refSelectionsRenderService?.resetSelectionsByModelData(selectionWithStyle);
+ } else {
+ refSelectionsService.setSelections(selectionWithStyle);
}
};
return highlightSheet;
@@ -249,20 +245,3 @@ export function buildTextRuns(descriptionService: IDescriptionService, colorMap:
return { textRuns, refSelections };
};
-function getFormulaRefSelectionStyle(themeService: ThemeService, refColor: string, id: string): ISelectionStyle {
- const style = themeService.getCurrentTheme();
- const fill = new ColorKit(refColor).setAlpha(0.05).toRgbString();
- return {
- id,
- strokeWidth: 1,
- stroke: refColor,
- fill,
- widgets: { tl: true, tc: true, tr: true, ml: true, mr: true, bl: true, bc: true, br: true },
- widgetSize: 6,
- widgetStrokeWidth: 1,
- widgetStroke: style.colorWhite,
- hasAutoFill: false,
- hasRowHeader: false,
- hasColumnHeader: false,
- };
-}
diff --git a/packages/sheets-formula-ui/src/views/range-selector/hooks/useSheetSelectionChange.ts b/packages/sheets-formula-ui/src/views/range-selector/hooks/useSheetSelectionChange.ts
index f198231d4c..b594d944b5 100644
--- a/packages/sheets-formula-ui/src/views/range-selector/hooks/useSheetSelectionChange.ts
+++ b/packages/sheets-formula-ui/src/views/range-selector/hooks/useSheetSelectionChange.ts
@@ -17,7 +17,7 @@
/* eslint-disable max-lines-per-function */
import type { Workbook } from '@univerjs/core';
-import type { ISelectionWithCoordAndStyle } from '@univerjs/sheets';
+import type { ISelectionWithCoord } from '@univerjs/sheets';
import type { INode } from '../utils/filterReferenceNode';
import { DisposableCollection, IUniverInstanceService, useDependency } from '@univerjs/core';
@@ -63,7 +63,7 @@ export const useSheetSelectionChange = (isNeed: boolean,
useEffect(() => {
if (isNeed && refSelectionsRenderService) {
let isFirst = true;
- const handleSelectionsChange = (selections: ISelectionWithCoordAndStyle[], isEnd: boolean) => {
+ const handleSelectionsChange = (selections: ISelectionWithCoord[], isEnd: boolean) => {
if (isFirst || isScalingRef.current) {
isFirst = false;
return;
diff --git a/packages/sheets-formula/src/common/selection.ts b/packages/sheets-formula/src/common/selection.ts
deleted file mode 100644
index e7adb25f31..0000000000
--- a/packages/sheets-formula/src/common/selection.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import { ColorKit, type ThemeService } from '@univerjs/core';
-import type { ISelectionStyle } from '@univerjs/sheets';
-
-export const FORMULA_REF_SELECTION_PLUGIN_NAME = 'formula_reference_selection_plugin_name';
-
-export function getFormulaRefSelectionStyle(themeService: ThemeService, refColor: string, id: string): ISelectionStyle {
- const style = themeService.getCurrentTheme();
- const fill = new ColorKit(refColor).setAlpha(0.05).toRgbString();
- return {
- id,
- strokeWidth: 1,
- stroke: refColor,
- fill,
- widgets: { tl: true, tc: true, tr: true, ml: true, mr: true, bl: true, bc: true, br: true },
- widgetSize: 6,
- widgetStrokeWidth: 1,
- widgetStroke: style.colorWhite,
- hasAutoFill: false,
- hasRowHeader: false,
- hasColumnHeader: false,
- };
-}
diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx
index eb67717ebb..16dee0b8fe 100644
--- a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx
@@ -208,7 +208,7 @@ export const CellLinkEdit = () => {
endRow: editing.row,
},
style: {
- hasAutoFill: false,
+ // hasAutoFill: false,
fill: `rgb(${color.r}, ${color.g}, ${color.b}, 0.12)`,
strokeWidth: 1,
stroke: '#FFBD37',
diff --git a/packages/sheets-thread-comment-ui/src/controllers/sheets-thread-comment-popup.controller.ts b/packages/sheets-thread-comment-ui/src/controllers/sheets-thread-comment-popup.controller.ts
index 5fe654adf1..8ef34a29a5 100644
--- a/packages/sheets-thread-comment-ui/src/controllers/sheets-thread-comment-popup.controller.ts
+++ b/packages/sheets-thread-comment-ui/src/controllers/sheets-thread-comment-popup.controller.ts
@@ -71,7 +71,7 @@ export class SheetsThreadCommentPopupController extends Disposable {
if (!range) {
return;
}
- const actualCell = skeleton.getCellByIndex(range.startRow, range.startColumn);
+ const actualCell = skeleton.getCellWithCoordByIndex(range.startRow, range.startColumn);
const rangeType = range.rangeType ?? RANGE_TYPE.NORMAL;
if ((rangeType !== RANGE_TYPE.NORMAL || range.endColumn - range.startColumn > 0 || range.endRow - range.startRow > 0) && !((actualCell.isMerged || actualCell.isMergedMainCell) && Rectangle.equals(actualCell.mergeInfo, range))) {
@@ -250,7 +250,7 @@ export class SheetsThreadCommentPopupController extends Disposable {
{
range: mergeInfo,
style: {
- hasAutoFill: false,
+ // hasAutoFill: false,
fill: 'rgb(255, 189, 55, 0.35)',
strokeWidth: 1,
stroke: '#FFBD37',
diff --git a/packages/sheets-thread-comment-ui/src/views/sheets-thread-comment-panel/index.tsx b/packages/sheets-thread-comment-ui/src/views/sheets-thread-comment-panel/index.tsx
index b9ad34c0b4..b3a9227cf7 100644
--- a/packages/sheets-thread-comment-ui/src/views/sheets-thread-comment-panel/index.tsx
+++ b/packages/sheets-thread-comment-ui/src/views/sheets-thread-comment-panel/index.tsx
@@ -83,7 +83,7 @@ export const SheetsThreadCommentPanel = () => {
return markSelectionService.addShape({
range: mergeInfo,
style: {
- hasAutoFill: false,
+ // hasAutoFill: false,
fill: 'rgb(255, 189, 55, 0.35)',
strokeWidth: 1,
stroke: '#FFBD37',
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts
index 626cb08620..e59b008fbf 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts
@@ -15,6 +15,7 @@
*/
import type { DependencyIdentifier, Injector, Univer, Workbook } from '@univerjs/core';
+import type { ISelectionWithCoord } from '@univerjs/sheets';
import {
Disposable,
ICommandService,
@@ -26,7 +27,6 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
-import type { ISelectionWithCoordAndStyle } from '@univerjs/sheets';
import {
AddWorksheetMergeMutation,
RemoveWorksheetMergeMutation,
@@ -39,14 +39,14 @@ import { beforeEach, describe, expect, it } from 'vitest';
import { FormatPainterController } from '../../../controllers/format-painter/format-painter.controller';
import { FormatPainterService, IFormatPainterService } from '../../../services/format-painter/format-painter.service';
+import { IMarkSelectionService } from '../../../services/mark-selection/mark-selection.service';
+import { ISheetSelectionRenderService } from '../../../services/selection/base-selection-render.service';
import { SetFormatPainterOperation } from '../../operations/set-format-painter.operation';
import {
ApplyFormatPainterCommand,
SetInfiniteFormatPainterCommand,
SetOnceFormatPainterCommand,
} from '../set-format-painter.command';
-import { IMarkSelectionService } from '../../../services/mark-selection/mark-selection.service';
-import { ISheetSelectionRenderService } from '../../../services/selection/base-selection-render.service';
import { createCommandTestBed } from './create-command-test-bed';
const theme = {
@@ -201,7 +201,7 @@ describe('Test format painter rules in controller', () => {
beforeEach(() => {
class SheetSelectionRenderService {
- private readonly _selectionMoveEnd$ = new BehaviorSubject<ISelectionWithCoordAndStyle[]>([]);
+ private readonly _selectionMoveEnd$ = new BehaviorSubject<ISelectionWithCoord[]>([]);
readonly selectionMoveEnd$ = this._selectionMoveEnd$.asObservable();
}
diff --git a/packages/sheets-ui/src/commands/operations/scroll.operation.ts b/packages/sheets-ui/src/commands/operations/scroll.operation.ts
index a540a19967..00f3d97588 100644
--- a/packages/sheets-ui/src/commands/operations/scroll.operation.ts
+++ b/packages/sheets-ui/src/commands/operations/scroll.operation.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
+import type { IOperation } from '@univerjs/core';
+import type { IScrollStateWithSearchParam } from '../../services/scroll-manager.service';
+
import { CommandType, IUniverInstanceService } from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
-
-import type { IOperation } from '@univerjs/core';
import { SheetScrollManagerService } from '../../services/scroll-manager.service';
-import type { IScrollStateWithSearchParam } from '../../services/scroll-manager.service';
export const SetScrollOperation: IOperation<IScrollStateWithSearchParam> = {
id: 'sheet.operation.set-scroll',
diff --git a/packages/sheets-ui/src/common/utils.ts b/packages/sheets-ui/src/common/utils.ts
index 2b1518cac1..f37f88425b 100644
--- a/packages/sheets-ui/src/common/utils.ts
+++ b/packages/sheets-ui/src/common/utils.ts
@@ -123,20 +123,20 @@ export function getCellIndexByOffsetWithMerge(offsetX: number, offsetY: number,
y: activeViewport.viewportScrollY,
};
- const cellPos = skeleton.getCellPositionByOffset(offsetX, offsetY, scaleX, scaleY, scrollXY);
+ const cellIndex = skeleton.getCellIndexByOffset(offsetX, offsetY, scaleX, scaleY, scrollXY);
// const mergeCell = skeleton.mergeData.find((range) => {
// const { startColumn, startRow, endColumn, endRow } = range;
// return cellPos.row >= startRow && cellPos.column >= startColumn && cellPos.row <= endRow && cellPos.column <= endColumn;
// });
- const mergeCell = skeleton.worksheet.getMergedCell(cellPos.row, cellPos.column);
+ const mergeCell = skeleton.worksheet.getMergedCell(cellIndex.row, cellIndex.column);
const params = {
- actualRow: mergeCell ? mergeCell.startRow : cellPos.row,
- actualCol: mergeCell ? mergeCell.startColumn : cellPos.column,
+ actualRow: mergeCell ? mergeCell.startRow : cellIndex.row,
+ actualCol: mergeCell ? mergeCell.startColumn : cellIndex.column,
mergeCell,
- row: cellPos.row,
- col: cellPos.column,
+ row: cellIndex.row,
+ col: cellIndex.column,
};
return params;
@@ -229,7 +229,7 @@ export function getCellRealRange(workbook: Workbook, worksheet: Worksheet, skele
}
});
- const actualCell = skeleton.getCellByIndex(actualRow, actualCol);
+ const actualCell = skeleton.getCellWithCoordByIndex(actualRow, actualCol);
const location: ISheetLocation = {
unitId: workbook.getUnitId(),
@@ -272,7 +272,7 @@ export function getHoverCellPosition(currentRender: IRender, workbook: Workbook,
}
});
- const actualCell = skeleton.getCellByIndex(actualRow, actualCol);
+ const actualCell = skeleton.getCellWithCoordByIndex(actualRow, actualCol);
const location: ISheetLocation = getCellRealRange(workbook, worksheet, skeleton, actualRow, actualCol);
let anchorCell: IRange;
if (actualCell.mergeInfo) {
diff --git a/packages/sheets-ui/src/controllers/cell-custom-render.controller.ts b/packages/sheets-ui/src/controllers/cell-custom-render.controller.ts
index 3fdf6941b9..6229004c9b 100644
--- a/packages/sheets-ui/src/controllers/cell-custom-render.controller.ts
+++ b/packages/sheets-ui/src/controllers/cell-custom-render.controller.ts
@@ -82,7 +82,7 @@ export class CellCustomRenderController extends Disposable implements IRenderMod
y: activeViewport.viewportScrollY,
};
- const cellPos = skeleton.getCellPositionByOffset(offsetX, offsetY, scaleX, scaleY, scrollXY);
+ const cellPos = skeleton.getCellIndexByOffset(offsetX, offsetY, scaleX, scaleY, scrollXY);
// const mergeCell = skeleton.mergeData.find((range) => {
// const { startColumn, startRow, endColumn, endRow } = range;
@@ -120,7 +120,7 @@ export class CellCustomRenderController extends Disposable implements IRenderMod
const info: ICellRenderContext = {
data: cellData,
style: skeleton.getsStyles().getStyleByCell(cellData),
- primaryWithCoord: skeleton.getCellByIndex(cellIndex.actualRow, cellIndex.actualCol),
+ primaryWithCoord: skeleton.getCellWithCoordByIndex(cellIndex.actualRow, cellIndex.actualCol),
unitId,
subUnitId,
row,
diff --git a/packages/sheets-ui/src/controllers/defined-name/defined-name.controller.ts b/packages/sheets-ui/src/controllers/defined-name/defined-name.controller.ts
index 93ad3c2dd3..7f7ca6b2b9 100644
--- a/packages/sheets-ui/src/controllers/defined-name/defined-name.controller.ts
+++ b/packages/sheets-ui/src/controllers/defined-name/defined-name.controller.ts
@@ -18,8 +18,9 @@ import type { Workbook } from '@univerjs/core';
import type { ISelectionWithStyle } from '@univerjs/sheets';
import { Disposable, ICommandService, Inject, IUniverInstanceService, ThemeService, UniverInstanceType } from '@univerjs/core';
import { deserializeRangeWithSheet, IDefinedNamesService, isReferenceStrings, operatorToken } from '@univerjs/engine-formula';
-import { getNormalSelectionStyle, getPrimaryForRange, ScrollToCellOperation, SetWorksheetActivateCommand, SheetsSelectionsService } from '@univerjs/sheets';
+import { getPrimaryForRange, ScrollToCellOperation, SetWorksheetActivateCommand, SheetsSelectionsService } from '@univerjs/sheets';
import { filter, merge } from 'rxjs';
+import { genNormalSelectionStyle } from '../../services/selection/const';
export class SheetsDefinedNameController extends Disposable {
constructor(
@@ -135,7 +136,7 @@ export class SheetsDefinedNameController extends Disposable {
selections.push({
range: unitRange.range,
- style: getNormalSelectionStyle(this._themeService),
+ style: genNormalSelectionStyle(this._themeService),
primary,
});
}
diff --git a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
index b99704636d..f9369ad4ef 100644
--- a/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/editing.render-controller.ts
@@ -19,7 +19,7 @@
import type { DocumentDataModel, ICellData, ICommandInfo, IDisposable, IDocumentBody, IDocumentData, IStyleData, Nullable, Styles, UnitModel, Workbook } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
-import type { WorkbookSelections } from '@univerjs/sheets';
+import type { WorkbookSelectionModel } from '@univerjs/sheets';
import type { IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';
import {
@@ -88,7 +88,7 @@ export class EditingRenderController extends Disposable implements IRenderModule
/** If the corresponding unit is active and prepared for editing. */
private _isUnitEditing = false;
- private _workbookSelections: WorkbookSelections;
+ private _workbookSelections: WorkbookSelectionModel;
private _d: Nullable<IDisposable>;
_cursorTimeout: NodeJS.Timeout;
diff --git a/packages/sheets-ui/src/controllers/mark-selection.controller.ts b/packages/sheets-ui/src/controllers/mark-selection.controller.ts
index 13317ecad8..145799eea0 100644
--- a/packages/sheets-ui/src/controllers/mark-selection.controller.ts
+++ b/packages/sheets-ui/src/controllers/mark-selection.controller.ts
@@ -15,9 +15,9 @@
*/
import type { ICommandInfo, Workbook } from '@univerjs/core';
-import { Disposable, ICommandService, Inject } from '@univerjs/core';
-
import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
+
+import { Disposable, ICommandService, Inject } from '@univerjs/core';
import { SetCellEditVisibleOperation } from '../commands/operations/cell-edit.operation';
import { IMarkSelectionService } from '../services/mark-selection/mark-selection.service';
import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';
diff --git a/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-canvas-render.controller.ts b/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-canvas-render.controller.ts
index 088a196545..969b651a4d 100644
--- a/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-canvas-render.controller.ts
+++ b/packages/sheets-ui/src/controllers/permission/sheet-permission-interceptor-canvas-render.controller.ts
@@ -156,7 +156,7 @@ export class SheetPermissionInterceptorCanvasRenderController extends RxDisposab
const selectionRange = ranges?.find((range) => {
const transformCoord = getTransformCoord(position.x, position.y, position.scene, position.skeleton);
- const cellPosition = position.skeleton.getCellByIndex(range.endRow, range.endColumn);
+ const cellPosition = position.skeleton.getCellWithCoordByIndex(range.endRow, range.endColumn);
const missX = Math.abs(cellPosition.endX - transformCoord.x);
const missY = Math.abs(cellPosition.endY - transformCoord.y);
return missX <= 5 && missY <= 5;
diff --git a/packages/sheets-ui/src/controllers/render-controllers/contextmenu.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/contextmenu.render-controller.ts
index b66d2a2de7..3a9bc98699 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/contextmenu.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/contextmenu.render-controller.ts
@@ -15,12 +15,12 @@
*/
import type { Workbook } from '@univerjs/core';
+import type { IRenderContext, IRenderModule, Spreadsheet, SpreadsheetColumnHeader, SpreadsheetHeader } from '@univerjs/engine-render';
import {
Disposable,
Inject,
RANGE_TYPE,
} from '@univerjs/core';
-import type { IRenderContext, IRenderModule, Spreadsheet, SpreadsheetColumnHeader, SpreadsheetHeader } from '@univerjs/engine-render';
import { SheetsSelectionsService } from '@univerjs/sheets';
import { ContextMenuPosition, IContextMenuService } from '@univerjs/ui';
diff --git a/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts
index 90433f03e3..57ff736878 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts
@@ -46,7 +46,7 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende
@IUniverInstanceService private readonly _instanceSrv: IUniverInstanceService,
@ICommandService private readonly _commandService: ICommandService,
@IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
- // FIXME: should use WorkbookSelections
+ // FIXME: should use WorkbookSelectionModel
// FIXME: should check if it is the current sheet, if it becomes the current sheet,
// it should update cell params, otherwise it should do nothing.
@Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
@@ -101,7 +101,7 @@ export class EditorBridgeRenderController extends RxDisposable implements IRende
const unitId = this._context.unitId;
const sheetId = this._context.unit.getActiveSheet()?.getSheetId();
if (!sheetId) return;
- const mergeInfo = this._sheetSkeletonManagerService.getWorksheetSkeleton(sheetId)?.skeleton.getCellByIndex(primary.actualRow, primary.actualColumn);
+ const mergeInfo = this._sheetSkeletonManagerService.getWorksheetSkeleton(sheetId)?.skeleton.getCellWithCoordByIndex(primary.actualRow, primary.actualColumn);
const newPrimary: ISelectionCell = mergeInfo
? {
actualRow: mergeInfo.actualRow,
diff --git a/packages/sheets-ui/src/controllers/render-controllers/header-move.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/header-move.render-controller.ts
index b945fddba3..f2f7f47ffb 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/header-move.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/header-move.render-controller.ts
@@ -14,6 +14,14 @@
* limitations under the License.
*/
+import type {
+ EventState,
+ IRange,
+ Nullable,
+ Workbook,
+} from '@univerjs/core';
+import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule, SpreadsheetColumnHeader, SpreadsheetHeader } from '@univerjs/engine-render';
+import type { IMoveColsCommandParams, IMoveRowsCommandParams, ISelectionWithStyle, WorkbookSelectionModel } from '@univerjs/sheets';
import {
createInterceptorKey, Disposable, ICommandService,
Inject,
@@ -32,16 +40,8 @@ import {
MoveRowsCommand,
SheetsSelectionsService,
} from '@univerjs/sheets';
-import { Subscription } from 'rxjs';
-import type {
- EventState,
- IRange,
- Nullable,
- Workbook,
-} from '@univerjs/core';
-import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule, SpreadsheetColumnHeader, SpreadsheetHeader } from '@univerjs/engine-render';
-import type { IMoveColsCommandParams, IMoveRowsCommandParams, ISelectionWithStyle, WorkbookSelections } from '@univerjs/sheets';
+import { Subscription } from 'rxjs';
import { SHEET_COMPONENT_HEADER_LAYER_INDEX, SHEET_VIEW_KEY } from '../../common/keys';
import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';
import { getCoordByOffset } from '../utils/component-tools';
@@ -77,7 +77,7 @@ export class HeaderMoveRenderController extends Disposable implements IRenderMod
public readonly interceptor = new InterceptorManager({ HEADER_MOVE_PERMISSION_CHECK });
- private readonly _workbookSelections: WorkbookSelections;
+ private readonly _workbookSelections: WorkbookSelectionModel;
constructor(
private readonly _context: IRenderContext<Workbook>,
@@ -181,7 +181,7 @@ export class HeaderMoveRenderController extends Disposable implements IRenderMod
const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
- const relativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+ const relativeCoords = scene.getCoordRelativeToViewport(Vector2.FromArray([evtOffsetX, evtOffsetY]));
const { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
@@ -213,7 +213,7 @@ export class HeaderMoveRenderController extends Disposable implements IRenderMod
}
// if matchSelectionData true, then into grab header mode.
- const startScrollXY = scene.getVpScrollXYInfoByPosToVp(
+ const startScrollXY = scene.getScrollXYInfoByViewport(
Vector2.FromArray([this._startOffsetX, this._startOffsetY])
);
@@ -242,7 +242,7 @@ export class HeaderMoveRenderController extends Disposable implements IRenderMod
initScrollTimer();
const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
- const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeToViewportCoord(
+ const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getCoordRelativeToViewport(
Vector2.FromArray([moveOffsetX, moveOffsetY])
);
@@ -367,7 +367,7 @@ export class HeaderMoveRenderController extends Disposable implements IRenderMod
const scrollXY = scene.getViewportScrollXY(scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN)!);
const { scaleX, scaleY } = scene.getAncestorScale();
- const moveActualSelection = skeleton.getCellPositionByOffset(
+ const moveActualSelection = skeleton.getCellIndexByOffset(
moveOffsetX,
moveOffsetY,
scaleX,
diff --git a/packages/sheets-ui/src/controllers/render-controllers/header-resize.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/header-resize.render-controller.ts
index 2c0d96e153..98285680ed 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/header-resize.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/header-resize.render-controller.ts
@@ -378,11 +378,11 @@ export class HeaderResizeRenderController extends Disposable implements IRenderM
// });
this._scenePointerMoveSub = scene.onPointerMove$.subscribeEvent((moveEvt: IPointerEvent | IMouseEvent) => {
- const relativeCoords = scene.getRelativeToViewportCoord(
+ const relativeCoords = scene.getCoordRelativeToViewport(
Vector2.FromArray([this._startOffsetX, this._startOffsetY])
);
- const scrollXY = scene.getVpScrollXYInfoByPosToVp(relativeCoords, viewPort);
+ const scrollXY = scene.getScrollXYInfoByViewport(relativeCoords, viewPort);
const transformCoord = getTransformCoord(moveEvt.offsetX, moveEvt.offsetY, scene, skeleton);
diff --git a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-contextmenu.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-contextmenu.render-controller.ts
index 9829719dd0..473c11c536 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-contextmenu.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-contextmenu.render-controller.ts
@@ -20,6 +20,7 @@ import { type IPointerEvent, type IRenderContext, type IRenderModule, SHEET_VIEW
import { type ISelectionWithStyle, SheetsSelectionsService } from '@univerjs/sheets';
import { ContextMenuPosition, IContextMenuService, ILayoutService } from '@univerjs/ui';
import { ISheetSelectionRenderService } from '../../../services/selection/base-selection-render.service';
+import { attachSelectionWithCoord } from '../../../services/selection/util';
import { SheetSkeletonManagerService } from '../../../services/sheet-skeleton-manager.service';
/**
@@ -44,22 +45,19 @@ export class SheetContextMenuMobileRenderController extends Disposable implement
private _init(): void {
let listenToSelectionChangeEvent = false;
this.disposeWithMe(this._selectionManagerService.selectionMoveStart$.subscribe(() => listenToSelectionChangeEvent = true));
- this.disposeWithMe(this._selectionManagerService.selectionMoveEnd$.subscribe((selectionsList: ISelectionWithStyle[]) => {
- if (!selectionsList || listenToSelectionChangeEvent === false) {
+ this.disposeWithMe(this._selectionManagerService.selectionMoveEnd$.subscribe((selectionWithStyleList: ISelectionWithStyle[]) => {
+ const skeleton = this._sheetSkeletonManagerService.getCurrent()!.skeleton;
+ if (!skeleton || !selectionWithStyleList || listenToSelectionChangeEvent === false) {
return;
}
listenToSelectionChangeEvent = false;
- const selectionRangeWithStyle = selectionsList[0];
- // if (!selectionRangeWithStyle.primary || Rectangle.equals(selectionRangeWithStyle.range, selectionRangeWithStyle.primary)) {
- // return;
- // }
+ const selectionRangeWithStyle = selectionWithStyleList[0] as unknown as ISelectionWithStyle;
if (!selectionRangeWithStyle.primary) return;
- const canvasRect = this._layoutService.getContentElement().getBoundingClientRect();
- const range = this._selectionRenderService.attachSelectionWithCoord(selectionRangeWithStyle as unknown as ISelectionWithStyle);
+ const selectionWithCoord = attachSelectionWithCoord(selectionRangeWithStyle, skeleton);
const rangeType = selectionRangeWithStyle.range.rangeType;
const { scene } = this._context;
@@ -70,33 +68,33 @@ export class SheetContextMenuMobileRenderController extends Disposable implement
let clientX = 0;
let clientY = 0;
- const skeleton = this._sheetSkeletonManagerService.getCurrent()!.skeleton;
const rowHeaderWidth = skeleton.rowHeaderWidth;
// TODO @lumixraku popup should positioned by transform not topleft.
// using transform & transform-origin would be easy to position popup
+ const canvasRect = this._layoutService.getContentElement().getBoundingClientRect();
switch (rangeType) {
case RANGE_TYPE.NORMAL:
- clientX = range.rangeWithCoord.startX + canvasRect.left - viewportScrollX;
- clientY = range.rangeWithCoord.endY + canvasRect.top - viewportScrollY;
+ clientX = selectionWithCoord.rangeWithCoord.startX + canvasRect.left - viewportScrollX;
+ clientY = selectionWithCoord.rangeWithCoord.endY + canvasRect.top - viewportScrollY;
break;
case RANGE_TYPE.COLUMN:
- clientX = range.rangeWithCoord.startX + canvasRect.left - viewportScrollX;
+ clientX = selectionWithCoord.rangeWithCoord.startX + canvasRect.left - viewportScrollX;
// slightly lower than control point for easy to drag control point.
- clientY = Math.min(canvasRect.height / 2, range.rangeWithCoord.endY) + 40;
+ clientY = Math.min(canvasRect.height / 2, selectionWithCoord.rangeWithCoord.endY) + 40;
break;
case RANGE_TYPE.ROW:
// slightly left than control point for easy to drag control point.
clientX = (canvasRect.width - rowHeaderWidth) / 2 + 20;
- clientY = range.rangeWithCoord.endY + canvasRect.top - viewportScrollY;
+ clientY = selectionWithCoord.rangeWithCoord.endY + canvasRect.top - viewportScrollY;
break;
case RANGE_TYPE.ALL:
- clientX = range.rangeWithCoord.startX + canvasRect.left;
- clientY = range.rangeWithCoord.startY + canvasRect.top;
+ clientX = selectionWithCoord.rangeWithCoord.startX + canvasRect.left;
+ clientY = selectionWithCoord.rangeWithCoord.startY + canvasRect.top;
break;
default:
- clientX = range.rangeWithCoord.startX + canvasRect.left - viewportScrollX;
- clientY = range.rangeWithCoord.endY + canvasRect.top - viewportScrollY;
+ clientX = selectionWithCoord.rangeWithCoord.startX + canvasRect.left - viewportScrollX;
+ clientY = selectionWithCoord.rangeWithCoord.endY + canvasRect.top - viewportScrollY;
break;
}
// in case clientXY is not in screen area.
diff --git a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts
index ba17e09582..89aed6a2c8 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/mobile/mobile-scroll.render-controller.ts
@@ -187,9 +187,10 @@ export class MobileSheetsScrollRenderController extends Disposable implements IR
// data source: scroll-manager.service.ts@_scrollInfo
const { sheetViewStartRow, sheetViewStartColumn, offsetX, offsetY } = rawScrollInfo;
- const { startX, startY } = skeleton.getCellByIndexWithNoHeader(
+ const { startX, startY } = skeleton.getCellWithCoordByIndex(
sheetViewStartRow,
- sheetViewStartColumn
+ sheetViewStartColumn,
+ false
);
// viewportScrollXByEvent is not same as viewportScrollX, by event, the value may be negative, or over max
diff --git a/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts
index 52935d4989..c8cef02f24 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/scroll.render-controller.ts
@@ -257,9 +257,10 @@ export class SheetsScrollRenderController extends Disposable implements IRenderM
// prev scrolling state from rawScrollInfo$
const { sheetViewStartRow, sheetViewStartColumn, offsetX, offsetY } = rawScrollInfo;
- const { startX, startY } = skeleton.getCellByIndexWithNoHeader(
+ const { startX, startY } = skeleton.getCellWithCoordByIndex(
sheetViewStartRow,
- sheetViewStartColumn
+ sheetViewStartColumn,
+ false
);
const viewportScrollX = startX + offsetX;
diff --git a/packages/sheets-ui/src/controllers/utils/component-tools.ts b/packages/sheets-ui/src/controllers/utils/component-tools.ts
index 46c5275836..8604bd0371 100644
--- a/packages/sheets-ui/src/controllers/utils/component-tools.ts
+++ b/packages/sheets-ui/src/controllers/utils/component-tools.ts
@@ -96,7 +96,7 @@ export function getSheetObject(
}
export function getCoordByCell(row: number, col: number, scene: Scene, skeleton: SpreadsheetSkeleton) {
- const { startX, startY, endX, endY } = skeleton.getCellByIndex(row, col);
+ const { startX, startY, endX, endY } = skeleton.getCellWithCoordByIndex(row, col);
return { startX, startY, endX, endY };
}
@@ -108,15 +108,15 @@ export function getCoordByOffset(
viewport?: Viewport,
closeFirst?: boolean
) {
- const relativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+ const relativeCoords = scene.getCoordRelativeToViewport(Vector2.FromArray([evtOffsetX, evtOffsetY]));
const { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
- const scrollXY = scene.getVpScrollXYInfoByPosToVp(relativeCoords, viewport);
+ const scrollXY = scene.getScrollXYInfoByViewport(relativeCoords, viewport);
const { scaleX, scaleY } = scene.getAncestorScale();
- const moveActualSelection = skeleton.getCellPositionByOffset(
+ const moveActualSelection = skeleton.getCellIndexByOffset(
newEvtOffsetX,
newEvtOffsetY,
scaleX,
@@ -142,11 +142,11 @@ export function getCoordByOffset(
}
export function getTransformCoord(evtOffsetX: number, evtOffsetY: number, scene: Scene, skeleton: SpreadsheetSkeleton) {
- const relativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+ const relativeCoords = scene.getCoordRelativeToViewport(Vector2.FromArray([evtOffsetX, evtOffsetY]));
const viewMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
- const scrollXY = scene.getVpScrollXYInfoByPosToVp(relativeCoords, viewMain);
+ const scrollXY = scene.getScrollXYInfoByViewport(relativeCoords, viewMain);
const { scaleX, scaleY } = scene.getAncestorScale();
const { x: scrollX, y: scrollY } = scrollXY;
diff --git a/packages/sheets-ui/src/facade/f-range.ts b/packages/sheets-ui/src/facade/f-range.ts
index 65ca88e5ef..8bb468363e 100644
--- a/packages/sheets-ui/src/facade/f-range.ts
+++ b/packages/sheets-ui/src/facade/f-range.ts
@@ -14,9 +14,10 @@
* limitations under the License.
*/
+import type { ICellWithCoord, IDisposable, Nullable } from '@univerjs/core';
import type { ISheetLocation } from '@univerjs/sheets';
import type { ComponentType } from '@univerjs/ui';
-import { DisposableCollection, generateRandomId, type IDisposable, type ISelectionCellWithMergeInfo, type Nullable } from '@univerjs/core';
+import { DisposableCollection, generateRandomId } from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
import { FRange } from '@univerjs/sheets/facade';
import { CellAlertManagerService, type ICanvasPopup, type ICellAlert, SheetCanvasPopManagerService } from '@univerjs/sheets-ui';
@@ -43,7 +44,7 @@ interface IFRangeSheetsUIMixin {
* Return this cell information, including whether it is merged and cell coordinates
* @returns The cell information
*/
- getCell(): ISelectionCellWithMergeInfo;
+ getCell(): ICellWithCoord;
/**
* Returns the coordinates of this cell,does not include units
* @returns coordinates of the cell, top, right, bottom, left
@@ -71,14 +72,14 @@ interface IFRangeSheetsUIMixin {
}
class FRangeSheetsUIMixin extends FRange implements IFRangeSheetsUIMixin {
- override getCell(): ISelectionCellWithMergeInfo {
+ override getCell(): ICellWithCoord {
const renderManagerService = this._injector.get(IRenderManagerService);
const unitId = this._workbook.getUnitId();
const subUnitId = this._worksheet.getSheetId();
const skeleton = renderManagerService.getRenderById(unitId)!
.with(SheetSkeletonManagerService)
.getWorksheetSkeleton(subUnitId)!.skeleton;
- return skeleton.getCellByIndex(this._range.startRow, this._range.startColumn);
+ return skeleton.getCellWithCoordByIndex(this._range.startRow, this._range.startColumn);
}
override getCellRect(): DOMRect {
diff --git a/packages/sheets-ui/src/hooks/useHighlightRange.ts b/packages/sheets-ui/src/hooks/useHighlightRange.ts
index bbcac24e46..2380b41b5b 100644
--- a/packages/sheets-ui/src/hooks/useHighlightRange.ts
+++ b/packages/sheets-ui/src/hooks/useHighlightRange.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-import { useEffect } from 'react';
import type { IRange } from '@univerjs/core';
import { useDependency } from '@univerjs/core';
+import { useEffect } from 'react';
import { IMarkSelectionService } from '../services/mark-selection/mark-selection.service';
export const useHighlightRange = (ranges: IRange[] = []) => {
@@ -25,7 +25,6 @@ export const useHighlightRange = (ranges: IRange[] = []) => {
const ids = ranges.map((range) => markSelectionService.addShape({
range,
style: {
- hasAutoFill: false,
fill: 'rgba(73, 184, 17, 0.05)',
strokeWidth: 1,
stroke: '#49B811',
diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.ts
index 9ecec6de75..ac32e0a830 100644
--- a/packages/sheets-ui/src/index.ts
+++ b/packages/sheets-ui/src/index.ts
@@ -61,11 +61,14 @@ export {
export { MarkSelectionService } from './services/mark-selection/mark-selection.service';
export { IMarkSelectionService } from './services/mark-selection/mark-selection.service';
export { SheetSelectionRenderService } from './services/selection/selection-render.service';
-export { getAllSelection, getTopLeftSelection } from './services/selection/base-selection-render.service';
+export { genSelectionByRange, getTopLeftSelectionOfCurrSheet, selectionDataForSelectAll as getAllSelection } from './services/selection/base-selection-render.service';
export { BaseSelectionRenderService, ISheetSelectionRenderService } from './services/selection/base-selection-render.service';
-export { SelectionControl as SelectionShape } from './services/selection/selection-control';
+export { SelectionControl as SelectionShape, SelectionControl } from './services/selection/selection-control';
+export { SelectionShapeExtension } from './services/selection/selection-shape-extension';
+export { genNormalSelectionStyle } from './services/selection/const';
export type { ISheetSkeletonManagerParam } from './services/sheet-skeleton-manager.service';
-export { attachRangeWithCoord, SheetSkeletonManagerService } from './services/sheet-skeleton-manager.service';
+export { SheetSkeletonManagerService } from './services/sheet-skeleton-manager.service';
+export { attachPrimaryWithCoord, attachRangeWithCoord, attachSelectionWithCoord } from './services/selection/util';
export { UniverSheetsUIPlugin } from './plugin';
export { SheetRenderController } from './controllers/render-controllers/sheet.render-controller';
export { HoverManagerService } from './services/hover-manager.service';
@@ -105,7 +108,6 @@ export type { IFormatPainterBeforeApplyHookParams, IFormatPainterHook } from './
export { type IBaseSheetBarProps } from './views/sheet-bar/sheet-bar-tabs/SheetBarItem';
export { FONT_FAMILY_COMPONENT, FONT_FAMILY_ITEM_COMPONENT } from './components/font-family/interface';
export { FONT_SIZE_COMPONENT } from './components/font-size/interface';
-export { attachPrimaryWithCoord, attachSelectionWithCoord } from './services/selection/util';
export { SELECTION_SHAPE_DEPTH } from './services/selection/const';
export { isRangeSelector, RANGE_SELECTOR_SYMBOLS } from './controllers/editor/utils/isRangeSelector';
export { EMBEDDING_FORMULA_EDITOR, isEmbeddingFormulaEditor } from './controllers/editor/utils/isEmbeddingFormulaEditor';
diff --git a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts b/packages/sheets-ui/src/services/canvas-pop-manager.service.ts
index e6bbbcb511..4322f20c68 100644
--- a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts
+++ b/packages/sheets-ui/src/services/canvas-pop-manager.service.ts
@@ -473,7 +473,7 @@ export class SheetCanvasPopManagerService extends Disposable {
): IBoundRectNoAngle {
const { scene, engine } = currentRender;
- const primaryWithCoord = skeleton.getCellByIndex(row, col);
+ const primaryWithCoord = skeleton.getCellWithCoordByIndex(row, col);
const cellInfo = primaryWithCoord.isMergedMainCell ? primaryWithCoord.mergeInfo : primaryWithCoord;
const { scaleX, scaleY } = scene.getAncestorScale();
diff --git a/packages/sheets-ui/src/services/editor-bridge.service.ts b/packages/sheets-ui/src/services/editor-bridge.service.ts
index 8163a9541f..0b05707371 100644
--- a/packages/sheets-ui/src/services/editor-bridge.service.ts
+++ b/packages/sheets-ui/src/services/editor-bridge.service.ts
@@ -21,6 +21,7 @@ import type { KeyCode } from '@univerjs/ui';
import type { Observable } from 'rxjs';
import {
CellValueType,
+ convertCellToRange,
createIdentifier,
Disposable,
DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
@@ -30,7 +31,6 @@ import {
IContextService,
Inject,
IUniverInstanceService,
- makeCellToSelection,
ThemeService,
toDisposable,
UniverInstanceType,
@@ -194,12 +194,12 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServ
if (!this._currentEditCellState) return;
const { primary, unitId, sheetId, scene, engine } = currentEditCell;
- const primaryWithCoord = attachPrimaryWithCoord(primary, skeleton);
+ const primaryWithCoord = attachPrimaryWithCoord(skeleton, primary);
if (primaryWithCoord == null) {
return;
}
- const actualRangeWithCoord = makeCellToSelection(primaryWithCoord);
+ const actualRangeWithCoord = convertCellToRange(primaryWithCoord);
const canvasOffset = getCanvasOffsetByEngine(engine);
let { startX, startY, endX, endY } = actualRangeWithCoord;
@@ -309,12 +309,12 @@ export class EditorBridgeService extends Disposable implements IEditorBridgeServ
const { primary, unitId, sheetId, scene, engine } = currentEditCell;
const { startRow, startColumn } = primary;
- const primaryWithCoord = attachPrimaryWithCoord(primary, skeleton);
+ const primaryWithCoord = attachPrimaryWithCoord(skeleton, primary);
if (primaryWithCoord == null) {
return;
}
- const actualRangeWithCoord = makeCellToSelection(primaryWithCoord);
+ const actualRangeWithCoord = convertCellToRange(primaryWithCoord);
const canvasOffset = getCanvasOffsetByEngine(engine);
let { startX, startY, endX, endY } = actualRangeWithCoord;
diff --git a/packages/sheets-ui/src/services/editor/cell-editor-resize.service.ts b/packages/sheets-ui/src/services/editor/cell-editor-resize.service.ts
index d41ce2db62..6292614e7a 100644
--- a/packages/sheets-ui/src/services/editor/cell-editor-resize.service.ts
+++ b/packages/sheets-ui/src/services/editor/cell-editor-resize.service.ts
@@ -362,7 +362,7 @@ export class SheetCellEditorResizeService extends Disposable implements IRenderM
if (!maxSize) return;
const { height: clientHeight, width: clientWidth, scaleAdjust } = maxSize;
- const cell = skeleton.getCellByIndex(row, column);
+ const cell = skeleton.getCellWithCoordByIndex(row, column);
const height = Math.min((cell.mergeInfo.endY - cell.mergeInfo.startY) * scaleY, clientHeight) * scaleAdjust;
const width = Math.min((cell.mergeInfo.endX - cell.mergeInfo.startX) * scaleX, clientWidth) * scaleAdjust;
const currentHeight = state.endY! - state.startY!;
diff --git a/packages/sheets-ui/src/services/hover-manager.service.ts b/packages/sheets-ui/src/services/hover-manager.service.ts
index f10b364943..b792f08895 100644
--- a/packages/sheets-ui/src/services/hover-manager.service.ts
+++ b/packages/sheets-ui/src/services/hover-manager.service.ts
@@ -158,7 +158,7 @@ export class HoverManagerService extends Disposable {
paragraph: IParagraph;
}> = null;
- const cell = skeleton.getCellByIndex(overflowLocation.row, overflowLocation.col);
+ const cell = skeleton.getCellWithCoordByIndex(overflowLocation.row, overflowLocation.col);
const cellData = worksheet.getCell(overflowLocation.row, overflowLocation.col);
const { topOffset = 0, leftOffset = 0 } = cellData?.fontRenderExtension ?? {};
diff --git a/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts b/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts
index 48b980dd4f..af528fa67e 100644
--- a/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts
+++ b/packages/sheets-ui/src/services/mark-selection/mark-selection.service.ts
@@ -19,10 +19,9 @@ import type { ISelectionWithStyle } from '@univerjs/sheets';
import { createIdentifier, Disposable, Inject, IUniverInstanceService, ThemeService, Tools, UniverInstanceType } from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
-import { ISheetSelectionRenderService } from '../selection/base-selection-render.service';
import { SELECTION_SHAPE_DEPTH } from '../selection/const';
-// import { ISheetSelectionRenderService } from '../selection/base-selection-render.service';
import { SelectionControl } from '../selection/selection-control';
+import { attachSelectionWithCoord } from '../selection/util';
import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
export interface IMarkSelectionService {
@@ -46,7 +45,9 @@ const DEFAULT_Z_INDEX = SELECTION_SHAPE_DEPTH.MARK_SELECTION; ;
export const IMarkSelectionService = createIdentifier<IMarkSelectionService>('univer.mark-selection-service');
/**
- * For condition format selection.
+ * For copy and cut selection.
+ * also for selection when hover on conditional format items in the cf panel on the right.
+ * but hover on panel if data validation, uses another method to draw selection.
*/
export class MarkSelectionService extends Disposable implements IMarkSelectionService {
private _shapeMap: Map<string, IMarkSelectionInfo> = new Map();
@@ -64,14 +65,16 @@ export class MarkSelectionService extends Disposable implements IMarkSelectionSe
const subUnitId = workbook.getActiveSheet()?.getSheetId();
if (!subUnitId) return null;
const id = Tools.generateRandomId();
- this._shapeMap.set(id, {
+
+ const markSelectionInfo: IMarkSelectionInfo = {
selection,
subUnitId,
unitId: workbook.getUnitId(),
zIndex,
control: null,
exits,
- });
+ };
+ this._shapeMap.set(id, markSelectionInfo);
this.refreshShapes();
return id;
@@ -99,13 +102,14 @@ export class MarkSelectionService extends Disposable implements IMarkSelectionSe
const { scene } = renderUnit;
const { rowHeaderWidth, columnHeaderHeight } = skeleton;
- const control = new SelectionControl(scene, zIndex, this._themeService, false, { rowHeaderWidth, columnHeaderHeight });
- const { rangeWithCoord, primaryWithCoord } = renderUnit.with(ISheetSelectionRenderService).attachSelectionWithCoord(selection);
- control.updateRange(rangeWithCoord, primaryWithCoord);
- const { style } = selection;
- if (style) {
- control.updateStyle(style);
- }
+ const control = new SelectionControl(scene, zIndex, this._themeService, {
+ enableAutoFill: false,
+ highlightHeader: false,
+ rowHeaderWidth,
+ columnHeaderHeight,
+ });
+ const selectionWithCoord = attachSelectionWithCoord(selection, skeleton);
+ control.updateRangeBySelectionWithCoord(selectionWithCoord);
shape.control = control;
});
}
diff --git a/packages/sheets-ui/src/services/scroll-manager.service.ts b/packages/sheets-ui/src/services/scroll-manager.service.ts
index eaa90a0f2d..e1ed08fc55 100644
--- a/packages/sheets-ui/src/services/scroll-manager.service.ts
+++ b/packages/sheets-ui/src/services/scroll-manager.service.ts
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-import { Inject } from '@univerjs/core';
-import { BehaviorSubject } from 'rxjs';
import type { Nullable, Workbook } from '@univerjs/core';
import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import { Inject } from '@univerjs/core';
+import { BehaviorSubject } from 'rxjs';
import { SheetSkeletonManagerService } from './sheet-skeleton-manager.service';
export interface IScrollState {
diff --git a/packages/sheets-ui/src/services/selection/base-selection-render.service.ts b/packages/sheets-ui/src/services/selection/base-selection-render.service.ts
index aea47a226c..4d9e53b140 100644
--- a/packages/sheets-ui/src/services/selection/base-selection-render.service.ts
+++ b/packages/sheets-ui/src/services/selection/base-selection-render.service.ts
@@ -15,33 +15,30 @@
*/
import type {
+ ICellInfo,
+ ICellWithCoord,
IDisposable,
IFreeze,
IInterceptor,
Injector,
IRange,
IRangeWithCoord,
- ISelectionCell,
- ISelectionCellWithMergeInfo,
- ISelectionWithCoord,
Nullable,
ThemeService,
} from '@univerjs/core';
import type { IMouseEvent, IPointerEvent, IRenderModule, Scene, SpreadsheetSkeleton, Viewport } from '@univerjs/engine-render';
-import type { ISelectionStyle, ISelectionWithCoordAndStyle, ISelectionWithStyle } from '@univerjs/sheets';
+import type { ISelectionStyle, ISelectionWithCoord, ISelectionWithStyle } from '@univerjs/sheets';
import type { IShortcutService } from '@univerjs/ui';
import type { Observable, Subscription } from 'rxjs';
import type { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
-import { createIdentifier, Disposable, InterceptorManager, makeCellToSelection, RANGE_TYPE } from '@univerjs/core';
-import { ScrollTimer, ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
-import { getNormalSelectionStyle as getDefaultNormalSelectionStyle, transformCellDataToSelectionData } from '@univerjs/sheets';
+import { convertCellToRange, createIdentifier, Disposable, InterceptorManager, RANGE_TYPE } from '@univerjs/core';
+import { ScrollTimer, ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
import { BehaviorSubject, Subject } from 'rxjs';
import { SHEET_COMPONENT_SELECTION_LAYER_INDEX } from '../../common/keys';
-import { RANGE_FILL_PERMISSION_CHECK, RANGE_MOVE_PERMISSION_CHECK } from './const';
+import { genNormalSelectionStyle, RANGE_FILL_PERMISSION_CHECK, RANGE_MOVE_PERMISSION_CHECK } from './const';
import { SelectionControl } from './selection-control';
import { SelectionLayer } from './selection-layer';
-import { SelectionShapeExtension } from './selection-shape-extension';
import { attachPrimaryWithCoord, attachSelectionWithCoord } from './util';
export interface IControlFillConfig {
@@ -50,10 +47,10 @@ export interface IControlFillConfig {
}
export interface ISheetSelectionRenderService {
- readonly selectionMoveEnd$: Observable<ISelectionWithCoordAndStyle[]>;
+ readonly selectionMoveEnd$: Observable<ISelectionWithCoord[]>;
readonly controlFillConfig$: Observable<IControlFillConfig | null>;
- readonly selectionMoving$: Observable<ISelectionWithCoordAndStyle[]>;
- readonly selectionMoveStart$: Observable<ISelectionWithCoordAndStyle[]>;
+ readonly selectionMoving$: Observable<ISelectionWithCoord[]>;
+ readonly selectionMoveStart$: Observable<ISelectionWithCoord[]>;
get selectionMoving(): boolean;
@@ -73,11 +70,16 @@ export interface ISheetSelectionRenderService {
// And `attachPrimaryWithCoord` is redundant.
/** @deprecated Use the function `attachSelectionWithCoord` instead. */
- attachSelectionWithCoord(selectionWithStyle: ISelectionWithStyle): ISelectionWithCoordAndStyle;
+ attachSelectionWithCoord(selectionWithStyle: ISelectionWithStyle): ISelectionWithCoord;
/** @deprecated Use the function `attachPrimaryWithCoord` instead`. */
- attachPrimaryWithCoord(primary: Nullable<Partial<ISelectionCell>>): Nullable<ISelectionCellWithMergeInfo>;
+ attachPrimaryWithCoord(primary: Nullable<Partial<ICellInfo>>): Nullable<ICellWithCoord>;
+
+ /**
+ * @deprecated Please use `getCellWithCoordByOffset` instead.
+ */
+ getSelectionCellByPosition(x: number, y: number): ICellWithCoord;
- getSelectionCellByPosition(x: number, y: number): Nullable<ISelectionCellWithMergeInfo>; // drawing
+ getCellWithCoordByOffset(x: number, y: number): Nullable<ICellWithCoord>; // drawing
setSingleSelectionEnabled(enabled: boolean): void;
@@ -130,11 +132,11 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
protected _skeleton!: SpreadsheetSkeleton;
protected _scene!: Scene;
- // The type of selector determines the type of data range and the highlighting style of the title bar
- protected _isHeaderHighlight: boolean = true;
+ // The type of selector determines the type of data range and the highlighting style of the title bar, now it always true. In future, this could be configurable by user.
+ protected _highlightHeader: boolean = true;
- // If true, the selector will respond to the range of merged cells and automatically extend the selected range. If false, it will ignore the merged cells.
- protected _shouldDetectMergedCells: boolean = true;
+ // protected _shouldDetectMergedCells: boolean = true;
+ protected _rangeType: RANGE_TYPE = RANGE_TYPE.NORMAL;
// The style of the selection area, including dashed lines, color, thickness, autofill, other points for modifying the range of the selection area, title highlighting, and so on, can all be customized.
protected _selectionStyle!: ISelectionStyle;
@@ -150,15 +152,15 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
/**
* Mainly emit by pointerup (pointerup is handled in _onPointerdown)
*/
- protected readonly _selectionMoveEnd$ = new BehaviorSubject<ISelectionWithCoordAndStyle[]>([]);
+ protected readonly _selectionMoveEnd$ = new BehaviorSubject<ISelectionWithCoord[]>([]);
readonly selectionMoveEnd$ = this._selectionMoveEnd$.asObservable();
- protected readonly _selectionMoving$ = new Subject<ISelectionWithCoordAndStyle[]>();
+ protected readonly _selectionMoving$ = new Subject<ISelectionWithCoord[]>();
readonly selectionMoving$ = this._selectionMoving$.asObservable();
/**
* Mainly emit by pointerdown
*/
- protected readonly _selectionMoveStart$ = new Subject<ISelectionWithCoordAndStyle[]>();
+ protected readonly _selectionMoveStart$ = new Subject<ISelectionWithCoord[]>();
readonly selectionMoveStart$ = this._selectionMoveStart$.asObservable();
private _selectionMoving = false;
@@ -170,7 +172,7 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
readonly interceptor = new InterceptorManager({ RANGE_MOVE_PERMISSION_CHECK, RANGE_FILL_PERMISSION_CHECK });
- private _escapeShortcutDisposable: Nullable<IDisposable> = null;
+ protected _escapeShortcutDisposable: Nullable<IDisposable> = null;
constructor(
protected readonly _injector: Injector,
@@ -184,6 +186,13 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
this._initMoving();
}
+ /**
+ * If true, the selector will respond to the range of merged cells and automatically extend the selected range. If false, it will ignore the merged cells.
+ */
+ private get _shouldDetectMergedCells(): boolean {
+ return this._rangeType === RANGE_TYPE.NORMAL;
+ }
+
private _initMoving(): void {
this.disposeWithMe(this._selectionMoving$.subscribe(() => {
this._selectionMoving = true;
@@ -202,7 +211,7 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
* Reset this._selectionStyle to default normal selection style
*/
protected _resetSelectionStyle(): void {
- this._setSelectionStyle(getDefaultNormalSelectionStyle(this._themeService));
+ this._setSelectionStyle(genNormalSelectionStyle(this._themeService));
}
/** @deprecated This should not be provided by the selection render service. */
@@ -214,43 +223,29 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
this._singleSelectionEnabled = enabled;
}
- /**
- * Add a selection in spreadsheet, create a new SelectionControl and then update this control by range derives from selection.
- * @param {ISelectionWithCoordAndStyle} selection
- */
- protected _addSelectionControlBySelectionData(selection: ISelectionWithCoordAndStyle): void {
- const skeleton = this._skeleton;
- const style = selection.style ?? getDefaultNormalSelectionStyle(this._themeService);
- const scene = this._scene;
- if (!scene || !skeleton) {
- return;
- }
-
- const { rangeWithCoord, primaryWithCoord } = selection;
- const { rangeType } = rangeWithCoord;
- const control = this.newSelectionControl(scene, rangeType || RANGE_TYPE.NORMAL, skeleton);
-
- // TODO: memory leak? This extension seems never released.
- // eslint-disable-next-line no-new
- new SelectionShapeExtension(control, skeleton, scene, this._themeService, this._injector, {
- selectionMoveEnd: (): void => {
- this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
- },
- });
-
+ newSelectionControl(scene: Scene, skeleton: SpreadsheetSkeleton, selection: ISelectionWithStyle): SelectionControl {
+ const zIndex = this.getSelectionControls().length;
const { rowHeaderWidth, columnHeaderHeight } = skeleton;
- control.update(rangeWithCoord, rowHeaderWidth, columnHeaderHeight, style, primaryWithCoord);
- }
-
- newSelectionControl(scene: Scene, _rangeType: RANGE_TYPE, skeleton: SpreadsheetSkeleton): SelectionControl {
- const selectionControls = this.getSelectionControls();
- const zIndex = selectionControls.length;
- const { rowHeaderWidth, columnHeaderHeight } = skeleton;
- const control = new SelectionControl(scene, zIndex, this._themeService, this._isHeaderHighlight, {
+ const control = new SelectionControl(scene, zIndex, this._themeService, {
+ highlightHeader: this._highlightHeader,
rowHeaderWidth,
columnHeaderHeight,
});
this._selectionControls.push(control);
+ const selectionWithCoord = attachSelectionWithCoord(selection, skeleton);
+ control.updateRangeBySelectionWithCoord(selectionWithCoord);
+
+ control.setControlExtension({
+ skeleton,
+ scene,
+ themeService: this._themeService,
+ injector: this._injector,
+ selectionHooks: {
+ selectionMoveEnd: (): void => {
+ this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
+ },
+ },
+ });
return control;
}
@@ -258,33 +253,28 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
/**
* Update the corresponding selectionControl based on selectionsData.
* selectionData[i] syncs selectionControls[i]
- * @param selections
+ * @param selectionsWithCoord
*/
- updateControlForCurrentByRangeData(selections: ISelectionWithCoordAndStyle[]): void {
- const selectionControls = this.getSelectionControls();
- if (!selectionControls) {
- return;
- }
-
+ resetSelectionsByModelData(selectionsWithStyleList: readonly ISelectionWithStyle[]): void {
+ const allSelectionControls = this.getSelectionControls();
const skeleton = this._skeleton;
-
- if (skeleton == null) {
+ if (!allSelectionControls || !skeleton) {
return;
}
- // const { rowHeaderWidth, columnHeaderHeight } = skeleton;
-
- // TODO @lumixraku This is awful!
- // SelectionControls should create & remove base on selections.
- // If selections is more than selectionControls, create new selectionControl, if selections is less than selectionControls, remove the last one.
- for (let i = 0, len = selections.length; i < len; i++) {
- const { rangeWithCoord, primaryWithCoord } = selections[i];
-
- const control = selectionControls[i];
+ for (let i = 0, len = selectionsWithStyleList.length; i < len; i++) {
+ const selectionWithStyle = selectionsWithStyleList[i];
+ const selectionWithCoord = attachSelectionWithCoord(selectionWithStyle, this._skeleton);
+ const control = allSelectionControls[i];
if (control) {
- control.updateRange(rangeWithCoord, primaryWithCoord);
+ control.updateRangeBySelectionWithCoord(selectionWithCoord);
+ } else {
+ this.newSelectionControl(this._scene!, skeleton, selectionWithStyle);
}
- // control && control.update(rangeWithCoord, rowHeaderWidth, columnHeaderHeight, style, primaryWithCoord);
+ }
+ if (selectionsWithStyleList.length < allSelectionControls.length) {
+ const controlsToDestroy = allSelectionControls.splice(selectionsWithStyleList.length);
+ controlsToDestroy.forEach((control) => control.dispose());
}
}
@@ -312,9 +302,9 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
/**
* Generate selectionData from this._selectionControls.model .
- * @returns {ISelectionWithCoordAndStyle[]} {range, primary, style}[]
+ * @returns {ISelectionWithCoord[]} {range, primary, style}[]
*/
- getSelectionDataWithStyle(): ISelectionWithCoordAndStyle[] {
+ getSelectionDataWithStyle(): ISelectionWithCoord[] {
const selectionControls = this._selectionControls;
const [unitId, sheetId] = this._skeleton.getLocation();
return selectionControls.map((control) => {
@@ -325,11 +315,28 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
});
}
+ /**
+ * @TODO lumixraku DO NOT expose private props.
+ */
getSelectionControls(): SelectionControl[] {
return this._selectionControls;
}
- protected _clearSelectionControls(): void {
+ /**
+ * Add a selection in spreadsheet, create a new SelectionControl and then update this control by range derives from selection.
+ * @param {ISelectionWithCoord} selectionWithStyle
+ */
+ protected _addSelectionControlByModelData(selectionWithStyle: ISelectionWithStyle): SelectionControl {
+ const skeleton = this._skeleton;
+ const style = selectionWithStyle.style ?? genNormalSelectionStyle(this._themeService);
+ const scene = this._scene;
+
+ selectionWithStyle.style = style;
+ const control = this.newSelectionControl(scene, skeleton, selectionWithStyle);
+ return control;
+ }
+
+ protected _clearAllSelectionControls(): void {
const allSelectionControls = this._selectionControls;
for (const control of allSelectionControls) {
control.dispose();
@@ -386,7 +393,7 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
}
/**
- * get active selection control
+ * get active(actually last) selection control
* @returns T extends SelectionControl
*/
getActiveSelectionControl<T extends SelectionControl = SelectionControl>(): Nullable<T> {
@@ -406,158 +413,21 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
}
/**
- * Clear existed selections.
+ * Clear existed selections by workbookSelections.selectionMoveEnd$
*/
protected _reset(): void {
- this._clearSelectionControls();
+ this._clearAllSelectionControls();
this._downObserver?.unsubscribe();
this._downObserver = null;
}
- resetAndEndSelection(): void {
- this.endSelection();
- this._reset();
- }
+ // resetAndEndSelection(): void {
+ // this.endSelection();
+ // this._reset();
+ // }
// TODO: @wzhudev: refactor the method to make it more readable
- /**
- * Handle pointer down event, then trigger selectionMoveStart$.
- * @param evt
- * @param _zIndex
- * @param rangeType
- * @param viewport
- * @param scrollTimerType
- */
- // eslint-disable-next-line max-lines-per-function, complexity
- protected _onPointerDown(
- evt: IPointerEvent | IMouseEvent,
- _zIndex = 0,
- rangeType: RANGE_TYPE = RANGE_TYPE.NORMAL,
- viewport: Nullable<Viewport>,
- scrollTimerType: ScrollTimerType = ScrollTimerType.ALL
- ): void {
- this._shouldDetectMergedCells = rangeType === RANGE_TYPE.NORMAL;
-
- const skeleton = this._skeleton;
- const scene = this._scene;
- if (!scene || !skeleton) {
- return;
- }
-
- if (viewport) {
- this._activeViewport = viewport;
- }
-
- const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
- const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
- if (!viewportMain) return;
- const relativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
-
- let { x: viewportPosX, y: viewportPosY } = relativeCoords;
- this._startViewportPosX = viewportPosX;
- this._startViewportPosY = viewportPosY;
-
- const scrollXY = scene.getVpScrollXYInfoByPosToVp(relativeCoords);
- const { scaleX, scaleY } = scene.getAncestorScale();
- const cursorCellRangeInfo = this._getCellRangeByCursorPosition(viewportPosX, viewportPosY, scaleX, scaleY, scrollXY);
- if (!cursorCellRangeInfo) return;
-
- const { rangeWithCoord: cursorCellRange, primaryWithCoord: primaryCursorCellRange } = cursorCellRangeInfo;
- const cursorCellRangeWithRangeType: IRangeWithCoord = { ...cursorCellRange, rangeType };
- this._startRangeWhenPointerDown = { ...cursorCellRange, rangeType };
-
- let activeSelectionControl: Nullable<SelectionControl> = this.getActiveSelectionControl();
- const curControls = this.getSelectionControls();
- for (const control of curControls) {
- // right click
- if (evt.button === 2 && control.model.isInclude(cursorCellRangeWithRangeType)) {
- activeSelectionControl = control;
- return;
- }
- // Click to an existing selection
- if (control.model.isEqual(cursorCellRangeWithRangeType)) {
- activeSelectionControl = control;
- break;
- }
-
- // There can only be one highlighted cell, so clear the highlighted cell of the existing selection
- if (!evt.shiftKey) {
- control.clearHighlight();
- }
- }
-
- this._checkClearPreviousControls(evt);
-
- const currentCell = activeSelectionControl?.model.currentCell;
- const expandByShiftKey = evt.shiftKey && currentCell;
- const remainLastEnable = this._remainLastEnabled &&
- !evt.ctrlKey &&
- !evt.shiftKey &&
- !this._skipLastEnabled &&
- !this._singleSelectionEnabled;
-
- //#region update selection control
- if (expandByShiftKey && currentCell) {
- // Perform pointer down selection.
- this._performSelectionByTwoCells(
- currentCell,
- cursorCellRangeWithRangeType,
- skeleton,
- rangeType,
- activeSelectionControl! // Get updated in this method
- );
- } else if (remainLastEnable && activeSelectionControl) {
- // Supports the formula ref text selection feature,
- // under the condition of preserving all previous selections, it modifies the position of the latest selection.
- this._updateSelectionControlByRange(
- activeSelectionControl,
- cursorCellRangeWithRangeType,
- primaryCursorCellRange
- );
- } else {
- // Create new control as default
- activeSelectionControl = this.newSelectionControl(scene, rangeType, skeleton);
- this._updateSelectionControlByRange(
- activeSelectionControl,
- cursorCellRangeWithRangeType,
- primaryCursorCellRange
- );
- }
- //#endregion
-
- this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
-
- scene.disableObjectsEvent();
- this._clearUpdatingListeners();
- this._addEndingListeners();
-
- scene.getTransformer()?.clearSelectedObjects();
-
- scene.getEngine()?.setRemainCapture();
-
- if (rangeType === RANGE_TYPE.ROW || rangeType === RANGE_TYPE.COLUMN) {
- if (rangeType === RANGE_TYPE.ROW) {
- viewportPosX = 0;
- } else if (rangeType === RANGE_TYPE.COLUMN) {
- viewportPosY = 0;
- }
- // TODO @lumixraku. This is so bad! There should be a explicit way to update col&row range. But now depends on the side effect of _movingHandler.
- // call _movingHandler to update range, col selection, endRow should be last row of current sheet.
- this._movingHandler(viewportPosX, viewportPosY, activeSelectionControl, rangeType);
- }
-
- this._setupPointerMoveListener(viewportMain, activeSelectionControl!, rangeType, scrollTimerType, viewportPosX, viewportPosY);
-
- this._escapeShortcutDisposable = this._shortcutService.forceEscape();
- this._scenePointerUpSub = scene.onPointerUp$.subscribeEvent(() => {
- this._clearUpdatingListeners();
- this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
- this._escapeShortcutDisposable?.dispose();
- this._escapeShortcutDisposable = null;
- });
- }
-
/**
* Init pointer move listener in each pointer down, unbind in each pointer up.
* Both cell selections and row-column selections are supported by this method.
@@ -592,7 +462,7 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
this._scenePointerMoveSub = scene.onPointerMove$.subscribeEvent((moveEvt: IPointerEvent | IMouseEvent) => {
const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
- const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeToViewportCoord(Vector2.FromArray([moveOffsetX, moveOffsetY]));
+ const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getCoordRelativeToViewport(Vector2.FromArray([moveOffsetX, moveOffsetY]));
this._movingHandler(newMoveOffsetX, newMoveOffsetY, activeSelectionControl, rangeType);
@@ -740,30 +610,35 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
}
/** @deprecated Use the function `attachSelectionWithCoord` instead`. */
- attachSelectionWithCoord(selectionWithStyle: ISelectionWithStyle): ISelectionWithCoordAndStyle {
+ attachSelectionWithCoord(selectionWithStyle: ISelectionWithStyle): ISelectionWithCoord {
return attachSelectionWithCoord(selectionWithStyle, this._skeleton);
}
/** @deprecated Use the function `attachPrimaryWithCoord` instead`. */
- attachPrimaryWithCoord(primary: ISelectionCell): ISelectionCellWithMergeInfo {
- return attachPrimaryWithCoord(primary, this._skeleton) as unknown as ISelectionCellWithMergeInfo;
+ attachPrimaryWithCoord(primary: ICellInfo): ICellWithCoord {
+ return attachPrimaryWithCoord(this._skeleton, primary) as unknown as ICellWithCoord;
+ }
+
+ /**
+ * @deprecated Please use `getCellWithCoordByOffset` instead.
+ */
+ getSelectionCellByPosition(x: number, y: number): ICellWithCoord {
+ return this.getCellWithCoordByOffset(x, y);
}
- getSelectionCellByPosition(x: number, y: number) {
+ getCellWithCoordByOffset(x: number, y: number): ICellWithCoord {
const scene = this._scene;
const skeleton = this._skeleton;
const scrollXY = scene.getViewportScrollXY(scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN)!);
const { scaleX, scaleY } = scene.getAncestorScale();
- const { row, column } = skeleton.getCellPositionByOffset(x, y, scaleX, scaleY, scrollXY);
- const cell = skeleton.getCellByIndex(row, column) as Nullable<ISelectionCellWithMergeInfo>;
- return cell;
+ return skeleton.getCellWithCoordByOffset(x, y, scaleX, scaleY, scrollXY);
}
/**
* 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
*/
- // eslint-disable-next-line max-lines-per-function, complexity
+
protected _movingHandler(
offsetX: number,
offsetY: number,
@@ -787,7 +662,7 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
const targetViewport = this._getViewportByCell(currSelectionRange.endRow, currSelectionRange.endColumn) ?? viewportMain;
- const scrollXY = scene.getVpScrollXYInfoByPosToVp(
+ const scrollXY = scene.getScrollXYInfoByViewport(
Vector2.FromArray([this._startViewportPosX, this._startViewportPosY]),
targetViewport
);
@@ -802,73 +677,41 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
offsetY = Number.POSITIVE_INFINITY;
}
- const cursorCellRangeInfo = this._getCellRangeByCursorPosition(offsetX, offsetY, scaleX, scaleY, scrollXY);
- if (!cursorCellRangeInfo) {
+ const currCell = this._skeleton.getCellByOffset(offsetX, offsetY, scaleX, scaleY, scrollXY);
+ if (!currCell) {
return;
}
- const { rangeWithCoord: cursorCellRange } = cursorCellRangeInfo;
- const activeCellRange = this._startRangeWhenPointerDown;
-
let newSelectionRange: IRange = {
- startRow: Math.min(cursorCellRange.startRow, activeCellRange.startRow),
- startColumn: Math.min(cursorCellRange.startColumn, activeCellRange.startColumn),
- endRow: Math.max(cursorCellRange.endRow, activeCellRange.endRow),
- endColumn: Math.max(cursorCellRange.endColumn, activeCellRange.endColumn),
+ startRow: Math.min(currCell.startRow, this._startRangeWhenPointerDown.startRow),
+ startColumn: Math.min(currCell.startColumn, this._startRangeWhenPointerDown.startColumn),
+ endRow: Math.max(currCell.endRow, this._startRangeWhenPointerDown.endRow),
+ endColumn: Math.max(currCell.endColumn, this._startRangeWhenPointerDown.endColumn),
};
if (this._shouldDetectMergedCells) {
- newSelectionRange = skeleton.getSelectionMergeBounding(newSelectionRange.startRow, newSelectionRange.startColumn, newSelectionRange.endRow, newSelectionRange.endColumn);
- }
-
- if (!newSelectionRange) {
- return;
+ newSelectionRange = skeleton.expandRangeByMerge(newSelectionRange);
}
+ const newSelection: ISelectionWithStyle = { range: newSelectionRange, primary: undefined, style: null };
+ const newSelectionRangeWithCoord = attachSelectionWithCoord(newSelection, skeleton);
+ newSelectionRangeWithCoord.rangeWithCoord.unitId = unitId;
+ newSelectionRangeWithCoord.rangeWithCoord.sheetId = sheetId;
+ newSelectionRangeWithCoord.rangeWithCoord.rangeType = rangeType;
+ // const startCellXY = skeleton.getNoMergeCellPositionByIndex(newSelectionRange.startRow, newSelectionRange.startColumn);
+ // const endCellXY = skeleton.getNoMergeCellPositionByIndex(newSelectionRange.endRow, newSelectionRange.endColumn);
- const startCellXY = skeleton.getNoMergeCellPositionByIndex(newSelectionRange.startRow, newSelectionRange.startColumn);
- const endCellXY = skeleton.getNoMergeCellPositionByIndex(newSelectionRange.endRow, newSelectionRange.endColumn);
-
- const newSelectionRangeWithCoord: IRangeWithCoord = {
- startRow: newSelectionRange.startRow,
- startColumn: newSelectionRange.startColumn,
- endRow: newSelectionRange.endRow,
- endColumn: newSelectionRange.endColumn,
- unitId,
- sheetId,
- startY: startCellXY?.startY || 0,
- endY: endCellXY?.endY || 0,
- startX: startCellXY?.startX || 0,
- endX: endCellXY?.endX || 0,
- };
// Only notify when the selection changes
-
const rangeChanged =
currSelectionRange.startRow !== newSelectionRange.startRow ||
currSelectionRange.startColumn !== newSelectionRange.startColumn ||
currSelectionRange.endRow !== newSelectionRange.endRow ||
currSelectionRange.endColumn !== newSelectionRange.endColumn;
if (activeSelectionControl != null && rangeChanged) {
- this._updateSelectionControlByRange(activeSelectionControl, newSelectionRangeWithCoord);
+ activeSelectionControl.updateRangeBySelectionWithCoord(newSelectionRangeWithCoord);
this._selectionMoving$.next(this.getSelectionDataWithStyle());
}
}
- /**
- * Update the selection control by range.
- * @param control
- * @param newSelectionRange
- * @param highlight
- */
- protected _updateSelectionControlByRange(control: SelectionControl, newSelectionRange: IRangeWithCoord, highlight: Nullable<ISelectionCellWithMergeInfo>): void {
- // const skeleton = this._skeleton;
- // const { rowHeaderWidth, columnHeaderHeight } = skeleton;
-
- // prompt controller get activeControls and then control.updateStyle, there are multiple style datas!!! this._selectionStyle
- // control.update(newSelectionRange, rowHeaderWidth, columnHeaderHeight, null, !highlight ? null : highlight);
-
- control.updateRange(newSelectionRange, highlight);
- }
-
protected _clearUpdatingListeners(): void {
const scene = this._scene;
scene.enableObjectsEvent();
@@ -900,41 +743,57 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
this._cancelUpSubscription = mainScene.onPointerUp$.subscribeEvent(() => this._clearUpdatingListeners());
}
- protected _getCellRangeByCursorPosition(
+ /**
+ * Get visible selection range & coord by offset on viewport. Nearly same as skeleton.getCellWithCoordByOffset
+ * Returning selection is only one cell. primary and range are same cell.
+ *
+ * visible selection range means getCellWithCoordByOffset needs first matched row/col in rowHeightAccumulation & colWidthAccumulation.
+ * Original name: _getCellRangeByCursorPosition
+ *
+ * @param offsetX position X in viewport.
+ * @param offsetY
+ * @param scaleX
+ * @param scaleY
+ * @param scrollXY
+ * @returns {Nullable<ISelectionWithCoord>} selection range with coord.
+ */
+ protected _getSelectionWithCoordByOffset(
offsetX: number,
offsetY: number,
scaleX: number,
scaleY: number,
scrollXY: { x: number; y: number }
): Nullable<ISelectionWithCoord> {
+ const skeleton = this._skeleton;
+ if (skeleton == null) return null;
+
+ //#region normal selection
if (this._shouldDetectMergedCells) {
- const { row, column } = this._skeleton.getCellPositionByOffset(offsetX, offsetY, scaleX, scaleY, scrollXY, { visibleOnly: true });
- const primaryWithCoord = this._skeleton.getCellByIndex(row, column) as Nullable<ISelectionCellWithMergeInfo>;
+ const primaryWithCoord = skeleton?.getCellWithCoordByOffset(
+ offsetX,
+ offsetY,
+ scaleX,
+ scaleY,
+ scrollXY,
+ { firstMatch: true } // for visible
+ );
if (!primaryWithCoord) return;
- const rangeWithCoord = makeCellToSelection(primaryWithCoord);
+ const rangeWithCoord = convertCellToRange(primaryWithCoord);
return {
primaryWithCoord,
rangeWithCoord,
};
}
+ //#endregion
- const skeleton = this._skeleton;
-
- if (skeleton == null) {
- return;
- }
-
- const moveActualSelection = skeleton.getCellPositionByOffset(offsetX, offsetY, scaleX, scaleY, scrollXY);
-
- const { row, column } = moveActualSelection;
-
+ //@region other range type
+ const { row, column } = skeleton.getCellIndexByOffset(offsetX, offsetY, scaleX, scaleY, scrollXY);
const startCell = skeleton.getNoMergeCellPositionByIndex(row, column);
-
const { startX, startY, endX, endY } = startCell;
- const rangeWithCoord = {
+ const rangeWithCoord: IRangeWithCoord = {
startY,
endY,
startX,
@@ -945,26 +804,23 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
endColumn: column,
};
- const primaryWithCoord = {
+ const primaryWithCoord: Nullable<ICellWithCoord> = {
+ mergeInfo: rangeWithCoord,
actualRow: row,
actualColumn: column,
-
isMerged: false,
-
isMergedMainCell: false,
-
startY,
endY,
startX,
endX,
-
- mergeInfo: rangeWithCoord,
};
return {
primaryWithCoord,
rangeWithCoord,
};
+ //#endregion
}
protected _checkClearPreviousControls(evt: IPointerEvent | IMouseEvent): void {
@@ -976,18 +832,19 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
(!evt.ctrlKey && !evt.shiftKey && !this._remainLastEnabled) ||
(this._singleSelectionEnabled && !evt.shiftKey)
) {
- this._clearSelectionControls();
+ this._clearAllSelectionControls();
}
}
- private _performSelectionByTwoCells(
- currentCell: ISelectionCellWithMergeInfo,
+ protected _makeSelectionByTwoCells(
+ currentCell: ICellWithCoord,
startSelectionRange: IRangeWithCoord,
skeleton: SpreadsheetSkeleton,
rangeType: RANGE_TYPE,
activeControl: SelectionControl
): void {
const { actualRow, actualColumn, mergeInfo: actualMergeInfo } = currentCell;
+ this._startRangeWhenPointerDown = { ...currentCell.mergeInfo };
// Get the maximum range selected based on the two cells selected with Shift key.
const newStartRow = Math.min(actualRow, startSelectionRange.startRow, actualMergeInfo.startRow);
@@ -998,62 +855,47 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
/**
* Calculate whether there are merged cells within the range. If there are, recursively expand the selection again.
*/
- const bounding = skeleton.getMergeBounding(newStartRow, newStartColumn, newEndRow, newEndColumn);
-
- const startCell = skeleton.getNoMergeCellPositionByIndex(bounding.startRow, bounding.startColumn);
-
- const endCell = skeleton.getNoMergeCellPositionByIndex(bounding.endRow, bounding.endColumn);
-
- const newSelectionRange = {
- startColumn: bounding.startColumn,
- startRow: bounding.startRow,
- endColumn: bounding.endColumn,
- endRow: bounding.endRow,
-
- startY: startCell.startY,
- endY: endCell.endY,
- startX: startCell.startX,
- endX: endCell.endX,
-
- rangeType,
+ const range = skeleton.expandRangeByMerge({
+ startRow: newStartRow,
+ startColumn: newStartColumn,
+ endRow: newEndRow,
+ endColumn: newEndColumn,
+ });
+ const selectionWithStyle = {
+ range,
+ primary: null,
+ style: null,
};
+ const selectionWithCoord = attachSelectionWithCoord(selectionWithStyle, skeleton);
+ activeControl.updateRangeBySelectionWithCoord(selectionWithCoord);
+ // const startCell = skeleton.getNoMergeCellPositionByIndex(range.startRow, range.startColumn);
+ // const endCell = skeleton.getNoMergeCellPositionByIndex(range.endRow, range.endColumn);
+ // const newSelectionRange = {
+ // startColumn: range.startColumn,
+ // startRow: range.startRow,
+ // endColumn: range.endColumn,
+ // endRow: range.endRow,
+
+ // startY: startCell.startY,
+ // endY: endCell.endY,
+ // startX: startCell.startX,
+ // endX: endCell.endX,
+
+ // rangeType,
+ // };
/**
* When expanding the selection with the Shift key,
* the original highlighted cell should remain unchanged.
* If the highlighted cell is a merged cell, the selection needs to be expanded.
*/
- const activeCell = skeleton.getCellByIndex(actualRow, actualColumn);
-
- this._startRangeWhenPointerDown = {
- startColumn: activeCell.mergeInfo.startColumn,
- startRow: activeCell.mergeInfo.startRow,
- endColumn: activeCell.mergeInfo.endColumn,
- endRow: activeCell.mergeInfo.endRow,
- startY: activeCell.mergeInfo.startY || 0,
- endY: activeCell.mergeInfo.endY || 0,
- startX: activeCell.mergeInfo.startX || 0,
- endX: activeCell.mergeInfo.endX || 0,
- rangeType,
- };
- this._updateSelectionControlByRange(activeControl, newSelectionRange, currentCell);
- }
+ // const activeCell = skeleton.getCellWithCoordByIndex(actualRow, actualColumn);
- /**
- * Reset all this.selectionControls by selectionsData.
- * @param selectionsData
- */
- protected _refreshSelectionControl(selectionsData: readonly ISelectionWithStyle[]): void {
- const selections = selectionsData.map((selectionWithStyle) => {
- const selectionData = attachSelectionWithCoord(selectionWithStyle, this._skeleton);
- selectionData.style = getDefaultNormalSelectionStyle(this._themeService);
- return selectionData;
- });
- this.updateControlForCurrentByRangeData(selections);
+ // activeControl.updateRange(newSelectionRange, currentCell);
}
}
-export function getAllSelection(skeleton: SpreadsheetSkeleton): ISelectionWithStyle {
+export function selectionDataForSelectAll(skeleton: SpreadsheetSkeleton): ISelectionWithStyle {
return {
range: {
startRow: 0,
@@ -1062,32 +904,48 @@ export function getAllSelection(skeleton: SpreadsheetSkeleton): ISelectionWithSt
endColumn: skeleton.getColumnCount() - 1,
rangeType: RANGE_TYPE.ALL,
},
- primary: getTopLeftSelection(skeleton)!.primary,
+ primary: getTopLeftSelectionOfCurrSheet(skeleton)!.primary,
style: null,
};
}
-export function getTopLeftSelection(skeleton: SpreadsheetSkeleton): Nullable<ISelectionWithStyle> {
- const mergeData = skeleton.mergeData;
- return (
- transformCellDataToSelectionData(0, 0, mergeData) || {
- range: {
- startRow: 0,
- startColumn: 0,
- endRow: 0,
- endColumn: 0,
- },
- primary: {
- actualRow: 0,
- actualColumn: 0,
- startRow: 0,
- startColumn: 0,
- endRow: 0,
- endColumn: 0,
- isMerged: false,
- isMergedMainCell: false,
- },
- style: null,
- }
- );
+export function getTopLeftSelectionOfCurrSheet(skeleton: SpreadsheetSkeleton): ISelectionWithStyle {
+ return genSelectionByRange(skeleton, {
+ startRow: 0,
+ startColumn: 0,
+ endRow: 0,
+ endColumn: 0,
+ });
+}
+
+/**
+ * @deprecated use `getTopLeftSelectionOfCurrSheet` instead
+ */
+const getTopLeftSelection = getTopLeftSelectionOfCurrSheet;
+export { getTopLeftSelection };
+
+export function genSelectionByRange(skeleton: SpreadsheetSkeleton, range: IRange): ISelectionWithStyle {
+ const topLeftCell = skeleton.worksheet.getCellInfoInMergeData(range.startRow, range.startColumn);
+ const bottomRightCell = skeleton.worksheet.getCellInfoInMergeData(range.endRow, range.endColumn);
+ const rs = {
+ range: {
+ startRow: topLeftCell.startRow,
+ startColumn: topLeftCell.startColumn,
+ endRow: bottomRightCell.endRow,
+ endColumn: bottomRightCell.endColumn,
+ rangeType: RANGE_TYPE.NORMAL,
+ },
+ primary: {
+ actualRow: topLeftCell.startRow,
+ actualColumn: topLeftCell.startColumn,
+ startRow: topLeftCell.startRow,
+ startColumn: topLeftCell.startColumn,
+ endRow: topLeftCell.endRow,
+ endColumn: topLeftCell.endColumn,
+ isMerged: topLeftCell.isMerged,
+ isMergedMainCell: topLeftCell.isMergedMainCell,
+ },
+ style: null,
+ };
+ return rs;
}
diff --git a/packages/sheets-ui/src/services/selection/const.ts b/packages/sheets-ui/src/services/selection/const.ts
index f87ee4a479..c181e6c02e 100644
--- a/packages/sheets-ui/src/services/selection/const.ts
+++ b/packages/sheets-ui/src/services/selection/const.ts
@@ -14,8 +14,10 @@
* limitations under the License.
*/
-import { createInterceptorKey } from '@univerjs/core';
+import type { ThemeService } from '@univerjs/core';
import type { Scene, SpreadsheetSkeleton } from '@univerjs/engine-render';
+import type { ISelectionStyle } from '@univerjs/sheets';
+import { ColorKit, createInterceptorKey } from '@univerjs/core';
export const RANGE_MOVE_PERMISSION_CHECK = createInterceptorKey<boolean, null>('rangeMovePermissionCheck');
export const RANGE_FILL_PERMISSION_CHECK = createInterceptorKey<boolean, { x: number; y: number; skeleton: SpreadsheetSkeleton; scene: Scene }>('rangeFillPermissionCheck');
@@ -24,3 +26,32 @@ export enum SELECTION_SHAPE_DEPTH {
FORMULA_EDITOR_SHOW = 100, // see packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
MARK_SELECTION = 10000,
};
+
+export function genNormalSelectionStyle(themeService: ThemeService): ISelectionStyle {
+ const styleSheet = themeService.getCurrentTheme();
+ const fill = new ColorKit(styleSheet.primaryColor).setAlpha(0.07).toRgbString();
+ return {
+ strokeWidth: 1,
+ stroke: styleSheet.primaryColor,
+ fill,
+ // widgets: { tl: true, tc: true, tr: true, ml: true, mr: true, bl: true, bc: true, br: true },
+ widgets: {},
+ widgetSize: 6,
+ widgetStrokeWidth: 1,
+ widgetStroke: styleSheet.colorWhite,
+
+ autofillSize: 6,
+ autofillStrokeWidth: 1,
+ autofillStroke: styleSheet.colorWhite,
+
+ rowHeaderFill: fill,
+ rowHeaderStroke: styleSheet.primaryColor,
+ rowHeaderStrokeWidth: 1,
+
+ columnHeaderFill: fill,
+ columnHeaderStroke: styleSheet.primaryColor,
+ columnHeaderStrokeWidth: 1,
+
+ expandCornerSize: 40,
+ };
+}
diff --git a/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts b/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts
index b277ff4bd3..6238681bdd 100644
--- a/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts
+++ b/packages/sheets-ui/src/services/selection/mobile-selection-render.service.ts
@@ -18,15 +18,15 @@
/* eslint-disable max-lines-per-function */
import type {
EventState,
+ ICellWithCoord,
IDisposable,
IRange,
IRangeWithCoord,
- ISelectionCellWithMergeInfo,
Nullable,
Workbook,
} from '@univerjs/core';
-import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule, Scene, Viewport } from '@univerjs/engine-render';
-import type { ISelectionWithCoordAndStyle, ISetSelectionsOperationParams, WorkbookSelections } from '@univerjs/sheets';
+import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule, Scene, SpreadsheetSkeleton, Viewport } from '@univerjs/engine-render';
+import type { ISelectionWithCoord, ISelectionWithStyle, ISetSelectionsOperationParams, WorkbookSelectionModel } from '@univerjs/sheets';
import type { ISheetObjectParam } from '../../controllers/utils/component-tools';
import {
ICommandService,
@@ -46,7 +46,7 @@ import { getCoordByOffset, getSheetObject } from '../../controllers/utils/compon
import { isThisColSelected, isThisRowSelected } from '../../controllers/utils/selections-tools';
import { SheetScrollManagerService } from '../scroll-manager.service';
import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
-import { BaseSelectionRenderService, getAllSelection, getTopLeftSelection } from './base-selection-render.service';
+import { BaseSelectionRenderService, getTopLeftSelectionOfCurrSheet, selectionDataForSelectAll } from './base-selection-render.service';
import { MobileSelectionControl } from './mobile-selection-shape';
import { attachSelectionWithCoord } from './util';
@@ -59,7 +59,7 @@ enum ExpandingControl {
BOTTOM = 'bottom',
}
export class MobileSheetsSelectionRenderService extends BaseSelectionRenderService implements IRenderModule {
- private readonly _workbookSelections: WorkbookSelections;
+ private readonly _workbookSelections: WorkbookSelectionModel;
private _renderDisposable: Nullable<IDisposable> = null;
_expandingSelection: boolean = false;
@@ -120,7 +120,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
this._commandService.syncExecuteCommand(SetSelectionsOperation.id, {
unitId,
subUnitId: sheetId,
- selections: [getTopLeftSelection(skeleton)],
+ selections: [getTopLeftSelectionOfCurrSheet(skeleton)],
} as ISetSelectionsOperationParams);
}
}));
@@ -128,13 +128,13 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
private _initSelectionChangeListener() {
// When selection completes, we need to update the selections' rendering and clear event handlers.
- this.disposeWithMe(this._workbookSelections.selectionMoveEnd$.subscribe((params) => {
- this._reset();
- for (const selectionWithStyle of params) {
- const selectionData = attachSelectionWithCoord(selectionWithStyle, this._skeleton);
- this._addSelectionControlBySelectionData(selectionData);
- }
- }));
+ // only ref selection need this. now mobile only has normal selection.
+ // this.disposeWithMe(this._workbookSelections.selectionMoveEnd$.subscribe((ISelectionWithStyleList) => {
+ // this._reset();
+ // for (const selectionWithStyle of ISelectionWithStyleList) {
+ // this._addSelectionControlByModelData(selectionWithStyle);
+ // }
+ // }));
}
private _initEventListeners(sheetObject: ISheetObjectParam): void {
@@ -178,9 +178,8 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
this._reset(); // remove all other selections
const skeleton = this._sheetSkeletonManagerService.getCurrent()!.skeleton;
- const selectionWithStyle = getAllSelection(skeleton);
- const selectionData = attachSelectionWithCoord(selectionWithStyle, skeleton);
- this._addSelectionControlBySelectionData(selectionData);
+ const selectionWithStyle = selectionDataForSelectAll(skeleton);
+ this._addSelectionControlByModelData(selectionWithStyle);
// pointerup --> create selection
this.refreshSelectionMoveStart();
@@ -267,7 +266,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
}));
}
- private _updateSelections(selectionDataWithStyleList: ISelectionWithCoordAndStyle[], type: SelectionMoveType) {
+ private _updateSelections(selectionDataWithStyleList: ISelectionWithCoord[], type: SelectionMoveType) {
const workbook = this._context.unit;
const unitId = workbook.getUnitId();
const sheetId = workbook.getActiveSheet().getSheetId();
@@ -287,9 +286,9 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
}
/**
- * invoked when pointerup or longpress on spreadsheet, or pointerdown on row&col
+ * invoked when pointerup or long press on spreadsheet, or pointerdown on row&col
* then move curr selection to cell at cursor
- * Main perpose to create a new selection, or update curr selection to a new range.
+ * Main purpose to create a new selection, or update curr selection to a new range.
* @param evt
* @param _zIndex
* @param rangeType
@@ -301,7 +300,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
rangeType: RANGE_TYPE = RANGE_TYPE.NORMAL,
viewport?: Viewport
) {
- this._shouldDetectMergedCells = rangeType === RANGE_TYPE.NORMAL;
+ this._rangeType = rangeType;
const skeleton = this._skeleton;
const scene = this._scene;
@@ -314,72 +313,63 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
}
const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
- const relativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+ const relativeCoords = scene.getCoordRelativeToViewport(Vector2.FromArray([evtOffsetX, evtOffsetY]));
- let { x: viewportPosX, y: viewportPosY } = relativeCoords;
- // this._startViewportPosX = viewportPosX;
- // this._startViewportPosY = viewportPosY;
- const scrollXY = scene.getVpScrollXYInfoByPosToVp(relativeCoords);
+ const { x: offsetX, y: offsetY } = relativeCoords;
+ this._startViewportPosX = offsetX;
+ this._startViewportPosY = offsetY;
+ const scrollXY = scene.getScrollXYInfoByViewport(relativeCoords);
const { scaleX, scaleY } = scene.getAncestorScale();
- const cursorCellRangeInfo = this._getCellRangeByCursorPosition(viewportPosX, viewportPosY, scaleX, scaleY, scrollXY);
- if (!cursorCellRangeInfo) return false;
-
- const { rangeWithCoord: cursorCellRange, primaryWithCoord: primaryCursorCellRange } = cursorCellRangeInfo;
- const cursorCellRangeWithRangeType = { ...cursorCellRange, rangeType };
- this._startRangeWhenPointerDown = { ...cursorCellRange, rangeType };
+ // const selectionCellWithCoord: Nullable<ISelectionWithCoord> = this._getSelectionWithCoordByOffset(viewportPosX, viewportPosY, scaleX, scaleY, scrollXY);
+ // if (!selectionCellWithCoord) return;
+ // const { rangeWithCoord: cursorCellRange, primaryWithCoord: primaryCursorCellRange } = cursorCellRangeInfo;
+ const selectCell = this._skeleton.getCellByOffset(offsetX, offsetY, scaleX, scaleY, scrollXY);
+ if (!selectCell) return;
+ switch (rangeType) {
+ case RANGE_TYPE.NORMAL:
+ break;
+ case RANGE_TYPE.ROW:
+ selectCell.startColumn = 0;
+ selectCell.endColumn = this._skeleton.getColumnCount() - 1;
+ break;
+ case RANGE_TYPE.COLUMN:
+ selectCell.startRow = 0;
+ selectCell.endRow = this._skeleton.getRowCount() - 1;
+ break;
+ case RANGE_TYPE.ALL:
+ selectCell.startRow = 0;
+ selectCell.startColumn = 0;
+ selectCell.endRow = this._skeleton.getRowCount() - 1;
+ selectCell.endColumn = this._skeleton.getColumnCount() - 1;
+ }
+ const selectionWithStyle: ISelectionWithStyle = { range: selectCell, primary: selectCell, style: null };
+ selectionWithStyle.range.rangeType = rangeType;
+ const selectionCellWithCoord = attachSelectionWithCoord(selectionWithStyle, this._skeleton);
+ this._startRangeWhenPointerDown = { ...selectionCellWithCoord.rangeWithCoord };
let activeSelectionControl = this.getActiveSelectionControl<MobileSelectionControl>();
+ const cursorRangeWidthCoord: IRangeWithCoord = { ...selectionCellWithCoord.rangeWithCoord };
for (const control of this.getSelectionControls()) {
- // in curr selection
- // if (control.model.isInclude(cursorCellRangeWithRangeType)) {
- // activeSelectionControl = control;
- // return;
- // }
// Click to an existing selection
- if (control.model.isEqual(cursorCellRangeWithRangeType)) {
+ if (control.model.isEqual(cursorRangeWidthCoord)) {
activeSelectionControl = control;
break;
}
-
- // There can only be one highlighted cell, so clear the highlighted cell of the existing selection
- // if (!expandingMode) {
- // control.clearHighlight();
- // }
}
- // In addition to pressing the ctrl or shift key, we must clear the previous selection
- // this._checkClearPreviousControls(evt);
-
// TODO merge to _checkClearPreviousControls
if (activeSelectionControl?.model.rangeType !== rangeType) {
- this._clearSelectionControls();
- activeSelectionControl = this.newSelectionControl(scene, rangeType);
+ this._clearAllSelectionControls();
+ activeSelectionControl = this.newSelectionControl(scene, skeleton, selectionWithStyle);
+ } else {
+ activeSelectionControl.updateRangeBySelectionWithCoord(selectionCellWithCoord);
}
- this._updateSelectionControlByRange(
- activeSelectionControl,
- cursorCellRangeWithRangeType,
- primaryCursorCellRange
- );
-
this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
this._clearUpdatingListeners();
// this._addEndingListeners();
this._expandingSelection = false;
-
- // this function call is exist in prev version
- if (rangeType === RANGE_TYPE.ROW || rangeType === RANGE_TYPE.COLUMN) {
- if (rangeType === RANGE_TYPE.ROW) {
- viewportPosX = 0;
- } else if (rangeType === RANGE_TYPE.COLUMN) {
- viewportPosY = 0;
- }
-
- // _moving would update activeSelectionControl range when row & col
- // this update logic should split from _moving!!!
- this._movingHandler(viewportPosX, viewportPosY, activeSelectionControl, rangeType);
- }
}
/**
@@ -388,10 +378,18 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
* @param scene
* @param rangeType
*/
- override newSelectionControl(scene: Scene, rangeType: RANGE_TYPE): MobileSelectionControl {
+ override newSelectionControl(scene: Scene, skeleton: SpreadsheetSkeleton, selection: ISelectionWithStyle): MobileSelectionControl {
const selectionControls = this.getSelectionControls();
-
- const control = new MobileSelectionControl(scene, selectionControls.length, this._isHeaderHighlight, this._themeService, rangeType);
+ const { rowHeaderWidth, columnHeaderHeight } = skeleton;
+ const rangeType = selection.range.rangeType;
+ const control = new MobileSelectionControl(scene, selectionControls.length, this._themeService, {
+ highlightHeader: this._highlightHeader,
+ rowHeaderWidth,
+ columnHeaderHeight,
+ rangeType,
+ });
+ const selectionWithCoord = attachSelectionWithCoord(selection, skeleton);
+ control.updateRangeBySelectionWithCoord(selectionWithCoord);
this._selectionControls.push(control);
const { expandingModeForTopLeft, expandingModeForBottomRight } = (() => {
@@ -507,7 +505,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
scene.getTransformer()?.clearSelectedObjects();
// #region pointermove
- const relativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([evt.offsetX, evt.offsetY]));
+ const relativeCoords = scene.getCoordRelativeToViewport(Vector2.FromArray([evt.offsetX, evt.offsetY]));
this._setupPointerMoveListener(viewportMain, activeSelectionControl!, rangeType, scrollTimerType, relativeCoords.x, relativeCoords.y);
// #endregion
@@ -526,55 +524,55 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
// #endregion
}
- private _changeCurrCellWhenControlPointerDown(): ISelectionCellWithMergeInfo {
+ private _changeCurrCellWhenControlPointerDown(): ICellWithCoord {
const activeSelectionControl = this.getActiveSelectionControl<MobileSelectionControl>()!;
const skeleton = this._skeleton;
- let currCellRange: ISelectionCellWithMergeInfo;
+ let currCellRange: ICellWithCoord;
const { startRow, startColumn, endRow, endColumn } = activeSelectionControl.model;
switch (this.expandingControlMode) {
case ExpandingControl.TOP_LEFT:
- currCellRange = skeleton.getCellByIndex(endRow, endColumn);
+ currCellRange = skeleton.getCellWithCoordByIndex(endRow, endColumn);
break;
case ExpandingControl.BOTTOM_RIGHT:
currCellRange =
- skeleton.getCellByIndex(startRow, startColumn);
+ skeleton.getCellWithCoordByIndex(startRow, startColumn);
break;
case ExpandingControl.LEFT:
currCellRange =
- skeleton.getCellByIndex(startRow, endColumn);
+ skeleton.getCellWithCoordByIndex(startRow, endColumn);
currCellRange.isMerged = false;
currCellRange.isMergedMainCell = false;
break;
case ExpandingControl.RIGHT:
currCellRange =
- skeleton.getCellByIndex(startRow, startColumn);
+ skeleton.getCellWithCoordByIndex(startRow, startColumn);
currCellRange.isMerged = false;
currCellRange.isMergedMainCell = false;
break;
case ExpandingControl.TOP:
currCellRange =
- skeleton.getCellByIndex(endRow, startColumn);
+ skeleton.getCellWithCoordByIndex(endRow, startColumn);
currCellRange.isMerged = false;
currCellRange.isMergedMainCell = false;
break;
case ExpandingControl.BOTTOM:
currCellRange =
- skeleton.getCellByIndex(startRow, startColumn);
+ skeleton.getCellWithCoordByIndex(startRow, startColumn);
currCellRange.isMerged = false;
currCellRange.isMergedMainCell = false;
break;
default:
currCellRange =
- skeleton.getCellByIndex(startRow, startColumn);
+ skeleton.getCellWithCoordByIndex(startRow, startColumn);
}
activeSelectionControl.updateCurrCell(currCellRange);
return currCellRange;
}
/**
- * Not same as _moving in base selection render service
+ * Not same as _moving in PC (base selection render service)
* The diff is
* In base version, new selection is determined by the cursor cell and _startRangeWhenPointerDown
*
@@ -586,7 +584,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
activeSelectionControl: MobileSelectionControl,
rangeType: RANGE_TYPE
) {
- this._shouldDetectMergedCells = rangeType === RANGE_TYPE.NORMAL;
+ this._rangeType = rangeType;
const skeleton = this._skeleton;
const scene = this._scene;
@@ -601,7 +599,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
const targetViewport = this._getViewportByCell(currSelectionRange.endRow, currSelectionRange.endColumn) ?? viewportMain;
- const scrollXY = scene.getVpScrollXYInfoByPosToVp(
+ const scrollXY = scene.getScrollXYInfoByViewport(
Vector2.FromArray([this._startViewportPosX, this._startViewportPosY]),
targetViewport
);
@@ -618,7 +616,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
offsetY = Number.POSITIVE_INFINITY;
}
- const cursorCellRangeInfo = this._getCellRangeByCursorPosition(offsetX, offsetY, scaleX, scaleY, scrollXY);
+ const cursorCellRangeInfo = this._getSelectionWithCoordByOffset(offsetX, offsetY, scaleX, scaleY, scrollXY);
if (!cursorCellRangeInfo) {
return false;
}
@@ -639,7 +637,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
};
if (rangeType === RANGE_TYPE.NORMAL) {
- newSelectionRange = skeleton.getSelectionMergeBounding(newSelectionRange.startRow, newSelectionRange.startColumn, newSelectionRange.endRow, newSelectionRange.endColumn);
+ newSelectionRange = skeleton.expandRangeByMerge(newSelectionRange);
} else if (rangeType === RANGE_TYPE.COLUMN) {
newSelectionRange = {
startRow: Math.min(cursorCellRange.startRow, currCellRange?.actualRow ?? -1),
@@ -661,20 +659,24 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
if (!newSelectionRange) {
return false;
}
-
- const startCellXY = skeleton.getNoMergeCellPositionByIndex(newSelectionRange.startRow, newSelectionRange.startColumn);
- const endCellXY = skeleton.getNoMergeCellPositionByIndex(newSelectionRange.endRow, newSelectionRange.endColumn);
-
- const newSelectionRangeWithCoord: IRangeWithCoord = {
- startColumn: newSelectionRange.startColumn,
- startRow: newSelectionRange.startRow,
- endColumn: newSelectionRange.endColumn,
- endRow: newSelectionRange.endRow,
- startY: startCellXY?.startY || 0,
- endY: endCellXY?.endY || 0,
- startX: startCellXY?.startX || 0,
- endX: endCellXY?.endX || 0,
- };
+ const newSelection: ISelectionWithStyle = { range: newSelectionRange, style: null, primary: null };
+ const newSelectionRangeWithCoord = attachSelectionWithCoord(newSelection, skeleton);
+ // newSelectionRangeWithCoord.rangeWithCoord.unitId = unitId;
+ // newSelectionRangeWithCoord.rangeWithCoord.sheetId = sheetId;
+
+ // const startCellXY = skeleton.getNoMergeCellPositionByIndex(newSelectionRange.startRow, newSelectionRange.startColumn);
+ // const endCellXY = skeleton.getNoMergeCellPositionByIndex(newSelectionRange.endRow, newSelectionRange.endColumn);
+
+ // const newSelectionRangeWithCoord: IRangeWithCoord = {
+ // startColumn: newSelectionRange.startColumn,
+ // startRow: newSelectionRange.startRow,
+ // endColumn: newSelectionRange.endColumn,
+ // endRow: newSelectionRange.endRow,
+ // startY: startCellXY?.startY || 0,
+ // endY: endCellXY?.endY || 0,
+ // startX: startCellXY?.startX || 0,
+ // endX: endCellXY?.endX || 0,
+ // };
const rangeChanged =
currSelectionRange.startRow !== newSelectionRange.startRow ||
@@ -683,7 +685,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
currSelectionRange.endColumn !== newSelectionRange.endColumn;
if (rangeChanged) {
if (activeSelectionControl) {
- this._updateSelectionControlByRange(activeSelectionControl, newSelectionRangeWithCoord);
+ activeSelectionControl.updateRangeBySelectionWithCoord(newSelectionRangeWithCoord);
this._selectionMoving$.next(this.getSelectionDataWithStyle());
}
}
diff --git a/packages/sheets-ui/src/services/selection/mobile-selection-shape.ts b/packages/sheets-ui/src/services/selection/mobile-selection-shape.ts
index 27516e0913..cfb85b4701 100644
--- a/packages/sheets-ui/src/services/selection/mobile-selection-shape.ts
+++ b/packages/sheets-ui/src/services/selection/mobile-selection-shape.ts
@@ -33,24 +33,32 @@ export class MobileSelectionControl extends SelectionControl {
*/
private _fillControlBottomRight: Rect | null;
+ protected _rangeType: RANGE_TYPE = RANGE_TYPE.NORMAL;
+
constructor(
protected override _scene: Scene,
protected override _zIndex: number,
- protected override _highlightHeader: boolean = true,
protected override readonly _themeService: ThemeService,
- protected _rangeType: RANGE_TYPE = RANGE_TYPE.NORMAL
+ options?: {
+ highlightHeader?: boolean;
+ enableAutoFill?: boolean;
+ rowHeaderWidth: number;
+ columnHeaderHeight: number;
+ rangeType?: RANGE_TYPE;
+ }
) {
- super(_scene, _zIndex, _themeService, _highlightHeader);
+ super(_scene, _zIndex, _themeService, options);
+ this._rangeType = options?.rangeType || RANGE_TYPE.NORMAL;
this.initControlPoints();
}
initControlPoints(): void {
- const defaultStyle = this.defaultStyle!;
+ const defaultStyle = this.currentStyle;
const expandCornerSize = defaultStyle.expandCornerSize || 0;
const expandCornerInnerSize = (defaultStyle.expandCornerSize || 0) / 4;
- const AutofillStrokeWidth = defaultStyle.AutofillStrokeWidth || 0;
+ const AutofillStrokeWidth = defaultStyle.autofillStrokeWidth || 0;
const stroke = defaultStyle.stroke!;
- const AutofillStroke = defaultStyle.AutofillStroke!;
+ const AutofillStroke = defaultStyle.autofillStroke!;
const zIndex = this.zIndex;
// @transformControlPoint takes care of left & top
this._fillControlTopLeft = new Rect(SELECTION_MANAGER_KEY.fillTopLeft + zIndex, {
@@ -132,25 +140,24 @@ export class MobileSelectionControl extends SelectionControl {
super.dispose();
}
- protected override _setSizeAndStyleForSelectionControl(style: ISelectionStyle): void {
- super._setSizeAndStyleForSelectionControl(style);
+ protected override _updateLayoutOfSelectionControl(style: ISelectionStyle): void {
+ super._updateLayoutOfSelectionControl(style);
// const rangeType = this.rangeType;
// startX startY shares same coordinate with viewport.(include row & colheader)
- const defaultStyle = this.defaultStyle;
+ const defaultStyle = this.currentStyle;
if (style == null) {
style = defaultStyle;
}
const {
widgets = defaultStyle.widgets!,
- hasAutoFill: autoFillEnabled = defaultStyle.hasAutoFill!,
} = style;
this.currentStyle = style;
// this condition is derived from selection-shape, I do not understand.
- if (autoFillEnabled === true && !super._hasWidgets(widgets)) {
+ if (this._enableAutoFill === true && !super._hasWidgets(widgets)) {
const { viewportScrollX, viewportScrollY } = this.getViewportMainScrollInfo();
const { endX, endY } = this.selectionModel;
this.transformControlPoint(viewportScrollX, viewportScrollY, endX, endY);
diff --git a/packages/sheets-ui/src/services/selection/selection-control.ts b/packages/sheets-ui/src/services/selection/selection-control.ts
index 17ad954e47..be2e5a7626 100644
--- a/packages/sheets-ui/src/services/selection/selection-control.ts
+++ b/packages/sheets-ui/src/services/selection/selection-control.ts
@@ -14,20 +14,22 @@
* limitations under the License.
*/
-import type { IRangeWithCoord, ISelectionCellWithMergeInfo, Nullable, ThemeService } from '@univerjs/core';
+import type { ICellWithCoord, IRangeWithCoord, Nullable, ThemeService } from '@univerjs/core';
import type { IObjectFullState, IRectProps, Scene } from '@univerjs/engine-render';
-import type { ISelectionStyle, ISelectionWidgetConfig, ISelectionWithCoordAndStyle } from '@univerjs/sheets';
+import type { ISelectionStyle, ISelectionWidgetConfig, ISelectionWithCoord } from '@univerjs/sheets';
+import type { ISelectionShapeExtensionOption } from './selection-shape-extension';
import { ColorKit, Disposable, RANGE_TYPE, toDisposable } from '@univerjs/core';
import { cancelRequestFrame, DashedRect, FIX_ONE_PIXEL_BLUR_OFFSET, Group, Rect, requestNewFrame, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';
import {
- getNormalSelectionStyle,
SELECTION_CONTROL_BORDER_BUFFER_COLOR,
SELECTION_CONTROL_BORDER_BUFFER_WIDTH,
} from '@univerjs/sheets';
-import { BehaviorSubject, Subject } from 'rxjs';
+import { BehaviorSubject, Subject } from 'rxjs';
import { SHEET_COMPONENT_HEADER_SELECTION_LAYER_INDEX, SHEET_COMPONENT_SELECTION_LAYER_INDEX } from '../../common/keys';
+import { genNormalSelectionStyle } from './const';
import { SelectionRenderModel } from './selection-render-model';
+import { SelectionShapeExtension } from './selection-shape-extension';
export enum SELECTION_MANAGER_KEY {
Selection = '__SpreadsheetSelectionShape__',
@@ -76,28 +78,42 @@ const SELECTION_TITLE_HIGHLIGHT_ALPHA = 0.3;
* The main selection canvas component, includes leftControl,rightControl,topControl,bottomControl,backgroundControlTop,backgroundControlMiddleLeft,backgroundControlMiddleRight,backgroundControlBottom,fillControl
*/
export class SelectionControl extends Disposable {
+ private _isHelperSelection: boolean = true;
+
+ /**
+ * For ref selections, there is no auto fill.
+ */
+ protected _enableAutoFill: boolean = true;
+ /**
+ * Only normal selections with primary cell has auto fill.
+ * This works for multiple normal selections. Only last selection has primary cell and auto fill.
+ */
+ private _showAutoFill: boolean = false;
+
+ /**
+ * If rowHeader & col Header would be highlighted with selection.
+ */
+ protected _highlightHeader: boolean = true;
+
+ protected _selectionRenderModel!: SelectionRenderModel;
+
private _leftBorder!: Rect;
private _rightBorder!: Rect;
private _topBorder!: Rect;
private _bottomBorder!: Rect;
-
private _backgroundControlTop!: Rect;
private _backgroundControlBottom!: Rect;
private _backgroundControlMiddleLeft!: Rect;
private _backgroundControlMiddleRight!: Rect;
-
- private _fillControl: Rect;
-
+ private _autoFillControl: Rect;
private _selectionShapeGroup!: Group;
-
private _rowHeaderBackground!: Rect;
private _rowHeaderBorder!: Rect;
private _rowHeaderGroup!: Group;
- // private _rowHeaderHighlight!: Rect;
private _columnHeaderBackground!: Rect;
private _columnHeaderBorder!: Rect;
private _columnHeaderGroup!: Group;
- // private _columnHeaderHighlight!: Rect;
+ private _dashedRect!: Rect;
// for ref selection
private _topLeftWidget!: Rect;
@@ -109,20 +125,17 @@ export class SelectionControl extends Disposable {
private _bottomCenterWidget!: Rect;
private _bottomRightWidget!: Rect;
- private _dashedRect!: Rect;
-
- protected _selectionModel!: SelectionRenderModel;
-
// why three style prop? what's diff between _selectionStyle & _currentStyle?
// protected _selectionStyle: Nullable<ISelectionStyle>;
private _defaultStyle!: ISelectionStyle;
private _currentStyle: ISelectionStyle;
-
protected _rowHeaderWidth: number = 0;
protected _columnHeaderHeight: number = 0;
protected _widgetRects: Rect[] = [];
+ protected _controlExtension: Nullable<SelectionShapeExtension>;
+
private _dispose$ = new BehaviorSubject<SelectionControl>(this);
readonly dispose$ = this._dispose$.asObservable();
@@ -137,25 +150,207 @@ export class SelectionControl extends Disposable {
readonly selectionFilling$ = new Subject<Nullable<IRangeWithCoord>>();
private readonly _selectionFilled$ = new Subject<Nullable<IRangeWithCoord>>();
-
readonly selectionFilled$ = this._selectionFilled$.asObservable();
- private _isHelperSelection: boolean = true;
-
constructor(
protected _scene: Scene,
protected _zIndex: number,
protected readonly _themeService: ThemeService,
- protected _highlightHeader: boolean = true,
options?: {
+ highlightHeader?: boolean;
+ enableAutoFill?: boolean;
rowHeaderWidth: number;
columnHeaderHeight: number;
+ rangeType?: RANGE_TYPE;
}
) {
super();
- this._rowHeaderWidth = (options?.rowHeaderWidth) || 0;
- this._columnHeaderHeight = (options?.columnHeaderHeight) || 0;
- this._initialize();
+ this._enableAutoFill = options?.enableAutoFill ?? true;
+ this._highlightHeader = options?.highlightHeader ?? true;
+ this._rowHeaderWidth = options?.rowHeaderWidth ?? 0;
+ this._columnHeaderHeight = options?.columnHeaderHeight ?? 0;
+ this._initializeSheetBody();
+ this._initialHeader();
+ }
+
+ // eslint-disable-next-line max-lines-per-function
+ private _initializeSheetBody(): void {
+ this._defaultStyle = genNormalSelectionStyle(this._themeService);
+ this._currentStyle = genNormalSelectionStyle(this._themeService);
+
+ this._selectionRenderModel = new SelectionRenderModel();
+ const zIndex = this._zIndex;
+ this._leftBorder = new Rect(SELECTION_MANAGER_KEY.left + zIndex, {
+ zIndex,
+ });
+
+ this._rightBorder = new Rect(SELECTION_MANAGER_KEY.right + zIndex, {
+ zIndex,
+ });
+
+ this._topBorder = new Rect(SELECTION_MANAGER_KEY.top + zIndex, {
+ zIndex,
+ });
+
+ this._bottomBorder = new Rect(SELECTION_MANAGER_KEY.bottom + zIndex, {
+ zIndex,
+ });
+
+ this._backgroundControlTop = new Rect(SELECTION_MANAGER_KEY.backgroundTop + zIndex, {
+ zIndex: zIndex - 1,
+ evented: false,
+ });
+
+ this._backgroundControlBottom = new Rect(SELECTION_MANAGER_KEY.backgroundBottom + zIndex, {
+ zIndex: zIndex - 1,
+ evented: false,
+ });
+
+ this._backgroundControlMiddleLeft = new Rect(SELECTION_MANAGER_KEY.backgroundMiddleLeft + zIndex, {
+ zIndex: zIndex - 1,
+ evented: false,
+ });
+ this._backgroundControlMiddleRight = new Rect(SELECTION_MANAGER_KEY.backgroundMiddleRight + zIndex, {
+ zIndex: zIndex - 1,
+ evented: false,
+ });
+
+ // size of fillControl is set in _updateControlStyleAndLayout(), because control size(visual size) stays same when zoom change.
+ // The size of control is not a const value, so it was handled by _updateWidgets() & _updateControlStyleAndLayout()
+ this._autoFillControl = new Rect(SELECTION_MANAGER_KEY.fill + zIndex, {
+ zIndex: zIndex + 1,
+ });
+ this._autoFillControl.hide();
+
+ // That weird, new Dashed rect should called when strokeDash. not every selectionControl need dashedRect.
+ // strokeDash === null || strokeDash === undefined ---> _dashRect.hide()
+ this._dashedRect = new DashedRect(SELECTION_MANAGER_KEY.dash + zIndex, {
+ zIndex: zIndex + 2,
+ evented: false,
+ stroke: '#fff',
+ });
+
+ const shapes = [
+ this._autoFillControl,
+ this._leftBorder, this._rightBorder, this._topBorder, this._bottomBorder,
+ this._backgroundControlTop, this._backgroundControlMiddleLeft,
+ this._backgroundControlMiddleRight, this._backgroundControlBottom,
+ this._dashedRect,
+ ];
+
+ this._widgetRects = this._initialWidget();
+ this._selectionShapeGroup = new Group(SELECTION_MANAGER_KEY.Selection + zIndex, ...shapes, ...this._widgetRects);
+ this._selectionShapeGroup.hide();
+ this._selectionShapeGroup.evented = false;
+ this._selectionShapeGroup.zIndex = zIndex;
+
+ const scene = this.getScene();
+ scene.addObject(this._selectionShapeGroup, SHEET_COMPONENT_SELECTION_LAYER_INDEX);
+
+ this.disposeWithMe(
+ toDisposable(
+ scene.onTransformChange$.subscribeEvent((state) => {
+ if (state.type !== TRANSFORM_CHANGE_OBSERVABLE_TYPE.scale) {
+ return;
+ }
+
+ this._updateLayoutOfSelectionControl(this._currentStyle);
+ this._updateControlCoord();
+ })
+ )
+ );
+ }
+
+ private _initialHeader(): void {
+ const zIndex = this._zIndex;
+ this._rowHeaderBackground = new Rect(SELECTION_MANAGER_KEY.rowHeaderBackground + zIndex, {
+ zIndex: zIndex - 1,
+ evented: false,
+ });
+
+ this._rowHeaderBorder = new Rect(SELECTION_MANAGER_KEY.rowHeaderBorder + zIndex, {
+ zIndex: zIndex - 1,
+ evented: false,
+ });
+
+ this._rowHeaderGroup = new Group(
+ SELECTION_MANAGER_KEY.rowHeaderGroup + zIndex,
+ this._rowHeaderBackground,
+ this._rowHeaderBorder
+ );
+
+ this._rowHeaderGroup.hide();
+ this._rowHeaderGroup.evented = false;
+ this._rowHeaderGroup.zIndex = zIndex;
+
+ this._columnHeaderBackground = new Rect(SELECTION_MANAGER_KEY.columnHeaderBackground + zIndex, {
+ zIndex: zIndex - 1,
+ evented: false,
+ });
+
+ this._columnHeaderBorder = new Rect(SELECTION_MANAGER_KEY.columnHeaderBorder + zIndex, {
+ zIndex: zIndex - 1,
+ evented: false,
+ });
+
+ this._columnHeaderGroup = new Group(
+ SELECTION_MANAGER_KEY.columnHeaderGroup + zIndex,
+ this._columnHeaderBackground,
+ this._columnHeaderBorder
+ );
+
+ this._columnHeaderGroup.hide();
+ this._columnHeaderGroup.evented = false;
+ this._columnHeaderGroup.zIndex = zIndex;
+
+ const scene = this.getScene();
+ scene.addObjects([this._rowHeaderGroup, this._columnHeaderGroup], SHEET_COMPONENT_HEADER_SELECTION_LAYER_INDEX);
+ }
+
+ private _initialWidget(): Rect[] {
+ const zIndex = this._zIndex;
+ this._topLeftWidget = new Rect(SELECTION_MANAGER_KEY.topLeftWidget + zIndex, {
+ zIndex: zIndex + 1,
+ });
+
+ this._topCenterWidget = new Rect(SELECTION_MANAGER_KEY.topCenterWidget + zIndex, {
+ zIndex: zIndex + 1,
+ });
+
+ this._topRightWidget = new Rect(SELECTION_MANAGER_KEY.topRightWidget + zIndex, {
+ zIndex: zIndex + 1,
+ });
+
+ this._middleLeftWidget = new Rect(SELECTION_MANAGER_KEY.middleLeftWidget + zIndex, {
+ zIndex: zIndex + 1,
+ });
+
+ this._middleRightWidget = new Rect(SELECTION_MANAGER_KEY.middleRightWidget + zIndex, {
+ zIndex: zIndex + 1,
+ });
+
+ this._bottomLeftWidget = new Rect(SELECTION_MANAGER_KEY.bottomLeftWidget + zIndex, {
+ zIndex: zIndex + 1,
+ });
+
+ this._bottomCenterWidget = new Rect(SELECTION_MANAGER_KEY.bottomCenterWidget + zIndex, {
+ zIndex: zIndex + 1,
+ });
+
+ this._bottomRightWidget = new Rect(SELECTION_MANAGER_KEY.bottomRightWidget + zIndex, {
+ zIndex: zIndex + 1,
+ });
+
+ return [
+ this._topLeftWidget,
+ this._topCenterWidget,
+ this._topRightWidget,
+ this._middleLeftWidget,
+ this._middleRightWidget,
+ this._bottomLeftWidget,
+ this._bottomCenterWidget,
+ this._bottomRightWidget,
+ ];
}
get zIndex(): number {
@@ -179,7 +374,7 @@ export class SelectionControl extends Disposable {
}
get fillControl(): Rect {
- return this._fillControl;
+ return this._autoFillControl;
}
get backgroundControlTop(): Rect {
@@ -214,8 +409,9 @@ export class SelectionControl extends Disposable {
return this._selectionShapeGroup;
}
+ // That's so bad! _selectionModel is protected! But I don't want to expose it to the outside world
get model(): SelectionRenderModel {
- return this._selectionModel;
+ return this._selectionRenderModel;
}
get topLeftWidget(): Rect {
@@ -255,33 +451,31 @@ export class SelectionControl extends Disposable {
}
get selectionModel(): SelectionRenderModel {
- return this._selectionModel;
+ return this._selectionRenderModel;
}
set selectionModel(model: SelectionRenderModel) {
- this._selectionModel = model;
+ this._selectionRenderModel = model;
}
- get defaultStyle(): ISelectionStyle {
- return this._defaultStyle;
- }
+ // get defaultStyle(): ISelectionStyle {
+ // return this._defaultStyle;
+ // }
- set defaultStyle(style: ISelectionStyle) {
- this._defaultStyle = style;
- }
+ // set defaultStyle(style: ISelectionStyle) {
+ // this._defaultStyle = style;
+ // }
- get dashedRect(): Rect {
- return this._dashedRect;
+ get currentStyle(): ISelectionStyle {
+ return this._currentStyle;
}
- get currentStyle(): Nullable<ISelectionStyle> {
- return this._currentStyle;
+ set currentStyle(style: ISelectionStyle) {
+ this._currentStyle = style;
}
- set currentStyle(style: Nullable<ISelectionStyle>) {
- if (style) {
- this._currentStyle = style;
- }
+ get dashedRect(): Rect {
+ return this._dashedRect;
}
get isHelperSelection(): boolean {
@@ -304,6 +498,10 @@ export class SelectionControl extends Disposable {
this._columnHeaderHeight = height;
}
+ setControlExtension(options: ISelectionShapeExtensionOption) {
+ this._controlExtension = new SelectionShapeExtension(this, options);
+ }
+
setEvent(state: boolean): void {
this.leftControl.evented = state;
this.rightControl.evented = state;
@@ -320,36 +518,33 @@ export class SelectionControl extends Disposable {
* @param selectionStyle
*/
// eslint-disable-next-line max-lines-per-function
- protected _setSizeAndStyleForSelectionControl(selectionStyle: ISelectionStyle): void {
- this.currentStyle = selectionStyle;
- const defaultStyle = this._defaultStyle;
- const currentStyle = this.currentStyle;
+ protected _updateLayoutOfSelectionControl(selectionStyle?: Nullable<Partial<ISelectionStyle>>): void {
+ if (selectionStyle) {
+ this.currentStyle = Object.assign({}, this._defaultStyle, selectionStyle);
+ }
+ const currentStyle = this.currentStyle as Required<ISelectionStyle>;
const {
- stroke = defaultStyle.stroke!,
- widgets = defaultStyle.widgets!,
- hasAutoFill = defaultStyle.hasAutoFill!,
- AutofillStroke = defaultStyle.AutofillStroke!,
+ stroke,
+ widgets,
+ autofillStroke: AutofillStroke,
strokeDash,
isAnimationDash,
} = currentStyle;
-
- let {
- strokeWidth = defaultStyle.strokeWidth!,
- AutofillSize = defaultStyle.AutofillSize!,
- AutofillStrokeWidth = defaultStyle.AutofillStrokeWidth!,
- } = currentStyle;
+ let autofillSize = currentStyle.autofillSize;
+ let strokeWidth = currentStyle.strokeWidth;
+ let autofillStrokeWidth = currentStyle.autofillStrokeWidth;
const scale = this._getScale();
const leftAdjustWidth = (strokeWidth + SELECTION_CONTROL_BORDER_BUFFER_WIDTH) / 2 / scale;
strokeWidth /= scale;
- AutofillSize /= scale;
- AutofillStrokeWidth /= scale < 1 ? 1 : scale;
+ autofillSize /= scale;
+ autofillStrokeWidth /= scale < 1 ? 1 : scale;
// const selectBorderOffsetFix = SELECTION_BORDER_OFFSET_FIX / scale;
const borderBuffer = SELECTION_CONTROL_BORDER_BUFFER_WIDTH / scale;
const fixOnePixelBlurOffset = FIX_ONE_PIXEL_BLUR_OFFSET / scale;
- // startX startY shares same coordinate with viewport.(include row & colheader)
- const { startX, startY, endX, endY } = this._selectionModel;
+ // startX startY shares same coordinate with viewport.(include row & col header)
+ const { startX, startY, endX, endY } = this._selectionRenderModel;
this.leftControl.transformByState({
height: endY - startY,
left: -leftAdjustWidth + fixOnePixelBlurOffset,
@@ -427,51 +622,69 @@ export class SelectionControl extends Disposable {
this.dashedRect.show();
}
-
- if (hasAutoFill === true && !this._hasWidgets(widgets)) {
+ this._showAutoFill = this._showAutoFill && this._enableAutoFill;
+ if (this._showAutoFill && !this._hasWidgets(widgets)) {
const fillProps: IRectProps = {
fill: stroke,
stroke: AutofillStroke,
strokeScaleEnabled: false,
};
const sizeState: IObjectFullState = {
- width: AutofillSize - AutofillStrokeWidth,
- height: AutofillSize - AutofillStrokeWidth,
- left: endX - startX - AutofillSize / 2 + AutofillStrokeWidth / 2 - fixOnePixelBlurOffset,
- top: endY - startY - AutofillSize / 2 + AutofillStrokeWidth / 2 - fixOnePixelBlurOffset,
- strokeWidth: AutofillStrokeWidth,
+ width: autofillSize - autofillStrokeWidth,
+ height: autofillSize - autofillStrokeWidth,
+ left: endX - startX - autofillSize / 2 + autofillStrokeWidth / 2 - fixOnePixelBlurOffset,
+ top: endY - startY - autofillSize / 2 + autofillStrokeWidth / 2 - fixOnePixelBlurOffset,
+ strokeWidth: autofillStrokeWidth,
};
- this.fillControl.setProps(fillProps);
- this.fillControl.transformByState(sizeState);
- this.fillControl.show();
+ this._autoFillControl.setProps(fillProps);
+ this._autoFillControl.transformByState(sizeState);
+ this._autoFillControl.show();
} else {
- this.fillControl.hide();
+ this._autoFillControl.hide();
}
- this._updateBackgroundControl(selectionStyle);
- this._updateHeaderBackground(selectionStyle);
- this._updateWidgets(selectionStyle);
+ this._updateBackgroundControl(currentStyle);
+ this._updateHeaderBackground(currentStyle);
+ this._updateWidgets(currentStyle);
}
/**
- * update selection control position by curr selection model
+ * update selection control coordination by curr selection model
*/
- protected _refreshControlPosition(): void {
- const { startX, startY } = this._selectionModel;
+ protected _updateControlCoord(): void {
+ const { startX, startY } = this._selectionRenderModel;
this.selectionShapeGroup.show();
this.selectionShapeGroup.translate(startX, startY);
this.selectionShapeGroup.makeDirtyNoDebounce(true);
}
- updateStyle(style: ISelectionStyle): void {
- this._setSizeAndStyleForSelectionControl(style);
- this._refreshControlPosition();
+ updateStyle(style: Partial<ISelectionStyle>): void {
+ this._updateLayoutOfSelectionControl(style);
+ this._updateControlCoord();
+ }
+
+ /**
+ * Update range, primary may be null, especially for moving handler.
+ * @param range
+ * @param primaryCell
+ */
+ updateRange(range: IRangeWithCoord, primaryCell: Nullable<ICellWithCoord>): void {
+ this._selectionRenderModel.setValue(range, primaryCell);
+ this._showAutoFill = primaryCell !== null;
+ this._updateLayoutOfSelectionControl();
+ this._updateControlCoord();
}
- updateRange(range: IRangeWithCoord, primaryCell: Nullable<ISelectionCellWithMergeInfo>): void {
- this._selectionModel.setValue(range, primaryCell);
- this._setSizeAndStyleForSelectionControl(this._currentStyle);
- this._refreshControlPosition();
+ updateRangeBySelectionWithCoord(selectionWthCoord: ISelectionWithCoord) {
+ this._selectionRenderModel.setValue(selectionWthCoord.rangeWithCoord, selectionWthCoord.primaryWithCoord);
+ // if undefined, then keeps the previous value
+ if (selectionWthCoord.primaryWithCoord === null) {
+ this._showAutoFill = false;
+ } else {
+ this._showAutoFill = true;
+ }
+ this._updateLayoutOfSelectionControl(selectionWthCoord.style);
+ this._updateControlCoord();
}
/**
@@ -488,27 +701,35 @@ export class SelectionControl extends Disposable {
rowHeaderWidth: number = 0,
columnHeaderHeight: number = 0,
style?: Nullable<ISelectionStyle>,
- primaryCell?: Nullable<ISelectionCellWithMergeInfo>
+ primaryCell?: Nullable<ICellWithCoord>
): void {
- this._selectionModel.setValue(newSelectionRange, primaryCell);
this._rowHeaderWidth = rowHeaderWidth;
this._columnHeaderHeight = columnHeaderHeight;
-
- this._setSizeAndStyleForSelectionControl(style || this._currentStyle);
- this._refreshControlPosition();
+ this.updateRangeBySelectionWithCoord({
+ rangeWithCoord: newSelectionRange,
+ primaryWithCoord: primaryCell,
+ style,
+ });
+ if (style) {
+ this.updateStyle(style);
+ }
}
/**
* update primary range
* @param primaryCell model.current (aka: highlight)
*/
- updateCurrCell(primaryCell?: Nullable<ISelectionCellWithMergeInfo>): void {
- this._selectionModel.setCurrentCell(primaryCell);
+ updateCurrCell(primaryCell: Nullable<ICellWithCoord>): void {
+ // in multiple selection shape, only shape with highlight has auto fill.
+ this._showAutoFill = primaryCell !== null;
+ this._selectionRenderModel.setCurrentCell(primaryCell);
}
clearHighlight(): void {
- this._selectionModel.clearCurrentCell();
- this._setSizeAndStyleForSelectionControl(this._currentStyle);
+ // in multiple selection shape, only shape with highlight has auto fill.
+ this._showAutoFill = false;
+ this._selectionRenderModel.clearCurrentCell();
+ this._updateLayoutOfSelectionControl(this._currentStyle);
}
getScene(): Scene {
@@ -525,7 +746,7 @@ export class SelectionControl extends Disposable {
this._backgroundControlMiddleLeft?.dispose();
this._backgroundControlMiddleRight?.dispose();
this._backgroundControlBottom?.dispose();
- this._fillControl.dispose();
+ this._autoFillControl.dispose();
this._selectionShapeGroup?.dispose();
this._rowHeaderBackground?.dispose();
@@ -545,6 +766,8 @@ export class SelectionControl extends Disposable {
this._bottomCenterWidget?.dispose();
this._bottomRightWidget?.dispose();
+ this._controlExtension?.dispose();
+
super.dispose();
this._dispose$.next(this);
@@ -591,15 +814,15 @@ export class SelectionControl extends Disposable {
}
}
- getValue(): ISelectionWithCoordAndStyle {
+ getValue(): ISelectionWithCoord {
return {
- ...this._selectionModel.getValue(),
+ ...this._selectionRenderModel.getValue(),
style: this._currentStyle,
};
}
getRange(): IRangeWithCoord {
- return this._selectionModel.getValue().rangeWithCoord;
+ return this._selectionRenderModel.getValue().rangeWithCoord;
}
enableHelperSelection(): void {
@@ -610,200 +833,14 @@ export class SelectionControl extends Disposable {
this._isHelperSelection = false;
}
- // eslint-disable-next-line max-lines-per-function
- private _initialize(): void {
- this._defaultStyle = getNormalSelectionStyle(this._themeService);
- this._currentStyle = getNormalSelectionStyle(this._themeService);
-
- this._selectionModel = new SelectionRenderModel();
- const zIndex = this._zIndex;
- this._leftBorder = new Rect(SELECTION_MANAGER_KEY.left + zIndex, {
- zIndex,
- });
-
- this._rightBorder = new Rect(SELECTION_MANAGER_KEY.right + zIndex, {
- zIndex,
- });
-
- this._topBorder = new Rect(SELECTION_MANAGER_KEY.top + zIndex, {
- zIndex,
- });
-
- this._bottomBorder = new Rect(SELECTION_MANAGER_KEY.bottom + zIndex, {
- zIndex,
- });
-
- this._backgroundControlTop = new Rect(SELECTION_MANAGER_KEY.backgroundTop + zIndex, {
- zIndex: zIndex - 1,
- evented: false,
- });
-
- this._backgroundControlBottom = new Rect(SELECTION_MANAGER_KEY.backgroundBottom + zIndex, {
- zIndex: zIndex - 1,
- evented: false,
- });
-
- this._backgroundControlMiddleLeft = new Rect(SELECTION_MANAGER_KEY.backgroundMiddleLeft + zIndex, {
- zIndex: zIndex - 1,
- evented: false,
- });
- this._backgroundControlMiddleRight = new Rect(SELECTION_MANAGER_KEY.backgroundMiddleRight + zIndex, {
- zIndex: zIndex - 1,
- evented: false,
- });
-
- // size of fillControl is set in _updateControlStyleAndLayout(), because control size(visual size) stays same when zoom change.
- // The size of control is not a const value, so it was handled by _updateWidgets() & _updateControlStyleAndLayout()
- this._fillControl = new Rect(SELECTION_MANAGER_KEY.fill + zIndex, {
- zIndex: zIndex + 1,
- });
-
- // That weird, new Dashedrect should called when strokeDash. not every selectionControl need dashedRect.
- // strokeDash === null || strokeDash === undefined ---> _dashRect.hide()
- this._dashedRect = new DashedRect(SELECTION_MANAGER_KEY.dash + zIndex, {
- zIndex: zIndex + 2,
- evented: false,
- stroke: '#fff',
- });
-
- const shapes = [
- this._fillControl,
- this._leftBorder, this._rightBorder, this._topBorder, this._bottomBorder,
- this._backgroundControlTop, this._backgroundControlMiddleLeft,
- this._backgroundControlMiddleRight, this._backgroundControlBottom,
- this._dashedRect,
- ];
-
- this._widgetRects = this._initialWidget();
- this._selectionShapeGroup = new Group(SELECTION_MANAGER_KEY.Selection + zIndex, ...shapes, ...this._widgetRects);
- this._selectionShapeGroup.hide();
- this._selectionShapeGroup.evented = false;
- this._selectionShapeGroup.zIndex = zIndex;
-
- const scene = this.getScene();
- scene.addObject(this._selectionShapeGroup, SHEET_COMPONENT_SELECTION_LAYER_INDEX);
-
- this.disposeWithMe(
- toDisposable(
- scene.onTransformChange$.subscribeEvent((state) => {
- if (state.type !== TRANSFORM_CHANGE_OBSERVABLE_TYPE.scale) {
- return;
- }
-
- this._setSizeAndStyleForSelectionControl(this._currentStyle);
- this._refreshControlPosition();
- })
- )
- );
-
- this._initialHeader();
- }
-
- private _initialHeader(): void {
- const zIndex = this._zIndex;
- this._rowHeaderBackground = new Rect(SELECTION_MANAGER_KEY.rowHeaderBackground + zIndex, {
- zIndex: zIndex - 1,
- evented: false,
- });
-
- this._rowHeaderBorder = new Rect(SELECTION_MANAGER_KEY.rowHeaderBorder + zIndex, {
- zIndex: zIndex - 1,
- evented: false,
- });
-
- this._rowHeaderGroup = new Group(
- SELECTION_MANAGER_KEY.rowHeaderGroup + zIndex,
- this._rowHeaderBackground,
- this._rowHeaderBorder
- );
-
- this._rowHeaderGroup.hide();
- this._rowHeaderGroup.evented = false;
- this._rowHeaderGroup.zIndex = zIndex;
-
- this._columnHeaderBackground = new Rect(SELECTION_MANAGER_KEY.columnHeaderBackground + zIndex, {
- zIndex: zIndex - 1,
- evented: false,
- });
-
- this._columnHeaderBorder = new Rect(SELECTION_MANAGER_KEY.columnHeaderBorder + zIndex, {
- zIndex: zIndex - 1,
- evented: false,
- });
-
- this._columnHeaderGroup = new Group(
- SELECTION_MANAGER_KEY.columnHeaderGroup + zIndex,
- this._columnHeaderBackground,
- this._columnHeaderBorder
- );
-
- this._columnHeaderGroup.hide();
- this._columnHeaderGroup.evented = false;
- this._columnHeaderGroup.zIndex = zIndex;
-
- const scene = this.getScene();
- scene.addObjects([this._rowHeaderGroup, this._columnHeaderGroup], SHEET_COMPONENT_HEADER_SELECTION_LAYER_INDEX);
- }
-
- private _initialWidget(): Rect[] {
- const zIndex = this._zIndex;
- this._topLeftWidget = new Rect(SELECTION_MANAGER_KEY.topLeftWidget + zIndex, {
- zIndex: zIndex + 1,
- });
-
- this._topCenterWidget = new Rect(SELECTION_MANAGER_KEY.topCenterWidget + zIndex, {
- zIndex: zIndex + 1,
- });
-
- this._topRightWidget = new Rect(SELECTION_MANAGER_KEY.topRightWidget + zIndex, {
- zIndex: zIndex + 1,
- });
-
- this._middleLeftWidget = new Rect(SELECTION_MANAGER_KEY.middleLeftWidget + zIndex, {
- zIndex: zIndex + 1,
- });
-
- this._middleRightWidget = new Rect(SELECTION_MANAGER_KEY.middleRightWidget + zIndex, {
- zIndex: zIndex + 1,
- });
-
- this._bottomLeftWidget = new Rect(SELECTION_MANAGER_KEY.bottomLeftWidget + zIndex, {
- zIndex: zIndex + 1,
- });
-
- this._bottomCenterWidget = new Rect(SELECTION_MANAGER_KEY.bottomCenterWidget + zIndex, {
- zIndex: zIndex + 1,
- });
-
- this._bottomRightWidget = new Rect(SELECTION_MANAGER_KEY.bottomRightWidget + zIndex, {
- zIndex: zIndex + 1,
- });
-
- return [
- this._topLeftWidget,
- this._topCenterWidget,
- this._topRightWidget,
- this._middleLeftWidget,
- this._middleRightWidget,
- this._bottomLeftWidget,
- this._bottomCenterWidget,
- this._bottomRightWidget,
- ];
- }
-
- private _updateHeaderBackground(style: Nullable<ISelectionStyle>): void {
- const { startX, startY, endX, endY, rangeType } = this._selectionModel;
- const defaultStyle = this._defaultStyle;
-
- if (style == null) {
- style = defaultStyle;
- }
-
+ private _updateHeaderBackground(style: ISelectionStyle): void {
+ const { startX, startY, endX, endY, rangeType } = this._selectionRenderModel;
+ const defaultStyle = this._currentStyle;
const scale = this._getScale();
const {
- stroke, hasRowHeader, rowHeaderFill = defaultStyle.rowHeaderFill!, rowHeaderStroke = defaultStyle.rowHeaderStroke!,
- hasColumnHeader, columnHeaderFill = defaultStyle.columnHeaderFill!, columnHeaderStroke = defaultStyle.columnHeaderStroke!,
+ stroke, rowHeaderFill = defaultStyle.rowHeaderFill!, rowHeaderStroke = defaultStyle.rowHeaderStroke!,
+ columnHeaderFill = defaultStyle.columnHeaderFill!, columnHeaderStroke = defaultStyle.columnHeaderStroke!,
} = style;
let {
@@ -817,9 +854,9 @@ export class SelectionControl extends Disposable {
const rowHeaderWidth = this._rowHeaderWidth;
const columnHeaderHeight = this._columnHeaderHeight;
- if (hasColumnHeader === true) {
+ if (this._highlightHeader && columnHeaderHeight > 0) {
let highlightTitleColor = columnHeaderFill;
- if (this._highlightHeader && rangeType === RANGE_TYPE.COLUMN) {
+ if (rangeType === RANGE_TYPE.COLUMN) {
highlightTitleColor = new ColorKit(stroke).setAlpha(SELECTION_TITLE_HIGHLIGHT_ALPHA).toString();
}
this._columnHeaderBackground.setProps({
@@ -844,9 +881,9 @@ export class SelectionControl extends Disposable {
this._columnHeaderGroup.makeDirty(true);
- if (hasRowHeader === true) {
+ if (this._highlightHeader && rowHeaderWidth > 0) {
let highlightTitleColor = rowHeaderFill;
- if (this._highlightHeader && rangeType === RANGE_TYPE.ROW) {
+ if (rangeType === RANGE_TYPE.ROW) {
highlightTitleColor = new ColorKit(stroke).setAlpha(SELECTION_TITLE_HIGHLIGHT_ALPHA).toString();
}
this._rowHeaderBackground.setProps({
@@ -872,20 +909,14 @@ export class SelectionControl extends Disposable {
this._rowHeaderGroup.makeDirty(true);
}
- private _updateBackgroundControl(style: Nullable<ISelectionStyle>): void {
- const { startX, startY, endX, endY } = this._selectionModel;
-
- const defaultStyle = this._defaultStyle;
-
- if (style == null) {
- style = defaultStyle;
- }
+ private _updateBackgroundControl(style: ISelectionStyle): void {
+ const { startX, startY, endX, endY } = this._selectionRenderModel;
const scale = this._getScale();
- const { fill = defaultStyle.fill! } = style;
- let { strokeWidth = defaultStyle.strokeWidth! } = style;
+ const { fill = style.fill! } = style;
+ let { strokeWidth } = style;
strokeWidth /= scale;
- const highlightSelection = this._selectionModel.highlightToSelection();
+ const highlightSelection = this._selectionRenderModel.highlightToSelection();
if (!highlightSelection) {
this._backgroundControlTop.resize(endX - startX, endY - startY);
@@ -953,17 +984,12 @@ export class SelectionControl extends Disposable {
this._backgroundControlBottom.setProps({ fill });
}
- private _updateWidgets(style: Nullable<ISelectionStyle>): void {
- const { startX, startY, endX, endY } = this._selectionModel;
- const defaultStyle = this._defaultStyle;
+ private _updateWidgets(style: Required<ISelectionStyle>): void {
+ const { startX, startY, endX, endY } = this._selectionRenderModel;
- if (style == null) {
- style = defaultStyle;
- }
-
- const { stroke = defaultStyle.stroke!, widgets = defaultStyle.widgets!, widgetStroke = defaultStyle.widgetStroke! } = style;
+ const { stroke = style.stroke!, widgets = style.widgets!, widgetStroke = style.widgetStroke! } = style;
const scale = this._getScale();
- let { widgetSize = defaultStyle.widgetSize!, widgetStrokeWidth = defaultStyle.widgetStrokeWidth! } = style;
+ let { widgetSize, widgetStrokeWidth } = style;
widgetSize /= scale;
widgetStrokeWidth /= scale;
@@ -1049,7 +1075,7 @@ export class SelectionControl extends Disposable {
}
}
- return true;
+ return false;
}
private _getScale(): number {
@@ -1058,7 +1084,6 @@ export class SelectionControl extends Disposable {
}
private _antLineOffset = 0;
-
private _antRequestNewFrame: number = -1;
private _stopAntLineAnimation(): void {
diff --git a/packages/sheets-ui/src/services/selection/selection-render-model.ts b/packages/sheets-ui/src/services/selection/selection-render-model.ts
index 9ec8c3cf7f..6fdbbd9d23 100644
--- a/packages/sheets-ui/src/services/selection/selection-render-model.ts
+++ b/packages/sheets-ui/src/services/selection/selection-render-model.ts
@@ -14,9 +14,14 @@
* limitations under the License.
*/
-import type { IRangeWithCoord, ISelectionCellWithMergeInfo, ISelectionWithCoord, Nullable } from '@univerjs/core';
-import { makeCellToSelection, RANGE_TYPE } from '@univerjs/core';
+import type { ICellWithCoord, IRangeWithCoord, Nullable } from '@univerjs/core';
+import type { ISelectionWithCoord } from '@univerjs/sheets';
+import { convertCellToRange, RANGE_TYPE } from '@univerjs/core';
+/**
+ * Data model for SelectionControl.model
+ * NOT Same as @univerjs/sheet.WorkbookSelectionModel, that's data model for Workbook
+ */
export class SelectionRenderModel implements IRangeWithCoord {
private _startColumn: number = -1;
private _startRow: number = -1;
@@ -30,9 +35,12 @@ export class SelectionRenderModel implements IRangeWithCoord {
/**
* The highlight cell of a selection. aka: current cell
*/
- private _primary: Nullable<ISelectionCellWithMergeInfo>;
+ private _primary: Nullable<ICellWithCoord>;
private _rangeType: RANGE_TYPE = RANGE_TYPE.NORMAL;
+ constructor() {
+ }
+
get startColumn() { return this._startColumn; }
get startRow() { return this._startRow; }
get endColumn() { return this._endColumn; }
@@ -88,9 +96,9 @@ export class SelectionRenderModel implements IRangeWithCoord {
return false;
}
- highlightToSelection() {
+ highlightToSelection(): Nullable<IRangeWithCoord> {
if (!this._primary) return;
- return makeCellToSelection(this._primary);
+ return convertCellToRange(this._primary);
}
getRange(): IRangeWithCoord {
@@ -126,7 +134,7 @@ export class SelectionRenderModel implements IRangeWithCoord {
};
}
- setValue(newSelectionRange: IRangeWithCoord, currentCell: Nullable<ISelectionCellWithMergeInfo>) {
+ setValue(newSelectionRange: IRangeWithCoord, currentCell: Nullable<ICellWithCoord>) {
const {
startColumn,
startRow,
@@ -152,16 +160,19 @@ export class SelectionRenderModel implements IRangeWithCoord {
if (rangeType !== undefined) {
this._rangeType = rangeType;
}
- this.setCurrentCell(currentCell);
+ if (currentCell !== undefined) {
+ this.setCurrentCell(currentCell);
+ }
}
/**
* Set primary cell.
*
- * TODO @lumixraku there are 3 concepts for same thing, primary and current and highlight, primary is better cuz selectionModel is using primary.
+ * @TODO lumixraku there are 3 concepts for same thing, primary and current and highlight
+ * highlight is best. primary sometimes means the actual cell(actual means ignore merge)
* @param currentCell
*/
- setCurrentCell(currentCell: Nullable<ISelectionCellWithMergeInfo>) {
+ setCurrentCell(currentCell: Nullable<ICellWithCoord>) {
if (currentCell) {
this._primary = currentCell;
}
diff --git a/packages/sheets-ui/src/services/selection/selection-render.service.ts b/packages/sheets-ui/src/services/selection/selection-render.service.ts
index 8958ce5e99..7299aa9711 100644
--- a/packages/sheets-ui/src/services/selection/selection-render.service.ts
+++ b/packages/sheets-ui/src/services/selection/selection-render.service.ts
@@ -14,20 +14,21 @@
* limitations under the License.
*/
-import type { IDisposable, Nullable, Workbook } from '@univerjs/core';
-import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule } from '@univerjs/engine-render';
-import type { ISelectionWithCoordAndStyle, ISetSelectionsOperationParams, WorkbookSelections } from '@univerjs/sheets';
+import type { IDisposable, IRangeWithCoord, Nullable, Workbook } from '@univerjs/core';
+import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule, Viewport } from '@univerjs/engine-render';
+import type { ISelectionWithCoord, ISelectionWithStyle, ISetSelectionsOperationParams, WorkbookSelectionModel } from '@univerjs/sheets';
import type { ISheetObjectParam } from '../../controllers/utils/component-tools';
+import type { SelectionControl } from './selection-control';
import { ICommandService, IContextService, ILogService, Inject, Injector, RANGE_TYPE, ThemeService, toDisposable } from '@univerjs/core';
import { ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
import { convertSelectionDataToRange, DISABLE_NORMAL_SELECTIONS, SelectionMoveType, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
import { IShortcutService } from '@univerjs/ui';
-import { distinctUntilChanged, merge, startWith } from 'rxjs';
+import { distinctUntilChanged, startWith } from 'rxjs';
import { getCoordByOffset, getSheetObject } from '../../controllers/utils/component-tools';
import { isThisColSelected, isThisRowSelected } from '../../controllers/utils/selections-tools';
import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
-import { BaseSelectionRenderService, getAllSelection, getTopLeftSelection } from './base-selection-render.service';
+import { BaseSelectionRenderService, getTopLeftSelectionOfCurrSheet, selectionDataForSelectAll } from './base-selection-render.service';
import { attachSelectionWithCoord } from './util';
/**
@@ -35,7 +36,7 @@ import { attachSelectionWithCoord } from './util';
* The normal selections would also be used by Auto Fill and Copy features.
*/
export class SheetSelectionRenderService extends BaseSelectionRenderService implements IRenderModule {
- private readonly _workbookSelections: WorkbookSelections;
+ private readonly _workbookSelections: WorkbookSelectionModel;
private _renderDisposable: Nullable<IDisposable> = null;
@@ -120,9 +121,8 @@ export class SheetSelectionRenderService extends BaseSelectionRenderService impl
this._reset(); // remove all other selections
const skeleton = this._sheetSkeletonManagerService.getCurrent()!.skeleton;
- const selectionWithStyle = getAllSelection(skeleton);
- const selectionData = attachSelectionWithCoord(selectionWithStyle, skeleton);
- this._addSelectionControlBySelectionData(selectionData);
+ const selectionWithStyle = selectionDataForSelectAll(skeleton);
+ this._addSelectionControlByModelData(selectionWithStyle);
this.refreshSelectionMoveEnd();
if (evt.button !== 2) {
@@ -136,8 +136,7 @@ export class SheetSelectionRenderService extends BaseSelectionRenderService impl
this._resetSelectionStyle();
const selections = this._workbookSelections.getCurrentSelections();
if (!selections) return;
-
- this._refreshSelectionControl(selections);
+ this.resetSelectionsByModelData(selections);
}));
}
@@ -146,14 +145,13 @@ export class SheetSelectionRenderService extends BaseSelectionRenderService impl
}
private _initSelectionChangeListener(): void {
- // When selection completes, we need to update the selections' rendering and clear event handlers.
- this.disposeWithMe(merge(this._workbookSelections.selectionMoveEnd$, this._workbookSelections.selectionSet$).subscribe((params) => {
- this._reset();
- for (const selectionWithStyle of params) {
- const selectionData = attachSelectionWithCoord(selectionWithStyle, this._skeleton);
- this._addSelectionControlBySelectionData(selectionData);
- }
- }));
+ // only ref selection need this,
+ // this.disposeWithMe(merge(this._workbookSelections.selectionMoveEnd$, this._workbookSelections.selectionSet$).subscribe((selectionWithStyleList) => {
+ // // this._reset();
+ // // for (const selectionWithStyle of selectionWithStyleList) {
+ // // this._addSelectionControlByModelData(selectionWithStyle);
+ // // }
+ // }));
}
private _initUserActionSyncListener(): void {
@@ -176,11 +174,11 @@ export class SheetSelectionRenderService extends BaseSelectionRenderService impl
}
/**
- * Update selectionData to current sheet.
+ * Update selectionData to selectionDataModel (WorkBookSelections) by SetSelectionsOperation.
* @param selectionDataWithStyleList
* @param type
*/
- private _updateSelections(selectionDataWithStyleList: ISelectionWithCoordAndStyle[], type: SelectionMoveType) {
+ private _updateSelections(selectionDataWithStyleList: ISelectionWithCoord[], type: SelectionMoveType) {
const workbook = this._context.unit;
const unitId = workbook.getUnitId();
const sheetId = workbook.getActiveSheet().getSheetId();
@@ -227,14 +225,14 @@ export class SheetSelectionRenderService extends BaseSelectionRenderService impl
this._commandService.syncExecuteCommand(SetSelectionsOperation.id, {
unitId,
subUnitId: sheetId,
- selections: selections.length !== 0 ? selections : [getTopLeftSelection(skeleton)],
+ selections: selections.length !== 0 ? selections : [getTopLeftSelectionOfCurrSheet(skeleton)],
} as ISetSelectionsOperationParams);
}
const currentSelections = this._workbookSelections.getCurrentSelections();
// for col width & row height resize
if (currentSelections != null) {
- this._refreshSelectionControl(currentSelections);
+ this.resetSelectionsByModelData(currentSelections);
}
}));
}
@@ -247,4 +245,147 @@ export class SheetSelectionRenderService extends BaseSelectionRenderService impl
private _getSheetObject() {
return getSheetObject(this._context.unit, this._context)!;
}
+
+ /**
+ * Handle pointer down event, bind pointermove & pointerup handler.
+ * then trigger selectionMoveStart$.
+ *
+ * @param evt
+ * @param _zIndex
+ * @param rangeType
+ * @param viewport
+ * @param scrollTimerType
+ */
+ // eslint-disable-next-line max-lines-per-function, complexity
+ protected _onPointerDown(
+ evt: IPointerEvent | IMouseEvent,
+ _zIndex = 0,
+ rangeType: RANGE_TYPE = RANGE_TYPE.NORMAL,
+ viewport: Nullable<Viewport>,
+ scrollTimerType: ScrollTimerType = ScrollTimerType.ALL
+ ): void {
+ this._rangeType = rangeType;
+
+ const skeleton = this._skeleton;
+ const scene = this._scene;
+ if (!scene || !skeleton) {
+ return;
+ }
+
+ if (viewport) {
+ this._activeViewport = viewport;
+ }
+
+ const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
+ const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
+ if (!viewportMain) return;
+ const relativeCoords = scene.getCoordRelativeToViewport(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+
+ const { x: offsetX, y: offsetY } = relativeCoords;
+ this._startViewportPosX = offsetX;
+ this._startViewportPosY = offsetY;
+
+ const scrollXY = scene.getScrollXYInfoByViewport(relativeCoords);
+ const { scaleX, scaleY } = scene.getAncestorScale();
+
+ const selectCell = this._skeleton.getCellByOffset(offsetX, offsetY, scaleX, scaleY, scrollXY);
+ if (!selectCell) return;
+ switch (rangeType) {
+ case RANGE_TYPE.NORMAL:
+ break;
+ case RANGE_TYPE.ROW:
+ selectCell.startColumn = 0;
+ selectCell.endColumn = this._skeleton.getColumnCount() - 1;
+ break;
+ case RANGE_TYPE.COLUMN:
+ selectCell.startRow = 0;
+ selectCell.endRow = this._skeleton.getRowCount() - 1;
+ break;
+ case RANGE_TYPE.ALL:
+ selectCell.startRow = 0;
+ selectCell.startColumn = 0;
+ selectCell.endRow = this._skeleton.getRowCount() - 1;
+ selectCell.endColumn = this._skeleton.getColumnCount() - 1;
+ }
+ const selectionWithStyle: ISelectionWithStyle = { range: selectCell, primary: selectCell, style: null };
+ selectionWithStyle.range.rangeType = rangeType;
+ const selectionCellWithCoord = attachSelectionWithCoord(selectionWithStyle, this._skeleton);
+ this._startRangeWhenPointerDown = { ...selectionCellWithCoord.rangeWithCoord };
+ // const selectionCellWithCoord: Nullable<ISelectionWithCoord> = this._getSelectionWithCoordByOffset(offsetX, offsetY, scaleX, scaleY, scrollXY);
+ // if (!selectionCellWithCoord) return;
+ // const { rangeWithCoord: cursorCellRange, primaryWithCoord: _primaryCursorCellRange } = selectionCellWithCoord;
+
+ let activeSelectionControl: Nullable<SelectionControl> = this.getActiveSelectionControl();
+ const cursorRangeWidthCoord: IRangeWithCoord = { ...selectionCellWithCoord.rangeWithCoord, rangeType };
+ const curControls = this.getSelectionControls();
+ for (const control of curControls) {
+ // right click
+ if (evt.button === 2 && control.model.isInclude(cursorRangeWidthCoord)) {
+ activeSelectionControl = control;
+ return;
+ }
+ // Click to an existing selection, then what?
+ // if (control.model.isEqual(cursorCellRangeWithRangeType)) {
+ // activeSelectionControl = control;
+ // break;
+ // }
+ }
+
+ this._checkClearPreviousControls(evt);
+
+ const currentCell = activeSelectionControl?.model.currentCell;
+ const expandByShiftKey = evt.shiftKey && currentCell;
+ const remainLastEnable = this._remainLastEnabled &&
+ !evt.ctrlKey &&
+ !evt.shiftKey &&
+ !this._skipLastEnabled &&
+ !this._singleSelectionEnabled;
+
+ //#region update selection control
+ if (expandByShiftKey && currentCell) {
+ // Perform pointer down selection.
+ this._makeSelectionByTwoCells(
+ currentCell,
+ cursorRangeWidthCoord,
+ skeleton,
+ rangeType,
+ activeSelectionControl! // Get updated in this method
+ );
+ } else if (remainLastEnable && activeSelectionControl) {
+ // Supports the formula ref text selection feature,
+ // under the condition of preserving all previous selections, it modifies the position of the latest selection.
+
+ activeSelectionControl.updateRangeBySelectionWithCoord(selectionCellWithCoord);// (cursorRangeWidthCoord, primaryCursorCellRange);
+ } else {
+ // In normal situation, pointerdown ---> Create new SelectionControl,
+ activeSelectionControl = this.newSelectionControl(scene, skeleton, selectionWithStyle);
+
+ // activeSelectionControl.updateRangeBySelectionWithCoord(selectionCellWithCoord); //(cursorRangeWidthCoord, primaryCursorCellRange);
+ }
+ // clear highlight except last one.
+ for (let i = 0; i < this.getSelectionControls().length - 1; i++) {
+ this.getSelectionControls()[i].clearHighlight();
+ }
+ //#endregion
+
+ scene.disableObjectsEvent();
+ this._clearUpdatingListeners();
+ this._addEndingListeners();
+ scene.getTransformer()?.clearSelectedObjects();
+ this._setupPointerMoveListener(viewportMain, activeSelectionControl!, rangeType, scrollTimerType, offsetX, offsetY);
+ this._escapeShortcutDisposable = this._shortcutService.forceEscape();
+
+ this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
+ this._scenePointerUpSub = scene.onPointerUp$.subscribeEvent(() => {
+ this._clearUpdatingListeners();
+
+ // selection control would be disposed in _selectionMoveEnd$.
+ // SelectionRenderService@selectionMoveEnd$ exec SetSelectionsOperation
+ // SheetsSelectionsService@setSelections
+ // SelectionRenderService._workbookSelections.selectionMoveEnd$ call _reset() to clear selectionControl.
+ this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
+ this._escapeShortcutDisposable?.dispose();
+ this._escapeShortcutDisposable = null;
+ });
+ }
}
diff --git a/packages/sheets-ui/src/services/selection/selection-shape-extension.ts b/packages/sheets-ui/src/services/selection/selection-shape-extension.ts
index 894358ea22..8e37233eb1 100644
--- a/packages/sheets-ui/src/services/selection/selection-shape-extension.ts
+++ b/packages/sheets-ui/src/services/selection/selection-shape-extension.ts
@@ -14,18 +14,20 @@
* limitations under the License.
*/
+import type { ISelectionWithStyle } from '@univerjs/sheets';
import { ColorKit, Quantity, UniverInstanceType } from '@univerjs/core';
import { CURSOR_TYPE, IRenderManagerService, Rect, ScrollTimer, ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
-import { getNormalSelectionStyle, SELECTION_CONTROL_BORDER_BUFFER_WIDTH } from '@univerjs/sheets';
+import { SELECTION_CONTROL_BORDER_BUFFER_WIDTH } from '@univerjs/sheets';
/* eslint-disable max-lines-per-function */
-import type { IFreeze, Injector, IRangeWithCoord, Nullable, ThemeService } from '@univerjs/core';
+import type { IFreeze, Injector, IRange, IRangeWithCoord, Nullable, ThemeService } from '@univerjs/core';
import type { IMouseEvent, IPointerEvent, Scene, SpreadsheetSkeleton, Viewport } from '@univerjs/engine-render';
import type { Subscription } from 'rxjs';
import type { SelectionControl } from './selection-control';
import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
import { ISheetSelectionRenderService } from './base-selection-render.service';
-import { RANGE_FILL_PERMISSION_CHECK, RANGE_MOVE_PERMISSION_CHECK } from './const';
+import { genNormalSelectionStyle, RANGE_FILL_PERMISSION_CHECK, RANGE_MOVE_PERMISSION_CHECK } from './const';
+import { attachSelectionWithCoord } from './util';
const HELPER_SELECTION_TEMP_NAME = '__SpreadsheetHelperSelectionTempRect';
@@ -36,6 +38,14 @@ export interface ISelectionShapeTargetSelection {
targetSelection: IRangeWithCoord;
}
+export interface ISelectionShapeExtensionOption {
+ skeleton: SpreadsheetSkeleton;
+ scene: Scene;
+ themeService: ThemeService;
+ injector: Injector;
+ selectionHooks: Record<string, () => void>;
+}
+
/**
* for auto-fill (crosshair expand selection range)
* drag selection range
@@ -78,20 +88,24 @@ export class SelectionShapeExtension {
private _fillControlColors: string[] = [];
+ private _skeleton: SpreadsheetSkeleton;
+ private _scene: Scene;
+ private readonly _themeService: ThemeService;
+ private readonly _injector: Injector;
+ private _selectionHooks: Record<string, () => void>;
constructor(
private _control: SelectionControl,
- private _skeleton: SpreadsheetSkeleton,
- private _scene: Scene,
- private readonly _themeService: ThemeService,
-
- /** @deprecated injection in extensions should be strictly limited. */
- // TODO@ybzky: remove injector here, permission control should be update from the outside.
- private readonly _injector: Injector,
- private _selectionHooks: Record<string, () => void>
+ options: ISelectionShapeExtensionOption
) {
+ this._skeleton = options.skeleton;
+ this._scene = options.scene;
+ this._themeService = options.themeService;
+ this._injector = options.injector;
+ this._selectionHooks = options.selectionHooks;
+
this._initialControl();
this._initialWidget();
- this._initialFill();
+ this._initialAutoFill();
this._control.dispose$.subscribe(() => {
this.dispose();
@@ -179,14 +193,18 @@ export class SelectionShapeExtension {
});
}
+ /**
+ * Move the whole selection control after cursor turn into move state.
+ * NOT same as widgetMoving, that's for 8 control points.
+ * @param moveOffsetX
+ * @param moveOffsetY
+ */
private _controlMoving(moveOffsetX: number, moveOffsetY: number) {
const scene = this._scene;
-
- const scrollXY = scene.getVpScrollXYInfoByPosToVp(Vector2.FromArray([moveOffsetX, moveOffsetY]));
-
+ const scrollXY = scene.getScrollXYInfoByViewport(Vector2.FromArray([moveOffsetX, moveOffsetY]));
const { scaleX, scaleY } = scene.getAncestorScale();
- const moveActualSelection = this._skeleton.getCellPositionByOffset(
+ const actualCellIndex = this._skeleton.getCellIndexByOffset(
moveOffsetX,
moveOffsetY,
scaleX,
@@ -194,75 +212,66 @@ export class SelectionShapeExtension {
scrollXY
);
- const { row, column } = moveActualSelection;
-
+ const { row, column } = actualCellIndex;
const maxRow = this._skeleton.getRowCount() - 1;
-
const maxColumn = this._skeleton.getColumnCount() - 1;
- let startRow = row + this._relativeSelectionPositionRow;
-
- if (startRow < 0) {
- startRow = 0;
- }
-
+ let startRow = Math.max(0, row + this._relativeSelectionPositionRow);
let endRow = startRow + this._relativeSelectionRowLength;
-
if (endRow > maxRow) {
endRow = maxRow;
-
if (endRow - startRow < this._relativeSelectionRowLength) {
startRow = endRow - this._relativeSelectionRowLength;
}
}
- let startColumn = column + this._relativeSelectionPositionColumn;
-
- if (startColumn < 0) {
- startColumn = 0;
- }
-
+ let startColumn = Math.max(0, column + this._relativeSelectionPositionColumn);
let endColumn = startColumn + this._relativeSelectionColumnLength;
-
if (endColumn > maxColumn) {
endColumn = maxColumn;
-
if (endColumn - startColumn < this._relativeSelectionColumnLength) {
startColumn = endColumn - this._relativeSelectionColumnLength;
}
}
-
- const startCell = this._skeleton.getNoMergeCellPositionByIndex(startRow, startColumn);
- const endCell = this._skeleton.getNoMergeCellPositionByIndex(endRow, endColumn);
-
- const startY = startCell?.startY || 0;
- const endY = endCell?.endY || 0;
- const startX = startCell?.startX || 0;
- const endX = endCell?.endX || 0;
-
- this._helperSelection?.transformByState({
- left: startX,
- top: startY,
- width: endX - startX,
- height: endY - startY,
- });
-
- this._targetSelection = {
- startY,
- endY,
- startX,
- endX,
- startRow,
- endRow,
- startColumn,
- endColumn,
+ const primaryCell = this._skeleton.worksheet.getCellInfoInMergeData(startRow, startColumn);
+ const selection: ISelectionWithStyle = {
+ range: { startRow, endRow, startColumn, endColumn },
+ primary: primaryCell,
+ style: null,
};
-
- this._control.selectionMoving$.next(this._targetSelection);
+ const selectionWithCoord = attachSelectionWithCoord(selection, this._skeleton);
+ // const startCell = this._skeleton.getNoMergeCellPositionByIndex(startRow, startColumn);
+ // const endCell = this._skeleton.getNoMergeCellPositionByIndex(endRow, endColumn);
+ // const startY = startCell?.startY || 0;
+ // const endY = endCell?.endY || 0;
+ // const startX = startCell?.startX || 0;
+ // const endX = endCell?.endX || 0;
+
+ // this._helperSelection?.transformByState({
+ // left: startX,
+ // top: startY,
+ // width: endX - startX,
+ // height: endY - startY,
+ // });
+
+ // this._targetSelection = {
+ // startY,
+ // endY,
+ // startX,
+ // endX,
+ // startRow,
+ // endRow,
+ // startColumn,
+ // endColumn,
+ // };
+ // const primaryWithCoordAndMergeInfo = attachPrimaryWithCoord(this._skeleton, primaryCell);
+ // this._control.updateRange(this._targetSelection, primaryWithCoordAndMergeInfo);
+ this._control.updateRangeBySelectionWithCoord(selectionWithCoord);
+ this._control.selectionMoving$.next(selectionWithCoord.rangeWithCoord);
}
/**
- * Drag move whole selectionControl when cusor turns to crosshair. Not for dragging 8 control points.
+ * Drag move whole selectionControl when cursor turns to crosshair. Not for dragging 8 control points.
* @param evt
*/
private _controlEvent(evt: IMouseEvent | IPointerEvent) {
@@ -270,15 +279,15 @@ export class SelectionShapeExtension {
const scene = this._scene;
- const relativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+ const relativeCoords = scene.getCoordRelativeToViewport(Vector2.FromArray([evtOffsetX, evtOffsetY]));
const { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
- const scrollXY = scene.getVpScrollXYInfoByPosToVp(relativeCoords);
+ const scrollXY = scene.getScrollXYInfoByViewport(relativeCoords);
const { scaleX, scaleY } = scene.getAncestorScale();
- const actualSelection = this._skeleton.getCellPositionByOffset(
+ const actualSelection = this._skeleton.getCellIndexByOffset(
newEvtOffsetX,
newEvtOffsetY,
scaleX,
@@ -348,7 +357,7 @@ export class SelectionShapeExtension {
return;
}
- const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeToViewportCoord(
+ const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getCoordRelativeToViewport(
Vector2.FromArray([moveOffsetX, moveOffsetY])
);
@@ -432,7 +441,7 @@ export class SelectionShapeExtension {
const scene = this._scene;
const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
- const relativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+ const relativeCoords = scene.getCoordRelativeToViewport(Vector2.FromArray([evtOffsetX, evtOffsetY]));
const { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
this._startOffsetX = evtOffsetX;
this._startOffsetY = evtOffsetY;
@@ -481,7 +490,7 @@ export class SelectionShapeExtension {
this._scenePointerMoveSub = scene.onPointerMove$.subscribeEvent((moveEvt: IPointerEvent | IMouseEvent) => {
const { offsetX: moveOffsetX, offsetY: moveOffsetY } = moveEvt;
- const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeToViewportCoord(
+ const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getCoordRelativeToViewport(
Vector2.FromArray([moveOffsetX, moveOffsetY])
);
@@ -517,9 +526,9 @@ export class SelectionShapeExtension {
private _widgetMoving(moveOffsetX: number, moveOffsetY: number, cursor: CURSOR_TYPE) {
const scene = this._scene;
- const scrollXY = scene.getVpScrollXYInfoByPosToVp(Vector2.FromArray([this._startOffsetX, this._startOffsetY]));
+ const scrollXY = scene.getScrollXYInfoByViewport(Vector2.FromArray([this._startOffsetX, this._startOffsetY]));
const { scaleX, scaleY } = scene.getAncestorScale();
- const moveActualSelection = this._skeleton.getCellPositionByOffset(
+ const moveActualSelection = this._skeleton.getCellIndexByOffset(
moveOffsetX,
moveOffsetY,
scaleX,
@@ -528,7 +537,7 @@ export class SelectionShapeExtension {
);
const { row, column } = moveActualSelection;
- const { rowHeaderWidth, columnHeaderHeight } = this._skeleton;
+ // const { rowHeaderWidth, columnHeaderHeight } = this._skeleton;
// const maxRow = this._skeleton.getRowCount() - 1;
// const maxColumn = this._skeleton.getColumnCount() - 1;
let startRow = this._relativeSelectionPositionRow;
@@ -570,38 +579,37 @@ export class SelectionShapeExtension {
endColumn = this._relativeSelectionPositionColumn + this._relativeSelectionColumnLength;
}
- const {
- startRow: finalStartRow,
- startColumn: finalStartColumn,
- endRow: finalEndRow,
- endColumn: finalEndColumn,
- } = this._swapPositions(startRow, startColumn, endRow, endColumn);
-
- const startCell = this._skeleton.getNoMergeCellPositionByIndex(finalStartRow, finalStartColumn);
- const endCell = this._skeleton.getNoMergeCellPositionByIndex(finalEndRow, finalEndColumn);
-
- const startY = startCell?.startY || 0;
- const endY = endCell?.endY || 0;
- const startX = startCell?.startX || 0;
- const endX = endCell?.endX || 0;
-
- this._targetSelection = {
- startY,
- endY,
- startX,
- endX,
- startRow,
- endRow,
- startColumn,
- endColumn,
- };
-
- this._control.update(this._targetSelection, rowHeaderWidth, columnHeaderHeight, this._control.currentStyle);
- this._control.clearHighlight();
+ const range = this._swapPositions(startRow, startColumn, endRow, endColumn);
+ const primaryCell = this._skeleton.getCellWithMergeInfoByIndex(startRow, startColumn);
+ const selectionWithStyle: ISelectionWithStyle = { range, primary: primaryCell, style: null };
+ const selectionRangeWithCoord = attachSelectionWithCoord(selectionWithStyle, this._skeleton);
+ this._targetSelection = selectionRangeWithCoord.rangeWithCoord;
+ // const startCell = this._skeleton.getNoMergeCellPositionByIndex(finalStartRow, finalStartColumn);
+ // const endCell = this._skeleton.getNoMergeCellPositionByIndex(finalEndRow, finalEndColumn);
+
+ // const startY = startCell?.startY || 0;
+ // const endY = endCell?.endY || 0;
+ // const startX = startCell?.startX || 0;
+ // const endX = endCell?.endX || 0;
+
+ // this._targetSelection = {
+ // startY,
+ // endY,
+ // startX,
+ // endX,
+ // startRow,
+ // endRow,
+ // startColumn,
+ // endColumn,
+ // };
+ // const primaryWithCoord = this._skeleton.getCellWithCoordByIndex(startRow, startColumn);
+ // this._control.updateRange(this._targetSelection, primaryWithCoord);
+
+ this._control.updateRangeBySelectionWithCoord(selectionRangeWithCoord);
this._control.selectionScaling$.next(this._targetSelection);
}
- private _initialFill() {
+ private _initialAutoFill() {
const { fillControl } = this._control;
fillControl.onPointerEnter$.subscribeEvent((evt: IPointerEvent | IMouseEvent) => {
@@ -617,11 +625,11 @@ export class SelectionShapeExtension {
fillControl.resetCursor();
});
- fillControl.onPointerDown$.subscribeEvent(this._fillEvent.bind(this));
+ fillControl.onPointerDown$.subscribeEvent(this._autoFillForPointerdown.bind(this));
}
// eslint-disable-next-line complexity
- private _fillMoving(moveOffsetX: number, moveOffsetY: number) {
+ private _autoFillMoving(moveOffsetX: number, moveOffsetY: number) {
const scene = this._scene;
// const activeViewport = scene.getActiveViewportByCoord(Vector2.FromArray([moveOffsetX, moveOffsetY]));
// const scrollXY = activeViewport ? scene.getScrollXY(activeViewport) : { x: 0, y: 0 };
@@ -629,7 +637,7 @@ export class SelectionShapeExtension {
const { scaleX, scaleY } = scene.getAncestorScale();
- const moveActualSelection = this._skeleton.getCellPositionByOffset(
+ const moveActualSelection = this._skeleton.getCellIndexByOffset(
moveOffsetX,
moveOffsetY,
scaleX,
@@ -639,7 +647,7 @@ export class SelectionShapeExtension {
const { row, column } = moveActualSelection;
- const moveRelativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([moveOffsetX, moveOffsetY]));
+ const moveRelativeCoords = scene.getCoordRelativeToViewport(Vector2.FromArray([moveOffsetX, moveOffsetY]));
const maxRow = this._skeleton.getRowCount() - 1;
@@ -764,12 +772,12 @@ export class SelectionShapeExtension {
this._control.selectionFilling$.next(this._targetSelection);
}
- private _fillEvent(evt: IMouseEvent | IPointerEvent) {
+ private _autoFillForPointerdown(evt: IMouseEvent | IPointerEvent) {
const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
const scene = this._scene;
- const relativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+ const relativeCoords = scene.getCoordRelativeToViewport(Vector2.FromArray([evtOffsetX, evtOffsetY]));
const { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
@@ -797,7 +805,7 @@ export class SelectionShapeExtension {
const style = this._control.currentStyle;
let stroke = style?.stroke;
let strokeWidth = style?.strokeWidth;
- const defaultStyle = getNormalSelectionStyle(this._themeService);
+ const defaultStyle = genNormalSelectionStyle(this._themeService);
if (stroke == null) {
stroke = defaultStyle.stroke;
}
@@ -852,11 +860,11 @@ export class SelectionShapeExtension {
return;
}
- const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeToViewportCoord(
+ const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getCoordRelativeToViewport(
Vector2.FromArray([moveOffsetX, moveOffsetY])
);
- this._fillMoving(newMoveOffsetX, newMoveOffsetY);
+ this._autoFillMoving(newMoveOffsetX, newMoveOffsetY);
scene.setCursor(CURSOR_TYPE.CROSSHAIR);
@@ -900,7 +908,7 @@ export class SelectionShapeExtension {
}
scrollTimer.scrolling(newMoveOffsetX, newMoveOffsetY, () => {
- this._fillMoving(newMoveOffsetX, newMoveOffsetY);
+ this._autoFillMoving(newMoveOffsetX, newMoveOffsetY);
});
});
@@ -926,7 +934,16 @@ export class SelectionShapeExtension {
return this._skeleton.worksheet.getMergedCellRange(startRow, startColumn, endRow, endColumn).length > 0;
}
- private _swapPositions(startRow: number, startColumn: number, endRow: number, endColumn: number) {
+ /**
+ * Make sure startRow < endRow and startColumn < endColumn
+ *
+ * @param startRow
+ * @param startColumn
+ * @param endRow
+ * @param endColumn
+ * @returns {IRange} range
+ */
+ private _swapPositions(startRow: number, startColumn: number, endRow: number, endColumn: number): IRange {
const finalStartRow = Math.min(startRow, endRow);
const finalStartColumn = Math.min(startColumn, endColumn);
const finalEndRow = Math.max(startRow, endRow);
diff --git a/packages/sheets-ui/src/services/selection/util.ts b/packages/sheets-ui/src/services/selection/util.ts
index 9b24e09cdf..208cf03410 100644
--- a/packages/sheets-ui/src/services/selection/util.ts
+++ b/packages/sheets-ui/src/services/selection/util.ts
@@ -14,34 +14,62 @@
* limitations under the License.
*/
-import type { ISelectionCell, ISelectionCellWithMergeInfo } from '@univerjs/core';
+import type { ICellWithCoord, IRange, IRangeWithCoord, ISelectionCell } from '@univerjs/core';
import type { SpreadsheetSkeleton } from '@univerjs/engine-render';
-import type { ISelectionWithCoordAndStyle, ISelectionWithStyle } from '@univerjs/sheets';
-import { attachRangeWithCoord } from '../sheet-skeleton-manager.service';
-// const nilSelection = {
-// startRow: -1,
-// startColumn: -1,
-// endRow: -1,
-// endColumn: -1,
-// startY: 0,
-// endY: 0,
-// startX: 0,
-// endX: 0,
-// rangeType: RANGE_TYPE.NORMAL,
-// }
+import type { ISelectionWithCoord, ISelectionWithStyle } from '@univerjs/sheets';
-export function attachSelectionWithCoord(selection: ISelectionWithStyle, skeleton: SpreadsheetSkeleton): ISelectionWithCoordAndStyle {
+/**
+ * Add startXY endXY to range, XY are no merge cell position.
+ * @param skeleton
+ * @param range
+ * @returns {IRangeWithCoord}
+ */
+export function attachRangeWithCoord(skeleton: SpreadsheetSkeleton, range: IRange): IRangeWithCoord {
+ const { startRow, startColumn, endRow, endColumn, rangeType } = range;
+
+ // after the selection is moved, it may be stored endRow < startRow or endColumn < startColumn
+ // so startCell and endCell need get min value to draw the selection
+ const _startRow = endRow < startRow ? endRow : startRow;
+ const _endRow = endRow < startRow ? startRow : endRow;
+
+ const _startColumn = endColumn < startColumn ? endColumn : startColumn;
+ const _endColumn = endColumn < startColumn ? startColumn : endColumn;
+
+ const startCell = skeleton.getNoMergeCellPositionByIndex(_startRow, _startColumn);
+ const endCell = skeleton.getNoMergeCellPositionByIndex(_endRow, _endColumn);
+
+ return {
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
+ rangeType,
+ startY: startCell?.startY || 0,
+ endY: endCell?.endY || 0,
+ startX: startCell?.startX || 0,
+ endX: endCell?.endX || 0,
+ };
+}
+
+/**
+ * Return selection with coord and style from selection, which has range & primary & style.
+ * coord are no merge cell position.
+ * @param selection
+ * @param skeleton
+ * @returns {ISelectionWithCoord} selection with coord and style
+ */
+export function attachSelectionWithCoord(selection: ISelectionWithStyle, skeleton: SpreadsheetSkeleton): ISelectionWithCoord {
const { range, primary, style } = selection;
const rangeWithCoord = attachRangeWithCoord(skeleton, range);
-
+ const primaryWithCoord = primary ? attachPrimaryWithCoord(skeleton, primary) : undefined;
return {
rangeWithCoord,
- primaryWithCoord: primary ? attachPrimaryWithCoord(primary, skeleton) : null,
+ primaryWithCoord,
style,
- } as ISelectionWithCoordAndStyle;
+ } as ISelectionWithCoord;
}
-export function attachPrimaryWithCoord(primary: ISelectionCell, skeleton: SpreadsheetSkeleton): ISelectionCellWithMergeInfo {
+export function attachPrimaryWithCoord(skeleton: SpreadsheetSkeleton, primary: ISelectionCell): ICellWithCoord {
const { actualRow, actualColumn, isMerged, isMergedMainCell, startRow, startColumn, endRow, endColumn } = primary;
const cellPosition = skeleton.getNoMergeCellPositionByIndex(actualRow, actualColumn);
const startCell = skeleton.getNoMergeCellPositionByIndex(startRow, startColumn);
@@ -66,5 +94,5 @@ export function attachPrimaryWithCoord(primary: ISelectionCell, skeleton: Spread
startX: startCell?.startX || 0,
endX: endCell?.endX || 0,
},
- };
+ } as ICellWithCoord;
}
diff --git a/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts b/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts
index 274bf4edc1..489ed74cf8 100644
--- a/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts
+++ b/packages/sheets-ui/src/services/sheet-skeleton-manager.service.ts
@@ -19,6 +19,7 @@ import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
import { Disposable, Inject, Injector } from '@univerjs/core';
import { SpreadsheetSkeleton } from '@univerjs/engine-render';
import { BehaviorSubject } from 'rxjs';
+import { attachRangeWithCoord } from './selection/util';
export interface ISheetSkeletonManagerParam {
unitId: string;
@@ -230,30 +231,3 @@ export class SheetSkeletonManagerService extends Disposable implements IRenderMo
return spreadsheetSkeleton;
}
}
-
-export function attachRangeWithCoord(skeleton: SpreadsheetSkeleton, range: IRange): IRangeWithCoord {
- const { startRow, startColumn, endRow, endColumn, rangeType } = range;
-
- // after the selection is moved, it may be stored endRow < startRow or endColumn < startColumn
- // so startCell and endCell need get min value to draw the selection
- const _startRow = endRow < startRow ? endRow : startRow;
- const _endRow = endRow < startRow ? startRow : endRow;
-
- const _startColumn = endColumn < startColumn ? endColumn : startColumn;
- const _endColumn = endColumn < startColumn ? startColumn : endColumn;
-
- const startCell = skeleton.getNoMergeCellPositionByIndex(_startRow, _startColumn);
- const endCell = skeleton.getNoMergeCellPositionByIndex(_endRow, _endColumn);
-
- return {
- startRow,
- startColumn,
- endRow,
- endColumn,
- rangeType,
- startY: startCell?.startY || 0,
- endY: endCell?.endY || 0,
- startX: startCell?.startX || 0,
- endX: endCell?.endX || 0,
- };
-}
diff --git a/packages/sheets-ui/src/services/utils/doc-skeleton-util.ts b/packages/sheets-ui/src/services/utils/doc-skeleton-util.ts
index 06a20a8160..a113ed6a9d 100644
--- a/packages/sheets-ui/src/services/utils/doc-skeleton-util.ts
+++ b/packages/sheets-ui/src/services/utils/doc-skeleton-util.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICustomRange, Injector, IParagraph, ISelectionCellWithMergeInfo, ITextRangeParam, Workbook } from '@univerjs/core';
+import type { ICellWithCoord, ICustomRange, Injector, IParagraph, ITextRangeParam, Workbook } from '@univerjs/core';
import type { DocumentSkeleton, IBoundRectNoAngle, IDocumentSkeletonGlyph, IFontCacheItem } from '@univerjs/engine-render';
import { CustomRangeType, HorizontalAlign, IUniverInstanceService, PresetListType, UniverInstanceType, VerticalAlign } from '@univerjs/core';
import { DocSkeletonManagerService } from '@univerjs/docs';
@@ -144,7 +144,7 @@ export const calculateDocSkeletonRects = (docSkeleton: DocumentSkeleton, padding
};
};
-export function calcPadding(cell: ISelectionCellWithMergeInfo, font: IFontCacheItem) {
+export function calcPadding(cell: ICellWithCoord, font: IFontCacheItem) {
const height = font.documentSkeleton.getSkeletonData()?.pages[0].height ?? 0;
const width = font.documentSkeleton.getSkeletonData()?.pages[0].width ?? 0;
const vt = font.verticalAlign;
@@ -213,7 +213,7 @@ export const getCustomRangePosition = (injector: Injector, unitId: string, subUn
const PADDING = DOC_VERTICAL_PADDING;
- const cellIndex = skeleton.getCellByIndex(row, col);
+ const cellIndex = skeleton.getCellWithCoordByIndex(row, col);
let { actualColumn, actualRow } = cellIndex;
skeleton.overflowCache.forValue((r, c, range) => {
@@ -223,7 +223,7 @@ export const getCustomRangePosition = (injector: Injector, unitId: string, subUn
}
});
- const actualCell = skeleton.getCellByIndex(actualRow, actualColumn);
+ const actualCell = skeleton.getCellWithCoordByIndex(actualRow, actualColumn);
const cellData = worksheet.getCell(actualCell.actualRow, actualCell.actualColumn);
const { topOffset = 0, leftOffset = 0 } = cellData?.fontRenderExtension ?? {};
const { paddingLeft, paddingTop } = calcPadding(actualCell, font);
diff --git a/packages/sheets-ui/src/services/utils/selection-util.ts b/packages/sheets-ui/src/services/utils/selection-util.ts
index 42b0cb8a0f..84f07d5e30 100644
--- a/packages/sheets-ui/src/services/utils/selection-util.ts
+++ b/packages/sheets-ui/src/services/utils/selection-util.ts
@@ -19,13 +19,12 @@ import type { ISelectionStyle } from '@univerjs/sheets';
export function createCopyPasteSelectionStyle(
themeService: ThemeService
-): ISelectionStyle {
+): Partial<ISelectionStyle> {
return {
strokeWidth: 1.5,
stroke: themeService.getCurrentTheme().primaryColor,
fill: 'rgba(178, 178, 178, 0.10)',
widgets: {},
- hasAutoFill: false,
strokeDash: 8,
};
}
diff --git a/packages/sheets-ui/src/views/permission/extensions/range-protection.render.ts b/packages/sheets-ui/src/views/permission/extensions/range-protection.render.ts
index 9314ac95f0..4f1eea88d8 100644
--- a/packages/sheets-ui/src/views/permission/extensions/range-protection.render.ts
+++ b/packages/sheets-ui/src/views/permission/extensions/range-protection.render.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-import { Range } from '@univerjs/core';
-import { SheetExtension } from '@univerjs/engine-render';
-import { UnitAction } from '@univerjs/protocol';
import type { ICellDataForSheetInterceptor, IScale } from '@univerjs/core';
import type { SpreadsheetSkeleton, UniverRenderingContext } from '@univerjs/engine-render';
import type { ICellPermission } from '@univerjs/sheets';
+import { Range } from '@univerjs/core';
+import { SheetExtension } from '@univerjs/engine-render';
+import { UnitAction } from '@univerjs/protocol';
import { base64 } from './protect-background-img';
export const RANGE_PROTECTION_CAN_VIEW_RENDER_EXTENSION_KEY = 'RANGE_PROTECTION_CAN_VIEW_RENDER_EXTENSION_KEY';
@@ -85,8 +85,8 @@ export abstract class RangeProtectionRenderExtension extends SheetExtension {
}
this.renderCache.add(config.ruleId);
config.ranges!.forEach((range) => {
- const start = spreadsheetSkeleton.getCellByIndexWithNoHeader(range.startRow, range.startColumn);
- const end = spreadsheetSkeleton.getCellByIndexWithNoHeader(range.endRow, range.endColumn);
+ const start = spreadsheetSkeleton.getCellWithCoordByIndex(range.startRow, range.startColumn, false);
+ const end = spreadsheetSkeleton.getCellWithCoordByIndex(range.endRow, range.endColumn, false);
ctx.fillRect(start.startX, start.startY, end.endX - start.startX, end.endY - start.startY);
});
}
diff --git a/packages/sheets-ui/src/views/permission/extensions/worksheet-permission.render.ts b/packages/sheets-ui/src/views/permission/extensions/worksheet-permission.render.ts
index 6db56e91ef..feb1eeb728 100644
--- a/packages/sheets-ui/src/views/permission/extensions/worksheet-permission.render.ts
+++ b/packages/sheets-ui/src/views/permission/extensions/worksheet-permission.render.ts
@@ -14,11 +14,11 @@
* limitations under the License.
*/
-import { SheetExtension } from '@univerjs/engine-render';
-import { UnitAction } from '@univerjs/protocol';
import type { IScale } from '@univerjs/core';
import type { SpreadsheetSkeleton, UniverRenderingContext } from '@univerjs/engine-render';
import type { IWorksheetProtectionRenderCellData } from '@univerjs/sheets';
+import { SheetExtension } from '@univerjs/engine-render';
+import { UnitAction } from '@univerjs/protocol';
import { base64 } from './protect-background-img';
export const worksheetProtectionKey = 'worksheet-protection';
@@ -54,8 +54,8 @@ export class WorksheetProtectionRenderExtension extends SheetExtension {
this._pattern = ctx.createPattern(this._img, 'repeat');
}
const { startRow, startColumn, endRow, endColumn } = spreadsheetSkeleton.rowColumnSegment;
- const start = spreadsheetSkeleton.getCellByIndexWithNoHeader(startRow, startColumn);
- const end = spreadsheetSkeleton.getCellByIndexWithNoHeader(endRow, endColumn);
+ const start = spreadsheetSkeleton.getCellWithCoordByIndex(startRow, startColumn, false);
+ const end = spreadsheetSkeleton.getCellWithCoordByIndex(endRow, endColumn, false);
const { hasWorksheetRule = false, selectionProtection = [] } = worksheet.getCell(startRow, startColumn) as IWorksheetProtectionRenderCellData || {};
if (!this._pattern) {
diff --git a/packages/sheets/src/basics/selection.ts b/packages/sheets/src/basics/selection.ts
index ab4a224c31..eb7e1dc648 100644
--- a/packages/sheets/src/basics/selection.ts
+++ b/packages/sheets/src/basics/selection.ts
@@ -14,15 +14,15 @@
* limitations under the License.
*/
-import { ColorKit, getCellInfoInMergeData, makeCellRangeToRangeData } from '@univerjs/core';
import type {
+ ICellWithCoord,
IRange,
+ IRangeWithCoord,
ISelection,
- ISelectionCellWithMergeInfo,
- ISelectionWithCoord,
+ ISelectionCell,
Nullable,
- ThemeService,
} from '@univerjs/core';
+import { getCellInfoInMergeData, makeCellRangeToRangeData } from '@univerjs/core';
export const SELECTION_CONTROL_BORDER_BUFFER_WIDTH = 1.5; // The draggable range of the selection is too thin, making it easy for users to miss. Therefore, a buffer gap is provided to make it easier for users to select.
@@ -91,7 +91,7 @@ export interface ISelectionStyle {
/**
* The volume of the touch points.
*/
- widgetSize?: number;
+ widgetSize: number;
/**
* The thickness of the border of the touch points
*/
@@ -105,15 +105,11 @@ export interface ISelectionStyle {
* https://support.microsoft.com/en-us/office/copy-a-formula-by-dragging-the-fill-handle-in-excel-for-mac-dd928259-622b-473f-9a33-83aa1a63e218
* Whether to show the drop-down fill button at the bottom right corner of the selection.
*/
- hasAutoFill: boolean;
- AutofillSize?: number; // The size of the fill button.
- AutofillStrokeWidth?: number; // The border size of the fill button.
- AutofillStroke?: string; // The color of the fill button.
+ // hasAutoFill?: boolean;
+ autofillSize?: number; // The size of the fill button.
+ autofillStrokeWidth?: number; // The border size of the fill button.
+ autofillStroke?: string; // The color of the fill button.
- /**
- * Whether to synchronize the display of row title highlights, the highlighting range is consistent with the horizontal range of the selection.
- */
- hasRowHeader?: boolean;
/**
* The color of the row title highlight.
* A level of transparency should be set to avoid covering the row title content.
@@ -128,10 +124,6 @@ export interface ISelectionStyle {
*/
rowHeaderStrokeWidth?: number;
- /**
- * The setting of column title highlight is similar to that of row title.
- */
- hasColumnHeader?: boolean;
columnHeaderFill?: string;
columnHeaderStroke?: string;
columnHeaderStrokeWidth?: number;
@@ -139,12 +131,33 @@ export interface ISelectionStyle {
expandCornerSize?: number;
}
-export interface ISelectionWithCoordAndStyle extends ISelectionWithCoord {
- style: Nullable<ISelectionStyle>;
+/**
+ * Selection range Info, contains selection range & primary range
+ * primary range is the range of the highlighted cell.
+ *
+ * rangeWithCoord: IRangeWithCoord;
+ * primaryWithCoord: Nullable<ICellWithCoord>;
+ * style?
+ */
+export interface ISelectionWithCoord {
+ rangeWithCoord: IRangeWithCoord;
+ primaryWithCoord: Nullable<ICellWithCoord>;
+ style?: Nullable<ISelectionStyle>;
}
+/**
+ * range: IRange;
+ * primary: Nullable<ISelectionCell>;
+ * style: Nullable<ISelectionStyle>;
+ */
export interface ISelectionWithStyle extends ISelection {
- style: Nullable<ISelectionStyle>;
+ range: IRange;
+ /**
+ * if primary is null, means clear primary cell.
+ * if primary is not defined, means not keep current primary cell.
+ */
+ primary: Nullable<ISelectionCell>;
+ style: Nullable<Partial<ISelectionStyle>>;
}
export interface ISheetRangeLocation {
@@ -153,39 +166,6 @@ export interface ISheetRangeLocation {
unitId: string;
}
-// The default configuration of the selection.
-export function getNormalSelectionStyle(themeService: ThemeService): ISelectionStyle {
- const styleSheet = themeService.getCurrentTheme();
- const fill = new ColorKit(styleSheet.primaryColor).setAlpha(0.07).toRgbString();
- return {
- strokeWidth: 1,
- stroke: styleSheet.primaryColor,
- fill,
- // widgets: { tl: true, tc: true, tr: true, ml: true, mr: true, bl: true, bc: true, br: true },
- widgets: {},
- widgetSize: 6,
- widgetStrokeWidth: 1,
- widgetStroke: styleSheet.colorWhite,
-
- hasAutoFill: true,
- AutofillSize: 6,
- AutofillStrokeWidth: 1,
- AutofillStroke: styleSheet.colorWhite,
-
- hasRowHeader: true,
- rowHeaderFill: fill,
- rowHeaderStroke: styleSheet.primaryColor,
- rowHeaderStrokeWidth: 1,
-
- hasColumnHeader: true,
- columnHeaderFill: fill,
- columnHeaderStroke: styleSheet.primaryColor,
- columnHeaderStrokeWidth: 1,
-
- expandCornerSize: 40,
- };
-}
-
/**
* Process a selection with coordinates and style,
* and extract the coordinate information, because the render needs coordinates when drawing.
@@ -195,7 +175,7 @@ export function getNormalSelectionStyle(themeService: ThemeService): ISelectionS
* @returns
*/
export function convertSelectionDataToRange(
- selectionWithCoordAndStyle: ISelectionWithCoordAndStyle
+ selectionWithCoordAndStyle: ISelectionWithCoord
): ISelectionWithStyle {
const { rangeWithCoord, primaryWithCoord, style } = selectionWithCoordAndStyle;
const result: ISelectionWithStyle = {
@@ -217,7 +197,7 @@ export function convertSelectionDataToRange(
return result;
}
-export function convertPrimaryWithCoordToPrimary(primaryWithCoord: ISelectionCellWithMergeInfo) {
+export function convertPrimaryWithCoordToPrimary(primaryWithCoord: ICellWithCoord) {
const { actualRow, actualColumn, isMerged, isMergedMainCell } = primaryWithCoord;
const { startRow, startColumn, endRow, endColumn } = primaryWithCoord.mergeInfo;
return {
diff --git a/packages/sheets/src/commands/operations/selection.operation.ts b/packages/sheets/src/commands/operations/selection.operation.ts
index 814819d25a..603067d4a5 100644
--- a/packages/sheets/src/commands/operations/selection.operation.ts
+++ b/packages/sheets/src/commands/operations/selection.operation.ts
@@ -16,7 +16,7 @@
import type { IOperation } from '@univerjs/core';
import type { ISelectionWithStyle } from '../../basics/selection';
-import type { SelectionMoveType } from '../../services/selections/selection-manager.service';
+import type { SelectionMoveType } from '../../services/selections/type';
import { CommandType } from '@univerjs/core';
import { getSelectionsService } from '../utils/selection-command-util';
@@ -30,6 +30,9 @@ export interface ISetSelectionsOperationParams {
reveal?: boolean;
}
+/**
+ * Set selections to SelectionModel(WorkbookSelectionModel) by selectionManagerService.
+ */
export const SetSelectionsOperation: IOperation<ISetSelectionsOperationParams> = {
id: 'sheet.operation.set-selections',
type: CommandType.OPERATION,
diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.ts
index ff6018c8f7..67f512b7c1 100644
--- a/packages/sheets/src/index.ts
+++ b/packages/sheets/src/index.ts
@@ -33,15 +33,13 @@ export {
export {
convertPrimaryWithCoordToPrimary,
convertSelectionDataToRange,
- getNormalSelectionStyle,
type ISelectionStyle,
type ISelectionWidgetConfig,
- type ISelectionWithCoordAndStyle,
+ type ISelectionWithCoord,
type ISelectionWithStyle,
type ISheetRangeLocation,
SELECTION_CONTROL_BORDER_BUFFER_COLOR,
SELECTION_CONTROL_BORDER_BUFFER_WIDTH,
- transformCellDataToSelectionData,
} from './basics/selection';
export { createTopMatrixFromMatrix, createTopMatrixFromRanges, findAllRectangle, rangeMerge, RangeMergeUtil } from './basics/rangeMerge';
export { type IUniverSheetsConfig } from './controllers/config.schema';
@@ -52,12 +50,12 @@ export { WorksheetPermissionService } from './services/permission/worksheet-perm
export { WorkbookPermissionService } from './services/permission/workbook-permission/workbook-permission.service';
export {
DISABLE_NORMAL_SELECTIONS,
+ IRefSelectionsService,
+ RefSelectionsService,
SelectionMoveType,
SheetsSelectionsService,
- WorkbookSelections,
-} from './services/selections/selection-manager.service';
-export { IRefSelectionsService, RefSelectionsService } from './services/selections/ref-selections.service';
-
+ WorkbookSelectionModel,
+} from './services/selections';
export { getAddMergeMutationRangeByType } from './controllers/merge-cell.controller';
export { NumfmtService } from './services/numfmt/numfmt.service';
export type { INumfmtItem, INumfmtItemWithCache } from './services/numfmt/type';
diff --git a/packages/sheets/src/services/selections/index.ts b/packages/sheets/src/services/selections/index.ts
new file mode 100644
index 0000000000..d69d354575
--- /dev/null
+++ b/packages/sheets/src/services/selections/index.ts
@@ -0,0 +1,20 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export { IRefSelectionsService, RefSelectionsService } from './ref-selections.service';
+export { WorkbookSelectionModel } from './selection-data-model';
+export { DISABLE_NORMAL_SELECTIONS, SheetsSelectionsService } from './selection-manager.service';
+export { type ISelectionManagerSearchParam, SelectionMoveType } from './type';
diff --git a/packages/sheets/src/services/selections/ref-selections.service.ts b/packages/sheets/src/services/selections/ref-selections.service.ts
index c06732e4b6..ee9ca87ad7 100644
--- a/packages/sheets/src/services/selections/ref-selections.service.ts
+++ b/packages/sheets/src/services/selections/ref-selections.service.ts
@@ -15,10 +15,10 @@
*/
import type { Workbook } from '@univerjs/core';
-import { createIdentifier, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import type { Observable } from 'rxjs';
+import type { WorkbookSelectionModel } from './selection-data-model';
+import { createIdentifier, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { BehaviorSubject, map, merge, switchMap, takeUntil } from 'rxjs';
-import type { WorkbookSelections } from './selection-manager.service';
import { SheetsSelectionsService } from './selection-manager.service';
/**
@@ -47,7 +47,7 @@ export class RefSelectionsService extends SheetsSelectionsService {
this.selectionMoveEnd$ = $.pipe(switchMap((ss) => merge(...ss.map((s) => s.selectionMoveEnd$))));
}
- private _getAliveWorkbooks$(): Observable<WorkbookSelections[]> {
+ private _getAliveWorkbooks$(): Observable<WorkbookSelectionModel[]> {
const aliveWorkbooks = this._instanceSrv.getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
aliveWorkbooks.forEach((workbook) => this._ensureWorkbookSelection(workbook.getUnitId()));
diff --git a/packages/sheets/src/services/selections/selection-data-model.ts b/packages/sheets/src/services/selections/selection-data-model.ts
new file mode 100644
index 0000000000..b884c4a467
--- /dev/null
+++ b/packages/sheets/src/services/selections/selection-data-model.ts
@@ -0,0 +1,153 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ISelectionCell, Nullable, Workbook } from '@univerjs/core';
+import type { ISelectionWithStyle } from '../../basics/selection';
+import { Disposable } from '@univerjs/core';
+
+import { BehaviorSubject, Subject } from 'rxjs';
+import { SelectionMoveType } from './type';
+
+/**
+ * Origin name: WorkbookSelections
+ * NOT Same as @univerjs/sheets-ui.SelectionRenderModel, that's data for SelectionControl in rendering.
+ */
+export class WorkbookSelectionModel extends Disposable {
+ /**
+ * Selection data model for each worksheet.
+ */
+ private _worksheetSelections = new Map<string, ISelectionWithStyle[]>();
+
+ private readonly _selectionMoveStart$ = new Subject<Nullable<ISelectionWithStyle[]>>();
+ readonly selectionMoveStart$ = this._selectionMoveStart$.asObservable();
+
+ private readonly _selectionMoving$ = new Subject<Nullable<ISelectionWithStyle[]>>();
+ readonly selectionMoving$ = this._selectionMoving$.asObservable();
+
+ readonly _selectionMoveEnd$ = new BehaviorSubject<ISelectionWithStyle[]>([]);
+ readonly selectionMoveEnd$ = this._selectionMoveEnd$.asObservable();
+
+ private readonly _selectionSet$ = new BehaviorSubject<ISelectionWithStyle[]>([]);
+ readonly selectionSet$ = this._selectionSet$.asObservable();
+
+ private readonly _beforeSelectionMoveEnd$ = new BehaviorSubject<ISelectionWithStyle[]>([]);
+ readonly beforeSelectionMoveEnd$ = this._beforeSelectionMoveEnd$.asObservable();
+
+ constructor(
+ private readonly _workbook: Workbook
+ ) {
+ super();
+ }
+
+ override dispose(): void {
+ super.dispose();
+
+ this._beforeSelectionMoveEnd$.complete();
+ this._selectionMoveEnd$.complete();
+ this._selectionMoving$.complete();
+ this._selectionMoveStart$.complete();
+ this._selectionSet$.complete();
+ }
+
+ /** Clear all selections in this workbook. */
+ clear(): void {
+ this._worksheetSelections.clear();
+ this._emitOnEnd([]);
+ }
+
+ addSelections(sheetId: string, selectionDatas: ISelectionWithStyle[]): void {
+ const selections = this.getSelectionsOfWorksheet(sheetId);
+ selections.push(...selectionDatas);
+ this._emitOnEnd(selections);
+ }
+
+ /**
+ * Set selectionDatas to _worksheetSelections, and emit selectionDatas by type.
+ * @param sheetId
+ * @param selectionDatas
+ * @param type
+ */
+ setSelections(sheetId: string, selectionDatas: ISelectionWithStyle[] = [], type: SelectionMoveType): void {
+ // selectionDatas should not be same variable as this._worksheetSelections !!!
+ // but there are some place get selection from this._worksheetSelections and set selectionDatas(2nd parameter of this function ) cause selectionDatas is always []
+ // see univer/pull/2909
+ this.deleteSheetSelection(sheetId);
+ this.getSelectionsOfWorksheet(sheetId).push(...selectionDatas);
+
+ switch (type) {
+ case SelectionMoveType.MOVE_START:
+ this._selectionMoveStart$.next(selectionDatas);
+ break;
+ case SelectionMoveType.MOVING:
+ this._selectionMoving$.next(selectionDatas);
+ break;
+ case SelectionMoveType.MOVE_END:
+ this._beforeSelectionMoveEnd$.next(selectionDatas);
+ this._selectionMoveEnd$.next(selectionDatas);
+ // this._emitOnEnd(selectionDatas);
+ break;
+ case SelectionMoveType.ONLY_SET: {
+ this._selectionSet$.next(selectionDatas);
+ break;
+ }
+ default:
+ this._emitOnEnd(selectionDatas);
+ break;
+ }
+ }
+
+ getCurrentSelections(): Readonly<ISelectionWithStyle[]> {
+ return this._getCurrentSelections();
+ }
+
+ getSelectionsOfWorksheet(sheetId: string): ISelectionWithStyle[] {
+ if (!this._worksheetSelections.has(sheetId)) {
+ this._worksheetSelections.set(sheetId, []);
+ }
+
+ return this._worksheetSelections.get(sheetId)!;
+ }
+
+ private _getCurrentSelections(): ISelectionWithStyle[] {
+ return this.getSelectionsOfWorksheet(this._workbook.getActiveSheet()!.getSheetId());
+ }
+
+ getCurrentLastSelection(): Readonly<Nullable<ISelectionWithStyle & { primary: ISelectionCell }>> {
+ const selectionData = this._getCurrentSelections();
+ return selectionData[selectionData.length - 1] as Readonly<Nullable<ISelectionWithStyle & { primary: ISelectionCell }>>;
+ }
+
+ /**
+ * Same method as getSelectionsOfWorksheet.
+ * @param sheetId
+ * @returns this._worksheetSelections
+ */
+ private _ensureSheetSelection(sheetId: string): ISelectionWithStyle[] {
+ if (!this._worksheetSelections.get(sheetId)) {
+ this._worksheetSelections.set(sheetId, []);
+ }
+
+ return this._worksheetSelections.get(sheetId)!;
+ }
+
+ deleteSheetSelection(sheetId: string) {
+ this._worksheetSelections.set(sheetId, []);
+ }
+
+ private _emitOnEnd(selections: ISelectionWithStyle[]): void {
+ this._selectionSet$.next(selections);
+ }
+}
diff --git a/packages/sheets/src/services/selections/selection-manager.service.ts b/packages/sheets/src/services/selections/selection-manager.service.ts
index cfcba3e8fb..51c599e2f1 100644
--- a/packages/sheets/src/services/selections/selection-manager.service.ts
+++ b/packages/sheets/src/services/selections/selection-manager.service.ts
@@ -17,24 +17,12 @@
import type { DeepReadonly, ISelectionCell, Nullable, Workbook } from '@univerjs/core';
import type { Observable } from 'rxjs';
import type { ISelectionWithStyle } from '../../basics/selection';
-import { Disposable, IUniverInstanceService, RxDisposable, UniverInstanceType } from '@univerjs/core';
+import type { ISelectionManagerSearchParam } from './type';
-import { BehaviorSubject, of, shareReplay, Subject, switchMap, takeUntil } from 'rxjs';
-
-export interface ISelectionManagerSearchParam {
- unitId: string;
- sheetId: string;
-}
-
-export enum SelectionMoveType {
- MOVE_START,
- MOVING,
- MOVE_END,
- /**
- * Events are not triggered by the API
- */
- ONLY_SET,
-}
+import { IUniverInstanceService, RxDisposable, UniverInstanceType } from '@univerjs/core';
+import { of, shareReplay, switchMap, takeUntil } from 'rxjs';
+import { WorkbookSelectionModel } from './selection-data-model';
+import { SelectionMoveType } from './type';
export class SheetsSelectionsService extends RxDisposable {
private get _currentSelectionPos(): Nullable<ISelectionManagerSearchParam> {
@@ -106,24 +94,24 @@ export class SheetsSelectionsService extends RxDisposable {
this._ensureWorkbookSelection(unitId).addSelections(sheetId, unitIdOrSelections);
}
- setSelections(selectionDatas: ISelectionWithStyle[], type?: SelectionMoveType): void;
- setSelections(unitId: string, worksheetId: string, selectionDatas: ISelectionWithStyle[], type?: SelectionMoveType): void;
/**
- * Set selection data to WorkbookSelections.
+ * Set selection data to WorkbookSelectionModel.
* If type is not specified, this method would clear all existing selections.
* @param unitIdOrSelections
* @param worksheetIdOrType
* @param selectionDatas
* @param type
*/
+ setSelections(selectionDatas: ISelectionWithStyle[], type?: SelectionMoveType): void;
+ setSelections(unitId: string, worksheetId: string, selectionDatas: ISelectionWithStyle[], type?: SelectionMoveType): void;
setSelections(
unitIdOrSelections: string | ISelectionWithStyle[],
worksheetIdOrType: string | SelectionMoveType | undefined,
selectionDatas?: ISelectionWithStyle[],
type?: SelectionMoveType
): void {
- if (typeof unitIdOrSelections === 'string') {
- this._ensureWorkbookSelection(unitIdOrSelections).setSelections(worksheetIdOrType as string, selectionDatas!, type ?? SelectionMoveType.MOVE_END);
+ if (typeof unitIdOrSelections === 'string' && typeof worksheetIdOrType === 'string') {
+ this._ensureWorkbookSelection(unitIdOrSelections).setSelections(worksheetIdOrType, selectionDatas!, type ?? SelectionMoveType.MOVE_END);
return;
}
@@ -133,7 +121,11 @@ export class SheetsSelectionsService extends RxDisposable {
}
const { unitId, sheetId } = current;
- this._ensureWorkbookSelection(unitId).setSelections(sheetId, unitIdOrSelections ?? selectionDatas, worksheetIdOrType as SelectionMoveType ?? SelectionMoveType.MOVE_END);
+ if (typeof unitIdOrSelections === 'object') {
+ const selectionData = unitIdOrSelections ?? selectionDatas;
+ const type = worksheetIdOrType as SelectionMoveType ?? SelectionMoveType.ONLY_SET;
+ this._ensureWorkbookSelection(unitId).setSelections(sheetId, selectionData, type);
+ }
}
clearCurrentSelections(): void {
@@ -174,15 +166,15 @@ export class SheetsSelectionsService extends RxDisposable {
}
const { unitId, sheetId } = current;
- return this._ensureWorkbookSelection(unitId).getSelectionOfWorksheet(sheetId);
+ return this._ensureWorkbookSelection(unitId).getSelectionsOfWorksheet(sheetId);
}
- getWorkbookSelections(unitId: string): WorkbookSelections {
+ getWorkbookSelections(unitId: string): WorkbookSelectionModel {
return this._ensureWorkbookSelection(unitId);
}
- protected _workbookSelections = new Map<string, WorkbookSelections>();
- protected _ensureWorkbookSelection(unitId: string): WorkbookSelections {
+ protected _workbookSelections = new Map<string, WorkbookSelectionModel>();
+ protected _ensureWorkbookSelection(unitId: string): WorkbookSelectionModel {
let wbSelection = this._workbookSelections.get(unitId);
if (!wbSelection) {
const workbook = this._instanceSrv.getUnit<Workbook>(unitId);
@@ -190,7 +182,7 @@ export class SheetsSelectionsService extends RxDisposable {
throw new Error(`[SheetsSelectionsService]: cannot resolve unit with id "${unitId}"!`);
}
- wbSelection = new WorkbookSelections(workbook);
+ wbSelection = new WorkbookSelectionModel(workbook);
this._workbookSelections.set(unitId, wbSelection);
}
@@ -202,129 +194,5 @@ export class SheetsSelectionsService extends RxDisposable {
}
}
-/**
- * This class manages selections in a single workbook.
- */
-export class WorkbookSelections extends Disposable {
- private readonly _selectionMoveStart$ = new Subject<Nullable<ISelectionWithStyle[]>>();
- readonly selectionMoveStart$ = this._selectionMoveStart$.asObservable();
-
- private readonly _selectionMoving$ = new Subject<Nullable<ISelectionWithStyle[]>>();
- readonly selectionMoving$ = this._selectionMoving$.asObservable();
-
- readonly _selectionMoveEnd$ = new BehaviorSubject<ISelectionWithStyle[]>([]);
- readonly selectionMoveEnd$ = this._selectionMoveEnd$.asObservable();
-
- private readonly _selectionSet$ = new BehaviorSubject<ISelectionWithStyle[]>([]);
- readonly selectionSet$ = this._selectionSet$.asObservable();
-
- private readonly _beforeSelectionMoveEnd$ = new BehaviorSubject<ISelectionWithStyle[]>([]);
- readonly beforeSelectionMoveEnd$ = this._beforeSelectionMoveEnd$.asObservable();
-
- constructor(
- private readonly _workbook: Workbook
- ) {
- super();
- }
-
- override dispose(): void {
- super.dispose();
-
- this._beforeSelectionMoveEnd$.complete();
- this._selectionMoveEnd$.complete();
- this._selectionMoving$.complete();
- this._selectionMoveStart$.complete();
- }
-
- /** Clear all selections in this workbook. */
- clear(): void {
- this._worksheetSelections.clear();
- this._emitOnEnd([]);
- }
-
- addSelections(sheetId: string, selectionDatas: ISelectionWithStyle[]): void {
- const selections = this._ensureSheetSelection(sheetId);
- selections.push(...selectionDatas);
- this._emitOnEnd(selections);
- }
-
- /**
- * Set selectionDatas to _worksheetSelections, and emit selectionDatas by type.
- * If type is not specfied, this method would clear all existing selections.
- * @param sheetId
- * @param selectionDatas
- * @param type
- */
- setSelections(sheetId: string, selectionDatas: ISelectionWithStyle[] = [], type: SelectionMoveType): void {
- // selectionDatas should not be same variable as this._worksheetSelections !!!
- // but there are some place get selection from this._worksheetSelections and set selectionDatas(2nd parameter of this function ) cause selectionDatas is always []
- // see univer/pull/2909
- this._ensureSheetSelection(sheetId).length = 0;
- this._ensureSheetSelection(sheetId).push(...selectionDatas);
-
- switch (type) {
- case SelectionMoveType.MOVE_START:
- this._selectionMoveStart$.next(selectionDatas);
- break;
- case SelectionMoveType.MOVING:
- this._selectionMoving$.next(selectionDatas);
- break;
- case SelectionMoveType.MOVE_END:
- this._emitOnEnd(selectionDatas);
- break;
- case SelectionMoveType.ONLY_SET: {
- this._selectionSet$.next(selectionDatas);
- break;
- }
- default:
- this._emitOnEnd(selectionDatas);
- break;
- }
- }
-
- getCurrentSelections(): Readonly<ISelectionWithStyle[]> {
- return this._getCurrentSelections();
- }
-
- getSelectionOfWorksheet(sheetId: string): ISelectionWithStyle[] {
- if (!this._worksheetSelections.has(sheetId)) {
- return [];
- }
-
- return this._worksheetSelections.get(sheetId)!;
- }
-
- private _getCurrentSelections() {
- return this.getSelectionOfWorksheet(this._workbook.getActiveSheet()!.getSheetId());
- }
-
- getCurrentLastSelection(): Readonly<Nullable<ISelectionWithStyle & { primary: ISelectionCell }>> {
- const selectionData = this._getCurrentSelections();
- return selectionData[selectionData.length - 1] as Readonly<Nullable<ISelectionWithStyle & { primary: ISelectionCell }>>;
- }
-
- private _worksheetSelections = new Map<string, ISelectionWithStyle[]>();
-
- /**
- * Same as _getCurrentSelections(which return this._worksheetSelections), but this method would set [] if no selection.
- * @param sheetId
- * @returns this._worksheetSelections
- */
- private _ensureSheetSelection(sheetId: string): ISelectionWithStyle[] {
- let worksheetSelection = this._worksheetSelections.get(sheetId);
- if (!worksheetSelection) {
- worksheetSelection = [];
- this._worksheetSelections.set(sheetId, worksheetSelection);
- }
-
- return worksheetSelection;
- }
-
- private _emitOnEnd(selections: ISelectionWithStyle[]): void {
- this._beforeSelectionMoveEnd$.next(selections);
- this._selectionMoveEnd$.next(selections);
- }
-}
-
/** An context key to disable normal selections if its value is set to `true`. */
export const DISABLE_NORMAL_SELECTIONS = 'DISABLE_NORMAL_SELECTIONS';
diff --git a/packages/sheets/src/services/selections/type.ts b/packages/sheets/src/services/selections/type.ts
new file mode 100644
index 0000000000..6bf3d7d3ed
--- /dev/null
+++ b/packages/sheets/src/services/selections/type.ts
@@ -0,0 +1,30 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export interface ISelectionManagerSearchParam {
+ unitId: string;
+ sheetId: string;
+}
+
+export enum SelectionMoveType {
+ MOVE_START,
+ MOVING,
+ MOVE_END,
+ /**
+ * Events are not triggered by cursor movement
+ */
+ ONLY_SET,
+}
diff --git a/packages/ui/src/components/hooks/__tests__/observable.spec.ts b/packages/ui/src/components/hooks/__tests__/observable.spec.ts
index 626b46ed00..a0ccc5d67b 100644
--- a/packages/ui/src/components/hooks/__tests__/observable.spec.ts
+++ b/packages/ui/src/components/hooks/__tests__/observable.spec.ts
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-import { describe, expect, it } from 'vitest';
+import type { Observable } from 'rxjs';
import { act, renderHook } from '@testing-library/react-hooks';
+import { useState } from 'react';
import { of, Subject } from 'rxjs';
-import type { Observable } from 'rxjs';
-import { useState } from 'react';
+import { describe, expect, it } from 'vitest';
import { useObservable } from '../observable';
// New to testing React Hooks? You can refer to https://mayashavin.com/articles/test-react-hooks-with-vitest .