|
1 | | -export class CommandManager {} |
| 1 | +/** |
| 2 | + * Contains a generic implementation of typed commands. |
| 3 | + * |
| 4 | + * This allows different parts of the extension to register commands with a certain type, |
| 5 | + * and then allow other parts to call those commands in a well-typed manner. |
| 6 | + */ |
| 7 | + |
| 8 | +import { Disposable } from "./Disposable"; |
| 9 | + |
| 10 | +/** |
| 11 | + * A command function is a completely untyped command. |
| 12 | + */ |
| 13 | +export type CommandFunction = (...args: any[]) => Promise<unknown>; |
| 14 | + |
| 15 | +/** |
| 16 | + * The command manager basically takes a single input, the type |
| 17 | + * of all the known commands. The second parameter is provided by |
| 18 | + * default (and should not be needed by the caller) it is a |
| 19 | + * technicality to allow the type system to look up commands. |
| 20 | + */ |
| 21 | +export class CommandManager< |
| 22 | + Commands extends Record<string, CommandFunction>, |
| 23 | + CommandName extends keyof Commands & string = keyof Commands & string, |
| 24 | +> implements Disposable |
| 25 | +{ |
| 26 | + // TODO: should this be a map? |
| 27 | + // TODO: handle multiple command names |
| 28 | + private commands: Disposable[] = []; |
| 29 | + |
| 30 | + constructor( |
| 31 | + private readonly commandRegister: <T extends CommandName>( |
| 32 | + commandName: T, |
| 33 | + fn: Commands[T], |
| 34 | + ) => Disposable, |
| 35 | + private readonly commandExecute: <T extends CommandName>( |
| 36 | + commandName: T, |
| 37 | + ...args: Parameters<Commands[T]> |
| 38 | + ) => Promise<Awaited<ReturnType<Commands[T]>>>, |
| 39 | + ) {} |
| 40 | + |
| 41 | + /** |
| 42 | + * Register a command with the specified name and implementation. |
| 43 | + */ |
| 44 | + register<T extends CommandName>( |
| 45 | + commandName: T, |
| 46 | + definition: Commands[T], |
| 47 | + ): void { |
| 48 | + this.commands.push(this.commandRegister(commandName, definition)); |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * Execute a command with the specified name and the provided arguments. |
| 53 | + */ |
| 54 | + execute<T extends CommandName>( |
| 55 | + commandName: T, |
| 56 | + ...args: Parameters<Commands[T]> |
| 57 | + ): Promise<Awaited<ReturnType<Commands[T]>>> { |
| 58 | + return this.commandExecute(commandName, ...args); |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * Dispose the manager, disposing all the registered commands. |
| 63 | + */ |
| 64 | + dispose(): void { |
| 65 | + this.commands.forEach((cmd) => { |
| 66 | + cmd.dispose(); |
| 67 | + }); |
| 68 | + this.commands = []; |
| 69 | + } |
| 70 | +} |
0 commit comments