excalidraw/src/components/ContextMenu.tsx

86 lines
1.8 KiB
TypeScript
Raw Normal View History

2020-01-07 07:50:59 +05:00
import React from "react";
import { Popover } from "./Popover";
import { render, unmountComponentAtNode } from "react-dom";
2020-04-10 18:09:29 -04:00
import "./ContextMenu.scss";
2020-01-07 07:50:59 +05:00
type ContextMenuOption = {
label: string;
action(): void;
};
type Props = {
options: ContextMenuOption[];
onCloseRequest?(): void;
top: number;
left: number;
};
const ContextMenu = ({ options, onCloseRequest, top, left }: Props) => (
<Popover
onCloseRequest={onCloseRequest}
top={top}
left={left}
fitInViewport={true}
>
<ul
className="context-menu"
onContextMenu={(event) => event.preventDefault()}
>
{options.map((option, idx) => (
<li key={idx} onClick={onCloseRequest}>
<ContextMenuOption {...option} />
</li>
))}
</ul>
</Popover>
);
2020-01-07 07:50:59 +05:00
const ContextMenuOption = ({ label, action }: ContextMenuOption) => (
<button className="context-menu-option" onClick={action}>
{label}
</button>
);
2020-01-07 07:50:59 +05:00
let contextMenuNode: HTMLDivElement;
const getContextMenuNode = (): HTMLDivElement => {
2020-01-07 07:50:59 +05:00
if (contextMenuNode) {
return contextMenuNode;
}
const div = document.createElement("div");
document.body.appendChild(div);
return (contextMenuNode = div);
};
2020-01-07 07:50:59 +05:00
type ContextMenuParams = {
options: (ContextMenuOption | false | null | undefined)[];
top: number;
left: number;
};
const handleClose = () => {
2020-01-07 07:50:59 +05:00
unmountComponentAtNode(getContextMenuNode());
};
2020-01-07 07:50:59 +05:00
export default {
push(params: ContextMenuParams) {
const options = Array.of<ContextMenuOption>();
params.options.forEach((option) => {
2020-01-07 07:50:59 +05:00
if (option) {
options.push(option);
}
});
if (options.length) {
render(
<ContextMenu
top={params.top}
left={params.left}
options={options}
onCloseRequest={handleClose}
/>,
2020-01-24 12:04:54 +02:00
getContextMenuNode(),
2020-01-07 07:50:59 +05:00
);
}
2020-01-24 12:04:54 +02:00
},
2020-01-07 07:50:59 +05:00
};