Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
revert: "feat(sheets): add compress for set-worksheet-col-width & row-height" (#6192)
WEI ZHANG386e68937a99
diff --git a/packages/sheets-ui/src/controllers/auto-width.controller.ts b/packages/sheets-ui/src/controllers/auto-width.controller.tsindex 50428dfc43..3b4bd824cf 100644--- a/packages/sheets-ui/src/controllers/auto-width.controller.ts+++ b/packages/sheets-ui/src/controllers/auto-width.controller.ts@@ -24,7 +24,6 @@ import { Disposable, Inject, IUniverInstanceService } from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';import {getSheetCommandTarget,- packNumberMap,SetWorksheetColWidthMutation,} from '@univerjs/sheets';import { SheetSkeletonManagerService } from '../services/sheet-skeleton-manager.service';@@ -50,7 +49,7 @@ export const createAutoColWidthUndoMutationsByRedos = (unitId,subUnitId,ranges,- colWidth: { compress: true, data: packNumberMap(colWidthObj as Record<string, number>) },+ colWidth: colWidthObj,};};@@ -85,7 +84,7 @@ export class AutoWidthController extends Disposable {subUnitId,unitId,ranges: params.ranges,- colWidth: { compress: true, data: packNumberMap(colWidthObject as Record<string, number>) },+ colWidth: colWidthObject,};const undoParams: ISetWorksheetColWidthMutationParams = createAutoColWidthUndoMutationsByRedos(redoParams, worksheet);return {diff --git a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.tsindex d9dfd81e3b..42ca6fc940 100644--- a/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts+++ b/packages/sheets-ui/src/controllers/clipboard/clipboard.controller.ts@@ -79,7 +79,6 @@ import {MoveColsMutation,MoveRangeMutation,MoveRowsMutation,- packNumberMap,RemoveColMutation,RemoveRowMutation,SetRangeValuesMutation,@@ -451,7 +450,7 @@ export class SheetClipboardController extends RxDisposable {startColumn: range.cols[0],endColumn: range.cols[range.cols.length - 1],}],- rowHeight: { compress: true, data: packNumberMap(rowHeight) },+ rowHeight,};redoMutations.push({id: SetWorksheetRowHeightMutation.id,@@ -462,7 +461,7 @@ export class SheetClipboardController extends RxDisposable {id: SetWorksheetRowHeightMutation.id,params: {...setRowPropertyMutation,- rowHeight: { compress: true, data: packNumberMap(originRowHeight) },+ rowHeight: originRowHeight,},});}@@ -533,26 +532,24 @@ export class SheetClipboardController extends RxDisposable {// apply col properties to the existing rowsif (colProperties.length > 0) {- const colWidth = colProperties- .slice(0, existingColsCount)- .reduce((p, c, index) => {- p[index + startColumn] = c.width ? Math.max(+c.width, currentSheet!.getColumnWidth(pasteToCols[index]) ?? defaultColumnWidth) : defaultColumnWidth;- return p;- }, {} as IObjectArrayPrimitiveType<number>);const setColPropertyMutation: ISetWorksheetColWidthMutationParams = {...targetSetColPropertyParams,- colWidth: { compress: true, data: packNumberMap(colWidth) },+ colWidth: colProperties+ .slice(0, existingColsCount)+ .reduce((p, c, index) => {+ p[index + startColumn] = c.width ? Math.max(+c.width, currentSheet!.getColumnWidth(pasteToCols[index]) ?? defaultColumnWidth) : defaultColumnWidth;+ return p;+ }, {} as IObjectArrayPrimitiveType<number>),};- const undoColWidth = colProperties- .slice(0, existingColsCount)- .reduce((p, c, index) => {- p[index + startColumn] = currentSheet!.getColumnWidth(pasteToCols[index]) ?? defaultColumnWidth;- return p;- }, {} as IObjectArrayPrimitiveType<Nullable<number>>);const undoSetColPropertyParams: ISetWorksheetColWidthMutationParams = {...targetSetColPropertyParams,- colWidth: { compress: true, data: packNumberMap(undoColWidth as Record<string, number>) },+ colWidth: colProperties+ .slice(0, existingColsCount)+ .reduce((p, c, index) => {+ p[index + startColumn] = currentSheet!.getColumnWidth(pasteToCols[index]) ?? defaultColumnWidth;+ return p;+ }, {} as IObjectArrayPrimitiveType<Nullable<number>>),};redoMutations.push({@@ -796,12 +793,6 @@ export class SheetClipboardController extends RxDisposable {const existingColsCount = colProperties.length - addingColsCount;const defaultColumnWidth = self._configService.getConfig<number>(DEFAULT_WORKSHEET_COLUMN_WIDTH_KEY) ?? DEFAULT_WORKSHEET_COLUMN_WIDTH;- const colWidth = colProperties- .slice(0, existingColsCount)- .reduce((p, c, index) => {- p[index + startColumn] = c.width ? Math.max(+c.width, currentSheet!.getColumnWidth(pasteToCols[index]) ?? defaultColumnWidth) : defaultColumnWidth;- return p;- }, {} as IObjectArrayPrimitiveType<number>);const setColPropertyMutation: ISetWorksheetColWidthMutationParams = {unitId: unitId!,subUnitId: subUnitId!,@@ -811,15 +802,14 @@ export class SheetClipboardController extends RxDisposable {startColumn: range.cols[0],endColumn: range.cols[range.cols.length - 1],}],- colWidth: { compress: true, data: packNumberMap(colWidth) },+ colWidth: colProperties+ .slice(0, existingColsCount)+ .reduce((p, c, index) => {+ p[index + startColumn] = c.width ? Math.max(+c.width, currentSheet!.getColumnWidth(pasteToCols[index]) ?? defaultColumnWidth) : defaultColumnWidth;+ return p;+ }, {} as IObjectArrayPrimitiveType<number>),};- const undoColWidth = colProperties- .slice(0, existingColsCount)- .reduce((p, c, index) => {- p[index + startColumn] = currentSheet!.getColumnWidth(pasteToCols[index]) ?? defaultColumnWidth;- return p;- }, {} as IObjectArrayPrimitiveType<Nullable<number>>);const undoSetColPropertyMutation: ISetWorksheetColWidthMutationParams = {unitId: unitId!,subUnitId: subUnitId!,@@ -829,7 +819,12 @@ export class SheetClipboardController extends RxDisposable {startColumn: range.cols[0],endColumn: range.cols[range.cols.length - 1],}],- colWidth: { compress: true, data: packNumberMap(undoColWidth as Record<string, number>) },+ colWidth: colProperties+ .slice(0, existingColsCount)+ .reduce((p, c, index) => {+ p[index + startColumn] = currentSheet!.getColumnWidth(pasteToCols[index]) ?? defaultColumnWidth;+ return p;+ }, {} as IObjectArrayPrimitiveType<Nullable<number>>),};redoMutations.push({diff --git a/packages/sheets/src/commands/mutations/__tests__/packed-number-map-mutation.spec.ts b/packages/sheets/src/commands/mutations/__tests__/packed-number-map-mutation.spec.tsdeleted file mode 100644index 40507bb4d9..0000000000--- a/packages/sheets/src/commands/mutations/__tests__/packed-number-map-mutation.spec.ts+++ /dev/null@@ -1,108 +0,0 @@-/**- * 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 { Injector, Workbook } from '@univerjs/core';-import type { ISetWorksheetColWidthMutationParams } from '../set-worksheet-col-width.mutation';-import type { ISetWorksheetRowHeightMutationParams } from '../set-worksheet-row-height.mutation';--import { ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import { createCommandTestBed } from '../../commands/__tests__/create-command-test-bed';-import { packNumberMap } from '../../utils/pack-number-map';-import { SetWorksheetColWidthMutation } from '../set-worksheet-col-width.mutation';-import { SetWorksheetRowHeightMutation } from '../set-worksheet-row-height.mutation';--describe('Test packed number map mutations', () => {- let univer: any;- let get: Injector['get'];- let commandService: ICommandService;-- beforeEach(() => {- const testBed = createCommandTestBed();- univer = testBed.univer;- get = testBed.get;-- commandService = get(ICommandService);- commandService.registerCommand(SetWorksheetColWidthMutation);- commandService.registerCommand(SetWorksheetRowHeightMutation);- });-- afterEach(() => univer.dispose());-- function getWorksheet() {- return get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()!;- }-- it('Should support PackedNumberMap in SetWorksheetColWidthMutation', () => {- const worksheet = getWorksheet();- const unitId = 'test';- const subUnitId = 'sheet1';-- // Initial check- expect(worksheet.getColumnWidth(0)).toBe(88); // Default width-- // Prepare packed data- const colWidths = {- 0: 100,- 1: 200,- 2: 100,- };- const packed = packNumberMap(colWidths);-- const params: ISetWorksheetColWidthMutationParams = {- unitId,- subUnitId,- ranges: [{ startRow: 0, endRow: 10, startColumn: 0, endColumn: 2 }],- colWidth: { compress: true, data: packed },- };-- commandService.syncExecuteCommand(SetWorksheetColWidthMutation.id, params);-- expect(worksheet.getColumnWidth(0)).toBe(100);- expect(worksheet.getColumnWidth(1)).toBe(200);- expect(worksheet.getColumnWidth(2)).toBe(100);- });-- it('Should support PackedNumberMap in SetWorksheetRowHeightMutation', () => {- const worksheet = getWorksheet();- const unitId = 'test';- const subUnitId = 'sheet1';-- // Initial check- expect(worksheet.getRowHeight(0)).toBe(24); // Default height (assuming 24, check default config if fails)-- // Prepare packed data- const rowHeights = {- 0: 50,- 1: 60,- 2: 50,- };- const packed = packNumberMap(rowHeights);-- const params: ISetWorksheetRowHeightMutationParams = {- unitId,- subUnitId,- ranges: [{ startRow: 0, endRow: 2, startColumn: 0, endColumn: 10 }],- rowHeight: { compress: true, data: packed },- };-- commandService.syncExecuteCommand(SetWorksheetRowHeightMutation.id, params);-- expect(worksheet.getRowHeight(0)).toBe(50);- expect(worksheet.getRowHeight(1)).toBe(60);- expect(worksheet.getRowHeight(2)).toBe(50);- });-});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.tsindex 3126e56619..e5814ab21e 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,17 +15,15 @@*/import type { IMutation, IObjectArrayPrimitiveType, IRange, Nullable, Worksheet } from '@univerjs/core';-import type { PackedNumberMap } from '../utils/pack-number-map';-import { CommandType, IUniverInstanceService, Tools } from '@univerjs/core';+import { getSheetCommandTarget } from '../commands/utils/target-util';-import { packNumberMap, unpackNumberMap } from '../utils/pack-number-map';export interface ISetWorksheetColWidthMutationParams {unitId: string;subUnitId: string;ranges: IRange[];- colWidth: number | IObjectArrayPrimitiveType<Nullable<number>> | { compress: true; data: PackedNumberMap };+ colWidth: number | IObjectArrayPrimitiveType<Nullable<number>>;}/**@@ -53,7 +51,7 @@ export const SetWorksheetColWidthMutationFactory = (unitId,subUnitId,ranges,- colWidth: { compress: true, data: packNumberMap(colWidth as Record<string, number>) },+ colWidth,};};@@ -79,12 +77,6 @@ export const SetWorksheetColWidthMutation: IMutation<ISetWorksheetColWidthMutatiif (!visible) continue;if (typeof params.colWidth === 'number') {manager.setColumnWidth(j, params.colWidth);- } else if (params.colWidth && typeof params.colWidth === 'object' && 'compress' in params.colWidth) {- const { data } = params.colWidth;- const map = unpackNumberMap(data);- if (Tools.isDefine(map[j])) {- manager.setColumnWidth(j, map[j]);- }} else if (Tools.isDefine(params.colWidth[j])) {manager.setColumnWidth(j, params.colWidth[j] as number);}diff --git a/packages/sheets/src/commands/mutations/set-worksheet-row-height.mutation.ts b/packages/sheets/src/commands/mutations/set-worksheet-row-height.mutation.tsindex 042184d564..4b83db8343 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@@ -15,16 +15,14 @@*/import type { BooleanNumber, IMutation, IObjectArrayPrimitiveType, IRange, IRowAutoHeightInfo, Nullable, Worksheet } from '@univerjs/core';-import type { PackedNumberMap } from '../utils/pack-number-map';import { CommandType, IUniverInstanceService, Tools } from '@univerjs/core';import { getSheetCommandTarget } from '../commands/utils/target-util';-import { packNumberMap, unpackNumberMap } from '../utils/pack-number-map';export interface ISetWorksheetRowHeightMutationParams {unitId: string;subUnitId: string;ranges: IRange[];- rowHeight: number | IObjectArrayPrimitiveType<Nullable<number>> | { compress: true; data: PackedNumberMap };+ rowHeight: number | IObjectArrayPrimitiveType<Nullable<number>>;}export interface ISetWorksheetRowIsAutoHeightMutationParams {@@ -59,7 +57,7 @@ export const SetWorksheetRowHeightMutationFactory = (unitId,subUnitId,ranges,- rowHeight: { compress: true, data: packNumberMap(rowHeight) },+ rowHeight,};};@@ -125,12 +123,6 @@ export const SetWorksheetRowHeightMutation: IMutation<ISetWorksheetRowHeightMutafor (let rowIndex = startRow; rowIndex <= endRow; rowIndex++) {if (typeof rowHeight === 'number') {manager.setRowHeight(rowIndex, rowHeight);- } else if (rowHeight && typeof rowHeight === 'object' && 'compress' in rowHeight) {- const { data } = rowHeight;- const map = unpackNumberMap(data);- if (Tools.isDefine(map[rowIndex])) {- manager.setRowHeight(rowIndex, map[rowIndex]);- }} else if (Tools.isDefine(rowHeight[rowIndex])) {manager.setRowHeight(rowIndex, rowHeight[rowIndex] as number);}diff --git a/packages/sheets/src/commands/utils/__tests__/pack-number-map.spec.ts b/packages/sheets/src/commands/utils/__tests__/pack-number-map.spec.tsdeleted file mode 100644index 13c5a6136c..0000000000--- a/packages/sheets/src/commands/utils/__tests__/pack-number-map.spec.ts+++ /dev/null@@ -1,125 +0,0 @@-/**- * 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 { packNumberMap, unpackNumberMap } from '../pack-number-map';--describe('packNumberMap', () => {- it('should return empty object for empty input', () => {- expect(packNumberMap({})).toEqual({});- });-- it('should handle single value', () => {- const input = { 1: 10 };- const expected = { 10: 1 };- expect(packNumberMap(input)).toEqual(expected);- });-- it('should handle multiple values with same value (continuous indices)', () => {- const input = { 1: 10, 2: 10, 3: 10 };- const expected = { 10: [[1, 3]] }; // Optimized to interval wrapped in array- expect(packNumberMap(input)).toEqual(expected);- });-- it('should handle multiple values with same value (discontinuous indices)', () => {- const input = { 1: 10, 3: 10, 5: 10 };- const expected = { 10: [1, 3, 5] }; // List of points- expect(packNumberMap(input)).toEqual(expected);- });-- it('should handle multiple values with different values', () => {- const input = { 1: 10, 2: 20 };- const expected = { 10: 1, 20: 2 };- expect(packNumberMap(input)).toEqual(expected);- });-- it('should handle mixed scenarios (single points and intervals)', () => {- // 1, 2, 3 -> 10 (interval [1, 3])- // 5 -> 10 (point 5)- // 7, 8 -> 10 (interval [7, 8])- const input = { 1: 10, 2: 10, 3: 10, 5: 10, 7: 10, 8: 10 };- const expected = { 10: [[1, 3], 5, [7, 8]] };- expect(packNumberMap(input)).toEqual(expected);- });-- it('should optimize single element array to number', () => {- const input = { 1: 10 };- // Should be 1 instead of [1]- expect(packNumberMap(input)).toEqual({ 10: 1 });- });-});--describe('unpackNumberMap', () => {- it('should return empty object for empty input', () => {- expect(unpackNumberMap({})).toEqual({});- });-- it('should handle single number value (optimized format)', () => {- const input = { 10: 1 };- const expected = { 1: 10 };- expect(unpackNumberMap(input)).toEqual(expected);- });-- it('should handle array with single number', () => {- // Although packNumberMap optimizes this, unpack should still handle it if it occurs- const input = { 10: [1] };- const expected = { 1: 10 };- expect(unpackNumberMap(input as any)).toEqual(expected);- });-- it('should handle array with interval', () => {- const input = { 10: [[1, 3]] };- const expected = { 1: 10, 2: 10, 3: 10 };- expect(unpackNumberMap(input as any)).toEqual(expected);- });-- it('should handle array with mixed numbers and intervals', () => {- const input = { 10: [[1, 3], 5, [7, 8]] };- const expected = {- 1: 10,- 2: 10,- 3: 10,- 5: 10,- 7: 10,- 8: 10,- };- expect(unpackNumberMap(input as any)).toEqual(expected);- });-- it('should verify round-trip consistency', () => {- const original = {- 1: 10,- 2: 10,- 3: 10,- 5: 20,- 7: 10,- 8: 10,- 10: 30,- };- const packed = packNumberMap(original);- const unpacked = unpackNumberMap(packed);-- // Convert keys back to strings for comparison because unpackNumberMap returns string keys- // Wait, unpackNumberMap returns Record<string, number>, but keys in JS objects are always strings.- // packNumberMap takes Record<string, number>.- // Let's check if the keys match.-- // original keys are '1', '2', ...- // unpacked keys should be '1', '2', ...-- expect(unpacked).toEqual(original);- });-});diff --git a/packages/sheets/src/commands/utils/pack-number-map.ts b/packages/sheets/src/commands/utils/pack-number-map.tsdeleted file mode 100644index c1f9f85fe1..0000000000--- a/packages/sheets/src/commands/utils/pack-number-map.ts+++ /dev/null@@ -1,130 +0,0 @@-/**- * 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 { IObjectArrayPrimitiveType, Nullable } from '@univerjs/core';-import { Tools } from '@univerjs/core';--export type IntervalValue = number | [number, number];--export type PackedNumberMap = Record<string, IntervalValue[] | number>;-/**- * Compression function (Map -> PackedNumberMap)- */-export function packNumberMap(originalData: IObjectArrayPrimitiveType<Nullable<number>>): PackedNumberMap {- const result: PackedNumberMap = {};-- // 1. Grouping: Classify data by Value, collect all Indices- // Temporary structure: { "24": [1, 2, 3, 8], "50": [10] }- const groupedByValue: Record<string, number[]> = {};-- // Get all Keys and sort by number size (this is crucial for interval calculation)- const sortedIndices = Object.keys(originalData)- .map(Number)- .sort((a, b) => a - b);-- if (sortedIndices.length === 0) return result;-- for (const idx of sortedIndices) {- const val = originalData[idx];- // Skip null/undefined values- if (!Tools.isDefine(val)) continue;- // Note: Convert value to string as key here- const valStr = String(val);-- if (!groupedByValue[valStr]) {- groupedByValue[valStr] = [];- }- groupedByValue[valStr].push(idx);- }-- // 2. Interval calculation and compression- for (const [val, indices] of Object.entries(groupedByValue)) {- const items: IntervalValue[] = [];-- if (indices.length === 0) continue;-- let start = indices[0];- let prev = start;-- // Traverse indices to find continuous intervals- for (let i = 1; i < indices.length; i++) {- const current = indices[i];-- // If not continuous (current != prev + 1)- if (current !== prev + 1) {- // Push previous result- if (start === prev) {- items.push(start); // Single point- } else {- items.push([start, prev]); // Interval- }- // Reset start point- start = current;- }- prev = current;- }-- // Handle the last segment after the loop ends- if (start === prev) {- items.push(start);- } else {- items.push([start, prev]);- }-- // 3. Extreme compression optimization- // If the result has only one element and it is a number (not an interval), store the number directly and remove the array wrapper- if (items.length === 1 && typeof items[0] === 'number') {- result[val] = items[0];- } else {- result[val] = items;- }- }-- return result;-}--/**- * Unpack function (PackedNumberMap -> Map)- */-export function unpackNumberMap(compactData: PackedNumberMap): IObjectArrayPrimitiveType<number> {- const resultMap: IObjectArrayPrimitiveType<number> = {};-- for (const [valStr, data] of Object.entries(compactData)) {- const value = Number(valStr);-- // Case 1: Extreme compression scenario, data is directly a number (e.g., "50": 31)- if (typeof data === 'number') {- resultMap[data] = value;- continue;- }-- // Case 2: data is an array, containing mixed numbers or intervals- // data type inferred as CompactValue[]- for (const item of data) {- if (Array.isArray(item)) {- // Handle interval [start, end]- const [start, end] = item;- for (let i = start; i <= end; i++) {- resultMap[i] = value;- }- } else {- // Handle single index number- resultMap[item] = value;- }- }- }- return resultMap;-}diff --git a/packages/sheets/src/index.ts b/packages/sheets/src/index.tsindex 59a6a37092..2cc406611b 100644--- a/packages/sheets/src/index.ts+++ b/packages/sheets/src/index.ts@@ -317,7 +317,6 @@ export { handleDeleteRangeMutation } from './commands/utils/handle-range-mutatioexport { getInsertRangeMutations, getRemoveRangeMutations } from './commands/utils/handle-range-mutation';export { handleInsertRangeMutation } from './commands/utils/handle-range-mutation';export { type ISheetCommandSharedParams } from './commands/utils/interface';-export { type IntervalValue, type PackedNumberMap, packNumberMap, unpackNumberMap } from './commands/utils/pack-number-map';export { getSelectionsService } from './commands/utils/selection-command-util';export { type IUniverSheetsConfig } from './controllers/config.schema';export { MAX_CELL_PER_SHEET_KEY } from './controllers/config/config';