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: ref selection expand after bottom line is over top line, and ref selection fill area(primary cell) and formula editor should clear when change sheet. (#3104)

lumixe73fc3c9699d
diff --git a/packages/core/src/sheets/worksheet.ts b/packages/core/src/sheets/worksheet.ts
index 916a54b11f..7753bb5ccc 100644
--- a/packages/core/src/sheets/worksheet.ts
+++ b/packages/core/src/sheets/worksheet.ts
@@ -238,6 +238,16 @@ export class Worksheet {
return null;
}
+ /**
+ * Get cellData, includes cellData, customRender, markers, dataValidate, etc.
+ *
+ * WARNING: All sheet CELL_CONTENT interceptors will be called in this method, cause performance issue.
+ * example: this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT);
+ *
+ * @param row
+ * @param col
+ * @returns ICellDataForSheetInterceptor
+ */
getCell(row: number, col: number): Nullable<ICellDataForSheetInterceptor> {
if (row < 0 || col < 0) {
return null;
diff --git a/packages/drawing-ui/src/controllers/image-cropper.controller.ts b/packages/drawing-ui/src/controllers/image-cropper.controller.ts
index 4ef111a1af..4f9739cd0f 100644
--- a/packages/drawing-ui/src/controllers/image-cropper.controller.ts
+++ b/packages/drawing-ui/src/controllers/image-cropper.controller.ts
@@ -350,8 +350,9 @@ export class ImageCropperController extends Disposable {
private _getApplyObjectByCropObject(cropObject: ImageCropperObject): Nullable<Image> {
const cropOKey = cropObject.oKey;
const applyOKey = cropOKey.slice(0, cropOKey.length - 5);
-
- const applyObject = cropObject.getScene().getObject(applyOKey) as Image;
+ const scene = cropObject.getScene();
+ if (!scene) return null;
+ const applyObject = scene.getObject(applyOKey) as Image;
if (applyObject == null) {
return null;
}
diff --git a/packages/drawing-ui/src/views/crop/image-cropper-object.ts b/packages/drawing-ui/src/views/crop/image-cropper-object.ts
index 11962d9baa..5fc31b062c 100644
--- a/packages/drawing-ui/src/views/crop/image-cropper-object.ts
+++ b/packages/drawing-ui/src/views/crop/image-cropper-object.ts
@@ -242,8 +242,11 @@ export class ImageCropperObject<T extends IImageCropperObjectProps = IImageCropp
if (this._cacheCanvas != null) {
return;
}
+ const scene = this.getScene();
+ if (scene == null) return;
+
this._cacheCanvas = new Canvas();
- const engine = this.getScene().getEngine() as Engine;
+ const engine = scene.getEngine() as Engine;
this._cacheCanvas.setSize(engine.width, engine.height);
engine.onTransformChange$.subscribeEvent(() => {
diff --git a/packages/engine-render/src/base-object.ts b/packages/engine-render/src/base-object.ts
index 654198a8f7..04ff07eb6a 100644
--- a/packages/engine-render/src/base-object.ts
+++ b/packages/engine-render/src/base-object.ts
@@ -27,6 +27,8 @@ import type { IViewportInfo, Vector2 } from './basics/vector2';
import type { UniverRenderingContext } from './context';
import type { Layer } from './layer';
import type { ITransformerConfig } from './basics/transformer-config';
+import type { Scene } from './scene';
+import type { Engine } from './engine';
export const BASE_OBJECT_ARRAY = [
'top',
@@ -790,11 +792,11 @@ export abstract class BaseObject extends Disposable {
return props;
}
- getScene(): any {
+ getScene(): Nullable<Scene> {
let parent: any = this.parent;
if (parent == null) {
- return;
+ return null;
}
if (parent.classType === RENDER_CLASS_TYPE.SCENE) {
@@ -818,7 +820,7 @@ export abstract class BaseObject extends Disposable {
this.getScene()?.setCursor(val);
}
- getEngine(): any {
+ getEngine(): Nullable<Engine> {
let parent: any = this.getParent();
while (parent != null) {
if (parent.classType === RENDER_CLASS_TYPE.ENGINE) {
diff --git a/packages/engine-render/src/components/sheets/extensions/font.ts b/packages/engine-render/src/components/sheets/extensions/font.ts
index 264f778704..e5d796e39b 100644
--- a/packages/engine-render/src/components/sheets/extensions/font.ts
+++ b/packages/engine-render/src/components/sheets/extensions/font.ts
@@ -63,13 +63,12 @@ export class Font extends SheetExtension {
const { viewRanges = [], checkOutOfViewBound } = moreBoundsInfo;
const { stylesCache, dataMergeCache, overflowCache, worksheet } = spreadsheetSkeleton;
const { font: fontList } = stylesCache;
- if (!spreadsheetSkeleton || !worksheet) {
+ if (!spreadsheetSkeleton || !worksheet || !fontList) {
return;
}
const { rowHeightAccumulation, columnTotalWidth, columnWidthAccumulation, rowTotalHeight } =
spreadsheetSkeleton;
-
if (
!rowHeightAccumulation ||
!columnWidthAccumulation ||
@@ -79,197 +78,151 @@ export class Font extends SheetExtension {
) {
return;
}
+
ctx.save();
const scale = this._getScale(parentScale);
- fontList &&
- Object.keys(fontList).forEach((fontFormat: string) => {
- const fontObjectArray = fontList[fontFormat];
+ const renderFontByCell = (fontFormat: string) => {
+ const fontObjectArray = fontList[fontFormat];
- // Since the overflow can spill out to both the left and right sides,
- // we need to consider the content outside the viewBounds.
- // At the same time, there are also merged cells, so we need to merge the current
- // viewrange and a single merged area when calculating.
+ // Since the overflow can spill out to both the left and right sides,
+ // we need to consider the content outside the viewBounds.
+ // At the same time, there are also merged cells, so we need to merge the current
+ // viewrange and a single merged area when calculating.
- // Early exit from font condition
- // if row is not visible
+ // Early exit from font condition
+ // if row is not visible
- // If the current cell's style is not set to overflow, and the cell is not within the visible field of view, then exit early.
- // (the field of view needs to consider the impact of merged cells).
+ // If the current cell's style is not set to overflow, and the cell is not within the visible field of view, then exit early.
+ // (the field of view needs to consider the impact of merged cells).
- // If the diffRanges do not intersect with the startRow and endRow on the row, then exit early.
+ // If the diffRanges do not intersect with the startRow and endRow on the row, then exit early.
- // eslint-disable-next-line complexity
- fontObjectArray.forValue((rowIndex, columnIndex, docsConfig) => {
- if (!checkOutOfViewBound) {
- if (!inViewRanges(viewRanges!, rowIndex, columnIndex)) {
- return true;
- }
- }
- const cellInfo = this.getCellIndex(
- rowIndex,
- columnIndex,
- rowHeightAccumulation,
- columnWidthAccumulation,
- dataMergeCache
- );
- let { startY, endY, startX, endX } = cellInfo;
- const { isMerged, isMergedMainCell, mergeInfo } = cellInfo;
-
- if (isMerged) {
+ // eslint-disable-next-line complexity
+ fontObjectArray.forValue((rowIndex, columnIndex, docsConfig) => {
+ if (!checkOutOfViewBound) {
+ if (!inViewRanges(viewRanges!, rowIndex, columnIndex)) {
return true;
- } else {
- const visibleRow = spreadsheetSkeleton.worksheet.getRowVisible(rowIndex);
- const visibleCol = spreadsheetSkeleton.worksheet.getColVisible(columnIndex);
- if (!visibleRow || !visibleCol) return true;
}
-
- // If the merged cell area intersects with the current viewRange,
- // then merge it into the current viewRange.
- // After the merge, the font extension within the current viewBounds
- // also needs to be drawn once.
- // But at this moment, we cannot assume that it is not within the viewRanges and exit, because there may still be horizontal overflow.
- // At this moment, we can only exclude the cells that are not within the current row.
- const mergeTo = diffRanges && diffRanges.length > 0 ? diffRanges : viewRanges;
- const combineWithMergeRanges = mergeRangeIfIntersects(mergeTo, [mergeInfo]);
- if (!inRowViewRanges(combineWithMergeRanges, rowIndex)) {
+ }
+ const cellInfo = this.getCellIndex(
+ rowIndex,
+ columnIndex,
+ rowHeightAccumulation,
+ columnWidthAccumulation,
+ dataMergeCache
+ );
+ let { startY, endY, startX, endX } = cellInfo;
+ const { isMerged, isMergedMainCell, mergeInfo } = cellInfo;
+
+ if (isMerged) {
+ return true;
+ } else {
+ const visibleRow = spreadsheetSkeleton.worksheet.getRowVisible(rowIndex);
+ const visibleCol = spreadsheetSkeleton.worksheet.getColVisible(columnIndex);
+ if (!visibleRow || !visibleCol) return true;
+ }
+
+ // If the merged cell area intersects with the current viewRange,
+ // then merge it into the current viewRange.
+ // After the merge, the font extension within the current viewBounds
+ // also needs to be drawn once.
+ // But at this moment, we cannot assume that it is not within the viewRanges and exit, because there may still be horizontal overflow.
+ // At this moment, we can only exclude the cells that are not within the current row.
+ const mergeTo = diffRanges && diffRanges.length > 0 ? diffRanges : viewRanges;
+ const combineWithMergeRanges = mergeRangeIfIntersects(mergeTo, [mergeInfo]);
+ if (!inRowViewRanges(combineWithMergeRanges, rowIndex)) {
+ return true;
+ }
+
+ if (isMergedMainCell) {
+ startY = mergeInfo.startY;
+ endY = mergeInfo.endY;
+ startX = mergeInfo.startX;
+ endX = mergeInfo.endX;
+ }
+ /**
+ * Incremental content rendering for texture mapping
+ * If the diffRanges do not intersect with the startRow and endRow on the row, then exit early.
+ *
+ * If this cell is not within a merged region, the mergeInfo start and end values are just the cell itself.
+ */
+ if (diffRanges) {
+ if (!this.isRowInRanges(mergeInfo.startRow, mergeInfo.endRow, diffRanges)) {
return true;
}
-
- if (isMergedMainCell) {
- startY = mergeInfo.startY;
- endY = mergeInfo.endY;
- startX = mergeInfo.startX;
- endX = mergeInfo.endX;
- }
- /**
- * Incremental content rendering for texture mapping
- * If the diffRanges do not intersect with the startRow and endRow on the row, then exit early.
- *
- * If this cell is not within a merged region, the mergeInfo start and end values are just the cell itself.
- */
- if (diffRanges) {
- if (!this.isRowInRanges(mergeInfo.startRow, mergeInfo.endRow, diffRanges)) {
- return true;
- }
- }
-
- /**
- * Overflow can cause text truncation, so columns are not rendered incrementally.
- */
- // if (
- // !this.isRenderDiffRangesByColumn(mergeInfo.startColumn, diffRanges) &&
- // !this.isRenderDiffRangesByColumn(mergeInfo.endColumn, diffRanges)
- // ) {
- // return true;
- // }
-
- // If the cell is overflowing, but the overflowRectangle has not been set,
- // then overflowRectangle is set to undefined.
- const overflowRectangle = overflowCache.getValue(rowIndex, columnIndex);
- const { horizontalAlign, vertexAngle = 0, centerAngle = 0 } = docsConfig;
-
- // If it's neither an overflow nor within the current range,
- // then we can exit early (taking into account the range extension
- // caused by the merged cells).
- if (!overflowRectangle && !inViewRanges(combineWithMergeRanges, rowIndex, columnIndex)) {
- return true;
- }
-
- /**
- * https://github.com/dream-num/univer-pro/issues/334
- * When horizontal alignment is not set, the default alignment for rotation angles varies to accommodate overflow scenarios.
- */
- let horizontalAlignOverFlow = horizontalAlign;
- if (horizontalAlign === HorizontalAlign.UNSPECIFIED) {
- if (centerAngle === VERTICAL_ROTATE_ANGLE && vertexAngle === VERTICAL_ROTATE_ANGLE) {
- horizontalAlignOverFlow = HorizontalAlign.CENTER;
- } else if ((vertexAngle > 0 && vertexAngle !== VERTICAL_ROTATE_ANGLE) || vertexAngle === -VERTICAL_ROTATE_ANGLE) {
- horizontalAlignOverFlow = HorizontalAlign.RIGHT;
- }
+ }
+
+ /**
+ * Overflow can cause text truncation, so columns are not rendered incrementally.
+ */
+ // if (
+ // !this.isRenderDiffRangesByColumn(mergeInfo.startColumn, diffRanges) &&
+ // !this.isRenderDiffRangesByColumn(mergeInfo.endColumn, diffRanges)
+ // ) {
+ // return true;
+ // }
+
+ // If the cell is overflowing, but the overflowRectangle has not been set,
+ // then overflowRectangle is set to undefined.
+ const overflowRectangle = overflowCache.getValue(rowIndex, columnIndex);
+ const { horizontalAlign, vertexAngle = 0, centerAngle = 0 } = docsConfig;
+
+ // If it's neither an overflow nor within the current range,
+ // then we can exit early (taking into account the range extension
+ // caused by the merged cells).
+ if (!overflowRectangle && !inViewRanges(combineWithMergeRanges, rowIndex, columnIndex)) {
+ return true;
+ }
+
+ /**
+ * https://github.com/dream-num/univer-pro/issues/334
+ * When horizontal alignment is not set, the default alignment for rotation angles varies to accommodate overflow scenarios.
+ */
+ let horizontalAlignOverFlow = horizontalAlign;
+ if (horizontalAlign === HorizontalAlign.UNSPECIFIED) {
+ if (centerAngle === VERTICAL_ROTATE_ANGLE && vertexAngle === VERTICAL_ROTATE_ANGLE) {
+ horizontalAlignOverFlow = HorizontalAlign.CENTER;
+ } else if ((vertexAngle > 0 && vertexAngle !== VERTICAL_ROTATE_ANGLE) || vertexAngle === -VERTICAL_ROTATE_ANGLE) {
+ horizontalAlignOverFlow = HorizontalAlign.RIGHT;
}
+ }
- const cellData = worksheet.getCell(rowIndex, columnIndex) as ICellData & ISheetFontRenderExtension || {};
- if (cellData.fontRenderExtension?.isSkip) {
- return true;
- }
+ const cellData = worksheet.getCell(rowIndex, columnIndex) as ICellData & ISheetFontRenderExtension || {};
+ if (cellData.fontRenderExtension?.isSkip) {
+ return true;
+ }
- ctx.save();
- ctx.beginPath();
+ ctx.save();
+ ctx.beginPath();
- const rightOffset = cellData.fontRenderExtension?.rightOffset ?? 0;
- const leftOffset = cellData.fontRenderExtension?.leftOffset ?? 0;
- let isOverflow = true;
+ const rightOffset = cellData.fontRenderExtension?.rightOffset ?? 0;
+ const leftOffset = cellData.fontRenderExtension?.leftOffset ?? 0;
+ let isOverflow = true;
- if (vertexAngle === 0) {
- startX = startX + leftOffset;
- endX = endX - rightOffset;
+ if (vertexAngle === 0) {
+ startX = startX + leftOffset;
+ endX = endX - rightOffset;
- if (rightOffset !== 0 || leftOffset !== 0) {
- isOverflow = false;
- }
+ if (rightOffset !== 0 || leftOffset !== 0) {
+ isOverflow = false;
}
-
- const cellWidth = endX - startX;
- const cellHeight = endY - startY;
-
- /**
- * In scenarios with offsets, there is no need to respond to text overflow.
- */
- if (overflowRectangle && isOverflow) {
- const { startColumn, startRow, endColumn, endRow } = overflowRectangle;
- if (startColumn === endColumn && startColumn === columnIndex) {
- ctx.rectByPrecision(
- startX + 1 / scale,
- startY + 1 / scale,
- cellWidth - 2 / scale,
- cellHeight - 2 / scale
- );
- ctx.clip();
- // ctx.clearRectForTexture(
- // startX + 1 / scale,
- // startY + 1 / scale,
- // cellWidth - 2 / scale,
- // cellHeight - 2 / scale
- // );
- } else {
- if (horizontalAlignOverFlow === HorizontalAlign.CENTER) {
- this._clipRectangleForOverflow(
- ctx,
- startRow,
- endRow,
- startColumn,
- endColumn,
- scale,
- rowHeightAccumulation,
- columnWidthAccumulation
- );
- } else if (horizontalAlignOverFlow === HorizontalAlign.RIGHT) {
- this._clipRectangleForOverflow(
- ctx,
- startRow,
- rowIndex,
- startColumn,
- columnIndex,
- scale,
- rowHeightAccumulation,
- columnWidthAccumulation
- );
- } else {
- this._clipRectangleForOverflow(
- ctx,
- rowIndex,
- endRow,
- columnIndex,
- endColumn,
- scale,
- rowHeightAccumulation,
- columnWidthAccumulation
- );
- }
- }
- } else {
- ctx.rectByPrecision(startX + 1 / scale, startY + 1 / scale, cellWidth - 2 / scale, cellHeight - 2 / scale);
- // for normal cell, forbid text overflow cellarea
+ }
+
+ const cellWidth = endX - startX;
+ const cellHeight = endY - startY;
+
+ /**
+ * In scenarios with offsets, there is no need to respond to text overflow.
+ */
+ if (overflowRectangle && isOverflow) {
+ const { startColumn, startRow, endColumn, endRow } = overflowRectangle;
+ if (startColumn === endColumn && startColumn === columnIndex) {
+ ctx.rectByPrecision(
+ startX + 1 / scale,
+ startY + 1 / scale,
+ cellWidth - 2 / scale,
+ cellHeight - 2 / scale
+ );
ctx.clip();
// ctx.clearRectForTexture(
// startX + 1 / scale,
@@ -277,13 +230,61 @@ export class Font extends SheetExtension {
// cellWidth - 2 / scale,
// cellHeight - 2 / scale
// );
+ } else {
+ if (horizontalAlignOverFlow === HorizontalAlign.CENTER) {
+ this._clipRectangleForOverflow(
+ ctx,
+ startRow,
+ endRow,
+ startColumn,
+ endColumn,
+ scale,
+ rowHeightAccumulation,
+ columnWidthAccumulation
+ );
+ } else if (horizontalAlignOverFlow === HorizontalAlign.RIGHT) {
+ this._clipRectangleForOverflow(
+ ctx,
+ startRow,
+ rowIndex,
+ startColumn,
+ columnIndex,
+ scale,
+ rowHeightAccumulation,
+ columnWidthAccumulation
+ );
+ } else {
+ this._clipRectangleForOverflow(
+ ctx,
+ rowIndex,
+ endRow,
+ columnIndex,
+ endColumn,
+ scale,
+ rowHeightAccumulation,
+ columnWidthAccumulation
+ );
+ }
}
- ctx.translate(startX + FIX_ONE_PIXEL_BLUR_OFFSET, startY + FIX_ONE_PIXEL_BLUR_OFFSET);
- this._renderDocuments(ctx, docsConfig, startX, startY, endX, endY, rowIndex, columnIndex, overflowCache);
- ctx.closePath();
- ctx.restore();
- });
+ } else {
+ ctx.rectByPrecision(startX + 1 / scale, startY + 1 / scale, cellWidth - 2 / scale, cellHeight - 2 / scale);
+ // for normal cell, forbid text overflow cellarea
+ ctx.clip();
+ // ctx.clearRectForTexture(
+ // startX + 1 / scale,
+ // startY + 1 / scale,
+ // cellWidth - 2 / scale,
+ // cellHeight - 2 / scale
+ // );
+ }
+ ctx.translate(startX + FIX_ONE_PIXEL_BLUR_OFFSET, startY + FIX_ONE_PIXEL_BLUR_OFFSET);
+ this._renderDocuments(ctx, docsConfig, startX, startY, endX, endY, rowIndex, columnIndex, overflowCache);
+ ctx.closePath();
+ ctx.restore();
});
+ };
+
+ Object.keys(fontList).forEach(renderFontByCell);
ctx.restore();
}
diff --git a/packages/engine-render/src/components/sheets/sheet-skeleton.ts b/packages/engine-render/src/components/sheets/sheet-skeleton.ts
index 9887073ea8..eecdc99904 100644
--- a/packages/engine-render/src/components/sheets/sheet-skeleton.ts
+++ b/packages/engine-render/src/components/sheets/sheet-skeleton.ts
@@ -206,6 +206,11 @@ export const DEFAULT_PADDING_DATA = {
export const RENDER_RAW_FORMULA_KEY = 'RENDER_RAW_FORMULA';
+export interface ICacheItem {
+ bg: boolean;
+ border: boolean;
+}
+
export class SpreadsheetSkeleton extends Skeleton {
private _rowHeightAccumulation: number[] = [];
private _columnWidthAccumulation: number[] = [];
@@ -537,6 +542,10 @@ export class SpreadsheetSkeleton extends Skeleton {
return Math.min(height, MAXIMUM_ROW_HEIGHT);
}
+ /**
+ * Calculate data for row col & cell position, then update position value to this._rowHeaderWidth & this._rowHeightAccumulation & this._columnHeaderHeight & this._columnWidthAccumulation.
+ * @returns this
+ */
private _updateLayout() {
if (!this.dirty) {
return;
@@ -1580,7 +1589,7 @@ export class SpreadsheetSkeleton extends Skeleton {
// }
private _calculateStylesCache() {
- const dataMergeCache = this._dataMergeCache;
+ const dataMergeCaches = this._dataMergeCache;
const rowColumnSegment = this._rowColumnSegment;
const columnWidthAccumulation = this.columnWidthAccumulation;
const { startRow, endRow, startColumn, endColumn } = rowColumnSegment;
@@ -1589,18 +1598,20 @@ export class SpreadsheetSkeleton extends Skeleton {
return;
}
- for (const data of dataMergeCache) {
- this._setCellCache(data.startRow, data.startColumn, false, data);
+ for (const mergeRange of dataMergeCaches) {
+ this._setCellStylesCache(mergeRange.startRow, mergeRange.startColumn, {
+ mergeRange,
+ });
}
for (let r = startRow; r <= endRow; r++) {
for (let c = startColumn; c <= endColumn; c++) {
- this._setCellCache(r, c, false);
+ this._setCellStylesCache(r, c);
}
// 针对溢出的情况计算文本长度,可视范围左侧列
for (let c = 0; c < startColumn; c++) {
- this._setCellCache(r, c, true);
+ this._setCellStylesCache(r, c, { cacheItem: { bg: false, border: false } });
}
if (endColumn === 0) {
@@ -1609,7 +1620,7 @@ export class SpreadsheetSkeleton extends Skeleton {
// 针对溢出的情况计算文本长度,可视范围右侧列
for (let c = endColumn + 1; c < columnWidthAccumulation.length; c++) {
- this._setCellCache(r, c, true);
+ this._setCellStylesCache(r, c, { cacheItem: { bg: false, border: false } });
}
}
@@ -1648,13 +1659,15 @@ export class SpreadsheetSkeleton extends Skeleton {
}
// eslint-disable-next-line complexity
- private _setCellCache(r: number, c: number, skipBackgroundAndBorder: boolean, mergeRange?: IRange) {
- const needsRendering = this._renderedCellCache.getValue(r, c);
-
+ private _setCellStylesCache(r: number, c: number, options?: {
+ mergeRange?: IRange;
+ cacheItem?: ICacheItem;
+ }) {
if (r === -1 || c === -1) {
return true;
}
+ const needsRendering = this._renderedCellCache.getValue(r, c);
if (needsRendering === false) {
this._makeDocumentSkeletonDirty(r, c);
return true;
@@ -1663,6 +1676,7 @@ export class SpreadsheetSkeleton extends Skeleton {
/**
* TODO: DR-Univer getCellRaw for slide demo, the implementation approach will be changed in the future.
*/
+ // const cell = this.worksheet.getCellRaw(r, c); // getCellRaw would be faster but doesn't contain condition format info.
const cell = this.worksheet.getCell(r, c) || this.worksheet.getCellRaw(r, c);
if (!cell) {
return true;
@@ -1692,7 +1706,9 @@ export class SpreadsheetSkeleton extends Skeleton {
// const style = getStyle(styles, cell);
const style = this._styles.getStyleByCell(cell);
- if (!skipBackgroundAndBorder && style && style.bg && style.bg.rgb) {
+ // by default, style cache should includes border and background info.
+ const cacheItem = options?.cacheItem || { bg: true, border: true };
+ if (cacheItem.bg && style && style.bg && style.bg.rgb) {
const rgb = style.bg.rgb;
if (!cache.background![rgb]) {
cache.background![rgb] = new ObjectMatrix();
@@ -1706,7 +1722,8 @@ export class SpreadsheetSkeleton extends Skeleton {
cache.backgroundPositions?.setValue(r, c, cellInfo);
}
- if (!skipBackgroundAndBorder && style && style.bd) {
+ if (cacheItem.border && style && style.bd) {
+ const mergeRange = options?.mergeRange;
if (mergeRange) {
this._setMergeBorderProps(BORDER_TYPE.TOP, cache, mergeRange);
this._setMergeBorderProps(BORDER_TYPE.BOTTOM, cache, mergeRange);
@@ -1777,7 +1794,8 @@ export class SpreadsheetSkeleton extends Skeleton {
this._calculateOverflowCell(r, c, config);
}
- if (!skipBackgroundAndBorder) {
+ // same as: if (!skipBackgroundAndBorder) {...}
+ if (cacheItem.bg || cacheItem.border) {
this._renderedCellCache.setValue(r, c, false);
} else {
this._renderedCellCache.setValue(r, c, true);
diff --git a/packages/engine-render/src/components/sheets/spreadsheet.ts b/packages/engine-render/src/components/sheets/spreadsheet.ts
index 338bf6843a..36a77e762f 100644
--- a/packages/engine-render/src/components/sheets/spreadsheet.ts
+++ b/packages/engine-render/src/components/sheets/spreadsheet.ts
@@ -108,8 +108,6 @@ export class Spreadsheet extends SheetComponent {
/**
* draw by viewport
- * cacheBound ---> viewBound
- * diffCacheBounds ---> diffRange
* @param ctx
* @param viewportInfo
*/
diff --git a/packages/engine-render/src/engine.ts b/packages/engine-render/src/engine.ts
index c8542d6410..35c0055880 100644
--- a/packages/engine-render/src/engine.ts
+++ b/packages/engine-render/src/engine.ts
@@ -281,8 +281,6 @@ export class Engine extends ThinEngine<Scene> {
this._activeRenderLoops = [];
this.getCanvas().dispose();
- // this._canvas = null; // 不应该这么做, 上面已经调用了 _canvas 的 dispose 方法
- // 并且 idleCallback --> resize 时需要 _canvas 对象
this.onTransformChange$.complete();
this._beginFrame$.complete();
diff --git a/packages/engine-render/src/scene.ts b/packages/engine-render/src/scene.ts
index 2b3318a6ea..ed264b87f9 100644
--- a/packages/engine-render/src/scene.ts
+++ b/packages/engine-render/src/scene.ts
@@ -34,6 +34,7 @@ import type { ThinEngine } from './thin-engine';
import { ThinScene } from './thin-scene';
import type { Viewport } from './viewport';
import type { ITransformerConfig } from './basics/transformer-config';
+import type { Engine } from './engine';
export class Scene extends ThinScene {
private _layers: Layer[] = [];
@@ -240,8 +241,10 @@ export class Scene extends ThinScene {
}
/**
- * scale to value, absolute
- * setTransform ---> viewport._updateScrollBarPosByViewportScroll ---> scrollTo
+ * Set scale, and then emit event to update Viewport scroll state.
+ * @param scaleX
+ * @param scaleY
+ * @returns Scene
*/
scale(scaleX?: number, scaleY?: number) {
const preScaleX = this.scaleX;
@@ -295,9 +298,7 @@ export class Scene extends ThinScene {
}
/**
- * This sequence will initiate a series of updates:
- * scene._setTransForm --> viewport@resetCanvasSizeAndUpdateScrollBar ---> scrollTo ---> limitedScroll ---> onScrollBeforeObserver ---> setScrollInfo
- * scrollInfo needs accurate scene width & height, limitedScroll depends on scene & engine's width & height
+ * Reset canvas size and update scroll
* @param state
*/
transformByState(state: ISceneTransformState) {
@@ -327,9 +328,9 @@ export class Scene extends ThinScene {
return this._parent;
}
- override getEngine(): Nullable<ThinEngine<Scene>> {
+ override getEngine(): Nullable<Engine> {
if (this._parent.classType === RENDER_CLASS_TYPE.ENGINE) {
- return this._parent as ThinEngine<Scene>;
+ return this._parent as Engine;
}
let parent: any = this._parent; // type: SceneViewer | Engine | BaseObject | Scene
@@ -376,6 +377,12 @@ export class Scene extends ThinScene {
return this;
}
+ /**
+ * Add object to Layer (Layer is specified by zIndex).
+ * @param o
+ * @param zIndex layer index
+ * @returns scene
+ */
override addObject(o: BaseObject, zIndex: number = 1) {
this.getLayer(zIndex)?.addObject(o);
this._addObject$.next(this);
diff --git a/packages/engine-render/src/shape/rich-text.ts b/packages/engine-render/src/shape/rich-text.ts
index 7ae1b6cf74..359f7d98da 100644
--- a/packages/engine-render/src/shape/rich-text.ts
+++ b/packages/engine-render/src/shape/rich-text.ts
@@ -351,12 +351,11 @@ export class RichText extends BaseObject {
}
/**
- *
- * it should be invoked when _documentData changed.
- * _documentData changed ---> update _documentSkeleton & _documentSkeleton
- *
- * now it is invoked when transformByState(change editor size) & end of editing
+ * After changing editor size & end of editing, update skeleton of doc.
*/
+ // TODO: This method should be invoked when _documentData changed.
+ // _documentData changed ---> update _documentSkeleton & _documentSkeleton
+ // now it is invoked when transformByState(change editor size) & end of editing
refreshDocumentByDocData() {
const docModel = this.documentModel = new DocumentDataModel(this._documentData);
const docViewModel = new DocumentViewModel(docModel);
diff --git a/packages/engine-render/src/viewport.ts b/packages/engine-render/src/viewport.ts
index c6cafd59c4..1a4225fd26 100644
--- a/packages/engine-render/src/viewport.ts
+++ b/packages/engine-render/src/viewport.ts
@@ -463,10 +463,6 @@ export class Viewport {
this._active = false;
}
- /**
- * invoked when canvas element size change
- * engineResizeObserver --> engine.resizeBySize --> scene._setTransForm
- */
resetCanvasSizeAndUpdateScroll() {
this._resizeCacheCanvas();
this._updateScrollByViewportScrollValue();
@@ -527,33 +523,18 @@ export class Viewport {
}
/**
- * There are serval cases to call this method.
- * the most common case is scrolling. Other situations include:
- * 1. changing the frozen row & col settings
- * 2. changing curr skeleton
- * 3. changing selection which cross viewport
- * 4. changing the viewport size (also include change window size)
- * 5. changing the scroll bar position
- *
- * when scrolling by trackpad:
- * scene.input-manager@_onMouseWheel --> scene@triggerMouseWheel --> [email protected]$.add -->
- * set-scroll.command.ts --> scroll.operation.ts -->
- * scrollManagerService.setScrollInfoAndEmitEvent
- *
- * when change skelenton:
- * _currentSkeletonBefore$ ---> scroll.render-controller@_updateSceneSize --> setSearchParam --> scene@_setTransForm ---> viewport.resetCanvasSizeAndUpdateScrollBar ---> scrollToXX
- * --> onScrollAfterObserver.notifyObservers --> scroll.render-controller@onScrollAfterObserver ---> setScrollInfoToCurrSheetWithoutNotify ---> sms._setScrollInfo
- *
- * _currentSkeleton$ ---> selection.render-controller ---> formula@_autoScroll ---> viewport.resize ---> get scrollXY by viewportScrollXY ---> scrollTo
- * _currentSkeleton$ ---> selection.render-controller ---> setCurrentSelection ---> formula@_autoScroll ---> scrollTo
- * _currentSkeleton$ ---> freeze.render-controller@_refreshFreeze --> viewport.resize ---> scrollTo ---> _scroll
- *
- * Debug
- * window.scene.getViewports()[0].scrollTo({x: 14.2, y: 1.8}, true)
- *
- * @param pos
- *
+ * ScrollBar scroll to certain position.
+ * @param pos position of scrollBar
*/
+ // There are serval cases to call this method.
+ // the most common case is scrolling. Other situations include:
+ // 1. changing the frozen row & col settings
+ // 2. changing curr skeleton
+ // 3. changing selection which cross viewport
+ // 4. changing the viewport size (also include change window size)
+ // 5. changing the scroll bar position
+ // Debug
+ // window.scene.getViewports()[0].scrollTo({x: 14.2, y: 1.8}, true)
scrollToBarPos(pos: Partial<IScrollBarPosition>) {
return this._scrollToBarPosCore(pos);
}
@@ -587,6 +568,12 @@ export class Viewport {
});
}
+ /**
+ * Viewport scroll to certain position.
+ * @param pos
+ * @param isTrigger
+ * @returns IViewportScrollPosition
+ */
scrollToViewportPos(pos: Partial<IViewportScrollPosition>, isTrigger = true) {
if (!this._scrollBar || this.isActive === false) {
return;
@@ -710,10 +697,12 @@ export class Viewport {
return this._scrollBar;
}
- // scrollTo ---> _scroll ---> onScrollAfter$.next ---> scroll.render-controller@updateScroll
- // scrollTo ---> _scroll ---> onScrollAfter$.next ---> freeze.render-controller@updateScroll
+ /**
+ * Just record state of scroll. This method won't scroll viewport and scrollbar.
+ * @param current
+ * @returns Viewport
+ */
updateScrollVal(current: Partial<IScrollObserverParam>) {
- // scrollvalue for scrollbar, when rows over 5000(big sheet), deltaScrollY always 0 when scrolling. Do not use this value to judge scrolling
// this._deltaScrollX = this.scrollX - this._preScrollX;
// this._deltaScrollY = this.scrollY - this._preScrollY;
this._preScrollX = this.scrollX;
@@ -763,8 +752,7 @@ export class Viewport {
}
/**
- * call stack: engine.renderLoop ---> scene.render ---> layer.render ---> viewport.render
- * that means each layer call all viewports to render
+ * Render function in each render loop.
* @param parentCtx parentCtx is cacheCtx from layer when layer._allowCache is true
* @param objects
* @param isMaxLayer
@@ -1252,7 +1240,7 @@ export class Viewport {
}
/**
- * This method will be invoked when viewport is resizing and removing rol & col
+ * Update scroll when viewport is resizing and removing rol & col
*/
private _updateScrollByViewportScrollValue() {
// zoom.render-controller ---> scene._setTransform --> _updateScrollBarPosByViewportScroll
diff --git a/packages/sheets-data-validation/src/widgets/dropdown-widget.ts b/packages/sheets-data-validation/src/widgets/dropdown-widget.ts
index f5bf984534..42b92987fd 100644
--- a/packages/sheets-data-validation/src/widgets/dropdown-widget.ts
+++ b/packages/sheets-data-validation/src/widgets/dropdown-widget.ts
@@ -125,6 +125,7 @@ function calcPadding(cellWidth: number, cellHeight: number, fontWidth: number, f
paddingTop = realMargin;
break;
}
+ paddingTop = Math.max(MARGIN_V, paddingTop);
let paddingLeft = 0;
switch (ht) {
@@ -138,6 +139,7 @@ function calcPadding(cellWidth: number, cellHeight: number, fontWidth: number, f
default:
break;
}
+ paddingLeft = Math.max(MARGIN_H, paddingLeft);
return {
paddingLeft,
diff --git a/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts b/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
index 534f6de631..c9ce2155cf 100644
--- a/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
+++ b/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts
@@ -15,10 +15,10 @@
*/
import type { ICellDataForSheetInterceptor, ICommandInfo, IObjectMatrixPrimitiveType, IRange, IRowAutoHeightInfo, Nullable, Workbook, Worksheet } from '@univerjs/core';
-import {
- ColorKit,
+import { ColorKit,
Disposable,
ICommandService,
+ ILogService,
Inject,
ObjectMatrix,
Rectangle,
@@ -31,7 +31,7 @@ import {
SetArrayFormulaDataMutation,
SetFormulaCalculationResultMutation,
} from '@univerjs/engine-formula';
-import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import type { IRenderContext, IRenderModule, SpreadsheetSkeleton } from '@univerjs/engine-render';
import { IRenderManagerService } from '@univerjs/engine-render';
import type { ISetColHiddenMutationParams, ISetColVisibleMutationParams, ISetRowHiddenMutationParams, ISetRowVisibleMutationParams, ISetWorksheetColWidthMutationParams, ISetWorksheetRowAutoHeightMutationParams, ISetWorksheetRowHeightMutationParams } from '@univerjs/sheets';
import { SetColHiddenMutation, SetColVisibleMutation, SetRowHiddenMutation, SetRowVisibleMutation, SetWorksheetColWidthMutation, SetWorksheetRowAutoHeightMutation, SetWorksheetRowHeightMutation } from '@univerjs/sheets';
@@ -53,6 +53,7 @@ const REFRESH_ARRAY_SHAPE_MUTATIONS = [
export class FormulaEditorShowController extends Disposable implements IRenderModule {
private _previousShape: Nullable<SelectionShape>;
+ private _skeleton: SpreadsheetSkeleton;
constructor(
private readonly _context: IRenderContext<Workbook>,
@@ -61,16 +62,40 @@ export class FormulaEditorShowController extends Disposable implements IRenderMo
@Inject(ThemeService) private readonly _themeService: ThemeService,
@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
@Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,
- @ICommandService private readonly _commandService: ICommandService
+ @ICommandService private readonly _commandService: ICommandService,
+ @ILogService private readonly _logService: ILogService
) {
super();
+ this._initSkeletonChangeListener();
this._initInterceptorEditorStart();
-
this._commandExecutedListener();
// Do not intercept v:null and add t: CellValueType.NUMBER. When the cell =TODAY() is automatically filled, the number format will recognize the Number type and parse it as 1900-01-00 date format.
}
+ private _initSkeletonChangeListener() {
+ this.disposeWithMe(
+ this._sheetSkeletonManagerService.currentSkeleton$.subscribe((param) => {
+ if (param == null) {
+ this._logService.error('[FormulaEditorShowController]: should not receive currentSkeleton$ as null!');
+ } else {
+ const { skeleton } = param;
+ const prevSheetId = this._skeleton?.worksheet?.getSheetId();
+ this._changeRuntime(skeleton);
+
+ // change to another sheet
+ if (prevSheetId !== skeleton.worksheet.getSheetId()) {
+ this._removeArrayFormulaRangeShape();
+ }
+ }
+ })
+ );
+ }
+
+ protected _changeRuntime(skeleton: SpreadsheetSkeleton) {
+ this._skeleton = skeleton;
+ }
+
private _initInterceptorEditorStart() {
this.disposeWithMe(
toDisposable(
diff --git a/packages/sheets-formula/src/controllers/prompt.controller.ts b/packages/sheets-formula/src/controllers/prompt.controller.ts
index 30730b9fe2..a986bdc2b2 100644
--- a/packages/sheets-formula/src/controllers/prompt.controller.ts
+++ b/packages/sheets-formula/src/controllers/prompt.controller.ts
@@ -171,7 +171,7 @@ export class PromptController extends Disposable {
}
/**
- * If there are multiple sheet instances, we should enable or disable all of them.
+ * For multiple sheet instances.
*/
private get _allSelectionRenderServices(): RefSelectionsRenderService[] {
return this._renderManagerService.getAllRenderersOfType(UniverInstanceType.UNIVER_SHEET)
@@ -219,25 +219,15 @@ export class PromptController extends Disposable {
private _initialize(): void {
this._initialCursorSync();
-
this._initAcceptFormula();
-
this._initialFormulaTheme();
-
this._initSelectionsEndListener();
-
this._closeRangePromptWhenEditorInvisible();
-
this._initialEditorInputChange();
-
this._commandExecutedListener();
-
this._cursorStateListener();
-
this._inputFormulaListener();
-
this._userMouseListener();
-
this._initialChangeEditor();
}
@@ -410,9 +400,9 @@ export class PromptController extends Disposable {
d.dispose();
if (selections.length === 0) return;
-
- // Update rendering in each selection render service.
- this._allSelectionRenderServices.forEach((r) => this._updateRefSelectionStyle(r, this._isSelectionMovingRefSelections));
+ // Theme color should be set when SelectionControl is created, it's too late to set theme color at selecitonEnd(pointerup).
+ // The logic below has been moved to syncToEditor.
+ // this._allSelectionRenderServices.forEach((r) => this._updateRefSelectionStyle(r, this._isSelectionMovingRefSelections));
const selectionControls = this._allSelectionRenderServices.map((s) => s.getSelectionControls()).flat();
selectionControls.forEach((c) => {
@@ -425,9 +415,9 @@ export class PromptController extends Disposable {
}));
}
- // #region - Selecting Mode: user can use cursor to select a range on the canvas and move the selection
- // with keyboard shortcuts
-
+ /**
+ * For interaction with mouse & keyboard shortcuts on spreadsheet. Not in formula editor.
+ */
private _updateSelecting(selectionsWithStyles: ISelectionWithStyle[], performInsertion: boolean = false) {
if (selectionsWithStyles.length === 0) return;
if (this._editorService.selectionChangingState() && !this._formulaPromptService.isLockedSelectionInsert()) return;
@@ -517,8 +507,6 @@ export class PromptController extends Disposable {
this._previousRangesCount = selections.length;
}
- // #endregion
-
private _initAcceptFormula() {
this.disposeWithMe(
this._formulaPromptService.acceptFormulaName$.subscribe((formulaString: string) => {
@@ -873,6 +861,9 @@ export class PromptController extends Disposable {
const { textRuns, refSelections } = this._buildTextRuns(sequenceNodes);
bodyList.forEach((body) => (body!.textRuns = textRuns));
this._allSelectionRenderServices.forEach((r) => this._refreshSelectionForReference(r, refSelections));
+
+ // No need set refSelection styles here. this._syncToEditor has same effect.
+ // this._allSelectionRenderServices.forEach((r) => this._updateRefSelectionStyle(r, this._isSelectionMovingRefSelections));
}
this._refreshFormulaAndCellEditor(unitIds);
@@ -1194,7 +1185,9 @@ export class PromptController extends Disposable {
}
/**
+ * Update Editor formula text in prompt editor by current selection in spreadsheet.
* Restore the sequenceNode generated by the lexer to the text in the editor, and set the cursor position.
+ *
* @param sequenceNodes
* @param textSelectionOffset
*/
@@ -1207,19 +1200,17 @@ export class PromptController extends Disposable {
fromSelection = true
) {
let dataStream = generateStringWithSequence(sequenceNodes);
-
const { textRuns, refSelections } = this._buildTextRuns(sequenceNodes);
-
this._isSelectionMovingRefSelections = refSelections;
- const activeRange = this._textSelectionManagerService.getActiveTextRangeWithStyle();
+ // Get theme color from prompt formula editor when creating a new selection.
+ this._allSelectionRenderServices.forEach((r) => this._updateRefSelectionStyle(r, this._isSelectionMovingRefSelections));
+ const activeRange = this._textSelectionManagerService.getActiveTextRangeWithStyle();
if (activeRange == null) {
return;
}
- const { collapsed, style } = activeRange;
-
this._currentInsertRefStringIndex = textSelectionOffset;
if (editorUnitId == null) {
@@ -1246,6 +1237,7 @@ export class PromptController extends Disposable {
offset = 0;
}
+ const { collapsed, style } = activeRange;
if (canUndo) {
this._commandService.executeCommand(ReplaceContentCommand.id, {
unitId: editorUnitId,
@@ -1495,7 +1487,7 @@ export class PromptController extends Disposable {
// const { unitId, sheetId } = toRange;
this._formulaPromptService.enableLockedSelectionChange();
- const id = selectionControl.selectionStyle?.id;
+ const id = selectionControl.currentStyle?.id;
if (!id || !Tools.isStringNumber(id)) {
return;
}
diff --git a/packages/sheets-formula/src/services/render-services/ref-selections.render-service.ts b/packages/sheets-formula/src/services/render-services/ref-selections.render-service.ts
index 1a81c94bcd..b874b701f3 100644
--- a/packages/sheets-formula/src/services/render-services/ref-selections.render-service.ts
+++ b/packages/sheets-formula/src/services/render-services/ref-selections.render-service.ts
@@ -18,7 +18,7 @@ import type { IDisposable, Nullable, Workbook } from '@univerjs/core';
import { DisposableCollection, Inject, Injector, RANGE_TYPE, ThemeService, toDisposable } from '@univerjs/core';
import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule } from '@univerjs/engine-render';
import { ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
-import { convertSelectionDataToRange, getNormalSelectionStyle, IRefSelectionsService, type ISelectionWithCoordAndStyle, type ISelectionWithStyle, type SheetsSelectionsService, type WorkbookSelections } from '@univerjs/sheets';
+import { convertSelectionDataToRange, getNormalSelectionStyle, IRefSelectionsService, type ISelectionWithCoordAndStyle, type ISelectionWithStyle, SelectionMoveType, type SheetsSelectionsService, type WorkbookSelections } from '@univerjs/sheets';
import { attachSelectionWithCoord, BaseSelectionRenderService, checkInHeaderRanges, getAllSelection, getCoordByOffset, getSheetObject, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
import { IShortcutService } from '@univerjs/ui';
@@ -28,6 +28,9 @@ import { IShortcutService } from '@univerjs/ui';
*
* Not that this service works with Uni-mode, which means it should be able to deal with multi render unit
* and handle selections on them, though each at a time.
+ *
+ *
+ *
*/
export class RefSelectionsRenderService extends BaseSelectionRenderService implements IRenderModule {
private readonly _workbookSelections: WorkbookSelections;
@@ -55,7 +58,7 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple
this._initSkeletonChangeListener();
this._initUserActionSyncListener();
- this._setStyle(getDefaultRefSelectionStyle(this._themeService));
+ this._setSelectionStyle(getDefaultRefSelectionStyle(this._themeService));
this._remainLastEnabled = true; // For ref range selections, we should always remain others.
}
@@ -134,13 +137,14 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple
}));
listenerDisposables.add(spreadsheetLeftTopPlaceholder?.onPointerDown$.subscribeEvent((evt: IPointerEvent | IMouseEvent, state) => {
- this._reset(); // remove all other selections
+ // remove all other selections
+ this._reset();
const skeleton = this._sheetSkeletonManagerService.getCurrent()!.skeleton;
const selectionWithStyle = getAllSelection(skeleton);
const selectionData = this.attachSelectionWithCoord(selectionWithStyle);
this._addSelectionControlBySelectionData(selectionData);
- this.refreshSelectionMoveStart();
+ this._selectionMoveStart$.next(this.getSelectionDataWithStyle());
if (evt.button !== 2) {
state.stopPropagation();
@@ -150,19 +154,30 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple
return listenerDisposables;
}
+ /**
+ * Update selectionModel in this._workbookSelections by user action in spreadsheet area.
+ */
private _initUserActionSyncListener() {
- this.disposeWithMe(this.selectionMoveEnd$.subscribe((params) => this._updateSelections(params)));
+ this.disposeWithMe(this.selectionMoveStart$.subscribe((selectionDataWithStyle) => {
+ this._updateSelections(selectionDataWithStyle, SelectionMoveType.MOVE_START);
+ }));
+ this.disposeWithMe(this.selectionMoving$.subscribe((selectionDataWithStyle) => {
+ this._updateSelections(selectionDataWithStyle, SelectionMoveType.MOVING);
+ }));
+ this.disposeWithMe(this.selectionMoveEnd$.subscribe((selectionDataWithStyle) => {
+ this._updateSelections(selectionDataWithStyle, SelectionMoveType.MOVE_END);
+ }));
}
- private _updateSelections(selectionDataWithStyleList: ISelectionWithCoordAndStyle[]) {
+ private _updateSelections(selectionDataWithStyleList: ISelectionWithCoordAndStyle[], type: SelectionMoveType) {
const workbook = this._context.unit;
const sheetId = workbook.getActiveSheet()!.getSheetId();
if (selectionDataWithStyleList.length === 0) return;
-
this._workbookSelections.setSelections(
sheetId,
- selectionDataWithStyleList.map((selectionDataWithStyle) => convertSelectionDataToRange(selectionDataWithStyle))
+ selectionDataWithStyleList.map((selectionDataWithStyle) => convertSelectionDataToRange(selectionDataWithStyle)),
+ type
);
}
@@ -186,6 +201,7 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple
// changing sheet is not the only way cause currentSkeleton$ emit, a lot of cmds will emit currentSkeleton$
// COMMAND_LISTENER_SKELETON_CHANGE ---> currentSkeleton$.next
// 'sheet.mutation.set-worksheet-row-auto-height' is one of COMMAND_LISTENER_SKELETON_CHANGE
+ // dv render controller would cause row auto height, this._autoHeightController.getUndoRedoParamsOfAutoHeight
this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe((param) => {
if (!param) {
return;
@@ -195,6 +211,7 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple
const { scene } = this._context;
const viewportMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
+ // changing sheet
if (this._skeleton && this._skeleton.worksheet.getSheetId() !== skeleton.worksheet.getSheetId()) {
this._reset();
}
@@ -231,9 +248,9 @@ export class RefSelectionsRenderService extends BaseSelectionRenderService imple
*/
function getDefaultRefSelectionStyle(themeService: ThemeService) {
const style = getNormalSelectionStyle(themeService);
- style.strokeDash = 8;
style.hasAutoFill = false;
style.hasRowHeader = false;
style.hasColumnHeader = false;
+ 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-ui/src/controllers/render-controllers/freeze.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts
index d395dfb085..948e77fd90 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/freeze.render-controller.ts
@@ -1609,10 +1609,5 @@ export class HeaderFreezeRenderController extends Disposable implements IRenderM
this._updateViewport(startRow, startColumn, ySplit, xSplit, resetScroll);
this._getSheetObject()?.spreadsheet.makeForceDirty();
-
- // no need to set viewport markForceDirty again
- // when change freeze area ---> viewport.resize ---> viewport.markForceDity()
- // this._getSheetObject()?.spreadsheet.makeForceDirty();
- // this._getSheetObject()?.scene.getViewports().forEach(vp => vp.makeForceDirty());
}
}
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 7cbdc36f6d..a66dd085ff 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
@@ -162,9 +162,6 @@ export class SheetsScrollRenderController extends Disposable implements IRenderM
//#region scrollInfo$ subscriber ---> viewport.scrollTo
this.disposeWithMe(
toDisposable(
- // wheel event --> set-scroll.command('sheet.operation.set-scroll') --> scroll.operation.ts -->
- // scrollManagerService.setScrollInfoAndEmitEvent ---> scrollManagerService.setScrollInfo(raw value, may be negative) &&
- // _notifyCurrentScrollInfo
this._scrollManagerService.rawScrollInfo$.subscribe((rawScrollInfo: Nullable<IScrollState>) => {
const skeleton = this._sheetSkeletonManagerService.getCurrent()?.skeleton;
if (!skeleton) return;
diff --git a/packages/sheets-ui/src/controllers/render-controllers/zoom.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/zoom.render-controller.ts
index f2259202e6..6f3dbac23a 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/zoom.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/zoom.render-controller.ts
@@ -92,11 +92,14 @@ export class SheetsZoomRenderController extends Disposable implements IRenderMod
if (!worksheet) return;
const zoomRatio = worksheet.getZoomRatio() || 1;
- // viewport.resize --> setScrollInfo
this._updateViewZoom(zoomRatio);
}));
}
+ /**
+ * Zoom scene, resize viewport and then setScrollInfo
+ * @param zoomRatio
+ */
private _updateViewZoom(zoomRatio: number) {
const sheetObject = this._getSheetObject();
sheetObject?.scene.scale(zoomRatio, zoomRatio);
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 b48a62cb62..8b186bc17b 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
@@ -29,7 +29,7 @@ import { createIdentifier, Disposable, InterceptorManager, makeCellToSelection,
import type { IMouseEvent, IPointerEvent, IRenderModule, Scene, SpreadsheetSkeleton, Viewport } from '@univerjs/engine-render';
import { ScrollTimer, ScrollTimerType, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
import type { ISelectionStyle, ISelectionWithCoordAndStyle, ISelectionWithStyle } from '@univerjs/sheets';
-import { getNormalSelectionStyle, transformCellDataToSelectionData } from '@univerjs/sheets';
+import { getNormalSelectionStyle as getDefaultNormalSelectionStyle, transformCellDataToSelectionData } from '@univerjs/sheets';
import type { IShortcutService } from '@univerjs/ui';
import type { Observable, Subscription } from 'rxjs';
import { BehaviorSubject, Subject } from 'rxjs';
@@ -142,12 +142,6 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
// #endregion
protected readonly _selectionMoveEnd$ = new BehaviorSubject<ISelectionWithCoordAndStyle[]>([]);
-
- /**
- * trigger when selection move end(pointerup)
- * and then update selection model in selectionManagerService
- * selectionMoveEnd$ ---> _updateSelections --> [email protected]
- */
readonly selectionMoveEnd$ = this._selectionMoveEnd$.asObservable();
protected readonly _selectionMoving$ = new Subject<ISelectionWithCoordAndStyle[]>();
readonly selectionMoving$ = this._selectionMoving$.asObservable();
@@ -172,7 +166,7 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
protected readonly _sheetSkeletonManagerService: SheetSkeletonManagerService
) {
super();
- this._resetStyle();
+ this._resetSelectionStyle();
this._initMoving();
}
@@ -186,12 +180,15 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
}));
}
- protected _setStyle(style: ISelectionStyle) {
+ protected _setSelectionStyle(style: ISelectionStyle) {
this._selectionStyle = style;
}
- protected _resetStyle() {
- this._setStyle(getNormalSelectionStyle(this._themeService));
+ /**
+ * Reset this._selectionStyle to default normal selection style
+ */
+ protected _resetSelectionStyle() {
+ this._setSelectionStyle(getDefaultNormalSelectionStyle(this._themeService));
}
/** @deprecated This should not be provided by the selection render service. */
@@ -204,42 +201,19 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
}
/**
- * add a selection
- *
- * in PC:init & pointerup would call this function.
- *
- * init
- * selectionController@_initSkeletonChangeListener --> selectionManagerService.add --> selectionManagerService._selectionMoveEnd$ --> this.addControlToCurrentByRangeData
- *
- * selectionMoveEnd$ --> this.addSelectionControlBySelectionData
- *
- *
- *
- * pointer
- * engine@_pointerDownEvent --> spreadsheet?.onPointerDownObserve --> eventTrigger --> scene@disableEvent() --> then scene.input-manager currentObject is always scene until scene@enableEvent.
- * engine@_pointerUpEvent --> scene.input-manager@_onPointerUp --> this._selectionMoveEnd$ --> _selectionManagerService.selectionMoveEnd$ --> this.addControlToCurrentByRangeData
- *
- * but in mobile, we do not call disableEvent() in eventTrigger,
- * so pointerup --> scene.input-manager currentObject is spreadsheet --> this.eventTrigger
- *
- *
- * columnHeader pointerup$ --> selectionMoveEnd$ --> selectionManagerService@setSelections -->
- * selectionManagerService@_emitOnEnd -->
- * _workbookSelections.selectionMoveEnd$ --> _addSelectionControlBySelectionData
- *
- * @param selectionData
+ * 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) {
- const { rangeWithCoord, primaryWithCoord } = selection;
- const { rangeType } = rangeWithCoord;
const skeleton = this._skeleton;
- const style = selection.style ?? getNormalSelectionStyle(this._themeService);
-
+ 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);
// TODO: memory leak? This extension seems never released.
@@ -266,7 +240,7 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
/**
* Update the corresponding selectionControl based on selectionsData.
- * selectionData[i] ---- selectionControls[i]
+ * selectionData[i] syncs selectionControls[i]
* @param selections
*/
updateControlForCurrentByRangeData(selections: ISelectionWithCoordAndStyle[]) {
@@ -281,16 +255,19 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
return;
}
- const { rowHeaderWidth, columnHeaderHeight } = skeleton;
+ // const { rowHeaderWidth, columnHeaderHeight } = skeleton;
// TODO @lumixraku This is awful!
- // selectionControls should create & remove base on selections.
+ // 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, style } = selections[i];
+ const { rangeWithCoord, primaryWithCoord } = selections[i];
const control = selectionControls[i];
-
- control && control.update(rangeWithCoord, rowHeaderWidth, columnHeaderHeight, style, primaryWithCoord);
+ if (control) {
+ control.updateRange(rangeWithCoord, primaryWithCoord);
+ }
+ // control && control.update(rangeWithCoord, rowHeaderWidth, columnHeaderHeight, style, primaryWithCoord);
}
}
@@ -308,6 +285,10 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
return this._skeleton;
}
+ /**
+ * Generate selectionData from this._selectionControls.model .
+ * @returns {ISelectionWithCoordAndStyle[]} {range, primary, style}[]
+ */
getSelectionDataWithStyle(): ISelectionWithCoordAndStyle[] {
const selectionControls = this._selectionControls;
const [unitId, sheetId] = this._skeleton.getLocation();
@@ -392,10 +373,6 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
endSelection() {
this._clearUpdatingListeners();
-
- // ---> _updateSelections --> executeCommand(SetSelectionsOperation.id --> selectionManager.setSelections
- // ---> _selectionMoveEnd$.next --> _initSelectionChangeListener _reset --> _clearSelectionControls
-
this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
// when selection mouse up, enable the short cut service
this._shortcutService.setDisable(false);
@@ -505,7 +482,7 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
} 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._updateSelectionControlRange(
+ this._updateSelectionControlByRange(
activeSelectionControl,
cursorCellRangeWithRangeType,
primaryCursorCellRange
@@ -513,7 +490,7 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
} else {
// Create new control as default
activeSelectionControl = this.newSelectionControl(scene, rangeType);
- this._updateSelectionControlRange(
+ this._updateSelectionControlByRange(
activeSelectionControl,
cursorCellRangeWithRangeType,
primaryCursorCellRange
@@ -535,7 +512,9 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
} else if (rangeType === RANGE_TYPE.COLUMN) {
viewportPosY = 0;
}
- this._moving(viewportPosX, viewportPosY, activeSelectionControl, rangeType);
+ // 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);
@@ -548,6 +527,15 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
});
}
+ /**
+ * Init pointer move listener, bind in each pointer down, unbind in each pointer up
+ * @param viewportMain
+ * @param activeSelectionControl
+ * @param rangeType
+ * @param scrollTimerType
+ * @param moveStartPosX
+ * @param moveStartPosY
+ */
// eslint-disable-next-line max-lines-per-function
protected _setupPointerMoveListener(
viewportMain: Nullable<Viewport>,
@@ -574,7 +562,7 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
const { x: newMoveOffsetX, y: newMoveOffsetY } = scene.getRelativeToViewportCoord(Vector2.FromArray([moveOffsetX, moveOffsetY]));
- this._moving(newMoveOffsetX, newMoveOffsetY, activeSelectionControl, rangeType);
+ this._movingHandler(newMoveOffsetX, newMoveOffsetY, activeSelectionControl, rangeType);
let scrollOffsetX = newMoveOffsetX;
let scrollOffsetY = newMoveOffsetY;
@@ -695,7 +683,7 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
}
this._scrollTimer.scrolling(scrollOffsetX, scrollOffsetY, () => {
- this._moving(newMoveOffsetX, newMoveOffsetY, activeSelectionControl, rangeType);
+ this._movingHandler(newMoveOffsetX, newMoveOffsetY, activeSelectionControl, rangeType);
});
});
// #endregion
@@ -729,8 +717,8 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
/**
* 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
- protected _moving(
+ // eslint-disable-next-line max-lines-per-function, complexity
+ protected _movingHandler(
offsetX: number,
offsetY: number,
activeSelectionControl: Nullable<SelectionControl>,
@@ -812,15 +800,25 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
currSelectionRange.endRow !== newSelectionRange.endRow ||
currSelectionRange.endColumn !== newSelectionRange.endColumn;
if (activeSelectionControl != null && rangeChanged) {
- this._updateSelectionControlRange(activeSelectionControl, newSelectionRangeWithCoord);
+ this._updateSelectionControlByRange(activeSelectionControl, newSelectionRangeWithCoord);
this._selectionMoving$.next(this.getSelectionDataWithStyle());
}
}
- protected _updateSelectionControlRange(control: SelectionControl, newSelectionRange: IRangeWithCoord, highlight: Nullable<ISelectionCellWithMergeInfo>) {
- const skeleton = this._skeleton;
- const { rowHeaderWidth, columnHeaderHeight } = skeleton;
- control.update(newSelectionRange, rowHeaderWidth, columnHeaderHeight, this._selectionStyle, !highlight ? null : highlight);
+ /**
+ * Update the selection control by range.
+ * @param control
+ * @param newSelectionRange
+ * @param highlight
+ */
+ protected _updateSelectionControlByRange(control: SelectionControl, newSelectionRange: IRangeWithCoord, highlight: Nullable<ISelectionCellWithMergeInfo>) {
+ // 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() {
@@ -995,13 +993,17 @@ export class BaseSelectionRenderService extends Disposable implements ISheetSele
endX: activeCell.mergeInfo.endX || 0,
rangeType,
};
- this._updateSelectionControlRange(activeControl, newSelectionRange, currentCell);
+ this._updateSelectionControlByRange(activeControl, newSelectionRange, currentCell);
}
+ /**
+ * Reset all this.selectionControls by selectionsData.
+ * @param selectionsData
+ */
protected _refreshSelectionControl(selectionsData: readonly ISelectionWithStyle[]) {
const selections = selectionsData.map((selectionWithStyle) => {
const selectionData = attachSelectionWithCoord(selectionWithStyle, this._skeleton);
- selectionData.style = getNormalSelectionStyle(this._themeService);
+ selectionData.style = getDefaultNormalSelectionStyle(this._themeService);
return selectionData;
});
this.updateControlForCurrentByRangeData(selections);
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 0d4c1fc32f..0721a5633d 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
@@ -355,7 +355,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
activeSelectionControl = this.newSelectionControl(scene, rangeType);
}
- this._updateSelectionControlRange(
+ this._updateSelectionControlByRange(
activeSelectionControl,
cursorCellRangeWithRangeType,
primaryCursorCellRange
@@ -376,7 +376,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
// _moving would update activeSelectionControl range when row & col
// this update logic should split from _moving!!!
- this._moving(viewportPosX, viewportPosY, activeSelectionControl, rangeType);
+ this._movingHandler(viewportPosX, viewportPosY, activeSelectionControl, rangeType);
}
}
@@ -580,7 +580,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
*
* In Mobile version, new selection is determined by cursor cell and current of activeSelectionControl.model
*/
- protected override _moving(
+ protected override _movingHandler(
offsetX: number,
offsetY: number,
activeSelectionControl: MobileSelectionControl,
@@ -681,7 +681,7 @@ export class MobileSheetsSelectionRenderService extends BaseSelectionRenderServi
currSelectionRange.endColumn !== newSelectionRange.endColumn;
if (rangeChanged) {
if (activeSelectionControl) {
- this._updateSelectionControlRange(activeSelectionControl, newSelectionRangeWithCoord);
+ this._updateSelectionControlByRange(activeSelectionControl, 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 d285c6904c..decda80446 100644
--- a/packages/sheets-ui/src/services/selection/mobile-selection-shape.ts
+++ b/packages/sheets-ui/src/services/selection/mobile-selection-shape.ts
@@ -157,11 +157,11 @@ export class MobileSelectionControl extends SelectionControl {
override updateRange(range: IRangeWithCoord) {
this._selectionModel.setValue(range);
- this._updateControl(null, this._rowHeaderWidth, this._columnHeaderHeight);
+ this._updateControlStyleAndLayout(null, this._rowHeaderWidth, this._columnHeaderHeight);
}
- protected override _updateControl(style: Nullable<ISelectionStyle>, rowHeaderWidth: number, columnHeaderHeight: number) {
- super._updateControl(style, rowHeaderWidth, columnHeaderHeight);
+ protected override _updateControlStyleAndLayout(style: Nullable<ISelectionStyle>, rowHeaderWidth: number, columnHeaderHeight: number) {
+ super._updateControlStyleAndLayout(style, rowHeaderWidth, columnHeaderHeight);
// const rangeType = this.rangeType;
// startX startY shares same coordinate with viewport.(include row & colheader)
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 b53fceaf7c..b6b0be8331 100644
--- a/packages/sheets-ui/src/services/selection/selection-render-model.ts
+++ b/packages/sheets-ui/src/services/selection/selection-render-model.ts
@@ -28,9 +28,7 @@ export class SelectionRenderModel implements IRangeWithCoord {
private _endY: number = 0;
/**
- * highlight cell of selection
- * when there is no merge info
- * top left cell of current selection (or bottomLeft of current selection)
+ * The highlight cell of a selection. aka: current cell
*/
private _primary: Nullable<ISelectionCellWithMergeInfo>;
private _rangeType: RANGE_TYPE = RANGE_TYPE.NORMAL;
@@ -153,10 +151,15 @@ export class SelectionRenderModel implements IRangeWithCoord {
if (rangeType) {
this._rangeType = rangeType;
}
-
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.
+ * @param currentCell
+ */
setCurrentCell(currentCell: Nullable<ISelectionCellWithMergeInfo>) {
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 1842c3cd23..f4f9352aa9 100644
--- a/packages/sheets-ui/src/services/selection/selection-render.service.ts
+++ b/packages/sheets-ui/src/services/selection/selection-render.service.ts
@@ -133,11 +133,11 @@ export class SheetSelectionRenderService extends BaseSelectionRenderService impl
private _initThemeChangeListener() {
this.disposeWithMe(this._themeService.currentTheme$.subscribe(() => {
- this._resetStyle();
- const param = this._workbookSelections.getCurrentSelections();
- if (!param) return;
+ this._resetSelectionStyle();
+ const selections = this._workbookSelections.getCurrentSelections();
+ if (!selections) return;
- this._refreshSelectionControl(param);
+ this._refreshSelectionControl(selections);
}));
}
@@ -176,8 +176,7 @@ export class SheetSelectionRenderService extends BaseSelectionRenderService impl
}
/**
- * set new selection range in seletion model
- * selectionMoveEnd$ ---> _updateSelections --> [email protected]
+ * Update selectionData to current sheet.
* @param selectionDataWithStyleList
* @param type
*/
@@ -217,18 +216,15 @@ export class SheetSelectionRenderService extends BaseSelectionRenderService impl
const prevSheetId = this._skeleton?.worksheet?.getSheetId();
this._changeRuntime(skeleton, scene, viewportMain);
- // If there is no initial selection, add one by default in the top left corner.
- // const firstSelection = this._workbookSelections.getCurrentLastSelection();
- // Dont do that above! Ref selection also need syncExecCmd to reset selection.
- // TODO @lumixraku why use such weird a way to clear existing selection? subscribe to currentSkeleton$ is much better?
-
if (this._normalSelectionDisabled()) return;
- // SetSelectionsOperation would clear all exists selections
- // SetSelectionsOperation ---> selectionManager@setSelections ---> moveEnd$ ---> selectionRenderService@_reset
if (prevSheetId !== skeleton.worksheet.getSheetId()) {
+ // If there is no initial selection, add one by default in the top left corner.
const firstSelection = this._workbookSelections.getCurrentLastSelection();
if (!firstSelection) {
+ // WARNING: SetSelectionsOperation with type=null would clear all exists selections
+ // SetSelectionsOperation ---> selectionManager@setSelections ---> moveEnd$ ---> selectionRenderService@_reset
+ // TODO @lumixraku why use such weird a way to clear existing selection? subscribe to currentSkeleton$ is much better?
this._commandService.syncExecuteCommand(SetSelectionsOperation.id, {
unitId,
subUnitId: sheetId,
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 042b18a957..3ea77758bd 100644
--- a/packages/sheets-ui/src/services/selection/selection-shape-extension.ts
+++ b/packages/sheets-ui/src/services/selection/selection-shape-extension.ts
@@ -90,9 +90,7 @@ export class SelectionShapeExtension {
private _selectionHooks: Record<string, () => void>
) {
this._initialControl();
-
this._initialWidget();
-
this._initialFill();
this._control.dispose$.subscribe(() => {
@@ -259,6 +257,10 @@ export class SelectionShapeExtension {
this._control.selectionMoving$.next(this._targetSelection);
}
+ /**
+ * Drag move whole selectionControl when cusor turns to crosshair. Not for dragging 8 control points.
+ * @param evt
+ */
private _controlEvent(evt: IMouseEvent | IPointerEvent) {
const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
@@ -281,7 +283,6 @@ export class SelectionShapeExtension {
);
this._startOffsetX = newEvtOffsetX;
-
this._startOffsetY = newEvtOffsetY;
const { row, column } = actualSelection;
@@ -294,7 +295,6 @@ export class SelectionShapeExtension {
} = this._control.model;
let fixRow = 0;
-
let fixColumn = 0;
if (row < originStartRow) {
@@ -310,14 +310,11 @@ export class SelectionShapeExtension {
}
this._relativeSelectionPositionRow = originStartRow - row + fixRow;
-
this._relativeSelectionPositionColumn = originStartColumn - column + fixColumn;
-
this._relativeSelectionRowLength = originEndRow - originStartRow;
-
this._relativeSelectionColumnLength = originEndColumn - originStartColumn;
- const style = this._control.selectionStyle!;
+ const style = this._control.currentStyle!;
const scale = this._getScale();
if (this.isHelperSelection) {
@@ -329,15 +326,11 @@ export class SelectionShapeExtension {
}
// const relativeCoords = scene.getRelativeCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
-
// const { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
const viewMain = scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN)!;
-
const scrollTimer = ScrollTimer.create(scene);
-
- scrollTimer.startScroll(newEvtOffsetX, newEvtOffsetY, viewMain);
-
this._scrollTimer = scrollTimer;
+ scrollTimer.startScroll(newEvtOffsetX, newEvtOffsetY, viewMain);
scene.disableEvent();
@@ -370,10 +363,9 @@ export class SelectionShapeExtension {
this._clearObserverEvent();
scene.enableEvent();
this._scrollTimer?.dispose();
- // selectionScaled$ --> disableLockedSelectionChange
this._control.selectionMoved$.next(this._targetSelection);
- // this._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
- // this function should placed after this._control.selectionMoved$,
+
+ // _selectionHooks.selectionMoveEnd should placed after this._control.selectionMoved$,
// because selectionMoveEnd will dispose all selectionControls, then this._control will be null.
this._selectionHooks.selectionMoveEnd?.();
});
@@ -421,18 +413,107 @@ export class SelectionShapeExtension {
});
control.onPointerDown$.subscribeEvent((evt: IMouseEvent | IPointerEvent) => {
- this._widgetEvent(evt, cursors[index]);
+ this._widgetPointerDownEvent(evt, cursors[index]);
+ });
+ });
+ }
+
+ /**
+ * Pointer down Events for 8 control point.
+ * @param evt
+ * @param cursor
+ */
+ private _widgetPointerDownEvent(evt: IMouseEvent | IPointerEvent, cursor: CURSOR_TYPE) {
+ const scene = this._scene;
+
+ const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
+ const relativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
+ const { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
+ this._startOffsetX = evtOffsetX;
+ this._startOffsetY = evtOffsetY;
+
+ const {
+ startRow: originStartRow,
+ startColumn: originStartColumn,
+ endRow: originEndRow,
+ endColumn: originEndColumn,
+ } = this._control.model;
+
+ // When dragging the bottom line of the selection area over the previous top line, at this time, endRow < startRow
+ // when dragging top line lower than the previous bottom line, at this time, startRow > endRow
+ // see https://github.com/dream-num/univer-pro/issues/1451
+ const startRow = Math.min(originStartRow, originEndRow);
+ const startColumn = Math.min(originStartColumn, originEndColumn);
+ const endRow = Math.max(originStartRow, originEndRow);
+ const endColumn = Math.max(originStartColumn, originEndColumn);
+
+ this._relativeSelectionPositionRow = startRow;
+ this._relativeSelectionPositionColumn = startColumn;
+ this._relativeSelectionRowLength = endRow - startRow;
+ this._relativeSelectionColumnLength = endColumn - startColumn;
+
+ if (cursor === CURSOR_TYPE.NORTH_WEST_RESIZE) {
+ this._relativeSelectionPositionRow = endRow;
+ this._relativeSelectionPositionColumn = endColumn;
+ } else if (cursor === CURSOR_TYPE.NORTH_RESIZE) {
+ this._relativeSelectionPositionRow = endRow;
+ } else if (cursor === CURSOR_TYPE.NORTH_EAST_RESIZE) {
+ this._relativeSelectionPositionRow = endRow;
+ } else if (cursor === CURSOR_TYPE.WEST_RESIZE) {
+ this._relativeSelectionPositionColumn = endColumn;
+ } else if (cursor === CURSOR_TYPE.SOUTH_WEST_RESIZE) {
+ this._relativeSelectionPositionColumn = endColumn;
+ } else if (cursor === CURSOR_TYPE.SOUTH_RESIZE) {
+ this._relativeSelectionPositionRow = startRow;
+ }
+
+ const scrollTimer = ScrollTimer.create(scene);
+ scrollTimer.startScroll(newEvtOffsetX, newEvtOffsetY);
+ this._scrollTimer = scrollTimer;
+
+ scene.disableEvent();
+
+ 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])
+ );
+
+ this._widgetMoving(newMoveOffsetX, newMoveOffsetY, cursor);
+
+ scene.setCursor(cursor);
+
+ scrollTimer.scrolling(newMoveOffsetX, newMoveOffsetY, () => {
+ this._widgetMoving(newMoveOffsetX, newMoveOffsetY, cursor);
});
});
+
+ this._scenePointerUpSub = scene.onPointerUp$.subscribeEvent(() => {
+ const scene = this._scene;
+ scene.resetCursor();
+ this._clearObserverEvent();
+ scene.enableEvent();
+ this._scrollTimer?.dispose();
+ this._control.selectionScaled$.next(this._targetSelection);
+
+ // _selectionHooks.selectionMoveEnd should placed after this._control.selectionMoved$,
+ // because selectionMoveEnd will dispose all selectionControls, then this._control will be null.
+ this._selectionHooks.selectionMoveEnd?.();
+ });
}
+ /**
+ * Pointer move Events for 8 control point.
+ * @param moveOffsetX
+ * @param moveOffsetY
+ * @param cursor
+ */
private _widgetMoving(moveOffsetX: number, moveOffsetY: number, cursor: CURSOR_TYPE) {
const scene = this._scene;
const scrollXY = scene.getVpScrollXYInfoByPosToVp(Vector2.FromArray([this._startOffsetX, this._startOffsetY]));
-
const { scaleX, scaleY } = scene.getAncestorScale();
-
const moveActualSelection = this._skeleton.getCellPositionByOffset(
moveOffsetX,
moveOffsetY,
@@ -442,19 +523,12 @@ export class SelectionShapeExtension {
);
const { row, column } = moveActualSelection;
-
const { rowHeaderWidth, columnHeaderHeight } = this._skeleton;
-
// const maxRow = this._skeleton.getRowCount() - 1;
-
// const maxColumn = this._skeleton.getColumnCount() - 1;
-
let startRow = this._relativeSelectionPositionRow;
-
let startColumn = this._relativeSelectionPositionColumn;
-
let endRow = row;
-
let endColumn = column;
if (cursor === CURSOR_TYPE.NORTH_WEST_RESIZE) {
@@ -517,97 +591,11 @@ export class SelectionShapeExtension {
endColumn,
};
- this._control.update(this._targetSelection, rowHeaderWidth, columnHeaderHeight, this._control.selectionStyle);
+ this._control.update(this._targetSelection, rowHeaderWidth, columnHeaderHeight, this._control.currentStyle);
this._control.clearHighlight();
this._control.selectionScaling$.next(this._targetSelection);
}
- /**
- * Events for 8 control point
- * @param evt
- * @param cursor
- */
- private _widgetEvent(evt: IMouseEvent | IPointerEvent, cursor: CURSOR_TYPE) {
- const { offsetX: evtOffsetX, offsetY: evtOffsetY } = evt;
-
- const scene = this._scene;
-
- const relativeCoords = scene.getRelativeToViewportCoord(Vector2.FromArray([evtOffsetX, evtOffsetY]));
-
- const { x: newEvtOffsetX, y: newEvtOffsetY } = relativeCoords;
-
- this._startOffsetX = evtOffsetX;
-
- this._startOffsetY = evtOffsetY;
-
- const {
- startRow: originStartRow,
- startColumn: originStartColumn,
- endRow: originEndRow,
- endColumn: originEndColumn,
- } = this._control.model;
-
- this._relativeSelectionPositionRow = originStartRow;
-
- this._relativeSelectionPositionColumn = originStartColumn;
-
- this._relativeSelectionRowLength = originEndRow - originStartRow;
-
- this._relativeSelectionColumnLength = originEndColumn - originStartColumn;
-
- if (cursor === CURSOR_TYPE.NORTH_WEST_RESIZE) {
- this._relativeSelectionPositionRow = originEndRow;
- this._relativeSelectionPositionColumn = originEndColumn;
- } else if (cursor === CURSOR_TYPE.NORTH_RESIZE) {
- this._relativeSelectionPositionRow = originEndRow;
- } else if (cursor === CURSOR_TYPE.NORTH_EAST_RESIZE) {
- this._relativeSelectionPositionRow = originEndRow;
- } else if (cursor === CURSOR_TYPE.WEST_RESIZE) {
- this._relativeSelectionPositionColumn = originEndColumn;
- } else if (cursor === CURSOR_TYPE.SOUTH_WEST_RESIZE) {
- this._relativeSelectionPositionColumn = originEndColumn;
- }
-
- const scrollTimer = ScrollTimer.create(scene);
-
- scrollTimer.startScroll(newEvtOffsetX, newEvtOffsetY);
-
- this._scrollTimer = scrollTimer;
-
- scene.disableEvent();
-
- 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])
- );
-
- this._widgetMoving(newMoveOffsetX, newMoveOffsetY, cursor);
-
- scene.setCursor(cursor);
-
- scrollTimer.scrolling(newMoveOffsetX, newMoveOffsetY, () => {
- this._widgetMoving(newMoveOffsetX, newMoveOffsetY, cursor);
- });
- });
-
- this._scenePointerUpSub = scene.onPointerUp$.subscribeEvent(() => {
- const scene = this._scene;
- scene.resetCursor();
- this._clearObserverEvent();
- scene.enableEvent();
- this._scrollTimer?.dispose();
- this._control.selectionScaled$.next(this._targetSelection);
- // selectionMoveEnd$ update selection model
- // _selectionHooks.selectionMoveEnd --> SelectionRenderService._selectionMoveEnd$.next(this.getSelectionDataWithStyle());
-
- // this function should placed after this._control.selectionMoved$,
- // because selectionMoveEnd will dispose all selectionControls, then this._control will be null.
- this._selectionHooks.selectionMoveEnd?.();
- });
- }
-
private _initialFill() {
const { fillControl } = this._control;
@@ -627,6 +615,7 @@ export class SelectionShapeExtension {
fillControl.onPointerDown$.subscribeEvent(this._fillEvent.bind(this));
}
+ // eslint-disable-next-line complexity
private _fillMoving(moveOffsetX: number, moveOffsetY: number) {
const scene = this._scene;
// const activeViewport = scene.getActiveViewportByCoord(Vector2.FromArray([moveOffsetX, moveOffsetY]));
@@ -800,7 +789,7 @@ export class SelectionShapeExtension {
this._relativeSelectionColumnLength = originEndColumn - originStartColumn;
- const style = this._control.selectionStyle;
+ const style = this._control.currentStyle;
let stroke = style?.stroke;
let strokeWidth = style?.strokeWidth;
const defaultStyle = getNormalSelectionStyle(this._themeService);
diff --git a/packages/sheets-ui/src/services/selection/selection-shape.ts b/packages/sheets-ui/src/services/selection/selection-shape.ts
index a86b9d4546..799886612f 100644
--- a/packages/sheets-ui/src/services/selection/selection-shape.ts
+++ b/packages/sheets-ui/src/services/selection/selection-shape.ts
@@ -72,7 +72,7 @@ export enum SELECTION_MANAGER_KEY {
const SELECTION_TITLE_HIGHLIGHT_ALPHA = 0.3;
/**
- * The main selection canvas component
+ * The main selection canvas component, includes leftControl,rightControl,topControl,bottomControl,backgroundControlTop,backgroundControlMiddleLeft,backgroundControlMiddleRight,backgroundControlBottom,fillControl
*/
export class SelectionControl extends Disposable {
private _leftControl!: Rect;
@@ -111,7 +111,10 @@ export class SelectionControl extends Disposable {
protected _selectionModel!: SelectionRenderModel;
- protected _selectionStyle: Nullable<ISelectionStyle>;
+ // 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;
@@ -121,6 +124,10 @@ export class SelectionControl extends Disposable {
private _dispose$ = new BehaviorSubject<SelectionControl>(this);
readonly dispose$ = this._dispose$.asObservable();
+ /**
+ * eventSource: selectionShapeExtension selectionMoving$.next,
+ * Observer: prompt.controller
+ */
readonly selectionMoving$ = new Subject<IRangeWithCoord>();
readonly selectionMoved$ = new Subject<IRangeWithCoord>();
readonly selectionScaling$ = new Subject<IRangeWithCoord>();
@@ -131,10 +138,6 @@ export class SelectionControl extends Disposable {
readonly selectionFilled$ = this._selectionFilled$.asObservable();
- private _defaultStyle!: ISelectionStyle;
-
- private _currentStyle: Nullable<ISelectionStyle>;
-
private _isHelperSelection: boolean = true;
constructor(
@@ -243,13 +246,13 @@ export class SelectionControl extends Disposable {
return this._themeService;
}
- get selectionStyle() {
- return this._selectionStyle;
- }
+ // get selectionStyle() {
+ // return this._selectionStyle;
+ // }
- set selectionStyle(style: Nullable<ISelectionStyle>) {
- this._selectionStyle = style;
- }
+ // set selectionStyle(style: Nullable<ISelectionStyle>) {
+ // this._selectionStyle = style;
+ // }
get selectionModel() {
return this._selectionModel;
@@ -276,7 +279,9 @@ export class SelectionControl extends Disposable {
}
set currentStyle(style: Nullable<ISelectionStyle>) {
- this._currentStyle = style;
+ if (style) {
+ this._currentStyle = style;
+ }
}
get isHelperSelection() {
@@ -310,184 +315,34 @@ export class SelectionControl extends Disposable {
this._selectionFilled$.next(val);
}
- updateStyle(style: ISelectionStyle) {
- this._updateControl(style, this._rowHeaderWidth, this._columnHeaderHeight);
- }
-
- updateRange(range: IRangeWithCoord) {
- this._selectionModel.setValue(range);
- // TODO @lumixraku
- // why update rowHeaderWidth and columnHeaderHeight at the same time? Did they change when update range?
- this._updateControl(null, this._rowHeaderWidth, this._columnHeaderHeight);
- }
-
/**
- * update seleciton model(new range)
- * @param newSelectionRange update new selection range!!
- * @param rowHeaderWidth
- * @param columnHeaderHeight
- * @param style
- * @param highlight
- */
- update(
- newSelectionRange: IRangeWithCoord,
- rowHeaderWidth: number = 0,
- columnHeaderHeight: number = 0,
- style?: Nullable<ISelectionStyle>,
- highlight?: Nullable<ISelectionCellWithMergeInfo>
- ) {
- this._selectionModel.setValue(newSelectionRange, highlight);
- if (style == null) {
- style = this._selectionStyle;
- }
- this._updateControl(style, rowHeaderWidth, columnHeaderHeight);
- }
-
- updateCurrCell(highlight?: Nullable<ISelectionCellWithMergeInfo>) {
- this._selectionModel.setCurrentCell(highlight);
- }
-
- clearHighlight() {
- this._selectionModel.clearCurrentCell();
- this._updateControl(this._selectionStyle, this._rowHeaderWidth, this._columnHeaderHeight);
- }
-
- getScene() {
- return this._scene;
- }
-
- override dispose() {
- this._leftControl?.dispose();
- this._rightControl?.dispose();
- this._topControl?.dispose();
- this._bottomControl?.dispose();
- this._backgroundControlTop?.dispose();
- this._backgroundControlMiddleLeft?.dispose();
- this._backgroundControlMiddleRight?.dispose();
- this._backgroundControlBottom?.dispose();
- this._fillControl.dispose();
- this._selectionShapeGroup?.dispose();
-
- this._rowHeaderBackground?.dispose();
- this._rowHeaderBorder?.dispose();
- this._rowHeaderGroup?.dispose();
- this._rowHeaderBackground?.dispose();
- this._columnHeaderBackground?.dispose();
- this._columnHeaderBorder?.dispose();
- this._columnHeaderGroup?.dispose();
-
- this._topLeftWidget?.dispose();
- this._topCenterWidget?.dispose();
- this._topRightWidget?.dispose();
- this._middleLeftWidget?.dispose();
- this._middleRightWidget?.dispose();
- this._bottomLeftWidget?.dispose();
- this._bottomCenterWidget?.dispose();
- this._bottomRightWidget?.dispose();
-
- super.dispose();
-
- this._dispose$.next(this);
- this._dispose$.complete();
- }
-
- /**
- * Get the cell information of the current selection, considering the case of merging cells
- */
- getCurrentCellInfo(): Nullable<IRangeWithCoord> {
- const currentCell = this.model.currentCell;
-
- if (currentCell) {
- let currentRangeData: IRangeWithCoord;
-
- if (currentCell.isMerged) {
- const mergeInfo = currentCell.mergeInfo;
-
- currentRangeData = {
- startRow: mergeInfo.startRow,
- endRow: mergeInfo.endRow,
- startColumn: mergeInfo.startColumn,
- endColumn: mergeInfo.endColumn,
- startX: mergeInfo.startX,
- endX: mergeInfo.endX,
- startY: mergeInfo.startY,
- endY: mergeInfo.endY,
- };
- } else {
- const { actualRow, actualColumn, startX, endX, startY, endY } = currentCell;
- currentRangeData = {
- startRow: actualRow,
- endRow: actualRow,
- startColumn: actualColumn,
- endColumn: actualColumn,
- startX,
- endX,
- startY,
- endY,
- };
- }
-
- return currentRangeData;
- }
- }
-
- getValue(): ISelectionWithCoordAndStyle {
- return {
- ...this._selectionModel.getValue(),
- style: this._selectionStyle,
- };
- }
-
- getRange() {
- return this._selectionModel.getValue().rangeWithCoord;
- }
-
- enableHelperSelection() {
- this._isHelperSelection = true;
- }
-
- disableHelperSelection() {
- this._isHelperSelection = false;
- }
-
- updateStyleId(id: string) {
- if (this._selectionStyle == null) {
- return;
- }
- this._selectionStyle.id = id;
- }
-
- /**
- * invoked when update selection style & range change
+ * invoked when update selection style & range change, invoked by updateStyle, updateRange, update
*/
// eslint-disable-next-line max-lines-per-function
- protected _updateControl(style: Nullable<ISelectionStyle>, rowHeaderWidth: number, columnHeaderHeight: number) {
+ protected _updateControlStyleAndLayout(selectionStyle: Nullable<ISelectionStyle>, rowHeaderWidth: number, columnHeaderHeight: number) {
+ // this._selectionStyle = selectionStyle;
+ this._rowHeaderWidth = rowHeaderWidth || 0;
+ this._columnHeaderHeight = columnHeaderHeight || 0;
+
// startX startY shares same coordinate with viewport.(include row & colheader)
const { startX, startY, endX, endY } = this._selectionModel;
const defaultStyle = this._defaultStyle;
- if (style == null) {
- style = defaultStyle;
- }
-
- this._currentStyle = style;
+ const currentStyle = this.currentStyle = selectionStyle || this._currentStyle;// rediculous! style param value is this._currentStyle, but this._currentStyle may be null.
const {
stroke = defaultStyle.stroke!,
widgets = defaultStyle.widgets!,
hasAutoFill = defaultStyle.hasAutoFill!,
-
AutofillStroke = defaultStyle.AutofillStroke!,
-
strokeDash,
-
isAnimationDash,
- } = style;
+ } = currentStyle;
let {
strokeWidth = defaultStyle.strokeWidth!,
AutofillSize = defaultStyle.AutofillSize!,
AutofillStrokeWidth = defaultStyle.AutofillStrokeWidth!,
- } = style;
+ } = currentStyle;
const scale = this._getScale();
@@ -559,7 +414,7 @@ export class SelectionControl extends Disposable {
this.dashRect.hide();
this._stopAntLineAnimation();
} else {
- const dashRectBorderWidth = style.strokeWidth * 2 / scale;
+ const dashRectBorderWidth = currentStyle.strokeWidth * 2 / scale;
this.dashRect.transformByState({
height: endY - startY,
width: endX - startX,
@@ -601,27 +456,178 @@ export class SelectionControl extends Disposable {
this.fillControl.hide();
}
- this._updateBackgroundControl(style);
+ this._updateBackgroundControl(selectionStyle);
- this._updateBackgroundTitle(style, rowHeaderWidth, columnHeaderHeight);
+ this._updateBackgroundTitle(selectionStyle, rowHeaderWidth, columnHeaderHeight);
- this._updateWidgets(style);
+ this._updateWidgets(selectionStyle);
this.selectionShape.show();
this.selectionShape.translate(startX, startY);
- this._selectionStyle = style;
+ // this._selectionStyle = selectionStyle;
- this._rowHeaderWidth = rowHeaderWidth || 0;
+ // this._rowHeaderWidth = rowHeaderWidth || 0;
- this._columnHeaderHeight = columnHeaderHeight || 0;
+ // this._columnHeaderHeight = columnHeaderHeight || 0;
this.selectionShape.makeDirtyNoDebounce(true);
}
+ updateStyle(style: ISelectionStyle) {
+ this._updateControlStyleAndLayout(style, this._rowHeaderWidth, this._columnHeaderHeight);
+ }
+
+ updateRange(range: IRangeWithCoord, primaryCell: Nullable<ISelectionCellWithMergeInfo>) {
+ this._selectionModel.setValue(range, primaryCell);
+ // TODO @lumixraku
+ // why update rowHeaderWidth and columnHeaderHeight at the same time? Did they change when update range?
+ this._updateControlStyleAndLayout(this._currentStyle, this._rowHeaderWidth, this._columnHeaderHeight);
+ }
+
+ /**
+ * update selection model with new range & primary cell(aka: highlight/current), also update row/col selection size & style.
+ *
+ * @param newSelectionRange
+ * @param rowHeaderWidth
+ * @param columnHeaderHeight
+ * @param style
+ * @param primaryCell primary cell
+ */
+ update(
+ newSelectionRange: IRangeWithCoord,
+ rowHeaderWidth: number = 0,
+ columnHeaderHeight: number = 0,
+ style?: Nullable<ISelectionStyle>,
+ primaryCell?: Nullable<ISelectionCellWithMergeInfo>
+ ) {
+ this._selectionModel.setValue(newSelectionRange, primaryCell);
+ this._updateControlStyleAndLayout(style || this._currentStyle, rowHeaderWidth, columnHeaderHeight);
+ }
+
+ /**
+ * update primary range
+ * @param primaryCell model.current (aka: highlight)
+ */
+ updateCurrCell(primaryCell?: Nullable<ISelectionCellWithMergeInfo>) {
+ this._selectionModel.setCurrentCell(primaryCell);
+ }
+
+ clearHighlight() {
+ this._selectionModel.clearCurrentCell();
+ this._updateControlStyleAndLayout(this._currentStyle, this._rowHeaderWidth, this._columnHeaderHeight);
+ }
+
+ getScene() {
+ return this._scene;
+ }
+
+ // eslint-disable-next-line complexity
+ override dispose() {
+ this._leftControl?.dispose();
+ this._rightControl?.dispose();
+ this._topControl?.dispose();
+ this._bottomControl?.dispose();
+ this._backgroundControlTop?.dispose();
+ this._backgroundControlMiddleLeft?.dispose();
+ this._backgroundControlMiddleRight?.dispose();
+ this._backgroundControlBottom?.dispose();
+ this._fillControl.dispose();
+ this._selectionShapeGroup?.dispose();
+
+ this._rowHeaderBackground?.dispose();
+ this._rowHeaderBorder?.dispose();
+ this._rowHeaderGroup?.dispose();
+ this._rowHeaderBackground?.dispose();
+ this._columnHeaderBackground?.dispose();
+ this._columnHeaderBorder?.dispose();
+ this._columnHeaderGroup?.dispose();
+
+ this._topLeftWidget?.dispose();
+ this._topCenterWidget?.dispose();
+ this._topRightWidget?.dispose();
+ this._middleLeftWidget?.dispose();
+ this._middleRightWidget?.dispose();
+ this._bottomLeftWidget?.dispose();
+ this._bottomCenterWidget?.dispose();
+ this._bottomRightWidget?.dispose();
+
+ super.dispose();
+
+ this._dispose$.next(this);
+ this._dispose$.complete();
+ }
+
+ /**
+ * Get the cell information of the current selection, considering the case of merging cells
+ */
+ getCurrentCellInfo(): Nullable<IRangeWithCoord> {
+ const currentCell = this.model.currentCell;
+
+ if (currentCell) {
+ let currentRangeData: IRangeWithCoord;
+
+ if (currentCell.isMerged) {
+ const mergeInfo = currentCell.mergeInfo;
+
+ currentRangeData = {
+ startRow: mergeInfo.startRow,
+ endRow: mergeInfo.endRow,
+ startColumn: mergeInfo.startColumn,
+ endColumn: mergeInfo.endColumn,
+ startX: mergeInfo.startX,
+ endX: mergeInfo.endX,
+ startY: mergeInfo.startY,
+ endY: mergeInfo.endY,
+ };
+ } else {
+ const { actualRow, actualColumn, startX, endX, startY, endY } = currentCell;
+ currentRangeData = {
+ startRow: actualRow,
+ endRow: actualRow,
+ startColumn: actualColumn,
+ endColumn: actualColumn,
+ startX,
+ endX,
+ startY,
+ endY,
+ };
+ }
+
+ return currentRangeData;
+ }
+ }
+
+ getValue(): ISelectionWithCoordAndStyle {
+ return {
+ ...this._selectionModel.getValue(),
+ style: this._currentStyle,
+ };
+ }
+
+ getRange() {
+ return this._selectionModel.getValue().rangeWithCoord;
+ }
+
+ enableHelperSelection() {
+ this._isHelperSelection = true;
+ }
+
+ disableHelperSelection() {
+ this._isHelperSelection = false;
+ }
+
+ // updateStyleId(id: string) {
+ // if (this._selectionStyle == null) {
+ // return;
+ // }
+ // this._selectionStyle.id = id;
+ // }
+
// eslint-disable-next-line max-lines-per-function
private _initialize() {
this._defaultStyle = getNormalSelectionStyle(this._themeService);
+ this._currentStyle = getNormalSelectionStyle(this._themeService);
this._selectionModel = new SelectionRenderModel();
const zIndex = this._zIndex;
@@ -660,10 +666,14 @@ export class SelectionControl extends Disposable {
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._dashRect = new DashedRect(SELECTION_MANAGER_KEY.dash + zIndex, {
zIndex: zIndex + 2,
evented: false,
@@ -695,7 +705,7 @@ export class SelectionControl extends Disposable {
return;
}
- this._updateControl(this._currentStyle, this._rowHeaderWidth, this._columnHeaderHeight);
+ this._updateControlStyleAndLayout(this._currentStyle, this._rowHeaderWidth, this._columnHeaderHeight);
})
)
);
diff --git a/packages/sheets-ui/src/views/header-resize-shape.ts b/packages/sheets-ui/src/views/header-resize-shape.ts
index a38331ce9d..3ad6cbe2f4 100644
--- a/packages/sheets-ui/src/views/header-resize-shape.ts
+++ b/packages/sheets-ui/src/views/header-resize-shape.ts
@@ -65,29 +65,22 @@ export class HeaderMenuResizeShape<
}
protected override _draw(ctx: UniverRenderingContext) {
- let { width, height } = this;
-
- let left = 0;
-
- let top = 0;
-
const scene = this.getScene();
+ if (!scene) return;
const { scaleX, scaleY } = scene.getAncestorScale();
-
const scale = Math.max(scaleX, scaleY);
-
const HEADER_MENU_SHAPE_WIDTH_HEIGHT_SCALE = HEADER_MENU_SHAPE_SIZE / scale;
-
const HEADER_MENU_SHAPE_THUMB_SIZE_SCALE = HEADER_MENU_SHAPE_THUMB_SIZE / scale;
+ let { width, height } = this;
+ let left = 0;
+ let top = 0;
if (this.mode === HEADER_RESIZE_SHAPE_TYPE.VERTICAL) {
width = HEADER_MENU_SHAPE_THUMB_SIZE_SCALE;
-
left = HEADER_MENU_SHAPE_WIDTH_HEIGHT_SCALE - HEADER_MENU_SHAPE_THUMB_SIZE_SCALE;
} else {
height = HEADER_MENU_SHAPE_THUMB_SIZE_SCALE;
-
top = HEADER_MENU_SHAPE_WIDTH_HEIGHT_SCALE - HEADER_MENU_SHAPE_THUMB_SIZE_SCALE;
}
diff --git a/packages/sheets/src/basics/selection.ts b/packages/sheets/src/basics/selection.ts
index dc0081e012..7f6ef51601 100644
--- a/packages/sheets/src/basics/selection.ts
+++ b/packages/sheets/src/basics/selection.ts
@@ -160,7 +160,6 @@ export function getNormalSelectionStyle(themeService: ThemeService): ISelectionS
return {
strokeWidth: 1,
stroke: styleSheet.primaryColor,
- // strokeDash: 8,
fill,
// widgets: { tl: true, tc: true, tr: true, ml: true, mr: true, bl: true, bc: true, br: true },
widgets: {},
diff --git a/packages/sheets/src/services/selections/selection-manager.service.ts b/packages/sheets/src/services/selections/selection-manager.service.ts
index 2124ef9dd3..ff5d1dcf7d 100644
--- a/packages/sheets/src/services/selections/selection-manager.service.ts
+++ b/packages/sheets/src/services/selections/selection-manager.service.ts
@@ -64,7 +64,10 @@ export class SheetsSelectionsService extends RxDisposable {
});
}
- /** Clear all selections in all workbooks. */
+ /**
+ * Clear all selections in all workbooks.
+ * invoked by prompt.controller
+ */
clear(): void {
this._workbookSelections.forEach((wbSelection) => wbSelection.clear());
}
@@ -97,6 +100,14 @@ export class SheetsSelectionsService extends RxDisposable {
setSelections(selectionDatas: ISelectionWithStyle[], type?: SelectionMoveType): void;
setSelections(unitId: string, worksheetId: string, selectionDatas: ISelectionWithStyle[], type?: SelectionMoveType): void;
+ /**
+ * Set seleciton data to WorkbookSelections.
+ * If type is not specfied, this method would clear all existing selections.
+ * @param unitIdOrSelections
+ * @param worksheetIdOrType
+ * @param selectionDatas
+ * @param type
+ */
setSelections(
unitIdOrSelections: string | ISelectionWithStyle[],
worksheetIdOrType: string | SelectionMoveType | undefined,
@@ -227,24 +238,32 @@ export class WorkbookSelections extends Disposable {
}
/**
- *
+ * 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 = SelectionMoveType.MOVE_END) {
- // @TODO lumixraku: selectionDatas should not be same variable !!!
- // but there are some place get selection from this._worksheetSelections and set as 2nd parameter of this function cause problem!!
+ // 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);
- // WTF: why we would not refresh in add but in replace?
- if (type === SelectionMoveType.MOVE_START) {
- this._selectionMoveStart$.next(selectionDatas);
- } else if (type === SelectionMoveType.MOVING) {
- this._selectionMoving$.next(selectionDatas);
- } else {
- this._emitOnEnd(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;
+ default:
+ this._emitOnEnd(selectionDatas);
+ break;
}
}
@@ -272,7 +291,7 @@ export class WorkbookSelections extends Disposable {
private _worksheetSelections = new Map<string, ISelectionWithStyle[]>();
/**
- * same as _getCurrentSelections, but would set [] if no selection.
+ * Same as _getCurrentSelections(which return this._worksheetSelections), but this method would set [] if no selection.
* @param sheetId
* @returns this._worksheetSelections
*/
diff --git a/packages/slides-ui/src/controllers/slide-editing.render-controller.ts b/packages/slides-ui/src/controllers/slide-editing.render-controller.ts
index 0da3f51dda..20d5d642f4 100644
--- a/packages/slides-ui/src/controllers/slide-editing.render-controller.ts
+++ b/packages/slides-ui/src/controllers/slide-editing.render-controller.ts
@@ -176,7 +176,6 @@ export class SlideEditingRenderController extends Disposable implements IRenderM
}
private _initEditorVisibilityListener(): void {
- // startEditing --> slide-editor-bridge.render-controller.ts@changeVisible --> _editorBridgeService.changeVisible
this.disposeWithMe(this._editorBridgeService.visible$
// .pipe(distinctUntilChanged((prev, curr) => prev.visible === curr.visible))
.subscribe((param) => {
@@ -263,16 +262,7 @@ export class SlideEditingRenderController extends Disposable implements IRenderM
}
/**
- * set size and pos of editing area
- * invoked by _handleEditorVisible
- *
- * size & pos derives from [email protected]
- *
- * set pos of editing area
- * EditorContainer.tsx cellEditorManagerService.setFocus(true) -->
- * _focus$.next --> editingRenderController -->
- * _textSelectionRenderManager.sync() --> _updateInputPosition --> activate(left, top)
- *
+ * Set size and pos of editing area.
* @param positionFromEditRectState
* @param canvasOffset
* @param documentSkeleton
@@ -288,6 +278,7 @@ export class SlideEditingRenderController extends Disposable implements IRenderM
scaleX: number = 1,
scaleY: number = 1
) {
+ //size & pos derives from [email protected]
const { startX, startY, endX, endY } = positionFromEditRectState;
const documentDataModel = documentLayoutObject.documentModel;
@@ -559,14 +550,13 @@ export class SlideEditingRenderController extends Disposable implements IRenderM
}
/**
- * show input area, resize input area and then place input to right place.
- * invoked when this._editorBridgeService.visible$ param.visible = true
- *
- * handleVisible is the 2nd part of editing.
- * startEditing --> _updateEditor
- * startEditing --> changeVisible --> slide-editor-bridge.render-controller.ts@changeVisible --> _editorBridgeService.changeVisible
+ * Show input area, resize input area and then place input to right place.
+ * @TODO why do resize in show input area?
* @param param
*/
+ // handleVisible is the 2nd part of editing.
+ // first part: startEditing --> _updateEditor
+ // 2nd part: startEditing --> changeVisible --> slide-editor-bridge.render-controller.ts@changeVisible --> _editorBridgeService.changeVisible
private _handleEditorVisible(param: IEditorBridgeServiceVisibleParam) {
const { eventType } = param;
diff --git a/packages/slides-ui/src/controllers/slide-editor-bridge.render-controller.ts b/packages/slides-ui/src/controllers/slide-editor-bridge.render-controller.ts
index 9d33343255..82a67a68d3 100644
--- a/packages/slides-ui/src/controllers/slide-editor-bridge.render-controller.ts
+++ b/packages/slides-ui/src/controllers/slide-editor-bridge.render-controller.ts
@@ -92,7 +92,6 @@ export class SlideEditorBridgeRenderController extends RxDisposable implements I
richTextObj: targetObject,
};
- // invoked by editorBridgeRenderController@startEditing ---> editorBridgeRenderController@_updateEditor
this._editorBridgeService.setEditorRect(setEditorRect);
}
diff --git a/packages/slides-ui/src/controllers/slide.render-controller.ts b/packages/slides-ui/src/controllers/slide.render-controller.ts
index 79a2654cf4..e8eff8d872 100644
--- a/packages/slides-ui/src/controllers/slide.render-controller.ts
+++ b/packages/slides-ui/src/controllers/slide.render-controller.ts
@@ -33,13 +33,6 @@ import type { PageID } from '../type';
export class SlideRenderController extends RxDisposable implements IRenderModule {
private _objectProvider: ObjectProvider | null = null;
- /**
- * As a dep of UNIVER_SLIDE, init by RenderManagerService@createRender --> injector.get(dep)
- * @param _renderContext
- * @param _injector
- * @param _univerInstanceService
- * @param _renderManagerService
- */
constructor(
private readonly _renderContext: IRenderContext<UnitModel>,
@Inject(Injector) private readonly _injector: Injector,
@@ -52,9 +45,6 @@ export class SlideRenderController extends RxDisposable implements IRenderModule
this._addNewRender();
}
- /**
- * _initialize --> _create --> _addNewRender
- */
private _addNewRender() {
const { unitId, engine, scene } = this._renderContext;
const slideDataModel = this._getCurrUnitModel();
@@ -157,7 +147,6 @@ export class SlideRenderController extends RxDisposable implements IRenderModule
}, 300);
/**
- * init --> _addNewRender
* @param mainScene
*/
private _createSlide(mainScene: Scene) {
@@ -245,8 +234,7 @@ export class SlideRenderController extends RxDisposable implements IRenderModule
}
/**
- * _createScene by pages, createScene --> set sceneMap
- * invoked stack: initialize --> _create --> _addNewRender --> _createSlidePages
+ * CreateScene by pages, and activate first one.
* @param slideDataModel
* @param slide
*/
@@ -354,14 +342,11 @@ export class SlideRenderController extends RxDisposable implements IRenderModule
}
/**
- * _initialize --> _create --> _addNewRender --> _createSlidePages --> page forEach --> createPageScene
- * _sceneMap.set(pageId, pageScene);
- *
+ * Create scene by page and set to _sceneMap.
* @param pageId
* @param page
- * @returns pageScene: Scene
*/
- createPageScene(pageId: string, page: ISlidePage) {
+ createPageScene(pageId: string, page: ISlidePage): Nullable<Scene> {
// const render = this._currentRender();
const render = this._renderContext;
if (!render || !this._objectProvider) {
@@ -373,7 +358,6 @@ export class SlideRenderController extends RxDisposable implements IRenderModule
const slide = mainComponent as Slide;
const { width, height } = slide;
- // new Scene ----> add SubScene.
const pageScene = new Scene(pageId, slide, {
width,
height,
@@ -420,12 +404,12 @@ export class SlideRenderController extends RxDisposable implements IRenderModule
}
/**
- * get pageScene from Slide
- * pageScene was added to the mainComponent(Slide) in createPageScene --> slide.addPageScene
+ * Get pageScene from Slide.
* @param pageId
- * @returns {Scene, Engine, UnitModel}
+ * @returns {Scene, Engine, UnitModel} scene & engine & unit from renderContext
*/
getPageRenderUnit(pageId: PageID) {
+ //pageScene was added to the mainComponent(Slide) in createPageScene --> slide.addPageScene
const subsceneMap = (this._renderContext.mainComponent as Slide).getSubScenes();
const pageScene = subsceneMap.get(pageId) as unknown as Scene;
const { engine, unit } = this._renderContext;
diff --git a/packages/slides-ui/src/services/slide-editor-bridge.service.ts b/packages/slides-ui/src/services/slide-editor-bridge.service.ts
index 66e96c1ec2..7665588840 100644
--- a/packages/slides-ui/src/services/slide-editor-bridge.service.ts
+++ b/packages/slides-ui/src/services/slide-editor-bridge.service.ts
@@ -152,16 +152,12 @@ export class SlideEditorBridgeService extends Disposable implements ISlideEditor
/**
* 1st part of startEditing.
- * editorBridgeRenderController@startEditing ---> editorBridgeRenderController@_updateEditor
* @editorInfo editorInfo
*/
setEditorRect(editorInfo: ISetEditorInfo) {
this._currentEditRectInfo = editorInfo;
-
- /**
- * If there is no editor currently focused, then default to selecting the sheet editor to prevent the editorService from using the previously selected editor object.
- * todo: wzhudev: In univer mode, it is necessary to switch to the corresponding editorId based on the host's unitId.
- */
+ // If there is no editor currently focused, then default to selecting the sheet editor to prevent the editorService from using the previously selected editor object.
+ // todo: wzhudev: In univer mode, it is necessary to switch to the corresponding editorId based on the host's unitId.
if (!this._editorService.getFocusEditor()) {
this._editorService.focus(SLIDE_EDITOR_ID);
this._contextService.setContextValue(EDITOR_ACTIVATED, false);