hugo-commandbar/assets/commandbar/js/commandExecutor.js

57 lines
1.3 KiB
JavaScript

import { SetOptionHandler } from "./setHandler.js";
export class CommandExecutor {
commandBar;
#history = [];
#handlers = new Map();
constructor(commandBar) {
this.commandBar = commandBar;
console.log(this.#handlers);
this.addHandler(new SetOptionHandler());
console.log(this.#handlers);
}
addHandler(handler) {
this.#handlers.set(handler.name, handler);
}
executeCommand(command) {
this.appendCommandToHistory(command);
const handler = this.#handlerForCommand(command);
if (!handler) {
throw new Error(`No handler for '${command.verb.valueOf()}' command`);
}
let result;
try {
result = handler.execute(command, this.commandBar);
} catch (e) {
result = null;
}
if (result !== undefined && !result) {
console.error(`Command failed: ${command}`);
}
}
#handlerForCommand(command) {
const verb = command.verb.valueOf();
return this.#handlers.get(verb);
}
// MARK: History
get historyLength() {
return this.#history.length;
}
appendCommandToHistory(command) {
this.#history.push(command);
}
commandAtHistoryIndex(index) {
return this.#history[index];
}
}