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: change column width and trigger auto height (#318)

Ran Luo725d13aa20fd
diff --git a/packages/base-render/src/Component/Sheets/SheetSkeleton.ts b/packages/base-render/src/Component/Sheets/SheetSkeleton.ts
index d91205ee3d..7276ebe90b 100644
--- a/packages/base-render/src/Component/Sheets/SheetSkeleton.ts
+++ b/packages/base-render/src/Component/Sheets/SheetSkeleton.ts
@@ -34,7 +34,9 @@ import {
WrapStrategy,
} from '@univerjs/core';
-import { BORDER_TYPE, COLOR_BLACK_RGB } from '../../Basics/Const';
+import { BORDER_TYPE, COLOR_BLACK_RGB, ORIENTATION_TYPE } from '../../Basics/Const';
+import { getRotateOffsetAndFarthestHypotenuse, getRotateOrientation } from '../../Basics/Draw';
+import { IDocumentSkeletonColumn } from '../../Basics/IDocumentSkeletonCached';
import {
fixLineWidthByScale,
getCellByIndex,
@@ -46,10 +48,69 @@ import {
mergeInfoOffset,
} from '../../Basics/Tools';
import { IBoundRect } from '../../Basics/Vector2';
+import { columnIterator } from '../Docs/Common/Tools';
import { DocumentSkeleton } from '../Docs/DocSkeleton';
import { Skeleton } from '../Skeleton';
import { BorderCache, IStylesCache } from './Interfaces';
-import { getDocsSkeletonPageSize } from './Spreadsheet';
+
+/**
+ * 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,
+ };
+}
interface ISetCellCache {
cache: IStylesCache;
@@ -336,9 +397,9 @@ export class SpreadsheetSkeleton extends Skeleton {
}
private calculateRowAutoHeight(rowNum: number): number {
- const { columnCount, columnData, mergeData } = this._config;
+ const { columnCount, columnData, mergeData, defaultRowHeight } = this._config;
const data = Tools.createObjectArray(columnData);
- let height = 0;
+ 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,
diff --git a/packages/base-render/src/Component/Sheets/Spreadsheet.ts b/packages/base-render/src/Component/Sheets/Spreadsheet.ts
index adb09b6eeb..7b1e4938d7 100644
--- a/packages/base-render/src/Component/Sheets/Spreadsheet.ts
+++ b/packages/base-render/src/Component/Sheets/Spreadsheet.ts
@@ -9,13 +9,8 @@ import {
} from '@univerjs/core';
import { BaseObject } from '../../BaseObject';
-import { ORIENTATION_TYPE, RENDER_CLASS_TYPE } from '../../Basics/Const';
-import {
- getRotateOffsetAndFarthestHypotenuse,
- getRotateOrientation,
- getTranslateInSpreadContextWithPixelRatio,
-} from '../../Basics/Draw';
-import { IDocumentSkeletonColumn } from '../../Basics/IDocumentSkeletonCached';
+import { RENDER_CLASS_TYPE } from '../../Basics/Const';
+import { getTranslateInSpreadContextWithPixelRatio } from '../../Basics/Draw';
import { ITransformChangeState } from '../../Basics/Interfaces';
import { fixLineWidthByScale, getCellByIndex, getCellPositionByIndex, getScale } from '../../Basics/Tools';
import { IBoundRect, Vector2 } from '../../Basics/Vector2';
@@ -24,8 +19,6 @@ import { Engine } from '../../Engine';
import { Scene } from '../../Scene';
import { SceneViewer } from '../../SceneViewer';
import { Viewport } from '../../Viewport';
-import { columnIterator } from '../Docs/Common/Tools';
-import { DocumentSkeleton } from '../Docs/DocSkeleton';
import { Documents } from '../Docs/Document';
import { SpreadsheetExtensionRegistry } from '../Extension';
import { Background } from './Extensions/Background';
@@ -33,69 +26,10 @@ import { Border } from './Extensions/Border';
import { BorderAuxiliary } from './Extensions/BorderAuxiliary';
import { Font } from './Extensions/Font';
import { SheetComponent } from './SheetComponent';
-import { SpreadsheetSkeleton } from './SheetSkeleton';
+import { getDocsSkeletonPageSize, 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;
diff --git a/packages/base-sheets/src/Controller/auto-height.controller.ts b/packages/base-sheets/src/Controller/auto-height.controller.ts
index fa92567b57..8a3f9585e6 100644
--- a/packages/base-sheets/src/Controller/auto-height.controller.ts
+++ b/packages/base-sheets/src/Controller/auto-height.controller.ts
@@ -1,7 +1,9 @@
-import { IUniverInstanceService, LifecycleStages, OnLifecycle, SheetInterceptorService } from '@univerjs/core';
+import { IRange, IUniverInstanceService, LifecycleStages, OnLifecycle, SheetInterceptorService } from '@univerjs/core';
import { Inject, Injector } from '@wendellhu/redi';
import { ISetStyleParams, SetStyleCommand } from '../commands/commands/set-style.command';
+import { DeltaColumnWidthCommand, SetColWidthCommand } from '../commands/commands/set-worksheet-col-width.command';
+import { ISetWorksheetColWidthMutationParams } from '../commands/mutations/set-worksheet-col-width.mutation';
import {
ISetWorksheetRowAutoHeightMutationParams,
SetWorksheetRowAutoHeightMutation,
@@ -22,17 +24,68 @@ export class AutoHeightController {
this._initialize();
}
- private _initialize() {
+ private _getUndoRedoParamsOfAutoHeight(ranges: IRange[]) {
const {
- _sheetInterceptorService: sheetInterceptorService,
- _selectionManagerService: selectionManagerService,
_univerInstanceService: univerInstanceService,
_sheetSkeletonManagerService: sheetSkeletonService,
_injector: injector,
} = this;
+ const { skeleton } = sheetSkeletonService.getCurrent()!;
+ const rowsAutoHeightInfo = skeleton.calculateAutoHeightInRange(ranges);
+
+ 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,
+ },
+ ],
+ };
+ }
+
+ private _initialize() {
+ const { _sheetInterceptorService: sheetInterceptorService, _selectionManagerService: selectionManagerService } =
+ this;
+
+ // for intercept set-worksheet-col-width command.
+ sheetInterceptorService.interceptCommand({
+ getMutations: (command: { id: string; params: ISetWorksheetColWidthMutationParams }) => {
+ if (command.id !== DeltaColumnWidthCommand.id && command.id !== SetColWidthCommand.id) {
+ return {
+ redos: [],
+ undos: [],
+ };
+ }
+
+ return this._getUndoRedoParamsOfAutoHeight(command.params.ranges);
+ },
+ });
+
+ // for intercept set style command.
sheetInterceptorService.interceptCommand({
- getMutations(command: { id: string; params: ISetStyleParams<number> }) {
+ getMutations: (command: { id: string; params: ISetStyleParams<number> }) => {
if (command.id !== SetStyleCommand.id) {
return {
redos: [],
@@ -60,38 +113,7 @@ export class AutoHeightController {
};
}
- 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,
- },
- ],
- };
+ return this._getUndoRedoParamsOfAutoHeight(selections);
},
});
}
diff --git a/packages/base-sheets/src/Controller/header-resize.controller.ts b/packages/base-sheets/src/Controller/header-resize.controller.ts
index 0884872ed9..ec81eb9669 100644
--- a/packages/base-sheets/src/Controller/header-resize.controller.ts
+++ b/packages/base-sheets/src/Controller/header-resize.controller.ts
@@ -132,6 +132,7 @@ export class HeaderResizeController extends Disposable {
if (sheetObject == null) {
return;
}
+
const { spreadsheetRowHeader, spreadsheetColumnHeader, scene } = sheetObject;
const eventBindingObject =
@@ -216,7 +217,7 @@ export class HeaderResizeController extends Disposable {
if (this._currentColumn === -1) {
return;
}
-
+ // TODO: @jocs remove magic number.
const columnSize = columnHeaderHeight * 0.7;
this._columnResizeRect.transformByState({
@@ -474,6 +475,7 @@ export class HeaderResizeController extends Disposable {
const { scene } = sheetObject;
scene.onPointerMoveObserver.remove(this._moveObserver);
scene.onPointerUpObserver.remove(this._upObserver);
+
this._moveObserver = null;
this._upObserver = null;
}
diff --git a/packages/base-sheets/src/View/header-resize-shape.ts b/packages/base-sheets/src/View/header-resize-shape.ts
index a54d73bae2..aeefd188cc 100644
--- a/packages/base-sheets/src/View/header-resize-shape.ts
+++ b/packages/base-sheets/src/View/header-resize-shape.ts
@@ -47,9 +47,7 @@ export class HeaderMenuResizeShape<
}
protected override _draw(ctx: CanvasRenderingContext2D) {
- let width = this.width;
-
- let height = this.height;
+ let { width, height } = this;
let left = 0;
diff --git a/packages/base-sheets/src/commands/commands/set-worksheet-col-width.command.ts b/packages/base-sheets/src/commands/commands/set-worksheet-col-width.command.ts
index 724d4b58c1..7074940be7 100644
--- a/packages/base-sheets/src/commands/commands/set-worksheet-col-width.command.ts
+++ b/packages/base-sheets/src/commands/commands/set-worksheet-col-width.command.ts
@@ -6,6 +6,8 @@ import {
IUniverInstanceService,
RANGE_TYPE,
Rectangle,
+ sequenceExecute,
+ SheetInterceptorService,
} from '@univerjs/core';
import { IAccessor } from '@wendellhu/redi';
@@ -27,10 +29,13 @@ export const DeltaColumnWidthCommand: ICommand<IDeltaColumnWidthCommandParams> =
handler: async (accessor: IAccessor, params: IDeltaColumnWidthCommandParams) => {
const selectionManagerService = accessor.get(SelectionManagerService);
const selections = selectionManagerService.getSelections();
+
if (!selections?.length) {
return false;
}
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const workbook = univerInstanceService.getCurrentUniverSheetInstance();
const worksheet = workbook.getActiveSheet();
@@ -42,13 +47,10 @@ export const DeltaColumnWidthCommand: ICommand<IDeltaColumnWidthCommandParams> =
const destColumnWidth = anchorColWidth + deltaX;
const colSelections = selections.filter((s) => s.range.rangeType === RANGE_TYPE.COLUMN);
- const rangeType = colSelections.some((s) => {
- const r = s.range;
- if (r.startColumn <= anchorCol && anchorCol <= r.endColumn) {
- return true;
- }
+ const rangeType = colSelections.some(({ range }) => {
+ const { startColumn, endColumn } = range;
- return false;
+ return startColumn <= anchorCol && anchorCol <= endColumn;
})
? RANGE_TYPE.COLUMN
: RANGE_TYPE.NORMAL;
@@ -76,23 +78,38 @@ export const DeltaColumnWidthCommand: ICommand<IDeltaColumnWidthCommandParams> =
],
};
}
+
const undoMutationParams: ISetWorksheetColWidthMutationParams = SetWorksheetColWidthMutationFactory(
accessor,
redoMutationParams
);
- const commandService = accessor.get(ICommandService);
- const undoRedoService = accessor.get(IUndoRedoService);
- const result = commandService.executeCommand(SetWorksheetColWidthMutation.id, redoMutationParams);
- if (result) {
+ const setColWidthResult = commandService.executeCommand(SetWorksheetColWidthMutation.id, redoMutationParams);
+
+ const { undos, redos } = accessor.get(SheetInterceptorService).onCommandExecute({
+ id: DeltaColumnWidthCommand.id,
+ params: redoMutationParams,
+ });
+
+ const result = await sequenceExecute([...redos], commandService);
+
+ if (setColWidthResult && result.result) {
undoRedoService.pushUndoRedo({
URI: workbookId,
- undo() {
- return commandService.executeCommand(SetWorksheetColWidthMutation.id, undoMutationParams);
- },
- redo() {
- return commandService.executeCommand(SetWorksheetColWidthMutation.id, redoMutationParams);
- },
+ undo: async () =>
+ (
+ await sequenceExecute(
+ [{ id: SetWorksheetColWidthMutation.id, params: undoMutationParams }, ...undos],
+ commandService
+ )
+ ).result,
+ redo: async () =>
+ (
+ await sequenceExecute(
+ [{ id: SetWorksheetColWidthMutation.id, params: redoMutationParams }, ...redos],
+ commandService
+ )
+ ).result,
});
return true;
@@ -121,11 +138,7 @@ export const SetColWidthCommand: ICommand = {
}
const workbookId = univerInstanceService.getCurrentUniverSheetInstance().getUnitId();
- const worksheetId = univerInstanceService
- .getCurrentUniverSheetInstance()
-
- .getActiveSheet()
- .getSheetId();
+ const worksheetId = univerInstanceService.getCurrentUniverSheetInstance().getActiveSheet().getSheetId();
const redoMutationParams: ISetWorksheetColWidthMutationParams = {
worksheetId,
@@ -137,20 +150,37 @@ export const SetColWidthCommand: ICommand = {
accessor,
redoMutationParams
);
- const result = commandService.executeCommand(SetWorksheetColWidthMutation.id, redoMutationParams);
- if (result) {
+ const setColWidthResult = commandService.executeCommand(SetWorksheetColWidthMutation.id, redoMutationParams);
+
+ const { undos, redos } = accessor.get(SheetInterceptorService).onCommandExecute({
+ id: SetColWidthCommand.id,
+ params: redoMutationParams,
+ });
+
+ const result = await sequenceExecute([...redos], commandService);
+
+ if (setColWidthResult && result.result) {
undoRedoService.pushUndoRedo({
URI: workbookId,
- undo() {
- return commandService.executeCommand(SetWorksheetColWidthMutation.id, undoMutationParams);
- },
- redo() {
- return commandService.executeCommand(SetWorksheetColWidthMutation.id, redoMutationParams);
- },
+ undo: async () =>
+ (
+ await sequenceExecute(
+ [{ id: SetWorksheetColWidthMutation.id, params: undoMutationParams }, ...undos],
+ commandService
+ )
+ ).result,
+ redo: async () =>
+ (
+ await sequenceExecute(
+ [{ id: SetWorksheetColWidthMutation.id, params: redoMutationParams }, ...redos],
+ commandService
+ )
+ ).result,
});
return true;
}
+
return false;
},
};
diff --git a/packages/base-sheets/src/commands/mutations/set-worksheet-col-width.mutation.ts b/packages/base-sheets/src/commands/mutations/set-worksheet-col-width.mutation.ts
index 1476b6b674..8b137a0022 100644
--- a/packages/base-sheets/src/commands/mutations/set-worksheet-col-width.mutation.ts
+++ b/packages/base-sheets/src/commands/mutations/set-worksheet-col-width.mutation.ts
@@ -54,10 +54,14 @@ export const SetWorksheetColWidthMutation: IMutation<ISetWorksheetColWidthMutati
}
const worksheet = universheet.getSheetBySheetId(params.worksheetId);
- if (!worksheet) return false;
+ if (!worksheet) {
+ return false;
+ }
+
const defaultColumnWidth = worksheet.getConfig().defaultColumnWidth;
const manager = worksheet.getColumnManager();
const ranges = params.ranges;
+
for (let i = 0; i < ranges.length; i++) {
const range = ranges[i];
for (let j = range.startColumn; j < range.endColumn + 1; j++) {