waveterm/frontend/app/store/contextmenu.ts
Evan Simkowitz f858d3ba0f
Pass workspace id to contextmenu-show (#1429)
Sometimes, the context menu click handlers don't seem to get passed any
window object. Here, I'm sending over the workspace id with the
`contextmenu-show` event so that we can resolve our cached copy of the
object in case the value from the click handler is empty.
2024-12-06 19:10:34 -08:00

58 lines
1.9 KiB
TypeScript

// Copyright 2024, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
import { atoms, getApi, globalStore } from "./global";
class ContextMenuModelType {
handlers: Map<string, () => void> = new Map(); // id -> handler
constructor() {
getApi().onContextMenuClick(this.handleContextMenuClick.bind(this));
}
handleContextMenuClick(id: string): void {
const handler = this.handlers.get(id);
if (handler) {
handler();
}
}
_convertAndRegisterMenu(menu: ContextMenuItem[]): ElectronContextMenuItem[] {
const electronMenuItems: ElectronContextMenuItem[] = [];
for (const item of menu) {
const electronItem: ElectronContextMenuItem = {
role: item.role,
type: item.type,
label: item.label,
sublabel: item.sublabel,
id: crypto.randomUUID(),
checked: item.checked,
};
if (item.visible === false) {
electronItem.visible = false;
}
if (item.enabled === false) {
electronItem.enabled = false;
}
if (item.click) {
this.handlers.set(electronItem.id, item.click);
}
if (item.submenu) {
electronItem.submenu = this._convertAndRegisterMenu(item.submenu);
}
electronMenuItems.push(electronItem);
}
return electronMenuItems;
}
showContextMenu(menu: ContextMenuItem[], ev: React.MouseEvent<any>): void {
this.handlers.clear();
const electronMenuItems = this._convertAndRegisterMenu(menu);
getApi().showContextMenu(globalStore.get(atoms.workspace).oid, electronMenuItems);
}
}
const ContextMenuModel = new ContextMenuModelType();
export { ContextMenuModel, ContextMenuModelType };