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): preserve text values during style updates (#7951)

wpxp123456857062d1228c
diff --git a/packages/sheets/src/commands/commands/__tests__/set-style.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-style.command.spec.ts
index f7de61baf5..b875cb55ea 100644
--- a/packages/sheets/src/commands/commands/__tests__/set-style.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/set-style.command.spec.ts
@@ -14,10 +14,11 @@
* limitations under the License.
*/
-import type { IColorStyle, Injector, ITextDecoration, ITextRotation, Univer, Workbook } from '@univerjs/core';
-import type { ISetStyleCommandParams } from '../set-style.command';
+import type { IColorStyle, Injector, IStyleData, ITextDecoration, ITextRotation, Univer, Workbook } from '@univerjs/core';
import {
BooleanNumber,
+ CellValueType,
+ DEFAULT_TEXT_FORMAT_EXCEL,
FontItalic,
FontWeight,
HorizontalAlign,
@@ -31,7 +32,7 @@ import {
WrapStrategy,
} from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-
+import type { ISetStyleCommandParams } from '../set-style.command';
import { SheetsSelectionsService } from '../../../services/selections/selection.service';
import { InsertSheetMutation } from '../../mutations/insert-sheet.mutation';
import { SetRangeValuesMutation } from '../../mutations/set-range-values.mutation';
@@ -88,6 +89,75 @@ describe("Test commands used for updating cells' styles", () => {
afterEach(() => univer.dispose());
+ it.each<{
+ name: string;
+ commandId: string;
+ params?: { value: string };
+ style: IStyleData;
+ }>([
+ {
+ name: 'background color',
+ commandId: SetBackgroundColorCommand.id,
+ params: { value: '#2C53F1' },
+ style: { bg: { rgb: '#2C53F1' } },
+ },
+ {
+ name: 'bold',
+ commandId: SetBoldCommand.id,
+ style: { bl: BooleanNumber.TRUE },
+ },
+ {
+ name: 'text color',
+ commandId: SetTextColorCommand.id,
+ params: { value: '#2C53F1' },
+ style: { cl: { rgb: '#2C53F1' } },
+ },
+ ])('preserves numeric text through $name, undo/redo and snapshot reload', async ({ commandId, params, style }) => {
+ const workbook = get(IUniverInstanceService).getUnit<Workbook>('test', UniverInstanceType.UNIVER_SHEET)!;
+ const worksheet = workbook.getSheetBySheetId('sheet1')!;
+ const unitId = workbook.getUnitId();
+ const subUnitId = worksheet.getSheetId();
+ const cellValue = {
+ 0: { 0: { v: '014', t: CellValueType.STRING } },
+ 1: { 0: { v: '014', t: CellValueType.FORCE_STRING } },
+ 2: { 0: { v: '014', t: CellValueType.STRING, s: { n: { pattern: DEFAULT_TEXT_FORMAT_EXCEL } } } },
+ };
+ expect(commandService.syncExecuteCommand(SetRangeValuesMutation.id, { unitId, subUnitId, cellValue })).toBe(true);
+ get(SheetsSelectionsService).addSelections([{
+ range: { startRow: 0, endRow: 2, startColumn: 0, endColumn: 0, rangeType: RANGE_TYPE.NORMAL },
+ primary: {
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ actualRow: 0,
+ actualColumn: 0,
+ isMerged: false,
+ isMergedMainCell: false,
+ },
+ style: null,
+ }]);
+ const readCells = (targetWorkbook: Workbook) => [0, 1, 2].map((row) => {
+ const cell = targetWorkbook.getSheetBySheetId(subUnitId)!.getCellRaw(row, 0);
+ return { ...cell, s: targetWorkbook.getStyles().getStyleByCell(cell) ?? null };
+ });
+ const before = readCells(workbook);
+ const after = before.map((cell) => ({ ...cell, s: { ...cell.s, ...style } }));
+ expect(await commandService.executeCommand(commandId, params)).toBe(true);
+ expect(readCells(workbook)).toEqual(after);
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(readCells(workbook)).toEqual(before);
+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(true);
+ expect(readCells(workbook)).toEqual(after);
+
+ const restored = createCommandTestBed(workbook.save());
+ try {
+ expect(readCells(restored.sheet)).toEqual(after);
+ } finally {
+ restored.univer.dispose();
+ }
+ });
+
it('set array of style', async () => {
const range = { startRow: 1, startColumn: 1, endColumn: 3, endRow: 3, rangeType: RANGE_TYPE.NORMAL };
diff --git a/packages/sheets/src/commands/mutations/__tests__/set-range-values.mutation.spec.ts b/packages/sheets/src/commands/mutations/__tests__/set-range-values.mutation.spec.ts
index 58a8498d14..78e61364b4 100644
--- a/packages/sheets/src/commands/mutations/__tests__/set-range-values.mutation.spec.ts
+++ b/packages/sheets/src/commands/mutations/__tests__/set-range-values.mutation.spec.ts
@@ -14,9 +14,17 @@
* limitations under the License.
*/
-import type { ISetRangeValuesMutationParams } from '../set-range-values.mutation';
-import { CellValueType, ICommandService, ObjectMatrix, Tools } from '@univerjs/core';
+import type { ICellData } from '@univerjs/core';
+import {
+ CellValueType,
+ DEFAULT_NUMBER_FORMAT,
+ DEFAULT_TEXT_FORMAT_EXCEL,
+ ICommandService,
+ ObjectMatrix,
+ Tools,
+} from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import type { ISetRangeValuesMutationParams } from '../set-range-values.mutation';
import { prepareSetRangeValuesMutation, SetRangeValuesMutation } from '../set-range-values.mutation';
import { createCommandTestBed } from './create-command-test-bed';
@@ -28,6 +36,192 @@ describe('SetRangeValuesMutation preparation', () => {
});
afterEach(() => bed.univer.dispose());
+ it.each<{
+ name: string;
+ cell: ICellData;
+ update: ICellData;
+ expected: ICellData;
+ isOverrideStyle?: boolean;
+ }>([
+ {
+ name: 'numeric text with leading zeroes',
+ cell: { v: '014', t: CellValueType.STRING },
+ update: { s: { bg: { rgb: '#2C53F1' } } },
+ expected: { v: '014', t: CellValueType.STRING },
+ },
+ {
+ name: 'forced numeric text',
+ cell: { v: '014', t: CellValueType.FORCE_STRING },
+ update: { s: { bg: { rgb: '#2C53F1' } } },
+ expected: { v: '014', t: CellValueType.FORCE_STRING },
+ },
+ {
+ name: 'text-formatted numeric text',
+ cell: { v: '014', t: CellValueType.STRING, s: { n: { pattern: DEFAULT_TEXT_FORMAT_EXCEL } } },
+ update: { s: { bg: { rgb: '#2C53F1' } } },
+ expected: { v: '014', t: CellValueType.STRING },
+ },
+ {
+ name: 'boolean-looking text',
+ cell: { v: 'TRUE', t: CellValueType.STRING },
+ update: { s: { bg: { rgb: '#2C53F1' } } },
+ expected: { v: 'TRUE', t: CellValueType.STRING },
+ },
+ {
+ name: 'numeric text exceeding number precision',
+ cell: { v: '9007199254740993', t: CellValueType.STRING },
+ update: { s: { bg: { rgb: '#2C53F1' } } },
+ expected: { v: '9007199254740993', t: CellValueType.STRING },
+ },
+ {
+ name: 'number',
+ cell: { v: 14, t: CellValueType.NUMBER },
+ update: { s: { bg: { rgb: '#2C53F1' } } },
+ expected: { v: 14, t: CellValueType.NUMBER },
+ },
+ {
+ name: 'boolean',
+ cell: { v: 1, t: CellValueType.BOOLEAN },
+ update: { s: { bg: { rgb: '#2C53F1' } } },
+ expected: { v: 1, t: CellValueType.BOOLEAN },
+ },
+ {
+ name: 'inherited numeric format during a color update',
+ cell: { v: '014', t: CellValueType.STRING, s: { n: { pattern: '0.00' } } },
+ update: { s: { bg: { rgb: '#2C53F1' } } },
+ expected: { v: '014', t: CellValueType.STRING },
+ },
+ {
+ name: 'unchanged number format in a style patch',
+ cell: { v: '014', t: CellValueType.STRING, s: { n: { pattern: '0.00' } } },
+ update: { s: { bg: { rgb: '#2C53F1' }, n: { pattern: '0.00' } } },
+ expected: { v: '014', t: CellValueType.STRING },
+ },
+ {
+ name: 'unchanged number format in a replacement style',
+ cell: { v: '014', t: CellValueType.STRING, s: { n: { pattern: '0.00' } } },
+ update: { s: { bg: { rgb: '#2C53F1' }, n: { pattern: '0.00' } } },
+ expected: { v: '014', t: CellValueType.STRING },
+ isOverrideStyle: true,
+ },
+ {
+ name: 'cleared color without a number format',
+ cell: { v: '014', t: CellValueType.STRING, s: { bg: { rgb: '#2C53F1' } } },
+ update: { s: null },
+ expected: { v: '014', t: CellValueType.STRING },
+ },
+ {
+ name: 'new untyped value',
+ cell: { v: '014', t: CellValueType.STRING },
+ update: { v: '015' },
+ expected: { v: 15, t: CellValueType.NUMBER },
+ },
+ {
+ name: 'explicit numeric type',
+ cell: { v: '014', t: CellValueType.STRING },
+ update: { t: CellValueType.NUMBER },
+ expected: { v: 14, t: CellValueType.NUMBER },
+ },
+ {
+ name: 'explicit text type',
+ cell: { v: 14, t: CellValueType.NUMBER },
+ update: { t: CellValueType.STRING },
+ expected: { v: '14', t: CellValueType.STRING },
+ },
+ {
+ name: 'cleared value',
+ cell: { v: '014', t: CellValueType.STRING },
+ update: { v: null },
+ expected: {},
+ },
+ {
+ name: 'new text format',
+ cell: { v: 14, t: CellValueType.NUMBER },
+ update: { s: { n: { pattern: DEFAULT_TEXT_FORMAT_EXCEL } } },
+ expected: { v: '14', t: CellValueType.STRING },
+ },
+ {
+ name: 'new numeric format',
+ cell: { v: '014', t: CellValueType.STRING },
+ update: { s: { n: { pattern: '0.00' } } },
+ expected: { v: 14, t: CellValueType.NUMBER },
+ },
+ {
+ name: 'text format replaced with a numeric format',
+ cell: { v: '014', t: CellValueType.STRING, s: { n: { pattern: DEFAULT_TEXT_FORMAT_EXCEL } } },
+ update: { s: { n: { pattern: '0.00' } } },
+ expected: { v: 14, t: CellValueType.NUMBER },
+ },
+ {
+ name: 'new general format',
+ cell: { v: '014', t: CellValueType.STRING },
+ update: { s: { n: { pattern: DEFAULT_NUMBER_FORMAT } } },
+ expected: { v: 14, t: CellValueType.NUMBER },
+ },
+ {
+ name: 'cleared numeric format',
+ cell: { v: '014', t: CellValueType.STRING, s: { n: { pattern: '0.00' } } },
+ update: { s: { n: null } },
+ expected: { v: 14, t: CellValueType.NUMBER },
+ },
+ {
+ name: 'cleared style with a numeric format',
+ cell: { v: '014', t: CellValueType.STRING, s: { n: { pattern: '0.00' } } },
+ update: { s: null },
+ expected: { v: 14, t: CellValueType.NUMBER },
+ },
+ {
+ name: 'replacement style removing a numeric format',
+ cell: { v: '014', t: CellValueType.STRING, s: { n: { pattern: '0.00' } } },
+ update: { s: { bg: { rgb: '#2C53F1' } } },
+ expected: { v: 14, t: CellValueType.NUMBER },
+ isOverrideStyle: true,
+ },
+ {
+ name: 'cleared text format retaining the original text type',
+ cell: { v: '014', t: CellValueType.STRING, s: { n: { pattern: DEFAULT_TEXT_FORMAT_EXCEL } } },
+ update: { s: null },
+ expected: { v: '014', t: CellValueType.STRING },
+ },
+ {
+ name: 'replacement style removing a text format',
+ cell: { v: '014', t: CellValueType.STRING, s: { n: { pattern: DEFAULT_TEXT_FORMAT_EXCEL } } },
+ update: { s: { bg: { rgb: '#2C53F1' } } },
+ expected: { v: '014', t: CellValueType.STRING },
+ isOverrideStyle: true,
+ },
+ {
+ name: 'forced text with a new numeric format',
+ cell: { v: '014', t: CellValueType.FORCE_STRING },
+ update: { s: { n: { pattern: '0.00' } } },
+ expected: { v: '014', t: CellValueType.FORCE_STRING },
+ },
+ ])('prepares and applies $name without unintended value conversions', ({ cell, update, expected, isOverrideStyle }) => {
+ const sheet = bed.sheet.getSheets()[0];
+ const styles = bed.sheet.getStyles();
+ const commandService = bed.get(ICommandService);
+ const address = { unitId: bed.sheet.getUnitId(), subUnitId: sheet.getSheetId() };
+ expect(commandService.syncExecuteCommand(SetRangeValuesMutation.id, {
+ ...address,
+ cellValue: { 0: { 0: Tools.deepClone(cell) } },
+ })).toBe(true);
+ const originalCell = Tools.deepClone(sheet.getCellRaw(0, 0));
+ const originalStyles = Tools.deepClone(styles.toJSON());
+ const params: ISetRangeValuesMutationParams = {
+ ...address,
+ cellValue: { 0: { 0: Tools.deepClone(update) } },
+ isOverrideStyle,
+ };
+ const prepared = prepareSetRangeValuesMutation(sheet.getCellMatrix(), styles, params);
+ expect(sheet.getCellRaw(0, 0)).toEqual(originalCell);
+ expect(styles.toJSON()).toEqual(originalStyles);
+ expect(prepared.after[0][0]?.v).toBe(expected.v);
+ expect(prepared.after[0][0]?.t).toBe(expected.t);
+ Object.entries(prepared.styles).forEach(([id, style]) => styles.addCustomStyle(id, style));
+ expect(commandService.syncExecuteCommand(SetRangeValuesMutation.id, params)).toBe(true);
+ expect(sheet.getCellRaw(0, 0) ?? null).toEqual(prepared.after[0][0]);
+ });
+
it('prepares native typed/formula/style changes without writing or leaking styles and matches native execution', () => {
const sheet = bed.sheet.getSheets()[0];
const styles = bed.sheet.getStyles();
diff --git a/packages/sheets/src/commands/mutations/set-range-values.mutation.ts b/packages/sheets/src/commands/mutations/set-range-values.mutation.ts
index c656f4aba4..1fae4844ad 100644
--- a/packages/sheets/src/commands/mutations/set-range-values.mutation.ts
+++ b/packages/sheets/src/commands/mutations/set-range-values.mutation.ts
@@ -204,7 +204,9 @@ function isStaleFormulaResult(cell: Nullable<ICellData>, source: Nullable<Pick<I
const overwriteCellPropertiesSet = new Set(['f', 'p', 'si', 'custom', 'ref', 'xf', 'ft', 'fd']);
function mergeCellData(newValue: ICellData, oldValue: ICellData, styles: Styles, isOverrideStyle = false) {
- const type = getCellType(styles, newValue, oldValue);
+ const canPreserveValue = newValue.v === undefined && newValue.t === undefined && oldValue.t != null;
+ const previousStyle = canPreserveValue ? styles.getStyleByCell(oldValue) : undefined;
+ const type = canPreserveValue ? oldValue.t : getCellType(styles, newValue, oldValue);
Object.keys(newValue).forEach((key) => {
const cellPropertyKey = key as keyof ICellData;
if (overwriteCellPropertiesSet.has(cellPropertyKey)) {
@@ -229,9 +231,13 @@ function mergeCellData(newValue: ICellData, oldValue: ICellData, styles: Styles,
delete oldValue.fd;
}
- if (oldValue.v !== undefined) {
- oldValue.t = type;
- oldValue.v = getCellValue(type, oldValue);
+ const numberFormatChanged = canPreserveValue &&
+ previousStyle?.n?.pattern !== styles.getStyleByCell(oldValue)?.n?.pattern;
+ if (oldValue.v !== undefined && (!canPreserveValue || numberFormatChanged)) {
+ // Format changes still infer from the original style, including forced/text-formatted values.
+ const nextType = numberFormatChanged ? getCellType(styles, newValue, { ...oldValue, s: previousStyle }) : type;
+ oldValue.t = nextType;
+ oldValue.v = getCellValue(nextType, oldValue);
}
if (oldValue.v === null) {
diff --git a/packages/sheets/src/facade/__tests__/f-range.spec.ts b/packages/sheets/src/facade/__tests__/f-range.spec.ts
index 2cd78c7c2b..5bde107f5a 100644
--- a/packages/sheets/src/facade/__tests__/f-range.spec.ts
+++ b/packages/sheets/src/facade/__tests__/f-range.spec.ts
@@ -26,6 +26,11 @@ import type {
import type { FUniver } from '@univerjs/core/facade';
import {
AbsoluteRefType,
+ BooleanNumber,
+ BorderStyleTypes,
+ BorderType,
+ CellValueType,
+ DEFAULT_NUMBER_FORMAT,
Dimension,
HorizontalAlign,
ICommandService,
@@ -34,6 +39,7 @@ import {
IUniverInstanceService,
LifecycleStages,
TestConfirmService,
+ Tools,
UniverInstanceType,
VerticalAlign,
WrapStrategy,
@@ -76,10 +82,88 @@ import {
UnregisterWorksheetRangeThemeStyleMutation,
} from '@univerjs/sheets';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { FRange } from '../f-range';
import type { FWorksheet } from '../f-worksheet';
+import { SetBorderBasicCommand, SetBorderCommand } from '../../commands/commands/set-border.command';
+import { BorderStyleManagerService } from '../../services/border-style-manager.service';
import { SHEETS_CUSTOM_FIELD_WARNING_MESSAGE } from '../const';
import { createFacadeTestBed } from './create-test-bed';
+describe('FRange style-only text preservation', () => {
+ it.each<{ name: string; apply: (range: FRange) => FRange }>([
+ { name: 'setFontWeight', apply: (range) => range.setFontWeight('bold') },
+ { name: 'setFontStyle', apply: (range) => range.setFontStyle('italic') },
+ { name: 'setFontColor', apply: (range) => range.setFontColor('#ffff00') },
+ { name: 'setFontFamily', apply: (range) => range.setFontFamily('Arial') },
+ { name: 'setFontSize', apply: (range) => range.setFontSize(20) },
+ { name: 'setBackground', apply: (range) => range.setBackground('#ffff00') },
+ { name: 'setBackgroundColor', apply: (range) => range.setBackgroundColor('#ffff00') },
+ { name: 'setHorizontalAlignment', apply: (range) => range.setHorizontalAlignment('center') },
+ { name: 'setVerticalAlignment', apply: (range) => range.setVerticalAlignment('middle') },
+ { name: 'setWrap', apply: (range) => range.setWrap(true) },
+ { name: 'setBorder', apply: (range) => range.setBorder(BorderType.ALL, BorderStyleTypes.THIN, '#ffff00') },
+ {
+ name: 'setValues with style-only cells',
+ apply: (range) => range.setValues(Array.from({ length: range.getHeight() }, () =>
+ Array.from({ length: range.getWidth() }, () => ({ s: { bl: BooleanNumber.TRUE } })))),
+ },
+ ])('preserves values and types through $name, including neighboring border cells', ({ name, apply }) => {
+ const bed = createFacadeTestBed(undefined, [[BorderStyleManagerService]]);
+ try {
+ const commandService = bed.get(ICommandService);
+ [
+ SetRangeValuesCommand,
+ SetRangeValuesMutation,
+ SetStyleCommand,
+ SetTextWrapCommand,
+ SetHorizontalTextAlignCommand,
+ SetVerticalTextAlignCommand,
+ SetBorderBasicCommand,
+ SetBorderCommand,
+ ].forEach((command) => commandService.registerCommand(command));
+ bed.get(SheetSkeletonService).ensureSkeleton('test', 'sheet1');
+ const worksheet = bed.univerAPI.getActiveWorkbook()!.getActiveSheet();
+ const surroundingRange = worksheet.getRange('A1:J5');
+ const border = { s: BorderStyleTypes.THIN, cl: { rgb: '#000000' } };
+ surroundingRange.setValue({
+ v: '001',
+ t: CellValueType.STRING,
+ s: { bd: { t: border, b: border, l: border, r: border } },
+ });
+ const cells: ICellData[] = [
+ ...['014', '1.50', '1e3', 'abc', '2-2', '12%'].map((v) => ({ v, t: CellValueType.STRING })),
+ { v: 14, t: CellValueType.NUMBER },
+ { v: 3, t: CellValueType.NUMBER, f: '=1+2' },
+ ];
+ const range = worksheet.getRange('B2:I4');
+ range.setValues([undefined, '000', DEFAULT_NUMBER_FORMAT].map((pattern) =>
+ cells.map((cell) => ({ ...cell, s: pattern ? { n: { pattern } } : undefined }))));
+ const before = Tools.deepClone(surroundingRange.getCellDataGrid());
+ const readValues = () => surroundingRange.getCellDataGrid().map((row) =>
+ row.map((cell) => ({ v: cell?.v, t: cell?.t, f: cell?.f })));
+ const expected = readValues();
+ expect(range.getCellDataGrid().map((row) => row.map((cell) => cell?.v))).toEqual([
+ cells.map((cell) => cell.v),
+ cells.map((cell) => cell.v),
+ cells.map((cell) => cell.v),
+ ]);
+
+ apply(range);
+
+ expect(readValues()).toEqual(expected);
+ expect(surroundingRange.getCellDataGrid()).not.toEqual(before);
+ if (name === 'setBorder') {
+ expect(worksheet.getRange('B1').getCellStyleData()?.bd?.b).toBeUndefined();
+ expect(worksheet.getRange('B5').getCellStyleData()?.bd?.t).toBeUndefined();
+ expect(worksheet.getRange('A2').getCellStyleData()?.bd?.r).toBeUndefined();
+ expect(worksheet.getRange('J2').getCellStyleData()?.bd?.l).toBeUndefined();
+ }
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+});
+
describe('Test FRange', () => {
let get: Injector['get'];
let commandService: ICommandService;