@react-md/menu
Version:
Create menus that auto-position themselves within the viewport and adhere to the accessibility guidelines
54 lines • 2.24 kB
JavaScript
import { useCallback, useEffect, useState, } from "react";
import { SCALE_Y_CLASSNAMES } from "@react-md/transition";
import { containsElement, TOP_INNER_LEFT_ANCHOR, useEnsuredRef, } from "@react-md/utils";
var DEFAULT_CONTEXT_MENU_ID = "context-menu";
export function useContextMenu(_a) {
var _b = _a === void 0 ? {} : _a, _c = _b.id, id = _c === void 0 ? DEFAULT_CONTEXT_MENU_ID : _c, propRef = _b.ref, _d = _b.anchor, anchor = _d === void 0 ? TOP_INNER_LEFT_ANCHOR : _d, _e = _b.classNames, classNames = _e === void 0 ? SCALE_Y_CLASSNAMES : _e, _f = _b.disableDeselect, disableDeselect = _f === void 0 ? false : _f;
var _g = useState(false), visible = _g[0], setVisible = _g[1];
var onRequestClose = useCallback(function () {
setVisible(false);
}, []);
var _h = useState({}), coords = _h[0], setCoords = _h[1];
var onContextMenu = useCallback(function (event) {
event.preventDefault();
event.stopPropagation();
var selection = window.getSelection();
if (selection && !disableDeselect) {
selection.empty();
}
setVisible(true);
if (event.button === 0 && event.buttons === 0) {
setCoords({});
return;
}
setCoords({ initialX: event.clientX, initialY: event.clientY });
}, [disableDeselect]);
var _j = useEnsuredRef(propRef), ref = _j[0], refHandler = _j[1];
useEffect(function () {
if (!visible) {
return;
}
var hide = function (event) {
var target = event.target;
if (!containsElement(ref, target)) {
onRequestClose();
}
};
window.addEventListener("contextmenu", hide, true);
return function () {
window.removeEventListener("contextmenu", hide, true);
};
}, [onRequestClose, visible, ref]);
var menuProps = {
id: id,
ref: refHandler,
anchor: anchor,
visible: visible,
classNames: classNames,
onRequestClose: onRequestClose,
positionOptions: coords,
disableControlClickOkay: true,
};
return [menuProps, onContextMenu, setVisible];
}
//# sourceMappingURL=useContextMenu.js.map