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
perf(render): optimize sheet interceptor hot paths (#6906)
Univere3719cb0be25
diff --git a/packages/core/src/common/interceptor.ts b/packages/core/src/common/interceptor.tsindex c8516f1721..b7117acf26 100644--- a/packages/core/src/common/interceptor.ts+++ b/packages/core/src/common/interceptor.ts@@ -62,25 +62,24 @@ export const composeInterceptors = <T, C>(interceptors: Array<IInterceptor<T, C>function (initialValue: Nullable<T>, context: C) {let index = -1;let value: Nullable<T> = initialValue;+ let nextCalled = false;- for (let i = 0; i <= interceptors.length; i++) {+ const next = (nextValue: Nullable<T>) => {+ nextCalled = true;+ return nextValue;+ };++ for (let i = 0; i < interceptors.length; i++) {if (i <= index) {throw new Error('[SheetInterceptorService]: next() called multiple times!');}index = i;- if (i === interceptors.length) {- return value;- }-const interceptor = interceptors[i];- let nextCalled = false;+ nextCalled = false;- value = interceptor.handler!(value, context, (nextValue) => {- nextCalled = true;- return nextValue;- });+ value = interceptor.handler!(value, context, next);if (!nextCalled) {break;diff --git a/packages/sheets/src/services/sheet-interceptor/__tests__/sheet-interceptor.service.spec.ts b/packages/sheets/src/services/sheet-interceptor/__tests__/sheet-interceptor.service.spec.tsindex 553f5b9157..f153c77824 100644--- a/packages/sheets/src/services/sheet-interceptor/__tests__/sheet-interceptor.service.spec.ts+++ b/packages/sheets/src/services/sheet-interceptor/__tests__/sheet-interceptor.service.spec.ts@@ -17,7 +17,7 @@import type { ICellData, IInterceptor, Injector, Nullable, Univer, Workbook } from '@univerjs/core';import type { ISheetLocation } from '../utils/interceptor';import { createInterceptorKey, InterceptorEffectEnum, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { INTERCEPTOR_POINT } from '../interceptor-const';import { SheetInterceptorService } from '../sheet-interceptor.service';import { createSheetTestBed } from './create-core-test-bed';@@ -27,6 +27,7 @@ describe('Test SheetInterceptorService', () => {let get: Injector['get'];const stringIntercept = createInterceptorKey<string, null>('stringIntercept');const numberIntercept = createInterceptorKey<number, { step: number }>('numberIntercept');+ type ICellContentTestLocation = ISheetLocation & { rawData: Nullable<ICellData> };beforeEach(() => {const testBed = createSheetTestBed(undefined, [[SheetInterceptorService]]);@@ -154,6 +155,35 @@ describe('Test SheetInterceptorService', () => {expect(getRowFiltered(2)).toBeFalsy();expect(getRowVisible(2)).toBeTruthy();});++ it('should reuse row filtered composed interceptors while registrations are stable', () => {+ const interceptorService = get(SheetInterceptorService);+ const fetchThroughInterceptorsSpy = vi.spyOn(interceptorService, 'fetchThroughInterceptors');++ getRowFiltered(1);+ getRowFiltered(2);+ getRowFiltered(3);++ expect(fetchThroughInterceptorsSpy).toHaveBeenCalledTimes(1);++ const disposable = interceptorService.intercept(INTERCEPTOR_POINT.ROW_FILTERED, {+ handler(filtered, _, next) {+ return next(filtered);+ },+ });++ getRowFiltered(4);+ getRowFiltered(5);++ expect(fetchThroughInterceptorsSpy).toHaveBeenCalledTimes(2);++ disposable.dispose();++ getRowFiltered(6);+ getRowFiltered(7);++ expect(fetchThroughInterceptorsSpy).toHaveBeenCalledTimes(3);+ });});describe('Test intercept in general case', () => {@@ -230,5 +260,86 @@ describe('Test SheetInterceptorService', () => {expect(result).toBe('zero');});++ it('should rebuild cached cell content effect interceptors after dispose and same-length replacement', () => {+ const interceptorService = get(SheetInterceptorService);+ const calls: string[] = [];++ interceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {+ effect: InterceptorEffectEnum.Style,+ priority: 100,+ handler(value, _, next) {+ calls.push('first');+ return next({ ...value, v: `${value?.v} first` });+ },+ });++ const staleDisposable = interceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {+ effect: InterceptorEffectEnum.Style,+ priority: 0,+ handler(value, _, next) {+ calls.push('stale');+ return next({ ...value, v: `${value?.v} stale` });+ },+ });++ expect(+ interceptorService.fetchThroughInterceptors<ICellData, ICellContentTestLocation>(+ INTERCEPTOR_POINT.CELL_CONTENT,+ InterceptorEffectEnum.Style+ )({ v: 'zero' }, null as unknown as ICellContentTestLocation)+ ).toEqual({ v: 'zero first stale' });++ staleDisposable.dispose();++ interceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {+ effect: InterceptorEffectEnum.Style,+ priority: 0,+ handler(value, _, next) {+ calls.push('fresh');+ return next({ ...value, v: `${value?.v} fresh` });+ },+ });++ calls.length = 0;++ expect(+ interceptorService.fetchThroughInterceptors<ICellData, ICellContentTestLocation>(+ INTERCEPTOR_POINT.CELL_CONTENT,+ InterceptorEffectEnum.Style+ )({ v: 'zero' }, null as unknown as ICellContentTestLocation)+ ).toEqual({ v: 'zero first fresh' });+ expect(calls).toEqual(['first', 'fresh']);+ });++ it('should reuse common cell content composed interceptors while registrations are stable', () => {+ const interceptorService = get(SheetInterceptorService);+ const fetchThroughInterceptorsSpy = vi.spyOn(interceptorService, 'fetchThroughInterceptors');++ getCell(0, 0);+ getCell(0, 1);+ getCell(1, 0);++ expect(fetchThroughInterceptorsSpy).toHaveBeenCalledTimes(1);++ const disposable = interceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {+ effect: InterceptorEffectEnum.Style | InterceptorEffectEnum.Value,+ handler(value, _, next) {+ return next(value);+ },+ });++ getCell(1, 1);+ getCell(2, 0);++ expect(fetchThroughInterceptorsSpy).toHaveBeenCalledTimes(2);++ disposable.dispose();++ getCell(2, 1);+ getCell(3, 0);++ expect(fetchThroughInterceptorsSpy).toHaveBeenCalledTimes(3);+ });});});diff --git a/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.ts b/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.tsindex aa99403ebf..ea758908da 100644--- a/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.ts+++ b/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.ts@@ -31,7 +31,7 @@ import type {Workbook,Worksheet,} from '@univerjs/core';-import type { ISheetLocation } from './utils/interceptor';+import type { ISheetLocation, ISheetRowLocation } from './utils/interceptor';import {composeInterceptors,@@ -87,6 +87,9 @@ interface ISheetLocationForEditor extends ISheetLocation {origin: Nullable<ICellData>;}+type ICellContentComposedInterceptor = ReturnType<IComposeInterceptors<ICellDataForSheetInterceptor, ISheetLocation & { rawData: Nullable<ICellData> }>>;+type IRowFilteredComposedInterceptor = ReturnType<IComposeInterceptors<boolean, ISheetRowLocation>>;+export const BEFORE_CELL_EDIT = createInterceptorKey<ICellDataForSheetInterceptor, ISheetLocationForEditor>('BEFORE_CELL_EDIT');export const AFTER_CELL_EDIT = createInterceptorKey<ICellDataForSheetInterceptor, ISheetLocationForEditor>('AFTER_CELL_EDIT');export const VALIDATE_CELL = createInterceptorKey<Promise<boolean>, ISheetLocation>('VALIDATE_CELL');@@ -106,9 +109,8 @@ export class SheetInterceptorService extends Disposable {private readonly _workbookDisposables = new Map<string, IDisposable>();private readonly _worksheetDisposables = new Map<string, IDisposable>();- private _interceptorsDirty = false;private _composedInterceptorByKey: Map<string, ReturnType<IComposeInterceptors<any, any>>> = new Map();- private _composedInterceptorsLengthByKey: Map<string, number> = new Map();+ private _composedInterceptorVersion = 0;readonly writeCellInterceptor = new InterceptorManager({BEFORE_CELL_EDIT,@@ -164,6 +166,7 @@ export class SheetInterceptorService extends Disposable {this._worksheetDisposables.clear();this._interceptorsByName.clear();+ this._composedInterceptorByKey.clear();}// #region intercept command execution@@ -349,7 +352,7 @@ export class SheetInterceptorService extends Disposable {interceptors.push(interceptor);const sortedInterceptors = interceptors.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));- this._interceptorsDirty = true;+ this._invalidateComposedInterceptors();if (key === INTERCEPTOR_POINT.CELL_CONTENT as unknown as string) {const JOINED_EFFECT = InterceptorEffectEnum.Style | InterceptorEffectEnum.Value;@@ -370,10 +373,14 @@ export class SheetInterceptorService extends Disposable {remove(this._interceptorsByName.get(`${key}-${JOINED_EFFECT}`)!, interceptor);remove(this._interceptorsByName.get(`${key}-${(InterceptorEffectEnum.Style)}`)!, interceptor);remove(this._interceptorsByName.get(`${key}-${(InterceptorEffectEnum.Value)}`)!, interceptor);+ this._invalidateComposedInterceptors();}));} else {this._interceptorsByName.set(key, sortedInterceptors);- return this.disposeWithMe(toDisposable(() => remove(this._interceptorsByName.get(key)!, interceptor)));+ return this.disposeWithMe(toDisposable(() => {+ remove(this._interceptorsByName.get(key)!, interceptor);+ this._invalidateComposedInterceptors();+ }));}}@@ -386,9 +393,8 @@ export class SheetInterceptorService extends Disposable {const byNamesKey = effect === undefined ? name as unknown as string : `${name as unknown as string}-${effect}`;const key = _key ?? byNamesKey;let composed = this._composedInterceptorByKey.get(key);- const composedInterceptorsLength = this._composedInterceptorsLengthByKey.get(key) || 0;- if (!composed || !this._interceptorsDirty || composedInterceptorsLength !== (this._interceptorsByName.get(byNamesKey)?.length || 0)) {+ if (!composed) {let interceptors = this._interceptorsByName.get(byNamesKey) as unknown as Array<IInterceptor<any, any>> | undefined;if (interceptors && filter) {interceptors = interceptors.filter(filter);@@ -396,12 +402,37 @@ export class SheetInterceptorService extends Disposable {composed = composeInterceptors<T, C>(interceptors || []);this._composedInterceptorByKey.set(key, composed);- this._composedInterceptorsLengthByKey.set(key, interceptors?.length || 0);}return composed;}+ private _invalidateComposedInterceptors(): void {+ this._composedInterceptorVersion += 1;+ this._composedInterceptorByKey.clear();+ }++ private _getCommonCellContentInterceptor(+ effect: InterceptorEffectEnum,+ cache: Map<InterceptorEffectEnum, ICellContentComposedInterceptor>+ ): ICellContentComposedInterceptor {+ let composed = cache.get(effect);+ if (!composed) {+ composed = this.fetchThroughInterceptors(INTERCEPTOR_POINT.CELL_CONTENT, effect);+ cache.set(effect, composed);+ }++ return composed;+ }++ private _getCommonRowFilteredInterceptor(cache: { interceptor: Nullable<IRowFilteredComposedInterceptor> }): IRowFilteredComposedInterceptor {+ if (!cache.interceptor) {+ cache.interceptor = this.fetchThroughInterceptors(INTERCEPTOR_POINT.ROW_FILTERED);+ }++ return cache.interceptor;+ }+private _interceptWorkbook(workbook: Workbook): void {const disposables = new DisposableCollection();const unitId = workbook.getUnitId();@@ -412,6 +443,11 @@ export class SheetInterceptorService extends Disposable {const subUnitId = worksheet.getSheetId();worksheet.__interceptViewModel((viewModel) => {const sheetDisposables = new DisposableCollection();+ const commonCellContentInterceptors = new Map<InterceptorEffectEnum, ICellContentComposedInterceptor>();+ const commonRowFilteredInterceptor: { interceptor: Nullable<IRowFilteredComposedInterceptor> } = { interceptor: null };+ let commonCellContentInterceptorsVersion = -1;+ let commonRowFilteredInterceptorVersion = -1;+sheetInterceptorService._worksheetDisposables.set(getWorksheetDisposableID(unitId, worksheet), sheetDisposables);sheetDisposables.add(viewModel.registerCellContentInterceptor({@@ -423,32 +459,39 @@ export class SheetInterceptorService extends Disposable {filter?: (interceptor: IInterceptor<any, any>) => boolean): Nullable<ICellData> {const rawData = worksheet.getCellRaw(row, col);- return sheetInterceptorService.fetchThroughInterceptors(INTERCEPTOR_POINT.CELL_CONTENT, effect, key, filter)(+ const context = {+ unitId,+ subUnitId,+ row,+ col,+ worksheet,+ workbook,rawData,- {- unitId,- subUnitId,- row,- col,- worksheet,- workbook,- rawData,+ };++ if (key === undefined && filter === undefined) {+ if (commonCellContentInterceptorsVersion !== sheetInterceptorService._composedInterceptorVersion) {+ commonCellContentInterceptors.clear();+ commonCellContentInterceptorsVersion = sheetInterceptorService._composedInterceptorVersion;}- );++ return sheetInterceptorService._getCommonCellContentInterceptor(effect, commonCellContentInterceptors)(rawData, context);+ }++ return sheetInterceptorService.fetchThroughInterceptors(INTERCEPTOR_POINT.CELL_CONTENT, effect, key, filter)(rawData, context);},}));sheetDisposables.add(viewModel.registerRowFilteredInterceptor({getRowFiltered(row: number): boolean {- return !!sheetInterceptorService.fetchThroughInterceptors(INTERCEPTOR_POINT.ROW_FILTERED)(+ if (commonRowFilteredInterceptorVersion !== sheetInterceptorService._composedInterceptorVersion) {+ commonRowFilteredInterceptor.interceptor = null;+ commonRowFilteredInterceptorVersion = sheetInterceptorService._composedInterceptorVersion;+ }++ return !!sheetInterceptorService._getCommonRowFilteredInterceptor(commonRowFilteredInterceptor)(false,- {- unitId,- subUnitId,- row,- workbook,- worksheet,- }+ { unitId, subUnitId, row, workbook, worksheet });},}));