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
fix(formula): collect changeset dirty ranges before render (#7272)
Univer875eda7eb33e
diff --git a/packages/engine-formula/src/controllers/__tests__/formula-calculation-trigger.controller.spec.ts b/packages/engine-formula/src/controllers/__tests__/formula-calculation-trigger.controller.spec.tsnew file mode 100644index 0000000000..ebe62a9361--- /dev/null+++ b/packages/engine-formula/src/controllers/__tests__/formula-calculation-trigger.controller.spec.ts@@ -0,0 +1,58 @@+/**+ * 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 * as core from '@univerjs/core';+import { LifecycleStages } from '@univerjs/core';+import { BehaviorSubject } from 'rxjs';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { FormulaCalculationTriggerController } from '../formula-calculation-trigger.controller';++describe('FormulaCalculationTriggerController', () => {+ afterEach(() => vi.restoreAllMocks());++ it('starts immediately in Node.js', () => {+ vi.spyOn(core, 'isNodeEnv').mockReturnValue(true);+ const start = vi.fn();+ const lifecycle$ = new BehaviorSubject(LifecycleStages.Ready);++ const controller = new FormulaCalculationTriggerController(+ { start } as never,+ { lifecycle$ } as never+ );++ expect(start).toHaveBeenCalledOnce();+ controller.dispose();+ });++ it('starts after rendering in the browser', () => {+ vi.spyOn(core, 'isNodeEnv').mockReturnValue(false);+ const start = vi.fn();+ const lifecycle$ = new BehaviorSubject(LifecycleStages.Ready);++ const controller = new FormulaCalculationTriggerController(+ { start } as never,+ { lifecycle$ } as never+ );++ expect(start).not.toHaveBeenCalled();+ lifecycle$.next(LifecycleStages.Rendered);+ expect(start).toHaveBeenCalledOnce();++ lifecycle$.next(LifecycleStages.Steady);+ expect(start).toHaveBeenCalledOnce();+ controller.dispose();+ });+});diff --git a/packages/engine-formula/src/controllers/formula-calculation-trigger.controller.ts b/packages/engine-formula/src/controllers/formula-calculation-trigger.controller.tsnew file mode 100644index 0000000000..0a86cb3d62--- /dev/null+++ b/packages/engine-formula/src/controllers/formula-calculation-trigger.controller.ts@@ -0,0 +1,38 @@+/**+ * 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 { Disposable, Inject, isNodeEnv, LifecycleService, LifecycleStages } from '@univerjs/core';+import { filter, take } from 'rxjs';+import { FormulaCalculationTriggerService } from '../services/formula-calculation-trigger.service';++export class FormulaCalculationTriggerController extends Disposable {+ constructor(+ @Inject(FormulaCalculationTriggerService) formulaCalculationTriggerService: FormulaCalculationTriggerService,+ @Inject(LifecycleService) lifecycleService: LifecycleService+ ) {+ super();++ if (isNodeEnv()) {+ formulaCalculationTriggerService.start();+ return;+ }++ this.disposeWithMe(lifecycleService.lifecycle$.pipe(+ filter((stage) => stage >= LifecycleStages.Rendered),+ take(1)+ ).subscribe(() => formulaCalculationTriggerService.start()));+ }+}diff --git a/packages/engine-formula/src/plugin.ts b/packages/engine-formula/src/plugin.tsindex f8af4b137d..23973536c6 100644--- a/packages/engine-formula/src/plugin.ts+++ b/packages/engine-formula/src/plugin.ts@@ -21,6 +21,7 @@ import pkg from '../package.json';import { defaultPluginConfig, ENGINE_FORMULA_PLUGIN_CONFIG_KEY } from './config/config';import { CalculateController } from './controllers/calculate.controller';import { ComputingStatusReporterController } from './controllers/computing-status.controller';+import { FormulaCalculationTriggerController } from './controllers/formula-calculation-trigger.controller';import { FormulaController } from './controllers/formula.controller';import { SetDependencyController } from './controllers/set-dependency.controller';import { SetFeatureCalculationController } from './controllers/set-feature-calculation.controller';@@ -94,6 +95,7 @@ export class UniverFormulaEnginePlugin extends Plugin {override onReady(): void {touchDependencies(this._injector, [[FormulaController],+ [FormulaCalculationTriggerController],[SuperTableActiveDirtyController],// [SetSuperTableController],]);@@ -135,6 +137,7 @@ export class UniverFormulaEnginePlugin extends Plugin {[FormulaDataModel],//Controllers[FormulaController],+ [FormulaCalculationTriggerController],[SuperTableActiveDirtyController],// [SetSuperTableController],[ComputingStatusReporterController],diff --git a/packages/engine-formula/src/services/__tests__/formula-calculation-trigger.service.spec.ts b/packages/engine-formula/src/services/__tests__/formula-calculation-trigger.service.spec.tsindex 087ebb7bcb..8fe8a1c9c3 100644--- a/packages/engine-formula/src/services/__tests__/formula-calculation-trigger.service.spec.ts+++ b/packages/engine-formula/src/services/__tests__/formula-calculation-trigger.service.spec.ts@@ -25,7 +25,7 @@ import {import { FormulaCalculationTriggerService } from '../formula-calculation-trigger.service';import { FormulaExecutedStateType } from '../runtime.service';-function createTestBed() {+function createTestBed(start = true) {let listener: ((command: ICommandInfo, options?: IExecutionOptions) => void) | undefined;const executed: Array<{ id: string; params: unknown; options: unknown }> = [];const conversions = new Map<string, { commandId: string; shouldTrigger?: () => boolean; getDirtyData: (command: ICommandInfo) => object }>();@@ -44,6 +44,9 @@ function createTestBed() {get: (id: string) => conversions.get(id),};const service = new FormulaCalculationTriggerService(commandService, activeDirtyManagerService as never);+ if (start) {+ service.start();+ }return {service,@@ -60,6 +63,38 @@ describe('FormulaCalculationTriggerService', () => {vi.restoreAllMocks();});+ it('collects changeset dirty data before start and merges it with the initial trigger', async () => {+ const testBed = createTestBed(false);+ testBed.conversions.set('sheet-dirty', {+ commandId: 'sheet-dirty',+ getDirtyData: () => ({+ dirtyRanges: [{ unitId: 'sheet-unit', sheetId: 'sheet-1', range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 } }],+ }),+ });+ testBed.conversions.set(SetTriggerFormulaCalculationStartMutation.id, {+ commandId: SetTriggerFormulaCalculationStartMutation.id,+ getDirtyData: () => ({ forceCalculation: true }),+ });++ testBed.emit({ id: 'sheet-dirty' } as ICommandInfo, { fromChangeset: true });+ await vi.advanceTimersByTimeAsync(100);+ expect(testBed.executed).toEqual([]);++ testBed.service.start();+ testBed.emit({ id: SetTriggerFormulaCalculationStartMutation.id } as ICommandInfo);+ await vi.advanceTimersByTimeAsync(100);++ expect(testBed.executed).toHaveLength(1);+ expect(testBed.executed[0]).toMatchObject({+ id: SetFormulaCalculationStartMutation.id,+ params: {+ forceCalculation: true,+ dirtyRanges: [{ unitId: 'sheet-unit', sheetId: 'sheet-1' }],+ },+ });+ testBed.service.dispose();+ });+it('merges dirty data from different unit types into one calculation', async () => {const testBed = createTestBed();testBed.conversions.set('sheet-dirty', {diff --git a/packages/engine-formula/src/services/formula-calculation-trigger.service.ts b/packages/engine-formula/src/services/formula-calculation-trigger.service.tsindex 744588d6da..11be6d633f 100644--- a/packages/engine-formula/src/services/formula-calculation-trigger.service.ts+++ b/packages/engine-formula/src/services/formula-calculation-trigger.service.ts@@ -42,6 +42,7 @@ export class FormulaCalculationTriggerService extends Disposable {private _waitingCommandQueue: ICommandInfo[] = [];private _executingDirtyData = createEmptyDirtyData();private _timer: ReturnType<typeof setTimeout> | undefined;+ private _started = false;private _executionInProgress = false;private _restartCalculation = false;@@ -53,6 +54,15 @@ export class FormulaCalculationTriggerService extends Disposable {this._initialize();}+ start(): void {+ if (this._started) {+ return;+ }++ this._started = true;+ this._scheduleFlush();+ }+override dispose(): void {clearTimeout(this._timer);this._waitingCommandQueue = [];@@ -81,11 +91,19 @@ export class FormulaCalculationTriggerService extends Disposable {}this._waitingCommandQueue.push(command);- clearTimeout(this._timer);- this._timer = setTimeout(() => this._flush(), CALCULATION_DEBOUNCE_TIME);+ this._scheduleFlush();}));}+ private _scheduleFlush(): void {+ if (!this._started || this._waitingCommandQueue.length === 0) {+ return;+ }++ clearTimeout(this._timer);+ this._timer = setTimeout(() => this._flush(), CALCULATION_DEBOUNCE_TIME);+ }+private _flush(): void {const commands = this._waitingCommandQueue;const dirtyData = this._generateDirty(commands);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 9c3c65bfcc..d82c11f1c5 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@@ -124,6 +124,7 @@ function createControllerTestBed() {});});+ injector.get(FormulaCalculationTriggerService).start();injector.get(FormulaCalculationSessionController);const controller = injector.get(TriggerCalculationController);