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: fetchThroughInterceptors support filter function (#4385)
Wenzhao Hue90909302d85
diff --git a/packages/core/src/common/interceptor.ts b/packages/core/src/common/interceptor.tsindex a65d0e5706..1fd3ac9df5 100644--- a/packages/core/src/common/interceptor.ts+++ b/packages/core/src/common/interceptor.ts@@ -14,6 +14,8 @@* limitations under the License.*/+/* eslint-disable ts/no-explicit-any */+import type { Nullable } from '../shared/types';import { remove } from './array';@@ -27,7 +29,9 @@ export enum InterceptorEffectEnum {Style = 1, // 1<< 0Value = 2, // 1<< 1}+export interface IInterceptor<M, C> {+ id?: string;priority?: number;handler: InterceptorHandler<M, C>;}@@ -94,9 +98,21 @@ export class InterceptorManager<P extends Record<string, IInterceptor<any, any>>this._interceptorPoints = interceptorPoints;}- public fetchThroughInterceptors<T, C>(name: IInterceptor<T, C>) {+ /**+ * Get the interceptors.+ * @param name Name of the intercepted point.+ * @param filter A callback function to filter the interceptors.+ * @returns It will return a composed interceptor function. If you will perform the interceptor repeatedly,+ * you should cache the result instead of calling this function multiple times.+ */+ public fetchThroughInterceptors<T, C>(name: IInterceptor<T, C>, filter?: (interceptor: IInterceptor<any, any>) => boolean) {const key = name as unknown as string;- const interceptors = this._interceptorsByName.get(key) as unknown as Array<typeof name>;+ let interceptors = this._interceptorsByName.get(key) as unknown as Array<typeof name>;++ if (filter) {+ interceptors = interceptors.filter(filter);+ }+return composeInterceptors(interceptors || []);}@@ -191,9 +207,21 @@ export class AsyncInterceptorManager<P extends Record<string, IAsyncInterceptor<this._asyncInterceptorPoints = asyncInterceptorPoints;}- public fetchThroughAsyncInterceptors<T, C>(name: IAsyncInterceptor<T, C>) {+ /**+ * Get the interceptors.+ * @param name Name of the intercepted point.+ * @param filter A callback function to filter the interceptors.+ * @returns It will return a composed interceptor function. If you will perform the interceptor repeatedly,+ * you should cache the result instead of calling this function multiple times.+ */+ public fetchThroughAsyncInterceptors<T, C>(name: IAsyncInterceptor<T, C>, filter?: (interceptor: IAsyncInterceptor<any, any>) => boolean) {const key = name as unknown as string;- const interceptors = this._asyncInterceptorsByName.get(key) as unknown as Array<typeof name>;+ let interceptors = this._asyncInterceptorsByName.get(key) as unknown as Array<typeof name>;++ if (filter) {+ interceptors = interceptors.filter(filter);+ }+return composeAsyncInterceptors(interceptors || []);}@@ -202,6 +230,7 @@ export class AsyncInterceptorManager<P extends Record<string, IAsyncInterceptor<if (!this._asyncInterceptorsByName.has(key)) {this._asyncInterceptorsByName.set(key, []);}+const interceptors = this._asyncInterceptorsByName.get(key)!;interceptors.push(interceptor);diff --git a/packages/core/src/sheets/__tests__/worksheet.spec.ts b/packages/core/src/sheets/__tests__/worksheet.spec.tsindex 1a934b8e73..0af8cbedae 100644--- a/packages/core/src/sheets/__tests__/worksheet.spec.ts+++ b/packages/core/src/sheets/__tests__/worksheet.spec.ts@@ -14,15 +14,14 @@* limitations under the License.*/-import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import type { Univer } from '../../univer';-import { LocaleType } from '../../types/enum/locale-type';-import { extractPureTextFromCell, type Worksheet } from '../worksheet';+import type { IRange, IWorkbookData } from '../typedef';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { DisposableCollection } from '../../shared/lifecycle';import { CellValueType } from '../../types/enum';-import type { IRange, IWorkbookData } from '../typedef';+import { LocaleType } from '../../types/enum/locale-type';import { RANGE_TYPE } from '../typedef';+import { extractPureTextFromCell, type Worksheet } from '../worksheet';import { createCoreTestBed } from './create-core-test-bed';describe('test worksheet', () => {diff --git a/packages/core/src/sheets/view-model.ts b/packages/core/src/sheets/view-model.tsindex c3ef2d3bc7..8026d6715f 100644--- a/packages/core/src/sheets/view-model.ts+++ b/packages/core/src/sheets/view-model.ts@@ -14,33 +14,28 @@* limitations under the License.*/-import type { IDisposable } from '../common/di';+/* eslint-disable ts/no-explicit-any */+import type { IDisposable } from '../common/di';+import type { IInterceptor } from '../common/interceptor';import type { Nullable } from '../shared/types';import type { ICellData, ICellDataForSheetInterceptor } from './typedef';import { InterceptorEffectEnum } from '../common/interceptor';import { Disposable, toDisposable } from '../shared/lifecycle';/**+ * A cell content interceptor is used to intercept the cell content. It can change or completely replace the cell content.+ ** @internal*/export interface ICellContentInterceptor {- getCell: (row: number, col: number, effect: InterceptorEffectEnum) => Nullable<ICellDataForSheetInterceptor>;-}--export interface IRowFilteredInterceptor {}--export interface IRowVisibleInterceptor {}--export interface IColVisibleInterceptor {}--export interface ISheetViewModel {- registerCellContentInterceptor: (interceptor: ICellContentInterceptor) => IDisposable;- registerRowFilteredInterceptor: (interceptor: IRowFilteredInterceptor) => IDisposable;- registerRowVisibleInterceptor: (interceptor: IRowVisibleInterceptor) => IDisposable;- registerColVisibleInterceptor: (interceptor: IColVisibleInterceptor) => IDisposable;-- getCell: (row: number, col: number) => Nullable<ICellDataForSheetInterceptor>;+ getCell: (+ row: number,+ col: number,+ effect: InterceptorEffectEnum,+ key?: string,+ filter?: (interceptor: IInterceptor<any, any>) => boolean+ ) => Nullable<ICellDataForSheetInterceptor>;}/**@@ -50,6 +45,12 @@ export interface IRowFilteredInterceptor {getRowFiltered(row: number): boolean;}+export interface IRowFilteredInterceptor {}++export interface IRowVisibleInterceptor {}++export interface IColVisibleInterceptor {}+/*** @internal*/@@ -70,9 +71,11 @@ export class SheetViewModel extends Disposable {this._rowFilteredInterceptor = null;}- getCell(row: number, col: number): Nullable<ICellDataForSheetInterceptor> {+ getCell(row: number, col: number): Nullable<ICellDataForSheetInterceptor>;+ getCell(row: number, col: number, key: string, filter: (interceptor: IInterceptor<any, any>) => boolean): Nullable<ICellDataForSheetInterceptor>;+ getCell(row: number, col: number, key?: string, filter?: (interceptor: IInterceptor<any, any>) => boolean): Nullable<ICellDataForSheetInterceptor> {if (this._cellContentInterceptor) {- return this._cellContentInterceptor.getCell(row, col, InterceptorEffectEnum.Value | InterceptorEffectEnum.Style);+ return this._cellContentInterceptor.getCell(row, col, InterceptorEffectEnum.Value | InterceptorEffectEnum.Style, key, filter);}return this.getRawCell(row, col);diff --git a/packages/core/src/sheets/worksheet.ts b/packages/core/src/sheets/worksheet.tsindex 5252d9979a..e4a1e917ef 100644--- a/packages/core/src/sheets/worksheet.ts+++ b/packages/core/src/sheets/worksheet.ts@@ -14,6 +14,7 @@* limitations under the License.*/+import type { IInterceptor } from '../common/interceptor';import type { IObjectMatrixPrimitiveType, Nullable } from '../shared';import type { IDocumentData, IDocumentRenderConfig, IPaddingData, IStyleData, ITextRotation } from '../types/interfaces';import type { Styles } from './styles';@@ -526,6 +527,11 @@ export class Worksheet {return this.getCellMatrix().getValue(row, col);}+ // eslint-disable-next-line ts/no-explicit-any+ getCellWithFilteredInterceptors(row: number, col: number, key: string, filter: (interceptor: IInterceptor<any, any>) => boolean): Nullable<ICellDataForSheetInterceptor> {+ return this._viewModel.getCell(row, col, key, filter);+ }+getRowFiltered(row: number): boolean {return this._viewModel.getRowFiltered(row);}diff --git a/packages/sheets/src/services/permission/worksheet-permission/worksheet-permission.service.ts b/packages/sheets/src/services/permission/worksheet-permission/worksheet-permission.service.tsindex 43048f6a7c..938f9c5024 100644--- a/packages/sheets/src/services/permission/worksheet-permission/worksheet-permission.service.ts+++ b/packages/sheets/src/services/permission/worksheet-permission/worksheet-permission.service.ts@@ -57,7 +57,7 @@ export class WorksheetPermissionService extends RxDisposable {const instance = new F(unitId, subUnitId);this._permissionService.addPermissionPoint(instance);});- this._logService.log('[WorksheetPermissionService]', 'Initialization completed', unitId, subUnitId);+ this._logService.debug('[WorksheetPermissionService]', 'Initialization completed', unitId, subUnitId);};workbook.getSheets().forEach((worksheet) => {handleWorksheet(worksheet);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 0586954550..3e7cc1eada 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@@ -14,14 +14,13 @@* limitations under the License.*/+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 type { ICellData, Injector, Nullable, Univer, Workbook } from '@univerjs/core';-import { INTERCEPTOR_POINT } from '../interceptor-const';import { SheetInterceptorService } from '../sheet-interceptor.service';import { createSheetTestBed } from './create-core-test-bed';-import type { ISheetLocation } from '../utils/interceptor';describe('Test SheetInterceptorService', () => {let univer: Univer;@@ -37,10 +36,12 @@ describe('Test SheetInterceptorService', () => {afterEach(() => univer.dispose());- function getCell(row: number, col: number): Nullable<ICellData> {+ function getCell(row: number, col: number): Nullable<ICellData>;+ function getCell(row: number, col: number, key: string, filter: (interceptor: IInterceptor<any, any>) => boolean): Nullable<ICellData>;+ function getCell(row: number, col: number, key?: string, filter?: (interceptor: IInterceptor<any, any>) => boolean): Nullable<ICellData> {const cus = get(IUniverInstanceService);const sheet = cus.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()!;- return sheet.getCell(row, col);+ return (key && filter) ? sheet.getCellWithFilteredInterceptors(row, col, key, filter) : sheet.getCell(row, col);}function getRowFiltered(row: number): boolean {@@ -89,6 +90,37 @@ describe('Test SheetInterceptorService', () => {expect(getCell(0, 0)).toEqual({ v: 'intercepted' });expect(getCell(0, 1)).toEqual({ v: 'A2' });});++ it('should skip some interceptors by filtering out the effect', () => {+ const interceptorService = get(SheetInterceptorService);+ interceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {+ id: 'should-skip',+ priority: 100,+ handler(_cell, location: ISheetLocation, next: (v: Nullable<ICellData>) => Nullable<ICellData>) {+ if (location.row === 0 && location.col === 0) {+ return { v: 'intercepted A' };+ }++ return next();+ },+ });++ interceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {+ id: 'should-not-skip',+ priority: 0,+ handler(_cell, location: ISheetLocation, next: (v: Nullable<ICellData>) => Nullable<ICellData>) {+ if (location.row === 0 && location.col === 0) {+ return { v: 'intercepted B' };+ }++ return next();+ },+ });++ expect(getCell(0, 0)).toEqual({ v: 'intercepted A' });+ expect(getCell(0, 1)).toEqual({ v: 'A2' });+ expect(getCell(0, 0, 'cache-filter-key', (interceptor) => interceptor.id !== 'should-skip')).toEqual({ v: 'intercepted B' });+ });});describe('Test intercepting getting row filtered', () => {@@ -199,17 +231,4 @@ describe('Test SheetInterceptorService', () => {expect(result).toBe('zero');});});-- // it('Test SheetInterceptorService', () => {- // it('getLastRowWithContent', () => {- // const univerInstanceService = get(IUniverInstanceService);- // const sheet = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()!;- // expect(sheet.getLastRowWithContent()).toBe(3);- // });- // it('getLastColumnWithContent', () => {- // const univerInstanceService = get(IUniverInstanceService);- // const sheet = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()!;- // expect(sheet.getLastColumnWithContent()).toBe(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 ff68b65f02..0bd4a5ce41 100644--- a/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.ts+++ b/packages/sheets/src/services/sheet-interceptor/sheet-interceptor.service.ts@@ -14,11 +14,14 @@* limitations under the License.*/+/* eslint-disable ts/no-explicit-any */+import type {ICellData,ICellDataForSheetInterceptor,ICellInterceptor,ICommandInfo,+ IComposeInterceptors,IDisposable,IInterceptor,IRange,@@ -87,6 +90,9 @@ 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();+readonly writeCellInterceptor = new InterceptorManager({BEFORE_CELL_EDIT,AFTER_CELL_EDIT,@@ -145,9 +151,11 @@ export class SheetInterceptorService extends Disposable {this._workbookDisposables.forEach((disposable) => disposable.dispose());this._workbookDisposables.clear();this._worksheetDisposables.clear();++ this._interceptorsByName.clear();}- // #region Intercept command execution+ // #region intercept command execution/*** Add a listener function to a specific command to add affiliated mutations. It should be called in controllers.@@ -205,7 +213,7 @@ export class SheetInterceptorService extends Disposable {}/**- * Add a listener function to a specific command to deteminte if the command can execute mutations. It should be+ * Add a listener function to a specific command to determine if the command can execute mutations. It should be* called in controllers.** Pairs with {@link beforeCommandExecute}.@@ -236,7 +244,7 @@ export class SheetInterceptorService extends Disposable {// #endregion- // #region intercept ranges - mainly for pivot table currrently (2024/10/28).+ // #region intercept ranges - mainly for pivot table currently (2024/10/28)./*** By adding callbacks to some Ranges can get some additional mutations, such as clearing all plugin data in a certain area.@@ -265,7 +273,9 @@ export class SheetInterceptorService extends Disposable {};}- // #region write cell+ // #endregion++ // #region intercept on writing cellasync onWriteCell(workbook: Workbook, worksheet: Worksheet, row: number, col: number, cellData: ICellData) {const context = {@@ -285,13 +295,12 @@ export class SheetInterceptorService extends Disposable {// #endregion- // #endregion-intercept<T extends IInterceptor<any, any>>(name: T, interceptor: T): IDisposable {const key = name as unknown as string;if (!this._interceptorsByName.has(key)) {this._interceptorsByName.set(key, []);}+const interceptors = this._interceptorsByName.get(key)!;interceptors.push(interceptor);const sortedInterceptors = interceptors.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));@@ -301,6 +310,7 @@ export class SheetInterceptorService extends Disposable {`${key}-${(InterceptorEffectEnum.Style | InterceptorEffectEnum.Value)}`,sortedInterceptors);+const BOTH_EFFECT = InterceptorEffectEnum.Style | InterceptorEffectEnum.Value;this._interceptorsByName.set(`${key}-${(InterceptorEffectEnum.Style)}`,@@ -317,19 +327,36 @@ export class SheetInterceptorService extends Disposable {);}+ this._interceptorsDirty = true;return this.disposeWithMe(toDisposable(() => remove(this._interceptorsByName.get(key)!, interceptor)));}- fetchThroughInterceptors<T, C>(name: IInterceptor<T, C>, effect?: InterceptorEffectEnum) {- const key = effect === undefined ? name as unknown as string : `${name as unknown as string}-${effect}`;- const interceptors = this._interceptorsByName.get(key) as unknown as Array<typeof name>;- return composeInterceptors<T, C>(interceptors || []);+ fetchThroughInterceptors<T, C>(+ name: IInterceptor<T, C>,+ effect?: InterceptorEffectEnum,+ _key?: string,+ filter?: (interceptor: IInterceptor<any, any>) => boolean+ ): ReturnType<IComposeInterceptors<T, C>> {+ 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);++ if (!composed || this._interceptorsDirty) {+ let interceptors = this._interceptorsByName.get(byNamesKey) as unknown as Array<IInterceptor<any, any>> | undefined;+ if (interceptors && filter) {+ interceptors = interceptors.filter(filter);+ }++ composed = composeInterceptors<T, C>(interceptors || []);+ this._composedInterceptorByKey.set(key, composed);+ }++ return composed;}private _interceptWorkbook(workbook: Workbook): void {const disposables = new DisposableCollection();const unitId = workbook.getUnitId();- // const isRowStylePrecedeColumnStyle = this._isRowStylePrecedeColumnStyle;// eslint-disable-next-line ts/no-this-aliasconst sheetInterceptorService = this;@@ -340,9 +367,15 @@ export class SheetInterceptorService extends Disposable {sheetInterceptorService._worksheetDisposables.set(getWorksheetDisposableID(unitId, worksheet), sheetDisposables);sheetDisposables.add(viewModel.registerCellContentInterceptor({- getCell(row: number, col: number, effect: InterceptorEffectEnum): Nullable<ICellData> {+ getCell(+ row: number,+ col: number,+ effect: InterceptorEffectEnum,+ key?: string,+ filter?: (interceptor: IInterceptor<any, any>) => boolean+ ): Nullable<ICellData> {const rawData = worksheet.getCellRaw(row, col);- return sheetInterceptorService.fetchThroughInterceptors(INTERCEPTOR_POINT.CELL_CONTENT, effect)(+ return sheetInterceptorService.fetchThroughInterceptors(INTERCEPTOR_POINT.CELL_CONTENT, effect, key, filter)(rawData,{unitId,@@ -352,8 +385,7 @@ export class SheetInterceptorService extends Disposable {worksheet,workbook,rawData,- }- );+ });},}));