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(sheet): add intercept type (#437)
Gpound.liu97590760789b
diff --git a/packages/base-sheets/src/commands/commands/set-range-values.command.ts b/packages/base-sheets/src/commands/commands/set-range-values.command.tsindex 95a2cfdb13..27df12570e 100644--- a/packages/base-sheets/src/commands/commands/set-range-values.command.ts+++ b/packages/base-sheets/src/commands/commands/set-range-values.command.ts@@ -3,6 +3,7 @@ import {ICellData,ICommand,ICommandService,+ INTERCEPTOR_POINT,IRange,isICellData,IUndoRedoService,@@ -93,7 +94,7 @@ export const SetRangeValuesCommand: ICommand = {);if (- !sheetInterceptorService.onCommandPermissionCheck({+ !sheetInterceptorService.fetchThroughInterceptors(INTERCEPTOR_POINT.PERMISSION)(null, {id: SetRangeValuesCommand.id,params: setRangeValuesMutationParams,})diff --git a/packages/base-sheets/src/services/__tests__/sheet-permission.spec.ts b/packages/base-sheets/src/services/__tests__/sheet-permission.spec.tsindex b84754f738..9fede84151 100644--- a/packages/base-sheets/src/services/__tests__/sheet-permission.spec.ts+++ b/packages/base-sheets/src/services/__tests__/sheet-permission.spec.ts@@ -2,8 +2,10 @@ import { ICommandService, IUniverInstanceService, Univer, UniverPermissionServicimport { Injector } from '@wendellhu/redi';import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import { SetRangeValuesCommand } from '../../commands/commands/set-range-values.command';+import { ISetRangeValuesCommandParams, SetRangeValuesCommand } from '../../commands/commands/set-range-values.command';+import { SetRangeValuesMutation } from '../../commands/mutations/set-range-values.mutation';import { SheetEditablePermission, SheetPermissionService } from '../permission';+import { SelectionManagerService } from '../selection-manager.service';import { createTestBase, TEST_WORKBOOK_DATA_DEMO } from './util';describe('test sheet permission service', () => {@@ -11,11 +13,12 @@ describe('test sheet permission service', () => {let commandService: ICommandService;let get: Injector['get'];beforeEach(() => {- const testBed = createTestBase(TEST_WORKBOOK_DATA_DEMO, [[SheetPermissionService]]);+ const testBed = createTestBase(TEST_WORKBOOK_DATA_DEMO, [[SheetPermissionService], [SelectionManagerService]]);get = testBed.get;univer = testBed.univer;commandService = testBed.get(ICommandService);commandService.registerCommand(SetRangeValuesCommand);+ commandService.registerCommand(SetRangeValuesMutation);});afterEach(() => {univer.dispose();@@ -61,4 +64,21 @@ describe('test sheet permission service', () => {expect(univerPermissionService.getEditable()).toBe(true);expect(sheetPermissionService.getSheetEditable(workbook.getUnitId(), sheet.getSheetId())).toBe(true);});++ it('test setRangeValue commands', async () => {+ const univerPermissionService = get(UniverPermissionService);+ const commandService = get(ICommandService);+ univerPermissionService.setEditable(false);+ const result = await commandService.executeCommand(SetRangeValuesCommand.id, {+ range: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0 },+ value: { v: 3 },+ } as ISetRangeValuesCommandParams);+ expect(result).toBe(false);+ univerPermissionService.setEditable(true);+ const result2 = await commandService.executeCommand(SetRangeValuesCommand.id, {+ range: { startRow: 0, startColumn: 0, endColumn: 0, endRow: 0 },+ value: { v: 3 },+ } as ISetRangeValuesCommandParams);+ expect(result2).toBe(true);+ });});diff --git a/packages/base-sheets/src/services/permission/sheet-permission.service.ts b/packages/base-sheets/src/services/permission/sheet-permission.service.tsindex b0f3e1035b..8e7f76f4c8 100644--- a/packages/base-sheets/src/services/permission/sheet-permission.service.ts+++ b/packages/base-sheets/src/services/permission/sheet-permission.service.ts@@ -1,6 +1,7 @@import {Disposable,getTypeFromPermissionItemList,+ INTERCEPTOR_POINT,IPermissionService,IUniverInstanceService,LifecycleStages,@@ -58,8 +59,9 @@ export class SheetPermissionService extends Disposable {private _interceptCommandPermission() {this.disposeWithMe(- this._sheetInterceptorService.interceptCommandPermission({- checkPermission: (commandInfo) => {+ this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.PERMISSION, {+ priority: 99,+ handler: (_value, commandInfo, next) => {const workbook = this._univerInstanceService.getCurrentUniverSheetInstance();const sheet = workbook?.getActiveSheet();const workbookId = workbook?.getUnitId();@@ -72,7 +74,7 @@ export class SheetPermissionService extends Disposable {return this.getSheetEditable(workbookId, sheetId);}}- return true;+ return next();},}));diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex fa77c8a6a6..dbe6eb58fb 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -35,11 +35,9 @@ export {UniverEditablePermissionPoint,UniverPermissionService,} from './services/permission';-export {- type IInterceptor,- type ISheetLocation,- SheetInterceptorService,-} from './services/sheet-interceptor/sheet-interceptor.service';+export { INTERCEPTOR_POINT } from './services/sheet-interceptor/interceptor-const';+export { SheetInterceptorService } from './services/sheet-interceptor/sheet-interceptor.service';+export type { IInterceptor, ISheetLocation } from './services/sheet-interceptor/utils/interceptor';export { type IStyleSheet, ThemeService } from './services/theme/theme.service';export {type IUndoRedoCommandInfos,diff --git a/packages/core/src/services/sheet-interceptor/__tests__/sheet-interceptor.service.spec.ts b/packages/core/src/services/sheet-interceptor/__tests__/sheet-interceptor.service.spec.tsindex 0a4589350f..82a07a7244 100644--- a/packages/core/src/services/sheet-interceptor/__tests__/sheet-interceptor.service.spec.ts+++ b/packages/core/src/services/sheet-interceptor/__tests__/sheet-interceptor.service.spec.ts@@ -6,12 +6,16 @@ import { Univer } from '../../../basics/univer';import { Nullable } from '../../../common/type-utils';import { ICellData } from '../../../types/interfaces/i-cell-data';import { IUniverInstanceService } from '../../instance/instance.service';-import { INTERCEPTOR_NAMES, ISheetLocation, SheetInterceptorService } from '../sheet-interceptor.service';+import { INTERCEPTOR_POINT } from '../interceptor-const';+import { SheetInterceptorService } from '../sheet-interceptor.service';+import { createInterceptorKey, ISheetLocation } from '../utils/interceptor';import { createCoreTestBed } from './create-core-test-bed';describe('Test SheetInterceptorService', () => {let univer: Univer;let get: Injector['get'];+ const stringIntercept = createInterceptorKey<string, null>('stringIntercept');+ const numberIntercept = createInterceptorKey<number, { step: number }>('numberIntercept');beforeEach(() => {const testBed = createCoreTestBed();@@ -29,7 +33,7 @@ describe('Test SheetInterceptorService', () => {describe('Test intercept getting cell content', () => {it('should intercept cells and merge result if next is called', () => {- get(SheetInterceptorService).intercept(INTERCEPTOR_NAMES.CELL_CONTENT, {+ get(SheetInterceptorService).intercept(INTERCEPTOR_POINT.CELL_CONTENT, {priority: 100,handler(_cell, location: ISheetLocation, next: (v: Nullable<ICellData>) => Nullable<ICellData>) {if (location.row === 0 && location.col === 0) {@@ -45,7 +49,7 @@ describe('Test SheetInterceptorService', () => {});it('interceptors should directly return result if next is not called', () => {- get(SheetInterceptorService).intercept(INTERCEPTOR_NAMES.CELL_CONTENT, {+ get(SheetInterceptorService).intercept(INTERCEPTOR_POINT.CELL_CONTENT, {priority: 100,handler(_cell, location: ISheetLocation, next: (v: Nullable<ICellData>) => Nullable<ICellData>) {if (location.row === 0 && location.col === 0) {@@ -63,89 +67,76 @@ describe('Test SheetInterceptorService', () => {describe('Test intercept in general case', () => {it('should intercept BEFORE_CELL_EDIT and sum the values', () => {- get(SheetInterceptorService).intercept(INTERCEPTOR_NAMES.BEFORE_CELL_EDIT, {+ get(SheetInterceptorService).intercept(numberIntercept, {priority: 0,- handler(value: number, context: { step: number }, next) {+ handler(value, context, next) {if (context.step) {- return next(value + context.step);+ return next((value || 0) + context.step);}return next(value);},});- get(SheetInterceptorService).intercept(INTERCEPTOR_NAMES.BEFORE_CELL_EDIT, {+ get(SheetInterceptorService).intercept(numberIntercept, {priority: 0,- handler(value: number, context: { step: number }, next) {+ handler(value, context, next) {if (context.step) {- return next(value + context.step * 2);+ return next((value || 0) + context.step * 2);}return next(value);},});- const result = get(SheetInterceptorService).fetchThroughInterceptors(- INTERCEPTOR_NAMES.BEFORE_CELL_EDIT,- 100,- { step: 10 }- );+ const result = get(SheetInterceptorService).fetchThroughInterceptors(numberIntercept)(100, { step: 10 });expect(result).toBe(130);});it('big priority should be executed first', () => {- get(SheetInterceptorService).intercept(INTERCEPTOR_NAMES.BEFORE_CELL_EDIT, {+ get(SheetInterceptorService).intercept(stringIntercept, {priority: 100,- handler(value: string, _, next) {+ handler(value, _, next) {return next(`${value} first`);},});- get(SheetInterceptorService).intercept(INTERCEPTOR_NAMES.BEFORE_CELL_EDIT, {+ get(SheetInterceptorService).intercept(stringIntercept, {priority: 0,- handler(value: string, _, next) {+ handler(value, _, next) {return next(`${value} second`);},});- const result = get(SheetInterceptorService).fetchThroughInterceptors(- INTERCEPTOR_NAMES.BEFORE_CELL_EDIT,- 'zero'- );+ const result = get(SheetInterceptorService).fetchThroughInterceptors(stringIntercept)('zero', null);expect(result).toBe('zero first second');});it('the second interceptor should not be executed when not call next in the first interceptor', () => {- get(SheetInterceptorService).intercept(INTERCEPTOR_NAMES.BEFORE_CELL_EDIT, {+ get(SheetInterceptorService).intercept(stringIntercept, {priority: 100,// eslint-disable-next-line @typescript-eslint/no-unused-vars- handler(value: string, _, _next) {+ handler(value, _, _next) {return `${value} first`;},});- get(SheetInterceptorService).intercept(INTERCEPTOR_NAMES.BEFORE_CELL_EDIT, {+ get(SheetInterceptorService).intercept(stringIntercept, {priority: 0,- handler(value: string, _, next) {+ handler(value, _, next) {return next(`${value} second`);},});- const result = get(SheetInterceptorService).fetchThroughInterceptors(- INTERCEPTOR_NAMES.BEFORE_CELL_EDIT,- 'zero'- );+ const result = get(SheetInterceptorService).fetchThroughInterceptors(stringIntercept)('zero', null);expect(result).toBe('zero first');});it('should return the initial value when there is no interceptor', () => {- const result = get(SheetInterceptorService).fetchThroughInterceptors(- INTERCEPTOR_NAMES.BEFORE_CELL_EDIT,- 'zero'- );+ const result = get(SheetInterceptorService).fetchThroughInterceptors(stringIntercept)('zero', null);expect(result).toBe('zero');});diff --git a/packages/core/src/services/sheet-interceptor/interceptor-const.ts b/packages/core/src/services/sheet-interceptor/interceptor-const.tsnew file mode 100644index 0000000000..758f7b2dff--- /dev/null+++ b/packages/core/src/services/sheet-interceptor/interceptor-const.ts@@ -0,0 +1,16 @@+import { ICellData } from '../../types/interfaces/i-cell-data';+import { ICommandInfo } from '../command/command.service';+import type { ISheetLocation } from './utils/interceptor';+import { createInterceptorKey } from './utils/interceptor';++const CELL_CONTENT = createInterceptorKey<ICellData, ISheetLocation>('CELL_CONTENT');+const BEFORE_CELL_EDIT = createInterceptorKey<ICellData, ISheetLocation>('BEFORE_CELL_EDIT');+const AFTER_CELL_EDIT = createInterceptorKey<ICellData>('AFTER_CELL_EDIT');+const PERMISSION = createInterceptorKey<boolean, ICommandInfo>('PERMISSION');++export const INTERCEPTOR_POINT = {+ CELL_CONTENT,+ BEFORE_CELL_EDIT,+ AFTER_CELL_EDIT,+ PERMISSION,+};diff --git a/packages/core/src/services/sheet-interceptor/sheet-interceptor.service.ts b/packages/core/src/services/sheet-interceptor/sheet-interceptor.service.tsindex 497bd7edd6..556a4ee321 100644--- a/packages/core/src/services/sheet-interceptor/sheet-interceptor.service.ts+++ b/packages/core/src/services/sheet-interceptor/sheet-interceptor.service.ts@@ -10,71 +10,14 @@ import { ICommandInfo } from '../command/command.service';import { IUniverInstanceService } from '../instance/instance.service';import { LifecycleStages, OnLifecycle } from '../lifecycle/lifecycle';import { IUndoRedoCommandInfos } from '../undoredo/undoredo.service';--/**- * A helper to compose a certain type of interceptors.- */-function composeInterceptors<M, T>(interceptors: Array<IInterceptor<M, T>>) {- // eslint-disable-next-line func-names- return function (initialValue: Nullable<M>, context: Nullable<T>) {- let index = -1;-- function passThrough(i: number, v: Nullable<M>): Nullable<M> {- if (i <= index) {- throw new Error('[SheetInterceptorService]: next() called multiple times!');- }-- index = i;- if (i === interceptors.length) {- return v;- }-- const interceptor = interceptors[i];-- return interceptor.handler!(v, context, passThrough.bind(null, i + 1));- }-- return passThrough(0, initialValue);- };-}--export interface ISheetLocation {- workbook: Workbook;- worksheet: Worksheet;- workbookId: string;- worksheetId: string;- row: number;- col: number;-}--/**- * Sheet features can provide a `ICellContentInterceptor` to intercept cell content that would be perceived by- * other features, such as copying, rendering, etc.- */--export interface IInterceptor<M = unknown, T = unknown> {- priority?: number;- handler(value: Nullable<M>, context: Nullable<T>, next: (v: Nullable<M>) => Nullable<M>): Nullable<M>;-}+import { INTERCEPTOR_POINT } from './interceptor-const';+import { composeInterceptors, IInterceptor } from './utils/interceptor';export interface ICommandInterceptor {priority?: number;getMutations(command: ICommandInfo): IUndoRedoCommandInfos;}-export interface ICommandPermissionInterceptor {- /**- * This function maybe have side effects ,a pop-up/alert/confirm may be required when the return value is false- */- checkPermission(command: ICommandInfo): boolean;-}--export enum INTERCEPTOR_NAMES {- CELL_CONTENT,- BEFORE_CELL_EDIT,- AFTER_CELL_EDIT,-}-/*** This class expose methods for sheet features to inject code to sheet underlying logic.*@@ -82,9 +25,8 @@ export enum INTERCEPTOR_NAMES {*/@OnLifecycle(LifecycleStages.Starting, SheetInterceptorService)export class SheetInterceptorService extends Disposable {- private _interceptorsByName: Map<INTERCEPTOR_NAMES, IInterceptor[]> = new Map();+ private _interceptorsByName: Map<string, Array<IInterceptor<unknown, unknown>>> = new Map();private _commandInterceptors: ICommandInterceptor[] = [];- private _commandPermissionInterceptor: ICommandPermissionInterceptor[] = [];private readonly _workbookDisposables = new Map<string, IDisposable>();private readonly _worksheetDisposables = new Map<string, IDisposable>();@@ -110,17 +52,22 @@ export class SheetInterceptorService extends Disposable {);// register default viewModel interceptor- this.intercept(INTERCEPTOR_NAMES.CELL_CONTENT, {+ this.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {priority: -1,- handler(content, location: ISheetLocation): Nullable<ICellData> {- const rawData = location.worksheet.getCellRaw(location.row, location.col);- if (content) {- return { ...rawData, ...content };+ handler(value, context): Nullable<ICellData> {+ const rawData = context.worksheet.getCellRaw(context.row, context.col);+ if (value) {+ return { ...rawData, ...value };}return rawData;},});++ this.intercept(INTERCEPTOR_POINT.PERMISSION, {+ priority: -1,+ handler: () => true,+ });}override dispose(): void {@@ -142,14 +89,6 @@ export class SheetInterceptorService extends Disposable {return this.disposeWithMe(toDisposable(() => remove(this._commandInterceptors, interceptor)));}- interceptCommandPermission(interceptor: ICommandPermissionInterceptor): IDisposable {- if (this._commandPermissionInterceptor.includes(interceptor)) {- throw new Error('[SheetInterceptorService]: Interceptor already exists!');- }- this._commandPermissionInterceptor.push(interceptor);- return this.disposeWithMe(toDisposable(() => remove(this._commandPermissionInterceptor, interceptor)));- }-/*** When command is executing, call this method to gether undo redo mutations from upper features.* @param command@@ -164,35 +103,26 @@ export class SheetInterceptorService extends Disposable {};}- /**- * Check the permissions of the user when commands will be executed.- * If one of the return values is false, the command is not executed.- */- onCommandPermissionCheck(command: ICommandInfo): boolean {- const result = this._commandPermissionInterceptor.some((handler) => !handler.checkPermission(command));-- return !result;- }-- intercept(name: INTERCEPTOR_NAMES, interceptor: IInterceptor) {- if (!this._interceptorsByName.has(name)) {- this._interceptorsByName.set(name, []);+ intercept<T extends IInterceptor<any, any>>(name: T, interceptor: T) {+ const key = name as unknown as string;+ if (!this._interceptorsByName.has(key)) {+ this._interceptorsByName.set(key, []);}- const interceptors = this._interceptorsByName.get(name)!;+ const interceptors = this._interceptorsByName.get(key)!;interceptors.push(interceptor);this._interceptorsByName.set(- name,+ key,interceptors.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0)));- return this.disposeWithMe(toDisposable(() => remove(this._interceptorsByName.get(name)!, interceptor)));+ return this.disposeWithMe(toDisposable(() => remove(this._interceptorsByName.get(key)!, interceptor)));}- fetchThroughInterceptors<M, T>(name: INTERCEPTOR_NAMES, initialValue: Nullable<M>, context: Nullable<T>) {- const interceptors = (this._interceptorsByName.get(name) ?? []) as Array<IInterceptor<M, T>>;-- return composeInterceptors<M, T>(interceptors)(initialValue, context);+ fetchThroughInterceptors<T, C>(name: IInterceptor<T, C>) {+ const key = name as unknown as string;+ const interceptors = this._interceptorsByName.get(key) as unknown as Array<typeof name>;+ return composeInterceptors<T>(interceptors || []);}private _interceptWorkbook(workbook: Workbook): void {@@ -206,7 +136,7 @@ export class SheetInterceptorService extends Disposable {const sheetDisposables = new DisposableCollection();const cellInterceptorDisposable = viewModel.registerCellContentInterceptor({getCell(row: number, col: number): Nullable<ICellData> {- return self.fetchThroughInterceptors(INTERCEPTOR_NAMES.CELL_CONTENT, undefined, {+ return self.fetchThroughInterceptors(INTERCEPTOR_POINT.CELL_CONTENT)(undefined, {workbookId,worksheetId,row,diff --git a/packages/core/src/services/sheet-interceptor/utils/interceptor.ts b/packages/core/src/services/sheet-interceptor/utils/interceptor.tsnew file mode 100644index 0000000000..af67e6087b--- /dev/null+++ b/packages/core/src/services/sheet-interceptor/utils/interceptor.ts@@ -0,0 +1,60 @@+import { Nullable } from '../../../common/type-utils';+import { Workbook } from '../../../sheets/workbook';+import { Worksheet } from '../../../sheets/worksheet';++export type InterceptorHandler<M = unknown, C = ISheetLocation> = (+ value: Nullable<M>,+ context: C,+ next: (value: Nullable<M>) => Nullable<M>+) => Nullable<M>;++export type IInterceptor<M, C> = {+ priority?: number;+ handler: InterceptorHandler<M, C>;+};+export interface ISheetLocation {+ workbook: Workbook;+ worksheet: Worksheet;+ workbookId: string;+ worksheetId: string;+ row: number;+ col: number;+}++export const createInterceptorKey = <T = any, C = any>(key: string) => {+ const symbol = `sheet_interceptor_${key}`;+ return symbol as unknown as IInterceptor<T, C>;+};++/**+ * A helper to compose a certain type of interceptors.+ */+export function composeInterceptors<T = any, C = any>(interceptors: Array<IInterceptor<T, C>>) {+ // eslint-disable-next-line func-names+ return function (+ initialValue: Parameters<IInterceptor<T, C>['handler']>[0],+ context: Parameters<IInterceptor<T, C>['handler']>[1]+ ) {+ let index = -1;++ function passThrough(+ i: number,+ v: Parameters<IInterceptor<T, C>['handler']>[0]+ ): Parameters<IInterceptor<T, C>['handler']>[0] {+ if (i <= index) {+ throw new Error('[SheetInterceptorService]: next() called multiple times!');+ }++ index = i;+ if (i === interceptors.length) {+ return v;+ }++ const interceptor = interceptors[i];++ return interceptor.handler!(v, context, passThrough.bind(null, i + 1));+ }++ return passThrough(0, initialValue);+ };+}