feat(commands): add app state dispatcher foundation
This commit is contained in:
29
commands/dispatcher.ts
Normal file
29
commands/dispatcher.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import type { AppState } from "@editor/state";
|
||||
import type { CommandContext } from "./command";
|
||||
import type { CommandRegistry } from "./registry";
|
||||
|
||||
export type Dispatch = <TPayload>(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;
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user