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
feat(formula): add host external reference contract (#7338)
Univer618bf1345925
diff --git a/packages/core/src/bases/typedef.ts b/packages/core/src/bases/typedef.tsindex 8fd3450358..b4a4702ab1 100644--- a/packages/core/src/bases/typedef.ts+++ b/packages/core/src/bases/typedef.ts@@ -15,6 +15,7 @@*/import type { ImageSourceType } from '../services/image-io/image-io.service';+import type { IResources } from '../services/resource-manager/type';import type { CellValueType, LocaleType } from '../types/enum';import type { IDocumentData } from '../types/interfaces';@@ -134,6 +135,7 @@ export interface IBaseSnapshot {createdAt: number;updatedAt: number;createdBy?: string;+ resources?: IResources;}export interface ITableSnapshot {diff --git a/packages/engine-formula/src/basics/common.ts b/packages/engine-formula/src/basics/common.tsindex 015436a960..420c1a57b1 100644--- a/packages/engine-formula/src/basics/common.ts+++ b/packages/engine-formula/src/basics/common.ts@@ -105,6 +105,22 @@ export interface IFormulaUnitNameMap {[unitId: string]: IFormulaUnitNameMapItem;}+export interface IFormulaExternalReferenceBinding {+ qualifier: string;+ sourceUnitId: string;+ sourceUnitType: FormulaUnitType;+}++export interface IFormulaExternalReferenceResource {+ schemaVersion: number;+ references: Record<string, IFormulaExternalReferenceBinding>;+}++/** Host-scoped External Reference resources keyed by the Host unitId. */+export interface IFormulaExternalReferences {+ [hostUnitId: string]: IFormulaExternalReferenceResource;+}+export interface IUnitSheetIdToNameMap {[unitId: string]: Nullable<{ [sheetId: string]: string }>;}@@ -247,6 +263,7 @@ export interface IFormulaDatasetConfig {unitStylesData?: IUnitStylesData;unitSheetNameMap?: IUnitSheetNameMap;unitNameMap?: IFormulaUnitNameMap;+ externalReferences?: IFormulaExternalReferences;maxIteration?: number;isCalculateTreeModel?: boolean;rowData?: IUnitRowData; // Include rows hidden by filtersdiff --git a/packages/engine-formula/src/controllers/__tests__/formula.controller.spec.ts b/packages/engine-formula/src/controllers/__tests__/formula.controller.spec.tsnew file mode 100644index 0000000000..5fa454f33f--- /dev/null+++ b/packages/engine-formula/src/controllers/__tests__/formula.controller.spec.ts@@ -0,0 +1,94 @@+/**+ * 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 { DataSyncPrimaryController } from '@univerjs/rpc';+import {+ CommandService,+ ConfigService,+ DesktopLogService,+ ICommandService,+ IConfigService,+ ILogService,+ Injector,+ LifecycleService,+ toDisposable,+} from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { ActiveDirtyManagerService, IActiveDirtyManagerService } from '../../services/active-dirty-manager.service';+import { FunctionService, IFunctionService } from '../../services/function.service';+import { RegisterOtherFormulaService } from '../../services/register-other-formula.service';+import { FormulaController } from '../formula.controller';++type FormulaDataSyncController = Pick<+ DataSyncPrimaryController,+ 'registerSyncingMutations' | 'syncUnitMutations'+>;++function createController(dataSyncPrimaryController?: FormulaDataSyncController): {+ controller: FormulaController;+ registerOtherFormulaService: RegisterOtherFormulaService;+} {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IFunctionService, { useClass: FunctionService }]);+ injector.add([IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }]);+ injector.add([LifecycleService]);+ injector.add([RegisterOtherFormulaService]);+ const registerOtherFormulaService = injector.get(RegisterOtherFormulaService);+ return {+ controller: new FormulaController(+ injector.get(ICommandService),+ injector.get(IFunctionService),+ injector.get(IConfigService),+ dataSyncPrimaryController,+ registerOtherFormulaService+ ),+ registerOtherFormulaService,+ };+}++describe('FormulaController', () => {+ it('registers mutation-only synchronization once per other-formula host', () => {+ const dispose = vi.fn();+ const dataSyncPrimaryController = {+ registerSyncingMutations: vi.fn<DataSyncPrimaryController['registerSyncingMutations']>(),+ syncUnitMutations: vi.fn<DataSyncPrimaryController['syncUnitMutations']>(() => toDisposable(dispose)),+ };+ const { controller, registerOtherFormulaService } = createController(dataSyncPrimaryController);++ registerOtherFormulaService.registerFormulaWithRange('doc-1', 'body-1', '=1');+ registerOtherFormulaService.registerFormulaWithRange('doc-1', 'body-1', '=2');+ registerOtherFormulaService.registerFormulaWithRange('slide-1', 'page-1', '=3');++ expect(dataSyncPrimaryController.syncUnitMutations).toHaveBeenCalledTimes(2);+ expect(dataSyncPrimaryController.syncUnitMutations).toHaveBeenNthCalledWith(1, 'doc-1');+ expect(dataSyncPrimaryController.syncUnitMutations).toHaveBeenNthCalledWith(2, 'slide-1');++ controller.dispose();+ expect(dispose).toHaveBeenCalledTimes(2);+ });++ it('supports formula registration when RPC data sync is unavailable', () => {+ const { controller, registerOtherFormulaService } = createController();++ expect(() => {+ registerOtherFormulaService.registerFormulaWithRange('doc-1', 'body-1', '=1');+ }).not.toThrow();+ controller.dispose();+ });+});diff --git a/packages/engine-formula/src/controllers/calculate.controller.ts b/packages/engine-formula/src/controllers/calculate.controller.tsindex cf6157dee5..ac63fc0c60 100644--- a/packages/engine-formula/src/controllers/calculate.controller.ts+++ b/packages/engine-formula/src/controllers/calculate.controller.ts@@ -107,7 +107,7 @@ export class CalculateController extends Disposable {private async _calculate(formulaDirtyData: Partial<IFormulaDirtyData>) {- const { forceCalculation: forceCalculate = false, dirtyRanges = [], dirtyNameMap = {}, dirtyDefinedNameMap = {}, dirtySuperTableMap = {}, dirtyUnitFeatureMap = {}, dirtyUnitOtherFormulaMap = {}, clearDependencyTreeCache = {}, maxIteration = DEFAULT_CYCLE_REFERENCE_COUNT, rowData, isCalculateTreeModel = false } = formulaDirtyData;+ const { forceCalculation: forceCalculate = false, dirtyRanges = [], dirtyNameMap = {}, dirtyDefinedNameMap = {}, dirtySuperTableMap = {}, dirtyUnitFeatureMap = {}, dirtyUnitOtherFormulaMap = {}, clearDependencyTreeCache = {}, maxIteration = DEFAULT_CYCLE_REFERENCE_COUNT, rowData, externalReferences, isCalculateTreeModel = false } = formulaDirtyData;const formulaData = this._formulaDataModel.getFormulaData();const arrayFormulaCellData = this._formulaDataModel.getArrayFormulaCellData();@@ -129,6 +129,7 @@ export class CalculateController extends Disposable {maxIteration,isCalculateTreeModel,rowData,+ externalReferences,});}diff --git a/packages/engine-formula/src/controllers/formula-calculation-session.controller.ts b/packages/engine-formula/src/controllers/formula-calculation-session.controller.tsindex d9c9428bc6..b94582df17 100644--- a/packages/engine-formula/src/controllers/formula-calculation-session.controller.ts+++ b/packages/engine-formula/src/controllers/formula-calculation-session.controller.ts@@ -19,7 +19,7 @@ import type {ISetFormulaCalculationNotificationMutation,ISetFormulaCalculationResultMutation,} from '../commands/mutations/set-formula-calculation.mutation';-import { Disposable, ICommandService, Inject } from '@univerjs/core';+import { Disposable, ICommandService, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import {SetFormulaCalculationNotificationMutation,SetFormulaCalculationResultMutation,@@ -46,6 +46,7 @@ function isFormulaCalculationResult(export class FormulaCalculationSessionController extends Disposable {constructor(@ICommandService private readonly _commandService: ICommandService,+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,@Inject(FormulaCalculationSessionService) private readonly _sessionService: FormulaCalculationSessionService,@Inject(RegisterOtherFormulaService) private readonly _registerOtherFormulaService: RegisterOtherFormulaService) {@@ -100,6 +101,10 @@ export class FormulaCalculationSessionController extends Disposable {pendingApplications.push(FormulaResultApplicationType.SHEET);}+ if (this._hasBaseResultToApply(params)) {+ pendingApplications.push(FormulaResultApplicationType.BASE);+ }+if (this._hasOtherFormulaResultToApply(params)) {pendingApplications.push(FormulaResultApplicationType.OTHER_FORMULA);}@@ -108,8 +113,22 @@ export class FormulaCalculationSessionController extends Disposable {}private _hasSheetResultToApply(result: ISetFormulaCalculationResultMutation): boolean {- return Object.values(result.unitData).some((sheetData) =>- sheetData != null && Object.values(sheetData).some((cellData) => cellData != null)+ return this._hasUnitResultToApply(result, UniverInstanceType.UNIVER_SHEET);+ }++ private _hasBaseResultToApply(result: ISetFormulaCalculationResultMutation): boolean {+ return this._hasUnitResultToApply(result, UniverInstanceType.UNIVER_BASE);+ }++ private _hasUnitResultToApply(+ result: ISetFormulaCalculationResultMutation,+ unitType: UniverInstanceType+ ): boolean {+ // Only registered host units have a matching result applicator. Unknown units must not keep the session pending.+ return Object.entries(result.unitData).some(([unitId, sheetData]) =>+ this._univerInstanceService.getUnit(unitId, unitType) != null+ && sheetData != null+ && Object.values(sheetData).some((cellData) => cellData != null));}diff --git a/packages/engine-formula/src/controllers/formula.controller.ts b/packages/engine-formula/src/controllers/formula.controller.tsindex 0220e65469..8011cf42d4 100644--- a/packages/engine-formula/src/controllers/formula.controller.ts+++ b/packages/engine-formula/src/controllers/formula.controller.ts@@ -18,7 +18,7 @@ import type { Ctor } from '@univerjs/core';import type { IFunctionNames } from '../basics/function';import type { IUniverEngineFormulaConfig } from '../config/config';import type { BaseFunction } from '../functions/base-function';-import { Disposable, ICommandService, IConfigService, Optional } from '@univerjs/core';+import { Disposable, ICommandService, IConfigService, Inject, Optional } from '@univerjs/core';import { DataSyncPrimaryController } from '@univerjs/rpc';import { RegisterFunctionMutation } from '../commands/mutations/register-function.mutation';import { SetArrayFormulaDataMutation } from '../commands/mutations/set-array-formula-data.mutation';@@ -48,13 +48,22 @@ import { RemoveSuperTableMutation, SetSuperTableMutation, SetSuperTableOptionMutimport { ENGINE_FORMULA_PLUGIN_CONFIG_KEY } from '../config/config';import { ALL_IMPLEMENTED_FUNCTIONS } from '../functions';import { IFunctionService } from '../services/function.service';+import { RegisterOtherFormulaService } from '../services/register-other-formula.service';++type FormulaDataSyncController = Pick<+ DataSyncPrimaryController,+ 'registerSyncingMutations' | 'syncUnitMutations'+>;export class FormulaController extends Disposable {+ private readonly _syncedOtherFormulaUnits = new Set<string>();+constructor(@ICommandService private readonly _commandService: ICommandService,@IFunctionService private readonly _functionService: IFunctionService,@IConfigService private readonly _configService: IConfigService,- @Optional(DataSyncPrimaryController) private readonly _dataSyncPrimaryController?: DataSyncPrimaryController+ @Optional(DataSyncPrimaryController) private readonly _dataSyncPrimaryController: FormulaDataSyncController | undefined,+ @Inject(RegisterOtherFormulaService) private readonly _registerOtherFormulaService: RegisterOtherFormulaService) {super();@@ -64,6 +73,23 @@ export class FormulaController extends Disposable {private _initialize(): void {this._registerCommands();this._registerFunctions();+ this._syncOtherFormulaUnits();+ }++ private _syncOtherFormulaUnits(): void {+ const dataSyncPrimaryController = this._dataSyncPrimaryController;+ if (!dataSyncPrimaryController) {+ return;+ }++ this.disposeWithMe(this._registerOtherFormulaService.formulaChangeWithRange$.subscribe(({ unitId }) => {+ if (this._syncedOtherFormulaUnits.has(unitId)) {+ return;+ }++ this._syncedOtherFormulaUnits.add(unitId);+ this.disposeWithMe(dataSyncPrimaryController.syncUnitMutations(unitId));+ }));}private _registerCommands(): void {diff --git a/packages/engine-formula/src/engine/analysis/__tests__/create-command-test-bed.ts b/packages/engine-formula/src/engine/analysis/__tests__/create-command-test-bed.tsindex d2dbdd2fb5..4119bcb552 100644--- a/packages/engine-formula/src/engine/analysis/__tests__/create-command-test-bed.ts+++ b/packages/engine-formula/src/engine/analysis/__tests__/create-command-test-bed.ts@@ -35,6 +35,10 @@ import { CalculateFormulaService, ICalculateFormulaService } from '../../../servimport { FormulaCurrentConfigService, IFormulaCurrentConfigService } from '../../../services/current-data.service';import { DefinedNamesService, IDefinedNamesService } from '../../../services/defined-names.service';import { DependencyManagerService, IDependencyManagerService } from '../../../services/dependency-manager.service';+import {+ IFormulaExternalReferenceDataLoader,+ NoopFormulaExternalReferenceDataLoader,+} from '../../../services/external-reference-data-loader.service';import {FeatureCalculationManagerService,IFeatureCalculationManagerService,@@ -302,6 +306,7 @@ function registerFormulaDependencies(injector: Injector) {injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);injector.add([IFormulaUnitReferenceResolver, { useClass: FormulaUnitReferenceResolver }]);+ injector.add([IFormulaExternalReferenceDataLoader, { useClass: NoopFormulaExternalReferenceDataLoader }]);injector.add([IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }]);injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);injector.add([IFunctionService, { useClass: FunctionService }]);diff --git a/packages/engine-formula/src/engine/ast-node/__tests__/reference-node.spec.ts b/packages/engine-formula/src/engine/ast-node/__tests__/reference-node.spec.tsnew file mode 100644index 0000000000..a564c8ac3a--- /dev/null+++ b/packages/engine-formula/src/engine/ast-node/__tests__/reference-node.spec.ts@@ -0,0 +1,79 @@+/**+ * 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 { IFormulaUnitReferenceResolver } from '../../../services/unit-reference-resolver.service';+import { describe, expect, it, vi } from 'vitest';+import { ReferenceObjectType } from '../../utils/value-object';+import { BaseAstNode } from '../base-ast-node';+import { ReferenceNode } from '../reference-node';+import { UnionNode } from '../union-node';++describe('ReferenceNode external range loading', () => {+ it('loads the full colon range from the qualified left reference', async () => {+ const load = vi.fn(async () => undefined);+ const currentConfig = {+ getSheetNameMap: () => ({}),+ getUnitData: () => ({}),+ getArrayFormulaCellData: () => ({}),+ getArrayFormulaRange: () => ({}),+ getUnitStylesData: () => ({}),+ };+ const runtime = {+ currentUnitId: 'host',+ currentSubUnitId: 'host-sheet',+ currentRow: 0,+ currentColumn: 0,+ getUnitData: () => ({}),+ getRuntimeArrayFormulaCellData: () => ({}),+ getUnitArrayFormula: () => ({}),+ getRuntimeFeatureCellData: () => ({}),+ };+ const resolver = {+ resolve: () => ({+ unitId: 'source',+ externalReference: {+ kind: 'host',+ qualifier: 'Sales',+ referenceId: 'sales',+ },+ }),+ } satisfies IFormulaUnitReferenceResolver;+ const superTableService = {+ getTableMap: () => null,+ getTableOptionMap: () => new Map(),+ };+ const left = new ReferenceNode(+ currentConfig,+ runtime,+ "'[Sales]Data'!A1",+ ReferenceObjectType.CELL,+ resolver,+ superTableService,+ { load },+ true+ );+ const right = new BaseAstNode('B2');+ const union = new UnionNode(':');+ left.setParent(union);+ right.setParent(union);++ await left.executeAsync();++ expect(load).toHaveBeenCalledWith(expect.objectContaining({+ token: "'[Sales]Data'!A1:B2",+ }));+ });+});diff --git a/packages/engine-formula/src/engine/ast-node/reference-node.ts b/packages/engine-formula/src/engine/ast-node/reference-node.tsindex a7893b0159..f88fd62970 100644--- a/packages/engine-formula/src/engine/ast-node/reference-node.ts+++ b/packages/engine-formula/src/engine/ast-node/reference-node.ts@@ -16,6 +16,7 @@import type { Nullable } from '@univerjs/core';import type { BaseReferenceObject } from '../reference-object/base-reference-object';+import { AstNodePromiseType } from '../../basics/common';import { ErrorType } from '../../basics/error-type';import {regexTestReferenceTableAllColumn,@@ -28,6 +29,7 @@ import {} from '../../basics/regex';import { matchToken } from '../../basics/token';import { IFormulaCurrentConfigService } from '../../services/current-data.service';+import { IFormulaExternalReferenceDataLoader } from '../../services/external-reference-data-loader.service';import { IFunctionService } from '../../services/function.service';import { IFormulaRuntimeService } from '../../services/runtime.service';import { ISuperTableService } from '../../services/super-table.service';@@ -48,21 +50,50 @@ interface ITableReferenceDescriptor {columnStruct: string | undefined;}+type ReferenceNodeCurrentConfigService = Pick<+ IFormulaCurrentConfigService,+ 'getArrayFormulaCellData' | 'getArrayFormulaRange' | 'getSheetNameMap' | 'getUnitData' | 'getUnitStylesData'+>;++type ReferenceNodeRuntimeService = Pick<+ IFormulaRuntimeService,+ | 'currentColumn'+ | 'currentRow'+ | 'currentSubUnitId'+ | 'currentUnitId'+ | 'getRuntimeArrayFormulaCellData'+ | 'getRuntimeFeatureCellData'+ | 'getUnitArrayFormula'+ | 'getUnitData'+>;++type ReferenceNodeSuperTableService = Pick<+ ISuperTableService,+ 'getTableMap' | 'getTableOptionMap'+>;+export class ReferenceNode extends BaseAstNode {private _refOffsetX = 0;private _refOffsetY = 0;constructor(- private _currentConfigService: IFormulaCurrentConfigService,- private _runtimeService: IFormulaRuntimeService,+ private _currentConfigService: ReferenceNodeCurrentConfigService,+ private _runtimeService: ReferenceNodeRuntimeService,operatorString: string,private _referenceObjectType: ReferenceObjectType,private _unitReferenceResolver: IFormulaUnitReferenceResolver,- private _superTableService: ISuperTableService,+ private _superTableService: ReferenceNodeSuperTableService,+ private _externalReferenceDataLoader: IFormulaExternalReferenceDataLoader,private _isPrepareMerge: boolean = false,private _tableReference?: ITableReferenceDescriptor) {super(operatorString);+ const unitQualifier = _tableReference+ ? _tableReference.unitQualifier+ : getReferenceObjectFromCache(operatorString, _referenceObjectType).getUnitQualifier();+ if (unitQualifier) {+ this.setAsync();+ }}override get nodeType() {@@ -125,10 +156,69 @@ export class ReferenceNode extends BaseAstNode {}}+ override async executeAsync(): Promise<AstNodePromiseType> {+ const hostUnitId = this._runtimeService.currentUnitId;+ const unitQualifier = this._tableReference+ ? this._tableReference.unitQualifier+ : getReferenceObjectFromCache(this.getToken(), this._referenceObjectType).getUnitQualifier();+ if (!unitQualifier) {+ this.execute();+ return AstNodePromiseType.SUCCESS;+ }++ const referenceKind = this._tableReference ? 'table' : 'a1';+ const resolution = this._unitReferenceResolver.resolve({+ hostUnitId,+ qualifier: unitQualifier,+ referenceKind,+ });+ if (typeof resolution === 'string') {+ this.setValue(ErrorValueObject.create(resolution));+ return AstNodePromiseType.ERROR;+ }++ if (resolution.externalReference) {+ const token = this._getExternalLoadToken();+ const error = await this._externalReferenceDataLoader.load({+ hostUnitId,+ qualifier: unitQualifier,+ referenceKind,+ token,+ tableName: this._tableReference?.tableName,+ columnStruct: this._tableReference?.columnStruct,+ resolution,+ });+ if (error) {+ this.setValue(ErrorValueObject.create(error));+ return AstNodePromiseType.ERROR;+ }+ }++ this.execute();+ return AstNodePromiseType.SUCCESS;+ }++ /**+ * A1 ranges are represented as two ReferenceNodes under a `:` UnionNode.+ * The qualified left node owns the external read, so include the right+ * boundary and materialize the whole rectangular range in one request.+ */+ private _getExternalLoadToken(): string {+ const parent = this.getParent();+ if (parent?.nodeType !== NodeType.UNION || parent.getToken() !== matchToken.COLON) {+ return this.getToken();+ }+ const [left, right] = parent.getChildren();+ if (left !== this || right == null) {+ return this.getToken();+ }+ return `${this.getToken()}${matchToken.COLON}${right.getToken()}`;+ }+private _configureReferenceObject(referenceObject: BaseReferenceObject,- currentConfigService: IFormulaCurrentConfigService,- runtimeService: IFormulaRuntimeService+ currentConfigService: ReferenceNodeCurrentConfigService,+ runtimeService: ReferenceNodeRuntimeService): void {referenceObject.setDefaultUnitId(runtimeService.currentUnitId);referenceObject.setDefaultSheetId(runtimeService.currentSubUnitId);@@ -165,7 +255,9 @@ export class ReferenceNodeFactory extends BaseAstNodeFactory {@IFormulaRuntimeService private readonly _formulaRuntimeService: IFormulaRuntimeService,@IFunctionService private readonly _functionService: IFunctionService,@ISuperTableService private readonly _superTableService: ISuperTableService,- @IFormulaUnitReferenceResolver private readonly _unitReferenceResolver: IFormulaUnitReferenceResolver+ @IFormulaUnitReferenceResolver private readonly _unitReferenceResolver: IFormulaUnitReferenceResolver,+ @IFormulaExternalReferenceDataLoader+ private readonly _externalReferenceDataLoader: IFormulaExternalReferenceDataLoader) {super();}@@ -234,7 +326,7 @@ export class ReferenceNodeFactory extends BaseAstNodeFactory {const runtimeService = this._formulaRuntimeService;const makeRef = (type: ReferenceObjectType) =>- new ReferenceNode(currentConfigService, runtimeService, tokenTrim, type, this._unitReferenceResolver, this._superTableService, isPrepareMerge);+ new ReferenceNode(currentConfigService, runtimeService, tokenTrim, type, this._unitReferenceResolver, this._superTableService, this._externalReferenceDataLoader, isPrepareMerge);const tableMap = this._getTableMap();const isSuperTableDirect = tableMap?.has(tokenTrim) ?? false;@@ -276,6 +368,7 @@ export class ReferenceNodeFactory extends BaseAstNodeFactory {ReferenceObjectType.COLUMN,this._unitReferenceResolver,this._superTableService,+ this._externalReferenceDataLoader,isPrepareMerge,{ unitQualifier, tableName, columnStruct });diff --git a/packages/engine-formula/src/engine/dependency/formula-dependency.ts b/packages/engine-formula/src/engine/dependency/formula-dependency.tsindex 76e03a631d..06b76d630e 100644--- a/packages/engine-formula/src/engine/dependency/formula-dependency.ts+++ b/packages/engine-formula/src/engine/dependency/formula-dependency.ts@@ -295,7 +295,9 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDecontinue;}- const { rowCount = Infinity, columnCount = Infinity } = this._currentConfigService.getSheetRowColumnCount(unitId, subUnitId) || {};+ const sheetSize = this._currentConfigService.getSheetRowColumnCount(unitId, subUnitId);+ const rowCount = sheetSize.rowCount > 0 ? sheetSize.rowCount : Infinity;+ const columnCount = sheetSize.columnCount > 0 ? sheetSize.columnCount : Infinity;const subFormulaDataKeys = Object.keys(subFormulaData);for (const subFormulaDataId of subFormulaDataKeys) {diff --git a/packages/engine-formula/src/engine/interpreter/__tests__/interpreter.spec.ts b/packages/engine-formula/src/engine/interpreter/__tests__/interpreter.spec.tsnew file mode 100644index 0000000000..7cff53e0b9--- /dev/null+++ b/packages/engine-formula/src/engine/interpreter/__tests__/interpreter.spec.ts@@ -0,0 +1,54 @@+/**+ * 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, vi } from 'vitest';+import { AstNodePromiseType } from '../../../basics/common';+import { BaseAstNode } from '../../ast-node/base-ast-node';+import { NumberValueObject } from '../../value-object/primitive-object';+import { Interpreter } from '../interpreter';++class AsyncReferenceLikeNode extends BaseAstNode {+ readonly executeAsyncSpy = vi.fn(async () => {+ this.setValue(NumberValueObject.create(42));+ return AstNodePromiseType.SUCCESS;+ });++ constructor() {+ super('[Remote]Sheet1!A1');+ this.setAsync();+ }++ override executeAsync() {+ return this.executeAsyncSpy();+ }+}++describe('Interpreter async nodes', () => {+ it('detects and awaits an async root node regardless of node type', async () => {+ const interpreter = new Interpreter({+ currentColumn: 0,+ currentRow: 0,+ isStopExecution: () => false,+ });+ const node = new AsyncReferenceLikeNode();++ expect(interpreter.checkAsyncNode(node)).toBe(true);+ const value = await interpreter.executeAsync({ node, refOffsetX: 0, refOffsetY: 0 });++ expect(node.executeAsyncSpy).toHaveBeenCalledOnce();+ expect((value as NumberValueObject).getValue()).toBe(42);+ });+});diff --git a/packages/engine-formula/src/engine/interpreter/interpreter.ts b/packages/engine-formula/src/engine/interpreter/interpreter.tsindex 64bcbd086d..c5950ab85e 100644--- a/packages/engine-formula/src/engine/interpreter/interpreter.ts+++ b/packages/engine-formula/src/engine/interpreter/interpreter.ts@@ -16,7 +16,6 @@import type { Nullable } from '@univerjs/core';import type { BaseAstNode } from '../ast-node/base-ast-node';-import type { FunctionNode } from '../ast-node/function-node';import type { LambdaNode } from '../ast-node/lambda-node';import type { ReferenceNode } from '../ast-node/reference-node';import type { BaseReferenceObject, FunctionVariantType } from '../reference-object/base-reference-object';@@ -34,8 +33,13 @@ import { NodeType } from '../ast-node/node-type';import { ErrorValueObject } from '../value-object/base-value-object';import { BooleanValueObject, NumberValueObject } from '../value-object/primitive-object';+type InterpreterRuntimeService = Pick<+ IFormulaRuntimeService,+ 'currentColumn' | 'currentRow' | 'isStopExecution'+>;+export class Interpreter extends Disposable {- constructor(@IFormulaRuntimeService private readonly _runtimeService: IFormulaRuntimeService) {+ constructor(@IFormulaRuntimeService private readonly _runtimeService: InterpreterRuntimeService) {super();}@@ -96,6 +100,9 @@ export class Interpreter extends Disposable {if (node == null) {return false;}+ if (node.isAsync()) {+ return true;+ }const result: boolean[] = [];this._checkAsyncNode(node, result);@@ -148,7 +155,7 @@ export class Interpreter extends Disposable {(node as ReferenceNode).setRefOffset(refOffsetX, refOffsetY);}- if (node.nodeType === NodeType.FUNCTION && (node as FunctionNode).isAsync()) {+ if (node.isAsync()) {await node.executeAsync();} else {node.execute();diff --git a/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts b/packages/engine-formula/src/functions/__tests__/create-function-test-bed.tsindex ae141d645d..55e09826c3 100644--- a/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts+++ b/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts@@ -50,6 +50,10 @@ import { FormulaDataModel } from '../../models/formula-data.model';import { CalculateFormulaService, ICalculateFormulaService } from '../../services/calculate-formula.service';import { FormulaCurrentConfigService, IFormulaCurrentConfigService } from '../../services/current-data.service';import { DefinedNamesService, IDefinedNamesService } from '../../services/defined-names.service';+import {+ IFormulaExternalReferenceDataLoader,+ NoopFormulaExternalReferenceDataLoader,+} from '../../services/external-reference-data-loader.service';import { FunctionService, IFunctionService } from '../../services/function.service';import { HyperlinkEngineFormulaService, IHyperlinkEngineFormulaService } from '../../services/hyperlink-engine-formula.service';import { IOtherFormulaManagerService, OtherFormulaManagerService } from '../../services/other-formula-manager.service';@@ -178,6 +182,7 @@ export function createFunctionTestBed(workbookData?: IWorkbookData, dependenciesinjector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);injector.add([IFormulaUnitReferenceResolver, { useClass: FormulaUnitReferenceResolver }]);+ injector.add([IFormulaExternalReferenceDataLoader, { useClass: NoopFormulaExternalReferenceDataLoader }]);injector.add([IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }]);injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);injector.add([IFunctionService, { useClass: FunctionService }]);diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.tsindex 4d333c28c7..6d6d56eabc 100644--- a/packages/engine-formula/src/index.ts+++ b/packages/engine-formula/src/index.ts@@ -29,6 +29,9 @@ export type {IFormulaDataItem,IFormulaDatasetConfig,IFormulaExecuteResultMap,+ IFormulaExternalReferenceBinding,+ IFormulaExternalReferenceResource,+ IFormulaExternalReferences,IFormulaStringMap,IFormulaUnitNameMap,IFormulaUnitNameMapItem,@@ -295,6 +298,11 @@ export type {export { IDependencyManagerService } from './services/dependency-manager.service';export { DependencyManagerService } from './services/dependency-manager.service';export { DependencyManagerBaseService } from './services/dependency-manager.service';+export {+ IFormulaExternalReferenceDataLoader,+ NoopFormulaExternalReferenceDataLoader,+} from './services/external-reference-data-loader.service';+export type { IFormulaExternalReferenceLoadInput } from './services/external-reference-data-loader.service';export {FeatureCalculationManagerService,IFeatureCalculationManagerService,diff --git a/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.tsindex f225e8f793..b2a7da766e 100644--- a/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts+++ b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts@@ -1092,6 +1092,21 @@ describe('Test formula data model', () => {'=SUM([Host.xlsx]Sheet1!$A$1:$B$10)');});++ it('should preserve workbook-qualified structured references in Base formulas', () => {+ const univerInstanceService = get(IUniverInstanceService);+ univerInstanceService.registerCtorForType(UniverInstanceType.UNIVER_BASE, BaseDataModel);+ const snapshot = structuredClone(TEST_BASE_DATA);+ snapshot.id = 'base-external-table';+ snapshot.tables!['table-main'].fields.total.config = {+ formula: '=SUM([Orders Base]!Orders[Amount])',+ };+ univer.createUnit(UniverInstanceType.UNIVER_BASE, snapshot);++ expect(formulaDataModel.getFormulaData()['base-external-table']?.['table-main']?.[0]?.[6]?.f).toBe(+ '=SUM([Orders Base]!Orders[Amount])'+ );+ });});});diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.tsindex d2b64ed062..29bdc20334 100644--- a/packages/engine-formula/src/models/formula-data.model.ts+++ b/packages/engine-formula/src/models/formula-data.model.ts@@ -940,6 +940,7 @@ const BASE_LEGACY_FIELD_REF_PATTERN = /\{([^}]+)\}/g;const BASE_TABLE_FIELD_REF_PATTERN = /\b([A-Z_]\w*)\[([^\]]+)\]/gi;const BASE_BRACKET_FIELD_REF_PATTERN = /(^|[^A-Za-z0-9_\]\[])\[([^\]]+)\]/g;const BASE_EXTERNAL_A1_REF_PATTERN = /(?:'\[[^\]]+\](?:[^']|'')+'|\[[^\]]+\][^\s'!]+)!\$?[A-Z]{1,3}\$?\d+(?::\$?[A-Z]{1,3}\$?\d+)?/gi;+const BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX = /(?:'((?:[^']|'')+)'|\[[^\]]+\]|[A-Za-z0-9_.-]+)![^\s!\[\]]+\[/g;function normalizeBaseFormulaForEngine(formula: string, currentTable: ITableSnapshot, snapshot: IBaseSnapshot): string {const refs: string[] = [];@@ -947,8 +948,7 @@ function normalizeBaseFormulaForEngine(formula: string, currentTable: ITableSnapconst index = refs.push(ref) - 1;return `__BASE_FORMULA_REF_${index}__`;};- const normalized = formula- .replace(BASE_EXTERNAL_A1_REF_PATTERN, (reference) => hold(reference))+ const normalized = protectBaseExternalReferences(formula, hold).replace(BASE_LEGACY_FIELD_REF_PATTERN, (_match, fieldName: string) => hold(createEngineThisRowRef(currentTable, fieldName, snapshot))).replace(BASE_TABLE_FIELD_REF_PATTERN, (_match, sourceTableName: string, fieldName: string) => {const targetTable = resolveBaseFormulaTable(sourceTableName, currentTable, snapshot);@@ -958,6 +958,59 @@ function normalizeBaseFormulaForEngine(formula: string, currentTable: ITableSnapreturn normalized.replace(/__BASE_FORMULA_REF_(\d+)__/g, (_match, index: string) => refs[Number(index)] ?? '');}+function protectBaseExternalReferences(formula: string, replace: (reference: string) => string): string {+ const withProtectedA1 = formula.replace(BASE_EXTERNAL_A1_REF_PATTERN, (reference, offset: number) =>+ isInsideBaseFormulaString(formula, offset) ? reference : replace(reference));+ return protectBaseExternalStructuredReferences(withProtectedA1, replace);+}++function protectBaseExternalStructuredReferences(+ formula: string,+ replace: (reference: string) => string+): string {+ const spans: Array<{ start: number; end: number }> = [];+ BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX.lastIndex = 0;+ let match: RegExpExecArray | null;+ while ((match = BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX.exec(formula)) != null) {+ if (isInsideBaseFormulaString(formula, match.index)) continue;+ const openBracket = BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX.lastIndex - 1;+ let depth = 0;+ for (let index = openBracket; index < formula.length; index++) {+ if (formula[index] === '[') depth++;+ if (formula[index] !== ']') continue;+ depth--;+ if (depth === 0) {+ spans.push({ start: match.index, end: index + 1 });+ BASE_EXTERNAL_STRUCTURED_REFERENCE_PREFIX.lastIndex = index + 1;+ break;+ }+ }+ }+ if (spans.length === 0) return formula;++ let result = '';+ let offset = 0;+ for (const span of spans) {+ result += formula.slice(offset, span.start);+ result += replace(formula.slice(span.start, span.end));+ offset = span.end;+ }+ return result + formula.slice(offset);+}++function isInsideBaseFormulaString(formula: string, position: number): boolean {+ let inString = false;+ for (let index = 0; index < position; index++) {+ if (formula[index] !== '"') continue;+ if (inString && formula[index + 1] === '"') {+ index++;+ continue;+ }+ inString = !inString;+ }+ return inString;+}+function createEngineThisRowRef(table: ITableSnapshot, fieldName: string, snapshot: IBaseSnapshot): string {return `${getEngineBaseTableName(table, snapshot)}[[#This Row],[${fieldName}]]`;}diff --git a/packages/engine-formula/src/plugin.ts b/packages/engine-formula/src/plugin.tsindex 7e5da89b5e..a4fcbe2536 100644--- a/packages/engine-formula/src/plugin.ts+++ b/packages/engine-formula/src/plugin.ts@@ -48,6 +48,10 @@ import { FormulaDataModel } from './models/formula-data.model';import { ActiveDirtyManagerService, IActiveDirtyManagerService } from './services/active-dirty-manager.service';import { CalculateFormulaService, ICalculateFormulaService } from './services/calculate-formula.service';import { FormulaCurrentConfigService, IFormulaCurrentConfigService } from './services/current-data.service';+import {+ IFormulaExternalReferenceDataLoader,+ NoopFormulaExternalReferenceDataLoader,+} from './services/external-reference-data-loader.service';import { DefinedNamesService, IDefinedNamesService } from './services/defined-names.service';import { DependencyManagerService, IDependencyManagerService } from './services/dependency-manager.service';import {@@ -195,6 +199,7 @@ export class UniverFormulaEnginePlugin extends Plugin {[IDependencyManagerService, { useClass: DependencyManagerService }],[IFormulaDependencyGenerator, { useClass: FormulaDependencyGenerator }],[IFormulaUnitReferenceResolver, { useClass: FormulaUnitReferenceResolver }],+ [IFormulaExternalReferenceDataLoader, { useClass: NoopFormulaExternalReferenceDataLoader }],];dependencies.forEach((dependency) => this._injector.add(dependency));diff --git a/packages/engine-formula/src/services/__tests__/register-other-formula.service.spec.ts b/packages/engine-formula/src/services/__tests__/register-other-formula.service.spec.tsindex 4c3538f1e2..cdb54d9ded 100644--- a/packages/engine-formula/src/services/__tests__/register-other-formula.service.spec.ts+++ b/packages/engine-formula/src/services/__tests__/register-other-formula.service.spec.ts@@ -101,6 +101,19 @@ describe('RegisterOtherFormulaService', () => {expect(executedIds).toContain(SetOtherFormulaMutation.id);});+ it('should expose all registered formulas for host-level dirty propagation', () => {+ const { service } = createService();++ const firstFormulaId = service.registerFormulaWithRange('unit-1', 'sheet-1', '=A1');+ const secondFormulaId = service.registerFormulaWithRange('unit-1', 'sheet-2', '=B2');++ expect(service.getFormulaDirtyMap('unit-1')).toEqual({+ 'sheet-1': { [firstFormulaId]: true },+ 'sheet-2': { [secondFormulaId]: true },+ });+ expect(service.getFormulaDirtyMap('missing-unit')).toEqual({});+ });+it('should cache formula results and resolve pending getFormulaValue', async () => {const { service, commandService } = createService();diff --git a/packages/engine-formula/src/services/current-data.service.ts b/packages/engine-formula/src/services/current-data.service.tsindex 2f82df4692..fa3e1b26c6 100644--- a/packages/engine-formula/src/services/current-data.service.ts+++ b/packages/engine-formula/src/services/current-data.service.ts@@ -24,6 +24,7 @@ import type {IDirtyUnitSuperTableMap,IFormulaData,IFormulaDatasetConfig,+ IFormulaExternalReferences,IFormulaUnitNameMap,IRuntimeUnitDataType,IUnitData,@@ -58,6 +59,7 @@ export interface IFormulaDirtyData {maxIteration?: number;isCalculateTreeModel?: boolean; // whether to calculate the dependency tree modelrowData?: IUnitRowData; // Include rows hidden by filters+ externalReferences?: IFormulaExternalReferences;}export interface IFormulaCurrentConfigService {@@ -76,6 +78,10 @@ export interface IFormulaCurrentConfigService {getUnitNameMap(): IFormulaUnitNameMap;+ getExternalReferences(): IFormulaExternalReferences;++ getCalculationGeneration(): number;+isForceCalculate(): boolean;getDirtyRanges(): IUnitRange[];@@ -149,6 +155,10 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaCprivate _unitNameMap: IFormulaUnitNameMap = {};+ private _externalReferences: IFormulaExternalReferences = {};++ private _calculationGeneration = 0;+private _forceCalculate: boolean = false;private _clearDependencyTreeCache: IDirtyUnitSheetNameMap = {};@@ -190,6 +200,7 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaCthis._formulaData = {};this._sheetNameMap = {};this._unitNameMap = {};+ this._externalReferences = {};this._clearDependencyTreeCache = {};this._dirtyRanges = [];this._dirtyNameMap = {};@@ -249,6 +260,14 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaCreturn this._unitNameMap;}+ getExternalReferences() {+ return this._externalReferences;+ }++ getCalculationGeneration() {+ return this._calculationGeneration;+ }+isForceCalculate() {return this._forceCalculate;}@@ -334,6 +353,7 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC}load(config: IFormulaDatasetConfig) {+ this._calculationGeneration++;if (config.allUnitData && config.unitSheetNameMap && config.unitStylesData) {this._unitData = config.allUnitData;this._unitStylesData = config.unitStylesData;@@ -378,6 +398,8 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaCthis._dirtyUnitOtherFormulaMap = config.dirtyUnitOtherFormulaMap;+ this._externalReferences = config.externalReferences ?? {};+this._excludedCell = config.excludedCell;this._mergeNameMap(this._sheetNameMap, this._dirtyNameMap);@@ -412,6 +434,7 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaCdirtyUnitFeatureMap: this._dirtyUnitFeatureMap,dirtyUnitOtherFormulaMap: this._dirtyUnitOtherFormulaMap,clearDependencyTreeCache: this._clearDependencyTreeCache,+ externalReferences: this._externalReferences,};}diff --git a/packages/engine-formula/src/services/external-reference-data-loader.service.ts b/packages/engine-formula/src/services/external-reference-data-loader.service.tsnew file mode 100644index 0000000000..8da5eb7b07--- /dev/null+++ b/packages/engine-formula/src/services/external-reference-data-loader.service.ts@@ -0,0 +1,51 @@+/**+ * 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 { IRange } from '@univerjs/core';+import type { ErrorType } from '../basics/error-type';+import type {+ FormulaUnitReferenceKind,+ IFormulaUnitReferenceResolution,+} from './unit-reference-resolver.service';+import { createIdentifier } from '@univerjs/core';++export interface IFormulaExternalReferenceLoadInput {+ hostUnitId: string;+ qualifier: string;+ referenceKind: FormulaUnitReferenceKind;+ token: string;+ tableName?: string;+ columnStruct?: string;+ resolution: IFormulaUnitReferenceResolution;+}++export interface IFormulaExternalReferenceDataLoader {+ load(input: IFormulaExternalReferenceLoadInput): Promise<ErrorType | void>;+ loadRuntimeRange?(input: {+ hostUnitId: string;+ unitId: string;+ sheetId: string;+ sheetName?: string;+ range: IRange;+ }): Promise<ErrorType | boolean | void>;+}++export const IFormulaExternalReferenceDataLoader =+ createIdentifier<IFormulaExternalReferenceDataLoader>('univer.formula.external-reference-data-loader');++export class NoopFormulaExternalReferenceDataLoader implements IFormulaExternalReferenceDataLoader {+ async load(): Promise<void> {}+}diff --git a/packages/engine-formula/src/services/formula/formula-calculation-session.service.ts b/packages/engine-formula/src/services/formula/formula-calculation-session.service.tsindex b0b4f6976c..54a9c17430 100644--- a/packages/engine-formula/src/services/formula/formula-calculation-session.service.ts+++ b/packages/engine-formula/src/services/formula/formula-calculation-session.service.ts@@ -34,6 +34,7 @@ export interface IFormulaCalculationSessionState {export enum FormulaResultApplicationType {SHEET = 'sheet',+ BASE = 'base',OTHER_FORMULA = 'other-formula',}diff --git a/packages/engine-formula/src/services/register-other-formula.service.ts b/packages/engine-formula/src/services/register-other-formula.service.tsindex 0f4bf2f780..25cabb8541 100644--- a/packages/engine-formula/src/services/register-other-formula.service.ts+++ b/packages/engine-formula/src/services/register-other-formula.service.ts@@ -22,7 +22,14 @@ import type {ISetOtherFormulaMutationParams,} from '../commands/mutations/set-other-formula.mutation';import type { IOtherFormulaResult } from './formula-common';-import { Disposable, generateRandomId, ICommandService, Inject, LifecycleService, ObjectMatrix } from '@univerjs/core';+import {+ Disposable,+ generateRandomId,+ ICommandService,+ Inject,+ LifecycleService,+ ObjectMatrix,+} from '@univerjs/core';import { BehaviorSubject, bufferWhen, filter, skip, Subject } from 'rxjs';import { OtherFormulaMarkDirty } from '../commands/mutations/formula.mutation';import { SetFormulaCalculationResultMutation } from '../commands/mutations/set-formula-calculation.mutation';@@ -230,6 +237,20 @@ export class RegisterOtherFormulaService extends Disposable {return formulaId;}+ getFormulaDirtyMap(unitId: string): Record<string, Record<string, boolean>> {+ const unitMap = this._formulaCacheMap.get(unitId);+ if (!unitMap) {+ return {};+ }++ return Object.fromEntries(+ Array.from(unitMap.entries(), ([subUnitId, formulas]) => [+ subUnitId,+ Object.fromEntries(Array.from(formulas.keys(), (formulaId) => [formulaId, true])),+ ])+ );+ }+deleteFormula(unitId: string, subUnitId: string, formulaIdList: string[]) {const params: IRemoveOtherFormulaMutationParams = {unitId,diff --git a/packages/engine-formula/src/services/unit-reference-resolver.service.ts b/packages/engine-formula/src/services/unit-reference-resolver.service.tsindex 49f7cea765..9f359ce6f2 100644--- a/packages/engine-formula/src/services/unit-reference-resolver.service.ts+++ b/packages/engine-formula/src/services/unit-reference-resolver.service.ts@@ -30,6 +30,12 @@ export interface IFormulaUnitReferenceResolveInput {export interface IFormulaUnitReferenceResolution {unitId: string;unitType?: FormulaUnitType;+ externalReference?: {+ kind: 'host' | 'ooxml';+ qualifier: string;+ referenceId?: string;+ slot?: number;+ };}export interface IFormulaUnitReferenceResolver {diff --git a/packages/rpc/src/controllers/data-sync/__tests__/data-sync.controller.spec.ts b/packages/rpc/src/controllers/data-sync/__tests__/data-sync.controller.spec.tsindex 44deb75eb1..93dc0cbb05 100644--- a/packages/rpc/src/controllers/data-sync/__tests__/data-sync.controller.spec.ts+++ b/packages/rpc/src/controllers/data-sync/__tests__/data-sync.controller.spec.ts@@ -193,6 +193,17 @@ describe('data-sync controllers', () => {await flushPromises();expect(remoteInstanceImpl.syncMutation).toHaveBeenCalledTimes(2);+ const unit3Disposable = controller.syncUnitMutations('unit-3');+ commandCallback?.({+ id: 'm-sync',+ type: CommandType.MUTATION,+ params: { unitId: 'unit-3' },+ }, {});+ await flushPromises();+ expect(remoteInstanceImpl.createInstance).toHaveBeenCalledTimes(2);+ expect(remoteInstanceImpl.syncMutation).toHaveBeenCalledTimes(3);+ unit3Disposable.dispose();+controller.dispose();});diff --git a/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts b/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.tsindex 12b27026d3..c73aa2838f 100644--- a/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts+++ b/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts@@ -97,6 +97,17 @@ export class DataSyncPrimaryController extends RxDisposable {});}+ /** Sync registered mutations for a unit without creating a replica unit. */+ syncUnitMutations(unitId: string): IDisposable {+ const alreadySyncing = this._syncingUnits.has(unitId);+ this._syncingUnits.add(unitId);+ return toDisposable(() => {+ if (!alreadySyncing) {+ this._syncingUnits.delete(unitId);+ }+ });+ }+private _initRPCChannels(): void {// for the worker to callthis._rpcChannelService.registerChannel(RemoteSyncServiceName, fromModule(this._remoteSyncService));diff --git a/packages/sheets-formula-ui/src/facade/__tests__/create-formula-test-bed.ts b/packages/sheets-formula-ui/src/facade/__tests__/create-formula-test-bed.tsindex 4d0d65509d..75992d68bb 100644--- a/packages/sheets-formula-ui/src/facade/__tests__/create-formula-test-bed.ts+++ b/packages/sheets-formula-ui/src/facade/__tests__/create-formula-test-bed.ts@@ -52,6 +52,7 @@ import {IDescriptionService,IFeatureCalculationManagerService,IFormulaCurrentConfigService,+ IFormulaExternalReferenceDataLoader,IFormulaRuntimeService,IFunctionService,IHyperlinkEngineFormulaService,@@ -64,6 +65,7 @@ import {LambdaParameterNodeFactory,Lexer,LexerTreeBuilder,+ NoopFormulaExternalReferenceDataLoader,OperatorNodeFactory,OtherFormulaManagerService,PrefixNodeFactory,@@ -197,6 +199,7 @@ function registerFormulaDependencies(injector: Injector) {injector.add([LexerTreeBuilder]);injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);+ injector.add([IFormulaExternalReferenceDataLoader, { useClass: NoopFormulaExternalReferenceDataLoader }]);injector.add([IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }]);injector.add([IDependencyManagerService, { useClass: DependencyManagerService }]);injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);diff --git a/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.tsindex d07dde00d2..53f0369383 100644--- a/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.ts+++ b/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.ts@@ -71,7 +71,7 @@ function createWorkbookData(): IWorkbookData {};}-function createControllerTestBed() {+function createControllerTestBed(initialFormulaComputing = CalculationMode.WHEN_EMPTY) {const dependencies: Dependency[] = [[IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],[FormulaCalculationTriggerService],@@ -87,7 +87,7 @@ function createControllerTestBed() {const commandService = injector.get(ICommandService);const configService = injector.get(IConfigService);- configService.setConfig(PLUGIN_CONFIG_KEY_BASE, { initialFormulaComputing: CalculationMode.WHEN_EMPTY }, { merge: true });+ configService.setConfig(PLUGIN_CONFIG_KEY_BASE, { initialFormulaComputing }, { merge: true });configService.setConfig(ENGINE_FORMULA_RETURN_DEPENDENCY_TREE, true);configService.setConfig(ENGINE_FORMULA_CYCLE_REFERENCE_COUNT, 7);@@ -184,6 +184,18 @@ describe('TriggerCalculationController', () => {testBed.testBed.univer.dispose();});+ it('should not enqueue an empty initial calculation in no-calculation mode', async () => {+ const testBed = createControllerTestBed(CalculationMode.NO_CALCULATION);++ await Promise.resolve();++ expect(testBed.registerOtherFormulaService.calculateStarted$.getValue()).toBe(true);+ expect(testBed.executedCommands.some(({ id }) => id === SetTriggerFormulaCalculationStartMutation.id)).toBe(false);++ testBed.executedDisposable.dispose();+ testBed.testBed.univer.dispose();+ });+it('should merge dirty data from real active-dirty registrations and skip style-triggered range updates', async () => {const testBed = createControllerTestBed();diff --git a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts b/packages/sheets-formula/src/controllers/trigger-calculation.controller.tsindex 71e7ef76a6..2d6f2db964 100644--- a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts+++ b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts@@ -302,8 +302,10 @@ export class TriggerCalculationController extends Disposable {private _initialExecuteFormula() {const calculationMode = this._getCalculationMode();- const params = this._getDirtyDataByCalculationMode(calculationMode);- this._commandService.executeCommand(SetTriggerFormulaCalculationStartMutation.id, params, lo);+ if (calculationMode !== CalculationMode.NO_CALCULATION) {+ const params = this._getDirtyDataByCalculationMode(calculationMode);+ this._commandService.executeCommand(SetTriggerFormulaCalculationStartMutation.id, params, lo);+ }this._registerOtherFormulaService.calculateStarted$.next(true);}diff --git a/packages/sheets-formula/src/facade/__tests__/f-formula.spec.ts b/packages/sheets-formula/src/facade/__tests__/f-formula.spec.tsindex 077b86ad7c..0a026b79e0 100644--- a/packages/sheets-formula/src/facade/__tests__/f-formula.spec.ts+++ b/packages/sheets-formula/src/facade/__tests__/f-formula.spec.ts@@ -368,7 +368,7 @@ describe('sheets-formula facade mixins', () => {await commandService.executeCommand(SetFormulaCalculationStartMutation.id, {}, { onlyLocal: true });await commandService.executeCommand(SetFormulaCalculationResultMutation.id, {unitData: {- unit1: {+ test: {sheet1: {0: {0: { v: 1 },@@ -385,7 +385,7 @@ describe('sheets-formula facade mixins', () => {await commandService.executeCommand(SetRangeValuesMutation.id,{- unitId: 'unit1',+ unitId: 'test',subUnitId: 'sheet1',cellValue: {},},@@ -397,6 +397,26 @@ describe('sheets-formula facade mixins', () => {await expect(waitForResult).resolves.toBeUndefined();});+ it('does not wait for a sheet application when the result targets an unknown unit', async () => {+ await commandService.executeCommand(SetFormulaCalculationStartMutation.id, {}, { onlyLocal: true });+ const waitForResult = univerAPI.getFormula().onCalculationResultApplied();++ await commandService.executeCommand(SetFormulaCalculationResultMutation.id, {+ unitData: {+ 'unknown-unit': {+ sheet1: {+ 0: {+ 0: { v: 1 },+ },+ },+ },+ },+ unitOtherData: {},+ });++ await expect(waitForResult).resolves.toBeUndefined();+ });+it('reads each of ten consecutive sheet results after its own application finishes', async () => {vi.stubGlobal('requestIdleCallback', ((callback: IdleRequestCallback) => {callback({ didTimeout: false, timeRemaining: () => 16 } as IdleDeadline);diff --git a/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.ts b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.tsindex d6931e174b..2cc0d54202 100644--- a/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.ts+++ b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.ts@@ -57,6 +57,7 @@ import {IDefinedNamesService,IFormulaCurrentConfigService,IFormulaDependencyGenerator,+ IFormulaExternalReferenceDataLoader,IFormulaRuntimeService,IFormulaUnitReferenceResolver,IFunctionService,@@ -70,6 +71,7 @@ import {Lexer,LexerNode,LexerTreeBuilder,+ NoopFormulaExternalReferenceDataLoader,OperatorNodeFactory,OtherFormulaManagerService,PrefixNodeFactory,@@ -252,6 +254,7 @@ function createControllerTestBed() {[Lexer],[IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }],[IFormulaUnitReferenceResolver, { useClass: FormulaUnitReferenceResolver }],+ [IFormulaExternalReferenceDataLoader, { useClass: NoopFormulaExternalReferenceDataLoader }],[IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }],[IFormulaRuntimeService, { useClass: FormulaRuntimeService }],[IOtherFormulaManagerService, { useClass: OtherFormulaManagerService }],diff --git a/packages/sheets/src/controllers/__tests__/formula/create-function-test-bed.ts b/packages/sheets/src/controllers/__tests__/formula/create-function-test-bed.tsindex 6689b1ed06..1299123b6d 100644--- a/packages/sheets/src/controllers/__tests__/formula/create-function-test-bed.ts+++ b/packages/sheets/src/controllers/__tests__/formula/create-function-test-bed.ts@@ -56,6 +56,7 @@ import {IFeatureCalculationManagerService,IFormulaCurrentConfigService,IFormulaDependencyGenerator,+ IFormulaExternalReferenceDataLoader,IFormulaRuntimeService,IFormulaUnitReferenceResolver,IFunctionService,@@ -68,6 +69,7 @@ import {LambdaParameterNodeFactory,Lexer,LexerTreeBuilder,+ NoopFormulaExternalReferenceDataLoader,OperatorNodeFactory,OtherFormulaManagerService,PrefixNodeFactory,@@ -199,6 +201,7 @@ export function createFunctionTestBed(workbookData?: IWorkbookData, dependenciesinjector.add([LexerTreeBuilder]);injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);+ injector.add([IFormulaExternalReferenceDataLoader, { useClass: NoopFormulaExternalReferenceDataLoader }]);injector.add([IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }]);injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);injector.add([IFormulaUnitReferenceResolver, { useClass: FormulaUnitReferenceResolver }]);