import React, { FC, HTMLAttributes, MouseEvent, ReactElement, useCallback, useState } from 'react';
import { CartesianCoords2D } from '@grafana/data';
interface PanelHeaderMenuTriggerApi {
panelMenuOpen: boolean;
closeMenu: () => void;
}
interface Props extends HTMLAttributes {
children: (props: PanelHeaderMenuTriggerApi) => ReactElement;
}
export const PanelHeaderMenuTrigger: FC = ({ children, ...divProps }) => {
const [clickCoordinates, setClickCoordinates] = useState({ x: 0, y: 0 });
const [panelMenuOpen, setPanelMenuOpen] = useState(false);
const onMenuToggle = useCallback(
(event: MouseEvent) => {
if (!isClick(clickCoordinates, eventToClickCoordinates(event))) {
return;
}
setPanelMenuOpen(!panelMenuOpen);
},
[clickCoordinates, panelMenuOpen, setPanelMenuOpen]
);
const onMouseDown = useCallback(
(event: MouseEvent) => {
setClickCoordinates(eventToClickCoordinates(event));
},
[setClickCoordinates]
);
return (
{children({ panelMenuOpen, closeMenu: () => setPanelMenuOpen(false) })}
);
};
function isClick(current: CartesianCoords2D, clicked: CartesianCoords2D): boolean {
return clicked.x === current.x && clicked.y === current.y;
}
function eventToClickCoordinates(event: MouseEvent): CartesianCoords2D {
return {
x: Math.floor(event.clientX),
y: Math.floor(event.clientY),
};
}