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.

Revert "refactor(SSC): remove SSC function (#7264)"

Wpxp12345657d36e11390d
diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.ts
index a4d27a5e7f..416d9bb86b 100644
--- a/packages/protocol/src/index.ts
+++ b/packages/protocol/src/index.ts
@@ -92,6 +92,15 @@ export {
type ICreateLatestSnapshotInBackgroundRequest,
type ICreateLatestSnapshotInBackgroundResponse,
} from './ts/univerpro/v1/helper';
+export type {
+ IComputeRequest,
+ IComputeResponse,
+ IGetPreprocessRangesRequest,
+ IGetPreprocessRangesResponse,
+ IGetValuesRequest,
+ IGetValuesResponse,
+ ITableInfoList,
+} from './ts/univerpro/v1/ssc';
export type {
IGetSSRRequest,
IGetSSRResponse,
diff --git a/packages/protocol/src/ts/univerpro/v1/ssc.ts b/packages/protocol/src/ts/univerpro/v1/ssc.ts
new file mode 100644
index 0000000000..4d0cd8beed
--- /dev/null
+++ b/packages/protocol/src/ts/univerpro/v1/ssc.ts
@@ -0,0 +1,81 @@
+/**
+ * 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 { IError } from '../../univer/constants/errors';
+import type { IRange } from '../../univer/range';
+import type { ITableInfo } from '../../univer/snapshot';
+import type { ISheetBlockMeta } from '../../univer/workbook';
+
+export enum responseDataMode {
+ /** none - no data, default */
+ none = 0,
+ /** all - all data */
+ all = 1,
+ /** sample - sample data */
+ sample = 2,
+ UNRECOGNIZED = -1,
+}
+
+export interface IGetPreprocessRangesRequest {
+ unitId: string;
+ rev: number;
+ /** use string, see responseDataMode enum, default is "none" */
+ responseDataMode?: string | undefined;
+}
+
+export interface ITableInfoList {
+ tableInfos: ITableInfo[];
+}
+
+export interface IGetPreprocessRangesResponse {
+ error: IError | undefined;
+ tableInfo: { [key: string]: ITableInfoList };
+}
+
+export interface IGetValuesRequest {
+ workbookId: string;
+ worksheetId: string;
+ range: IRange | undefined;
+}
+
+export interface IGetValuesResponse {
+ error:
+ | IError
+ | undefined;
+ /** A matrix of values in JSON format. */
+ value: string;
+}
+
+export interface IComputeRequest {
+ /** The id of the unit to be computed. */
+ workbookId: string;
+ /**
+ * The revision of the unit to be computed. If not specified or set to 0, the SSC service
+ * will fetch the latest version at the request time.
+ */
+ revision: number;
+ /** Timeout in milliseconds. Default is 30s. */
+ timeout: number;
+}
+
+export interface IComputeResponse {
+ error:
+ | IError
+ | undefined;
+ /** Of which revision the unit is processed on. */
+ revision: number;
+ sscBlock: { [key: string]: ISheetBlockMeta };
+}
diff --git a/packages/protocol/src/ts/universer/v1/snapshot.ts b/packages/protocol/src/ts/universer/v1/snapshot.ts
index 4b16f04cc8..02624efd54 100644
--- a/packages/protocol/src/ts/universer/v1/snapshot.ts
+++ b/packages/protocol/src/ts/universer/v1/snapshot.ts
@@ -24,7 +24,26 @@ import type { IResource } from '../../univer/resource';
import type { ISnapshot, ITableInfo } from '../../univer/snapshot';
import type { ICustomCellTemplate } from '../../univer/unit-template';
import type { IUnit } from '../../univer/univer-file';
-import type { ISheetBlock } from '../../univer/workbook';
+import type { ISheetBlock, ISheetBlockMeta } from '../../univer/workbook';
+
+interface IGetSnapshotMetaWithPreCalculatedRequest {
+ /** The id of the unit to be computed. */
+ workbookId: string;
+ /**
+ * The revision of the unit to be computed. If not specified or set to 0, the SSC service
+ * will fetch the latest version at the request time.
+ */
+ revision: number;
+}
+
+interface IGetSnapshotMetaWithPreCalculatedResponse {
+ error:
+ | IError
+ | undefined;
+ /** Of which revision the unit is processed on. */
+ revision: number;
+ sscBlock: { [key: string]: ISheetBlockMeta };
+}
interface IGetUnitMetaRequest {
unitId: string;
@@ -399,6 +418,11 @@ export interface ISnapshotService {
GetSheetTable(request: IGetSheetTableRequest, metadata?: Metadata): Observable<IGetSheetTableResponse>;
/** get unit meta */
GetUnitMeta(request: IGetUnitMetaRequest, metadata?: Metadata): Observable<IGetUnitMetaResponse>;
+ /** Get formula calculation results */
+ GetSnapshotMetaWithPreCalculated(
+ request: IGetSnapshotMetaWithPreCalculatedRequest,
+ metadata?: Metadata,
+ ): Observable<IGetSnapshotMetaWithPreCalculatedResponse>;
ReportUnitRoutingStats(
request: IReportUnitRoutingStatsRequest,
metadata?: Metadata,
diff --git a/packages/sheets-formula/src/config/config.ts b/packages/sheets-formula/src/config/config.ts
index f863575916..17574d4213 100644
--- a/packages/sheets-formula/src/config/config.ts
+++ b/packages/sheets-formula/src/config/config.ts
@@ -50,6 +50,11 @@ export interface IUniverSheetsFormulaBaseConfig {
* Define the calculation mode during initialization, default is `WHEN_EMPTY`
*/
initialFormulaComputing?: CalculationMode;
+
+ /**
+ * If true, the plugin will write array formula results to the snapshot. Normally you should not set this value.
+ */
+ writeArrayFormulaToSnapshot?: boolean;
}
export const defaultPluginBaseConfig: IUniverSheetsFormulaBaseConfig = {};
diff --git a/packages/sheets-formula/src/controllers/__tests__/array-formula-cell-interceptor.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/array-formula-cell-interceptor.controller.spec.ts
index f950c85e1d..8982e9beec 100644
--- a/packages/sheets-formula/src/controllers/__tests__/array-formula-cell-interceptor.controller.spec.ts
+++ b/packages/sheets-formula/src/controllers/__tests__/array-formula-cell-interceptor.controller.spec.ts
@@ -15,15 +15,25 @@
*/
import type { Dependency, IWorkbookData, Workbook, Worksheet } from '@univerjs/core';
+import type { IFormulaData } from '@univerjs/engine-formula';
import {
CellValueType,
ICommandService,
+ IConfigService,
InterceptorEffectEnum,
LocaleType,
} from '@univerjs/core';
-import { FormulaDataModel, SetArrayFormulaDataMutation } from '@univerjs/engine-formula';
-import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';
+import {
+ FormulaDataModel,
+ IDefinedNamesService,
+ LexerTreeBuilder,
+ SetArrayFormulaDataMutation,
+ SetDefinedNameMutation,
+ SetFormulaCalculationResultMutation,
+} from '@univerjs/engine-formula';
+import { INTERCEPTOR_POINT, SetRangeValuesMutation, SheetInterceptorService } from '@univerjs/sheets';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { PLUGIN_CONFIG_KEY_BASE } from '../../config/config';
import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';
import { ArrayFormulaCellInterceptorController } from '../array-formula-cell-interceptor.controller';
@@ -85,6 +95,7 @@ function getInterceptedCell(worksheet: Worksheet, workbook: Workbook, row: numbe
describe('ArrayFormulaCellInterceptorController', () => {
let testBed: ReturnType<typeof createControllerTestBed>;
let commandService: ICommandService;
+ let configService: IConfigService;
let formulaDataModel: FormulaDataModel;
let interceptorService: SheetInterceptorService;
let workbook: Workbook;
@@ -93,12 +104,16 @@ describe('ArrayFormulaCellInterceptorController', () => {
beforeEach(() => {
testBed = createControllerTestBed();
commandService = testBed.injector.get(ICommandService);
+ configService = testBed.injector.get(IConfigService);
formulaDataModel = testBed.injector.get(FormulaDataModel);
interceptorService = testBed.injector.get(SheetInterceptorService);
workbook = testBed.sheet as Workbook;
worksheet = workbook.getActiveSheet()!;
commandService.registerCommand(SetArrayFormulaDataMutation);
+ commandService.registerCommand(SetDefinedNameMutation);
+ commandService.registerCommand(SetFormulaCalculationResultMutation);
+ commandService.registerCommand(SetRangeValuesMutation);
testBed.injector.get(ArrayFormulaCellInterceptorController);
});
@@ -108,7 +123,11 @@ describe('ArrayFormulaCellInterceptorController', () => {
testBed?.univer.dispose();
});
- it('should sync array formula data to the model', async () => {
+ it('should sync array formula data to the model and write snapshot refs when configured', async () => {
+ configService.setConfig(PLUGIN_CONFIG_KEY_BASE, { writeArrayFormulaToSnapshot: true });
+
+ const executeCommandSpy = vi.spyOn(commandService, 'executeCommand');
+
const arrayFormulaRange = {
test: {
sheet1: {
@@ -178,6 +197,141 @@ describe('ArrayFormulaCellInterceptorController', () => {
expect(formulaDataModel.getArrayFormulaRange()).toEqual(arrayFormulaRange);
expect(formulaDataModel.getArrayFormulaCellData()).toEqual(arrayFormulaCellData);
+
+ const setRangeValuesCalls = executeCommandSpy.mock.calls.filter(([id]) => id === SetRangeValuesMutation.id);
+
+ expect(setRangeValuesCalls).toHaveLength(3);
+ expect(setRangeValuesCalls.map((call) => (call[1] as { unitId?: string }).unitId)).toEqual(['test', 'test', 'test']);
+ expect(setRangeValuesCalls[0]?.[1]).toMatchObject({
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ cellValue: {
+ 0: {
+ 0: { ref: 'A1:B2' },
+ },
+ },
+ });
+ expect(setRangeValuesCalls[1]?.[1]).toMatchObject({
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ cellValue: {
+ 0: {
+ 2: { ref: 'C1' },
+ },
+ },
+ });
+ expect(setRangeValuesCalls[2]?.[1]).toMatchObject({
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ cellValue: arrayFormulaCellData.test.sheet1,
+ });
+ });
+
+ it('should add prefixed formulas for workbook cells and defined names when calculation results arrive', async () => {
+ configService.setConfig(PLUGIN_CONFIG_KEY_BASE, { writeArrayFormulaToSnapshot: true });
+
+ const definedNamesService = testBed.injector.get(IDefinedNamesService);
+ const lexerTreeBuilder = testBed.injector.get(LexerTreeBuilder);
+ const executeCommandSpy = vi.spyOn(commandService, 'executeCommand');
+ const prefixSpy = vi
+ .spyOn(lexerTreeBuilder, 'getNewFormulaWithPrefix')
+ .mockImplementation((formula) => `PREFIX:${formula}`);
+
+ definedNamesService.registerDefinedNames('test', {
+ formulaName: {
+ id: 'formula-name',
+ name: 'FORMULA_NAME',
+ formulaOrRefString: '=SUM(A1)',
+ localSheetId: 'AllDefaultWorkbook',
+ comment: '',
+ },
+ refName: {
+ id: 'ref-name',
+ name: 'REF_NAME',
+ formulaOrRefString: 'Sheet1!$A$1',
+ localSheetId: 'AllDefaultWorkbook',
+ comment: '',
+ },
+ });
+
+ await commandService.executeCommand(SetFormulaCalculationResultMutation.id, {
+ unitData: {},
+ unitOtherData: {},
+ });
+
+ const setRangeValuesCalls = executeCommandSpy.mock.calls.filter(([id]) => id === SetRangeValuesMutation.id);
+ const setDefinedNameCalls = executeCommandSpy.mock.calls.filter(([id]) => id === SetDefinedNameMutation.id);
+
+ expect(prefixSpy).toHaveBeenCalledWith('=SUM(A1)', expect.any(Function));
+ expect(prefixSpy).toHaveBeenCalledWith('=SKIP()', expect.any(Function));
+ expect(setRangeValuesCalls.at(-1)?.[1]).toMatchObject({
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ cellValue: {
+ 3: {
+ 0: { xf: 'PREFIX:=SUM(A1)' },
+ 1: { xf: 'PREFIX:=SUM(A1)' },
+ },
+ },
+ });
+ expect(setDefinedNameCalls).toContainEqual([
+ SetDefinedNameMutation.id,
+ expect.objectContaining({
+ unitId: 'test',
+ name: 'FORMULA_NAME',
+ formulaOrRefStringWithPrefix: 'PREFIX:=SUM(A1)',
+ }),
+ expect.objectContaining({
+ onlyLocal: true,
+ fromFormula: true,
+ }),
+ ]);
+ });
+
+ it('should write prefixed formulas only for sheet units when calculation data includes other unit types', async () => {
+ configService.setConfig(PLUGIN_CONFIG_KEY_BASE, { writeArrayFormulaToSnapshot: true });
+
+ const lexerTreeBuilder = testBed.injector.get(LexerTreeBuilder);
+ const executeCommandSpy = vi.spyOn(commandService, 'executeCommand');
+ const prefixSpy = vi
+ .spyOn(lexerTreeBuilder, 'getNewFormulaWithPrefix')
+ .mockImplementation((formula) => `PREFIX:${formula}`);
+
+ vi.spyOn(formulaDataModel, 'getFormulaData').mockReturnValue({
+ test: {
+ sheet1: {
+ 3: {
+ 0: { f: '=SUM(A1)' },
+ },
+ },
+ },
+ 'base-unit': {
+ tasks: {
+ 0: {
+ 0: { f: '=SUM(A1)' },
+ },
+ },
+ },
+ } satisfies IFormulaData);
+
+ await commandService.executeCommand(SetFormulaCalculationResultMutation.id, {
+ unitData: {},
+ unitOtherData: {},
+ });
+
+ const setRangeValuesCalls = executeCommandSpy.mock.calls.filter(([id]) => id === SetRangeValuesMutation.id);
+
+ expect(prefixSpy).toHaveBeenCalledTimes(1);
+ expect(setRangeValuesCalls).toHaveLength(1);
+ expect(setRangeValuesCalls[0]?.[1]).toMatchObject({
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ cellValue: {
+ 3: {
+ 0: { xf: 'PREFIX:=SUM(A1)' },
+ },
+ },
+ });
});
it('should intercept array formula cells with default values, precision cleanup, raw passthrough and array values', () => {
diff --git a/packages/sheets-formula/src/controllers/array-formula-cell-interceptor.controller.ts b/packages/sheets-formula/src/controllers/array-formula-cell-interceptor.controller.ts
index 7c03fc8140..aef193607f 100644
--- a/packages/sheets-formula/src/controllers/array-formula-cell-interceptor.controller.ts
+++ b/packages/sheets-formula/src/controllers/array-formula-cell-interceptor.controller.ts
@@ -15,18 +15,24 @@
*/
import type { ICellData, ICommandInfo, Nullable, Workbook } from '@univerjs/core';
-import type { IArrayFormulaEmbeddedMap, IArrayFormulaRangeType, IArrayFormulaUnitCellType, ISetArrayFormulaDataMutationParams } from '@univerjs/engine-formula';
+import type { IArrayFormulaEmbeddedMap, IArrayFormulaRangeType, IArrayFormulaUnitCellType, ISetArrayFormulaDataMutationParams, ISetDefinedNameMutationParam } from '@univerjs/engine-formula';
import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';
-import { CellValueType, Disposable, ICommandService, Inject, InterceptorEffectEnum, isRealNum, IUniverInstanceService, ObjectMatrix, UniverInstanceType } from '@univerjs/core';
-import { FormulaDataModel, serializeRange, SetArrayFormulaDataMutation, stripErrorMargin } from '@univerjs/engine-formula';
+import type { IUniverSheetsFormulaBaseConfig } from '../config/config';
+import { CellValueType, Disposable, ICommandService, IConfigService, Inject, InterceptorEffectEnum, isRealNum, IUniverInstanceService, ObjectMatrix, UniverInstanceType } from '@univerjs/core';
+import { FormulaDataModel, IDefinedNamesService, IFunctionService, LexerTreeBuilder, serializeRange, SetArrayFormulaDataMutation, SetDefinedNameMutation, SetFormulaCalculationResultMutation, stripErrorMargin } from '@univerjs/engine-formula';
import { INTERCEPTOR_POINT, SetRangeValuesMutation, SheetInterceptorService } from '@univerjs/sheets';
+import { PLUGIN_CONFIG_KEY_BASE } from '../config/config';
export class ArrayFormulaCellInterceptorController extends Disposable {
constructor(
@ICommandService private readonly _commandService: ICommandService,
+ @IConfigService private readonly _configService: IConfigService,
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,
- @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel
+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,
+ @Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,
+ @IFunctionService private readonly _functionService: IFunctionService,
+ @IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService
) {
super();
@@ -43,6 +49,7 @@ export class ArrayFormulaCellInterceptorController extends Disposable {
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo) => {
// Synchronous data from worker
+ const isSSC = this._configService.getConfig<IUniverSheetsFormulaBaseConfig>(PLUGIN_CONFIG_KEY_BASE)?.writeArrayFormulaToSnapshot;
if (command.id === SetArrayFormulaDataMutation.id) {
const params = command.params as ISetArrayFormulaDataMutationParams;
@@ -50,14 +57,86 @@ export class ArrayFormulaCellInterceptorController extends Disposable {
return;
}
- const { arrayFormulaRange, arrayFormulaCellData } = params;
+ const { arrayFormulaRange, arrayFormulaCellData, arrayFormulaEmbedded } = params;
this._formulaDataModel.setArrayFormulaRange(arrayFormulaRange);
this._formulaDataModel.setArrayFormulaCellData(arrayFormulaCellData);
+
+ // Note the logic should only be executed in exporting and hence shall be set once.
+ if (isSSC) {
+ this._writeArrayFormulaToSnapshot(arrayFormulaRange, arrayFormulaCellData, arrayFormulaEmbedded);
+ }
+ } else if (command.id === SetFormulaCalculationResultMutation.id && isSSC) {
+ this._addPrefixToFunctionSnapshot();
+ this._addPrefixToDefinedNamesFunctionSnapshot();
}
})
);
}
+ private _addPrefixToDefinedNamesFunctionSnapshot() {
+ const allDefinedNames = this._definedNamesService.getAllDefinedNames();
+ Object.entries(allDefinedNames).forEach(([unitId, definedNames]) => {
+ definedNames && Array.from(Object.entries(definedNames)).forEach(([_, definedName]) => {
+ const { formulaOrRefString } = definedName;
+ if (formulaOrRefString.substring(0, 1) === '=') {
+ const newFormula = this._lexerTreeBuilder.getNewFormulaWithPrefix(formulaOrRefString, this._functionService.hasExecutor.bind(this._functionService));
+ if (newFormula) {
+ this._commandService.executeCommand<ISetDefinedNameMutationParam>(SetDefinedNameMutation.id, {
+ ...definedName,
+ unitId,
+ formulaOrRefStringWithPrefix: newFormula,
+ }, {
+ onlyLocal: true,
+ fromFormula: true,
+ });
+ }
+ }
+ });
+ });
+ }
+
+ private _addPrefixToFunctionSnapshot() {
+ const dataModel = this._formulaDataModel.getFormulaData();
+ const cacheMap = new Map<string, string>();
+ this._forEachSheetSnapshotData(dataModel, (unitId, subUnitId, formulaDataItem) => {
+ // Convert from IObjectMatrixPrimitiveType<IRange> to IObjectMatrixPrimitiveType<ICellData>
+ if (!formulaDataItem) {
+ return;
+ }
+ const cellValue = new ObjectMatrix<ICellData>();
+ const matrix = new ObjectMatrix(formulaDataItem);
+ matrix.forValue((row, col, value) => {
+ const functionText = value?.f;
+ if (value?.x != null || !functionText || functionText.length === 0) {
+ return;
+ }
+
+ if (cacheMap.has(functionText)) {
+ const cachedFormula = cacheMap.get(functionText)!;
+ cellValue.setValue(row, col, { xf: cachedFormula });
+ return;
+ }
+
+ const newFormula = this._lexerTreeBuilder.getNewFormulaWithPrefix(functionText, this._functionService.hasExecutor.bind(this._functionService));
+ if (newFormula) {
+ cellValue.setValue(row, col, { xf: newFormula });
+ cacheMap.set(functionText, newFormula);
+ }
+ });
+
+ // Keep this local to avoid triggering re-calculate in the worker.
+ this._commandService.executeCommand<ISetRangeValuesMutationParams>(SetRangeValuesMutation.id, {
+ unitId,
+ subUnitId,
+ cellValue: cellValue.getMatrix(),
+ }, {
+ onlyLocal: true,
+ fromFormula: true,
+ });
+ });
+ cacheMap.clear();
+ }
+
private _forEachSheetSnapshotData<T>(
snapshotData: Record<string, Nullable<Record<string, T>>> | null | undefined,
iterator: (unitId: string, subUnitId: string, data: T) => void