Skip to content

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

feat(sheet): automatically adjusts the line height (#308)

Ran Luo15fedbdc2e57
diff --git a/packages/base-render/src/Basics/Tools.ts b/packages/base-render/src/Basics/Tools.ts
index 922b9d1837..6dca32d9d4 100644
--- a/packages/base-render/src/Basics/Tools.ts
+++ b/packages/base-render/src/Basics/Tools.ts
@@ -527,11 +527,12 @@ export function getCellByIndex(
columnWidthAccumulation
);
- const { isMerged, isMergedMainCell, startRow, startColumn, endRow, endColumn } = mergeCellHandler(
+ const { isMerged, isMergedMainCell, startRow, startColumn, endRow, endColumn } = getCellInfoInMergeData(
row,
column,
mergeData
);
+
let mergeInfo = {
startRow,
startColumn,
@@ -582,8 +583,10 @@ export function getCellByIndex(
};
}
-// WTF: this name doesn't express any useful information about what is this used for
-export function mergeCellHandler(row: number, column: number, mergeData?: IRange[]): ISelectionCell {
+/**
+ * Determines whether the cell(row, column) is within the range of the merged cells.
+ */
+export function getCellInfoInMergeData(row: number, column: number, mergeData?: IRange[]): ISelectionCell {
let isMerged = false; // The upper left cell only renders the content
let isMergedMainCell = false;
let newEndRow = row;
@@ -603,6 +606,7 @@ export function mergeCellHandler(row: number, column: number, mergeData?: IRange
startColumn: mergeColumn,
};
}
+
for (let i = 0; i < mergeData.length; i++) {
const {
startRow: startRowMarge,
@@ -642,6 +646,29 @@ export function mergeCellHandler(row: number, column: number, mergeData?: IRange
};
}
+/**
+ * Determine whether there are any cells in a row that are not in the merged cells, mainly used for the calculation of auto height
+ */
+export function hasUnMergedCellInRow(
+ row: number,
+ startColumn: number,
+ endColumn: number,
+ mergeData: IRange[]
+): boolean {
+ // In the selection area, if a cell is not in the merged cell, the automatic height of the row needs to be calculated.
+ let hasUnMergedCell = false;
+ for (let colIndex = startColumn; colIndex <= endColumn; colIndex++) {
+ const { isMerged, isMergedMainCell } = getCellInfoInMergeData(row, colIndex, mergeData);
+
+ if (!isMerged && !isMergedMainCell) {
+ hasUnMergedCell = true;
+ break;
+ }
+ }
+
+ return hasUnMergedCell;
+}
+
export function mergeInfoOffset(
mergeInfo: IRangeWithCoord,
offsetX: number,
diff --git a/packages/base-render/src/Component/Sheets/SheetSkeleton.ts b/packages/base-render/src/Component/Sheets/SheetSkeleton.ts
index 3cd0d6b30f..d91205ee3d 100644
--- a/packages/base-render/src/Component/Sheets/SheetSkeleton.ts
+++ b/packages/base-render/src/Component/Sheets/SheetSkeleton.ts
@@ -38,8 +38,10 @@ import { BORDER_TYPE, COLOR_BLACK_RGB } from '../../Basics/Const';
import {
fixLineWidthByScale,
getCellByIndex,
+ getCellInfoInMergeData,
getCellPositionByIndex,
getFontStyleString,
+ hasUnMergedCellInRow,
isRectIntersect,
mergeInfoOffset,
} from '../../Basics/Tools';
@@ -47,6 +49,7 @@ import { IBoundRect } from '../../Basics/Vector2';
import { DocumentSkeleton } from '../Docs/DocSkeleton';
import { Skeleton } from '../Skeleton';
import { BorderCache, IStylesCache } from './Interfaces';
+import { getDocsSkeletonPageSize } from './Spreadsheet';
interface ISetCellCache {
cache: IStylesCache;
@@ -55,6 +58,11 @@ interface ISetCellCache {
cellData?: ObjectMatrix<ICellData>;
}
+export interface IRowAutoHeightInfo {
+ row: number;
+ autoHeight?: number;
+}
+
interface CellOtherConfig {
/**
* textRotation
@@ -294,6 +302,85 @@ export class SpreadsheetSkeleton extends Skeleton {
return this;
}
+ calculateAutoHeightInRange(ranges: Nullable<IRange[]>) {
+ if (!Tools.isArray(ranges)) {
+ return [];
+ }
+
+ const results: IRowAutoHeightInfo[] = [];
+ const { mergeData } = this._config;
+
+ for (const range of ranges) {
+ const { startRow, endRow, startColumn, endColumn } = range;
+
+ for (let rowIndex = startRow; rowIndex <= endRow; rowIndex++) {
+ // If the row has already been calculated, it does not need to be calculated
+ if (results.some(({ row }) => row === rowIndex)) {
+ continue;
+ }
+
+ const hasUnMergedCell = hasUnMergedCellInRow(rowIndex, startColumn, endColumn, mergeData);
+
+ if (hasUnMergedCell) {
+ const autoHeight = this.calculateRowAutoHeight(rowIndex);
+
+ results.push({
+ row: rowIndex,
+ autoHeight,
+ });
+ }
+ }
+ }
+
+ return results;
+ }
+
+ private calculateRowAutoHeight(rowNum: number): number {
+ const { columnCount, columnData, mergeData } = this._config;
+ const data = Tools.createObjectArray(columnData);
+ let height = 0;
+
+ for (let i = 0; i < columnCount; i++) {
+ // When calculating the automatic height of a row, if a cell is in a merged cell,
+ // skip the cell directly, which currently follows the logic of Excel
+ const { isMerged, isMergedMainCell } = getCellInfoInMergeData(rowNum, i, mergeData);
+
+ if (isMerged || isMergedMainCell) {
+ continue;
+ }
+
+ const modelObject = this.getCellDocumentModel(rowNum, i);
+ if (modelObject == null) {
+ continue;
+ }
+
+ const { documentModel, textRotation, wrapStrategy } = modelObject;
+ if (documentModel == null) {
+ continue;
+ }
+
+ let { a: angle } = textRotation as ITextRotation;
+ const { v: isVertical = BooleanNumber.FALSE } = textRotation as ITextRotation;
+ if (isVertical === BooleanNumber.TRUE) {
+ angle = DEFAULT_ROTATE_ANGLE;
+ }
+
+ const colWidth = data.get(i)?.w;
+ if (typeof colWidth === 'number' && wrapStrategy === WrapStrategy.WRAP) {
+ documentModel.updateDocumentDataPageSize(colWidth);
+ }
+
+ const documentSkeleton = DocumentSkeleton.create(documentModel, this._localService);
+ documentSkeleton.calculate();
+
+ const { height: h = 0 } = getDocsSkeletonPageSize(documentSkeleton, angle) ?? {};
+
+ height = Math.max(height, h);
+ }
+
+ return height;
+ }
+
updateLayout() {
if (!this.dirty) {
return;
@@ -866,6 +953,7 @@ export class SpreadsheetSkeleton extends Skeleton {
const verticalAlign: VerticalAlign = cellOtherConfig.verticalAlign || VerticalAlign.UNSPECIFIED;
const wrapStrategy: WrapStrategy = cellOtherConfig.wrapStrategy || WrapStrategy.UNSPECIFIED;
const paddingData: IPaddingData = cellOtherConfig.paddingData || DEFAULT_PADDING_DATA;
+
if (cell.p) {
const { a: angle = 0, v: isVertical = BooleanNumber.FALSE } = textRotation;
let centerAngle = 0;
@@ -1038,11 +1126,11 @@ export class SpreadsheetSkeleton extends Skeleton {
if (!rowDataItem) {
continue;
}
-
- if (rowDataItem.h != null) {
- rowHeight = rowDataItem.h;
- } else if (rowDataItem.ah != null) {
- rowHeight = rowDataItem.ah;
+ const { h = defaultRowHeight, ah, isAutoHeight } = rowDataItem;
+ if ((isAutoHeight == null || !!isAutoHeight) && typeof ah === 'number') {
+ rowHeight = ah;
+ } else {
+ rowHeight = h;
}
if (rowDataItem.hd === BooleanNumber.TRUE) {
diff --git a/packages/base-render/src/Component/Sheets/Spreadsheet.ts b/packages/base-render/src/Component/Sheets/Spreadsheet.ts
index 7a35cc4fe5..adb09b6eeb 100644
--- a/packages/base-render/src/Component/Sheets/Spreadsheet.ts
+++ b/packages/base-render/src/Component/Sheets/Spreadsheet.ts
@@ -37,6 +37,65 @@ import { SpreadsheetSkeleton } from './SheetSkeleton';
const OBJECT_KEY = '__SHEET_EXTENSION_FONT_DOCUMENT_INSTANCE__';
+/**
+ * Obtain the height and width of a cell's text, taking into account scenarios with rotated text.
+ * @param documentSkeleton Data of the document's ViewModel
+ * @param angle The rotation angle of an Excel cell
+ * @returns
+ */
+export function getDocsSkeletonPageSize(documentSkeleton: DocumentSkeleton, angle: number = 0) {
+ const skeletonData = documentSkeleton?.getSkeletonData();
+
+ if (!skeletonData) {
+ return;
+ }
+ const { pages } = skeletonData;
+ const lastPage = pages[pages.length - 1];
+
+ if (angle === 0) {
+ const { width, height } = lastPage;
+ return { width, height };
+ }
+
+ let allRotatedWidth = 0;
+ let allRotatedHeight = 0;
+
+ const orientation = getRotateOrientation(angle);
+ const widthArray: Array<{ rotatedWidth: number; spaceWidth: number }> = [];
+ columnIterator([lastPage], (column: IDocumentSkeletonColumn) => {
+ const { lines, width: columnWidth, spaceWidth } = column;
+
+ const { rotatedHeight, rotatedWidth } = getRotateOffsetAndFarthestHypotenuse(lines, columnWidth, angle);
+ allRotatedHeight += rotatedHeight;
+
+ widthArray.push({ rotatedWidth, spaceWidth });
+ });
+
+ const tanTheta = Math.tan(angle);
+ const sinTheta = Math.sin(angle);
+
+ const widthCount = widthArray.length;
+ for (let i = 0; i < widthCount; i++) {
+ const { rotatedWidth, spaceWidth } = widthArray[i];
+
+ if (i === 0) {
+ allRotatedWidth += rotatedWidth;
+ }
+
+ if (
+ (orientation === ORIENTATION_TYPE.UP && i === 0) ||
+ (orientation === ORIENTATION_TYPE.DOWN && i === widthCount - 1)
+ ) {
+ allRotatedWidth += (rotatedWidth + spaceWidth / sinTheta) / tanTheta;
+ }
+ }
+
+ return {
+ width: allRotatedWidth,
+ height: allRotatedHeight,
+ };
+}
+
export class Spreadsheet extends SheetComponent {
private _borderAuxiliaryExtension!: BorderAuxiliary;
@@ -309,65 +368,6 @@ export class Spreadsheet extends SheetComponent {
// this._selection?.dispose();
// this._hasSelection = false;
// }
-
- /**
- * Obtain the height and width of a cell's text, taking into account scenarios with rotated text.
- * @param documentSkeleton Data of the document's ViewModel
- * @param angle The rotation angle of an Excel cell
- * @returns
- */
- getDocsSkeletonPageSize(documentSkeleton: DocumentSkeleton, angle: number = 0) {
- const skeletonData = documentSkeleton?.getSkeletonData();
-
- if (!skeletonData) {
- return;
- }
- const { pages } = skeletonData;
- const lastPage = pages[pages.length - 1];
-
- if (angle === 0) {
- const { width, height } = lastPage;
- return { width, height };
- }
-
- let allRotatedWidth = 0;
- let allRotatedHeight = 0;
-
- const orientation = getRotateOrientation(angle);
- const widthArray: Array<{ rotatedWidth: number; spaceWidth: number }> = [];
- columnIterator([lastPage], (column: IDocumentSkeletonColumn) => {
- const { lines, width: columnWidth, spaceWidth } = column;
-
- const { rotatedHeight, rotatedWidth } = getRotateOffsetAndFarthestHypotenuse(lines, columnWidth, angle);
- allRotatedHeight += rotatedHeight;
-
- widthArray.push({ rotatedWidth, spaceWidth });
- });
-
- const tanTheta = Math.tan(angle);
- const sinTheta = Math.sin(angle);
-
- const widthCount = widthArray.length;
- for (let i = 0; i < widthCount; i++) {
- const { rotatedWidth, spaceWidth } = widthArray[i];
-
- if (i === 0) {
- allRotatedWidth += rotatedWidth;
- }
-
- if (
- (orientation === ORIENTATION_TYPE.UP && i === 0) ||
- (orientation === ORIENTATION_TYPE.DOWN && i === widthCount - 1)
- ) {
- allRotatedWidth += (rotatedWidth + spaceWidth / sinTheta) / tanTheta;
- }
- }
-
- return {
- width: allRotatedWidth,
- height: allRotatedHeight,
- };
- }
// scaleCacheCanvas() {
// let scaleX = this.getParent()?.ancestorScaleX || 1;
// let scaleY = this.getParent()?.ancestorScaleX || 1;
@@ -575,7 +575,7 @@ export class Spreadsheet extends SheetComponent {
cellValueType !== CellValueType.BOOLEAN &&
horizontalAlign !== HorizontalAlign.JUSTIFIED
) {
- let contentSize = this.getDocsSkeletonPageSize(documentSkeleton, angle);
+ let contentSize = getDocsSkeletonPageSize(documentSkeleton, angle);
if (!contentSize) {
return true;
@@ -633,7 +633,7 @@ export class Spreadsheet extends SheetComponent {
const cellHeight = endY - startY;
documentSkeleton.getModel().updateDocumentDataPageSize(cellHeight);
documentSkeleton.calculate();
- const contentSize = this.getDocsSkeletonPageSize(documentSkeleton, angle);
+ const contentSize = getDocsSkeletonPageSize(documentSkeleton, angle);
if (!contentSize) {
return true;
diff --git a/packages/base-render/src/Engine.ts b/packages/base-render/src/Engine.ts
index 2fee50d5d7..3eb0edd5fa 100644
--- a/packages/base-render/src/Engine.ts
+++ b/packages/base-render/src/Engine.ts
@@ -125,6 +125,8 @@ export class Engine extends ThinEngine<Scene> {
this.disposeWithMe(fromWindowEvent('resize', () => this.resize()));
}
+ // TODO: @jocs is it necessary to use ResizeObserver API?
+ // https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver
resize() {
if (!this._container) {
return;
diff --git a/packages/base-render/src/RenderEngine.ts b/packages/base-render/src/RenderEngine.ts
index 86462ccbbb..2cf1b50317 100644
--- a/packages/base-render/src/RenderEngine.ts
+++ b/packages/base-render/src/RenderEngine.ts
@@ -17,6 +17,7 @@ export class RenderEngine extends Plugin {
@Inject(Injector) override readonly _injector: Injector
) {
super(PLUGIN_NAMES.BASE_RENDER);
+
this._injector.add([IRenderingEngine, { useFactory: () => new Engine() }]);
this._injector.add([
diff --git a/packages/base-render/src/Shape/RichText.ts b/packages/base-render/src/Shape/RichText.ts
index 588d33c8d9..fd67179824 100644
--- a/packages/base-render/src/Shape/RichText.ts
+++ b/packages/base-render/src/Shape/RichText.ts
@@ -139,8 +139,8 @@ export class RichText extends BaseObject {
}
const { pages } = skeletonData;
const lastPage = pages[pages.length - 1];
-
const { width, height } = lastPage;
+
return { width, height };
}
diff --git a/packages/base-sheets/src/Basics/Const/COMMAND_LISTENER_CONST.ts b/packages/base-sheets/src/Basics/Const/COMMAND_LISTENER_CONST.ts
index bb2956c3d8..1120a7a607 100644
--- a/packages/base-sheets/src/Basics/Const/COMMAND_LISTENER_CONST.ts
+++ b/packages/base-sheets/src/Basics/Const/COMMAND_LISTENER_CONST.ts
@@ -9,10 +9,14 @@ import { SetRangeValuesMutation } from '../../commands/mutations/set-range-value
import { SetRowHiddenMutation, SetRowVisibleMutation } from '../../commands/mutations/set-row-visible.mutation';
import { SetWorksheetActivateMutation } from '../../commands/mutations/set-worksheet-activate.mutation';
import { SetWorksheetColWidthMutation } from '../../commands/mutations/set-worksheet-col-width.mutation';
-import { SetWorksheetRowHeightMutation } from '../../commands/mutations/set-worksheet-row-height.mutation';
+import {
+ SetWorksheetRowAutoHeightMutation,
+ SetWorksheetRowHeightMutation,
+} from '../../commands/mutations/set-worksheet-row-height.mutation';
export const COMMAND_LISTENER_SKELETON_CHANGE = [
SetWorksheetRowHeightMutation.id,
+ SetWorksheetRowAutoHeightMutation.id,
SetWorksheetColWidthMutation.id,
SetWorksheetActivateMutation.id,
InsertRowMutation.id,
diff --git a/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts b/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts
index 4b8619841a..2da11b0509 100644
--- a/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts
+++ b/packages/base-sheets/src/Controller/BasicWorksheet.controller.ts
@@ -66,7 +66,11 @@ import { DeltaColumnWidthCommand, SetColWidthCommand } from '../commands/command
import { SetWorksheetHideCommand } from '../commands/commands/set-worksheet-hide.command';
import { SetWorksheetNameCommand } from '../commands/commands/set-worksheet-name.command';
import { SetWorksheetOrderCommand } from '../commands/commands/set-worksheet-order.command';
-import { DeltaRowHeightCommand, SetRowHeightCommand } from '../commands/commands/set-worksheet-row-height.command';
+import {
+ DeltaRowHeightCommand,
+ // SetRowAutoHeightCommand,
+ SetRowHeightCommand,
+} from '../commands/commands/set-worksheet-row-height.command';
import { SetWorksheetShowCommand } from '../commands/commands/set-worksheet-show.command';
import { ChangeZoomRatioCommand, SetZoomRatioCommand } from '../commands/commands/set-zoom-ratio.command';
import { TrimWhitespaceCommand } from '../commands/commands/trim-whitespace.command';
@@ -92,7 +96,10 @@ import { SetWorksheetColWidthMutation } from '../commands/mutations/set-workshee
import { SetWorksheetHideMutation } from '../commands/mutations/set-worksheet-hide.mutation';
import { SetWorksheetNameMutation } from '../commands/mutations/set-worksheet-name.mutation';
import { SetWorksheetOrderMutation } from '../commands/mutations/set-worksheet-order.mutation';
-import { SetWorksheetRowHeightMutation } from '../commands/mutations/set-worksheet-row-height.mutation';
+import {
+ SetWorksheetRowAutoHeightMutation,
+ SetWorksheetRowHeightMutation,
+} from '../commands/mutations/set-worksheet-row-height.mutation';
export interface IStyleTypeValue<T> {
type: keyof IStyleData;
@@ -149,8 +156,10 @@ export class BasicWorksheetController extends Disposable implements IDisposable
SetColWidthCommand,
SetWorksheetColWidthMutation,
+ // SetRowAutoHeightCommand,
SetRowHeightCommand,
SetWorksheetRowHeightMutation,
+ SetWorksheetRowAutoHeightMutation,
SetRowHiddenCommand,
SetRowHiddenMutation,
SetColHiddenCommand,
diff --git a/packages/base-sheets/src/Controller/auto-height.controller.ts b/packages/base-sheets/src/Controller/auto-height.controller.ts
new file mode 100644
index 0000000000..fa92567b57
--- /dev/null
+++ b/packages/base-sheets/src/Controller/auto-height.controller.ts
@@ -0,0 +1,98 @@
+import { IUniverInstanceService, LifecycleStages, OnLifecycle, SheetInterceptorService } from '@univerjs/core';
+import { Inject, Injector } from '@wendellhu/redi';
+
+import { ISetStyleParams, SetStyleCommand } from '../commands/commands/set-style.command';
+import {
+ ISetWorksheetRowAutoHeightMutationParams,
+ SetWorksheetRowAutoHeightMutation,
+ SetWorksheetRowAutoHeightMutationFactory,
+} from '../commands/mutations/set-worksheet-row-height.mutation';
+import { SelectionManagerService } from '../services/selection-manager.service';
+import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';
+
+@OnLifecycle(LifecycleStages.Ready, AutoHeightController)
+export class AutoHeightController {
+ constructor(
+ @Inject(Injector) private _injector: Injector,
+ @Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,
+ @Inject(SelectionManagerService) private _selectionManagerService: SelectionManagerService,
+ @Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,
+ @Inject(SheetSkeletonManagerService) private _sheetSkeletonManagerService: SheetSkeletonManagerService
+ ) {
+ this._initialize();
+ }
+
+ private _initialize() {
+ const {
+ _sheetInterceptorService: sheetInterceptorService,
+ _selectionManagerService: selectionManagerService,
+ _univerInstanceService: univerInstanceService,
+ _sheetSkeletonManagerService: sheetSkeletonService,
+ _injector: injector,
+ } = this;
+
+ sheetInterceptorService.interceptCommand({
+ getMutations(command: { id: string; params: ISetStyleParams<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.
+ const AFFECT_LAYOUT_STYLES = ['ff', 'fs', 'tr', 'tb'];
+
+ if (!AFFECT_LAYOUT_STYLES.includes(command.params?.style.type)) {
+ return {
+ redos: [],
+ undos: [],
+ };
+ }
+
+ const selections = selectionManagerService.getRangeDatas();
+
+ if (!selections?.length) {
+ return {
+ redos: [],
+ undos: [],
+ };
+ }
+
+ const { skeleton } = sheetSkeletonService.getCurrent()!;
+ const rowsAutoHeightInfo = skeleton.calculateAutoHeightInRange(selections);
+
+ const workbook = univerInstanceService.getCurrentUniverSheetInstance();
+ const workbookId = workbook.getUnitId();
+ const worksheetId = workbook.getActiveSheet().getSheetId();
+
+ const redoParams: ISetWorksheetRowAutoHeightMutationParams = {
+ worksheetId,
+ workbookId,
+ rowsAutoHeightInfo,
+ };
+
+ const undoParams: ISetWorksheetRowAutoHeightMutationParams = SetWorksheetRowAutoHeightMutationFactory(
+ injector,
+ redoParams
+ );
+
+ return {
+ undos: [
+ {
+ id: SetWorksheetRowAutoHeightMutation.id,
+ params: undoParams,
+ },
+ ],
+ redos: [
+ {
+ id: SetWorksheetRowAutoHeightMutation.id,
+ params: redoParams,
+ },
+ ],
+ };
+ },
+ });
+ }
+}
diff --git a/packages/base-sheets/src/Controller/sheet-render.controller.ts b/packages/base-sheets/src/Controller/sheet-render.controller.ts
index 7c7012bb0c..c9d1490bff 100644
--- a/packages/base-sheets/src/Controller/sheet-render.controller.ts
+++ b/packages/base-sheets/src/Controller/sheet-render.controller.ts
@@ -100,7 +100,6 @@ export class SheetRenderController extends Disposable {
const unitId = workbook.getUnitId();
const worksheet = workbook.getActiveSheet();
const sheetId = worksheet.getSheetId();
-
const params = command.params;
const { workbookId, worksheetId } = params as ISetWorksheetMutationParams;
if (!(workbookId === workbook.getUnitId() && worksheetId === worksheet.getSheetId())) {
diff --git a/packages/base-sheets/src/SheetPlugin.ts b/packages/base-sheets/src/SheetPlugin.ts
index adecb94ff5..760ab2788c 100644
--- a/packages/base-sheets/src/SheetPlugin.ts
+++ b/packages/base-sheets/src/SheetPlugin.ts
@@ -5,6 +5,7 @@ import { Dependency, Inject, Injector } from '@wendellhu/redi';
import { SetScrollOperation } from './commands/operations/scroll.operation';
import { SetSelectionsOperation } from './commands/operations/selection.operation';
import { SetZoomRatioOperation } from './commands/operations/set-zoom-ratio.operation';
+import { AutoHeightController } from './Controller/auto-height.controller';
import { BasicWorksheetController } from './Controller/BasicWorksheet.controller';
import { FormulaBarController } from './Controller/FormulaBarController';
import { FreezeController } from './Controller/freeze.controller';
@@ -76,6 +77,7 @@ export class SheetPlugin extends Plugin {
[FreezeController],
[ScrollController],
[ZoomController],
+ [AutoHeightController],
];
dependencies.forEach((d) => {
diff --git a/packages/base-sheets/src/View/sheet-canvas-view.ts b/packages/base-sheets/src/View/sheet-canvas-view.ts
index e2e9fdb66a..1df0741938 100644
--- a/packages/base-sheets/src/View/sheet-canvas-view.ts
+++ b/packages/base-sheets/src/View/sheet-canvas-view.ts
@@ -97,7 +97,6 @@ export class SheetCanvasView {
}
const isAddedToExistedScene = container == null && parentRenderUnitId != null;
-
if (isAddedToExistedScene) {
this._renderManagerService.createRenderWithParent(unitId, parentRenderUnitId);
} else {
@@ -184,7 +183,6 @@ export class SheetCanvasView {
}
const { rowHeader, columnHeader } = worksheet.getConfig();
-
const viewMain = new Viewport(VIEWPORT_KEY.VIEW_MAIN, scene, {
left: rowHeader.width,
top: columnHeader.height,
@@ -192,6 +190,7 @@ export class SheetCanvasView {
right: 0,
isWheelPreventDefaultX: true,
});
+
const viewRowTop = new Viewport(VIEWPORT_KEY.VIEW_ROW_TOP, scene, {
active: false,
isWheelPreventDefaultX: true,
diff --git a/packages/base-sheets/src/commands/commands/insert-row-col.command.ts b/packages/base-sheets/src/commands/commands/insert-row-col.command.ts
index 806fa6fa08..62fcb5139f 100644
--- a/packages/base-sheets/src/commands/commands/insert-row-col.command.ts
+++ b/packages/base-sheets/src/commands/commands/insert-row-col.command.ts
@@ -76,7 +76,7 @@ export const InsertRowCommand: ICommand = {
const undoRedoService = accessor.get(IUndoRedoService);
const univerInstanceService = accessor.get(IUniverInstanceService);
- const workbook = univerInstanceService.getUniverSheetInstance(params.workbookId)!!;
+ const workbook = univerInstanceService.getUniverSheetInstance(params.workbookId)!;
const worksheet = workbook.getSheetBySheetId(params.worksheetId)!;
const { range, direction, workbookId, worksheetId } = params;
diff --git a/packages/base-sheets/src/commands/commands/set-style.command.ts b/packages/base-sheets/src/commands/commands/set-style.command.ts
index 804b437de8..7e50c3e047 100644
--- a/packages/base-sheets/src/commands/commands/set-style.command.ts
+++ b/packages/base-sheets/src/commands/commands/set-style.command.ts
@@ -13,6 +13,8 @@ import {
IUndoRedoService,
IUniverInstanceService,
ObjectMatrix,
+ sequenceExecute,
+ SheetInterceptorService,
Tools,
VerticalAlign,
WrapStrategy,
@@ -55,11 +57,8 @@ export const SetStyleCommand: ICommand<ISetStyleParams<unknown>> = {
}
const workbookId = univerInstanceService.getCurrentUniverSheetInstance().getUnitId();
- const worksheetId = univerInstanceService
- .getCurrentUniverSheetInstance()
+ const worksheetId = univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet().getSheetId();
- .getActiveSheet()
- .getSheetId();
const style = params.style;
const workbook = univerInstanceService.getUniverSheetInstance(workbookId);
@@ -116,16 +115,35 @@ export const SetStyleCommand: ICommand<ISetStyleParams<unknown>> = {
setRangeValuesMutationParams
);
- const result = commandService.executeCommand(SetRangeValuesMutation.id, setRangeValuesMutationParams);
- if (result) {
+ const setRangeValuesResult = commandService.executeCommand(
+ SetRangeValuesMutation.id,
+ setRangeValuesMutationParams
+ );
+
+ const { undos, redos } = accessor.get(SheetInterceptorService).onCommandExecute({
+ id: SetStyleCommand.id,
+ params,
+ });
+
+ const result = await sequenceExecute([...redos], commandService);
+
+ if (setRangeValuesResult && result.result) {
undoRedoService.pushUndoRedo({
URI: workbookId,
- undo() {
- return commandService.executeCommand(SetRangeValuesMutation.id, undoSetRangeValuesMutationParams);
- },
- redo() {
- return commandService.executeCommand(SetRangeValuesMutation.id, setRangeValuesMutationParams);
- },
+ undo: async () =>
+ (
+ await sequenceExecute(
+ [{ id: SetRangeValuesMutation.id, params: undoSetRangeValuesMutationParams }, ...undos],
+ commandService
+ )
+ ).result,
+ redo: async () =>
+ (
+ await sequenceExecute(
+ [{ id: SetRangeValuesMutation.id, params: setRangeValuesMutationParams }, ...redos],
+ commandService
+ )
+ ).result,
});
return true;
diff --git a/packages/base-sheets/src/commands/commands/set-worksheet-row-height.command.ts b/packages/base-sheets/src/commands/commands/set-worksheet-row-height.command.ts
index b99cf8ab4c..eabfaf3fdb 100644
--- a/packages/base-sheets/src/commands/commands/set-worksheet-row-height.command.ts
+++ b/packages/base-sheets/src/commands/commands/set-worksheet-row-height.command.ts
@@ -102,6 +102,42 @@ export const DeltaRowHeightCommand: ICommand = {
},
};
+export interface ISetRowAutoHeightCommandParams {}
+
+// export const SetRowAutoHeightCommand: ICommand = {
+// type: CommandType.COMMAND,
+// id: 'sheet.command.set-row-auto-height',
+// handler: async (accessor: IAccessor) => {
+// const commandService = accessor.get(ICommandService);
+// const undoRedoService = accessor.get(IUndoRedoService);
+// const univerInstanceService = accessor.get(IUniverInstanceService);
+// const workbook = univerInstanceService.getCurrentUniverSheetInstance();
+// const workbookId = workbook.getUnitId();
+// const { redoMutationParams, undoMutationParams } = getAutoHeightUndoRedoParams(accessor);
+
+// if (redoMutationParams == null || undoMutationParams == null) {
+// return false;
+// }
+
+// const result = commandService.executeCommand(SetWorksheetRowAutoHeightMutation.id, redoMutationParams);
+
+// if (result) {
+// undoRedoService.pushUndoRedo({
+// URI: workbookId,
+// undo() {
+// return commandService.executeCommand(SetWorksheetRowAutoHeightMutation.id, undoMutationParams);
+// },
+// redo() {
+// return commandService.executeCommand(SetWorksheetRowAutoHeightMutation.id, redoMutationParams);
+// },
+// });
+
+// return true;
+// }
+// return true;
+// },
+// };
+
export interface ISetRowHeightCommandParams {
value: number;
}
@@ -115,7 +151,9 @@ export const SetRowHeightCommand: ICommand = {
const univerInstanceService = accessor.get(IUniverInstanceService);
const selections = selectionManagerService.getRangeDatas();
- if (!selections?.length) return false;
+ if (!selections?.length) {
+ return false;
+ }
const workbook = univerInstanceService.getCurrentUniverSheetInstance();
const workbookId = workbook.getUnitId();
@@ -127,6 +165,7 @@ export const SetRowHeightCommand: ICommand = {
ranges: selections,
rowHeight: params.value,
};
+
const undoMutationParams: ISetWorksheetRowHeightMutationParams = SetWorksheetRowHeightMutationFactory(
accessor,
redoMutationParams
diff --git a/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts b/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts
index 862a84644b..ae30f518c3 100644
--- a/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts
+++ b/packages/base-sheets/src/commands/mutations/set-range-values.mutation.ts
@@ -46,6 +46,7 @@ export const SetRangeValuesUndoMutationFactory = (
const { workbookId, worksheetId, cellValue } = params;
const univerInstanceService = accessor.get(IUniverInstanceService);
const universheet = univerInstanceService.getUniverSheetInstance(workbookId);
+
if (universheet == null) {
throw new Error('universheet is null error!');
}
diff --git a/packages/base-sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts b/packages/base-sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts
index 97003caffb..554bf39d86 100644
--- a/packages/base-sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts
+++ b/packages/base-sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts
@@ -1,3 +1,4 @@
+import { IRowAutoHeightInfo } from '@univerjs/base-render';
import { CommandType, IMutation, IRange, IUniverInstanceService, ObjectArray } from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
@@ -8,20 +9,25 @@ export interface ISetWorksheetRowHeightMutationParams {
rowHeight: number | ObjectArray<number>;
}
+export interface ISetWorksheetRowAutoHeightMutationParams {
+ workbookId: string;
+ worksheetId: string;
+ rowsAutoHeightInfo: IRowAutoHeightInfo[];
+}
+
export const SetWorksheetRowHeightMutationFactory = (
accessor: IAccessor,
params: ISetWorksheetRowHeightMutationParams
): ISetWorksheetRowHeightMutationParams => {
const univerInstanceService = accessor.get(IUniverInstanceService);
- const universheet = univerInstanceService.getUniverSheetInstance(params.workbookId);
-
- if (universheet == null) {
- throw new Error('universheet is null error!');
+ const workbook = univerInstanceService.getUniverSheetInstance(params.workbookId);
+ if (workbook == null) {
+ throw new Error('workbook is null error!');
}
- const worksheet = universheet.getSheetBySheetId(params.worksheetId);
+ const worksheet = workbook.getSheetBySheetId(params.worksheetId);
if (worksheet == null) {
- throw new Error('universheet is null error!');
+ throw new Error('worksheet is null error!');
}
const rowHeight = new ObjectArray<number>();
const manager = worksheet.getRowManager();
@@ -42,6 +48,36 @@ export const SetWorksheetRowHeightMutationFactory = (
};
};
+export const SetWorksheetRowAutoHeightMutationFactory = (
+ accessor: IAccessor,
+ params: ISetWorksheetRowAutoHeightMutationParams
+): ISetWorksheetRowAutoHeightMutationParams => {
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const workbook = univerInstanceService.getUniverSheetInstance(params.workbookId);
+ const worksheet = workbook?.getSheetBySheetId(params.worksheetId);
+ if (worksheet == null) {
+ throw new Error('workbook or worksheet is null error!');
+ }
+ const { rowsAutoHeightInfo } = params;
+ const results: IRowAutoHeightInfo[] = [];
+ const manager = worksheet.getRowManager();
+
+ for (const rowInfo of rowsAutoHeightInfo) {
+ const { row } = rowInfo;
+ const { ah } = manager.getRowOrCreate(row);
+ results.push({
+ row,
+ autoHeight: ah,
+ });
+ }
+
+ return {
+ workbookId: params.workbookId,
+ worksheetId: params.worksheetId,
+ rowsAutoHeightInfo: results,
+ };
+};
+
export const SetWorksheetRowHeightMutation: IMutation<ISetWorksheetRowHeightMutationParams> = {
id: 'sheet.mutation.set-worksheet-row-height',
type: CommandType.MUTATION,
@@ -55,13 +91,16 @@ export const SetWorksheetRowHeightMutation: IMutation<ISetWorksheetRowHeightMuta
const worksheet = universheet.getSheetBySheetId(params.worksheetId);
if (!worksheet) return false;
+
const defaultRowHeight = worksheet.getConfig().defaultRowHeight;
const manager = worksheet.getRowManager();
const ranges = params.ranges;
+
for (let i = 0; i < ranges.length; i++) {
const range = ranges[i];
for (let j = range.startRow; j < range.endRow + 1; j++) {
const row = manager.getRowOrCreate(j);
+
if (typeof params.rowHeight === 'number') {
row.h = params.rowHeight;
} else {
@@ -73,3 +112,27 @@ export const SetWorksheetRowHeightMutation: IMutation<ISetWorksheetRowHeightMuta
return true;
},
};
+
+export const SetWorksheetRowAutoHeightMutation: IMutation<ISetWorksheetRowAutoHeightMutationParams> = {
+ id: 'sheet.mutation.set-worksheet-row-auto-height',
+ type: CommandType.MUTATION,
+ handler: async (accessor, params) => {
+ const { workbookId, worksheetId, rowsAutoHeightInfo } = params;
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const workbook = univerInstanceService.getUniverSheetInstance(workbookId);
+ const worksheet = workbook?.getSheetBySheetId(worksheetId);
+
+ if (!worksheet || !workbook) {
+ return false;
+ }
+
+ const rowManager = worksheet.getRowManager();
+
+ for (const { row, autoHeight } of rowsAutoHeightInfo) {
+ const curRow = rowManager.getRowOrCreate(row);
+ curRow.ah = autoHeight;
+ }
+
+ return true;
+ },
+};
diff --git a/packages/base-sheets/src/index.ts b/packages/base-sheets/src/index.ts
index 9631ab56c8..311f3252d0 100644
--- a/packages/base-sheets/src/index.ts
+++ b/packages/base-sheets/src/index.ts
@@ -141,6 +141,7 @@ export { SetWorksheetNameMutation } from './commands/mutations/set-worksheet-nam
export { SetWorksheetOrderMutation } from './commands/mutations/set-worksheet-order.mutation';
export {
type ISetWorksheetRowHeightMutationParams,
+ SetWorksheetRowAutoHeightMutation,
SetWorksheetRowHeightMutation,
} from './commands/mutations/set-worksheet-row-height.mutation';
export { SetScrollOperation } from './commands/operations/scroll.operation';
diff --git a/packages/base-sheets/src/services/selection-manager.service.ts b/packages/base-sheets/src/services/selection-manager.service.ts
index b72e3c1ebd..afd072d8c0 100644
--- a/packages/base-sheets/src/services/selection-manager.service.ts
+++ b/packages/base-sheets/src/services/selection-manager.service.ts
@@ -1,7 +1,7 @@
import {
+ getCellInfoInMergeData,
ISelectionStyle,
ISelectionWithStyle,
- mergeCellHandler,
NORMAL_SELECTION_PLUGIN_STYLE,
} from '@univerjs/base-render';
import { IRange, ISelectionCell, makeCellRangeToRangeData, Nullable } from '@univerjs/core';
@@ -221,7 +221,7 @@ export class SelectionManagerService implements IDisposable {
}
transformCellDataToSelectionData(row: number, column: number, mergeData: IRange[]): Nullable<ISelectionWithStyle> {
- const newCellRange = mergeCellHandler(row, column, mergeData);
+ const newCellRange = getCellInfoInMergeData(row, column, mergeData);
const newSelectionData = makeCellRangeToRangeData(newCellRange);
diff --git a/packages/base-sheets/src/services/sheet-skeleton-manager.service.ts b/packages/base-sheets/src/services/sheet-skeleton-manager.service.ts
index 13a806ce42..e3f96e40cb 100644
--- a/packages/base-sheets/src/services/sheet-skeleton-manager.service.ts
+++ b/packages/base-sheets/src/services/sheet-skeleton-manager.service.ts
@@ -127,6 +127,7 @@ export class SheetSkeletonManagerService implements IDisposable {
workbook.getStyles(),
this._localeService
);
+
return spreadsheetSkeleton;
}
}
diff --git a/packages/core/src/Types/Interfaces/IRowData.ts b/packages/core/src/Types/Interfaces/IRowData.ts
index 26d8e6ce41..d4cf0ed2b5 100644
--- a/packages/core/src/Types/Interfaces/IRowData.ts
+++ b/packages/core/src/Types/Interfaces/IRowData.ts
@@ -8,6 +8,10 @@ export interface IRowData {
* height in pixel
*/
h: number;
+ /**
+ * is current row self-adaptive to its content, use `ah` to set row height when true, else use `h`.
+ */
+ isAutoHeight?: boolean;
/**
* auto height
*/
diff --git a/packages/core/src/services/command/command.service.ts b/packages/core/src/services/command/command.service.ts
index 6c692b0959..8468f69a0b 100644
--- a/packages/core/src/services/command/command.service.ts
+++ b/packages/core/src/services/command/command.service.ts
@@ -353,5 +353,6 @@ class MultiCommand implements IMultiCommand {
export function sequenceExecute(tasks: ICommandInfo[], commandService: ICommandService) {
const promises = tasks.map((task) => () => commandService.executeCommand(task.id, task.params));
+
return sequence(promises);
}
diff --git a/packages/core/src/sheets/row-manager.ts b/packages/core/src/sheets/row-manager.ts
index a64124e41e..3817411b6f 100644
--- a/packages/core/src/sheets/row-manager.ts
+++ b/packages/core/src/sheets/row-manager.ts
@@ -76,6 +76,7 @@ export class RowManager {
const config = this._config;
const create = { hd: BooleanNumber.FALSE, h: config.defaultRowHeight };
_rowData.set(rowPos, create);
+
return create;
}
@@ -114,11 +115,12 @@ export class RowManager {
if (!row) {
return true;
}
+
return row.hd !== BooleanNumber.TRUE;
}
/**
- * Get count of column in the sheet
+ * Get count of row in the sheet
* @returns
*/
getSize(): number {
diff --git a/packages/core/src/sheets/workbook.ts b/packages/core/src/sheets/workbook.ts
index 6078ceccdc..fa110447d6 100644
--- a/packages/core/src/sheets/workbook.ts
+++ b/packages/core/src/sheets/workbook.ts
@@ -125,6 +125,7 @@ export class Workbook extends Disposable {
const worksheet = new Worksheet(worksheetSnapshot, this._styles);
this._worksheets.set(id, worksheet);
this._sheetCreated$.next(worksheet);
+
return true;
}
@@ -186,16 +187,18 @@ export class Workbook extends Disposable {
* @returns void
*/
flush(): void {
- //TDOO ..
+ //TODO ..
}
getSheets(): Worksheet[] {
const { sheetOrder } = this._snapshot;
+
return sheetOrder.map((sheetId) => this._worksheets.get(sheetId)) as Worksheet[];
}
getSheetIndex(sheet: Worksheet): number {
const { sheetOrder } = this._snapshot;
+
return sheetOrder.findIndex((sheetId) => {
if (sheet.getSheetId() === sheetId) {
return true;
diff --git a/packages/core/src/sheets/worksheet.ts b/packages/core/src/sheets/worksheet.ts
index 1672f1550a..22f3fcd293 100644
--- a/packages/core/src/sheets/worksheet.ts
+++ b/packages/core/src/sheets/worksheet.ts
@@ -120,6 +120,7 @@ export class Worksheet {
clone(): Worksheet {
const { _snapshot: _config } = this;
const copy = Tools.deepClone(_config);
+
return new Worksheet(copy, this._styles);
}