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): persist formula removal when setValue writes cell data (#8117)

wpxp123456a6c652dded38
diff --git a/packages/core/src/shared/__tests__/common.spec.ts b/packages/core/src/shared/__tests__/common.spec.ts
index 9fe4a2658b..b191d3719a 100644
--- a/packages/core/src/shared/__tests__/common.spec.ts
+++ b/packages/core/src/shared/__tests__/common.spec.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
+import { describe, expect, it } from 'vitest';
import type { ICellData, ICellWithCoord, IRange, ISelectionCell } from '../../sheets/typedef';
import type { IDocumentData } from '../../types/interfaces';
-import { describe, expect, it } from 'vitest';
import {
RANGE_TYPE,
} from '../../sheets/typedef';
@@ -250,9 +250,9 @@ describe('Test common', () => {
rangeType: RANGE_TYPE.COLUMN,
})).toBe(true);
- expect(covertCellValue('=SUM(1,2)')).toEqual({ f: '=SUM(1,2)', v: null, p: null });
- expect(covertCellValue(1)).toEqual({ v: 1, p: null, f: null });
- const cell = { v: 'text', p: null, f: null } as ICellData;
+ expect(covertCellValue('=SUM(1,2)')).toEqual({ f: '=SUM(1,2)', v: null, p: null, si: null });
+ expect(covertCellValue(1)).toEqual({ v: 1, p: null, f: null, si: null });
+ const cell = { v: 'text', p: null, f: null, si: null } as ICellData;
expect(covertCellValue(cell)).toBe(cell);
const mixedValues = [
@@ -262,14 +262,15 @@ describe('Test common', () => {
expect(covertCellValues(mixedValues, { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 } as IRange)).toEqual({
0: {
- 0: { v: 1, p: null, f: null },
- 1: { f: '=A1', v: null, p: null },
+ 0: { v: 1, p: null, f: null, si: null },
+ 1: { f: '=A1', v: null, p: null, si: null },
},
1: {
0: {
v: 0.02,
p: null,
f: null,
+ si: null,
s: { n: { pattern: '0%' } },
},
1: null,
@@ -280,8 +281,30 @@ describe('Test common', () => {
3: { 4: '=B2' },
}, { startRow: 3, endRow: 3, startColumn: 4, endColumn: 4 } as IRange)).toEqual({
3: {
- 4: { f: '=B2', v: null, p: null },
+ 4: { f: '=B2', v: null, p: null, si: null },
},
});
});
+
+ it('should replace the target formula when a cell-data write supplies content without formula identity', () => {
+ const content = { v: 300 } as ICellData;
+ expect(covertCellValue(content)).toEqual({ v: 300, f: null, si: null });
+ expect(content).toEqual({ v: 300 });
+
+ const richText = { p: { id: 'rich-text', body: { dataStream: 'text' } } } as ICellData;
+ expect(covertCellValue(richText)).toEqual({ p: richText.p, f: null, si: null });
+ expect(richText).toEqual({ p: { id: 'rich-text', body: { dataStream: 'text' } } });
+
+ const formula = { f: '=A1', si: null } as ICellData;
+ expect(covertCellValue(formula)).toBe(formula);
+
+ const sharedFormula = { f: '=A1' } as ICellData;
+ expect(covertCellValue(sharedFormula)).toEqual({ f: '=A1', si: null });
+
+ const style = { s: { bg: { rgb: '#ffffff' } } } as ICellData;
+ expect(covertCellValue(style)).toBe(style);
+
+ const sharedFollower = { si: 'shared-1' } as ICellData;
+ expect(covertCellValue(sharedFollower)).toBe(sharedFollower);
+ });
});
diff --git a/packages/core/src/shared/common.ts b/packages/core/src/shared/common.ts
index 73da3f21c6..59b247cc41 100644
--- a/packages/core/src/shared/common.ts
+++ b/packages/core/src/shared/common.ts
@@ -551,8 +551,33 @@ export function cellToRange(row: number, col: number): IRange {
return { startRow: row, endRow: row, startColumn: col, endColumn: col };
}
+/**
+ * Writing content replaces the target formula, and writing a new formula disassociates the target
+ * from its shared formula id. The formula controller performs both removals for the current client
+ * with an `onlyLocal` mutation, which never reaches a collaboration changeset, so they have to be
+ * part of the write itself.
+ * @param {ICellData} cell - The cell data to normalize.
+ * @returns {ICellData} The same instance when no formula identity has to be removed.
+ */
+function withFormulaIdentityCleared(cell: ICellData): ICellData {
+ if (cell.si !== undefined) {
+ return cell;
+ }
+
+ if (cell.f !== undefined) {
+ return { ...cell, si: null };
+ }
+
+ if (cell.v === undefined && cell.p === undefined) {
+ return cell;
+ }
+
+ return { ...cell, f: null, si: null };
+}
+
/**
* Covert cell value to cell data.
+ * A formula or content value also clears the shared formula id of the cell it replaces.
* @param {CellValue | ICellData} value - The cell value.
* @returns {ICellData} The cell data.
*/
@@ -562,6 +587,7 @@ export function covertCellValue(value: CellValue | ICellData): ICellData {
f: value as string,
v: null,
p: null,
+ si: null,
};
}
if (isCellV(value)) {
@@ -573,6 +599,7 @@ export function covertCellValue(value: CellValue | ICellData): ICellData {
v: parseData.v as number,
p: null,
f: null,
+ si: null,
s: {
n: {
pattern: parseData.z || DEFAULT_NUMBER_FORMAT,
@@ -586,10 +613,11 @@ export function covertCellValue(value: CellValue | ICellData): ICellData {
v: value as Nullable<CellValue>,
p: null,
f: null,
+ si: null,
};
}
if (isICellData(value)) {
- return value;
+ return withFormulaIdentityCleared(value);
}
// maybe {}
diff --git a/packages/sheets-formula/src/facade/__tests__/f-range-engine-formula.spec.ts b/packages/sheets-formula/src/facade/__tests__/f-range-engine-formula.spec.ts
index b7def52fa3..a12ec88fe4 100644
--- a/packages/sheets-formula/src/facade/__tests__/f-range-engine-formula.spec.ts
+++ b/packages/sheets-formula/src/facade/__tests__/f-range-engine-formula.spec.ts
@@ -14,9 +14,10 @@
* limitations under the License.
*/
-import type { Injector, IWorkbookData } from '@univerjs/core';
+import type { ICommandInfo, Injector, IWorkbookData } from '@univerjs/core';
import type { FUniver } from '@univerjs/core/facade';
-import { ICommandService, LocaleType } from '@univerjs/core';
+import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
+import { ICommandService, LocaleType, UndoCommand } from '@univerjs/core';
import { ErrorType } from '@univerjs/engine-formula';
import { SetRangeValuesCommand, SetRangeValuesMutation } from '@univerjs/sheets';
import { beforeEach, describe, expect, it } from 'vitest';
@@ -288,4 +289,37 @@ describe('Test FRangeEngineFormulaMixin', () => {
expect(errorsByType[ErrorType.NUM]).toBe(1);
expect(errorsByType[ErrorType.VALUE]).toBe(1);
});
+
+ it('should carry a replaced formula removal in the collaboration changeset', async () => {
+ const worksheet = univerAPI.getActiveWorkbook()!.getActiveSheet();
+ const durableMutations: ICommandInfo[] = [];
+ commandService.onMutationExecutedForCollab((command, options) => {
+ if (options?.onlyLocal !== true) {
+ durableMutations.push(command);
+ }
+ });
+
+ worksheet.getRange('C1').setValue({ v: 300 });
+
+ expect(worksheet.getRange('C1').getCellData()).toMatchObject({ v: 300 });
+ expect(worksheet.getRange('C1').getCellData()?.f).toBeUndefined();
+
+ // Replicas and the collaboration server only receive mutations without `onlyLocal`, so the
+ // removal has to travel with the write instead of relying on the formula controller.
+ expect(durableMutations).toHaveLength(1);
+ expect((durableMutations[0].params as ISetRangeValuesMutationParams).cellValue).toMatchObject({
+ 0: { 2: { v: 300, f: null, si: null } },
+ });
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(worksheet.getRange('C1').getCellData()).toMatchObject({ f: '=SUM(A1:B1)', v: 3 });
+ });
+
+ it('should keep the formula when only style is written', () => {
+ const worksheet = univerAPI.getActiveWorkbook()!.getActiveSheet();
+
+ worksheet.getRange('C1').setValue({ s: { bg: { rgb: '#ff0000' } } });
+
+ expect(worksheet.getRange('C1').getCellData()?.f).toBe('=SUM(A1:B1)');
+ });
});
diff --git a/packages/sheets/src/facade/__tests__/f-range.spec.ts b/packages/sheets/src/facade/__tests__/f-range.spec.ts
index 5bde107f5a..75b203a082 100644
--- a/packages/sheets/src/facade/__tests__/f-range.spec.ts
+++ b/packages/sheets/src/facade/__tests__/f-range.spec.ts
@@ -16,6 +16,7 @@
import type {
ICellData,
+ ICommandInfo,
IDocumentData,
Injector,
IStyleData,
@@ -24,6 +25,7 @@ import type {
Workbook,
} from '@univerjs/core';
import type { FUniver } from '@univerjs/core/facade';
+import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
import {
AbsoluteRefType,
BooleanNumber,
@@ -1305,3 +1307,62 @@ describe('Test FRange', () => {
});
});
});
+
+describe('FRange formula replacement', () => {
+ function createBed() {
+ const bed = createFacadeTestBed(undefined, [[BorderStyleManagerService]]);
+ const commandService = bed.get(ICommandService);
+ [SetRangeValuesCommand, SetRangeValuesMutation].forEach((command) => commandService.registerCommand(command));
+
+ return { bed, commandService, worksheet: bed.univerAPI.getActiveWorkbook()!.getActiveSheet() };
+ }
+
+ it('removes the formula and the shared formula id from the collaboration changeset', () => {
+ const { bed, commandService, worksheet } = createBed();
+ try {
+ const durable: ICommandInfo[] = [];
+ commandService.onMutationExecutedForCollab((command, options) => {
+ if (options?.onlyLocal !== true) {
+ durable.push(command);
+ }
+ });
+
+ worksheet.getRange('A1').setValues([[{ f: '=SUM(B1:B2)', si: 'shared-1', v: 3 }]]);
+ expect(worksheet.getRange('A1').getCellData()).toMatchObject({ f: '=SUM(B1:B2)', si: 'shared-1' });
+
+ worksheet.getRange('A1').setValue({ v: 300 });
+
+ expect(worksheet.getRange('A1').getCellData()).toMatchObject({ v: 300 });
+ expect(worksheet.getRange('A1').getCellData()?.f).toBeUndefined();
+ expect(worksheet.getRange('A1').getCellData()?.si).toBeUndefined();
+ expect((durable[durable.length - 1].params as ISetRangeValuesMutationParams).cellValue).toMatchObject({
+ 0: { 0: { v: 300, f: null, si: null } },
+ });
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+
+ it('disassociates a rewritten formula from the previous shared formula id', () => {
+ const { bed, commandService, worksheet } = createBed();
+ try {
+ const durable: ICommandInfo[] = [];
+ commandService.onMutationExecutedForCollab((command, options) => {
+ if (options?.onlyLocal !== true) {
+ durable.push(command);
+ }
+ });
+
+ worksheet.getRange('A1').setValues([[{ f: '=SUM(B1:B2)', si: 'shared-1', v: 3 }]]);
+ worksheet.getRange('A1').setValue('=SUM(B1:B3)');
+
+ expect(worksheet.getRange('A1').getCellData()).toMatchObject({ f: '=SUM(B1:B3)' });
+ expect(worksheet.getRange('A1').getCellData()?.si).toBeUndefined();
+ expect((durable[durable.length - 1].params as ISetRangeValuesMutationParams).cellValue).toMatchObject({
+ 0: { 0: { f: '=SUM(B1:B3)', si: null } },
+ });
+ } finally {
+ bed.univer.dispose();
+ }
+ });
+});
diff --git a/packages/sheets/src/facade/__tests__/utils.spec.ts b/packages/sheets/src/facade/__tests__/utils.spec.ts
index 6b964991b5..5edccbcc0f 100644
--- a/packages/sheets/src/facade/__tests__/utils.spec.ts
+++ b/packages/sheets/src/facade/__tests__/utils.spec.ts
@@ -29,11 +29,11 @@ import {
describe('Test utils', () => {
it('function covertCellValue', () => {
- expect(covertCellValue('=SUM(1)')).toStrictEqual({ f: '=SUM(1)', v: null, p: null });
+ expect(covertCellValue('=SUM(1)')).toStrictEqual({ f: '=SUM(1)', v: null, p: null, si: null });
- expect(covertCellValue('1')).toStrictEqual({ v: '1', f: null, p: null });
- expect(covertCellValue(1)).toStrictEqual({ v: 1, f: null, p: null });
- expect(covertCellValue(true)).toStrictEqual({ v: true, f: null, p: null });
+ expect(covertCellValue('1')).toStrictEqual({ v: '1', f: null, p: null, si: null });
+ expect(covertCellValue(1)).toStrictEqual({ v: 1, f: null, p: null, si: null });
+ expect(covertCellValue(true)).toStrictEqual({ v: true, f: null, p: null, si: null });
expect(covertCellValue({})).toStrictEqual({});
});
@@ -48,8 +48,8 @@ describe('Test utils', () => {
{ startRow: 1, startColumn: 1, endRow: 2, endColumn: 2 }
)
).toStrictEqual({
- 1: { 1: { v: 1, f: null, p: null }, 2: { v: 2, f: null, p: null } },
- 2: { 1: { v: 3, f: null, p: null }, 2: { v: 4, f: null, p: null } },
+ 1: { 1: { v: 1, f: null, p: null, si: null }, 2: { v: 2, f: null, p: null, si: null } },
+ 2: { 1: { v: 3, f: null, p: null, si: null }, 2: { v: 4, f: null, p: null, si: null } },
});
expect(
@@ -61,8 +61,8 @@ describe('Test utils', () => {
{ startRow: 1, startColumn: 1, endRow: 2, endColumn: 2 }
)
).toStrictEqual({
- 1: { 1: { v: 1, f: null, p: null }, 2: { v: 2, f: null, p: null } },
- 2: { 1: { v: 3, f: null, p: null }, 2: { v: 4, f: null, p: null } },
+ 1: { 1: { v: 1, f: null, p: null, si: null }, 2: { v: 2, f: null, p: null, si: null } },
+ 2: { 1: { v: 3, f: null, p: null, si: null }, 2: { v: 4, f: null, p: null, si: null } },
});
expect(
@@ -74,8 +74,8 @@ describe('Test utils', () => {
{ startRow: 1, startColumn: 1, endRow: 2, endColumn: 2 }
)
).toStrictEqual({
- 1: { 1: { v: 1 }, 2: { v: 2 } },
- 2: { 1: { v: 3 }, 2: { v: 4 } },
+ 1: { 1: { v: 1, f: null, si: null }, 2: { v: 2, f: null, si: null } },
+ 2: { 1: { v: 3, f: null, si: null }, 2: { v: 4, f: null, si: null } },
});
expect(
@@ -87,8 +87,8 @@ describe('Test utils', () => {
{ startRow: 1, startColumn: 1, endRow: 2, endColumn: 2 }
)
).toStrictEqual({
- 1: { 1: { v: 1 }, 2: { v: 2 } },
- 2: { 1: { v: 3 }, 2: { v: 4 } },
+ 1: { 1: { v: 1, f: null, si: null }, 2: { v: 2, f: null, si: null } },
+ 2: { 1: { v: 3, f: null, si: null }, 2: { v: 4, f: null, si: null } },
});
});
diff --git a/packages/sheets/src/facade/f-range.ts b/packages/sheets/src/facade/f-range.ts
index b87670a281..1e3561d1e5 100644
--- a/packages/sheets/src/facade/f-range.ts
+++ b/packages/sheets/src/facade/f-range.ts
@@ -47,8 +47,6 @@ import type {
IStyleTypeValue,
SplitDelimiterEnum,
} from '@univerjs/sheets';
-import type { IFacadeClearOptions } from './f-worksheet';
-import type { FHorizontalAlignment, FVerticalAlignment } from './utils';
import {
BooleanNumber,
covertCellValue,
@@ -97,6 +95,8 @@ import {
SheetRangeThemeService,
SplitTextToColumnsCommand,
} from '@univerjs/sheets';
+import type { IFacadeClearOptions } from './f-worksheet';
+import type { FHorizontalAlignment, FVerticalAlignment } from './utils';
import { SHEETS_CUSTOM_FIELD_WARNING_MESSAGE } from './const';
import { FWorkbook } from './f-workbook';
import { FWorksheet } from './f-worksheet';
@@ -1310,10 +1310,12 @@ export class FRange extends FBaseInitialable {
* - `ICellData`: updates cell-data fields directly, for explicit control over `v` (value),
* `f` (formula), `p` (rich text), `t` (value type), and `s` (style). The object bypasses the
* formula and formatted-number parsing above: `{ v: '=SUM(A1:A2)' }` does not set a formula;
- * use `{ f: '=SUM(A1:A2)', v: null, p: null }` instead. Omitted content fields are not
- * automatically cleared, so use `f: null` and `p: null` when replacing a formula or rich text
- * with `v`. Use `v: null` to clear the stored value. Supplied style properties are merged into
- * the existing style; `s: null` clears the style.
+ * use `{ f: '=SUM(A1:A2)', v: null, p: null }` instead. Writing `v` or `p` without `f` and
+ * `si` replaces the target formula, as writing a scalar value does, and writing `f` without
+ * `si` disassociates the cell from its previous shared formula. Rich text is still not
+ * cleared by a value write, so pass `p: null` when replacing rich text with `v`. Use
+ * `v: null` to clear the stored value. Supplied style properties are merged into the existing
+ * style; `s: null` clears the style.
*
* In both modes, the stored value is converted according to its cell type. Unless an `ICellData`
* input supplies `t`, the type is inferred from the value, number format, and existing cell type.