Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat: optimizing cell rendering and auto-height calculating (#5262)
ZhangWei9bbb3951ed91
diff --git a/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-filter-row-current-worksheet-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-filter-row-current-worksheet-ci-chromium-linux.pngindex 6cc852d87f..278b5614d2 100644Binary files a/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-filter-row-current-worksheet-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-filter-row-current-worksheet-ci-chromium-linux.png differdiff --git a/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-filter-row-other-worksheet-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-filter-row-other-worksheet-ci-chromium-linux.pngindex 58232a98ad..eb68a95f13 100644Binary files a/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-filter-row-other-worksheet-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-filter-row-other-worksheet-ci-chromium-linux.png differdiff --git a/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-hide-row-current-worksheet-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-hide-row-current-worksheet-ci-chromium-linux.pngindex 621567705c..4367f2fdf0 100644Binary files a/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-hide-row-current-worksheet-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-formula-related.spec.ts-snapshots/formula-hide-row-current-worksheet-ci-chromium-linux.png differdiff --git a/e2e/visual-comparison/sheets/sheets-switching-render-unit.spec.ts-snapshots/switching-render-unit-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-switching-render-unit.spec.ts-snapshots/switching-render-unit-ci-chromium-linux.pngindex a1ce64a557..47a8491eb1 100644Binary files a/e2e/visual-comparison/sheets/sheets-switching-render-unit.spec.ts-snapshots/switching-render-unit-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-switching-render-unit.spec.ts-snapshots/switching-render-unit-ci-chromium-linux.png differdiff --git a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/dark-mode-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/dark-mode-ci-chromium-linux.pngindex 2114ff10bd..b9b46c4acd 100644Binary files a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/dark-mode-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/dark-mode-ci-chromium-linux.png differdiff --git a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/default-sheet-fullpage-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/default-sheet-fullpage-ci-chromium-linux.pngindex 5a5e8c93ed..cb5f97c159 100644Binary files a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/default-sheet-fullpage-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/default-sheet-fullpage-ci-chromium-linux.png differdiff --git a/packages/core/src/shared/object-matrix.ts b/packages/core/src/shared/object-matrix.tsindex 28f8d36a12..efd78eb290 100644--- a/packages/core/src/shared/object-matrix.ts+++ b/packages/core/src/shared/object-matrix.ts@@ -29,6 +29,29 @@ export interface IObjectArrayPrimitiveType<T> {[key: number]: T;}+export function mapObjectMatrix<T, R>(o: IObjectMatrixPrimitiveType<T>, callback: (row: number, col: number, value: T) => R): IObjectMatrixPrimitiveType<R> {+ const result: IObjectMatrixPrimitiveType<R> = {};+ for (const row in o) {+ const rowNumber = Number(row);+ const columns = o[rowNumber];+ for (const col in columns) {+ const colNumber = Number(col);+ const value = columns[colNumber];+ const resultValue = callback(rowNumber, colNumber, value);+ if (resultValue !== undefined) {+ if (result[rowNumber]) {+ result[rowNumber][colNumber] = resultValue;+ } else {+ result[rowNumber] = {+ [colNumber]: resultValue,+ };+ }+ }+ }+ }+ return result;+}+export function getArrayLength<T>(o: IObjectArrayPrimitiveType<T> | IObjectMatrixPrimitiveType<T>) {let maxIndex = 0;const keys = Object.keys(o);@@ -211,8 +234,6 @@ function _moveForward<T>(});}-// TODO: this is not a good name-/*** A two-dimensional array represented by a two-level deep object and provides an array-like API*@@ -701,6 +722,15 @@ export class ObjectMatrix<T> {return ranges;}+ merge(newObject: ObjectMatrix<Nullable<T>>) {+ this.forValue((row, column) => {+ const cellValue = newObject.getValue(row, column);+ if (cellValue != null) {+ this.setValue(row, column, cellValue);+ }+ });+ }+private _setOriginValue(matrix: IObjectMatrixPrimitiveType<T> = {}) {this._matrix = matrix;}diff --git a/packages/core/src/sheets/worksheet.ts b/packages/core/src/sheets/worksheet.tsindex 059b10e56d..a86a392d71 100644--- a/packages/core/src/sheets/worksheet.ts+++ b/packages/core/src/sheets/worksheet.ts@@ -14,6 +14,7 @@* limitations under the License.*/+import type { IDisposable } from '@wendellhu/redi';import type { IInterceptor } from '../common/interceptor';import type { IObjectMatrixPrimitiveType, Nullable } from '../shared';import type { BooleanNumber, HorizontalAlign, TextDirection, VerticalAlign, WrapStrategy } from '../types/enum';@@ -22,7 +23,7 @@ import type { Styles } from './styles';import type { CustomData, ICellData, ICellDataForSheetInterceptor, ICellDataWithSpanAndDisplay, IFreeze, IRange, ISelectionCell, IWorksheetData } from './typedef';import { BuildTextUtils, DocumentDataModel } from '../docs';import { convertTextRotation, getFontStyleString } from '../docs/data-model/utils';-import { composeStyles, ObjectMatrix, Tools } from '../shared';+import { composeStyles, ObjectMatrix, toDisposable, Tools } from '../shared';import { createRowColIter } from '../shared/row-col-iter';import { DEFAULT_STYLES } from '../types/const';import { CellValueType } from '../types/enum';@@ -73,7 +74,7 @@ const DEFAULT_CELL_DOCUMENT_MODEL_OPTION = {export class Worksheet {protected _sheetId: string;protected _snapshot: IWorksheetData;- protected _cellData: ObjectMatrix<ICellData>;+ protected _cellData: ObjectMatrix<Nullable<ICellData>>;protected _rowManager: RowManager;protected _columnManager: ColumnManager;@@ -82,6 +83,8 @@ export class Worksheet {protected _spanModel: SpanModel;+ private _getCellHeight: Nullable<(row: number, col: number) => number>;+constructor(public readonly unitId: string,snapshot: Partial<IWorksheetData>,@@ -91,7 +94,7 @@ export class Worksheet {const { columnData, rowData, cellData } = this._snapshot;this._sheetId = this._snapshot.id ?? Tools.generateRandomId(6);- this._cellData = new ObjectMatrix<ICellData>(cellData as IObjectMatrixPrimitiveType<ICellData>);+ this._cellData = new ObjectMatrix<Nullable<ICellData>>(cellData as IObjectMatrixPrimitiveType<Nullable<ICellData>>);// This view model will immediately injected with hooks from SheetViewModel service as Worksheet is constructed.this._viewModel = new SheetViewModel((row, col) => this.getCellRaw(row, col));@@ -108,10 +111,29 @@ export class Worksheet {callback(this._viewModel);}+ /**+ * @internal+ * this is an internal method, please do not use it+ */+ __registerGetCellHeight(callback: (row: number, col: number) => number): IDisposable {+ this._getCellHeight = callback;++ return toDisposable(() => {+ this._getCellHeight = null;+ });+ }+getSnapshot(): IWorksheetData {return this._snapshot;}+ getCellHeight(row: number, col: number): number {+ if (this._getCellHeight) {+ return this._getCellHeight(row, col);+ }+ return this._snapshot.defaultRowHeight;+ }+/*** Set the merge data of the sheet, all the merged cells will be rebuilt.* @param mergeDatadiff --git a/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.tsindex 0deacc37e3..19ea2eaa29 100644--- a/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts+++ b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts@@ -392,7 +392,7 @@ describe('Test formula data model', () => {},};- const cellMatrix = new ObjectMatrix(cellValue);+ const cellMatrix = new ObjectMatrix<Nullable<ICellData>>(cellValue);const result = {[unitId]: {diff --git a/packages/engine-render/src/basics/tools.ts b/packages/engine-render/src/basics/tools.tsindex 47a638c11a..1de5e323c6 100644--- a/packages/engine-render/src/basics/tools.ts+++ b/packages/engine-render/src/basics/tools.ts@@ -247,7 +247,7 @@ export function fixLineWidthByScale(num: number, scale: number) {// eslint-disable-next-line max-lines-per-functionexport function getFontStyleString(- textStyle?: IStyleBase+ textStyle?: Nullable<IStyleBase>): IDocumentSkeletonFontStyle {const defaultFont = DEFAULT_STYLES.ff;diff --git a/packages/engine-render/src/components/docs/layout/doc-simple-skeleton.ts b/packages/engine-render/src/components/docs/layout/doc-simple-skeleton.tsnew file mode 100644index 0000000000..d3423dd689--- /dev/null+++ b/packages/engine-render/src/components/docs/layout/doc-simple-skeleton.ts@@ -0,0 +1,147 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { LineBreaker } from './line-breaker';+import { FontCache } from './shaping-engine/font-cache';++export interface ILineInfo {+ text: string;+ width: number;+ height: number;+ baseline: number;+}++export class DocSimpleSkeleton {+ private _lineBreaker: LineBreaker;+ private _lines: ILineInfo[] = [];+ private _dirty = true;++ constructor(+ private _text: string,+ private _fontStyle: string,+ private _warp: boolean,+ private _width: number,+ private _height: number+ ) {+ this._lineBreaker = new LineBreaker(this._text);+ }++ calculate() {+ if (!this._dirty) {+ return this._lines;+ }+ this._dirty = false;+ this._lines = [];+ if (this._text.length === 0) {+ const textSize = FontCache.getMeasureText('A', this._fontStyle);+ this._lines.push({+ text: '',+ width: 0,+ height: textSize.fontBoundingBoxAscent + textSize.fontBoundingBoxDescent,+ baseline: textSize.fontBoundingBoxAscent,+ });+ return this._lines;+ }++ if (!this._warp) {+ const textSize = FontCache.getMeasureText(this._text, this._fontStyle);+ this._lines.push({+ text: this._text,+ width: textSize.width,+ height: textSize.fontBoundingBoxAscent + textSize.fontBoundingBoxDescent,+ baseline: textSize.fontBoundingBoxAscent,+ });+ return this._lines;+ }++ let lastPosition = 0;+ let currentLine: ILineInfo = {+ text: '',+ width: 0,+ height: 0,+ baseline: 0,+ };++ let totalHeight = 0;+ while (true) {+ const breakPoint = this._lineBreaker.nextBreakPoint();+ if (!breakPoint) {+ break;+ }+ const { position } = breakPoint;+ const text = this._text.slice(lastPosition, position);+ const textSize = FontCache.getMeasureText(text, this._fontStyle);++ // Check if adding this text would exceed the width+ if ((textSize.width + currentLine.width) > this._width) {+ if (currentLine.text.length > 0) {+ // Push the current line first+ this._lines.push({ ...currentLine });+ totalHeight += currentLine.height;+ if (totalHeight > this._height) {+ break;+ }+ // Reset current line and add the new text+ currentLine = {+ text,+ width: textSize.width,+ height: textSize.fontBoundingBoxAscent + textSize.fontBoundingBoxDescent,+ baseline: textSize.fontBoundingBoxAscent,+ };+ } else {+ // If current line is empty, we have to add this text anyway (single word too long)+ currentLine = {+ text,+ width: textSize.width,+ height: textSize.fontBoundingBoxAscent + textSize.fontBoundingBoxDescent,+ baseline: textSize.fontBoundingBoxAscent,+ };+ }+ } else {+ // Add text to current line+ currentLine.text = currentLine.text + text;+ currentLine.width = currentLine.width + textSize.width;+ currentLine.baseline = textSize.fontBoundingBoxAscent;+ currentLine.height = textSize.fontBoundingBoxAscent + textSize.fontBoundingBoxDescent;+ }++ lastPosition = position;+ }++ // Don't forget to add the last line if it has content+ if (currentLine.text.length > 0) {+ this._lines.push({ ...currentLine });+ }++ return this._lines;+ }++ getLines() {+ return this._lines;+ }++ getTotalHeight() {+ return this._lines.reduce((acc, line) => acc + line.height, 0);+ }++ getTotalWidth() {+ return this._lines.reduce((acc, line) => Math.max(acc, line.width), 0);+ }++ makeDirty() {+ this._dirty = true;+ }+}diff --git a/packages/engine-render/src/components/sheets/extensions/font.ts b/packages/engine-render/src/components/sheets/extensions/font.tsindex d9f60046af..c3c44f2463 100644--- a/packages/engine-render/src/components/sheets/extensions/font.ts+++ b/packages/engine-render/src/components/sheets/extensions/font.ts@@ -25,13 +25,14 @@ import type { IDrawInfo } from '../../extension';import type { IFontCacheItem } from '../interfaces';import type { SheetComponent } from '../sheet-component';import type { SpreadsheetSkeleton } from '../sheet.render-skeleton';-import { HorizontalAlign, Range, VerticalAlign, WrapStrategy } from '@univerjs/core';+import { CellValueType, HorizontalAlign, Range, VerticalAlign, WrapStrategy } from '@univerjs/core';import { FIX_ONE_PIXEL_BLUR_OFFSET } from '../../../basics';import { VERTICAL_ROTATE_ANGLE } from '../../../basics/text-rotation';import { clampRange, inViewRanges } from '../../../basics/tools';+import { Text } from '../../../shape/text';import { SpreadsheetExtensionRegistry } from '../../extension';import { EXPAND_SIZE_FOR_RENDER_OVERFLOW, FONT_EXTENSION_Z_INDEX } from '../constants';-import { getDocsSkeletonPageSize } from '../sheet.render-skeleton';+import { DEFAULT_PADDING_DATA, getDocsSkeletonPageSize } from '../sheet.render-skeleton';import { SheetExtension } from './sheet-extension';const UNIQUE_KEY = 'DefaultFontExtension';@@ -200,7 +201,6 @@ export class Font extends SheetExtension {const fontCache = fontMatrix.getValue(row, col);if (!fontCache) return true;- if (!fontCache.documentSkeleton) return true;renderFontCtx.fontCache = fontCache;//#region overflow@@ -242,19 +242,24 @@ export class Font extends SheetExtension {//#endregionctx.translate(renderFontCtx.startX + FIX_ONE_PIXEL_BLUR_OFFSET, renderFontCtx.startY + FIX_ONE_PIXEL_BLUR_OFFSET);- this._renderDocuments(ctx, row, col, renderFontCtx, spreadsheetSkeleton.overflowCache);-+ if (fontCache.documentSkeleton) {+ this._renderDocuments(ctx, row, col, renderFontCtx, spreadsheetSkeleton.overflowCache);+ } else {+ this._renderText(ctx, row, col, renderFontCtx, spreadsheetSkeleton.overflowCache);+ }ctx.closePath();ctx.restore();- const documentDataModel = fontCache.documentSkeleton.getViewModel().getDataModel();- if (documentDataModel.getDrawingsOrder()?.length) {- ctx.save();- ctx.beginPath();- this._clipByRenderBounds(renderFontCtx, row, col, 1);- this._renderImages(ctx, fontCache, renderFontCtx.startX, renderFontCtx.startY, renderFontCtx.endX, renderFontCtx.endY);- ctx.closePath();- ctx.restore();+ if (fontCache.documentSkeleton) {+ const documentDataModel = fontCache.documentSkeleton.getViewModel().getDataModel();+ if (documentDataModel.getDrawingsOrder()?.length) {+ ctx.save();+ ctx.beginPath();+ this._clipByRenderBounds(renderFontCtx, row, col, 1);+ this._renderImages(ctx, fontCache, renderFontCtx.startX, renderFontCtx.startY, renderFontCtx.endX, renderFontCtx.endY);+ ctx.closePath();+ ctx.restore();+ }}renderFontCtx.startX = 0;@@ -267,8 +272,8 @@ export class Font extends SheetExtension {private _renderImages(ctx: UniverRenderingContext, fontsConfig: IFontCacheItem, startX: number, startY: number, endX: number, endY: number) {const { documentSkeleton, verticalAlign, horizontalAlign } = fontsConfig;- const fontHeight = documentSkeleton.getSkeletonData()!.pages[0].height;- const fontWidth = documentSkeleton.getSkeletonData()!.pages[0].width;+ const fontHeight = documentSkeleton!.getSkeletonData()!.pages[0].height;+ const fontWidth = documentSkeleton!.getSkeletonData()!.pages[0].width;const PADDING = 2;let fontX = startX;let fontY = startY;@@ -296,9 +301,9 @@ export class Font extends SheetExtension {break;}- const documentDataModel = documentSkeleton.getViewModel().getDataModel();+ const documentDataModel = documentSkeleton!.getViewModel().getDataModel();const drawingDatas = documentDataModel.getDrawings();- const drawings = documentSkeleton.getSkeletonData()?.pages[0].skeDrawings;+ const drawings = documentSkeleton!.getSkeletonData()?.pages[0].skeDrawings;drawings?.forEach((drawing) => {const drawingData = drawingDatas?.[drawing.drawingId] as { imageSourceType: ImageSourceType; source: string } & IDocDrawingBase;if (drawingData) {@@ -439,6 +444,57 @@ export class Font extends SheetExtension {renderFontContext.endY = endY;}+ private _renderText(+ ctx: UniverRenderingContext,+ row: number,+ col: number,+ renderFontCtx: IRenderFontContext,+ overflowCache: ObjectMatrix<IRange>+ ) {+ const { fontCache } = renderFontCtx;+ if (!fontCache) return;++ const { vertexAngle = 0, wrapStrategy, cellData } = fontCache;+ if (cellData?.v === undefined || cellData?.v === null) return;+ const text = String(cellData.v) as string;+ let { startX, startY, endX, endY } = renderFontCtx;+ let cellWidth = endX - startX - DEFAULT_PADDING_DATA.l - DEFAULT_PADDING_DATA.r;+ const cellHeight = endY - startY - DEFAULT_PADDING_DATA.t - DEFAULT_PADDING_DATA.b;++ const overflowRectangle = overflowCache.getValue(row, col);+ const isOverflow = !(wrapStrategy === WrapStrategy.WRAP && vertexAngle === 0);+ if (isOverflow && overflowRectangle) {+ const endColumn = overflowRectangle.endColumn;+ const startColumn = overflowRectangle.startColumn;+ const startRow = overflowRectangle.startRow;+ const endRow = overflowRectangle.endRow;+ const endCell = renderFontCtx.spreadsheetSkeleton.getCellWithCoordByIndex(endRow, endColumn);+ endX = endCell.endX;+ endY = endCell.endY;++ const startCell = renderFontCtx.spreadsheetSkeleton.getCellWithCoordByIndex(startRow, startColumn);+ startX = startCell.startX;+ startY = startCell.startY;+ cellWidth = endX - startX - DEFAULT_PADDING_DATA.l - DEFAULT_PADDING_DATA.r;+ }++ const isNumber = cellData.t === CellValueType.NUMBER && typeof cellData.v === 'number';+ Text.drawWith(ctx, {+ text,+ fontStyle: fontCache.fontString,+ warp: wrapStrategy === WrapStrategy.WRAP && vertexAngle === 0,+ hAlign: isNumber && fontCache.horizontalAlign === HorizontalAlign.UNSPECIFIED ? HorizontalAlign.RIGHT : fontCache.horizontalAlign,+ vAlign: fontCache.verticalAlign,+ width: cellWidth,+ height: cellHeight,+ left: DEFAULT_PADDING_DATA.l,+ top: DEFAULT_PADDING_DATA.t,+ color: fontCache.style?.cl?.rgb,+ strokeLine: Boolean(fontCache.style?.st?.s),+ underline: Boolean(fontCache.style?.ul?.s),+ });+ }+private _renderDocuments(ctx: UniverRenderingContext,row: number,diff --git a/packages/engine-render/src/components/sheets/interfaces.ts b/packages/engine-render/src/components/sheets/interfaces.tsindex f199c675d9..f346be3b3b 100644--- a/packages/engine-render/src/components/sheets/interfaces.ts+++ b/packages/engine-render/src/components/sheets/interfaces.ts@@ -20,6 +20,7 @@ import type {ICellDataForSheetInterceptor,ICellWithCoord,ImageCacheMap,+ IStyleData,Nullable,ObjectMatrix,VerticalAlign,@@ -42,7 +43,7 @@ export interface BorderCacheItem {}export interface IFontCacheItem {- documentSkeleton: DocumentSkeleton;+ documentSkeleton?: DocumentSkeleton;vertexAngle?: number; // Text rotation offset based on the top-left corner.centerAngle?: number; // Text rotation based on the center point.verticalAlign: VerticalAlign;@@ -50,13 +51,14 @@ export interface IFontCacheItem {wrapStrategy: WrapStrategy;imageCacheMap: ImageCacheMap;cellData: Nullable<ICellDataForSheetInterceptor>;+ fontString: string;+ style?: Nullable<IStyleData>;}type colorString = string;export interface IStylesCache {background?: Record<colorString, ObjectMatrix<string>>;backgroundPositions?: ObjectMatrix<ICellWithCoord>;- font?: Record<string, ObjectMatrix<IFontCacheItem>>;/*** Get value from getCell in skeleton and this value is used in font extension*/diff --git a/packages/engine-render/src/components/sheets/sheet.render-skeleton.ts b/packages/engine-render/src/components/sheets/sheet.render-skeleton.tsindex b5c715667c..60aea4115c 100644--- a/packages/engine-render/src/components/sheets/sheet.render-skeleton.ts+++ b/packages/engine-render/src/components/sheets/sheet.render-skeleton.ts@@ -34,8 +34,6 @@ import type {ITextRotation,Nullable,Styles,- VerticalAlign,-Worksheet,} from '@univerjs/core';import type { IDocumentSkeletonColumn } from '../../basics/i-document-skeleton-cached';@@ -64,9 +62,11 @@ import {searchArray,SheetSkeleton,Tools,+ VerticalAlign,WrapStrategy,} from '@univerjs/core';import { distinctUntilChanged, startWith } from 'rxjs';+import { FontCache } from '../../basics';import { BORDER_TYPE as BORDER_LTRB, COLOR_BLACK_RGB, MAXIMUM_COL_WIDTH, MAXIMUM_ROW_HEIGHT, MIN_COL_WIDTH } from '../../basics/const';import { getRotateOffsetAndFarthestHypotenuse } from '../../basics/draw';import { convertTextRotation, VERTICAL_ROTATE_ANGLE } from '../../basics/text-rotation';@@ -74,6 +74,7 @@ import {degToRad,getFontStyleString,} from '../../basics/tools';+import { DocSimpleSkeleton } from '../docs/layout/doc-simple-skeleton';import { DocumentSkeleton } from '../docs/layout/doc-skeleton';import { columnIterator } from '../docs/layout/tools';import { DocumentViewModel } from '../docs/view-model/document-view-model';@@ -129,6 +130,8 @@ export interface IGetPosByRowColOptions {firstMatch?: boolean;}+const CACHE_COUNT = 100;+export class SpreadsheetSkeleton extends SheetSkeleton {/*** Range viewBounds. only update by viewBounds.@@ -149,19 +152,18 @@ export class SpreadsheetSkeleton extends SheetSkeleton {private _stylesCache: IStylesCache = {background: {},backgroundPositions: new ObjectMatrix<ICellWithCoord>(),- font: {} as Record<string, ObjectMatrix<IFontCacheItem>>,fontMatrix: new ObjectMatrix<IFontCacheItem>(),border: new ObjectMatrix<BorderCache>(),};+ private _clearTaskId: Nullable<number> = null;/** A matrix to store if a (row, column) position has render cache. */private _handleBgMatrix = new ObjectMatrix<boolean>();private _handleBorderMatrix = new ObjectMatrix<boolean>();- private _handleFontMatrix = new ObjectMatrix<boolean>();private _showGridlines: BooleanNumber = BooleanNumber.TRUE;private _gridlinesColor: string | undefined = undefined;-private _scene: Nullable<Scene> = null;+constructor(worksheet: Worksheet,_styles: Styles,@@ -182,6 +184,10 @@ export class SpreadsheetSkeleton extends SheetSkeleton {this.makeDirty(true);}));++ this.disposeWithMe(this.worksheet.__registerGetCellHeight((row, col) => {+ return this.calculateAutoHeightForCell(row, col) ?? 0;+ }));}setScene(scene: Scene) {@@ -248,7 +254,6 @@ export class SpreadsheetSkeleton extends SheetSkeleton {this._stylesCache = {background: {},backgroundPositions: new ObjectMatrix<ICellWithCoord>(),- font: {} as Record<string, ObjectMatrix<IFontCacheItem>>,fontMatrix: new ObjectMatrix<IFontCacheItem>(),border: new ObjectMatrix<BorderCache>(),};@@ -310,6 +315,30 @@ export class SpreadsheetSkeleton extends SheetSkeleton {return this._visibleRangeMap;}+ /**+ * Clear cache out of visible range when browser are free.+ */+ private _clearCacheOutOfVisibleRange(visibleStartRow: number, visibleEndRow: number, visibleStartColumn: number, visibleEndColumn: number) {+ if (this._clearTaskId) {+ cancelIdleCallback(this._clearTaskId);+ }++ this._clearTaskId = requestIdleCallback(() => {+ this._stylesCache.fontMatrix.forValue((row, col) => {+ if (+ row < (visibleStartRow - CACHE_COUNT) ||+ row > (visibleEndRow + CACHE_COUNT) ||+ col < (visibleStartColumn - CACHE_COUNT) ||+ col > (visibleEndColumn + CACHE_COUNT)+ ) {+ this._stylesCache.fontMatrix.realDeleteValue(row, col);+ }+ });++ this._clearTaskId = null;+ });+ }+/*** Set border background and font to this._stylesCache by visible range, which derives from bounds)* @param vpInfo viewBounds@@ -324,6 +353,9 @@ export class SpreadsheetSkeleton extends SheetSkeleton {const columnWidthAccumulation = this.columnWidthAccumulation;const { startRow: visibleStartRow, endRow: visibleEndRow, startColumn: visibleStartColumn, endColumn: visibleEndColumn } = rowColumnSegment;+ // clear cache out of visible range+ this._clearCacheOutOfVisibleRange(visibleStartRow, visibleEndRow, visibleStartColumn, visibleEndColumn);+if (visibleEndColumn === -1 || visibleEndRow === -1) return;const mergeRanges = this.getCurrentRowColumnSegmentMergeData(this._drawingRange);@@ -364,7 +396,7 @@ export class SpreadsheetSkeleton extends SheetSkeleton {* @param ranges* @returns {IRowAutoHeightInfo[]} result*/- calculateAutoHeightInRange(ranges: Nullable<IRange[]>): IRowAutoHeightInfo[] {+ calculateAutoHeightInRange(ranges: Nullable<IRange[]>, currentCellHeights?: ObjectMatrix<number>): IRowAutoHeightInfo[] {if (!Tools.isArray(ranges)) {return [];}@@ -373,11 +405,12 @@ export class SpreadsheetSkeleton extends SheetSkeleton {const { rowData } = this._worksheetData;const rowObjectArray = rowData;const calculatedRows = new Set<number>();+ const rowCount = this.worksheet.getRowCount();for (const range of ranges) {const { startRow, endRow, startColumn, endColumn } = range;-- for (let rowIndex = startRow; rowIndex <= endRow; rowIndex++) {+ const end = Math.min(endRow, rowCount);+ for (let rowIndex = startRow; rowIndex <= end; rowIndex++) {// If the row has already been calculated, it does not need to be calculatedif (calculatedRows.has(rowIndex)) {continue;@@ -391,12 +424,49 @@ export class SpreadsheetSkeleton extends SheetSkeleton {const hasUnMergedCell = this._hasUnMergedCellInRow(rowIndex, startColumn, endColumn);if (hasUnMergedCell) {- const autoHeight = this._calculateRowAutoHeight(rowIndex);- calculatedRows.add(rowIndex);- results.push({- row: rowIndex,- autoHeight,- });+ // if `currentCellHeights` is provided, we just need to compare `newHeights` with `currentCellHeights` to figure out if we should update the row height+ if (currentCellHeights) {+ const currentAutoHeight = this.worksheet.getRowHeight(rowIndex);+ let maxPrev = 0;+ let maxCurrent = 0;+ for (let colIndex = startColumn; colIndex <= endColumn; colIndex++) {+ const autoHeight = currentCellHeights.getValue(rowIndex, colIndex) ?? 0;+ maxPrev = Math.max(maxPrev, autoHeight);+ const currentHeight = this.calculateAutoHeightForCell(rowIndex, colIndex) ?? this._worksheetData.defaultRowHeight;+ maxCurrent = Math.max(maxCurrent, currentHeight);+ }++ if (maxPrev < currentAutoHeight) {+ calculatedRows.add(rowIndex);++ results.push({+ row: rowIndex,+ autoHeight: Math.max(currentAutoHeight, maxCurrent),+ });+ } else {+ if (maxCurrent >= currentAutoHeight) {+ calculatedRows.add(rowIndex);+ results.push({+ row: rowIndex,+ autoHeight: maxCurrent,+ });+ } else {+ const autoHeight = this._calculateRowAutoHeight(rowIndex);+ calculatedRows.add(rowIndex);+ results.push({+ row: rowIndex,+ autoHeight,+ });+ }+ }+ } else {+ const autoHeight = this._calculateRowAutoHeight(rowIndex);+ calculatedRows.add(rowIndex);+ results.push({+ row: rowIndex,+ autoHeight,+ });+ }}}}@@ -404,55 +474,61 @@ export class SpreadsheetSkeleton extends SheetSkeleton {return results;}- // eslint-disable-next-line max-lines-per-function- private _calculateRowAutoHeight(rowNum: number): number {- const worksheet = this.worksheet;- const { columnCount, columnData, defaultRowHeight, defaultColumnWidth } = this._worksheetData;- let height = defaultRowHeight;-- for (let i = 0; i < columnCount; i++) {- // When calculating the automatic height of a row, if a cell is in a merged cell,- // skip the cell directly, which currently follows the logic of Excel- const cellMergeInfo = this.worksheet.getCellInfoInMergeData(rowNum, i);- if (this._skipAutoHeightForMergedCells) {- if (cellMergeInfo.isMerged || cellMergeInfo.isMergedMainCell) {- continue;- }+ // eslint-disable-next-line max-lines-per-function, complexity+ calculateAutoHeightForCell(row: number, col: number) {+ const { columnData, defaultColumnWidth } = this._worksheetData;+ const cellMergeInfo = this.worksheet.getCellInfoInMergeData(row, col);+ if (this._skipAutoHeightForMergedCells) {+ if (cellMergeInfo.isMerged || cellMergeInfo.isMergedMainCell) {+ return undefined;}- const cell = worksheet.getCell(rowNum, i);- if (cell?.interceptorAutoHeight) {- const cellHeight = cell.interceptorAutoHeight();- if (cellHeight) {- height = Math.max(height, cellHeight);- continue;- }+ }++ // TODO@weird94: in future, we should use `getCellRaw` instead of `getCell` to improve performance.+ const cell = this.worksheet.getCell(row, col);+ const style = this._styles.getStyleByCell(cell);++ if (cell?.interceptorAutoHeight) {+ const cellHeight = cell.interceptorAutoHeight();+ if (cellHeight) {+ return cellHeight;}+ }++ const sideGap = (cell?.fontRenderExtension?.leftOffset ?? 0) + (cell?.fontRenderExtension?.rightOffset ?? 0);++ const { vertexAngle, centerAngle } = convertTextRotation(style?.tr ?? { a: 0 });+ const isRichText = cell?.p || vertexAngle || centerAngle;+ let colWidth = columnData[col]?.w ?? defaultColumnWidth;+ if (cellMergeInfo.isMergedMainCell) {+ const mergeCellStartCol = cellMergeInfo.startColumn;+ const mergeCellEndCol = cellMergeInfo.endColumn;++ colWidth = Array.from(+ { length: mergeCellEndCol - mergeCellStartCol + 1 },+ (_, index) => mergeCellStartCol + index+ ).reduce((sum, colIndex) => {+ return sum + (columnData[colIndex]?.w ?? defaultColumnWidth);+ }, 0);+ }++ colWidth -= sideGap;++ if (isRichText) {const modelObject = cell && this._getCellDocumentModel(cell);if (modelObject == null) {- continue;+ return undefined;}const { documentModel, textRotation, wrapStrategy } = modelObject;if (documentModel == null) {- continue;+ return undefined;}const documentViewModel = new DocumentViewModel(documentModel);const { vertexAngle: angle } = convertTextRotation(textRotation);- let colWidth = columnData[i]?.w ?? defaultColumnWidth;- if (cellMergeInfo.isMergedMainCell) {- const mergeCellStartCol = cellMergeInfo.startColumn;- const mergeCellEndCol = cellMergeInfo.endColumn;- const mergeCellWidth = mergeCellEndCol - mergeCellStartCol + 1;- colWidth = Array.from(- { length: mergeCellEndCol - mergeCellStartCol + 1 },- (_, index) => mergeCellStartCol + index- ).reduce((sum, colIndex) => {- return sum + (columnData[colIndex]?.w ?? defaultColumnWidth);- }, 0);- }if (typeof colWidth === 'number' && wrapStrategy === WrapStrategy.WRAP) {documentModel.updateDocumentDataPageSize(colWidth);}@@ -482,7 +558,40 @@ export class SpreadsheetSkeleton extends SheetSkeleton {l * Math.sin(absAngleInRad);}- height = Math.max(height, h);+ return h;+ } else {+ if (cell?.v === undefined || cell?.v === null) {+ return undefined;+ }++ if (style?.tb === WrapStrategy.WRAP) {+ const skeleton = new DocSimpleSkeleton(+ `${cell!.v!}`,+ getFontStyleString(style).fontCache,+ style?.tb === WrapStrategy.WRAP,+ colWidth - DEFAULT_PADDING_DATA.l - DEFAULT_PADDING_DATA.r,+ Infinity+ );+ skeleton.calculate();+ return skeleton.getTotalHeight();+ } else {+ // For same fontStyle, the height of the text is fixed.+ // So we can use a fixed text to calculate the height to make a speed up.+ const textSize = FontCache.getMeasureText('A', getFontStyleString(style).fontCache);+ return textSize.fontBoundingBoxAscent + textSize.fontBoundingBoxDescent + DEFAULT_PADDING_DATA.t + DEFAULT_PADDING_DATA.b;+ }+ }+ }++ private _calculateRowAutoHeight(rowNum: number): number {+ const { columnCount, defaultRowHeight } = this._worksheetData;+ let height = defaultRowHeight;++ for (let i = 0; i < columnCount; i++) {+ const cellHeight = this.calculateAutoHeightForCell(rowNum, i);+ if (cellHeight) {+ height = Math.max(height, cellHeight);+ }}return Math.min(height, MAXIMUM_ROW_HEIGHT);@@ -510,7 +619,7 @@ export class SpreadsheetSkeleton extends SheetSkeleton {calculatedCols.add(colIndex);results.push({col: colIndex,- width: autoWidth,+ width: Math.max(this._worksheetData.defaultColumnWidth, autoWidth),});}}@@ -924,7 +1033,6 @@ export class SpreadsheetSkeleton extends SheetSkeleton {if (cell.t === CellValueType.FORCE_STRING && displayRawFormula) {cellText = `'${cellText}`;}-documentModel = createDocumentModelWithStyle(cellText, textStyle, {...cellOtherConfig,textRotation,@@ -1000,8 +1108,17 @@ export class SpreadsheetSkeleton extends SheetSkeleton {return true;}- let contentSize = getDocsSkeletonPageSize(documentSkeleton, vertexAngle);+ let contentSize;+ if (documentSkeleton) {+ contentSize = getDocsSkeletonPageSize(documentSkeleton, vertexAngle);+ } else {+ const textSize = FontCache.getMeasureText(`${docsConfig.cellData!.v!}`, docsConfig.fontString);+ contentSize = {+ width: textSize.width,+ height: textSize.fontBoundingBoxDescent + textSize.fontBoundingBoxAscent,+ };+ }if (!contentSize) {return true;}@@ -1044,9 +1161,9 @@ export class SpreadsheetSkeleton extends SheetSkeleton {);const cellHeight = endY - startY;- documentSkeleton.getViewModel().getDataModel().updateDocumentDataPageSize(cellHeight);- documentSkeleton.calculate();- const contentSize = getDocsSkeletonPageSize(documentSkeleton, vertexAngle);+ documentSkeleton!.getViewModel().getDataModel().updateDocumentDataPageSize(cellHeight);+ documentSkeleton!.calculate();+ const contentSize = getDocsSkeletonPageSize(documentSkeleton!, vertexAngle);if (!contentSize) {return true;@@ -1139,7 +1256,6 @@ export class SpreadsheetSkeleton extends SheetSkeleton {this._stylesCache = {background: {},backgroundPositions: new ObjectMatrix<ICellWithCoord>(),- font: {},fontMatrix: new ObjectMatrix<IFontCacheItem>(),border: new ObjectMatrix<BorderCache>(),};@@ -1234,17 +1350,20 @@ export class SpreadsheetSkeleton extends SheetSkeleton {this._stylesCache.fontMatrix.setValue(row, col, cacheValue as IFontCacheItem);return;}+ const style = this._styles.getStyleByCell(cellData);+ const { vertexAngle, centerAngle } = convertTextRotation(style?.tr ?? { a: 0 });+ const isRichText = cellData?.p || vertexAngle || centerAngle;++ const modelObject = isRichText ?+ this._getCellDocumentModel(cellData, { displayRawFormula: this._renderRawFormula })+ : null;- const modelObject = this._getCellDocumentModel(cellData, {- displayRawFormula: this._renderRawFormula,- });if (modelObject) {const { documentModel } = modelObject;if (documentModel) {- const { fontString: _fontString, textRotation, wrapStrategy, verticalAlign, horizontalAlign } = modelObject;+ const { fontString, wrapStrategy, verticalAlign, horizontalAlign } = modelObject;const documentViewModel = new DocumentViewModel(documentModel);if (documentViewModel) {- const { vertexAngle, centerAngle } = convertTextRotation(textRotation);const documentSkeleton = DocumentSkeleton.create(documentViewModel, this._localeService);documentSkeleton.calculate();@@ -1257,15 +1376,29 @@ export class SpreadsheetSkeleton extends SheetSkeleton {wrapStrategy,imageCacheMap: this._imageCacheMap,cellData,+ fontString,+ style,};- this._calculateOverflowCell(row, col, config as IFontCacheItem);- this._handleFontMatrix.setValue(row, col, true);}}+ } else {+ const fontString = getFontStyleString(style ?? undefined).fontCache;+ const { vt: verticalAlign, ht: horizontalAlign, tb: wrapStrategy } = style ?? {};+ config = {+ documentSkeleton: undefined,+ vertexAngle,+ centerAngle,+ verticalAlign: verticalAlign ?? VerticalAlign.UNSPECIFIED,+ horizontalAlign: horizontalAlign ?? HorizontalAlign.UNSPECIFIED,+ wrapStrategy: wrapStrategy ?? WrapStrategy.OVERFLOW,+ imageCacheMap: this._imageCacheMap,+ cellData,+ fontString,+ style,+ };}-+ this._calculateOverflowCell(row, col, config as IFontCacheItem);this._stylesCache.fontMatrix.setValue(row, col, config as IFontCacheItem);- this._handleFontMatrix.setValue(row, col, true);}/**diff --git a/packages/engine-render/src/index.ts b/packages/engine-render/src/index.tsindex 4156b9bb2d..5f05afc13c 100644--- a/packages/engine-render/src/index.ts+++ b/packages/engine-render/src/index.ts@@ -16,6 +16,7 @@export * from './base-object';export * from './basics';+export * from './components/docs/layout/doc-simple-skeleton';export { getOffsetRectForDom } from './basics/position';export * from './canvas';export * from './components';diff --git a/packages/engine-render/src/shape/index.ts b/packages/engine-render/src/shape/index.tsindex f1774da722..232c1ad33c 100644--- a/packages/engine-render/src/shape/index.ts+++ b/packages/engine-render/src/shape/index.ts@@ -26,3 +26,4 @@ export * from './regular-polygon';export * from './rich-text';export * from './scroll-bar';export * from './shape';+export * from './text';diff --git a/packages/engine-render/src/shape/text.ts b/packages/engine-render/src/shape/text.tsindex 3f58b03ee4..dc4bff6499 100644--- a/packages/engine-render/src/shape/text.ts+++ b/packages/engine-render/src/shape/text.ts@@ -14,11 +14,157 @@* limitations under the License.*/+import type { IKeyValue, Nullable } from '@univerjs/core';+import type { UniverRenderingContext } from '../context';import type { IShapeProps } from './shape';+import { HorizontalAlign, VerticalAlign } from '@univerjs/core';+import { COLOR_BLACK_RGB } from '../basics';+import { DocSimpleSkeleton } from '../components/docs/layout/doc-simple-skeleton';import { Shape } from './shape';export interface ITextProps extends IShapeProps {width: number;+ height: number;+ text: string;+ fontStyle: string;+ warp?: boolean;+ hAlign?: HorizontalAlign;+ vAlign?: VerticalAlign;+ color?: Nullable<string>;+ strokeLine?: boolean;+ underline?: boolean;}-export class Text extends Shape<ITextProps> {}+export const TEXT_OBJECT_ARRAY = ['text', 'fontStyle', 'warp', 'hAlign', 'vAlign', 'width', 'height', 'color'];++export class Text extends Shape<ITextProps> {+ text: string;+ fontStyle: string;+ warp: boolean;+ hAlign: HorizontalAlign;+ vAlign: VerticalAlign;+ skeleton: DocSimpleSkeleton;++ constructor(key: string, props: ITextProps) {+ super(key, props);++ this.width = props.width;+ this.height = props.height;+ this.text = props.text;+ this.fontStyle = props.fontStyle;+ this.warp = props.warp ?? false;+ this.hAlign = props.hAlign ?? HorizontalAlign.LEFT;+ this.vAlign = props.vAlign ?? VerticalAlign.TOP;+ this.skeleton = new DocSimpleSkeleton(+ props.text,+ props.fontStyle,+ Boolean(props.warp),+ props.width,+ props.height+ );+ }++ static override drawWith(ctx: UniverRenderingContext, props: ITextProps, _skeleton?: DocSimpleSkeleton) {+ const { text, fontStyle, warp, hAlign, vAlign, width, height, left = 0, top = 0 } = props;+ const skeleton = _skeleton ?? new DocSimpleSkeleton(text, fontStyle, Boolean(warp), width, vAlign === VerticalAlign.TOP ? height : Infinity);+ const lines = skeleton.calculate();+ const totalHeight = skeleton.getTotalHeight();+ const offsetY = vAlign === VerticalAlign.TOP ? 0 : vAlign === VerticalAlign.MIDDLE ? (height - totalHeight) / 2 : height - totalHeight;+ let lineTop = top + offsetY;++ // Set font once outside the loop for better performance+ ctx.save();+ ctx.font = fontStyle;++ ctx.fillStyle = props.color ?? COLOR_BLACK_RGB;++ // Get font metrics using FontCache for consistency with height calculation+ for (const line of lines) {+ const lineHeight = line.height;+ const lineWidth = line.width;+ const lineX = (hAlign === HorizontalAlign.LEFT || hAlign === HorizontalAlign.UNSPECIFIED) ? 0 : (hAlign === HorizontalAlign.CENTER ? (width - lineWidth) / 2 : (width - lineWidth));+ const baselineY = lineTop + line.baseline;++ // Draw the text+ ctx.fillText(line.text, left + lineX, baselineY);++ // Draw underline if specified+ if (props.underline) {+ this._drawTextDecoration(ctx, {+ x: left + lineX,+ y: lineTop + lineHeight - 1, // Position underline near bottom of line+ width: lineWidth,+ color: props.color || '#000000',+ lineWidth: 1,+ });+ }++ // Draw strikethrough if specified+ if (props.strokeLine) {+ this._drawTextDecoration(ctx, {+ x: left + lineX,+ y: lineTop + line.baseline - lineHeight * 0.3, // Position strikethrough roughly in middle+ width: lineWidth,+ color: props.color || '#000000',+ lineWidth: 1,+ });+ }++ lineTop = lineTop + lineHeight;+ }++ ctx.restore();++ return totalHeight;+ }++ /**+ * Draw text decoration lines (underline, strikethrough, etc.)+ */+ private static _drawTextDecoration(ctx: UniverRenderingContext, options: {+ x: number;+ y: number;+ width: number;+ color: string;+ lineWidth: number;+ }) {+ const { x, y, width, color, lineWidth } = options;++ ctx.save();+ ctx.strokeStyle = color;+ ctx.lineWidth = lineWidth;+ ctx.beginPath();+ ctx.moveTo(x, y);+ ctx.lineTo(x + width, y);+ ctx.stroke();++ ctx.restore();+ }++ protected override _draw(ctx: UniverRenderingContext) {+ this.skeleton.calculate();+ Text.drawWith(ctx, this, this.skeleton);+ }++ override makeDirty(state?: boolean): this | undefined {+ super.makeDirty(state);+ if (state) {+ this.skeleton.makeDirty();+ }+ return this;+ }++ override toJson() {+ const props: IKeyValue = {};+ TEXT_OBJECT_ARRAY.forEach((key) => {+ if (this[key as keyof Text]) {+ props[key] = this[key as keyof Text];+ }+ });++ return {+ ...super.toJson(),+ ...props,+ };+ }+}diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.tsindex be34df7713..57a4b5efb7 100644--- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts+++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts@@ -73,10 +73,9 @@ export class SheetsCfRenderController extends Disposable {}const styleMap = context.workbook.getStyles();const defaultStyle = (typeof cell?.s === 'string' ? styleMap.get(cell?.s) : cell?.s) || {};- const s = { ...defaultStyle };- const cloneCell = { ...cell, s } as IConditionalFormattingCellData & ICellDataForSheetInterceptor;+ const cloneCell = cell as IConditionalFormattingCellData & ICellDataForSheetInterceptor;if (result.style) {- Object.assign(s, result.style);+ Object.assign(cloneCell, defaultStyle);}if (!cloneCell.fontRenderExtension) {cloneCell.fontRenderExtension = {};diff --git a/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts b/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.tsindex b788588707..97ab5c3efc 100644--- a/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts+++ b/packages/sheets-data-validation-ui/src/controllers/dv-render.controller.ts@@ -287,6 +287,7 @@ export class SheetsDataValidationMobileRenderController extends RxDisposable {this._initAutoHeight();}+ // eslint-disable-next-line max-lines-per-functionprivate _initViewModelIntercept() {this.disposeWithMe(this._sheetInterceptorService.intercept(@@ -295,7 +296,7 @@ export class SheetsDataValidationMobileRenderController extends RxDisposable {effect: InterceptorEffectEnum.Style,// must be after numfmtpriority: InterceptCellContentPriority.DATA_VALIDATION,- // eslint-disable-next-line complexity+ // eslint-disable-next-line complexity, max-lines-per-functionhandler: (cell, pos, next) => {const { row, col, unitId, subUnitId, workbook, worksheet } = pos;@@ -313,54 +314,78 @@ export class SheetsDataValidationMobileRenderController extends RxDisposable {const cellValue = getCellValueOrigin(cellOrigin);const valueStr = `${cellValue ?? ''}`;- return next({- ...cell,- markers: {- ...cell?.markers,- ...validStatus === DataValidationStatus.INVALID ? INVALID_MARK : null,- },- customRender: [- ...(cell?.customRender ?? []),- ...(validator?.canvasRender ? [validator.canvasRender] : []),- ],- fontRenderExtension: {- ...cell?.fontRenderExtension,- isSkip: cell?.fontRenderExtension?.isSkip || validator?.skipDefaultFontRender?.(rule, cellValue, pos),- },- interceptorStyle: {- ...cell?.interceptorStyle,- ...validator?.getExtraStyle(rule, valueStr, {- get style() {- const styleMap = workbook.getStyles();- return (typeof cell?.s === 'string' ? styleMap.get(cell?.s) : cell?.s) || {};- },- }, row, col),- },- interceptorAutoHeight: () => {- const skeleton = this._renderManagerService.getRenderById(unitId)- ?.with(SheetSkeletonManagerService)- .getSkeletonParam(subUnitId)- ?.skeleton;- if (!skeleton) {- return undefined;- }- const mergeCell = skeleton.worksheet.getMergedCell(row, col);+ cell = {};- const info: ICellRenderContext = {- data: cell,- style: skeleton.getStyles().getStyleByCell(cell),- primaryWithCoord: skeleton.getCellWithCoordByIndex(mergeCell?.startRow ?? row, mergeCell?.startColumn ?? col),- unitId,- subUnitId,- row,- col,- workbook,- worksheet,- };- return validator?.canvasRender?.calcCellAutoHeight?.(info);- },- coverable: (cell?.coverable ?? true) && !(rule.type === DataValidationType.LIST || rule.type === DataValidationType.LIST_MULTIPLE),- });+ cell.markers = {+ ...cell?.markers,+ ...validStatus === DataValidationStatus.INVALID ? INVALID_MARK : null,+ };+ cell.customRender = [+ ...(cell?.customRender ?? []),+ ...(validator?.canvasRender ? [validator.canvasRender] : []),+ ];+ cell.fontRenderExtension = {+ ...cell?.fontRenderExtension,+ isSkip: cell?.fontRenderExtension?.isSkip || validator?.skipDefaultFontRender?.(rule, cellValue, pos),+ };+ cell.interceptorStyle = {+ ...cell?.interceptorStyle,+ ...validator?.getExtraStyle(rule, valueStr, {+ get style() {+ const styleMap = workbook.getStyles();+ return (typeof cell?.s === 'string' ? styleMap.get(cell?.s) : cell?.s) || {};+ },+ }, row, col),+ };+ cell.interceptorAutoHeight = () => {+ const skeleton = this._renderManagerService.getRenderById(unitId)+ ?.with(SheetSkeletonManagerService)+ .getSkeletonParam(subUnitId)+ ?.skeleton;+ if (!skeleton) {+ return undefined;+ }+ const mergeCell = skeleton.worksheet.getMergedCell(row, col);++ const info: ICellRenderContext = {+ data: cell,+ style: skeleton.getStyles().getStyleByCell(cell),+ primaryWithCoord: skeleton.getCellWithCoordByIndex(mergeCell?.startRow ?? row, mergeCell?.startColumn ?? col),+ unitId,+ subUnitId,+ row,+ col,+ workbook,+ worksheet,+ };+ return validator?.canvasRender?.calcCellAutoHeight?.(info);+ };+ cell.interceptorAutoWidth = () => {+ const skeleton = this._renderManagerService.getRenderById(unitId)+ ?.with(SheetSkeletonManagerService)+ .getSkeletonParam(subUnitId)+ ?.skeleton;+ if (!skeleton) {+ return undefined;+ }+ const mergeCell = skeleton.worksheet.getMergedCell(row, col);++ const info: ICellRenderContext = {+ data: cell,+ style: skeleton.getStyles().getStyleByCell(cell),+ primaryWithCoord: skeleton.getCellWithCoordByIndex(mergeCell?.startRow ?? row, mergeCell?.startColumn ?? col),+ unitId,+ subUnitId,+ row,+ col,+ workbook,+ worksheet,+ };+ return validator?.canvasRender?.calcCellAutoWidth?.(info);+ };+ cell.coverable = (cell?.coverable ?? true) && !(rule.type === DataValidationType.LIST || rule.type === DataValidationType.LIST_MULTIPLE);++ return next(cell);},})@@ -376,8 +401,10 @@ export class SheetsDataValidationMobileRenderController extends RxDisposable {.subscribe((infos) => {const ranges: IRange[] = [];infos.forEach((info) => {- if (info.rule?.ranges) {- ranges.push(...info.rule.ranges);+ if (info.rule.type === DataValidationType.LIST_MULTIPLE || info.rule.type === DataValidationType.LIST) {+ if (info.rule?.ranges) {+ ranges.push(...info.rule.ranges);+ }}});diff --git a/packages/sheets-data-validation-ui/src/views/widgets/dropdown-widget.ts b/packages/sheets-data-validation-ui/src/views/widgets/dropdown-widget.tsindex 673d8bb550..d4a5817bc6 100644--- a/packages/sheets-data-validation-ui/src/views/widgets/dropdown-widget.ts+++ b/packages/sheets-data-validation-ui/src/views/widgets/dropdown-widget.ts@@ -14,13 +14,13 @@* limitations under the License.*/-import type { ICellRenderContext, IDocumentData, IPaddingData, IStyleData, Nullable } from '@univerjs/core';+import type { ICellRenderContext, IPaddingData } from '@univerjs/core';import type { IBaseDataValidationWidget } from '@univerjs/data-validation';import type { IMouseEvent, IPointerEvent, SpreadsheetSkeleton, UniverRenderingContext, UniverRenderingContext2D } from '@univerjs/engine-render';import type { ListValidator } from '@univerjs/sheets-data-validation';import type { IShowDataValidationDropdownParams } from '../../commands/operations/data-validation.operation';-import { BooleanNumber, DataValidationRenderMode, DataValidationType, DEFAULT_EMPTY_DOCUMENT_VALUE, DEFAULT_STYLES, DocumentDataModel, HorizontalAlign, ICommandService, Inject, IUniverInstanceService, LocaleService, Tools, UniverInstanceType, VerticalAlign, WrapStrategy } from '@univerjs/core';-import { CURSOR_TYPE, Documents, DocumentSkeleton, DocumentViewModel, getCurrentTypeOfRenderer, getDocsSkeletonPageSize, IRenderManagerService, Rect } from '@univerjs/engine-render';+import { DataValidationRenderMode, DataValidationType, DEFAULT_STYLES, HorizontalAlign, ICommandService, Inject, IUniverInstanceService, LocaleService, UniverInstanceType, VerticalAlign, WrapStrategy } from '@univerjs/core';+import { CURSOR_TYPE, DocSimpleSkeleton, getCurrentTypeOfRenderer, getFontStyleString, IRenderManagerService, Rect, Text } from '@univerjs/engine-render';import { getCellValueOrigin, SheetDataValidationModel } from '@univerjs/sheets-data-validation';import { ShowDataValidationDropdown } from '../../commands/operations/data-validation.operation';import { DROP_DOWN_DEFAULT_COLOR } from '../../const';@@ -31,94 +31,18 @@ import { DROP_DOWN_DEFAULT_COLOR } from '../../const';const PADDING_H = 4;const ICON_SIZE = 4;const ICON_PLACE = 14;+const PADDING_V = 1;/*** margin for Capsule, that means distance between capsule and cell border*/const MARGIN_H = 6;-const MARGIN_V = 4;+const MARGIN_V = 3;const RADIUS_BG = 8;const DROP_DOWN_ICON_COLOR = '#565656';const downPath = new Path2D('M3.32201 4.84556C3.14417 5.05148 2.85583 5.05148 2.67799 4.84556L0.134292 1.90016C-0.152586 1.56798 0.0505937 1 0.456301 1L5.5437 1C5.94941 1 6.15259 1.56798 5.86571 1.90016L3.32201 4.84556Z');-function convertToDocumentData(text: string, style?: Nullable<IStyleData>) {- const contentLength = text.length;- const documentData: IDocumentData = {- id: 'd',- body: {- dataStream: `${text}${DEFAULT_EMPTY_DOCUMENT_VALUE}`,- textRuns: [- {- ts: {- fs: 11,- ff: undefined,- it: BooleanNumber.FALSE,- bl: BooleanNumber.FALSE,- ul: {- s: BooleanNumber.FALSE,- },- st: {- s: BooleanNumber.FALSE,- },- ol: {- s: BooleanNumber.FALSE,- },- cl: undefined,- ...style,- bg: undefined,- bd: undefined,- },- st: 0,- ed: contentLength,- },- ],- },- documentStyle: {- pageSize: {- width: Number.POSITIVE_INFINITY,- height: Number.POSITIVE_INFINITY,- },- },- };-- return documentData;-}--function createDocSkeleton(text: string, localeService: LocaleService, style?: Nullable<IStyleData>) {- const documentData = convertToDocumentData(text, style);-- const docModel = new DocumentDataModel(documentData);- const docViewModel = new DocumentViewModel(docModel);-- const documentSkeleton = DocumentSkeleton.create(docViewModel, localeService);-- return {- documentSkeleton,- docModel,- docViewModel,- };-}--function createDocuments(text: string, localeService: LocaleService, style?: Nullable<IStyleData>) {- const {- documentSkeleton,- docModel,- docViewModel,- } = createDocSkeleton(text, localeService, style);-- const documents = new Documents(`DOCUMENTS_${Tools.generateRandomId()}`, documentSkeleton, {- pageMarginLeft: 0,- pageMarginTop: 0,- });- return {- documents,- documentSkeleton,- docModel,- docViewModel,- };-}-function calcPadding(cellWidth: number, cellHeight: number, fontWidth: number, fontHeight: number, vt: VerticalAlign, ht: HorizontalAlign, margin = true) {let paddingTop = 0;const realMargin = margin ? MARGIN_V : 0;@@ -265,22 +189,21 @@ export class DropdownWidget implements IBaseDataValidationWidget {vt = vt ?? VerticalAlign.BOTTOM;ht = ht ?? DEFAULT_STYLES.ht;pd = pd ?? DEFAULT_STYLES.pd;+ const fontStyle = getFontStyleString(style).fontCache;if (rule.renderMode === DataValidationRenderMode.ARROW) {const { l = DEFAULT_STYLES.pd.l, t = DEFAULT_STYLES.pd.t, r = DEFAULT_STYLES.pd.r, b = DEFAULT_STYLES.pd.b } = pd;const realWidth = cellWidth - l - r - ICON_PLACE - 4;- const { documentSkeleton, documents, docModel } = createDocuments(valueStr, this._localeService, style);-- if (- tb === WrapStrategy.WRAP- ) {- docModel.updateDocumentDataPageSize(Math.max(realWidth, 1));- }-- documentSkeleton.calculate();- documentSkeleton.getActualSize();- const textLayout = getDocsSkeletonPageSize(documentSkeleton)!;- const { height: fontHeight, width: fontWidth } = textLayout;+ const textSkeleton = new DocSimpleSkeleton(+ valueStr,+ fontStyle,+ Boolean(tb === WrapStrategy.WRAP),+ realWidth,+ Infinity+ );+ textSkeleton.calculate();+ const fontWidth = textSkeleton.getTotalWidth();+ const fontHeight = textSkeleton.getTotalHeight();const { paddingTop, paddingLeft } = calcPadding(realWidth, cellHeight - t - b, fontWidth, fontHeight, vt, ht, true);this._drawDownIcon(ctx, cellBounding, cellWidth, cellHeight, fontHeight, vt, pd);@@ -296,7 +219,17 @@ export class DropdownWidget implements IBaseDataValidationWidget {ctx.beginPath();ctx.rect(0, 0, realWidth, fontHeight);ctx.clip();- documents.render(ctx as UniverRenderingContext);+ Text.drawWith(ctx, {+ text: valueStr,+ fontStyle,+ width: realWidth,+ height: fontHeight,+ color: style?.cl?.rgb,+ strokeLine: Boolean(style?.st?.s),+ underline: Boolean(style?.ul?.s),+ warp: tb === WrapStrategy.WRAP,+ hAlign: HorizontalAlign.LEFT,+ }, textSkeleton);ctx.translateWithPrecision(paddingLeft, 0);ctx.restore();@@ -309,6 +242,7 @@ export class DropdownWidget implements IBaseDataValidationWidget {height: cellHeight - t - b,});} else {+ // Capsulectx.save();ctx.translateWithPrecision(cellBounding.startX, cellBounding.startY);ctx.beginPath();@@ -316,20 +250,22 @@ export class DropdownWidget implements IBaseDataValidationWidget {ctx.clip();const realWidth = cellWidth - (MARGIN_H * 2) - PADDING_H - ICON_PLACE - 4;- const { documentSkeleton, documents, docModel } = createDocuments(valueStr, this._localeService, style);- if (- tb === WrapStrategy.WRAP- ) {- docModel.updateDocumentDataPageSize(Math.max(realWidth, 1));- }- documentSkeleton.calculate();- const textLayout = getDocsSkeletonPageSize(documentSkeleton)!;- const { height: fontHeight, width: fontWidth } = textLayout;- const { paddingTop, paddingLeft } = calcPadding(realWidth, cellHeight, fontWidth, fontHeight, vt, ht);+ const textSkeleton = new DocSimpleSkeleton(+ valueStr,+ fontStyle,+ Boolean(tb === WrapStrategy.WRAP),+ realWidth,+ Infinity+ );+ textSkeleton.calculate();+ const fontWidth = textSkeleton.getTotalWidth();+ const fontHeight = textSkeleton.getTotalHeight();+ const rectHeight = fontHeight + (PADDING_V * 2);+ const rectWidth = Math.max(cellWidth - MARGIN_H * 2, 1);+ const { paddingTop, paddingLeft } = calcPadding(rectWidth, cellHeight, fontWidth, rectHeight, vt, ht);ctx.translateWithPrecision(MARGIN_H, paddingTop);- const rectWidth = Math.max(cellWidth - MARGIN_H * 2, 1);- const rectHeight = fontHeight;+Rect.drawWith(ctx as UniverRenderingContext, {width: rectWidth,height: rectHeight,@@ -337,14 +273,26 @@ export class DropdownWidget implements IBaseDataValidationWidget {radius: RADIUS_BG,});ctx.save();- ctx.translateWithPrecision(PADDING_H, 0);+ ctx.translateWithPrecision(PADDING_H, PADDING_V);ctx.beginPath();ctx.rect(0, 0, realWidth, fontHeight);ctx.clip();ctx.translateWithPrecision(paddingLeft, 0);- documents.render(ctx as UniverRenderingContext);++ Text.drawWith(ctx, {+ text: valueStr,+ fontStyle,+ width: realWidth,+ height: fontHeight,+ color: style?.cl?.rgb,+ strokeLine: Boolean(style?.st?.s),+ underline: Boolean(style?.ul?.s),+ warp: tb === WrapStrategy.WRAP,+ hAlign: HorizontalAlign.LEFT,+ }, textSkeleton);+ctx.restore();- ctx.translateWithPrecision(realWidth + PADDING_H + 4, (fontHeight - ICON_SIZE) / 2);+ ctx.translateWithPrecision(realWidth + PADDING_H + 4, ((fontHeight) - ICON_SIZE) / 2);ctx.fillStyle = DROP_DOWN_ICON_COLOR;ctx.fill(downPath);ctx.restore();@@ -379,7 +327,6 @@ export class DropdownWidget implements IBaseDataValidationWidget {endX: _cellBounding.endX - rightOffset,startY: _cellBounding.startY + topOffset,endY: _cellBounding.endY - downOffset,-};const cellWidth = cellBounding.endX - cellBounding.startX;const value = getCellValueOrigin(data);@@ -391,36 +338,26 @@ export class DropdownWidget implements IBaseDataValidationWidget {if (rule.renderMode === DataValidationRenderMode.ARROW) {const realWidth = cellWidth - ICON_PLACE;- const { documentSkeleton, docModel } = createDocuments(valueStr, this._localeService, style);- if (- tb === WrapStrategy.WRAP- ) {- docModel.updateDocumentDataPageSize(Math.max(realWidth, 1));- }-- documentSkeleton.calculate();- documentSkeleton.getActualSize();- const textLayout = getDocsSkeletonPageSize(documentSkeleton)!;- const { height: fontHeight } = textLayout;-- return fontHeight + t + b + MARGIN_V * 2;+ const skeleton = new DocSimpleSkeleton(+ valueStr,+ getFontStyleString(style).fontCache,+ Boolean(tb === WrapStrategy.WRAP),+ realWidth,+ Infinity+ );+ skeleton.calculate();+ return skeleton.getTotalHeight() + t + b + (MARGIN_V * 2);} else {- const realWidth = cellWidth - (MARGIN_H * 2) - PADDING_H - ICON_PLACE;- const { documentSkeleton, docModel } = createDocSkeleton(valueStr, this._localeService, style);- if (- tb === WrapStrategy.WRAP- ) {- docModel.updateDocumentDataPageSize(Math.max(realWidth, 1));- }-- documentSkeleton.calculate();- const textLayout = getDocsSkeletonPageSize(documentSkeleton)!;-- const {- height: fontHeight,- } = textLayout;-- return fontHeight + (MARGIN_V * 2);+ const realWidth = Math.max(cellWidth - (MARGIN_H * 2) - PADDING_H - ICON_PLACE, 10);+ const skeleton = new DocSimpleSkeleton(+ valueStr,+ getFontStyleString(style).fontCache,+ Boolean(tb === WrapStrategy.WRAP),+ realWidth,+ Infinity+ );+ skeleton.calculate();+ return skeleton.getTotalHeight() + (MARGIN_V * 2) + +(PADDING_V * 2);}}@@ -463,20 +400,21 @@ export class DropdownWidget implements IBaseDataValidationWidget {// + 1 is must, or last character will be cutpaddingAll = ICON_PLACE + MARGIN_H * 2 + PADDING_H * 2 + r + l + RADIUS_BG / 2 + 1;break;- // default is CUSTOM+ // default is CUSTOMdefault:paddingAll = ICON_PLACE + MARGIN_H * 2 + PADDING_H * 2 + r + l + RADIUS_BG / 2 + 1;}const widthForTextLayout = cellWidth - paddingAll;- const { documentSkeleton, docModel } = createDocuments(valueStr, this._localeService, style);- if (tb === WrapStrategy.WRAP) {- docModel.updateDocumentDataPageSize(Math.max(widthForTextLayout, 1));- }- documentSkeleton.calculate();- documentSkeleton.getActualSize();- const textLayout = getDocsSkeletonPageSize(documentSkeleton)!;- return textLayout.width + paddingAll;+ const skeleton = new DocSimpleSkeleton(+ valueStr,+ getFontStyleString(style).fontCache,+ Boolean(tb === WrapStrategy.WRAP),+ widthForTextLayout,+ Infinity+ );+ skeleton.calculate();+ return skeleton.getTotalWidth() + paddingAll;}isHit(position: { x: number; y: number }, info: ICellRenderContext) {diff --git a/packages/sheets-data-validation/src/services/dv-cache.service.ts b/packages/sheets-data-validation/src/services/dv-cache.service.tsindex 93b1f699ee..81040a43d7 100644--- a/packages/sheets-data-validation/src/services/dv-cache.service.ts+++ b/packages/sheets-data-validation/src/services/dv-cache.service.ts@@ -97,7 +97,9 @@ export class DataValidationCacheService extends Disposable {const cache = this._ensureCache(unitId, subUnitId);ranges.forEach((range) => {Range.foreach(range, (row, col) => {- cache.setValue(row, col, undefined);+ if (cache.getValue(row, col) !== undefined) {+ cache.setValue(row, col, undefined);+ }});});diff --git a/packages/sheets-filter-ui/src/views/render-modules/sheets-filter.render-controller.ts b/packages/sheets-filter-ui/src/views/render-modules/sheets-filter.render-controller.tsindex bad954a418..9dd39bb044 100644--- a/packages/sheets-filter-ui/src/views/render-modules/sheets-filter.render-controller.ts+++ b/packages/sheets-filter-ui/src/views/render-modules/sheets-filter.render-controller.ts@@ -188,18 +188,18 @@ export class SheetsFilterRenderController extends RxDisposable implements IRendesubUnitId !== worksheetId ||row !== startRow ||col < startColumn ||- col > endColumn+ col > endColumn ||+ !cell) {return next(cell);}- return next({- ...cell,- fontRenderExtension: {- ...cell?.fontRenderExtension,- rightOffset: FILTER_ICON_SIZE,- },- });+ cell.fontRenderExtension = {+ ...cell?.fontRenderExtension,+ rightOffset: FILTER_ICON_SIZE,+ };++ return next(cell);},priority: 10,});diff --git a/packages/sheets-formula-ui/src/controllers/formula-render.controller.ts b/packages/sheets-formula-ui/src/controllers/formula-render.controller.tsindex a31dda3455..6618a37773 100644--- a/packages/sheets-formula-ui/src/controllers/formula-render.controller.ts+++ b/packages/sheets-formula-ui/src/controllers/formula-render.controller.ts@@ -49,13 +49,16 @@ export class FormulaRenderManagerController extends RxDisposable {return next(cell);}- return next({- ...cell,- markers: {- ...cell?.markers,- ...FORMULA_ERROR_MARK,- },- });+ if (!cell) {+ return next(cell);+ }++ cell.markers = {+ ...cell?.markers,+ ...FORMULA_ERROR_MARK,+ };++ return next(cell);},priority: 10,}diff --git a/packages/sheets-formula/src/controllers/array-formula-cell-interceptor.controller.ts b/packages/sheets-formula/src/controllers/array-formula-cell-interceptor.controller.tsindex a903be14bc..a10e339547 100644--- a/packages/sheets-formula/src/controllers/array-formula-cell-interceptor.controller.ts+++ b/packages/sheets-formula/src/controllers/array-formula-cell-interceptor.controller.ts@@ -73,11 +73,13 @@ export class ArrayFormulaCellInterceptorController extends Disposable {// The cell in the upper left corner of the array formula also triggers the default value determinationif (cellData.v == null && cellData.t == null) {- return next({- ...cell,- v: 0, // Default value for empty cell- t: CellValueType.NUMBER,- });+ if (!cell) {+ return next(cell);+ }++ cell.v = 0; // Default value for empty cell+ cell.t = CellValueType.NUMBER;+ return next(cell);}// Dealing with precision issues@@ -86,17 +88,18 @@ export class ArrayFormulaCellInterceptorController extends Disposable {// "v": "123413.23000000001",// "t": 2,if (cell?.t === CellValueType.NUMBER && cell.v !== undefined && cell.v !== null && isRealNum(cell.v)) {- return next({- ...cell,- v: stripErrorMargin(Number(cell.v)),- });+ cell.v = stripErrorMargin(Number(cell.v));+ return next(cell);}- return next({- ...cell,- v: cellData.v,- t: cellData.t,- });+ if (!cell) {+ return next(cell);+ }++ cell.v = cellData.v;+ cell.t = cellData.t;++ return next(cell);},}));diff --git a/packages/sheets-formula/src/controllers/update-formula.controller.ts b/packages/sheets-formula/src/controllers/update-formula.controller.tsindex ca0660ae62..9983c4216d 100644--- a/packages/sheets-formula/src/controllers/update-formula.controller.ts+++ b/packages/sheets-formula/src/controllers/update-formula.controller.ts@@ -15,6 +15,7 @@*/import type {+ ICellData,ICommandInfo,IExecutionOptions,IUnitRange,@@ -229,7 +230,7 @@ export class UpdateFormulaController extends Disposable {const formulaData = this._formulaDataModel.getFormulaData();const { id: sheetId, cellData } = sheet;- const cellMatrix = new ObjectMatrix(cellData);+ const cellMatrix = new ObjectMatrix<Nullable<ICellData>>(cellData);const newFormulaData = initSheetFormulaData(formulaData, unitId, sheetId, cellMatrix);this._commandService.executeCommand(diff --git a/packages/sheets-hyper-link-ui/src/controllers/render-controllers/render.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/render-controllers/render.controller.tsindex 931eba90f9..f056adc875 100644--- a/packages/sheets-hyper-link-ui/src/controllers/render-controllers/render.controller.ts+++ b/packages/sheets-hyper-link-ui/src/controllers/render-controllers/render.controller.ts@@ -62,12 +62,10 @@ export class SheetsHyperLinkRenderManagerController extends Disposable {const { row, col, unitId, subUnitId } = pos;const link = this._hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, row, col);- if (link) {- return next({- ...cell,- linkUrl: link.payload,- linkId: link.id,- });+ if (link && cell) {+ cell.linkUrl = link.payload;+ cell.linkId = link.id;+ return next(cell);}return next(cell);diff --git a/packages/sheets-note-ui/src/controllers/sheets-cell-content.controller.ts b/packages/sheets-note-ui/src/controllers/sheets-cell-content.controller.tsindex 6852a750d0..b1ba25943a 100644--- a/packages/sheets-note-ui/src/controllers/sheets-cell-content.controller.ts+++ b/packages/sheets-note-ui/src/controllers/sheets-cell-content.controller.ts@@ -43,16 +43,19 @@ export class SheetsCellContentController extends Disposable {const { row, col, unitId, subUnitId } = pos;const note = this._sheetsNoteModel.getNote(unitId, subUnitId, row, col);if (note) {- return next({- ...cell,- markers: {- ...cell?.markers,- tr: {- color: '#FFBD37',- size: 6,- },+ if (!cell) {+ cell = {};+ }++ cell.markers = {+ ...cell?.markers,+ tr: {+ color: '#FFBD37',+ size: 6,},- });+ };++ return next(cell);}return next(cell);diff --git a/packages/sheets-note-ui/src/views/note.tsx b/packages/sheets-note-ui/src/views/note.tsxindex e97dbd0ee4..38bc908e1a 100644--- a/packages/sheets-note-ui/src/views/note.tsx+++ b/packages/sheets-note-ui/src/views/note.tsx@@ -20,6 +20,7 @@ import type { IPopup } from '@univerjs/ui';import type { IUniverSheetsNoteUIPluginConfig } from '../controllers/config.schema';import { ICommandService, LocaleService } from '@univerjs/core';import { borderClassName, clsx, scrollbarClassName } from '@univerjs/design';+import { IRenderManagerService } from '@univerjs/engine-render';import { SheetDeleteNoteCommand, SheetsNoteModel, SheetUpdateNoteCommand } from '@univerjs/sheets-note';import { useConfigValue, useDebounceFn, useDependency } from '@univerjs/ui';import { useEffect, useMemo, useRef, useState } from 'react';@@ -29,12 +30,14 @@ import { SHEETS_NOTE_UI_PLUGIN_CONFIG_KEY } from '../controllers/config.schema';export const SheetsNote = (props: { popup: IPopup<{ location: ISheetLocationBase }> }) => {const noteModel = useDependency(SheetsNoteModel);const localeService = useDependency(LocaleService);+ const renderManagerService = useDependency(IRenderManagerService);const config = useConfigValue<IUniverSheetsNoteUIPluginConfig>(SHEETS_NOTE_UI_PLUGIN_CONFIG_KEY);const activePopup = props.popup.extraProps?.location;if (!activePopup) {console.error('Popup extraProps or location is undefined.');return null; // Or handle this case appropriately}+ const currentRender = renderManagerService.getRenderById(activePopup.unitId)!;const [note, setNote] = useState<ISheetNote>(() => {const defaultNote = { width: config?.defaultNoteSize?.width || 216, height: config?.defaultNoteSize?.height || 92, note: '' };const existingNote = noteModel.getNote(activePopup.unitId, activePopup.subUnitId!, activePopup.row, activePopup.col);@@ -118,6 +121,11 @@ export const SheetsNote = (props: { popup: IPopup<{ location: ISheetLocationBasereturn (<textarea+ onWheel={(e) => {+ if (document.activeElement !== textareaRef.current) {+ currentRender.engine.getCanvasElement().dispatchEvent(new WheelEvent(e.type, e.nativeEvent));+ }+ }}ref={textareaRef}data-u-comp="note-textarea"className={clsx(`diff --git a/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.tsindex 09d2034ed1..a3ecb4c0af 100644--- a/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.ts+++ b/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.ts@@ -142,20 +142,17 @@ export class SheetsNumfmtCellContentController extends Disposable {if (isTextFormat(numfmtValue.pattern)) {// If the user has disabled the text format mark, do not show itif (this._configService.getConfig<IUniverSheetsNumfmtConfig>(SHEETS_NUMFMT_PLUGIN_CONFIG_KEY)?.disableTextFormatMark) {- return next({- ...cell,- t: CellValueType.STRING,- });+ if (!cell) {+ return next(cell);+ }++ cell.t = CellValueType.STRING;+ return next(cell);}- return next({- ...cell,- t: CellValueType.STRING,- markers: {- ...cell?.markers,- ...TEXT_FORMAT_MARK,- },- });+ cell.t = CellValueType.STRING;+ cell.markers = { ...cell?.markers, ...TEXT_FORMAT_MARK };+ return next(cell);}let numfmtRes: string = '';diff --git a/packages/sheets-sort/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/sheets-sort/src/commands/commands/__tests__/create-command-test-bed.tsindex 0afebc14f6..f382edb193 100644--- a/packages/sheets-sort/src/commands/commands/__tests__/create-command-test-bed.ts+++ b/packages/sheets-sort/src/commands/commands/__tests__/create-command-test-bed.ts@@ -17,7 +17,7 @@import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';import { BooleanNumber, ILogService, Inject, Injector, IUniverInstanceService, LocaleService, LocaleType, LogLevel, Plugin, Tools, Univer, UniverInstanceType } from '@univerjs/core';import { FormulaDataModel } from '@univerjs/engine-formula';-import { SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';+import { SheetInterceptorService, SheetSkeletonService, SheetsSelectionsService } from '@univerjs/sheets';import { SheetsSortController } from '../../../controllers/sheets-sort.controller';import enUS from '../../../locale/en-US';import { SheetsSortService } from '../../../services/sheets-sort.service';@@ -143,6 +143,7 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?injector.add([SheetsSortController]);injector.add([SheetsSelectionsService, { useClass: mockSelectionManagerService as any }]);injector.add([SheetInterceptorService]);+ injector.add([SheetSkeletonService]);injector.add([FormulaDataModel, { useClass: mockFormulaDataModel }]);dependencies?.forEach((d) => injector.add(d));diff --git a/packages/sheets-table-ui/src/controllers/sheet-table-filter-button-render.controller.ts b/packages/sheets-table-ui/src/controllers/sheet-table-filter-button-render.controller.tsindex 9ef86c3dc0..499f4285f0 100644--- a/packages/sheets-table-ui/src/controllers/sheet-table-filter-button-render.controller.ts+++ b/packages/sheets-table-ui/src/controllers/sheet-table-filter-button-render.controller.ts@@ -145,18 +145,18 @@ export class SheetsTableFilterButtonRenderController extends RxDisposable implemsubUnitId !== worksheetId ||row !== startRow ||col < startColumn ||- col > endColumn+ col > endColumn ||+ !cell) {return next(cell);}- return next({- ...cell,- fontRenderExtension: {- ...cell?.fontRenderExtension,- rightOffset: FILTER_ICON_SIZE,- },- });+ cell.fontRenderExtension = {+ ...cell?.fontRenderExtension,+ rightOffset: FILTER_ICON_SIZE,+ };++ return next(cell);},priority: 10,});diff --git a/packages/sheets-table/src/controllers/sheets-table.controller.ts b/packages/sheets-table/src/controllers/sheets-table.controller.tsindex 86d5733974..01ddaf7d27 100644--- a/packages/sheets-table/src/controllers/sheets-table.controller.ts+++ b/packages/sheets-table/src/controllers/sheets-table.controller.ts@@ -123,8 +123,12 @@ export class SheetsTableController extends Disposable {const tableStartRow = tableRange.startRow;if (tableStartRow === row) {const columnName = table.getColumnNameByIndex(index);- const newCell = { ...cell, v: columnName };- return next(newCell);+ if (!cell) {+ cell = {};+ }++ cell.v = columnName;+ return next(cell);}}}diff --git a/packages/sheets-thread-comment-ui/src/controllers/render-controllers/render.controller.ts b/packages/sheets-thread-comment-ui/src/controllers/render-controllers/render.controller.tsindex 0d0ea82407..a234d5fe53 100644--- a/packages/sheets-thread-comment-ui/src/controllers/render-controllers/render.controller.ts+++ b/packages/sheets-thread-comment-ui/src/controllers/render-controllers/render.controller.ts@@ -42,16 +42,19 @@ export class SheetsThreadCommentRenderController extends Disposable {handler: (cell, pos, next) => {const { row, col, unitId, subUnitId } = pos;if (this._sheetsThreadCommentModel.showCommentMarker(unitId, subUnitId, row, col)) {- return next({- ...cell,- markers: {- ...cell?.markers,- tr: {- color: '#FFBD37',- size: 6,- },+ if (!cell) {+ cell = {};+ }++ cell.markers = {+ ...cell?.markers,+ tr: {+ color: '#FFBD37',+ size: 6,},- });+ };++ return next(cell);}return next(cell);diff --git a/packages/sheets-ui/src/controllers/auto-height.controller.ts b/packages/sheets-ui/src/controllers/auto-height.controller.tsindex df1331a476..917e5acc9d 100644--- a/packages/sheets-ui/src/controllers/auto-height.controller.ts+++ b/packages/sheets-ui/src/controllers/auto-height.controller.ts@@ -14,36 +14,31 @@* limitations under the License.*/-import type { IRange, Workbook } from '@univerjs/core';+import type { IRange, ObjectMatrix, Workbook } from '@univerjs/core';import type { RenderManagerService } from '@univerjs/engine-render';-import type {- IMoveRangeCommandParams,- IReorderRangeMutationParams,- ISetRangeValuesRangeMutationParams,- ISetStyleCommandParams,- ISetWorksheetRowAutoHeightMutationParams,- ISetWorksheetRowIsAutoHeightMutationParams,-} from '@univerjs/sheets';-import type { IUniverSheetsUIConfig } from './config.schema';-import { Disposable, IConfigService, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';+import type { ISetWorksheetRowAutoHeightMutationParams } from '@univerjs/sheets';+import { Disposable, generateRandomId, IConfigService, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';import {+ CancelMarkDirtyRowAutoHeightMutation,getSheetCommandTarget,- MoveRangeCommand,- ReorderRangeCommand,- SetRangeValuesCommand,- SetStyleCommand,+ MarkDirtyRowAutoHeightMutation,SetWorksheetRowAutoHeightMutation,SetWorksheetRowAutoHeightMutationFactory,- SetWorksheetRowIsAutoHeightCommand,SheetInterceptorService,SheetsSelectionsService,} from '@univerjs/sheets';import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';-import { SHEETS_UI_PLUGIN_CONFIG_KEY } from './config.schema';export const AFFECT_LAYOUT_STYLES = ['ff', 'fs', 'tr', 'tb'];+interface IAutoHeightParams {+ cellHeights?: ObjectMatrix<number>;+ autoHeightRanges?: IRange[];+ lazyAutoHeightRanges?: IRange[];+ ranges: IRange[];+}+export class AutoHeightController extends Disposable {constructor(@IRenderManagerService private readonly _renderManagerService: RenderManagerService,@@ -56,18 +51,43 @@ export class AutoHeightController extends Disposable {this._initialize();}- private _getRangesScope(ranges: IRange[]): number {- let start: number | undefined;- let end: number | undefined;- for (const { startRow, endRow } of ranges) {- start = start === undefined ? startRow : Math.min(start, startRow);- end = end === undefined ? endRow : Math.max(end, endRow);+ private _processLazyAutoHeight(redoUndoItem: { redos: any[]; undos: any[] }, unitId: string, subUnitId: string, lazyAutoHeightRanges?: IRange[]) {+ if (lazyAutoHeightRanges?.length) {+ const redo = {+ id: MarkDirtyRowAutoHeightMutation.id,+ params: {+ unitId,+ subUnitId,+ ranges: lazyAutoHeightRanges,+ id: generateRandomId(),+ },+ options: {+ onlyLocal: true,+ },+ };+ const undo = {+ id: CancelMarkDirtyRowAutoHeightMutation.id,+ params: {+ unitId,+ subUnitId,+ id: redo.params.id,+ },+ options: {+ onlyLocal: true,+ },+ };++ return {+ redos: [...redoUndoItem.redos, redo],+ undos: [...redoUndoItem.undos, undo],+ };}- return (end as number) - (start as number) + 1;++ return redoUndoItem;}- getUndoRedoParamsOfAutoHeight(ranges: IRange[], subUnitIdParam?: string): { redos: any[]; undos: any[] } {- const { _univerInstanceService: univerInstanceService, _configService: configService } = this;+ getUndoRedoParamsOfAutoHeight(ranges: IRange[], subUnitIdParam?: string, currentCellHeights?: ObjectMatrix<number>): { redos: any[]; undos: any[] } {+ const { _univerInstanceService: univerInstanceService } = this;const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;// Better NOT use `getActiveWorksheet` method, because users may manipulate another worksheet in active sheet.@@ -92,33 +112,31 @@ export class AutoHeightController extends Disposable {undos: [],};};+ const rowsAutoHeightInfo = skeleton.calculateAutoHeightInRange(ranges, currentCellHeights);- const config = configService.getConfig<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);- let rangeList = ranges;- if (!Array.isArray(ranges)) {- // TODO: @weird94 after we resolve the performance issue of auto hight, we can remove this code.- // The code "const params = command.params as ISetRangeValuesRangeMutationParams;" of _initialize() method may make IRange as IRange[]. so need adjust here.- if (ranges && (ranges as IRange).startRow !== undefined && (ranges as IRange).startRow !== undefined) {- rangeList = [ranges];- } else {- rangeList = [];+ const updatedRowsAutoHeightInfo = rowsAutoHeightInfo.filter((info) => {+ const { row, autoHeight } = info;+ if (!autoHeight) {+ return false;}- }- const count = this._getRangesScope(rangeList);- const maxLimit = config?.maxAutoHeightCount ?? 1000;- if (maxLimit < count) {+ const currentRowHeight = worksheet.getRowHeight(row);+ if (currentRowHeight === autoHeight) {+ return false;+ }+ return true;+ });++ if (updatedRowsAutoHeightInfo.length === 0) {return {redos: [],undos: [],};}- const rowsAutoHeightInfo = skeleton.calculateAutoHeightInRange(ranges);-const redoParams: ISetWorksheetRowAutoHeightMutationParams = {subUnitId,unitId,- rowsAutoHeightInfo,+ rowsAutoHeightInfo: updatedRowsAutoHeightInfo,};const undoParams: ISetWorksheetRowAutoHeightMutationParams = SetWorksheetRowAutoHeightMutationFactory(redoParams, worksheet);return {@@ -137,88 +155,13 @@ export class AutoHeightController extends Disposable {};}- // eslint-disable-next-line max-lines-per-functionprivate _initialize() {- const { _sheetInterceptorService: sheetInterceptorService, _selectionManagerService: selectionManagerService } =- this;- // for intercept'SetRangeValuesCommand' command.- this.disposeWithMe(sheetInterceptorService.interceptCommand({- getMutations: (command) => {- if (command.id === SetRangeValuesCommand.id) {- const params = command.params as ISetRangeValuesRangeMutationParams;- return this.getUndoRedoParamsOfAutoHeight(params.range, params.subUnitId);- }-- return {- redos: [],- undos: [],- };- },- }));-- // for intercept 'sheet.command.set-row-is-auto-height' command.- this.disposeWithMe(sheetInterceptorService.interceptCommand({- getMutations: (command: { id: string; params: ISetWorksheetRowIsAutoHeightMutationParams }) => {- if (command.id !== SetWorksheetRowIsAutoHeightCommand.id) {- return {- redos: [],- undos: [],- };- }-- return this.getUndoRedoParamsOfAutoHeight(command.params.ranges, command.params.subUnitId);- },- }));-- // for intercept set style command.- this.disposeWithMe(sheetInterceptorService.interceptCommand({- getMutations: (command: { id: string; params: ISetStyleCommandParams<number> }) => {- if (command.id !== SetStyleCommand.id) {- return {- redos: [],- undos: [],- };- }-- // TODO: @jocs, All styles that affect the size of the cell,- // I don't know if the enumeration is complete, to be added in the future.-- if (!AFFECT_LAYOUT_STYLES.includes(command.params?.style.type)) {- return {- redos: [],- undos: [],- };- }-- const selections = selectionManagerService.getCurrentSelections()?.map((s) => s.range);-- if (!selections?.length) {- return {- redos: [],- undos: [],- };- }-- return this.getUndoRedoParamsOfAutoHeight(selections, command.params.subUnitId);- },- }));-- this.disposeWithMe(sheetInterceptorService.interceptAfterCommand({- getMutations: (command) => {- if (command.id === MoveRangeCommand.id) {- const params = command.params as IMoveRangeCommandParams;- return this.getUndoRedoParamsOfAutoHeight([params.fromRange, params.toRange]);- }-- if (command.id === ReorderRangeCommand.id) {- const params = command.params as IReorderRangeMutationParams;- return this.getUndoRedoParamsOfAutoHeight([params.range]);- }+ this.disposeWithMe(this._sheetInterceptorService.interceptAutoHeight({+ getMutations: (info) => {+ const { unitId, subUnitId, ranges, autoHeightRanges, lazyAutoHeightRanges, cellHeights } = info;- return {- redos: [],- undos: [],- };+ const undoRedoItem = this.getUndoRedoParamsOfAutoHeight(autoHeightRanges ?? ranges, subUnitId, cellHeights);+ return this._processLazyAutoHeight(undoRedoItem, unitId, subUnitId, lazyAutoHeightRanges);},}));}diff --git a/packages/sheets-ui/src/controllers/force-string-render.controller.ts b/packages/sheets-ui/src/controllers/force-string-render.controller.tsindex ce08e577aa..3ecead53db 100644--- a/packages/sheets-ui/src/controllers/force-string-render.controller.ts+++ b/packages/sheets-ui/src/controllers/force-string-render.controller.ts@@ -73,13 +73,9 @@ export class ForceStringRenderController extends RxDisposable implements IRenderreturn next(cell);}- return next({- ...cell,- markers: {- ...cell?.markers,- ...FORCE_STRING_MARK,- },- });+ cell.markers = { ...cell?.markers, ...FORCE_STRING_MARK };++ return next(cell);}return next(cell);diff --git a/packages/sheets-ui/src/controllers/menu/__tests__/create-menu-test-bed.ts b/packages/sheets-ui/src/controllers/menu/__tests__/create-menu-test-bed.tsindex 859cb2623e..9ecdef09bb 100644--- a/packages/sheets-ui/src/controllers/menu/__tests__/create-menu-test-bed.ts+++ b/packages/sheets-ui/src/controllers/menu/__tests__/create-menu-test-bed.ts@@ -17,7 +17,7 @@import type { IWorkbookData } from '@univerjs/core';import { Inject, Injector, LocaleType, Plugin, Univer, UniverInstanceType } from '@univerjs/core';import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';-import { RangeProtectionCache, RangeProtectionRefRangeService, RangeProtectionRenderModel, RangeProtectionRuleModel, RangeProtectionService, RefRangeService, SheetInterceptorService, SheetsSelectionsService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';+import { RangeProtectionCache, RangeProtectionRefRangeService, RangeProtectionRenderModel, RangeProtectionRuleModel, RangeProtectionService, RefRangeService, SheetInterceptorService, SheetSkeletonService, SheetsSelectionsService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';import { IMenuManagerService, IPlatformService, IShortcutService, MenuManagerService, PlatformService, ShortcutService } from '@univerjs/ui';const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {@@ -74,6 +74,7 @@ export function createMenuTestBed() {injector.add([RangeProtectionCache]);injector.add([RangeProtectionRuleModel]);injector.add([RangeProtectionService]);+ injector.add([SheetSkeletonService]);this._injector.get(SheetInterceptorService);this._injector.get(WorkbookPermissionService);diff --git a/packages/sheets-ui/src/facade/f-sheet-hooks.ts b/packages/sheets-ui/src/facade/f-sheet-hooks.tsindex 3e5299003e..e9e025df77 100644--- a/packages/sheets-ui/src/facade/f-sheet-hooks.ts+++ b/packages/sheets-ui/src/facade/f-sheet-hooks.ts@@ -142,13 +142,12 @@ export class FSheetHooksUIMixin extends FSheetHooks implements IFSheetHooksUIMixreturn this._injector.get(SheetInterceptorService).intercept(INTERCEPTOR_POINT.CELL_CONTENT, {effect,handler: (cell, pos, next) => {- return next({- ...cell,- customRender: [- ...(cell?.customRender || []),- ...(customRender || []),- ],- });+ if (!cell) {+ return next(cell);+ }++ cell.customRender = [...(cell.customRender || []), ...(customRender || [])];+ return next(cell);},priority,});diff --git a/packages/sheets-ui/src/mobile-plugin.ts b/packages/sheets-ui/src/mobile-plugin.tsindex c87ba1b9bd..070ca83a03 100644--- a/packages/sheets-ui/src/mobile-plugin.ts+++ b/packages/sheets-ui/src/mobile-plugin.ts@@ -50,6 +50,7 @@ import { SheetRenderController } from './controllers/render-controllers/sheet.reimport { SheetsZoomRenderController } from './controllers/render-controllers/zoom.render-controller';import { StatusBarController } from './controllers/status-bar.controller';import { AutoFillService, IAutoFillService } from './services/auto-fill/auto-fill.service';+import { AutoHeightService } from './services/auto-height.service';import { SheetCanvasPopManagerService } from './services/canvas-pop-manager.service';import { CellAlertManagerService } from './services/cell-alert-manager.service';import { ISheetCellDropdownManagerService, SheetCellDropdownManagerService } from './services/cell-dropdown-manager.service';@@ -147,6 +148,7 @@ export class UniverSheetsMobileUIPlugin extends Plugin {[SheetRenderController],[ISheetSelectionRenderService, { useClass: MobileSheetsSelectionRenderService }],[SheetScrollManagerService],+ [AutoHeightService],] as Dependency[]).forEach((renderDep) => {this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, renderDep));});diff --git a/packages/sheets-ui/src/plugin.ts b/packages/sheets-ui/src/plugin.tsindex 2fe0883816..d00d12e1bf 100644--- a/packages/sheets-ui/src/plugin.ts+++ b/packages/sheets-ui/src/plugin.ts@@ -65,6 +65,7 @@ import { SheetsZoomRenderController } from './controllers/render-controllers/zooimport { SheetUIController } from './controllers/sheet-ui.controller';import { StatusBarController } from './controllers/status-bar.controller';import { AutoFillService, IAutoFillService } from './services/auto-fill/auto-fill.service';+import { AutoHeightService } from './services/auto-height.service';import { SheetCanvasPopManagerService } from './services/canvas-pop-manager.service';import { CellAlertManagerService } from './services/cell-alert-manager.service';import { ISheetCellDropdownManagerService, SheetCellDropdownManagerService } from './services/cell-dropdown-manager.service';@@ -243,6 +244,7 @@ export class UniverSheetsUIPlugin extends Plugin {[SheetSkeletonRenderController],[SheetRenderController],[ISheetSelectionRenderService, { useClass: SheetSelectionRenderService }],+ [AutoHeightService],] as Dependency[]).forEach((m) => {this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, m));});diff --git a/packages/sheets-ui/src/services/auto-height.service.ts b/packages/sheets-ui/src/services/auto-height.service.tsnew file mode 100644index 0000000000..7f5b82532c--- /dev/null+++ b/packages/sheets-ui/src/services/auto-height.service.ts@@ -0,0 +1,223 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IRange, Workbook } from '@univerjs/core';+import type { IRenderContext, IRenderModule, SpreadsheetSkeleton } from '@univerjs/engine-render';+import type { ICancelMarkDirtyRowAutoHeightMutationParams, IMarkDirtyRowAutoHeightMutationParams } from '@univerjs/sheets';+import { createIdentifier, Disposable, ICommandService, Inject, Rectangle } from '@univerjs/core';+import { CancelMarkDirtyRowAutoHeightMutation, MarkDirtyRowAutoHeightMutation, SetWorksheetRowAutoHeightMutation } from '@univerjs/sheets';+import { SheetSkeletonManagerService } from './sheet-skeleton-manager.service';++export interface IAutoHeightTask {+ ranges: IRange[];+ maxTime?: number;+ sheetId: string;+ id: string;+}++export interface IAutoHeightTaskInfo extends IAutoHeightTask {+ startTime: number;+ skeleton: SpreadsheetSkeleton;+}++export const IAutoHeightService = createIdentifier('sheets-ui.services.auto-height');++export function taskRowsFromRanges(ranges: IRange[], rows: number) {+ const result: IRange[] = [];+ const lasts: IRange[] = [...ranges];+ let needRows = rows;++ while (lasts.length > 0) {+ const range = lasts.shift();+ if (!range) {+ break;+ }++ const count = range.endRow - range.startRow + 1;+ if (count > needRows) {+ result.push({+ ...range,+ startRow: range.startRow,+ endRow: range.startRow + needRows - 1,+ });+ lasts.unshift({+ ...range,+ startRow: range.startRow + needRows,+ });+ break;+ } else {+ result.push(range);+ needRows -= count;+ }+ }++ return { result, lasts };+}++const CALCULATE_ROWS = 500;++export class AutoHeightService extends Disposable implements IRenderModule {+ private _autoHeightTasks: IAutoHeightTaskInfo[] = [];+ private _calculateLoopId: number | null = null;++ constructor(+ private _context: IRenderContext<Workbook>,+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService,+ @ICommandService private readonly _commandService: ICommandService+ ) {+ super();++ this._initMarkDirty();+ }++ private _initMarkDirty() {+ this.disposeWithMe(+ this._commandService.onCommandExecuted((info) => {+ if (info.id === MarkDirtyRowAutoHeightMutation.id) {+ const params = info.params as IMarkDirtyRowAutoHeightMutationParams;+ const { unitId, subUnitId, ranges, id } = params;+ if (unitId !== this._context.unitId) {+ return;+ }++ this.startAutoHeightTask({+ ranges,+ sheetId: subUnitId,+ id,+ // 10s timeout+ maxTime: 10_000,+ });+ }++ if (info.id === CancelMarkDirtyRowAutoHeightMutation.id) {+ const params = info.params as ICancelMarkDirtyRowAutoHeightMutationParams;+ const { unitId, id } = params;+ if (unitId !== this._context.unitId) {+ return;+ }+ this.cancelTask(id);+ }+ })+ );+ }++ private _loopTask(task: IAutoHeightTaskInfo) {+ const skeleton = task.skeleton;+ let result: IRange[] = [];+ let lasts: IRange[] = [];+ if (task.maxTime && task.maxTime + task.startTime <= Date.now()) {+ result = task.ranges;+ } else {+ const info = taskRowsFromRanges(task.ranges, CALCULATE_ROWS);+ result = info.result;+ lasts = info.lasts;+ }++ const autoHeightInfos = skeleton.calculateAutoHeightInRange(result);+ const updatedRowsAutoHeightInfo = autoHeightInfos.filter((info) => {+ const { row, autoHeight } = info;+ if (!autoHeight) {+ return false;+ }+ const currentRowHeight = skeleton.getRowHeight(row);+ if (currentRowHeight === autoHeight) {+ return false;+ }+ return true;+ });++ if (lasts.length) {+ task.ranges = lasts;+ this._autoHeightTasks.unshift(task);+ }++ if (updatedRowsAutoHeightInfo.length) {+ const redoParams = {+ unitId: this._context.unitId,+ subUnitId: task.sheetId,+ rowsAutoHeightInfo: updatedRowsAutoHeightInfo,+ };+ this._commandService.syncExecuteCommand(SetWorksheetRowAutoHeightMutation.id, redoParams);+ }+ }++ private _calculateLoop(options: IdleDeadline) {+ while (this._autoHeightTasks.length) {+ if (options.timeRemaining() <= 0) {+ break;+ }+ const task = this._autoHeightTasks.shift();+ if (!task) {+ this._calculateLoopId = null;+ return;+ }+ this._loopTask(task);+ }++ this._calculateLoopId = requestIdleCallback((options) => {+ this._calculateLoop(options);+ });+ }++ private _initialCalculateLoop() {+ if (this._calculateLoopId === null) {+ this._calculateLoopId = requestIdleCallback((options) => {+ this._calculateLoop(options);+ });+ }+ }++ startAutoHeightTask(task: IAutoHeightTask): void {+ const skeleton = this._sheetSkeletonManagerService.getSkeleton(task.sheetId);+ if (!skeleton) {+ return;+ }++ task.ranges = Rectangle.mergeRanges(task.ranges.map((range) => {+ return {+ ...range,+ startColumn: 0,+ endColumn: 0,+ };+ }));++ const remainRanges = Rectangle.subtractMulti(+ task.ranges,+ this._autoHeightTasks+ .filter((newTask) => newTask.sheetId === task.sheetId)+ .map((task) => task.ranges)+ .flat()+ );++ if (remainRanges.length) {+ this._autoHeightTasks.push({+ ...task,+ startTime: Date.now(),+ skeleton,+ ranges: remainRanges,+ });++ this._initialCalculateLoop();+ }+ }++ cancelTask(taskId: string): void {+ const index = this._autoHeightTasks.findIndex((task) => task.id === taskId);+ if (index !== -1) {+ this._autoHeightTasks.splice(index, 1);+ }+ }+}diff --git a/packages/sheets-ui/src/services/cell-popup-manager.service.ts b/packages/sheets-ui/src/services/cell-popup-manager.service.tsindex 0eafae3069..87fdf9d6c8 100644--- a/packages/sheets-ui/src/services/cell-popup-manager.service.ts+++ b/packages/sheets-ui/src/services/cell-popup-manager.service.ts@@ -113,6 +113,7 @@ export class CellPopupManagerService extends Disposable {},noPushMinimumGap: true,autoRelayout: false,+ zIndex: 90,},unitId,subUnitIddiff --git a/packages/sheets/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/sheets/src/commands/commands/__tests__/create-command-test-bed.tsindex eaadd995c3..235867723c 100644--- a/packages/sheets/src/commands/commands/__tests__/create-command-test-bed.ts+++ b/packages/sheets/src/commands/commands/__tests__/create-command-test-bed.ts@@ -37,6 +37,7 @@ import { WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '../import { WorksheetPermissionService } from '../../../services/permission/worksheet-permission/worksheet-permission.service';import { SheetsSelectionsService } from '../../../services/selections/selection.service';import { SheetInterceptorService } from '../../../services/sheet-interceptor/sheet-interceptor.service';+import { SheetSkeletonService } from '../../../skeleton/skeleton.service';const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {id: 'test',@@ -104,6 +105,7 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?injector.add([SheetsSelectionsService]);injector.add([BorderStyleManagerService]);injector.add([SheetInterceptorService]);+ injector.add([SheetSkeletonService]);dependencies?.forEach((d) => injector.add(d));diff --git a/packages/sheets/src/commands/commands/move-range.command.ts b/packages/sheets/src/commands/commands/move-range.command.tsindex 77066da42e..cc247a5ebc 100644--- a/packages/sheets/src/commands/commands/move-range.command.ts+++ b/packages/sheets/src/commands/commands/move-range.command.ts@@ -49,6 +49,7 @@ export const MoveRangeCommand: ICommand = {type: CommandType.COMMAND,id: MoveRangeCommandId,+ // eslint-disable-next-line max-lines-per-functionhandler: async (accessor: IAccessor, params: IMoveRangeCommandParams) => {const commandService = accessor.get(ICommandService);const undoRedoService = accessor.get(IUndoRedoService);@@ -79,7 +80,7 @@ export const MoveRangeCommand: ICommand = {const interceptorCommands = sheetInterceptorService.onCommandExecute({id: MoveRangeCommand.id,- params: { ...params },+ params,});const redos = [@@ -113,17 +114,23 @@ export const MoveRangeCommand: ICommand = {const result = sequenceExecute(redos, commandService).result;+ const { undos: autoHeightUndos, redos: autoHeightRedos } = sheetInterceptorService.generateMutationsOfAutoHeight({+ unitId,+ subUnitId,+ ranges: [params.fromRange, params.toRange],+ });+const afterInterceptors = sheetInterceptorService.afterCommandExecute({id: MoveRangeCommand.id,- params: { ...params },+ params,});if (result) {- sequenceExecute(afterInterceptors.redos, commandService);+ sequenceExecute([...afterInterceptors.redos, ...autoHeightRedos], commandService);undoRedoService.pushUndoRedo({unitID: unitId,- undoMutations: [...undos, ...afterInterceptors.undos],- redoMutations: [...redos, ...afterInterceptors.redos],+ undoMutations: [...undos, ...afterInterceptors.undos, ...autoHeightUndos],+ redoMutations: [...redos, ...afterInterceptors.redos, ...autoHeightRedos],});return true;}diff --git a/packages/sheets/src/commands/commands/reorder-range.command.ts b/packages/sheets/src/commands/commands/reorder-range.command.tsindex 6cc640209c..7b7d61b03d 100644--- a/packages/sheets/src/commands/commands/reorder-range.command.ts+++ b/packages/sheets/src/commands/commands/reorder-range.command.ts@@ -19,7 +19,9 @@ import type { IReorderRangeMutationParams } from '../mutations/reorder-range.mutimport type { ISheetCommandSharedParams } from '../utils/interface';import { CommandType, ICommandService, IUndoRedoService, sequenceExecute } from '@univerjs/core';import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';+import { SheetSkeletonService } from '../../skeleton/skeleton.service';import { ReorderRangeMutation, ReorderRangeUndoMutationFactory } from '../mutations/reorder-range.mutation';+import { getSuitableRangesInView } from './util';export interface IReorderRangeCommandParams extends ISheetCommandSharedParams {range: IRange;@@ -63,18 +65,26 @@ export const ReorderRangeCommand: ICommand<IReorderRangeCommandParams> = {undoReorderMutation,...interceptorCommands.undos,];- const result = sequenceExecute(redos, commandService);+ const result = sequenceExecute(redos, commandService);+ const { suitableRanges, remainingRanges } = getSuitableRangesInView([range], accessor.get(SheetSkeletonService).getSkeleton(unitId, subUnitId));+ const { undos: autoHeightUndos, redos: autoHeightRedos } = sheetInterceptorService.generateMutationsOfAutoHeight({+ unitId,+ subUnitId,+ ranges: [range],+ autoHeightRanges: suitableRanges,+ lazyAutoHeightRanges: remainingRanges,+ });const reorderAfterIntercepted = sheetInterceptorService.afterCommandExecute({ id: ReorderRangeCommand.id, params });if (result.result) {- sequenceExecute(reorderAfterIntercepted.redos, commandService);+ sequenceExecute([...reorderAfterIntercepted.redos, ...autoHeightRedos], commandService);const undoRedoService = accessor.get(IUndoRedoService);undoRedoService.pushUndoRedo({unitID: unitId,- undoMutations: [...undos, ...reorderAfterIntercepted.undos],- redoMutations: [...redos, ...reorderAfterIntercepted.redos],+ undoMutations: [...undos, ...reorderAfterIntercepted.undos, ...autoHeightUndos],+ redoMutations: [...redos, ...reorderAfterIntercepted.redos, ...autoHeightRedos],});return true;}diff --git a/packages/sheets/src/commands/commands/set-range-values.command.ts b/packages/sheets/src/commands/commands/set-range-values.command.tsindex bdbb0a4f17..aee36e7872 100644--- a/packages/sheets/src/commands/commands/set-range-values.command.ts+++ b/packages/sheets/src/commands/commands/set-range-values.command.ts@@ -24,6 +24,7 @@ import {isICellData,IUndoRedoService,IUniverInstanceService,+ mapObjectMatrix,ObjectMatrix,sequenceExecute,Tools,@@ -101,16 +102,24 @@ export const SetRangeValuesCommand: ICommand = {const setRangeValuesMutationParams = { subUnitId, unitId, cellValue: realCellValue ?? cellValue.getMatrix() };const redoParams = SetRangeValuesUndoMutationFactory(accessor, setRangeValuesMutationParams);+ const cellHeights = mapObjectMatrix(setRangeValuesMutationParams.cellValue, (row, col) => worksheet.getCellHeight(row, col) || undefined);const setValueMutationResult = commandService.syncExecuteCommand(SetRangeValuesMutation.id, setRangeValuesMutationParams);if (!setValueMutationResult) return false;const { undos, redos } = sheetInterceptorService.onCommandExecute({id: SetRangeValuesCommand.id,- params: { ...setRangeValuesMutationParams, range: currentSelections },+ params: setRangeValuesMutationParams,});- const result = sequenceExecute([...redos], commandService);+ const { undos: autoHeightUndos, redos: autoHeightRedos } = sheetInterceptorService.generateMutationsOfAutoHeight({+ unitId,+ subUnitId,+ ranges: currentSelections,+ cellHeights: new ObjectMatrix<number>(cellHeights as IObjectMatrixPrimitiveType<number>),+ });++ const result = sequenceExecute([...redos, ...autoHeightRedos], commandService);if (result.result) {const selectionOperation = followSelectionOperation(range ?? cellValue.getRange(), workbook, worksheet);undoRedoService.pushUndoRedo({@@ -118,11 +127,13 @@ export const SetRangeValuesCommand: ICommand = {undoMutations: [{ id: SetRangeValuesMutation.id, params: redoParams },...undos,+ ...autoHeightUndos,selectionOperation,],redoMutations: [{ id: SetRangeValuesMutation.id, params: setRangeValuesMutationParams },...redos,+ ...autoHeightRedos,Tools.deepClone(selectionOperation),],id: redoUndoId,diff --git a/packages/sheets/src/commands/commands/set-style.command.ts b/packages/sheets/src/commands/commands/set-style.command.tsindex d450e01a10..a7ffea1048 100644--- a/packages/sheets/src/commands/commands/set-style.command.ts+++ b/packages/sheets/src/commands/commands/set-style.command.ts@@ -20,6 +20,7 @@ import type {ICellData,IColorStyle,ICommand,+ IMutationInfo,IRange,IStyleData,ITextRotation,@@ -43,7 +44,9 @@ import {} from '@univerjs/core';import { SheetsSelectionsService } from '../../services/selections/selection.service';import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';+import { SheetSkeletonService } from '../../skeleton/skeleton.service';import { SetRangeValuesMutation, SetRangeValuesUndoMutationFactory } from '../mutations/set-range-values.mutation';+import { getRangesHeight, getSuitableRangesInView } from './util';import { createRangeIteratorWithSkipFilteredRows } from './utils/selection-utils';import { getSheetCommandTarget } from './utils/target-util';@@ -60,6 +63,8 @@ export interface ISetStyleCommandParams<T> extends ISetStyleCommonParams {style: IStyleTypeValue<T>;}+export const AFFECT_LAYOUT_STYLES = ['ff', 'fs', 'tr', 'tb'];+/*** The command to set cell style.* Set style to a bunch of ranges.@@ -68,6 +73,7 @@ export const SetStyleCommand: ICommand<ISetStyleCommandParams<unknown>> = {type: CommandType.COMMAND,id: 'sheet.command.set-style',+ // eslint-disable-next-line max-lines-per-functionhandler: <T> (accessor: IAccessor, params: ISetStyleCommandParams<T>) => {const univerInstanceService = accessor.get(IUniverInstanceService);@@ -116,6 +122,8 @@ export const SetStyleCommand: ICommand<ISetStyleCommandParams<unknown>> = {cellValue: cellValue.getMatrix(),};+ const skeleton = accessor.get(SheetSkeletonService).getSkeleton(unitId, subUnitId);+const undoSetRangeValuesMutationParams: ISetRangeValuesMutationParams = SetRangeValuesUndoMutationFactory(accessor,setRangeValuesMutationParams@@ -126,18 +134,36 @@ export const SetStyleCommand: ICommand<ISetStyleCommandParams<unknown>> = {setRangeValuesMutationParams);- const { undos, redos } = accessor.get(SheetInterceptorService).onCommandExecute({+ const interceptor = accessor.get(SheetInterceptorService);+ let autoHeightUndos: IMutationInfo<object>[] = [];+ let autoHeightRedos: IMutationInfo<object>[] = [];+ if (AFFECT_LAYOUT_STYLES.includes(params?.style.type)) {+ const { suitableRanges, remainingRanges } = getSuitableRangesInView(ranges, skeleton);+ const cellHeights = getRangesHeight(suitableRanges, worksheet);+ const { undos, redos } = interceptor.generateMutationsOfAutoHeight({+ unitId,+ subUnitId,+ ranges: suitableRanges,+ autoHeightRanges: suitableRanges,+ lazyAutoHeightRanges: remainingRanges,+ cellHeights,+ });+ autoHeightUndos = undos;+ autoHeightRedos = redos;+ }++ const { undos, redos } = interceptor.onCommandExecute({id: SetStyleCommand.id,params,});- const result = sequenceExecute([...redos], commandService);+ const result = sequenceExecute([...redos, ...autoHeightRedos], commandService);if (setRangeValuesResult && result.result) {undoRedoService.pushUndoRedo({unitID: setRangeValuesMutationParams.unitId,- undoMutations: [{ id: SetRangeValuesMutation.id, params: undoSetRangeValuesMutationParams }, ...undos],- redoMutations: [{ id: SetRangeValuesMutation.id, params: setRangeValuesMutationParams }, ...redos],+ undoMutations: [{ id: SetRangeValuesMutation.id, params: undoSetRangeValuesMutationParams }, ...undos, ...autoHeightUndos],+ redoMutations: [{ id: SetRangeValuesMutation.id, params: setRangeValuesMutationParams }, ...redos, ...autoHeightRedos],});return true;diff --git a/packages/sheets/src/commands/commands/set-worksheet-col-width.command.ts b/packages/sheets/src/commands/commands/set-worksheet-col-width.command.tsindex 6482d51557..5e90ee0cb8 100644--- a/packages/sheets/src/commands/commands/set-worksheet-col-width.command.ts+++ b/packages/sheets/src/commands/commands/set-worksheet-col-width.command.ts@@ -28,10 +28,12 @@ import {} from '@univerjs/core';import { SheetsSelectionsService } from '../../services/selections/selection.service';import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';+import { SheetSkeletonService } from '../../skeleton/skeleton.service';import {SetWorksheetColWidthMutation,SetWorksheetColWidthMutationFactory,} from '../mutations/set-worksheet-col-width.mutation';+import { getRangesHeight, getSuitableRangesInView } from './util';import { getSheetCommandTarget } from './utils/target-util';export interface IDeltaColumnWidthCommandParams {@@ -113,7 +115,12 @@ export const DeltaColumnWidthCommand: ICommand<IDeltaColumnWidthCommandParams> =};}- const { undos, redos } = accessor.get(SheetInterceptorService).onCommandExecute({+ const skeleton = accessor.get(SheetSkeletonService).getSkeleton(unitId, subUnitId);+ const { suitableRanges, remainingRanges } = getSuitableRangesInView(redoMutationParams.ranges, skeleton);+ const cellHeights = getRangesHeight(suitableRanges, worksheet);++ const interceptor = accessor.get(SheetInterceptorService);+ const { undos, redos } = interceptor.onCommandExecute({id: DeltaColumnWidthCommand.id,params: redoMutationParams,});@@ -128,13 +135,26 @@ export const DeltaColumnWidthCommand: ICommand<IDeltaColumnWidthCommandParams> =redoMutationParams);- const result = sequenceExecute([...redos], commandService);+ const { undos: autoHeightUndos, redos: autoHeightRedos } = interceptor.generateMutationsOfAutoHeight({+ unitId,+ subUnitId,+ ranges: suitableRanges,+ autoHeightRanges: suitableRanges,+ lazyAutoHeightRanges: remainingRanges,+ });++ const { undos: afterUndos, redos: afterRedos } = accessor.get(SheetInterceptorService).afterCommandExecute({+ id: DeltaColumnWidthCommand.id,+ params: redoMutationParams,+ });++ const result = sequenceExecute([...redos, ...afterRedos, ...autoHeightRedos], commandService);if (setColWidthResult && result.result) {undoRedoService.pushUndoRedo({unitID: unitId,- undoMutations: [{ id: SetWorksheetColWidthMutation.id, params: undoMutationParams }, ...undos],- redoMutations: [{ id: SetWorksheetColWidthMutation.id, params: redoMutationParams }, ...redos],+ undoMutations: [{ id: SetWorksheetColWidthMutation.id, params: undoMutationParams }, ...undos, ...afterUndos, ...autoHeightUndos],+ redoMutations: [{ id: SetWorksheetColWidthMutation.id, params: redoMutationParams }, ...redos, ...afterRedos, ...autoHeightRedos],});return true;@@ -168,6 +188,7 @@ export const SetColWidthCommand: ICommand = {if (!target) return false;const { subUnitId, unitId, worksheet } = target;+ const skeleton = accessor.get(SheetSkeletonService).getSkeleton(unitId, subUnitId);const redoMutationParams: ISetWorksheetColWidthMutationParams = {subUnitId,unitId,@@ -175,12 +196,18 @@ export const SetColWidthCommand: ICommand = {colWidth: params.value,};+ const { suitableRanges, remainingRanges } = getSuitableRangesInView(redoMutationParams.ranges, skeleton);+ const cellHeights = getRangesHeight(suitableRanges, worksheet);+const undoMutationParams = SetWorksheetColWidthMutationFactory(redoMutationParams, worksheet);const setColWidthResult = commandService.syncExecuteCommand(SetWorksheetColWidthMutation.id, redoMutationParams);- const { undos, redos } = accessor.get(SheetInterceptorService).onCommandExecute({- id: SetColWidthCommand.id,- params: redoMutationParams,+ const { undos: autoHeightUndos, redos: autoHeightRedos } = sheetInterceptorService.generateMutationsOfAutoHeight({+ unitId,+ subUnitId,+ ranges: suitableRanges,+ autoHeightRanges: suitableRanges,+ lazyAutoHeightRanges: remainingRanges,});const intercepted = sheetInterceptorService.onCommandExecute({@@ -188,13 +215,13 @@ export const SetColWidthCommand: ICommand = {params: redoMutationParams,});- const result = sequenceExecute([...redos, ...intercepted.redos], commandService);+ const result = sequenceExecute([...intercepted.redos, ...autoHeightRedos], commandService);if (setColWidthResult && result.result) {undoRedoService.pushUndoRedo({unitID: unitId,- undoMutations: [...(intercepted.preUndos ?? []), { id: SetWorksheetColWidthMutation.id, params: undoMutationParams }, ...undos],- redoMutations: [...(intercepted.preRedos ?? []), { id: SetWorksheetColWidthMutation.id, params: redoMutationParams }, ...redos],+ undoMutations: [...(intercepted.preUndos ?? []), { id: SetWorksheetColWidthMutation.id, params: undoMutationParams }, ...intercepted.undos, ...autoHeightUndos],+ redoMutations: [...(intercepted.preRedos ?? []), { id: SetWorksheetColWidthMutation.id, params: redoMutationParams }, ...intercepted.redos, ...autoHeightRedos],});return true;diff --git a/packages/sheets/src/commands/commands/set-worksheet-row-height.command.ts b/packages/sheets/src/commands/commands/set-worksheet-row-height.command.tsindex e72d9438b9..5086b38ad0 100644--- a/packages/sheets/src/commands/commands/set-worksheet-row-height.command.ts+++ b/packages/sheets/src/commands/commands/set-worksheet-row-height.command.ts@@ -32,12 +32,14 @@ import {} from '@univerjs/core';import { SheetsSelectionsService } from '../../services/selections/selection.service';import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';+import { SheetSkeletonService } from '../../skeleton/skeleton.service';import {SetWorksheetRowHeightMutation,SetWorksheetRowHeightMutationFactory,SetWorksheetRowIsAutoHeightMutation,SetWorksheetRowIsAutoHeightMutationFactory,} from '../mutations/set-worksheet-row-height.mutation';+import { getSuitableRangesInView } from './util';import { getSheetCommandTarget } from './utils/target-util';export interface IDeltaRowHeightCommand {@@ -326,17 +328,29 @@ export const SetWorksheetRowIsAutoHeightCommand: ICommand = {redoMutationParams);- const { undos, redos } = accessor.get(SheetInterceptorService).onCommandExecute({+ const skeleton = accessor.get(SheetSkeletonService).getSkeleton(unitId, subUnitId);+ const { suitableRanges, remainingRanges } = getSuitableRangesInView(redoMutationParams.ranges, skeleton);++ const sheetInterceptorService = accessor.get(SheetInterceptorService);+ const { undos: autoHeightUndos, redos: autoHeightRedos } = sheetInterceptorService.generateMutationsOfAutoHeight({+ unitId,+ subUnitId,+ ranges: suitableRanges,+ autoHeightRanges: suitableRanges,+ lazyAutoHeightRanges: remainingRanges,+ });++ const { undos, redos } = sheetInterceptorService.onCommandExecute({id: SetWorksheetRowIsAutoHeightCommand.id,params: redoMutationParams,});- const result = sequenceExecute([...redos], commandService);+ const result = sequenceExecute([...redos, ...autoHeightRedos], commandService);if (setIsAutoHeightResult && result.result) {undoRedoService.pushUndoRedo({unitID: unitId,- undoMutations: [{ id: SetWorksheetRowIsAutoHeightMutation.id, params: undoMutationParams }, ...undos],- redoMutations: [{ id: SetWorksheetRowIsAutoHeightMutation.id, params: redoMutationParams }, ...redos],+ undoMutations: [{ id: SetWorksheetRowIsAutoHeightMutation.id, params: undoMutationParams }, ...undos, ...autoHeightUndos],+ redoMutations: [{ id: SetWorksheetRowIsAutoHeightMutation.id, params: redoMutationParams }, ...redos, ...autoHeightRedos],});return true;diff --git a/packages/sheets/src/commands/commands/util.ts b/packages/sheets/src/commands/commands/util.tsnew file mode 100644index 0000000000..98dee6cd52--- /dev/null+++ b/packages/sheets/src/commands/commands/util.ts@@ -0,0 +1,108 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IRange, Nullable, SheetSkeleton, Worksheet } from '@univerjs/core';+import { ObjectMatrix, Range } from '@univerjs/core';++export function getRangesHeight(ranges: IRange[], worksheet: Worksheet) {+ const cellHeights = new ObjectMatrix<number>();+ ranges.map((range) => Range.transformRange(range, worksheet)).forEach((range) => {+ Range.foreach(range, (row, col) => {+ const cellHeight = worksheet.getCellHeight(row, col);+ if (cellHeight) {+ cellHeights.setValue(row, col, cellHeight);+ }+ });+ });++ return cellHeights;+}++const MAX_RANGE_CELL_COUNT = 10_000;++export function getSuitableRangesInView(ranges: IRange[], skeleton: Nullable<SheetSkeleton>): { suitableRanges: IRange[]; remainingRanges: IRange[] } {+ if (!skeleton) {+ return { suitableRanges: ranges, remainingRanges: [] };+ }++ const colCount = skeleton.worksheet.getColumnCount();+ const maxRowCount = Math.ceil(MAX_RANGE_CELL_COUNT / colCount);+ const suitableRanges: IRange[] = [];+ const remainingRanges: IRange[] = [];+ const row = skeleton.getOffsetRelativeToRowCol(0, skeleton.scrollY).row;+ // Calculate the distance between each range and current row, then sort by distance+ const rangesWithDistance = ranges.map((range) => {+ // Calculate the minimum distance between range and current row+ let distance: number;+ if (row >= range.startRow && row <= range.endRow) {+ // Current row is within the range, distance is 0+ distance = 0;+ } else if (row < range.startRow) {+ // Current row is above the range, distance is range.startRow - row+ distance = range.startRow - row;+ } else {+ // Current row is below the range, distance is row - range.endRow+ distance = row - range.endRow;+ }++ return {+ range,+ distance,+ rowCount: range.endRow - range.startRow + 1, // Number of rows in the range+ };+ });++ // Sort by distance, if distance is the same, sort by row count in ascending order+ rangesWithDistance.sort((a, b) => {+ if (a.distance !== b.distance) {+ return a.distance - b.distance;+ }+ return a.rowCount - b.rowCount;+ });++ // Add ranges one by one until total row count reaches MAX_RANGE_HEIGHT+ let totalRowCount = 0;+ for (const item of rangesWithDistance) {+ if (totalRowCount + item.rowCount <= maxRowCount) {+ suitableRanges.push(item.range);+ totalRowCount += item.rowCount;+ } else {+ // If adding current range would exceed the limit, check if there's remaining quota to split the range+ const remainingQuota = maxRowCount - totalRowCount;++ if (remainingQuota > 0) {+ // Split range: add the part that can fit to suitable, add the rest to remaining+ const suitablePart: IRange = {+ ...item.range,+ endRow: item.range.startRow + remainingQuota - 1,+ };+ const remainingPart: IRange = {+ ...item.range,+ startRow: item.range.startRow + remainingQuota,+ };++ suitableRanges.push(suitablePart);+ remainingRanges.push(remainingPart);+ totalRowCount = maxRowCount; // Reached maximum limit+ } else {+ // No remaining quota, add the entire range to remaining+ remainingRanges.push(item.range);+ }+ }+ }++ return { suitableRanges, remainingRanges };+}diff --git a/packages/sheets/src/commands/mutations/mark-dirty-auto-height.mutation.ts b/packages/sheets/src/commands/mutations/mark-dirty-auto-height.mutation.tsnew file mode 100644index 0000000000..dfb4c8b43e--- /dev/null+++ b/packages/sheets/src/commands/mutations/mark-dirty-auto-height.mutation.ts@@ -0,0 +1,47 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IOperation, IRange } from '@univerjs/core';+import { CommandType } from '@univerjs/core';++export interface IMarkDirtyRowAutoHeightMutationParams {+ unitId: string;+ subUnitId: string;+ ranges: IRange[];+ id: string;+}++export const MarkDirtyRowAutoHeightMutation: IOperation<IMarkDirtyRowAutoHeightMutationParams> = {+ id: 'sheet.operation.mark-dirty-row-auto-height',+ type: CommandType.OPERATION,+ handler: () => {+ return true;+ },+};++export interface ICancelMarkDirtyRowAutoHeightMutationParams {+ unitId: string;+ subUnitId: string;+ id: string;+}++export const CancelMarkDirtyRowAutoHeightMutation: IOperation<ICancelMarkDirtyRowAutoHeightMutationParams> = {+ id: 'sheet.operation.cancel-mark-dirty-row-auto-height',+ type: CommandType.OPERATION,+ handler: () => {+ return true;+ },+};diff --git a/packages/sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts b/packages/sheets/src/commands/mutations/set-worksheet-row-height.mutation.tsindex 34556ddf13..a48f70e577 100644--- a/packages/sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts+++ b/packages/sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts@@ -14,8 +14,8 @@* limitations under the License.*/-import { CommandType, IUniverInstanceService } from '@univerjs/core';import type { BooleanNumber, IMutation, IObjectArrayPrimitiveType, IRange, IRowAutoHeightInfo, Nullable, Worksheet } from '@univerjs/core';+import { CommandType, IUniverInstanceService } from '@univerjs/core';import { getSheetCommandTarget } from '../commands/utils/target-util';const MAXIMUM_ROW_HEIGHT = 2000;@@ -101,7 +101,7 @@ export const SetWorksheetRowAutoHeightMutationFactory = (const { row } = rowInfo;const { ah } = manager.getRowOrCreate(row);- results.push({ row, autoHeight: ah });+ results.push({ row, autoHeight: ah! });}return {diff --git a/packages/sheets/src/controllers/basic-worksheet.controller.ts b/packages/sheets/src/controllers/basic-worksheet.controller.tsindex a279543346..515d19e382 100644--- a/packages/sheets/src/controllers/basic-worksheet.controller.ts+++ b/packages/sheets/src/controllers/basic-worksheet.controller.ts@@ -114,6 +114,7 @@ import { ToggleCellCheckboxCommand } from '../commands/commands/toggle-checkbox.import { ToggleGridlinesCommand } from '../commands/commands/toggle-gridlines.command';import { UnregisterWorksheetRangeThemeStyleCommand } from '../commands/commands/unregister-range-theme.command';import { AddRangeProtectionMutation } from '../commands/mutations/add-range-protection.mutation';+import { AddRangeThemeMutation } from '../commands/mutations/add-range-theme.mutation';import { AddWorksheetMergeMutation } from '../commands/mutations/add-worksheet-merge.mutation';import { AddWorksheetProtectionMutation } from '../commands/mutations/add-worksheet-protection.mutation';import { SetWorksheetRangeThemeStyleMutation } from '../commands/mutations/add-worksheet-range-theme.mutation';@@ -123,10 +124,12 @@ import { DeleteWorksheetRangeThemeStyleMutation } from '../commands/mutations/deimport { EmptyMutation } from '../commands/mutations/empty.mutation';import { InsertColMutation, InsertRowMutation } from '../commands/mutations/insert-row-col.mutation';import { InsertSheetMutation } from '../commands/mutations/insert-sheet.mutation';+import { CancelMarkDirtyRowAutoHeightMutation, MarkDirtyRowAutoHeightMutation } from '../commands/mutations/mark-dirty-auto-height.mutation';import { MoveRangeMutation } from '../commands/mutations/move-range.mutation';import { MoveColsMutation, MoveRowsMutation } from '../commands/mutations/move-rows-cols.mutation';import { RemoveNumfmtMutation, SetNumfmtMutation } from '../commands/mutations/numfmt-mutation';import { RegisterWorksheetRangeThemeStyleMutation } from '../commands/mutations/register-range-theme.mutation';+import { RemoveRangeThemeMutation } from '../commands/mutations/remove-range-theme.mutation';import { RemoveColMutation, RemoveRowMutation } from '../commands/mutations/remove-row-col.mutation';import { RemoveSheetMutation } from '../commands/mutations/remove-sheet.mutation';import { RemoveWorksheetMergeMutation } from '../commands/mutations/remove-worksheet-merge.mutation';@@ -136,6 +139,7 @@ import { SetColHiddenMutation, SetColVisibleMutation } from '../commands/mutatioimport { SetFrozenMutation } from '../commands/mutations/set-frozen.mutation';import { SetGridlinesColorMutation } from '../commands/mutations/set-gridlines-color.mutation';import { SetRangeProtectionMutation } from '../commands/mutations/set-range-protection.mutation';+import { SetRangeThemeMutation } from '../commands/mutations/set-range-theme.mutation';import { SetRangeValuesMutation } from '../commands/mutations/set-range-values.mutation';import { SetRowDataMutation } from '../commands/mutations/set-row-data.mutation';import { SetRowHiddenMutation, SetRowVisibleMutation } from '../commands/mutations/set-row-visible.mutation';@@ -162,9 +166,6 @@ import { SelectRangeCommand, SetSelectionsOperation } from '../commands/operatioimport { SetWorksheetActiveOperation } from '../commands/operations/set-worksheet-active.operation';import { ONLY_REGISTER_FORMULA_RELATED_MUTATIONS_KEY } from './config';import { MAX_CELL_PER_SHEET_DEFAULT, MAX_CELL_PER_SHEET_KEY } from './config/config';-import { SetRangeThemeMutation } from '../commands/mutations/set-range-theme.mutation';-import { RemoveRangeThemeMutation } from '../commands/mutations/remove-range-theme.mutation';-import { AddRangeThemeMutation } from '../commands/mutations/add-range-theme.mutation';export interface IStyleTypeValue<T> {type: keyof IStyleData;@@ -204,6 +205,9 @@ export class BasicWorksheetController extends Disposable implements IDisposableEmptyMutation,SetRowHiddenMutation, // formula SUBTOTALSetRowVisibleMutation,++ MarkDirtyRowAutoHeightMutation,+ CancelMarkDirtyRowAutoHeightMutation,] as IMutation<object>[]).forEach((mutation) => {this._commandService.registerCommand(mutation);this._dataSyncPrimaryController?.registerSyncingMutations(mutation);diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.tsindex a2a52b6176..31b31f3772 100644--- a/packages/sheets/src/index.ts+++ b/packages/sheets/src/index.ts@@ -102,7 +102,7 @@ export {} from './services/ref-range/util';export type { MutationsAffectRange } from './services/ref-range/util';export { InterceptCellContentPriority, INTERCEPTOR_POINT } from './services/sheet-interceptor/interceptor-const';-export { AFTER_CELL_EDIT, BEFORE_CELL_EDIT, SheetInterceptorService, VALIDATE_CELL } from './services/sheet-interceptor/sheet-interceptor.service';+export { AFTER_CELL_EDIT, BEFORE_CELL_EDIT, type IAutoHeightContext, SheetInterceptorService, VALIDATE_CELL } from './services/sheet-interceptor/sheet-interceptor.service';export type { ISheetLocation, ISheetLocationBase, ISheetRowLocation } from './services/sheet-interceptor/utils/interceptor';export { MERGE_CELL_INTERCEPTOR_CHECK, MergeCellController } from './controllers/merge-cell.controller';export { AddMergeRedoSelectionsOperationFactory, AddMergeUndoSelectionsOperationFactory } from './commands/utils/handle-merge-operation';@@ -331,6 +331,7 @@ export {export {DeltaColumnWidthCommand,type IDeltaColumnWidthCommandParams,+ type ISetColWidthCommandParams,SetColWidthCommand,} from './commands/commands/set-worksheet-col-width.command';export { SetWorksheetHideCommand } from './commands/commands/set-worksheet-hide.command';@@ -452,6 +453,12 @@ export {SetWorksheetRowHeightMutation,SetWorksheetRowIsAutoHeightMutation,} from './commands/mutations/set-worksheet-row-height.mutation';+export {+ CancelMarkDirtyRowAutoHeightMutation,+ type ICancelMarkDirtyRowAutoHeightMutationParams,+ type IMarkDirtyRowAutoHeightMutationParams,+ MarkDirtyRowAutoHeightMutation,+} from './commands/mutations/mark-dirty-auto-height.mutation';export { type IScrollToCellOperationParams, ScrollToCellOperation } from './commands/operations/scroll-to-cell.operation';diff --git a/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.ts b/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.tsindex 03a69ea589..8b38fe7091 100644--- a/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.ts+++ b/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.ts@@ -27,6 +27,7 @@ import type {IRange,IUndoRedoCommandInfosByInterceptor,Nullable,+ ObjectMatrix,Workbook,Worksheet,} from '@univerjs/core';@@ -68,6 +69,20 @@ export interface IRangeInterceptors {getMutations(rangesInfo: IRangesInfo): IUndoRedoCommandInfosByInterceptor;}+export interface IAutoHeightContext {+ unitId: string;+ subUnitId: string;+ ranges: IRange[];+ autoHeightRanges?: IRange[];+ lazyAutoHeightRanges?: IRange[];+ cellHeights?: ObjectMatrix<number>;+}++export interface IAutoHeightInterceptors {+ priority?: number;+ getMutations(ctx: IAutoHeightContext): IUndoRedoCommandInfosByInterceptor;+}+interface ISheetLocationForEditor extends ISheetLocation {origin: Nullable<ICellData>;}@@ -83,6 +98,7 @@ export class SheetInterceptorService extends Disposable {private _interceptorsByName: Map<string, Array<IInterceptor<unknown, unknown>>> = new Map();private _commandInterceptors: ICommandInterceptor[] = [];private _rangeInterceptors: IRangeInterceptors[] = [];+ private _autoHeightInterceptors: IAutoHeightInterceptors[] = [];private _beforeCommandInterceptor: IBeforeCommandInterceptor[] = [];private _afterCommandInterceptors: ICommandInterceptor[] = [];@@ -120,12 +136,16 @@ export class SheetInterceptorService extends Disposable {priority: -1,effect: InterceptorEffectEnum.Style | InterceptorEffectEnum.Value,handler(value, context): Nullable<ICellData> {+ // only copy here, should avoid unnecessary copy object when interceptor is calledconst rawData = context.worksheet.getCellRaw(context.row, context.col);if (value) {- return { ...rawData, ...value };+ return {+ ...rawData,+ ...value,+ };}- return rawData;+ return rawData ? { ...rawData } : undefined;},});@@ -212,6 +232,28 @@ export class SheetInterceptorService extends Disposable {};}+ interceptAutoHeight(interceptor: IAutoHeightInterceptors): IDisposable {+ if (this._autoHeightInterceptors.includes(interceptor)) {+ throw new Error('[SheetInterceptorService]: Interceptor already exists!');+ }++ this._autoHeightInterceptors.push(interceptor);+ this._autoHeightInterceptors.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));++ return this.disposeWithMe(toDisposable(() => remove(this._autoHeightInterceptors, interceptor)));+ }++ generateMutationsOfAutoHeight(ctx: IAutoHeightContext): IUndoRedoCommandInfosByInterceptor {+ const infos = this._autoHeightInterceptors.map((i) => i.getMutations(ctx));++ return {+ preUndos: infos.map((i) => i.preUndos ?? []).flat(),+ undos: infos.map((i) => i.undos).flat(),+ preRedos: infos.map((i) => i.preRedos ?? []).flat(),+ redos: infos.map((i) => i.redos).flat(),+ };+ }+/*** Add a listener function to a specific command to determine if the command can execute mutations. It should be* called in controllers.