@react-md/menu
Version:
Create menus that auto-position themselves within the viewport and adhere to the accessibility guidelines
65 lines • 2.33 kB
JavaScript
import { useCallback, useRef, useState } from "react";
/**
* This is the main visibility hook to be used for the `DropdownMenu` and
* `DropdownMenuItem` components. It'll provide the current visibility as well
* as the default focus type once the menu becomes visible.
*
* @private
*/
export function useVisibility(_a) {
var _b = _a === void 0 ? {} : _a, _c = _b.defaultVisible, defaultVisible = _c === void 0 ? false : _c, _d = _b.defaultFocus, defaultFocusValue = _d === void 0 ? "first" : _d, onVisibilityChange = _b.onVisibilityChange;
var _e = useState({
visible: defaultVisible,
defaultFocus: defaultFocusValue,
}), _f = _e[0], visible = _f.visible, defaultFocus = _f.defaultFocus, setState = _e[1];
var prevVisible = useRef(visible);
if (prevVisible.current !== visible) {
prevVisible.current = visible;
if (onVisibilityChange) {
onVisibilityChange(visible);
}
}
/**
* A callback to use that allows you to provide a string for if the focus
* target should be the "first" or "last" focusable element in the menu. This
* should be "first" for all cases except when the control opens the menu with
* an arrow up key event.
*/
var showWithFocus = useCallback(function (defaultFocus) {
setState({ visible: true, defaultFocus: defaultFocus });
}, []);
/**
* The default implementation of showing the menu that will focus the first
* menu item once visible.
*/
var show = useCallback(function () {
showWithFocus("first");
}, [showWithFocus]);
/**
* Hides the menu.
*/
var hide = useCallback(function () {
setState({ visible: false, defaultFocus: "first" });
}, []);
/**
* Toggles the visibility of the menu.
*/
var toggle = useCallback(function () {
setState(function (_a) {
var visible = _a.visible, defaultFocus = _a.defaultFocus;
return ({
visible: !visible,
defaultFocus: defaultFocus,
});
});
}, []);
return {
visible: visible,
defaultFocus: defaultFocus,
show: show,
showWithFocus: showWithFocus,
hide: hide,
toggle: toggle,
};
}
//# sourceMappingURL=useVisibility.js.map