add contextmenu model, example code in block.tsx

This commit is contained in:
sawka 2024-06-20 12:34:32 -07:00
parent 0a19aa31d4
commit d59e0f5959
2 changed files with 62 additions and 3 deletions

View File

@ -7,6 +7,7 @@ import { PreviewView } from "@/app/view/preview";
import { TerminalView } from "@/app/view/term/term";
import { ErrorBoundary } from "@/element/errorboundary";
import { CenteredDiv } from "@/element/quickelems";
import { ContextMenuModel } from "@/store/contextmenu";
import { atoms, globalStore, useBlockAtom } from "@/store/global";
import * as WOS from "@/store/wos";
import clsx from "clsx";
@ -87,6 +88,14 @@ const BlockFrame_Tech = ({
if (preview) {
isFocused = true;
}
function handleContextMenu(e: React.MouseEvent<HTMLDivElement>) {
let menu: ContextMenuItem[] = [];
menu.push({
label: "Close",
click: onClose,
});
ContextMenuModel.showContextMenu(menu, e);
}
return (
<div
className={clsx(
@ -98,11 +107,11 @@ const BlockFrame_Tech = ({
onClick={onClick}
ref={blockRef}
>
<div className="block-frame-tech-header" ref={dragHandleRef}>
<div className="block-frame-tech-header" ref={dragHandleRef} onContextMenu={handleContextMenu}>
{getBlockHeaderText(blockData)}
</div>
<div className="block-frame-tech-close" onClick={onClose}>
<i className="fa fa-solid fa-xmark fa-fw " />
<div className={clsx("block-frame-tech-close")} onClick={onClose}>
<i className="fa fa-solid fa-xmark fa-fw" />
</div>
{preview ? <div className="block-frame-preview" /> : children}
</div>

View File

@ -0,0 +1,50 @@
// Copyright 2024, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
import { v4 as uuidv4 } from "uuid";
import { getApi } from "./global";
class ContextMenuModelType {
handlers: Map<string, () => void> = new Map(); // id -> handler
constructor() {
getApi().onContextMenuClick(this.handleContextMenuClick.bind(this));
}
handleContextMenuClick(e: any, id: string): void {
let handler = this.handlers.get(id);
if (handler) {
handler();
}
}
_convertAndRegisterMenu(menu: ContextMenuItem[]): ElectronContextMenuItem[] {
let electronMenuItems: ElectronContextMenuItem[] = [];
for (let item of menu) {
let electronItem: ElectronContextMenuItem = {
role: item.role,
type: item.type,
label: item.label,
id: uuidv4(),
};
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(electronMenuItems, { x: ev.clientX, y: ev.clientY });
}
}
const ContextMenuModel = new ContextMenuModelType();
export { ContextMenuModel, ContextMenuModelType };