Skip to content

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

fix(sheets): validate dimensions and restore zero-sized rows and columns (#7960)

wpxp12345695b35c605cd3
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 298c2898e0..7f4a9ab3ac 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -182,6 +182,7 @@ export { cssPxToEmu, EMU_PER_CSS_PX, emuToCssPx } from './shared/units';
export * from './sheets';
export type { IWorkbookCalculationSettings } from './sheets/calculation-settings';
export { MAX_ITERATION_COUNT, normalizeWorkbookCalculationSettings } from './sheets/calculation-settings';
+export { isValidColumnDimensions, isValidRowDimensions, isValidSheetDimension } from './sheets/sheet-dimensions';
export { Skeleton } from './skeleton';
export * from './types/const';
export { skipParseTagNames } from './types/const/clipboard';
diff --git a/packages/core/src/sheets/__tests__/sheet-skeleton.spec.ts b/packages/core/src/sheets/__tests__/sheet-skeleton.spec.ts
new file mode 100644
index 0000000000..5527c7c8dd
--- /dev/null
+++ b/packages/core/src/sheets/__tests__/sheet-skeleton.spec.ts
@@ -0,0 +1,112 @@
+/**
+ * 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 { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { LocaleService } from '../../services/locale/locale.service';
+import { BooleanNumber } from '../../types/enum';
+import { LocaleType } from '../../types/enum/locale-type';
+import { SheetSkeleton } from '../sheet-skeleton';
+import { createCoreTestBed } from './create-core-test-bed';
+
+describe('SheetSkeleton dimension fallback', () => {
+ let testBed: ReturnType<typeof createCoreTestBed>;
+
+ beforeEach(() => {
+ testBed = createCoreTestBed();
+ const localeService = testBed.get(LocaleService);
+ localeService.load({ [LocaleType.EN_US]: {} });
+ localeService.setLocale(LocaleType.EN_US);
+ localeService.setDirection('ltr');
+ });
+
+ afterEach(() => testBed.univer.dispose());
+
+ it.each([-232.90908628521544, Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, '88', null])(
+ 'collapses invalid dimensions %s while keeping subsequent cells visible and hit-testable',
+ (value) => {
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const config = worksheet.getConfig();
+ config.columnCount = 4;
+ config.rowCount = 3;
+ config.columnData[0] = { w: value as number };
+ config.columnData[1] = { w: 114.3671875 };
+ config.rowData[0] = { h: value as number, ah: Number.POSITIVE_INFINITY };
+ config.rowData[1] = { h: 30.5, ah: Number.NaN };
+ const injector = testBed.univer.__getInjector();
+ const createSkeleton = () => injector.createInstance(SheetSkeleton, worksheet, testBed.sheet.getStyles());
+ injector.add([SheetSkeleton, { useFactory: createSkeleton }]);
+ const skeleton = injector.get(SheetSkeleton);
+ try {
+ skeleton.calculate();
+ expect(skeleton.columnWidthAccumulation).toEqual([0, 114.3671875, 202.3671875, 290.3671875]);
+ expect(skeleton.columnTotalWidth).toBe(290.3671875);
+ expect(skeleton.rowHeightAccumulation).toEqual([0, 30.5, 54.5]);
+ for (let column = 1; column < 4; column++) {
+ const cell = skeleton.getNoMergeCellWithCoordByIndex(0, column, false);
+ expect(cell.endX - cell.startX).toBe(worksheet.getColumnWidth(column));
+ expect(skeleton.getColumnIndexByOffsetX((cell.startX + cell.endX) / 2 + skeleton.rowHeaderWidth, 1, { x: 0, y: 0 })).toBe(column);
+ }
+ expect(worksheet.getColumnWidth(0)).toBe(0);
+ expect(worksheet.getRowHeight(0)).toBe(0);
+ expect(worksheet.getRowHeight(1)).toBe(30.5);
+ } finally {
+ skeleton.dispose();
+ }
+ }
+ );
+
+ it('preserves zero and hidden dimensions while ignoring invalid auto heights', () => {
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const config = worksheet.getConfig();
+ config.columnCount = 4;
+ config.rowCount = 6;
+ config.defaultColumnWidth = Number.NaN;
+ config.defaultRowHeight = -1;
+ config.columnData[0] = { w: 0 };
+ config.columnData[1] = { w: -1, hd: BooleanNumber.TRUE };
+ config.columnData[3] = {};
+ config.rowData[0] = { h: 0 };
+ config.rowData[1] = { h: -1, hd: BooleanNumber.TRUE };
+ config.rowData[2] = { h: 30.5, ah: 0 };
+ config.rowData[3] = { h: 20, ah: 40.5 };
+ config.rowData[4] = { h: -1 };
+ config.rowData[5] = {};
+ const injector = testBed.univer.__getInjector();
+ const createSkeleton = () => injector.createInstance(SheetSkeleton, worksheet, testBed.sheet.getStyles());
+ injector.add([SheetSkeleton, { useFactory: createSkeleton }]);
+ const skeleton = injector.get(SheetSkeleton);
+ worksheet.__interceptViewModel((viewModel) => {
+ skeleton.disposeWithMe(viewModel.registerRowFilteredInterceptor({ getRowFiltered: (row) => row === 4 }));
+ });
+ try {
+ skeleton.calculate();
+ expect(skeleton.columnWidthAccumulation).toEqual([0, 0, 88, 176]);
+ expect(skeleton.rowHeightAccumulation).toEqual([0, 0, 30.5, 71, 71, 95]);
+ expect(worksheet.getColumnWidth(3)).toBe(88);
+ expect(worksheet.getRowHeight(5)).toBe(24);
+ expect(worksheet.getRowHeight(4)).toBe(0);
+ expect(worksheet.getColumnWidth(2)).toBe(88);
+ expect(worksheet.getRowHeight(2)).toBe(30.5);
+ expect(worksheet.getRowHeight(3)).toBe(40.5);
+ worksheet.getColumnManager().setColumnWidth(2, Number.NaN);
+ worksheet.getRowManager().setRowHeight(2, -1);
+ expect(worksheet.getColumnWidth(2)).toBe(88);
+ expect(worksheet.getRowHeight(2)).toBe(30.5);
+ } finally {
+ skeleton.dispose();
+ }
+ });
+});
diff --git a/packages/core/src/sheets/__tests__/sheet-snapshot-utils.spec.ts b/packages/core/src/sheets/__tests__/sheet-snapshot-utils.spec.ts
new file mode 100644
index 0000000000..5d38891396
--- /dev/null
+++ b/packages/core/src/sheets/__tests__/sheet-snapshot-utils.spec.ts
@@ -0,0 +1,105 @@
+/**
+ * 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 { describe, expect, it } from 'vitest';
+import type { IWorksheetData } from '../typedef';
+import { BooleanNumber } from '../../types/enum';
+import {
+ DEFAULT_WORKSHEET_COLUMN_WIDTH,
+ DEFAULT_WORKSHEET_ROW_HEIGHT,
+ mergeWorksheetSnapshotWithDefault,
+} from '../sheet-snapshot-utils';
+import { createCoreTestBed } from './create-core-test-bed';
+
+describe('worksheet dimension normalization', () => {
+ it.each([-232.90908628521544, Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, '88', null])(
+ 'repairs invalid dimensions %s without losing column or row metadata',
+ (value) => {
+ const snapshot = mergeWorksheetSnapshotWithDefault({
+ defaultColumnWidth: 90.5,
+ defaultRowHeight: 25.5,
+ columnData: { 0: { w: value as number, hd: BooleanNumber.TRUE, s: 'column-style' } },
+ rowData: { 0: { h: value as number, ah: value as number, ia: BooleanNumber.TRUE, s: 'row-style' } },
+ });
+ expect(snapshot.columnData[0]).toEqual({ w: 0, hd: BooleanNumber.TRUE, s: 'column-style' });
+ expect(snapshot.rowData[0]).toEqual({ h: 0, ia: BooleanNumber.TRUE, s: 'row-style' });
+ }
+ );
+
+ it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY, '24', null])(
+ 'uses built-in defaults when worksheet defaults are invalid: %s',
+ (value) => {
+ const snapshot = mergeWorksheetSnapshotWithDefault({
+ defaultColumnWidth: value as number,
+ defaultRowHeight: value as number,
+ columnData: { 0: { w: -1 } },
+ rowData: { 0: { h: -1 } },
+ });
+ expect(snapshot.defaultColumnWidth).toBe(DEFAULT_WORKSHEET_COLUMN_WIDTH);
+ expect(snapshot.defaultRowHeight).toBe(DEFAULT_WORKSHEET_ROW_HEIGHT);
+ expect(snapshot.columnData[0].w).toBe(0);
+ expect(snapshot.rowData[0].h).toBe(0);
+ }
+ );
+
+ it('preserves zero sizes, fractional sizes, hidden state and sparse data', () => {
+ const snapshot = mergeWorksheetSnapshotWithDefault({
+ columnData: { 0: { w: 0 }, 100: { w: 114.3671875, hd: BooleanNumber.TRUE } },
+ rowData: { 0: { h: 0, ah: 0 }, 100: { h: 25.5, ah: 32.5 } },
+ });
+ expect(snapshot.columnData).toEqual({ 0: { w: 0 }, 100: { w: 114.3671875, hd: BooleanNumber.TRUE } });
+ expect(snapshot.rowData).toEqual({ 0: { h: 0, ah: 0 }, 100: { h: 25.5, ah: 32.5 } });
+ });
+
+ it('uses worksheet defaults for missing dimensions instead of collapsing the row or column', () => {
+ const testBed = createCoreTestBed();
+ try {
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const config = worksheet.getConfig();
+ config.defaultColumnWidth = 90.5;
+ config.defaultRowHeight = 25.5;
+ config.columnData[0] = { s: 'column-style' };
+ config.rowData[0] = { ah: 0, s: 'row-style' };
+ expect(worksheet.getColumnWidth(0)).toBe(90.5);
+ expect(worksheet.getRowHeight(0)).toBe(25.5);
+ expect(worksheet.getColumnWidth(2)).toBe(90.5);
+ expect(worksheet.getRowHeight(2)).toBe(25.5);
+ } finally {
+ testBed.univer.dispose();
+ }
+ });
+
+ it('persists repaired dimensions through save and reload without changing cell data', () => {
+ const testBed = createCoreTestBed();
+ let reloaded: ReturnType<typeof createCoreTestBed> | undefined;
+ try {
+ const snapshot = testBed.sheet.save();
+ const sheetId = testBed.sheet.getActiveSheet()!.getSheetId();
+ const sheet = snapshot.sheets[sheetId] as IWorksheetData;
+ sheet.columnData = { 0: { w: -232.90908628521544 }, 1: { w: 114.3671875 } };
+ sheet.rowData = { 0: { h: -5, ah: Number.POSITIVE_INFINITY } };
+ reloaded = createCoreTestBed(snapshot);
+ const saved = reloaded.sheet.save();
+ expect(saved.sheets[sheetId].columnData?.[0].w).toBe(0);
+ expect(saved.sheets[sheetId].rowData?.[0]).toEqual({ h: 0 });
+ expect(saved.sheets[sheetId].cellData).toEqual(sheet.cellData);
+ expect(mergeWorksheetSnapshotWithDefault(saved.sheets[sheetId])).toEqual(saved.sheets[sheetId]);
+ } finally {
+ reloaded?.univer.dispose();
+ testBed.univer.dispose();
+ }
+ });
+});
diff --git a/packages/core/src/sheets/column-manager.ts b/packages/core/src/sheets/column-manager.ts
index d3425c9640..98185bdbc1 100644
--- a/packages/core/src/sheets/column-manager.ts
+++ b/packages/core/src/sheets/column-manager.ts
@@ -20,6 +20,8 @@ import type { IStyleData } from '../types/interfaces';
import type { CustomData, IColumnData, IRange, IWorksheetData } from './typedef';
import { getArrayLength } from '../shared/object-matrix';
import { BooleanNumber } from '../types/enum';
+import { isValidSheetDimension, normalizeSheetDimension } from './sheet-dimensions';
+import { DEFAULT_WORKSHEET_COLUMN_WIDTH } from './sheet-snapshot-utils';
import { RANGE_TYPE } from './typedef';
/**
@@ -183,7 +185,9 @@ export class ColumnManager {
* @returns {number} width of column
*/
getColumnWidth(columnPos: number): number {
- return this._columnData[columnPos]?.w ?? this._config.defaultColumnWidth;
+ const defaultWidth = normalizeSheetDimension(this._config.defaultColumnWidth, DEFAULT_WORKSHEET_COLUMN_WIDTH, false);
+ const width = this._columnData[columnPos]?.w;
+ return width === undefined ? defaultWidth : normalizeSheetDimension(width, 0);
}
/**
@@ -192,6 +196,9 @@ export class ColumnManager {
* @param width width of column
*/
setColumnWidth(columnPos: number, width: number) {
+ if (!isValidSheetDimension(width)) {
+ return;
+ }
const column = this._columnData[columnPos];
// To prevent data redundancy, we only set the width when it is different from the default column width.
@@ -241,6 +248,9 @@ export class ColumnManager {
const columnData = columnDataInfo?.[c - startColumn];
if (columnData !== undefined && columnData !== null && Object.keys(columnData).length > 0) {
this._columnData[c] = { ...columnData };
+ if (columnData.w !== undefined && !isValidSheetDimension(columnData.w)) {
+ this._columnData[c].w = 0;
+ }
}
}
}
diff --git a/packages/core/src/sheets/row-manager.ts b/packages/core/src/sheets/row-manager.ts
index 42b616ca87..12aba23daf 100644
--- a/packages/core/src/sheets/row-manager.ts
+++ b/packages/core/src/sheets/row-manager.ts
@@ -21,6 +21,8 @@ import type { CustomData, IRange, IRowData, IWorksheetData } from './typedef';
import type { SheetViewModel } from './view-model';
import { getArrayLength } from '../shared/object-matrix';
import { BooleanNumber } from '../types/enum';
+import { isValidSheetDimension, normalizeSheetDimension } from './sheet-dimensions';
+import { DEFAULT_WORKSHEET_ROW_HEIGHT } from './sheet-snapshot-utils';
import { RANGE_TYPE } from './typedef';
const MAXIMUM_ROW_HEIGHT = 2000;
@@ -85,16 +87,19 @@ export class RowManager {
getRowHeight(rowPos: number, count: number = 1): number {
const { _rowData } = this;
const config = this._config;
+ const defaultHeight = normalizeSheetDimension(config.defaultRowHeight, DEFAULT_WORKSHEET_ROW_HEIGHT, false);
let height: number = 0;
for (let i = 0; i < count; i++) {
const row = _rowData[i + rowPos] || {
hd: BooleanNumber.FALSE,
- h: config.defaultRowHeight,
+ h: defaultHeight,
};
- const { ia, ah, h = config.defaultRowHeight } = row;
+ const { ia, ah, h = defaultHeight } = row;
- height += (ia == null || ia === BooleanNumber.TRUE) && typeof ah === 'number' ? ah : h;
+ height += (ia == null || ia === BooleanNumber.TRUE) && isValidSheetDimension(ah, false)
+ ? ah
+ : normalizeSheetDimension(h, 0);
}
return height;
@@ -106,6 +111,9 @@ export class RowManager {
* @param height row height
*/
setRowHeight(rowPos: number, height: number) {
+ if (!isValidSheetDimension(height)) {
+ return;
+ }
const row = this._rowData[rowPos];
// To prevent data redundancy, we only set the height when it is different from the default row height.
@@ -157,6 +165,13 @@ export class RowManager {
const rowData = rowDataInfo?.[r - startRow];
if (rowData !== undefined && rowData !== null && Object.keys(rowData).length > 0) {
this._rowData[r] = { ...rowData };
+ const row = this._rowData[r];
+ if (row.h !== undefined && !isValidSheetDimension(row.h)) {
+ row.h = 0;
+ }
+ if (row.ah !== undefined && !isValidSheetDimension(row.ah)) {
+ delete row.ah;
+ }
}
}
}
diff --git a/packages/core/src/sheets/sheet-dimensions.ts b/packages/core/src/sheets/sheet-dimensions.ts
new file mode 100644
index 0000000000..bf1dc3edbb
--- /dev/null
+++ b/packages/core/src/sheets/sheet-dimensions.ts
@@ -0,0 +1,35 @@
+/**
+ * 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 { Nullable } from '../shared/types';
+import type { IColumnData, IRowData } from './typedef';
+
+export function isValidSheetDimension(value: unknown, allowZero = true): value is number {
+ return typeof value === 'number' && Number.isFinite(value) && (allowZero ? value >= 0 : value > 0);
+}
+
+export function normalizeSheetDimension(value: unknown, fallback: number, allowZero = true): number {
+ return isValidSheetDimension(value, allowZero) ? value : fallback;
+}
+
+export function isValidColumnDimensions(data: Nullable<Partial<IColumnData>>): boolean {
+ return data?.w == null || isValidSheetDimension(data.w);
+}
+
+export function isValidRowDimensions(data: Nullable<Partial<IRowData>>): boolean {
+ return (data?.h == null || isValidSheetDimension(data.h)) &&
+ (data?.ah == null || isValidSheetDimension(data.ah));
+}
diff --git a/packages/core/src/sheets/sheet-skeleton.ts b/packages/core/src/sheets/sheet-skeleton.ts
index 3da951b210..27f7e2d224 100644
--- a/packages/core/src/sheets/sheet-skeleton.ts
+++ b/packages/core/src/sheets/sheet-skeleton.ts
@@ -48,6 +48,8 @@ import { getIntersectRange } from '../shared/range';
import { Skeleton } from '../skeleton';
import { BooleanNumber, HorizontalAlign } from '../types/enum';
import { DocumentFlavor } from '../types/interfaces';
+import { isValidSheetDimension, normalizeSheetDimension } from './sheet-dimensions';
+import { DEFAULT_WORKSHEET_COLUMN_WIDTH, DEFAULT_WORKSHEET_ROW_HEIGHT } from './sheet-snapshot-utils';
/**
* Configuration for a single gap (visual separator between rows or columns).
@@ -402,9 +404,10 @@ export class SheetSkeleton extends Skeleton {
): { rowTotalHeight: number; rowHeightAccumulation: number[] } {
let rowTotalHeight = 0;
const rowHeightAccumulation: number[] = [];
+ const fallbackHeight = normalizeSheetDimension(defaultRowHeight, DEFAULT_WORKSHEET_ROW_HEIGHT, false);
const data = rowData;
for (let r = 0; r < rowCount; r++) {
- let rowHeight = defaultRowHeight;
+ let rowHeight = fallbackHeight;
if (this.worksheet.getRowFiltered(r)) {
rowHeight = 0;
@@ -414,14 +417,14 @@ export class SheetSkeleton extends Skeleton {
continue;
}
- const { h = defaultRowHeight, ah, ia } = rowDataItem;
+ const { h = fallbackHeight, ah, ia } = rowDataItem;
if (
(ia == null || ia === BooleanNumber.TRUE) &&
- typeof ah === 'number' && ah > 0
+ isValidSheetDimension(ah, false)
) {
rowHeight = ah;
} else {
- rowHeight = h;
+ rowHeight = normalizeSheetDimension(h, 0);
}
if (rowDataItem.hd === BooleanNumber.TRUE) {
@@ -454,11 +457,12 @@ export class SheetSkeleton extends Skeleton {
): { columnTotalWidth: number; columnWidthAccumulation: number[] } {
let columnTotalWidth = 0;
const columnWidthAccumulation: number[] = [];
+ const fallbackWidth = normalizeSheetDimension(defaultColumnWidth, DEFAULT_WORKSHEET_COLUMN_WIDTH, false);
const data = columnData;
for (let c = 0; c < colCount; c++) {
- let columnWidth = defaultColumnWidth;
+ let columnWidth = fallbackWidth;
if (data[c] != null) {
const columnDataItem = data[c];
@@ -466,8 +470,8 @@ export class SheetSkeleton extends Skeleton {
if (!columnDataItem) {
continue;
}
- if (columnDataItem.w != null) {
- columnWidth = columnDataItem.w;
+ if (columnDataItem.w !== undefined) {
+ columnWidth = normalizeSheetDimension(columnDataItem.w, 0);
}
if (columnDataItem.hd === BooleanNumber.TRUE) {
diff --git a/packages/core/src/sheets/sheet-snapshot-utils.ts b/packages/core/src/sheets/sheet-snapshot-utils.ts
index 235b21e84b..84b9029312 100644
--- a/packages/core/src/sheets/sheet-snapshot-utils.ts
+++ b/packages/core/src/sheets/sheet-snapshot-utils.ts
@@ -16,6 +16,7 @@
import type { IWorksheetData } from './typedef';
import { BooleanNumber } from '../types/enum/text-style';
+import { isValidSheetDimension, normalizeSheetDimension } from './sheet-dimensions';
// TODO@wzhudev: default value should not be exposed, but the keys.
@@ -94,5 +95,26 @@ export function mergeWorksheetSnapshotWithDefault(snapshot: Partial<IWorksheetDa
freeze.startRow = freeze.ySplit === 0 ? defaultSnapshot.freeze.startRow : (freeze.startRow ?? defaultSnapshot.freeze.startRow);
freeze.startColumn = freeze.xSplit === 0 ? defaultSnapshot.freeze.startColumn : (freeze.startColumn ?? defaultSnapshot.freeze.startColumn);
+ snapshot.defaultColumnWidth = normalizeSheetDimension(snapshot.defaultColumnWidth, DEFAULT_WORKSHEET_COLUMN_WIDTH, false);
+ snapshot.defaultRowHeight = normalizeSheetDimension(snapshot.defaultRowHeight, DEFAULT_WORKSHEET_ROW_HEIGHT, false);
+
+ for (const column of Object.values(snapshot.columnData!)) {
+ if (column && column.w !== undefined && !isValidSheetDimension(column.w)) {
+ column.w = 0;
+ }
+ }
+
+ for (const row of Object.values(snapshot.rowData!)) {
+ if (!row) {
+ continue;
+ }
+ if (row.h !== undefined && !isValidSheetDimension(row.h)) {
+ row.h = 0;
+ }
+ if (row.ah !== undefined && !isValidSheetDimension(row.ah)) {
+ delete row.ah;
+ }
+ }
+
return snapshot as IWorksheetData;
}
diff --git a/packages/sheets-ui/src/controllers/render-controllers/__tests__/header-resize.render-controller.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/__tests__/header-resize.render-controller.spec.ts
index a85ccb3d75..83298ca12f 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/__tests__/header-resize.render-controller.spec.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/__tests__/header-resize.render-controller.spec.ts
@@ -14,77 +14,154 @@
* limitations under the License.
*/
-import { ICommandService } from '@univerjs/core';
-import { DeltaRowHeightCommand } from '@univerjs/sheets';
-import { describe, expect, it, vi } from 'vitest';
+import type { IMouseEvent } from '@univerjs/engine-render';
+import { BooleanNumber, ICommandService, RANGE_TYPE, RedoCommand, UndoCommand } from '@univerjs/core';
+import {
+ DeltaColumnWidthCommand,
+ DeltaRowHeightCommand,
+ SetWorksheetColWidthMutation,
+ SetWorksheetRowHeightMutation,
+ SetWorksheetRowIsAutoHeightMutation,
+ SheetSkeletonService,
+ SheetsSelectionsService,
+} from '@univerjs/sheets';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import type { HeaderMenuResizeShape } from '../../../views/header-resize-shape';
+import type { ITestEvent } from './render-test-bed';
import { SHEET_VIEW_KEY } from '../../../common/keys';
import { HeaderResizeRenderController } from '../header-resize.render-controller';
import { createRenderTestBed } from './render-test-bed';
describe('HeaderResizeRenderController', () => {
- it('resizes row by dragging the resize handle and triggers DeltaRowHeightCommand', () => {
- const testBed = createRenderTestBed();
- const { context, injector } = testBed;
+ let testBed: ReturnType<typeof createRenderTestBed>;
+ const cleanups: Array<() => void> = [];
+ beforeEach(() => {
+ testBed = createRenderTestBed({ dependencies: [[SheetSkeletonService]] });
+ cleanups.push(() => testBed.univer.dispose());
+ const { context, injector, sheet } = testBed;
+ const worksheet = sheet.getActiveSheet()!;
+ worksheet.getRowManager().setRowHeight(0, 20);
+ worksheet.getColumnManager().setColumnWidth(0, 100);
const commandService = injector.get(ICommandService);
- const executeSpy = vi.spyOn(commandService, 'executeCommand').mockResolvedValue(true as any);
+ for (const command of [
+ DeltaColumnWidthCommand,
+ DeltaRowHeightCommand,
+ SetWorksheetColWidthMutation,
+ SetWorksheetRowHeightMutation,
+ SetWorksheetRowIsAutoHeightMutation,
+ ]) {
+ commandService.registerCommand(command);
+ }
+ injector.get(SheetsSelectionsService).setSelections([{
+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ }]);
+ const createController = () => injector.createInstance(HeaderResizeRenderController, context);
+ injector.add([HeaderResizeRenderController, { useFactory: createController }]);
+ });
+
+ afterEach(() => {
+ for (const cleanup of cleanups.splice(0).reverse()) {
+ cleanup();
+ }
+ });
- const controller = injector.createInstance(HeaderResizeRenderController, context as any);
+ it('updates row height by dragging the resize handle', () => {
+ const { context, injector, scene, sheet } = testBed;
+
+ const controller = injector.get(HeaderResizeRenderController);
+ cleanups.push(() => controller.dispose());
controller.interceptor.intercept(controller.interceptor.getInterceptPoints().HEADER_RESIZE_PERMISSION_CHECK, {
handler: () => true,
});
// Hover near the bottom edge of the first row to show the row resize handle.
- const rowHeader = context.components.get(SHEET_VIEW_KEY.ROW) as any;
+ const rowHeader = context.components.get(SHEET_VIEW_KEY.ROW) as unknown as {
+ onPointerMove$: ITestEvent<Partial<IMouseEvent>, object>;
+ };
rowHeader.onPointerMove$.emit({ offsetX: 10, offsetY: 19, button: 0 }, {});
- const rowResizeRect = (controller as any)._rowResizeRect;
+ const rowResizeRect = (controller as unknown as { _rowResizeRect: HeaderMenuResizeShape })._rowResizeRect;
// Start dragging the resize handle downward.
- rowResizeRect.onPointerDown$.emitEvent({ offsetX: 10, offsetY: 19, button: 0 } as any);
- (context.scene as any).onPointerMove$.emit({ offsetX: 10, offsetY: 35, button: 0 }, {});
- (context.scene as any).onPointerUp$.emit({ offsetX: 10, offsetY: 35, button: 0 }, {});
+ rowResizeRect.onPointerDown$.emitEvent({ offsetX: 10, offsetY: 19, button: 0 } as IMouseEvent);
+ scene.onPointerMove$.emit({ offsetX: 10, offsetY: 35, button: 0 }, { stopPropagation: () => undefined });
+ scene.onPointerUp$.emit({ offsetX: 10, offsetY: 35, button: 0 }, { stopPropagation: () => undefined });
- expect(executeSpy).toHaveBeenCalledWith(
- DeltaRowHeightCommand.id,
- expect.objectContaining({
- anchorRow: expect.any(Number),
- deltaY: expect.any(Number),
- })
- );
+ expect(sheet.getActiveSheet()!.getRowHeight(0)).toBeGreaterThan(20);
+ });
- testBed.univer.dispose();
+ it.each([RANGE_TYPE.ROW, RANGE_TYPE.COLUMN])('clamps dragging %s past the start to zero with undo and redo', async (rangeType) => {
+ const { context, injector, scene, sheet } = testBed;
+ const worksheet = sheet.getActiveSheet()!;
+ const commandService = injector.get(ICommandService);
+ const controller = injector.get(HeaderResizeRenderController);
+ cleanups.push(() => controller.dispose());
+ controller.interceptor.intercept(controller.interceptor.getInterceptPoints().HEADER_RESIZE_PERMISSION_CHECK, {
+ handler: () => true,
+ });
+ const isRow = rangeType === RANGE_TYPE.ROW;
+ const header = context.components.get(isRow ? SHEET_VIEW_KEY.ROW : SHEET_VIEW_KEY.COLUMN) as unknown as {
+ onPointerMove$: ITestEvent<Partial<IMouseEvent>, object>;
+ };
+ const start = isRow ? { offsetX: 10, offsetY: 19, button: 0 } : { offsetX: 99, offsetY: 10, button: 0 };
+ header.onPointerMove$.emit(start, {});
+ const shapes = controller as unknown as {
+ _rowResizeRect: HeaderMenuResizeShape;
+ _columnResizeRect: HeaderMenuResizeShape;
+ };
+ const shape = isRow ? shapes._rowResizeRect : shapes._columnResizeRect;
+ shape.onPointerDown$.emitEvent(start as IMouseEvent);
+ const end = isRow ? { offsetX: 10, offsetY: -100, button: 0 } : { offsetX: -100, offsetY: 10, button: 0 };
+ scene.onPointerMove$.emit(end, { stopPropagation: () => undefined });
+ scene.onPointerUp$.emit(end, { stopPropagation: () => undefined });
+ const getSize = () => isRow ? worksheet.getRowHeight(0) : worksheet.getColumnWidth(0);
+ expect(getSize()).toBe(0);
+ expect(isRow ? worksheet.getRowVisible(0) : worksheet.getColVisible(0)).toBe(true);
+ if (isRow) {
+ expect(worksheet.getRowManager().getRow(0)?.ia).toBe(BooleanNumber.FALSE);
+ }
+ await commandService.executeCommand(UndoCommand.id);
+ expect(getSize()).toBe(isRow ? 20 : 100);
+ await commandService.executeCommand(RedoCommand.id);
+ expect(getSize()).toBe(0);
});
it('positions resize handles in the base header area when outline uses margins', () => {
- const testBed = createRenderTestBed();
const { context, injector, skeleton } = testBed;
skeleton.rowHeaderWidth = 46;
skeleton.columnHeaderHeight = 20;
skeleton.rowHeaderWidthAndMarginLeft = 86;
skeleton.columnHeaderHeightAndMarginTop = 60;
- (skeleton.worksheet as any).getConfig = () => ({
- rowHeader: { width: 46 },
- columnHeader: { height: 20 },
+ Object.assign(skeleton.worksheet, {
+ getConfig: () => ({
+ rowHeader: { width: 46 },
+ columnHeader: { height: 20 },
+ }),
});
- const controller = injector.createInstance(HeaderResizeRenderController, context as any);
+ const controller = injector.get(HeaderResizeRenderController);
+ cleanups.push(() => controller.dispose());
controller.interceptor.intercept(controller.interceptor.getInterceptPoints().HEADER_RESIZE_PERMISSION_CHECK, {
handler: () => true,
});
- const rowHeader = context.components.get(SHEET_VIEW_KEY.ROW) as any;
+ const rowHeader = context.components.get(SHEET_VIEW_KEY.ROW) as unknown as {
+ onPointerMove$: ITestEvent<Partial<IMouseEvent>, object>;
+ };
rowHeader.onPointerMove$.emit({ offsetX: 70, offsetY: 19, button: 0 }, {});
- const rowResizeRect = (controller as any)._rowResizeRect;
+ const rowResizeRect = (controller as unknown as { _rowResizeRect: HeaderMenuResizeShape })._rowResizeRect;
expect(rowResizeRect.left).toBeCloseTo(40 + 46 / 2 - (46 / 3) / 2);
expect(rowResizeRect.size).toBeCloseTo(46 / 3);
- const columnHeader = context.components.get(SHEET_VIEW_KEY.COLUMN) as any;
+ const columnHeader = context.components.get(SHEET_VIEW_KEY.COLUMN) as unknown as {
+ onPointerMove$: ITestEvent<Partial<IMouseEvent>, object>;
+ };
columnHeader.onPointerMove$.emit({ offsetX: 99, offsetY: 52, button: 0 }, {});
- const columnResizeRect = (controller as any)._columnResizeRect;
+ const columnResizeRect = (controller as unknown as { _columnResizeRect: HeaderMenuResizeShape })._columnResizeRect;
expect(columnResizeRect.top).toBeCloseTo(40 + 20 / 2 - (20 * 0.7) / 2);
expect(columnResizeRect.size).toBeCloseTo(20 * 0.7);
-
- testBed.univer.dispose();
});
});
diff --git a/packages/sheets-ui/src/controllers/render-controllers/__tests__/header-unhide.render-controller.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/__tests__/header-unhide.render-controller.spec.ts
index a6e143e1c8..2f70873ca9 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/__tests__/header-unhide.render-controller.spec.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/__tests__/header-unhide.render-controller.spec.ts
@@ -14,27 +14,42 @@
* limitations under the License.
*/
-import { describe, expect, it, vi } from 'vitest';
+import { BooleanNumber, LocaleService, LocaleType } from '@univerjs/core';
+import { afterEach, describe, expect, it } from 'vitest';
+import type { HeaderUnhideShape } from '../../../views/header-unhide-shape';
import { HeaderUnhideRangeAxis, HeaderUnhideRangeService } from '../../../services/header-unhide-range.service';
import { HeaderUnhideRenderController } from '../header-unhide.render-controller';
import { createRenderTestBed } from './render-test-bed';
describe('HeaderUnhideRenderController', () => {
+ const cleanups: Array<() => void> = [];
+ afterEach(() => {
+ for (const cleanup of cleanups.splice(0).reverse()) {
+ cleanup();
+ }
+ });
+
it('filters hidden row ranges and keeps hidden column icons at the bottom of expanded column headers', () => {
const testBed = createRenderTestBed();
+ cleanups.push(() => testBed.univer.dispose());
+ testBed.get(LocaleService).setDirection('ltr');
+ testBed.get(LocaleService).setLocale(LocaleType.EN_US);
const { context, injector, sheet, sheetSkeletonManagerService, skeleton } = testBed;
const worksheet = sheet.getActiveSheet()!;
skeleton.columnHeaderHeight = 60;
- vi.spyOn(worksheet, 'getHiddenRows').mockReturnValue([
- { startRow: 5, endRow: 5, startColumn: 0, endColumn: 0 },
- { startRow: 8, endRow: 8, startColumn: 0, endColumn: 0 },
- ]);
- vi.spyOn(worksheet, 'getHiddenCols').mockReturnValue([
- { startColumn: 6, endColumn: 6, startRow: 0, endRow: 0 },
- ]);
-
- const controller = injector.createInstance(HeaderUnhideRenderController, context as any);
+ for (let row = 5; row <= 5; row++) {
+ worksheet.getRowManager().getRowOrCreate(row).hd = BooleanNumber.TRUE;
+ }
+ for (let row = 8; row <= 8; row++) {
+ worksheet.getRowManager().getRowOrCreate(row).hd = BooleanNumber.TRUE;
+ }
+ worksheet.getColumnManager().getColumnOrCreate(6).hd = BooleanNumber.TRUE;
+
+ const createController = () => injector.createInstance(HeaderUnhideRenderController, context);
+ injector.add([HeaderUnhideRenderController, { useFactory: createController }]);
+ const controller = injector.get(HeaderUnhideRenderController);
+ cleanups.push(() => controller.dispose());
controller.interceptor.intercept(controller.interceptor.getInterceptPoints().HEADER_UNHIDE_RANGE_VISIBLE_CHECK, {
handler: (_visible, range) => range.axis !== HeaderUnhideRangeAxis.ROW || range.range.startRow !== 5,
});
@@ -44,67 +59,180 @@ describe('HeaderUnhideRenderController', () => {
sheetId: worksheet.getSheetId(),
});
- const shapes = (controller as any)._shapes;
+ const shapes = (controller as unknown as { _shapes: { rows: HeaderUnhideShape[]; cols: HeaderUnhideShape[] } })._shapes;
expect(shapes.rows).toHaveLength(1);
expect(shapes.cols).toHaveLength(1);
expect(shapes.cols[0].top).toBe(60 - 12);
-
- testBed.univer.dispose();
});
it('keeps hidden column icons at the bottom of column headers when outline adds top padding', () => {
const testBed = createRenderTestBed();
+ cleanups.push(() => testBed.univer.dispose());
+ testBed.get(LocaleService).setDirection('ltr');
+ testBed.get(LocaleService).setLocale(LocaleType.EN_US);
const { context, injector, sheet, sheetSkeletonManagerService, skeleton } = testBed;
const worksheet = sheet.getActiveSheet()!;
skeleton.columnHeaderHeight = 20;
skeleton.columnHeaderHeightAndMarginTop = 60;
- vi.spyOn(worksheet, 'getHiddenRows').mockReturnValue([]);
- vi.spyOn(worksheet, 'getHiddenCols').mockReturnValue([
- { startColumn: 6, endColumn: 6, startRow: 0, endRow: 0 },
- ]);
- const controller = injector.createInstance(HeaderUnhideRenderController, context as any);
+ worksheet.getColumnManager().getColumnOrCreate(6).hd = BooleanNumber.TRUE;
+
+ const createController = () => injector.createInstance(HeaderUnhideRenderController, context);
+ injector.add([HeaderUnhideRenderController, { useFactory: createController }]);
+ const controller = injector.get(HeaderUnhideRenderController);
+ cleanups.push(() => controller.dispose());
sheetSkeletonManagerService.emitCurrentSkeleton({
unitId: sheet.getUnitId(),
sheetId: worksheet.getSheetId(),
});
- const shapes = (controller as any)._shapes;
+ const shapes = (controller as unknown as { _shapes: { rows: HeaderUnhideShape[]; cols: HeaderUnhideShape[] } })._shapes;
expect(shapes.cols).toHaveLength(1);
expect(shapes.cols[0].top).toBe(60 - 12);
-
- testBed.univer.dispose();
});
it('filters hidden row ranges through the shared unhide range service', () => {
const testBed = createRenderTestBed();
+ cleanups.push(() => testBed.univer.dispose());
+ testBed.get(LocaleService).setDirection('ltr');
+ testBed.get(LocaleService).setLocale(LocaleType.EN_US);
const { context, injector, sheet, sheetSkeletonManagerService, skeleton } = testBed;
const worksheet = sheet.getActiveSheet()!;
skeleton.columnHeaderHeight = 60;
- vi.spyOn(worksheet, 'getHiddenRows').mockReturnValue([
- { startRow: 13, endRow: 21, startColumn: 0, endColumn: 0 },
- { startRow: 30, endRow: 31, startColumn: 0, endColumn: 0 },
- ]);
- vi.spyOn(worksheet, 'getHiddenCols').mockReturnValue([]);
-
- injector.get(HeaderUnhideRangeService).registerRangeVisibleHandler((visible, payload) => (
+ for (let row = 13; row <= 21; row++) {
+ worksheet.getRowManager().getRowOrCreate(row).hd = BooleanNumber.TRUE;
+ }
+ for (let row = 30; row <= 31; row++) {
+ worksheet.getRowManager().getRowOrCreate(row).hd = BooleanNumber.TRUE;
+ }
+
+ const registration = injector.get(HeaderUnhideRangeService).registerRangeVisibleHandler((visible, payload) => (
visible && !(payload.axis === HeaderUnhideRangeAxis.ROW && payload.range.startRow === 13 && payload.range.endRow === 21)
));
+ cleanups.push(() => registration.dispose());
- const controller = injector.createInstance(HeaderUnhideRenderController, context as any);
+ const createController = () => injector.createInstance(HeaderUnhideRenderController, context);
+ injector.add([HeaderUnhideRenderController, { useFactory: createController }]);
+ const controller = injector.get(HeaderUnhideRenderController);
+ cleanups.push(() => controller.dispose());
sheetSkeletonManagerService.emitCurrentSkeleton({
unitId: sheet.getUnitId(),
sheetId: worksheet.getSheetId(),
});
- const shapes = (controller as any)._shapes;
+ const shapes = (controller as unknown as { _shapes: { rows: HeaderUnhideShape[]; cols: HeaderUnhideShape[] } })._shapes;
expect(shapes.rows).toHaveLength(1);
expect(shapes.rows[0].top).toBe(30 * 20 - 12);
+ });
+
+ it('renders one button for adjacent hidden and zero-width columns, including sheet boundaries', () => {
+ const testBed = createRenderTestBed();
+ cleanups.push(() => testBed.univer.dispose());
+ const { injector, context, sheet, sheetSkeletonManagerService } = testBed;
+ testBed.get(LocaleService).setDirection('ltr');
+ const worksheet = sheet.getActiveSheet()!;
+ const manager = worksheet.getColumnManager();
+ manager.setColumnWidth(0, 0);
+ manager.getColumnOrCreate(1).hd = BooleanNumber.TRUE;
+ manager.setColumnWidth(2, 0);
+ manager.setColumnWidth(4, 1.5);
+ manager.setColumnWidth(worksheet.getColumnCount() - 1, 0);
+ const createController = () => injector.createInstance(HeaderUnhideRenderController, context);
+ injector.add([HeaderUnhideRenderController, { useFactory: createController }]);
+ const controller = injector.get(HeaderUnhideRenderController);
+ cleanups.push(() => controller.dispose());
+ sheetSkeletonManagerService.emitCurrentSkeleton({ unitId: sheet.getUnitId(), sheetId: worksheet.getSheetId() });
+ const shapes = (controller as unknown as { _shapes: { cols: HeaderUnhideShape[] } })._shapes;
+ expect(shapes.cols).toHaveLength(2);
+ expect(shapes.cols[0].left).toBe(0);
+ manager.setColumnWidth(0, worksheet.getConfig().defaultColumnWidth);
+ manager.getColumnOrCreate(1).hd = BooleanNumber.FALSE;
+ manager.setColumnWidth(2, worksheet.getConfig().defaultColumnWidth);
+ manager.setColumnWidth(worksheet.getColumnCount() - 1, worksheet.getConfig().defaultColumnWidth);
+ sheetSkeletonManagerService.emitCurrentSkeleton({ unitId: sheet.getUnitId(), sheetId: worksheet.getSheetId() });
+ expect((controller as unknown as { _shapes: { cols: HeaderUnhideShape[] } })._shapes.cols).toHaveLength(0);
+ });
+
+ it('renders one button for adjacent hidden and zero-height rows and skips positive and filtered heights', () => {
+ const testBed = createRenderTestBed();
+ cleanups.push(() => testBed.univer.dispose());
+ const { injector, context, sheet, sheetSkeletonManagerService } = testBed;
+ testBed.get(LocaleService).setDirection('ltr');
+ testBed.get(LocaleService).setLocale(LocaleType.EN_US);
+ const worksheet = sheet.getActiveSheet()!;
+ const manager = worksheet.getRowManager();
+ manager.setRowHeight(0, 0);
+ manager.getRowOrCreate(1).hd = BooleanNumber.TRUE;
+ manager.setRowHeight(2, 0);
+ manager.setRowHeight(4, 1.5);
+ manager.setRowHeight(5, 0);
+ manager.getRowOrCreate(5).ah = 40;
+ manager.setRowHeight(6, 0);
+ manager.setRowHeight(worksheet.getRowCount() - 1, 0);
+ worksheet.__interceptViewModel((viewModel) => {
+ const registration = viewModel.registerRowFilteredInterceptor({ getRowFiltered: (row) => row === 6 });
+ cleanups.push(() => registration.dispose());
+ });
+ expect(worksheet.getRowVisible(6)).toBe(false);
+ const createController = () => injector.createInstance(HeaderUnhideRenderController, context);
+ injector.add([HeaderUnhideRenderController, { useFactory: createController }]);
+ const controller = injector.get(HeaderUnhideRenderController);
+ cleanups.push(() => controller.dispose());
+ sheetSkeletonManagerService.emitCurrentSkeleton({ unitId: sheet.getUnitId(), sheetId: worksheet.getSheetId() });
+ const shapes = (controller as unknown as { _shapes: { rows: HeaderUnhideShape[] } })._shapes;
+ expect(shapes.rows).toHaveLength(2);
+ expect(shapes.rows[0].top).toBe(0);
+ manager.setRowHeight(0, worksheet.getConfig().defaultRowHeight);
+ manager.getRowOrCreate(1).hd = BooleanNumber.FALSE;
+ manager.setRowHeight(2, worksheet.getConfig().defaultRowHeight);
+ manager.setRowHeight(worksheet.getRowCount() - 1, worksheet.getConfig().defaultRowHeight);
+ sheetSkeletonManagerService.emitCurrentSkeleton({ unitId: sheet.getUnitId(), sheetId: worksheet.getSheetId() });
+ expect((controller as unknown as { _shapes: { rows: HeaderUnhideShape[] } })._shapes.rows).toHaveLength(0);
+ });
- testBed.univer.dispose();
+ it('applies both existing visibility filters to zero-height row buttons', () => {
+ const testBed = createRenderTestBed();
+ cleanups.push(() => testBed.univer.dispose());
+ const { injector, context, sheet, sheetSkeletonManagerService } = testBed;
+ testBed.get(LocaleService).setDirection('ltr');
+ testBed.get(LocaleService).setLocale(LocaleType.EN_US);
+ const worksheet = sheet.getActiveSheet()!;
+ worksheet.getRowManager().setRowHeight(0, 0);
+ worksheet.getRowManager().setRowHeight(3, 0);
+ const registration = injector.get(HeaderUnhideRangeService).registerRangeVisibleHandler((visible, payload) => (
+ visible && !(payload.axis === HeaderUnhideRangeAxis.ROW && payload.range.startRow === 3)
+ ));
+ cleanups.push(() => registration.dispose());
+ const createController = () => injector.createInstance(HeaderUnhideRenderController, context);
+ injector.add([HeaderUnhideRenderController, { useFactory: createController }]);
+ const controller = injector.get(HeaderUnhideRenderController);
+ cleanups.push(() => controller.dispose());
+ controller.interceptor.intercept(controller.interceptor.getInterceptPoints().HEADER_UNHIDE_RANGE_VISIBLE_CHECK, {
+ handler: (visible, payload) => visible && !(payload.axis === HeaderUnhideRangeAxis.ROW && payload.range.startRow === 0),
+ });
+ sheetSkeletonManagerService.emitCurrentSkeleton({ unitId: sheet.getUnitId(), sheetId: worksheet.getSheetId() });
+ expect((controller as unknown as { _shapes: { rows: HeaderUnhideShape[] } })._shapes.rows).toHaveLength(0);
+ });
+
+ it('applies the existing visibility filter to zero-width column buttons', () => {
+ const testBed = createRenderTestBed();
+ cleanups.push(() => testBed.univer.dispose());
+ const { injector, context, sheet } = testBed;
+ testBed.get(LocaleService).setDirection('ltr');
+ const worksheet = sheet.getActiveSheet()!;
+ worksheet.getColumnManager().setColumnWidth(0, 0);
+ const registration = injector.get(HeaderUnhideRangeService).registerRangeVisibleHandler((visible, payload) => (
+ visible && payload.axis !== HeaderUnhideRangeAxis.COLUMN
+ ));
+ cleanups.push(() => registration.dispose());
+ const createController = () => injector.createInstance(HeaderUnhideRenderController, context);
+ injector.add([HeaderUnhideRenderController, { useFactory: createController }]);
+ const controller = injector.get(HeaderUnhideRenderController);
+ cleanups.push(() => controller.dispose());
+ expect((controller as unknown as { _shapes: { cols: HeaderUnhideShape[] } })._shapes.cols).toHaveLength(0);
});
});
diff --git a/packages/sheets-ui/src/controllers/render-controllers/header-resize.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/header-resize.render-controller.ts
index 7a238fe073..0da1cbad77 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/header-resize.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/header-resize.render-controller.ts
@@ -18,13 +18,19 @@
/* eslint-disable complexity */
import type { EventState, IRange, Nullable, Workbook } from '@univerjs/core';
-import type { IMouseEvent, IPointerEvent, IRenderContext, IRenderModule, SpreadsheetColumnHeader, SpreadsheetHeader } from '@univerjs/engine-render';
+import type {
+ IMouseEvent,
+ IPointerEvent,
+ IRenderContext,
+ IRenderModule,
+ SpreadsheetColumnHeader,
+ SpreadsheetHeader,
+} from '@univerjs/engine-render';
import type {
IDeltaColumnWidthCommandParams,
IDeltaRowHeightCommandParams,
ISetWorksheetRowIsAutoHeightCommandParams,
} from '@univerjs/sheets';
-import type { ISetWorksheetColIsAutoWidthCommandParams } from '../../commands/commands/set-worksheet-auto-col-width.command';
import {
createInterceptorKey,
Disposable,
@@ -34,7 +40,6 @@ import {
RANGE_TYPE,
} from '@univerjs/core';
import { CURSOR_TYPE, Rect, SHEET_VIEWPORT_KEY, Vector2 } from '@univerjs/engine-render';
-
import {
DeltaColumnWidthCommand,
DeltaRowHeightCommand,
@@ -42,6 +47,7 @@ import {
SheetsSelectionsService,
} from '@univerjs/sheets';
import { Subscription } from 'rxjs';
+import type { ISetWorksheetColIsAutoWidthCommandParams } from '../../commands/commands/set-worksheet-auto-col-width.command';
import { SetWorksheetColAutoWidthCommand } from '../../commands/commands/set-worksheet-auto-col-width.command';
import { SHEET_COMPONENT_HEADER_LAYER_INDEX, SHEET_VIEW_KEY } from '../../common/keys';
import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';
@@ -416,9 +422,7 @@ export class HeaderResizeRenderController extends Disposable implements IRenderM
moveChangeY = canvasMaxHeight - scrollBarHorizontalHeight + scrollXY.y - cell.startY;
}
- if (moveChangeY < -(cell.endY - cell.startY) + 2) {
- moveChangeY = -(cell.endY - cell.startY) + 2;
- }
+ moveChangeY = Math.max(moveChangeY, -(cell.endY - cell.startY));
if (isStartMove) {
this._resizeHelperShape?.transformByState({
@@ -438,9 +442,7 @@ export class HeaderResizeRenderController extends Disposable implements IRenderM
moveChangeX = canvasMaxWidth - scrollBarVerticalWidth + scrollXY.x - cell.startX;
}
- if (moveChangeX < -(cell.endX - cell.startX) + 2) {
- moveChangeX = -(cell.endX - cell.startX) + 2;
- }
+ moveChangeX = Math.max(moveChangeX, -(cell.endX - cell.startX));
if (isStartMove) {
this._resizeHelperShape?.transformByState({
@@ -458,7 +460,7 @@ export class HeaderResizeRenderController extends Disposable implements IRenderM
}
});
- this._scenePointerUpSub = scene.onPointerUp$.subscribeEvent((upEvt: IPointerEvent | IMouseEvent) => {
+ this._scenePointerUpSub = scene.onPointerUp$.subscribeEvent(() => {
const scene = this._context.scene;
this._clearObserverEvent();
diff --git a/packages/sheets-ui/src/controllers/render-controllers/header-unhide.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/header-unhide.render-controller.ts
index d6b6e31c04..120e55f08f 100644
--- a/packages/sheets-ui/src/controllers/render-controllers/header-unhide.render-controller.ts
+++ b/packages/sheets-ui/src/controllers/render-controllers/header-unhide.render-controller.ts
@@ -14,15 +14,16 @@
* limitations under the License.
*/
-import type { Workbook, Worksheet } from '@univerjs/core';
+import type { IRange, Workbook, Worksheet } from '@univerjs/core';
import type { IRenderContext } from '@univerjs/engine-render';
import type { ISetSpecificColsVisibleCommandParams, ISetSpecificRowsVisibleCommandParams } from '@univerjs/sheets';
-import type { IHeaderUnhideRangeVisibleCheck } from '../../services/header-unhide-range.service';
import {
createInterceptorKey,
ICommandService,
Inject,
InterceptorManager,
+ RANGE_TYPE,
+ Rectangle,
RxDisposable,
} from '@univerjs/core';
import {
@@ -30,7 +31,7 @@ import {
SetSpecificRowsVisibleCommand,
} from '@univerjs/sheets';
import { takeUntil } from 'rxjs';
-
+import type { IHeaderUnhideRangeVisibleCheck } from '../../services/header-unhide-range.service';
import { SHEET_COMPONENT_UNHIDE_LAYER_INDEX } from '../../common/keys';
import { HeaderUnhideRangeAxis, HeaderUnhideRangeService } from '../../services/header-unhide-range.service';
import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';
@@ -65,6 +66,7 @@ export class HeaderUnhideRenderController extends RxDisposable {
super.dispose();
this._clearShapes();
+ this.interceptor.dispose();
}
private _init(): void {
@@ -76,7 +78,7 @@ export class HeaderUnhideRenderController extends RxDisposable {
if (!worksheet) {
activeSheetId = '';
return;
- };
+ }
activeSheetId = worksheet.getSheetId();
this._update(this._workbook, worksheet);
@@ -99,7 +101,9 @@ export class HeaderUnhideRenderController extends RxDisposable {
private _update(workbook: Workbook, worksheet: Worksheet): void {
const skeleton = this._sheetSkeletonManagerService.getSkeletonParam(worksheet.getSheetId())?.skeleton;
- if (!skeleton) return;
+ if (!skeleton) {
+ return;
+ }
// steps to render the unhide button for the current worksheet
// 1. and get hidden rows and columns
@@ -108,18 +112,42 @@ export class HeaderUnhideRenderController extends RxDisposable {
this._headerUnhideRangeService.shouldRenderRange(visibleCheck(true, payload) ?? true, payload)
);
- const hiddenRowRanges = worksheet.getHiddenRows().filter((range) => shouldRenderRange({
- axis: HeaderUnhideRangeAxis.ROW,
- range,
- workbook,
- worksheet,
- }));
- const hiddenColRanges = worksheet.getHiddenCols().filter((range) => shouldRenderRange({
- axis: HeaderUnhideRangeAxis.COLUMN,
- range,
- workbook,
- worksheet,
- }));
+ const zeroHeightRowRanges: IRange[] = [];
+ const rowData = worksheet.getRowManager().getRowData();
+ for (const rowIndex of Object.keys(rowData)) {
+ const row = Number(rowIndex);
+ if (row >= 0 && row < worksheet.getRowCount() && worksheet.getRowVisible(row) && worksheet.getRowHeight(row) === 0) {
+ zeroHeightRowRanges.push({ startRow: row, endRow: row, startColumn: 0, endColumn: worksheet.getColumnCount() - 1 });
+ }
+ }
+ const rowRanges = [...worksheet.getHiddenRows(), ...Rectangle.mergeRanges(zeroHeightRowRanges)]
+ .map((range) => ({ ...range, rangeType: RANGE_TYPE.ROW }))
+ .filter((range) => shouldRenderRange({
+ axis: HeaderUnhideRangeAxis.ROW,
+ range,
+ workbook,
+ worksheet,
+ }));
+ const hiddenRowRanges = Rectangle.mergeRanges(rowRanges)
+ .map((range) => ({ ...range, rangeType: RANGE_TYPE.ROW }));
+ const zeroWidthColRanges: IRange[] = [];
+ const columnData = worksheet.getColumnManager().getColumnData();
+ for (const columnIndex of Object.keys(columnData)) {
+ const column = Number(columnIndex);
+ if (column >= 0 && column < worksheet.getColumnCount() && worksheet.getColVisible(column) && worksheet.getColumnWidth(column) === 0) {
+ zeroWidthColRanges.push({ startRow: 0, endRow: worksheet.getRowCount() - 1, startColumn: column, endColumn: column });
+ }
+ }
+ const columnRanges = [...worksheet.getHiddenCols(), ...Rectangle.mergeRanges(zeroWidthColRanges)]
+ .map((range) => ({ ...range, rangeType: RANGE_TYPE.COLUMN }))
+ .filter((range) => shouldRenderRange({
+ axis: HeaderUnhideRangeAxis.COLUMN,
+ range,
+ workbook,
+ worksheet,
+ }));
+ const hiddenColRanges = Rectangle.mergeRanges(columnRanges)
+ .map((range) => ({ ...range, rangeType: RANGE_TYPE.COLUMN }));
// First just let me render a unhide button of the column header!.
const sheetObject = this._getSheetObject();
diff --git a/packages/sheets-ui/src/menu/menu.ts b/packages/sheets-ui/src/menu/menu.ts
index d3a0e4fbdc..1868a2cc98 100644
--- a/packages/sheets-ui/src/menu/menu.ts
+++ b/packages/sheets-ui/src/menu/menu.ts
@@ -16,7 +16,6 @@
import type { IAccessor, IColorStyle, IStyleData, Nullable, Workbook } from '@univerjs/core';
import type { IMenuButtonItem, IMenuSelectorItem } from '@univerjs/ui';
-import type { LocaleKey } from '../locale/types';
import {
BooleanNumber,
composeStyles,
@@ -83,7 +82,7 @@ import {
MenuItemType,
} from '@univerjs/ui';
import { combineLatest, combineLatestWith, map, Observable, startWith } from 'rxjs';
-
+import type { LocaleKey } from '../locale/types';
import {
SheetCopyCommand,
SheetCutCommand,
@@ -1298,7 +1297,7 @@ export function SetRowHeightMenuItemFactory(accessor: IAccessor): IMenuButtonIte
const univerInstanceService = accessor.get(IUniverInstanceService);
const selectionManagerService = accessor.get(SheetsSelectionsService);
- const min = 2;
+ const min = 0;
return {
id: SetRowHeightCommand.id,
@@ -1343,7 +1342,7 @@ export function SetColWidthMenuItemFactory(accessor: IAccessor): IMenuButtonItem
const univerInstanceService = accessor.get(IUniverInstanceService);
const selectionManagerService = accessor.get(SheetsSelectionsService);
- const min = 2;
+ const min = 0;
return {
id: SetColWidthCommand.id,
diff --git a/packages/sheets-ui/src/views/menu-item-input/MenuItemInput.tsx b/packages/sheets-ui/src/views/menu-item-input/MenuItemInput.tsx
index 484453f512..6e5ba678b0 100644
--- a/packages/sheets-ui/src/views/menu-item-input/MenuItemInput.tsx
+++ b/packages/sheets-ui/src/views/menu-item-input/MenuItemInput.tsx
@@ -15,11 +15,11 @@
*/
import type { KeyboardEvent } from 'react';
-import type { IMenuItemInputProps } from './interface';
import { LocaleService } from '@univerjs/core';
import { InputNumber } from '@univerjs/design';
import { IContextMenuService, useDependency, useObservable } from '@univerjs/ui';
import { useEffect, useRef, useState } from 'react';
+import type { IMenuItemInputProps } from './interface';
export const MenuItemInput = (props: IMenuItemInputProps) => {
const {
@@ -46,12 +46,7 @@ export const MenuItemInput = (props: IMenuItemInputProps) => {
}, []);
const handleChange = (value: number | null) => {
- if (!value) {
- setInputValue(min.toString());
- return;
- }
-
- const inputValue = value.toString();
+ const inputValue = (value ?? min).toString();
setInputValue(inputValue);
onChange(inputValue);
};
diff --git a/packages/sheets-ui/src/views/menu-item-input/__tests__/MenuItemInput.spec.tsx b/packages/sheets-ui/src/views/menu-item-input/__tests__/MenuItemInput.spec.tsx
index fb9a856f48..0d6929243f 100644
--- a/packages/sheets-ui/src/views/menu-item-input/__tests__/MenuItemInput.spec.tsx
+++ b/packages/sheets-ui/src/views/menu-item-input/__tests__/MenuItemInput.spec.tsx
@@ -15,15 +15,48 @@
*/
import type { ReactElement } from 'react';
-import { Injector, LocaleService, LocaleType } from '@univerjs/core';
+import {
+ ICommandService,
+ Injector,
+ LocaleService,
+ LocaleType,
+ RANGE_TYPE,
+ RedoCommand,
+ UndoCommand,
+} from '@univerjs/core';
import { ConfigProvider } from '@univerjs/design';
import designEnUS from '@univerjs/design/locale/en-US';
-import { ContextMenuService, IContextMenuService, RediContext } from '@univerjs/ui';
+import {
+ SetColWidthCommand,
+ SetRowHeightCommand,
+ SetWorksheetColWidthMutation,
+ SetWorksheetRowHeightMutation,
+ SetWorksheetRowIsAutoHeightMutation,
+ SheetSkeletonService,
+ SheetsSelectionsService,
+ WorkbookPermissionService,
+ WorksheetPermissionService,
+} from '@univerjs/sheets';
+import {
+ ComponentManager,
+ ContextMenuPanel,
+ ContextMenuService,
+ DesktopLayoutService,
+ IconManager,
+ IContextMenuService,
+ ILayoutService,
+ IMenuManagerService,
+ MenuManagerService,
+ RediContext,
+} from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { BehaviorSubject } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createCommandTestBed } from '../../../commands/commands/__tests__/create-command-test-bed';
import enUS from '../../../locale/en-US';
+import { SetColWidthMenuItemFactory, SetRowHeightMenuItemFactory, SheetMenuPosition } from '../../../menu/menu';
+import { MENU_ITEM_INPUT_COMPONENT } from '../interface';
import { MenuItemInput } from '../MenuItemInput';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -52,8 +85,12 @@ function createInjector() {
return injector;
}
-function renderWithDependencies(element: ReactElement) {
- const injector = createInjector();
+function renderWithDependencies(
+ element: ReactElement,
+ setupInjector?: (injector: Injector) => void,
+ injector = createInjector()
+) {
+ setupInjector?.(injector);
const container = document.createElement('div');
document.body.appendChild(container);
const root = createRoot(container);
@@ -112,6 +149,136 @@ describe('MenuItemInput', () => {
vi.useRealTimers();
});
+ it.each([
+ ['column', '0'],
+ ['row', '0'],
+ ['column', ''],
+ ['row', ''],
+ ])('applies zero %s size from input %j through the real context menu and supports undo/redo', async (axis, text) => {
+ const testBed = createCommandTestBed(undefined, [[SheetSkeletonService]]);
+ const injector = testBed.univer.__getInjector();
+ const commands = injector.get(ICommandService);
+ injector.get(WorkbookPermissionService);
+ injector.get(WorksheetPermissionService);
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const isColumn = axis === 'column';
+ const getSize = () => isColumn ? worksheet.getColumnWidth(1) : worksheet.getRowHeight(1);
+ const original = getSize();
+ const executions: Promise<boolean>[] = [];
+ for (const command of [
+ SetColWidthCommand,
+ SetRowHeightCommand,
+ SetWorksheetColWidthMutation,
+ SetWorksheetRowHeightMutation,
+ SetWorksheetRowIsAutoHeightMutation,
+ ]) {
+ commands.registerCommand(command);
+ }
+ injector.get(SheetsSelectionsService).setSelections([{
+ range: {
+ startRow: 1,
+ endRow: 1,
+ startColumn: 1,
+ endColumn: 1,
+ rangeType: isColumn ? RANGE_TYPE.COLUMN : RANGE_TYPE.ROW,
+ },
+ primary: null,
+ style: null,
+ }]);
+ const menuType = isColumn ? SheetMenuPosition.COL_HEADER_CONTEXT_MENU : SheetMenuPosition.ROW_HEADER_CONTEXT_MENU;
+ const commandId = isColumn ? SetColWidthCommand.id : SetRowHeightCommand.id;
+ const { container, unmount } = renderWithDependencies(
+ <ContextMenuPanel
+ menuType={menuType}
+ onOptionSelect={(option) => {
+ executions.push(commands.executeCommand(option.commandId ?? option.label as string, { value: option.value }));
+ }}
+ />,
+ (injector) => {
+ injector.add([IContextMenuService, { useClass: ContextMenuService }]);
+ injector.add([IMenuManagerService, { useClass: MenuManagerService }]);
+ injector.add([ILayoutService, { useClass: DesktopLayoutService }]);
+ injector.add([ComponentManager]);
+ injector.add([IconManager]);
+ const locales = injector.get(LocaleService);
+ locales.load({ [LocaleType.EN_US]: { ...enUS, ...designEnUS } });
+ locales.setLocale(LocaleType.EN_US);
+ locales.setDirection('ltr');
+ injector.get(ILayoutService).registerRootContainerElement(document.body);
+ injector.get(ComponentManager).register(MENU_ITEM_INPUT_COMPONENT, MenuItemInput);
+ injector.get(IMenuManagerService).appendRootMenu({
+ [menuType]: {
+ [commandId]: {
+ menuItemFactory: isColumn ? SetColWidthMenuItemFactory : SetRowHeightMenuItemFactory,
+ },
+ },
+ });
+ },
+ injector
+ );
+ disposals.push(() => {
+ unmount();
+ testBed.univer.dispose();
+ });
+ const input = getInput(container);
+ act(() => input.focus());
+ act(() => input.select());
+ act(() => setInputText(input, text));
+ expect(input.value).toBe('0');
+ const button = input.closest('button');
+ if (!(button instanceof HTMLButtonElement)) {
+ throw new TypeError('Dimension menu item not found');
+ }
+ act(() => button.focus());
+ act(() => button.click());
+ expect(await Promise.all(executions)).toEqual([true]);
+ expect(getSize()).toBe(0);
+ await commands.executeCommand(UndoCommand.id);
+ expect(getSize()).toBe(original);
+ await commands.executeCommand(RedoCommand.id);
+ expect(getSize()).toBe(0);
+ });
+
+ it('reports zero immediately when the configured minimum allows collapsed dimensions', () => {
+ const { container, unmount } = renderWithDependencies(
+ <MenuItemInput
+ prefix="sheets-ui.rightClick.rowHeight"
+ suffix="px"
+ value="24"
+ min={0}
+ max={1000}
+ onChange={(value) => ChangeRecords.push(value)}
+ />
+ );
+ disposals.push(unmount);
+
+ act(() => {
+ setInputText(getInput(container), '0');
+ });
+
+ expect(getInput(container).value).toBe('0');
+ expect(ChangeRecords.values).toEqual(['0']);
+ });
+
+ it('reports the positive minimum when the input is cleared', () => {
+ const { container, unmount } = renderWithDependencies(
+ <MenuItemInput
+ prefix="sheets-ui.rightClick.insertRowsAbove"
+ suffix="sheets-ui.rightClick.insertRowsAboveSuffix"
+ value="12"
+ min={1}
+ max={20}
+ onChange={(value) => ChangeRecords.push(value)}
+ />
+ );
+ disposals.push(unmount);
+
+ act(() => setInputText(getInput(container), ''));
+
+ expect(getInput(container).value).toBe('1');
+ expect(ChangeRecords.values).toEqual(['1']);
+ });
+
it('clamps typed values to the configured maximum before reporting the command value', () => {
const { container, unmount } = renderWithDependencies(
<MenuItemInput
diff --git a/packages/sheets-ui/src/views/mobile/menu-item-input/__tests__/MobileMenuItemInput.spec.tsx b/packages/sheets-ui/src/views/mobile/menu-item-input/__tests__/MobileMenuItemInput.spec.tsx
index e5ef09b48f..dd595debdc 100644
--- a/packages/sheets-ui/src/views/mobile/menu-item-input/__tests__/MobileMenuItemInput.spec.tsx
+++ b/packages/sheets-ui/src/views/mobile/menu-item-input/__tests__/MobileMenuItemInput.spec.tsx
@@ -14,7 +14,6 @@
* limitations under the License.
*/
-import type { IMenuItemInputProps } from '../../../menu-item-input/interface';
import { LocaleService, LocaleType, Univer } from '@univerjs/core';
import { ConfigProvider } from '@univerjs/design';
import designEnUS from '@univerjs/design/locale/en-US';
@@ -22,6 +21,7 @@ import { RediContext } from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { IMenuItemInputProps } from '../../../menu-item-input/interface';
import enUS from '../../../../locale/en-US';
import { MobileMenuItemInput } from '../MobileMenuItemInput';
@@ -47,6 +47,7 @@ async function renderInput(props: Partial<IMenuItemInputProps> = {}) {
onChange,
...props,
};
+ const container = document.createElement('div');
const renderWithProps = (nextProps: Partial<IMenuItemInputProps>) => (
<RediContext.Provider value={{ injector }}>
<ConfigProvider locale={designEnUS.design} mountContainer={container}>
@@ -56,7 +57,6 @@ async function renderInput(props: Partial<IMenuItemInputProps> = {}) {
</ConfigProvider>
</RediContext.Provider>
);
- const container = document.createElement('div');
document.body.appendChild(container);
const root = createRoot(container);
await act(async () => root.render(renderWithProps({})));
@@ -117,6 +117,18 @@ afterEach(() => {
});
describe('MobileMenuItemInput', () => {
+ it('allows confirming zero when the configured minimum allows collapsed dimensions', async () => {
+ const { container, onChange } = await renderInput({ min: 0 });
+ const input = getInput(container);
+ await setInputText(input, '0');
+ expect(onChange).not.toHaveBeenCalled();
+
+ await act(async () => getConfirmButton(container).click());
+
+ expect(input.value).toBe('0');
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('0');
+ });
+
it('keeps multi-digit typing as a draft until explicit confirmation', async () => {
const { container, onChange, onRowClick } = await renderInput();
const input = getInput(container);
diff --git a/packages/sheets/src/commands/commands/__tests__/set-col-visible.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-col-visible.command.spec.ts
new file mode 100644
index 0000000000..d1f86fa6a3
--- /dev/null
+++ b/packages/sheets/src/commands/commands/__tests__/set-col-visible.command.spec.ts
@@ -0,0 +1,131 @@
+/**
+ * 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 { BooleanNumber, ICommandService, LocaleService, LocaleType, RedoCommand, UndoCommand } from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { SheetInterceptorService } from '../../../services/sheet-interceptor/sheet-interceptor.service';
+import { SetColHiddenMutation, SetColVisibleMutation } from '../../mutations/set-col-visible.mutation';
+import { SetWorksheetColWidthMutation } from '../../mutations/set-worksheet-col-width.mutation';
+import { SetSelectionsOperation } from '../../operations/selection.operation';
+import { SetSpecificColsVisibleCommand } from '../set-col-visible.command';
+import { createCommandTestBed } from './create-command-test-bed';
+
+describe('restoring hidden and zero-width columns', () => {
+ let testBed: ReturnType<typeof createCommandTestBed>;
+
+ beforeEach(() => {
+ testBed = createCommandTestBed({
+ id: 'test',
+ name: 'Restore columns',
+ appVersion: '1.0.0',
+ locale: LocaleType.EN_US,
+ styles: {},
+ sheetOrder: ['sheet1'],
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ name: 'Sheet1',
+ rowCount: 10,
+ columnCount: 7,
+ defaultColumnWidth: 109.5,
+ columnData: {
+ 0: { w: 0, s: 'zero-column' },
+ 1: { w: 140, hd: BooleanNumber.TRUE },
+ 2: { w: 0 },
+ 3: { w: 0, hd: BooleanNumber.TRUE },
+ 4: { w: 1.5 },
+ 6: { w: 0 },
+ },
+ },
+ },
+ });
+ const commandService = testBed.get(ICommandService);
+ for (const command of [SetSpecificColsVisibleCommand, SetColVisibleMutation, SetColHiddenMutation, SetWorksheetColWidthMutation, SetSelectionsOperation]) {
+ commandService.registerCommand(command);
+ }
+ const localeService = testBed.get(LocaleService);
+ localeService.setLocale(LocaleType.EN_US);
+ localeService.setDirection('ltr');
+ });
+
+ afterEach(() => testBed.univer.dispose());
+
+ it('restores zero-width columns to the worksheet default and undoes without hiding them', async () => {
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const commandService = testBed.get(ICommandService);
+ let autoHeightCalls = 0;
+ testBed.get(SheetInterceptorService).interceptAutoHeight({
+ getMutations: () => {
+ autoHeightCalls++;
+ return { undos: [], redos: [] };
+ },
+ });
+ const before = testBed.sheet.save();
+ expect(await commandService.executeCommand(SetSpecificColsVisibleCommand.id, {
+ unitId: testBed.sheet.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ ranges: [{ startRow: 0, endRow: 9, startColumn: 0, endColumn: 0 }],
+ })).toBe(true);
+ expect(worksheet.getColumnWidth(0)).toBe(109.5);
+ expect(worksheet.getColVisible(0)).toBe(true);
+ expect(worksheet.getColumnManager().getColumn(0)?.s).toBe('zero-column');
+ const after = testBed.sheet.save();
+ await commandService.executeCommand(UndoCommand.id);
+ expect(testBed.sheet.save()).toEqual(before);
+ expect(worksheet.getColVisible(0)).toBe(true);
+ await commandService.executeCommand(RedoCommand.id);
+ expect(testBed.sheet.save()).toEqual(after);
+ expect(autoHeightCalls).toBe(0);
+ });
+
+ it('restores mixed hidden and zero-width columns in one undo step while preserving other widths', async () => {
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const commandService = testBed.get(ICommandService);
+ const before = testBed.sheet.save();
+ expect(await commandService.executeCommand(SetSpecificColsVisibleCommand.id, {
+ unitId: testBed.sheet.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ ranges: [{ startRow: 0, endRow: 9, startColumn: 0, endColumn: 4 }],
+ })).toBe(true);
+ expect([0, 1, 2, 3, 4].map((column) => worksheet.getColumnWidth(column))).toEqual([109.5, 140, 109.5, 0, 1.5]);
+ expect([0, 1, 2, 3, 4].map((column) => worksheet.getColVisible(column))).toEqual([true, true, true, true, true]);
+ const after = testBed.sheet.save();
+ await commandService.executeCommand(UndoCommand.id);
+ expect(testBed.sheet.save()).toEqual(before);
+ await commandService.executeCommand(RedoCommand.id);
+ expect(testBed.sheet.save()).toEqual(after);
+ });
+
+ it('keeps the existing hidden-column behavior when the hidden column also has zero width', async () => {
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const commandService = testBed.get(ICommandService);
+ const params = {
+ unitId: testBed.sheet.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ ranges: [{ startRow: 0, endRow: 9, startColumn: 3, endColumn: 3 }],
+ };
+ expect(await commandService.executeCommand(SetSpecificColsVisibleCommand.id, params)).toBe(true);
+ expect(worksheet.getColVisible(3)).toBe(true);
+ expect(worksheet.getColumnWidth(3)).toBe(0);
+ expect(await commandService.executeCommand(SetSpecificColsVisibleCommand.id, params)).toBe(true);
+ expect(worksheet.getColumnWidth(3)).toBe(109.5);
+ await commandService.executeCommand(UndoCommand.id);
+ expect(worksheet.getColVisible(3)).toBe(true);
+ expect(worksheet.getColumnWidth(3)).toBe(0);
+ await commandService.executeCommand(UndoCommand.id);
+ expect(worksheet.getColVisible(3)).toBe(false);
+ });
+});
diff --git a/packages/sheets/src/commands/commands/__tests__/set-row-visible.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-row-visible.command.spec.ts
new file mode 100644
index 0000000000..2e443588df
--- /dev/null
+++ b/packages/sheets/src/commands/commands/__tests__/set-row-visible.command.spec.ts
@@ -0,0 +1,173 @@
+/**
+ * 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 { BooleanNumber, ICommandService, LocaleService, LocaleType, RedoCommand, UndoCommand } from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { INTERCEPTOR_POINT } from '../../../services/sheet-interceptor/interceptor-const';
+import { SheetInterceptorService } from '../../../services/sheet-interceptor/sheet-interceptor.service';
+import { SetRowHiddenMutation, SetRowVisibleMutation } from '../../mutations/set-row-visible.mutation';
+import { SetWorksheetRowHeightMutation } from '../../mutations/set-worksheet-row-height.mutation';
+import { SetSelectionsOperation } from '../../operations/selection.operation';
+import { SetSpecificRowsVisibleCommand } from '../set-row-visible.command';
+import { createCommandTestBed } from './create-command-test-bed';
+
+describe('restoring hidden and zero-height rows', () => {
+ let testBed: ReturnType<typeof createCommandTestBed>;
+ const cleanups: Array<() => void> = [];
+
+ beforeEach(() => {
+ testBed = createCommandTestBed({
+ id: 'test',
+ name: 'Restore rows',
+ appVersion: '1.0.0',
+ locale: LocaleType.EN_US,
+ styles: {},
+ sheetOrder: ['sheet1'],
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ name: 'Sheet1',
+ rowCount: 8,
+ columnCount: 10,
+ defaultRowHeight: 29.5,
+ rowData: {
+ 0: { h: 0, ia: BooleanNumber.FALSE, ah: 80, s: 'zero-row' },
+ 1: { h: 40, hd: BooleanNumber.TRUE },
+ 2: { h: 0, ah: 0 },
+ 3: { h: 0, hd: BooleanNumber.TRUE },
+ 4: { h: 1.5 },
+ 5: { h: 0, ah: 48 },
+ 6: { h: 0 },
+ 7: { h: 0 },
+ },
+ },
+ },
+ });
+ const commandService = testBed.get(ICommandService);
+ for (const command of [
+ SetSpecificRowsVisibleCommand,
+ SetRowVisibleMutation,
+ SetRowHiddenMutation,
+ SetWorksheetRowHeightMutation,
+ SetSelectionsOperation,
+ ]) {
+ commandService.registerCommand(command);
+ }
+ const localeService = testBed.get(LocaleService);
+ localeService.setLocale(LocaleType.EN_US);
+ localeService.setDirection('ltr');
+ });
+
+ afterEach(() => {
+ for (const cleanup of cleanups.splice(0).reverse()) {
+ cleanup();
+ }
+ testBed.univer.dispose();
+ });
+
+ it('restores the worksheet default height without changing metadata or recalculating auto height', async () => {
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const commandService = testBed.get(ICommandService);
+ let autoHeightCalls = 0;
+ testBed.get(SheetInterceptorService).interceptAutoHeight({
+ getMutations: () => {
+ autoHeightCalls++;
+ return { undos: [], redos: [] };
+ },
+ });
+ const before = testBed.sheet.save();
+ expect(await commandService.executeCommand(SetSpecificRowsVisibleCommand.id, {
+ unitId: testBed.sheet.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 9 }],
+ })).toBe(true);
+ expect(worksheet.getRowHeight(0)).toBe(29.5);
+ expect(worksheet.getRowVisible(0)).toBe(true);
+ expect(worksheet.getRowManager().getRow(0)).toMatchObject({
+ ia: BooleanNumber.FALSE,
+ ah: 80,
+ s: 'zero-row',
+ });
+ const after = testBed.sheet.save();
+ await commandService.executeCommand(UndoCommand.id);
+ expect(testBed.sheet.save()).toEqual(before);
+ expect(worksheet.getRowVisible(0)).toBe(true);
+ await commandService.executeCommand(RedoCommand.id);
+ expect(testBed.sheet.save()).toEqual(after);
+ expect(autoHeightCalls).toBe(0);
+ });
+
+ it('restores mixed rows in one undo step and preserves positive and effective automatic heights', async () => {
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const commandService = testBed.get(ICommandService);
+ const before = testBed.sheet.save();
+ expect(await commandService.executeCommand(SetSpecificRowsVisibleCommand.id, {
+ unitId: testBed.sheet.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ ranges: [{ startRow: 0, endRow: 5, startColumn: 0, endColumn: 9 }],
+ })).toBe(true);
+ expect([0, 1, 2, 3, 4, 5].map((row) => worksheet.getRowHeight(row)))
+ .toEqual([29.5, 40, 29.5, 0, 1.5, 48]);
+ expect([0, 1, 2, 3, 4, 5].map((row) => worksheet.getRowVisible(row)))
+ .toEqual([true, true, true, true, true, true]);
+ expect(worksheet.getRowManager().getRow(5)?.h).toBe(0);
+ const after = testBed.sheet.save();
+ await commandService.executeCommand(UndoCommand.id);
+ expect(testBed.sheet.save()).toEqual(before);
+ await commandService.executeCommand(RedoCommand.id);
+ expect(testBed.sheet.save()).toEqual(after);
+ });
+
+ it('keeps the existing hidden-row behavior when the hidden row also has zero height', async () => {
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const commandService = testBed.get(ICommandService);
+ const params = {
+ unitId: testBed.sheet.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ ranges: [{ startRow: 3, endRow: 3, startColumn: 0, endColumn: 9 }],
+ };
+ expect(await commandService.executeCommand(SetSpecificRowsVisibleCommand.id, params)).toBe(true);
+ expect(worksheet.getRowVisible(3)).toBe(true);
+ expect(worksheet.getRowHeight(3)).toBe(0);
+ expect(await commandService.executeCommand(SetSpecificRowsVisibleCommand.id, params)).toBe(true);
+ expect(worksheet.getRowHeight(3)).toBe(29.5);
+ await commandService.executeCommand(UndoCommand.id);
+ expect(worksheet.getRowVisible(3)).toBe(true);
+ expect(worksheet.getRowHeight(3)).toBe(0);
+ await commandService.executeCommand(UndoCommand.id);
+ expect(worksheet.getRowVisible(3)).toBe(false);
+ });
+
+ it('preserves rows collapsed by filtering when restoring an adjacent zero-height row', async () => {
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const commandService = testBed.get(ICommandService);
+ const registration = testBed.get(SheetInterceptorService).intercept(INTERCEPTOR_POINT.ROW_FILTERED, {
+ handler: (filtered, location, next) => filtered || location.row === 7 || next(),
+ });
+ cleanups.push(() => registration.dispose());
+ const before = testBed.sheet.save();
+ expect(await commandService.executeCommand(SetSpecificRowsVisibleCommand.id, {
+ unitId: testBed.sheet.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ ranges: [{ startRow: 6, endRow: 7, startColumn: 0, endColumn: 9 }],
+ })).toBe(true);
+ expect(worksheet.getRowHeight(6)).toBe(29.5);
+ expect(worksheet.getRowManager().getRow(7)?.h).toBe(0);
+ expect(worksheet.getRowVisible(7)).toBe(false);
+ await commandService.executeCommand(UndoCommand.id);
+ expect(testBed.sheet.save()).toEqual(before);
+ });
+});
diff --git a/packages/sheets/src/commands/commands/__tests__/set-worksheet-col-width.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-worksheet-col-width.command.spec.ts
new file mode 100644
index 0000000000..418f8e6d8d
--- /dev/null
+++ b/packages/sheets/src/commands/commands/__tests__/set-worksheet-col-width.command.spec.ts
@@ -0,0 +1,89 @@
+/**
+ * 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 { ICommandService, LocaleService, LocaleType, RANGE_TYPE, RedoCommand, UndoCommand } from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { SheetsSelectionsService } from '../../../services/selections/selection.service';
+import { SetWorksheetColWidthMutation } from '../../mutations/set-worksheet-col-width.mutation';
+import { DeltaColumnWidthCommand, SetColWidthCommand } from '../set-worksheet-col-width.command';
+import { createCommandTestBed } from './create-command-test-bed';
+
+describe('col-width dimension validation', () => {
+ let testBed: ReturnType<typeof createCommandTestBed>;
+
+ beforeEach(() => {
+ testBed = createCommandTestBed();
+ const commandService = testBed.get(ICommandService);
+ commandService.registerCommand(SetColWidthCommand);
+ commandService.registerCommand(DeltaColumnWidthCommand);
+ commandService.registerCommand(SetWorksheetColWidthMutation);
+
+ const localeService = testBed.get(LocaleService);
+ localeService.setLocale(LocaleType.EN_US);
+ localeService.setDirection('ltr');
+ });
+
+ afterEach(() => testBed.univer.dispose());
+
+ it.each([-1, Number.NaN, Number.POSITIVE_INFINITY, '96', null])(
+ 'rejects invalid size %s without changing the sheet or undo history',
+ async (value) => {
+ const commandService = testBed.get(ICommandService);
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const ranges = [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }];
+ const params = { unitId: testBed.sheet.getUnitId(), subUnitId: worksheet.getSheetId(), ranges };
+ const original = worksheet.getColumnWidth(0);
+ expect(await commandService.executeCommand(SetColWidthCommand.id, { ...params, value: 96.5 })).toBe(true);
+ const snapshot = testBed.sheet.save();
+ expect(await commandService.executeCommand(SetColWidthCommand.id, { ...params, value })).toBe(false);
+ expect(testBed.sheet.save()).toEqual(snapshot);
+ await commandService.executeCommand(UndoCommand.id);
+ expect(worksheet.getColumnWidth(0)).toBe(original);
+ await commandService.executeCommand(RedoCommand.id);
+ expect(worksheet.getColumnWidth(0)).toBe(96.5);
+ }
+ );
+
+ it('rejects a drag resulting in negative size before side effects', async () => {
+ testBed.get(SheetsSelectionsService).setSelections([{
+ range: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1, rangeType: RANGE_TYPE.COLUMN },
+ primary: null,
+ style: null,
+ }]);
+ const commandService = testBed.get(ICommandService);
+ const snapshot = testBed.sheet.save();
+ expect(await commandService.executeCommand(DeltaColumnWidthCommand.id, { anchorCol: 0, deltaX: -1000 })).toBe(false);
+ expect(testBed.sheet.save()).toEqual(snapshot);
+ });
+
+ it('supports zero size with undo and redo', async () => {
+ const commandService = testBed.get(ICommandService);
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const original = worksheet.getColumnWidth(0);
+ const params = {
+ unitId: testBed.sheet.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],
+ value: 0,
+ };
+ expect(await commandService.executeCommand(SetColWidthCommand.id, params)).toBe(true);
+ expect(worksheet.getColumnWidth(0)).toBe(0);
+ await commandService.executeCommand(UndoCommand.id);
+ expect(worksheet.getColumnWidth(0)).toBe(original);
+ await commandService.executeCommand(RedoCommand.id);
+ expect(worksheet.getColumnWidth(0)).toBe(0);
+ });
+});
diff --git a/packages/sheets/src/commands/commands/__tests__/set-worksheet-row-height.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-worksheet-row-height.command.spec.ts
new file mode 100644
index 0000000000..959546ffea
--- /dev/null
+++ b/packages/sheets/src/commands/commands/__tests__/set-worksheet-row-height.command.spec.ts
@@ -0,0 +1,92 @@
+/**
+ * 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 { ICommandService, LocaleService, LocaleType, RANGE_TYPE, RedoCommand, UndoCommand } from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { SheetsSelectionsService } from '../../../services/selections/selection.service';
+import {
+ SetWorksheetRowHeightMutation,
+ SetWorksheetRowIsAutoHeightMutation,
+} from '../../mutations/set-worksheet-row-height.mutation';
+import { DeltaRowHeightCommand, SetRowHeightCommand } from '../set-worksheet-row-height.command';
+import { createCommandTestBed } from './create-command-test-bed';
+
+describe('row-height dimension validation', () => {
+ let testBed: ReturnType<typeof createCommandTestBed>;
+
+ beforeEach(() => {
+ testBed = createCommandTestBed();
+ const commandService = testBed.get(ICommandService);
+ commandService.registerCommand(SetRowHeightCommand);
+ commandService.registerCommand(DeltaRowHeightCommand);
+ commandService.registerCommand(SetWorksheetRowHeightMutation);
+ commandService.registerCommand(SetWorksheetRowIsAutoHeightMutation);
+ const localeService = testBed.get(LocaleService);
+ localeService.setLocale(LocaleType.EN_US);
+ localeService.setDirection('ltr');
+ });
+
+ afterEach(() => testBed.univer.dispose());
+
+ it.each([-1, Number.NaN, Number.POSITIVE_INFINITY, '96', null])(
+ 'rejects invalid size %s without changing the sheet or undo history',
+ async (value) => {
+ const commandService = testBed.get(ICommandService);
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const ranges = [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }];
+ const params = { unitId: testBed.sheet.getUnitId(), subUnitId: worksheet.getSheetId(), ranges };
+ const original = worksheet.getRowHeight(0);
+ expect(await commandService.executeCommand(SetRowHeightCommand.id, { ...params, value: 96.5 })).toBe(true);
+ const snapshot = testBed.sheet.save();
+ expect(await commandService.executeCommand(SetRowHeightCommand.id, { ...params, value })).toBe(false);
+ expect(testBed.sheet.save()).toEqual(snapshot);
+ await commandService.executeCommand(UndoCommand.id);
+ expect(worksheet.getRowHeight(0)).toBe(original);
+ await commandService.executeCommand(RedoCommand.id);
+ expect(worksheet.getRowHeight(0)).toBe(96.5);
+ }
+ );
+
+ it('rejects a drag resulting in negative size before side effects', async () => {
+ testBed.get(SheetsSelectionsService).setSelections([{
+ range: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1, rangeType: RANGE_TYPE.ROW },
+ primary: null,
+ style: null,
+ }]);
+ const commandService = testBed.get(ICommandService);
+ const snapshot = testBed.sheet.save();
+ expect(await commandService.executeCommand(DeltaRowHeightCommand.id, { anchorRow: 0, deltaY: -1000 })).toBe(false);
+ expect(testBed.sheet.save()).toEqual(snapshot);
+ });
+
+ it('supports zero size with undo and redo', async () => {
+ const commandService = testBed.get(ICommandService);
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const original = worksheet.getRowHeight(0);
+ const params = {
+ unitId: testBed.sheet.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],
+ value: 0,
+ };
+ expect(await commandService.executeCommand(SetRowHeightCommand.id, params)).toBe(true);
+ expect(worksheet.getRowHeight(0)).toBe(0);
+ await commandService.executeCommand(UndoCommand.id);
+ expect(worksheet.getRowHeight(0)).toBe(original);
+ await commandService.executeCommand(RedoCommand.id);
+ expect(worksheet.getRowHeight(0)).toBe(0);
+ });
+});
diff --git a/packages/sheets/src/commands/commands/set-col-visible.command.ts b/packages/sheets/src/commands/commands/set-col-visible.command.ts
index 5f089ddf5f..070ddad898 100644
--- a/packages/sheets/src/commands/commands/set-col-visible.command.ts
+++ b/packages/sheets/src/commands/commands/set-col-visible.command.ts
@@ -14,17 +14,19 @@
* limitations under the License.
*/
-import type { IAccessor, ICommand, IRange, Nullable, Worksheet } from '@univerjs/core';
-import type { ISetColHiddenMutationParams, ISetColVisibleMutationParams } from '../mutations/set-col-visible.mutation';
-import type { ISetSelectionsOperationParams } from '../operations/selection.operation';
+import type { IAccessor, ICommand, IMutationInfo, IRange, Nullable, Worksheet } from '@univerjs/core';
import {
CommandType,
ICommandService,
IUndoRedoService,
IUniverInstanceService,
RANGE_TYPE,
+ Rectangle,
sequenceExecute,
} from '@univerjs/core';
+import type { ISetColHiddenMutationParams, ISetColVisibleMutationParams } from '../mutations/set-col-visible.mutation';
+import type { ISetWorksheetColWidthMutationParams } from '../mutations/set-worksheet-col-width.mutation';
+import type { ISetSelectionsOperationParams } from '../operations/selection.operation';
import { SheetsSelectionsService } from '../../services/selections/selection.service';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import {
@@ -33,6 +35,10 @@ import {
SetColVisibleMutation,
SetColVisibleUndoMutationFactory,
} from '../mutations/set-col-visible.mutation';
+import {
+ SetWorksheetColWidthMutation,
+ SetWorksheetColWidthMutationFactory,
+} from '../mutations/set-worksheet-col-width.mutation';
import { SetSelectionsOperation } from '../operations/selection.operation';
import { getPrimaryForRange } from './utils/selection-utils';
import { getSheetCommandTarget } from './utils/target-util';
@@ -54,13 +60,40 @@ export const SetSpecificColsVisibleCommand: ICommand<ISetSpecificColsVisibleComm
const instanceService = accessor.get(IUniverInstanceService);
const target = getSheetCommandTarget(instanceService, { unitId, subUnitId });
- if (!target) return false;
+ if (!target) {
+ return false;
+ }
const { worksheet } = target;
+ const zeroWidthRanges: IRange[] = [];
+ for (const range of ranges) {
+ for (let column = range.startColumn; column <= range.endColumn; column++) {
+ if (worksheet.getColVisible(column) && worksheet.getColumnWidth(column) === 0) {
+ zeroWidthRanges.push({ ...range, startColumn: column, endColumn: column });
+ }
+ }
+ }
+ const widthRanges = Rectangle.mergeRanges(zeroWidthRanges);
+ const visibilityRanges = widthRanges.length ? getHiddenColRanges(worksheet, ranges) : ranges;
+ const widthRedos: IMutationInfo[] = [];
+ const widthUndos: IMutationInfo[] = [];
+ if (widthRanges.length) {
+ const widthParams: ISetWorksheetColWidthMutationParams = {
+ unitId,
+ subUnitId,
+ ranges: widthRanges,
+ colWidth: worksheet.getConfig().defaultColumnWidth,
+ };
+ widthRedos.push({ id: SetWorksheetColWidthMutation.id, params: widthParams });
+ widthUndos.push({
+ id: SetWorksheetColWidthMutation.id,
+ params: SetWorksheetColWidthMutationFactory(widthParams, worksheet),
+ });
+ }
const redoMutationParams: ISetColVisibleMutationParams = {
unitId,
subUnitId,
- ranges,
+ ranges: visibilityRanges,
};
const setSelectionOperationParams: ISetSelectionsOperationParams = {
unitId,
@@ -81,11 +114,21 @@ export const SetSpecificColsVisibleCommand: ICommand<ISetSpecificColsVisibleComm
})),
};
+ const visibilityRedos: IMutationInfo[] = visibilityRanges.length
+ ? [{ id: SetColVisibleMutation.id, params: redoMutationParams }]
+ : [];
+ const visibilityUndos: IMutationInfo[] = visibilityRanges.length
+ ? [{ id: SetColHiddenMutation.id, params: undoMutationParams }]
+ : [];
const result = sequenceExecute([
- { id: SetColVisibleMutation.id, params: redoMutationParams },
+ ...visibilityRedos,
+ ...widthRedos,
{ id: SetSelectionsOperation.id, params: setSelectionOperationParams },
], commandService);
+ if (!result.result) {
+ return false;
+ }
const intercepted = sheetInterceptorService.onCommandExecute({
id: SetSpecificColsVisibleCommand.id,
params,
@@ -104,14 +147,16 @@ export const SetSpecificColsVisibleCommand: ICommand<ISetSpecificColsVisibleComm
undoRedoService.pushUndoRedo({
unitID: unitId,
undoMutations: [
- { id: SetColHiddenMutation.id, params: undoMutationParams },
+ ...widthUndos,
+ ...visibilityUndos,
{ id: SetSelectionsOperation.id, params: undoSetSelectionsOperationParams },
...(intercepted.undos ?? []),
...afterInterceptors.undos,
],
redoMutations: [
...(intercepted.preRedos ?? []),
- { id: SetColVisibleMutation.id, params: redoMutationParams },
+ ...visibilityRedos,
+ ...widthRedos,
{ id: SetSelectionsOperation.id, params: setSelectionOperationParams },
...intercepted.redos,
...afterInterceptors.redos,
diff --git a/packages/sheets/src/commands/commands/set-row-visible.command.ts b/packages/sheets/src/commands/commands/set-row-visible.command.ts
index 40f48cf0a9..767d6b5750 100644
--- a/packages/sheets/src/commands/commands/set-row-visible.command.ts
+++ b/packages/sheets/src/commands/commands/set-row-visible.command.ts
@@ -14,17 +14,19 @@
* limitations under the License.
*/
-import type { IAccessor, ICommand, IRange, Nullable, Worksheet } from '@univerjs/core';
-import type { ISetRowHiddenMutationParams, ISetRowVisibleMutationParams } from '../mutations/set-row-visible.mutation';
-import type { ISetSelectionsOperationParams } from '../operations/selection.operation';
+import type { IAccessor, ICommand, IMutationInfo, IRange, Nullable, Worksheet } from '@univerjs/core';
import {
CommandType,
ICommandService,
IUndoRedoService,
IUniverInstanceService,
RANGE_TYPE,
+ Rectangle,
sequenceExecute,
} from '@univerjs/core';
+import type { ISetRowHiddenMutationParams, ISetRowVisibleMutationParams } from '../mutations/set-row-visible.mutation';
+import type { ISetWorksheetRowHeightMutationParams } from '../mutations/set-worksheet-row-height.mutation';
+import type { ISetSelectionsOperationParams } from '../operations/selection.operation';
import { SheetsSelectionsService } from '../../services/selections/selection.service';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import {
@@ -33,6 +35,10 @@ import {
SetRowVisibleMutation,
SetRowVisibleUndoMutationFactory,
} from '../mutations/set-row-visible.mutation';
+import {
+ SetWorksheetRowHeightMutation,
+ SetWorksheetRowHeightMutationFactory,
+} from '../mutations/set-worksheet-row-height.mutation';
import { SetSelectionsOperation } from '../operations/selection.operation';
import { getPrimaryForRange } from './utils/selection-utils';
import { getSheetCommandTarget } from './utils/target-util';
@@ -53,10 +59,37 @@ export const SetSpecificRowsVisibleCommand: ICommand<ISetSpecificRowsVisibleComm
const sheetInterceptorService = accessor.get(SheetInterceptorService);
const target = getSheetCommandTarget(accessor.get(IUniverInstanceService), { unitId, subUnitId });
- if (!target) return false;
+ if (!target) {
+ return false;
+ }
const { worksheet } = target;
- const redoMutationParams: ISetRowVisibleMutationParams = { unitId, subUnitId, ranges };
+ const zeroHeightRanges: IRange[] = [];
+ for (const range of ranges) {
+ for (let row = range.startRow; row <= range.endRow; row++) {
+ if (worksheet.getRowVisible(row) && worksheet.getRowHeight(row) === 0) {
+ zeroHeightRanges.push({ ...range, startRow: row, endRow: row });
+ }
+ }
+ }
+ const heightRanges = Rectangle.mergeRanges(zeroHeightRanges);
+ const visibilityRanges = heightRanges.length ? getHiddenRowRanges(worksheet, ranges) : ranges;
+ const heightRedos: IMutationInfo[] = [];
+ const heightUndos: IMutationInfo[] = [];
+ if (heightRanges.length) {
+ const heightParams: ISetWorksheetRowHeightMutationParams = {
+ unitId,
+ subUnitId,
+ ranges: heightRanges,
+ rowHeight: worksheet.getConfig().defaultRowHeight,
+ };
+ heightRedos.push({ id: SetWorksheetRowHeightMutation.id, params: heightParams });
+ heightUndos.push({
+ id: SetWorksheetRowHeightMutation.id,
+ params: SetWorksheetRowHeightMutationFactory(heightParams, worksheet),
+ });
+ }
+ const redoMutationParams: ISetRowVisibleMutationParams = { unitId, subUnitId, ranges: visibilityRanges };
const setSelectionOperationParams: ISetSelectionsOperationParams = {
unitId,
subUnitId,
@@ -79,14 +112,24 @@ export const SetSpecificRowsVisibleCommand: ICommand<ISetSpecificRowsVisibleComm
})),
};
+ const visibilityRedos: IMutationInfo[] = visibilityRanges.length
+ ? [{ id: SetRowVisibleMutation.id, params: redoMutationParams }]
+ : [];
+ const visibilityUndos: IMutationInfo[] = visibilityRanges.length
+ ? [{ id: SetRowHiddenMutation.id, params: undoMutationParams }]
+ : [];
const result = sequenceExecute(
[
- { id: SetRowVisibleMutation.id, params: redoMutationParams },
+ ...visibilityRedos,
+ ...heightRedos,
{ id: SetSelectionsOperation.id, params: setSelectionOperationParams },
],
commandService
);
+ if (!result.result) {
+ return false;
+ }
const intercepted = sheetInterceptorService.onCommandExecute({
id: SetSpecificRowsVisibleCommand.id,
params,
@@ -105,14 +148,16 @@ export const SetSpecificRowsVisibleCommand: ICommand<ISetSpecificRowsVisibleComm
unitID: unitId,
undoMutations: [
...(intercepted.preUndos ?? []),
- { id: SetRowHiddenMutation.id, params: undoMutationParams },
+ ...heightUndos,
+ ...visibilityUndos,
{ id: SetSelectionsOperation.id, params: undoSetSelectionsOperationParams },
...(intercepted.undos ?? []),
...afterInterceptors.undos,
],
redoMutations: [
...(intercepted.preRedos ?? []),
- { id: SetRowVisibleMutation.id, params: redoMutationParams },
+ ...visibilityRedos,
+ ...heightRedos,
{ id: SetSelectionsOperation.id, params: setSelectionOperationParams },
...intercepted.redos,
...afterInterceptors.redos,
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.ts
index 16e2e26b83..fa6488d247 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
@@ -15,16 +15,17 @@
*/
import type { IAccessor, ICommand, IRange } from '@univerjs/core';
-import type { ISetWorksheetColWidthMutationParams } from '../mutations/set-worksheet-col-width.mutation';
import {
CommandType,
ICommandService,
+ isValidSheetDimension,
IUndoRedoService,
IUniverInstanceService,
RANGE_TYPE,
Rectangle,
sequenceExecute,
} from '@univerjs/core';
+import type { ISetWorksheetColWidthMutationParams } from '../mutations/set-worksheet-col-width.mutation';
import { SheetsSelectionsService } from '../../services/selections/selection.service';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import { SheetSkeletonService } from '../../skeleton/skeleton.service';
@@ -56,13 +57,18 @@ export const DeltaColumnWidthCommand: ICommand<IDeltaColumnWidthCommandParams> =
const undoRedoService = accessor.get(IUndoRedoService);
const target = getSheetCommandTarget(accessor.get(IUniverInstanceService));
- if (!target) return false;
+ if (!target) {
+ return false;
+ }
const { worksheet, unitId, subUnitId } = target;
const { anchorCol, deltaX } = params;
const anchorColWidth = worksheet.getColumnWidth(anchorCol);
const destColumnWidth = anchorColWidth + deltaX;
+ if (!isValidSheetDimension(destColumnWidth)) {
+ return false;
+ }
const isAllSheetRange = selections.length === 1 && selections[0].range.rangeType === RANGE_TYPE.ALL;
const colSelections = selections.filter((s) => s.range.rangeType === RANGE_TYPE.COLUMN);
@@ -174,6 +180,9 @@ export const SetColWidthCommand: ICommand = {
type: CommandType.COMMAND,
id: 'sheet.command.set-worksheet-col-width',
handler: (accessor: IAccessor, params: ISetColWidthCommandParams) => {
+ if (!isValidSheetDimension(params?.value)) {
+ return false;
+ }
const selectionManagerService = accessor.get(SheetsSelectionsService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
@@ -184,7 +193,9 @@ export const SetColWidthCommand: ICommand = {
if (!selections?.length) return false;
const target = getSheetCommandTarget(accessor.get(IUniverInstanceService), params);
- if (!target) return false;
+ if (!target) {
+ return false;
+ }
const { subUnitId, unitId, worksheet } = target;
const skeleton = accessor.get(SheetSkeletonService).getSkeleton(unitId, subUnitId);
@@ -264,7 +275,9 @@ export const SetWorksheetColIsAutoWidthCommand: ICommand = {
const univerInstanceService = accessor.get(IUniverInstanceService);
const target = getSheetCommandTarget(univerInstanceService, params);
- if (!target) return false;
+ if (!target) {
+ return false;
+ }
const { unitId, subUnitId } = target;
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.ts
index 36f13053be..c3c5b7769a 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
@@ -15,20 +15,21 @@
*/
import type { IAccessor, ICommand, IRange } from '@univerjs/core';
-import type {
- ISetWorksheetRowHeightMutationParams,
- ISetWorksheetRowIsAutoHeightMutationParams,
-} from '../mutations/set-worksheet-row-height.mutation';
import {
BooleanNumber,
CommandType,
ICommandService,
+ isValidSheetDimension,
IUndoRedoService,
IUniverInstanceService,
RANGE_TYPE,
Rectangle,
sequenceExecute,
} from '@univerjs/core';
+import type {
+ ISetWorksheetRowHeightMutationParams,
+ ISetWorksheetRowIsAutoHeightMutationParams,
+} from '../mutations/set-worksheet-row-height.mutation';
import { SheetsSelectionsService } from '../../services/selections/selection.service';
import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';
import { SheetSkeletonService } from '../../skeleton/skeleton.service';
@@ -60,13 +61,18 @@ export const DeltaRowHeightCommand: ICommand = {
}
const target = getSheetCommandTarget(accessor.get(IUniverInstanceService));
- if (!target) return false;
+ if (!target) {
+ return false;
+ }
const { worksheet, subUnitId, unitId } = target;
const { anchorRow, deltaY } = params;
const anchorRowHeight = worksheet.getRowHeight(anchorRow);
const destRowHeight = anchorRowHeight + deltaY;
+ if (!isValidSheetDimension(destRowHeight)) {
+ return false;
+ }
const isAllSheetRange = selections.length === 1 && selections[0].range.rangeType === RANGE_TYPE.ALL;
const rowSelections = selections.filter((s) => s.range.rangeType === RANGE_TYPE.ROW);
@@ -206,6 +212,9 @@ export const SetRowHeightCommand: ICommand = {
id: 'sheet.command.set-row-height',
// eslint-disable-next-line max-lines-per-function
handler: (accessor: IAccessor, params: ISetRowHeightCommandParams) => {
+ if (!isValidSheetDimension(params?.value)) {
+ return false;
+ }
const selectionManagerService = accessor.get(SheetsSelectionsService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
@@ -219,7 +228,9 @@ export const SetRowHeightCommand: ICommand = {
}
const target = getSheetCommandTarget(univerInstanceService, params);
- if (!target) return false;
+ if (!target) {
+ return false;
+ }
const { unitId, subUnitId, worksheet } = target;
@@ -319,7 +330,9 @@ export const SetWorksheetRowIsAutoHeightCommand: ICommand = {
const univerInstanceService = accessor.get(IUniverInstanceService);
const target = getSheetCommandTarget(univerInstanceService, params);
- if (!target) return false;
+ if (!target) {
+ return false;
+ }
const { unitId, subUnitId, worksheet } = target;
const ranges = params?.ranges?.length ? params.ranges : selectionManagerService.getCurrentSelections()?.map((s) => s.range);
diff --git a/packages/sheets/src/commands/mutations/__tests__/insert-row-col.mutation.spec.ts b/packages/sheets/src/commands/mutations/__tests__/insert-row-col.mutation.spec.ts
new file mode 100644
index 0000000000..a6a7ad0713
--- /dev/null
+++ b/packages/sheets/src/commands/mutations/__tests__/insert-row-col.mutation.spec.ts
@@ -0,0 +1,46 @@
+/**
+ * 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 { ICommandService } from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { InsertColMutation, InsertRowMutation } from '../insert-row-col.mutation';
+import { createCommandTestBed } from './create-command-test-bed';
+
+describe('insert dimensions validation', () => {
+ let testBed: ReturnType<typeof createCommandTestBed>;
+
+ beforeEach(() => {
+ testBed = createCommandTestBed();
+ testBed.get(ICommandService).registerCommand(InsertColMutation);
+ testBed.get(ICommandService).registerCommand(InsertRowMutation);
+ });
+
+ afterEach(() => testBed.univer.dispose());
+
+ it('rejects invalid insertion metadata before moving cells or changing counts', () => {
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const params = {
+ unitId: testBed.sheet.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ range: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },
+ };
+ const snapshot = testBed.sheet.save();
+ const commandService = testBed.get(ICommandService);
+ expect(commandService.syncExecuteCommand(InsertColMutation.id, { ...params, colInfo: { 0: { w: 50 }, 1: { w: -1 } } })).toBe(false);
+ expect(commandService.syncExecuteCommand(InsertRowMutation.id, { ...params, rowInfo: { 0: { h: 50 }, 1: { ah: Number.NaN } } })).toBe(false);
+ expect(testBed.sheet.save()).toEqual(snapshot);
+ });
+});
diff --git a/packages/sheets/src/commands/mutations/__tests__/set-col-data.mutation.spec.ts b/packages/sheets/src/commands/mutations/__tests__/set-col-data.mutation.spec.ts
new file mode 100644
index 0000000000..2226d1778c
--- /dev/null
+++ b/packages/sheets/src/commands/mutations/__tests__/set-col-data.mutation.spec.ts
@@ -0,0 +1,57 @@
+/**
+ * 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 { ICommandService } from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { SetColDataMutation, SetColDataMutationFactory } from '../set-col-data.mutation';
+import { createCommandTestBed } from './create-command-test-bed';
+
+describe('col data dimension validation', () => {
+ let testBed: ReturnType<typeof createCommandTestBed>;
+
+ beforeEach(() => {
+ testBed = createCommandTestBed();
+ testBed.get(ICommandService).registerCommand(SetColDataMutation);
+ });
+
+ afterEach(() => testBed.univer.dispose());
+
+ it.each([-1, Number.NaN, Number.POSITIVE_INFINITY])('rejects a bad dimension %s before applying other properties', (value) => {
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const snapshot = testBed.sheet.save();
+ expect(testBed.get(ICommandService).syncExecuteCommand(SetColDataMutation.id, {
+ unitId: testBed.sheet.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ columnData: { 0: { w: 50.5 }, 1: { w: value } },
+ })).toBe(false);
+ expect(testBed.sheet.save()).toEqual(snapshot);
+ });
+
+ it('preserves undo patches that clear an optional dimension', () => {
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const commandService = testBed.get(ICommandService);
+ const params = {
+ unitId: testBed.sheet.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ columnData: { 0: { w: 50.5 } },
+ };
+ const snapshot = testBed.sheet.save();
+ const undo = SetColDataMutationFactory(params, worksheet);
+ expect(commandService.syncExecuteCommand(SetColDataMutation.id, params)).toBe(true);
+ expect(commandService.syncExecuteCommand(SetColDataMutation.id, undo)).toBe(true);
+ expect(testBed.sheet.save()).toEqual(snapshot);
+ });
+});
diff --git a/packages/sheets/src/commands/mutations/__tests__/set-row-data.mutation.spec.ts b/packages/sheets/src/commands/mutations/__tests__/set-row-data.mutation.spec.ts
new file mode 100644
index 0000000000..51766b5618
--- /dev/null
+++ b/packages/sheets/src/commands/mutations/__tests__/set-row-data.mutation.spec.ts
@@ -0,0 +1,57 @@
+/**
+ * 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 { ICommandService } from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { SetRowDataMutation, SetRowDataMutationFactory } from '../set-row-data.mutation';
+import { createCommandTestBed } from './create-command-test-bed';
+
+describe('row data dimension validation', () => {
+ let testBed: ReturnType<typeof createCommandTestBed>;
+
+ beforeEach(() => {
+ testBed = createCommandTestBed();
+ testBed.get(ICommandService).registerCommand(SetRowDataMutation);
+ });
+
+ afterEach(() => testBed.univer.dispose());
+
+ it.each([-1, Number.NaN, Number.POSITIVE_INFINITY])('rejects a bad dimension %s before applying other properties', (value) => {
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const snapshot = testBed.sheet.save();
+ expect(testBed.get(ICommandService).syncExecuteCommand(SetRowDataMutation.id, {
+ unitId: testBed.sheet.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ rowData: { 0: { h: 50.5 }, 1: { h: value } },
+ })).toBe(false);
+ expect(testBed.sheet.save()).toEqual(snapshot);
+ });
+
+ it('preserves undo patches that clear an optional dimension', () => {
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const commandService = testBed.get(ICommandService);
+ const params = {
+ unitId: testBed.sheet.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ rowData: { 0: { h: 50.5 } },
+ };
+ const snapshot = testBed.sheet.save();
+ const undo = SetRowDataMutationFactory(params, worksheet);
+ expect(commandService.syncExecuteCommand(SetRowDataMutation.id, params)).toBe(true);
+ expect(commandService.syncExecuteCommand(SetRowDataMutation.id, undo)).toBe(true);
+ expect(testBed.sheet.save()).toEqual(snapshot);
+ });
+});
diff --git a/packages/sheets/src/commands/mutations/__tests__/set-worksheet-col-width.mutation.spec.ts b/packages/sheets/src/commands/mutations/__tests__/set-worksheet-col-width.mutation.spec.ts
new file mode 100644
index 0000000000..b36cf4ddb7
--- /dev/null
+++ b/packages/sheets/src/commands/mutations/__tests__/set-worksheet-col-width.mutation.spec.ts
@@ -0,0 +1,50 @@
+/**
+ * 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 { ICommandService } from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { SetWorksheetColWidthMutation } from '../set-worksheet-col-width.mutation';
+import { createCommandTestBed } from './create-command-test-bed';
+
+describe('col-width mutation validation', () => {
+ let testBed: ReturnType<typeof createCommandTestBed>;
+
+ beforeEach(() => {
+ testBed = createCommandTestBed();
+ testBed.get(ICommandService).registerCommand(SetWorksheetColWidthMutation);
+ });
+
+ afterEach(() => testBed.univer.dispose());
+
+ it.each([-1, Number.NaN, Number.POSITIVE_INFINITY, '90', null, undefined, false, ''])(
+ 'rejects invalid size %s atomically for scalar and batch mutations',
+ (value) => {
+ const commandService = testBed.get(ICommandService);
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const params = {
+ unitId: testBed.sheet.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ ranges: [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }],
+ };
+ const snapshot = testBed.sheet.save();
+ const sizesToCheck = value == null ? [value] : [value, { 0: 90.5, 1: value }];
+ for (const sizes of sizesToCheck) {
+ expect(commandService.syncExecuteCommand(SetWorksheetColWidthMutation.id, { ...params, colWidth: sizes })).toBe(false);
+ expect(testBed.sheet.save()).toEqual(snapshot);
+ }
+ }
+ );
+});
diff --git a/packages/sheets/src/commands/mutations/__tests__/set-worksheet-row-height.mutation.spec.ts b/packages/sheets/src/commands/mutations/__tests__/set-worksheet-row-height.mutation.spec.ts
new file mode 100644
index 0000000000..c0f1ed05ba
--- /dev/null
+++ b/packages/sheets/src/commands/mutations/__tests__/set-worksheet-row-height.mutation.spec.ts
@@ -0,0 +1,62 @@
+/**
+ * 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 { ICommandService } from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { SetWorksheetRowAutoHeightMutation, SetWorksheetRowHeightMutation } from '../set-worksheet-row-height.mutation';
+import { createCommandTestBed } from './create-command-test-bed';
+
+describe('row-height mutation validation', () => {
+ let testBed: ReturnType<typeof createCommandTestBed>;
+
+ beforeEach(() => {
+ testBed = createCommandTestBed();
+ testBed.get(ICommandService).registerCommand(SetWorksheetRowHeightMutation);
+ testBed.get(ICommandService).registerCommand(SetWorksheetRowAutoHeightMutation);
+ });
+
+ afterEach(() => testBed.univer.dispose());
+
+ it.each([-1, Number.NaN, Number.POSITIVE_INFINITY, '90', null, undefined, false, ''])(
+ 'rejects invalid size %s atomically for scalar and batch mutations',
+ (value) => {
+ const commandService = testBed.get(ICommandService);
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const params = {
+ unitId: testBed.sheet.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ ranges: [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }],
+ };
+ const snapshot = testBed.sheet.save();
+ const sizesToCheck = value == null ? [value] : [value, { 0: 90.5, 1: value }];
+ for (const sizes of sizesToCheck) {
+ expect(commandService.syncExecuteCommand(SetWorksheetRowHeightMutation.id, { ...params, rowHeight: sizes })).toBe(false);
+ expect(testBed.sheet.save()).toEqual(snapshot);
+ }
+ }
+ );
+
+ it('rejects invalid automatic heights without partially changing rows', () => {
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const snapshot = testBed.sheet.save();
+ expect(testBed.get(ICommandService).syncExecuteCommand(SetWorksheetRowAutoHeightMutation.id, {
+ unitId: testBed.sheet.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ rowsAutoHeightInfo: [{ row: 0, autoHeight: 30 }, { row: 1, autoHeight: Number.POSITIVE_INFINITY }],
+ })).toBe(false);
+ expect(testBed.sheet.save()).toEqual(snapshot);
+ });
+});
diff --git a/packages/sheets/src/commands/mutations/insert-row-col.mutation.ts b/packages/sheets/src/commands/mutations/insert-row-col.mutation.ts
index 5831c5ebd5..591004d134 100644
--- a/packages/sheets/src/commands/mutations/insert-row-col.mutation.ts
+++ b/packages/sheets/src/commands/mutations/insert-row-col.mutation.ts
@@ -15,13 +15,13 @@
*/
import type { IAccessor, IMutation } from '@univerjs/core';
+import { CommandType, isValidColumnDimensions, isValidRowDimensions, IUniverInstanceService } from '@univerjs/core';
import type {
IInsertColMutationParams,
IInsertRowMutationParams,
IRemoveColMutationParams,
IRemoveRowsMutationParams,
} from '../../basics/interfaces/mutation-interface';
-import { CommandType, IUniverInstanceService } from '@univerjs/core';
import { getSheetMutationTarget } from '../commands/utils/target-util';
export const InsertRowMutationUndoFactory = (
@@ -52,6 +52,9 @@ export const InsertRowMutation: IMutation<IInsertRowMutationParams> = {
const { worksheet } = target;
const rowManager = worksheet.getRowManager();
const { range, rowInfo } = params;
+ if (rowInfo && !Object.values(rowInfo).every(isValidRowDimensions)) {
+ return false;
+ }
const { startRow, endRow } = range;
// insert row data
@@ -92,11 +95,14 @@ export const InsertColMutation: IMutation<IInsertColMutationParams> = {
const target = getSheetMutationTarget(accessor.get(IUniverInstanceService), params);
if (!target) {
throw new Error('Workbook or Worksheet not found at InsertColMutation');
- };
+ }
const { worksheet } = target;
const columnManager = worksheet.getColumnManager();
const { range, colInfo } = params;
+ if (colInfo && !Object.values(colInfo).every(isValidColumnDimensions)) {
+ return false;
+ }
const { startColumn, endColumn } = range;
// insert column data
diff --git a/packages/sheets/src/commands/mutations/set-col-data.mutation.ts b/packages/sheets/src/commands/mutations/set-col-data.mutation.ts
index 0d64aa0322..a334d0f35b 100644
--- a/packages/sheets/src/commands/mutations/set-col-data.mutation.ts
+++ b/packages/sheets/src/commands/mutations/set-col-data.mutation.ts
@@ -15,7 +15,7 @@
*/
import type { IColumnData, IMutation, IObjectArrayPrimitiveType, Nullable, Worksheet } from '@univerjs/core';
-import { CommandType, IUniverInstanceService } from '@univerjs/core';
+import { CommandType, isValidColumnDimensions, IUniverInstanceService } from '@univerjs/core';
import { getOldColumnData } from '../../basics/row-column-value';
import { getSheetCommandTarget } from '../commands/utils/target-util';
@@ -54,9 +54,14 @@ export const SetColDataMutation: IMutation<ISetColDataMutationParams> = {
type: CommandType.MUTATION,
handler: (accessor, params) => {
const { columnData } = params;
+ if (!Object.values(columnData).every(isValidColumnDimensions)) {
+ return false;
+ }
const univerInstanceService = accessor.get(IUniverInstanceService);
const target = getSheetCommandTarget(univerInstanceService, params);
- if (!target) return false;
+ if (!target) {
+ return false;
+ }
const { worksheet } = target;
const manager = worksheet.getColumnManager();
diff --git a/packages/sheets/src/commands/mutations/set-row-data.mutation.ts b/packages/sheets/src/commands/mutations/set-row-data.mutation.ts
index eff9ac80a0..59c950abe2 100644
--- a/packages/sheets/src/commands/mutations/set-row-data.mutation.ts
+++ b/packages/sheets/src/commands/mutations/set-row-data.mutation.ts
@@ -15,7 +15,7 @@
*/
import type { IMutation, IObjectArrayPrimitiveType, IRowData, Nullable, Worksheet } from '@univerjs/core';
-import { CommandType, IUniverInstanceService } from '@univerjs/core';
+import { CommandType, isValidRowDimensions, IUniverInstanceService } from '@univerjs/core';
import { getOldRowData } from '../../basics/row-column-value';
import { getSheetCommandTarget } from '../commands/utils/target-util';
@@ -54,9 +54,14 @@ export const SetRowDataMutation: IMutation<ISetRowDataMutationParams> = {
type: CommandType.MUTATION,
handler: (accessor, params) => {
const { rowData } = params;
+ if (!Object.values(rowData).every(isValidRowDimensions)) {
+ return false;
+ }
const univerInstanceService = accessor.get(IUniverInstanceService);
const target = getSheetCommandTarget(univerInstanceService, params);
- if (!target) return false;
+ if (!target) {
+ return false;
+ }
const { worksheet } = target;
const manager = worksheet.getRowManager();
diff --git a/packages/sheets/src/commands/mutations/set-worksheet-col-width.mutation.ts b/packages/sheets/src/commands/mutations/set-worksheet-col-width.mutation.ts
index e5814ab21e..41a9403596 100644
--- a/packages/sheets/src/commands/mutations/set-worksheet-col-width.mutation.ts
+++ b/packages/sheets/src/commands/mutations/set-worksheet-col-width.mutation.ts
@@ -15,8 +15,7 @@
*/
import type { IMutation, IObjectArrayPrimitiveType, IRange, Nullable, Worksheet } from '@univerjs/core';
-import { CommandType, IUniverInstanceService, Tools } from '@univerjs/core';
-
+import { CommandType, isValidSheetDimension, IUniverInstanceService, Tools } from '@univerjs/core';
import { getSheetCommandTarget } from '../commands/utils/target-util';
export interface ISetWorksheetColWidthMutationParams {
@@ -64,7 +63,17 @@ export const SetWorksheetColWidthMutation: IMutation<ISetWorksheetColWidthMutati
handler: (accessor, params) => {
const univerInstanceService = accessor.get(IUniverInstanceService);
const target = getSheetCommandTarget(univerInstanceService, params);
- if (!target) return false;
+ if (!target) {
+ return false;
+ }
+
+ const dimensions = params.colWidth;
+ if (typeof dimensions === 'number'
+ ? !isValidSheetDimension(dimensions)
+ : dimensions == null || typeof dimensions !== 'object' ||
+ Object.values(dimensions).some((value) => value != null && !isValidSheetDimension(value))) {
+ return false;
+ }
const { worksheet } = target;
const manager = worksheet.getColumnManager();
@@ -74,7 +83,9 @@ export const SetWorksheetColWidthMutation: IMutation<ISetWorksheetColWidthMutati
const range = ranges[i];
for (let j = range.startColumn; j < range.endColumn + 1; j++) {
const visible = worksheet.getColVisible(j);
- if (!visible) continue;
+ if (!visible) {
+ continue;
+ }
if (typeof params.colWidth === 'number') {
manager.setColumnWidth(j, params.colWidth);
} else if (Tools.isDefine(params.colWidth[j])) {
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.ts
index 4b83db8343..bab9d5ec30 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,16 @@
* limitations under the License.
*/
-import type { BooleanNumber, IMutation, IObjectArrayPrimitiveType, IRange, IRowAutoHeightInfo, Nullable, Worksheet } from '@univerjs/core';
-import { CommandType, IUniverInstanceService, Tools } from '@univerjs/core';
+import type {
+ BooleanNumber,
+ IMutation,
+ IObjectArrayPrimitiveType,
+ IRange,
+ IRowAutoHeightInfo,
+ Nullable,
+ Worksheet,
+} from '@univerjs/core';
+import { CommandType, isValidSheetDimension, IUniverInstanceService, Tools } from '@univerjs/core';
import { getSheetCommandTarget } from '../commands/utils/target-util';
export interface ISetWorksheetRowHeightMutationParams {
@@ -114,7 +122,17 @@ export const SetWorksheetRowHeightMutation: IMutation<ISetWorksheetRowHeightMuta
const { ranges, rowHeight } = params;
const univerInstanceService = accessor.get(IUniverInstanceService);
const target = getSheetCommandTarget(univerInstanceService, params);
- if (!target) return false;
+ if (!target) {
+ return false;
+ }
+
+ const dimensions = params.rowHeight;
+ if (typeof dimensions === 'number'
+ ? !isValidSheetDimension(dimensions)
+ : dimensions == null || typeof dimensions !== 'object' ||
+ Object.values(dimensions).some((value) => value != null && !isValidSheetDimension(value))) {
+ return false;
+ }
const { worksheet } = target;
const manager = worksheet.getRowManager();
@@ -140,7 +158,9 @@ export const SetWorksheetRowIsAutoHeightMutation: IMutation<ISetWorksheetRowIsAu
const { ranges, autoHeightInfo } = params;
const univerInstanceService = accessor.get(IUniverInstanceService);
const target = getSheetCommandTarget(univerInstanceService, params);
- if (!target) return false;
+ if (!target) {
+ return false;
+ }
const manager = target.worksheet.getRowManager();
for (const { startRow, endRow } of ranges) {
@@ -164,9 +184,14 @@ export const SetWorksheetRowAutoHeightMutation: IMutation<ISetWorksheetRowAutoHe
type: CommandType.MUTATION,
handler: (accessor, params) => {
const { rowsAutoHeightInfo } = params;
+ if (rowsAutoHeightInfo.some(({ autoHeight }) => autoHeight != null && !isValidSheetDimension(autoHeight))) {
+ return false;
+ }
const univerInstanceService = accessor.get(IUniverInstanceService);
const target = getSheetCommandTarget(univerInstanceService, params);
- if (!target) return false;
+ if (!target) {
+ return false;
+ }
const rowManager = target.worksheet.getRowManager();
diff --git a/packages/thread-comment-ui/src/views/ThreadCommentPanel.tsx b/packages/thread-comment-ui/src/views/ThreadCommentPanel.tsx
index 49beea5940..cf74cad5b6 100644
--- a/packages/thread-comment-ui/src/views/ThreadCommentPanel.tsx
+++ b/packages/thread-comment-ui/src/views/ThreadCommentPanel.tsx
@@ -17,15 +17,15 @@
import type { Nullable } from '@univerjs/core';
import type { IThreadComment } from '@univerjs/thread-comment';
import type { Observable } from 'rxjs';
-import type { LocaleKey } from '../locale/types';
-import type { ThreadCommentPanelSection } from './thread-comment-panel/util';
-import type { IThreadCommentTreeProps } from './ThreadCommentTree';
import { ICommandService, LocaleService, UniverInstanceType, UserManagerService } from '@univerjs/core';
import { ActionRow, Button, Select } from '@univerjs/design';
import { IncreaseIcon } from '@univerjs/icons';
import { ThreadCommentModel } from '@univerjs/thread-comment';
import { useDependency, useObservable } from '@univerjs/ui';
import { useEffect, useMemo, useRef, useState } from 'react';
+import type { LocaleKey } from '../locale/types';
+import type { ThreadCommentPanelSection } from './thread-comment-panel/util';
+import type { IThreadCommentTreeProps } from './ThreadCommentTree';
import { SetActiveCommentOperation } from '../commands/operations/comment.operations';
import { ThreadCommentPanelService } from '../services/thread-comment-panel.service';
import { getThreadCommentPanelItemKey, isSameThreadCommentTarget, shouldClearThreadCommentTarget } from './thread-comment-panel/util';
@@ -181,11 +181,14 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {
return;
}
- const activeElement = document.getElementById(
- `${location}-${activeComment.unitId}-${activeComment.subUnitId}-${activeComment.commentId}`
- );
+ const isInsideActiveComment = Object.values(ThreadCommentTreeLocation).some((commentLocation) => {
+ const activeElement = document.getElementById(
+ `${commentLocation}-${activeComment.unitId}-${activeComment.subUnitId}-${activeComment.commentId}`
+ );
+ return activeElement?.contains(target);
+ });
if (
- activeElement?.contains(target) ||
+ isInsideActiveComment ||
target.closest('button, input, textarea, select, a, [contenteditable="true"], [role="menu"], [role="menuitem"], [role="option"], [role="listbox"], [role="combobox"], [role="separator"]')
) {
return;
@@ -199,7 +202,7 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {
document.addEventListener('pointerdown', handlePointerDown, true);
return () => document.removeEventListener('pointerdown', handlePointerDown, true);
- }, [activeCommentId, commandService, location, onTempCommentClose, panelService, scopedTempComment]);
+ }, [activeCommentId, commandService, onTempCommentClose, panelService, scopedTempComment]);
useEffect(() => {
if (!activeCommentId) {
diff --git a/packages/thread-comment-ui/src/views/__tests__/ThreadCommentPanel.spec.tsx b/packages/thread-comment-ui/src/views/__tests__/ThreadCommentPanel.spec.tsx
index 5297a2ca7c..f797e43921 100644
--- a/packages/thread-comment-ui/src/views/__tests__/ThreadCommentPanel.spec.tsx
+++ b/packages/thread-comment-ui/src/views/__tests__/ThreadCommentPanel.spec.tsx
@@ -66,6 +66,7 @@ import { ThreadCommentPanelService } from '../../services/thread-comment-panel.s
import { MobileThreadCommentPanel } from '../mobile/MobileThreadCommentPanel';
import { transformTextNodes2Document } from '../thread-comment-editor/util';
import { ThreadCommentPanel } from '../ThreadCommentPanel';
+import { ThreadCommentTree, ThreadCommentTreeLocation } from '../ThreadCommentTree';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -685,6 +686,54 @@ describe('ThreadCommentPanel', () => {
expect(testBed.panelService.activeCommentId).toBeUndefined();
});
+ it.each([
+ { unitId: UNIT_ID, subUnitId: SHEET_ID, id: 'open-thread', keepsActive: true },
+ { unitId: 'other-unit', subUnitId: SHEET_ID, id: 'open-thread', keepsActive: false },
+ { unitId: UNIT_ID, subUnitId: 'other-sheet', id: 'open-thread', keepsActive: false },
+ { unitId: UNIT_ID, subUnitId: SHEET_ID, id: 'other-thread', keepsActive: false },
+ ])('handles editor canvas clicks in cell popup $unitId/$subUnitId/$id', (popup) => {
+ const testBed = createPanelTestBed();
+ addRootComment(testBed.threadCommentModel, createComment({ id: 'open-thread', ref: 'A1' }));
+ ({ container, root } = renderPanel(
+ testBed.injector,
+ <>
+ <ThreadCommentPanel
+ unitId={UNIT_ID}
+ subUnitId$={new BehaviorSubject<string | undefined>(SHEET_ID)}
+ type={UniverInstanceType.UNIVER_SHEET}
+ onAdd={() => undefined}
+ getSubUnitName={(subUnitId) => subUnitId}
+ />
+ <ThreadCommentTree
+ unitId={popup.unitId}
+ subUnitId={popup.subUnitId}
+ id={popup.id}
+ location={ThreadCommentTreeLocation.CELL}
+ type={UniverInstanceType.UNIVER_SHEET}
+ getSubUnitName={(subUnitId) => subUnitId}
+ />
+ </>
+ ));
+ act(() => {
+ getPanelItem(container!, 'open-thread').click();
+ });
+ const activeComment = testBed.panelService.activeCommentId;
+ expect(activeComment?.commentId).toBe('open-thread');
+
+ const popupElement = document.getElementById(
+ `${ThreadCommentTreeLocation.CELL}-${popup.unitId}-${popup.subUnitId}-${popup.id}`
+ );
+ expect(popupElement).not.toBeNull();
+ // The editor service boundary does not create a renderer canvas in this test.
+ const canvas = document.createElement('canvas');
+ popupElement!.appendChild(canvas);
+ act(() => {
+ canvas.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true, button: 0 }));
+ });
+
+ expect(testBed.panelService.activeCommentId).toEqual(popup.keepsActive ? activeComment : undefined);
+ });
+
it('clears the active comment when the primary pointer hits a blank area', () => {
const testBed = createPanelTestBed();
addRootComment(testBed.threadCommentModel, createComment({ id: 'open-thread', ref: 'A1' }));