import type { AppState } from "@editor/state"; import type { CommandContext } from "./command"; import type { CommandRegistry } from "./registry"; export type Dispatch = (commandId: string, payload: TPayload) => AppState; export type CommandDispatcher = { dispatch: Dispatch; }; export function createCommandDispatcher(options: { registry: CommandRegistry; getState: () => AppState; setState: (state: AppState) => void; }): CommandDispatcher { return { dispatch(commandId, payload) { const command = options.registry.get(commandId); if (!command) { throw new Error(`Unknown command: ${commandId}`); } const context: CommandContext = { state: options.getState() }; const nextState = command.execute(context, payload); options.setState(nextState); return nextState; }, }; }