2022-10-10 12:50:21 +00:00
|
|
|
import { Hook, Manifest } from "../../plugos/types.ts";
|
|
|
|
import { System } from "../../plugos/system.ts";
|
|
|
|
import { EventEmitter } from "../../plugos/event.ts";
|
2022-03-29 09:21:32 +00:00
|
|
|
|
|
|
|
export type CommandDef = {
|
|
|
|
name: string;
|
|
|
|
|
2022-04-21 09:46:33 +00:00
|
|
|
contexts?: string[];
|
|
|
|
|
2022-03-29 09:21:32 +00:00
|
|
|
// Bind to keyboard shortcut
|
|
|
|
key?: string;
|
|
|
|
mac?: string;
|
|
|
|
};
|
|
|
|
|
|
|
|
export type AppCommand = {
|
|
|
|
command: CommandDef;
|
|
|
|
run: () => Promise<void>;
|
|
|
|
};
|
|
|
|
|
|
|
|
export type CommandHookT = {
|
|
|
|
command?: CommandDef;
|
|
|
|
};
|
|
|
|
|
|
|
|
export type CommandHookEvents = {
|
2022-06-20 16:30:45 +00:00
|
|
|
commandsUpdated(commandMap: Map<string, AppCommand>): void;
|
2022-03-29 09:21:32 +00:00
|
|
|
};
|
|
|
|
|
2022-10-10 12:50:21 +00:00
|
|
|
export class CommandHook extends EventEmitter<CommandHookEvents>
|
|
|
|
implements Hook<CommandHookT> {
|
2022-03-29 09:21:32 +00:00
|
|
|
editorCommands = new Map<string, AppCommand>();
|
|
|
|
|
|
|
|
buildAllCommands(system: System<CommandHookT>) {
|
|
|
|
this.editorCommands.clear();
|
2023-05-23 18:53:53 +00:00
|
|
|
for (const plug of system.loadedPlugs.values()) {
|
2022-10-10 12:50:21 +00:00
|
|
|
for (
|
|
|
|
const [name, functionDef] of Object.entries(
|
|
|
|
plug.manifest!.functions,
|
|
|
|
)
|
|
|
|
) {
|
2022-03-29 09:21:32 +00:00
|
|
|
if (!functionDef.command) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
const cmd = functionDef.command;
|
|
|
|
this.editorCommands.set(cmd.name, {
|
|
|
|
command: cmd,
|
|
|
|
run: () => {
|
2022-07-04 09:52:09 +00:00
|
|
|
return plug.invoke(name, [cmd]);
|
2022-03-29 09:21:32 +00:00
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2022-06-20 16:30:45 +00:00
|
|
|
this.emit("commandsUpdated", this.editorCommands);
|
2022-03-29 09:21:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
apply(system: System<CommandHookT>): void {
|
|
|
|
system.on({
|
|
|
|
plugLoaded: () => {
|
|
|
|
this.buildAllCommands(system);
|
|
|
|
},
|
|
|
|
});
|
2023-07-14 12:22:26 +00:00
|
|
|
// On next tick
|
|
|
|
setTimeout(() => {
|
|
|
|
this.buildAllCommands(system);
|
|
|
|
});
|
2022-03-29 09:21:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
validateManifest(manifest: Manifest<CommandHookT>): string[] {
|
2023-05-23 18:53:53 +00:00
|
|
|
const errors = [];
|
2022-03-29 09:21:32 +00:00
|
|
|
for (const [name, functionDef] of Object.entries(manifest.functions)) {
|
|
|
|
if (!functionDef.command) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
const cmd = functionDef.command;
|
|
|
|
if (!cmd.name) {
|
|
|
|
errors.push(`Function ${name} has a command but no name`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
}
|