@react-md/menu
Version:
Create menus that auto-position themselves within the viewport and adhere to the accessibility guidelines
69 lines • 2.5 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useVisibility = void 0;
var react_1 = require("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
*/
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 = react_1.useState({
visible: defaultVisible,
defaultFocus: defaultFocusValue,
}), _f = _e[0], visible = _f.visible, defaultFocus = _f.defaultFocus, setState = _e[1];
var prevVisible = react_1.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 = react_1.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 = react_1.useCallback(function () {
showWithFocus("first");
}, [showWithFocus]);
/**
* Hides the menu.
*/
var hide = react_1.useCallback(function () {
setState({ visible: false, defaultFocus: "first" });
}, []);
/**
* Toggles the visibility of the menu.
*/
var toggle = react_1.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,
};
}
exports.useVisibility = useVisibility;
//# sourceMappingURL=useVisibility.js.map