/** * 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 { IAccessor, IDisposable } from '../../common/di'; import { findLast, remove } from '../../common/array'; import { createIdentifier, Inject, Injector } from '../../common/di'; import { CustomCommandExecutionError } from '../../common/error'; import { sequence, sequenceAsync } from '../../common/sequence'; import { Disposable, DisposableCollection, toDisposable } from '../../shared/lifecycle'; import { IConfigService } from '../config/config.service'; import { IContextService } from '../context/context.service'; import { ILogService } from '../log/log.service'; /** * The config key for enabling command execution logging. * Set via `logCommandExecution` in `IUniverConfig` when calling `new Univer()`. * @default true */ export const COMMAND_LOG_EXECUTION_CONFIG_KEY = 'command.logExecution'; /** * The type of a command. */ export enum CommandType { /** * Responsible for creating, orchestrating, and executing MUTATION or OPERATION according to specific business * logic. For example, a delete row COMMAND will generate a delete row MUTATION, an insert row MUTATION for undo, * and a set cell content MUTATION. */ COMMAND = 0, /** * OPERATION is the change made to data that is not saved to snapshot, without conflict resolution, * such as modifying scroll position, modifying sidebar state, etc. */ OPERATION = 1, /** * MUTATION is the change made to the data saved to snapshot, such as inserting rows and columns, * modifying cell content, modifying filter ranges, etc. If you want to add collaborative editing capabilities to * Univer, it is the smallest unit of conflict resolution. */ MUTATION = 2, } /** * In Univer, all data modifications need to be executed through commands. The command-based approach can better track * changes in values, implement functions such as undo, redo, and collaborative editing, handle complex associated * logic between functions, etc. * * All commands should implements this interface or related {@link IMutation} or {@link IOperation} interface, and * should be registered in the {@link ICommandService}. */ export interface ICommand

{ /** * Identifier of the command. It should be unique in the application unless it is a {@link IMultiCommand}. * Its pattern should be like `..`. * * @example { id: 'sheet.command.set-selection-frozen' } */ readonly id: string; /** * The type of the command. */ readonly type: CommandType; /** * The handler of the command. * @param accessor The accessor to the dependency injection container. * @param params Params of the command. Params should be serializable. * @param options Options of the command. * @returns The result of the command. By default it should be a boolean value which indicates the command is * executed successfully or not. */ handler(accessor: IAccessor, params?: P, options?: IExecutionOptions): Promise | R; } /** * A command that may have multiple implementations. Each implementation should have different `priority` * and `preconditions` callback to determine which implementation should be executed. */ export interface IMultiCommand

extends ICommand { /** The name of the multi command. It should be unique in the application. */ name: string; /** @ignore */ multi: true; /** Priority of this implementation. Implementation with higher priority will be checked first. */ priority: number; /** * A callback function that tells `ICommandService` if this implementation should be executed. * @param contextService The context service. * @returns If this implementation should be executed, return `true`, otherwise return `false`. */ preconditions?: (contextService: IContextService) => boolean; } export interface IMutationCommonParams { /** * It is used to indicate which {@link CommandType.COMMAND} or {@link CommandType.OPERATION} triggers the mutation. */ trigger?: string; /** * Mark this mutation as a split chunk from a large mutation. * When collaboration layer encounters this flag, it will send this mutation * in a separate changeset to avoid oversized payloads. * * This is typically set by operations that split large data (e.g., copy worksheet, * paste large ranges) into smaller chunks for better network transmission. */ __splitChunk__?: boolean; } /** * {@link CommandType.MUTATION} should implement this interface. */ export interface IMutation

extends ICommand { type: CommandType.MUTATION; /** * The handler of the mutation. * @param accessor The accessor to the dependency injection container. * @param params Params of the mutation. Params should be serializable. * @returns The result of the mutation. By default it should be a boolean value which indicates the mutation is * executed successfully or not. */ handler(accessor: IAccessor, params: P): R; } /** * {@link CommandType.OPERATION} should implement this interface. */ export interface IOperation

extends ICommand { type: CommandType.OPERATION; /** * The handler of the operation. * @param accessor The accessor to the dependency injection container. * @param params Params of the operation. Params should be serializable. * @returns The result of the operation. By default it should be a boolean value which indicates the operation is * executed successfully or not. */ handler(accessor: IAccessor, params: P): R; } /** * This object represents an execution of a command. */ export interface ICommandInfo { /** * Id of the command being executed. */ id: string; /** * Type of the command. */ type?: CommandType; /** * Parameters of this execution. */ params?: T; } /** This object represents an execution of a {@link CommandType.MUTATION} */ export interface IMutationInfo { id: string; type?: CommandType.MUTATION; params: T; } /** This object represents an execution of a {@link CommandType.OPERATION} */ export interface IOperationInfo { id: string; type?: CommandType.OPERATION; params: T; } export interface IExecutionOptions { /** This mutation should only be executed on the local machine, and should not be synced to replicas. */ onlyLocal?: boolean; /** This command is from collaboration peers. */ fromCollab?: boolean; /** This command is from snapshot load. */ fromChangeset?: boolean; /** * This mutation should be synced to changeset but not executed locally. * The actual execution will be handled asynchronously via onlyLocal. */ syncOnly?: boolean; [key: PropertyKey]: string | number | boolean | undefined; } export type CommandListener = (commandInfo: Readonly, options?: IExecutionOptions) => void; /** * The identifier of the command service. */ export const ICommandService = createIdentifier('univer.core.command-service'); /** * The service to register and execute commands. */ export interface ICommandService { disposed(): boolean; /** * Check if a command is already registered at the current command service. * @param commandId The id of the command. * @returns If the command is registered, return `true`, otherwise return `false`. */ hasCommand(commandId: string): boolean; /** * Register a command to the command service. * @param command The command to register. */ registerCommand(command: ICommand): IDisposable; /** * Unregister a command from the command service. * @param commandId The id of the command to unregister. */ unregisterCommand(commandId: string): void; /** * Register a command as a multi command. * @param command The command to register as a multi command. */ registerMultipleCommand(command: ICommand): IDisposable; /** * Execute a command with the given id and parameters. * @param id Identifier of the command. * @param params Parameters of this execution. * @param options Options of this execution. * @returns The result of the execution. It is a boolean value by default which indicates the command is executed. */ executeCommand

( id: string, params?: P, options?: IExecutionOptions ): Promise; /** * Execute a command with the given id and parameters synchronously. * @param id Identifier of the command. * @param params Parameters of this execution. * @param options Options of this execution. * @returns The result of the execution. It is a boolean value by default which indicates the command is executed. */ syncExecuteCommand

(id: string, params?: P, options?: IExecutionOptions): R; /** * Register a callback function that will be executed after a command is executed. * Note: This will NOT be called for commands with syncOnly option. * @param listener */ onCommandExecuted(listener: CommandListener): IDisposable; /** * Register a callback function that will be executed before a command is executed. * @param listener */ beforeCommandExecuted(listener: CommandListener): IDisposable; /** * Register a callback function specifically for collaboration sync. * This will only be called for mutations (not commands/operations) that need to be synced, * including syncOnly mutations. * @param listener */ onMutationExecutedForCollab(listener: CommandListener): IDisposable; } class CommandRegistry { private readonly _commands = new Map(); private readonly _commandTypes = new Map(); registerCommand(command: ICommand): IDisposable { if (this._commands.has(command.id)) { throw new Error(`[CommandRegistry]: command "${command.id}" has been registered before.`); } this._commands.set(command.id, command); this._commandTypes.set(command.id, command.type); return toDisposable(() => { this.unregisterCommand(command.id); }); } unregisterCommand(commandId: string): void { this._commands.delete(commandId); this._commandTypes.delete(commandId); } hasCommand(id: string): boolean { return this._commands.has(id); } getCommand(id: string): [ICommand] | null { if (!this._commands.has(id)) { return null; } return [this._commands.get(id)!]; } getCommandType(id: string): CommandType | undefined { return this._commandTypes.get(id); } } interface ICommandExecutionStackItem extends ICommandInfo { } export const NilCommand: ICommand = { id: 'nil', type: CommandType.COMMAND, handler: () => true, }; export class CommandService extends Disposable implements ICommandService { protected readonly _commandRegistry: CommandRegistry; private readonly _beforeCommandExecutionListeners: CommandListener[] = []; private readonly _commandExecutedListeners: CommandListener[] = []; private readonly _collabMutationListeners: CommandListener[] = []; private _multiCommandDisposables = new Map(); private _commandExecutingLevel = 0; private _commandExecutionStack: ICommandExecutionStackItem[] = []; constructor( @Inject(Injector) private readonly _injector: Injector, @ILogService private readonly _logService: ILogService, @IConfigService private readonly _configService: IConfigService ) { super(); this._commandRegistry = new CommandRegistry(); this.registerCommand(NilCommand); } override dispose(): void { super.dispose(); this._commandExecutedListeners.length = 0; this._beforeCommandExecutionListeners.length = 0; this._collabMutationListeners.length = 0; } disposed(): boolean { return this._disposed; } private _warnCommandSkippedAfterDisposed(id: string): void { this._logService.warn('[CommandService]', `command "${id}" skipped because CommandService is disposed.`); } hasCommand(commandId: string): boolean { return this._commandRegistry.hasCommand(commandId); } registerCommand(command: ICommand): IDisposable { return this._commandRegistry.registerCommand(command); } unregisterCommand(commandId: string): void { this._commandRegistry.unregisterCommand(commandId); this._multiCommandDisposables.get(commandId)?.dispose(); } registerMultipleCommand(command: ICommand): IDisposable { return this._registerMultiCommand(command); } beforeCommandExecuted(listener: CommandListener): IDisposable { if (this._beforeCommandExecutionListeners.indexOf(listener) === -1) { this._beforeCommandExecutionListeners.push(listener); return toDisposable(() => { const index = this._beforeCommandExecutionListeners.indexOf(listener); this._beforeCommandExecutionListeners.splice(index, 1); }); } throw new Error('[CommandService]: could not add a listener twice.'); } onCommandExecuted(listener: (commandInfo: ICommandInfo) => void): IDisposable { if (this._commandExecutedListeners.indexOf(listener) === -1) { this._commandExecutedListeners.push(listener); return toDisposable(() => { const index = this._commandExecutedListeners.indexOf(listener); this._commandExecutedListeners.splice(index, 1); }); } throw new Error('[CommandService]: could not add a listener twice.'); } onMutationExecutedForCollab(listener: CommandListener): IDisposable { if (this._collabMutationListeners.indexOf(listener) === -1) { this._collabMutationListeners.push(listener); return toDisposable(() => { const index = this._collabMutationListeners.indexOf(listener); this._collabMutationListeners.splice(index, 1); }); } throw new Error('[CommandService]: could not add a collab mutation listener twice.'); } async executeCommand

( id: string, params?: P, options?: IExecutionOptions ): Promise { if (this._disposed) { this._warnCommandSkippedAfterDisposed(id); return false as R; } try { const item = this._commandRegistry.getCommand(id); if (item) { const [command] = item; const commandInfo: ICommandInfo = { id: command.id, type: command.type, params, }; this._attachMutationTrigger(command, params); const stackItemDisposable = this._pushCommandExecutionStack(commandInfo); const _options = options ?? {}; this._beforeCommandExecutionListeners.forEach((listener) => listener(commandInfo, _options)); if (this._disposed) { stackItemDisposable.dispose(); this._warnCommandSkippedAfterDisposed(id); return false as R; } const result = await this._execute(command as ICommand, params, _options); // For syncOnly mutations, only call collab listeners, not regular listeners if (_options.syncOnly) { if (command.type === CommandType.MUTATION) { this._collabMutationListeners.forEach((listener) => listener(commandInfo, _options)); } } else { this._commandExecutedListeners.forEach((listener) => listener(commandInfo, _options)); if (command.type === CommandType.MUTATION) { this._collabMutationListeners.forEach((listener) => listener(commandInfo, _options)); } } stackItemDisposable.dispose(); return result; } throw new Error(`[CommandService]: command "${id}" is not registered.`); } catch (error) { if (error instanceof CustomCommandExecutionError) { // If need custom logic, can add it here return false as R; } else { throw error; } } } syncExecuteCommand

( id: string, params?: P | undefined, options?: IExecutionOptions ): R { if (this._disposed) { this._warnCommandSkippedAfterDisposed(id); return false as R; } try { const item = this._commandRegistry.getCommand(id); if (item) { const [command] = item; const commandInfo: ICommandInfo = { id: command.id, type: command.type, params, }; this._attachMutationTrigger(command, params); const stackItemDisposable = this._pushCommandExecutionStack(commandInfo); const _options = options ?? {}; this._beforeCommandExecutionListeners.forEach((listener) => listener(commandInfo, _options)); if (this._disposed) { stackItemDisposable.dispose(); this._warnCommandSkippedAfterDisposed(id); return false as R; } const result = this._syncExecute(command as ICommand, params, _options); // For syncOnly mutations, only call collab listeners, not regular listeners if (_options.syncOnly) { if (command.type === CommandType.MUTATION) { this._collabMutationListeners.forEach((listener) => listener(commandInfo, _options)); } } else { this._commandExecutedListeners.forEach((listener) => listener(commandInfo, _options)); if (command.type === CommandType.MUTATION) { this._collabMutationListeners.forEach((listener) => listener(commandInfo, _options)); } } stackItemDisposable.dispose(); return result; } throw new Error(`[CommandService]: command "${id}" is not registered.`); } catch (error) { if (error instanceof CustomCommandExecutionError) { return false as R; } else { throw error; } } } private _pushCommandExecutionStack(stackItem: ICommandExecutionStackItem): IDisposable { this._commandExecutionStack.push(stackItem); return toDisposable(() => remove(this._commandExecutionStack, stackItem)); } private _registerMultiCommand(command: ICommand): IDisposable { // compose a multi command and register it const registry = this._commandRegistry.getCommand(command.id); let multiCommand: MultiCommand; if (!registry) { multiCommand = new MultiCommand(command.id); const disposableCollection = new DisposableCollection(); disposableCollection.add(this._commandRegistry.registerCommand(multiCommand)); disposableCollection.add( toDisposable(() => { this._multiCommandDisposables.delete(command.id); }) ); this._multiCommandDisposables.set(command.id, disposableCollection); } else { const registeredCommand = registry[0]; if (!(registeredCommand instanceof MultiCommand)) { throw new TypeError('Command has registered as a single command.'); } multiCommand = registeredCommand; } const implementationDisposable = multiCommand.registerImplementation(command as IMultiCommand); return toDisposable(() => { implementationDisposable.dispose(); if (!multiCommand.hasImplementations()) { this._multiCommandDisposables.get(command.id)?.dispose(); } }); } private _attachMutationTrigger

(command: ICommand

, params?: P): void { if (command.type !== CommandType.MUTATION || !params) { return; } const triggerCommand = findLast( this._commandExecutionStack, (item) => item.type === CommandType.COMMAND ); if (triggerCommand) { this._setMutationTrigger(params, triggerCommand.id); return; } if ('trigger' in params && params.trigger !== undefined) { return; } const triggerOperation = findLast( this._commandExecutionStack, (item) => item.type === CommandType.OPERATION ); if (triggerOperation) { this._setMutationTrigger(params, triggerOperation.id); } } private _setMutationTrigger(params: object, trigger: string): void { Object.assign(params, { trigger } satisfies IMutationCommonParams); } private async _execute

(command: ICommand, params?: P, options?: IExecutionOptions): Promise { // If syncOnly is true, skip execution but return true to indicate success for sync purposes if (options?.syncOnly) { return true as R; } if (this._configService.getConfig(COMMAND_LOG_EXECUTION_CONFIG_KEY) !== false) { this._logService.debug( '[CommandService]', `${'|-'.repeat(Math.max(this._commandExecutingLevel, 0))}executing command "${command.id}"` ); } this._commandExecutingLevel++; let result: R | boolean; try { result = await this._injector.invoke(command.handler, params, options); this._commandExecutingLevel--; } catch (e) { result = false; this._commandExecutingLevel = 0; throw e; } return result; } private _syncExecute

(command: ICommand, params?: P, options?: IExecutionOptions): R { // If syncOnly is true, skip execution but return true to indicate success for sync purposes if (options?.syncOnly) { return true as R; } if (this._configService.getConfig(COMMAND_LOG_EXECUTION_CONFIG_KEY) !== false) { this._logService.debug( '[CommandService]', `${'|-'.repeat(Math.max(0, this._commandExecutingLevel))}executing command "${command.id}".` ); } this._commandExecutingLevel++; let result: R | boolean; try { result = this._injector.invoke(command.handler, params, options) as R; if (result instanceof Promise) { throw new TypeError('[CommandService]: Command handler should not return a promise.'); } this._commandExecutingLevel--; } catch (e) { result = false; this._commandExecutingLevel = 0; throw e; } return result; } } class MultiCommand implements IMultiCommand { readonly name: string; readonly multi = true; readonly type = CommandType.COMMAND; readonly priority: number = 0; private readonly _implementations: Array<{ command: IMultiCommand }> = []; constructor(readonly id: string) { this.name = id; } registerImplementation(implementation: IMultiCommand): IDisposable { const registry = { command: implementation }; this._implementations.push(registry); this._implementations.sort((a, b) => b.command.priority - a.command.priority); return toDisposable(() => { const index = this._implementations.indexOf(registry); this._implementations.splice(index, 1); }); } hasImplementations(): boolean { return this._implementations.length > 0; } handler = async (accessor: IAccessor, params?: object | undefined): Promise => { if (!this._implementations.length) { return false; } const logService = accessor.get(ILogService); const contextService = accessor.get(IContextService); const injector = accessor.get(Injector); for (const item of this._implementations) { const preconditions = item.command.preconditions; if (!preconditions || (preconditions && preconditions(contextService))) { logService.debug('[MultiCommand]', `executing implementation "${item.command.name}".`); const result = await injector.invoke(item.command.handler, params); if (result) { return true; } } } return false; }; } export function sequenceExecute(tasks: ICommandInfo[], commandService: ICommandService, options?: IExecutionOptions) { const taskFns = tasks.map((task) => () => commandService.syncExecuteCommand(task.id, task.params, options)); return sequence(taskFns); } export function sequenceExecuteAsync( tasks: ICommandInfo[], commandService: ICommandService, options?: IExecutionOptions ) { const promises = tasks.map((task) => () => commandService.executeCommand(task.id, task.params, options)); return sequenceAsync(promises); }