UNPKG

@atlaskit/dropdown-menu

Version:

A dropdown menu displays a list of actions or options to a user.

58 lines (54 loc) 2.41 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _react = require("react"); var _checkboxGroupContext = require("../context/checkbox-group-context"); var _selectionStore = require("../context/selection-store"); /** * Custom hook to handle checkbox state for dropdown menu. * It works in tandem with the selection store context when the * component is uncontrolled. */ var useCheckboxState = function useCheckboxState(_ref) { var isSelected = _ref.isSelected, id = _ref.id, defaultSelected = _ref.defaultSelected; var _useContext = (0, _react.useContext)(_selectionStore.SelectionStoreContext), setItemState = _useContext.setItemState, getItemState = _useContext.getItemState; var groupId = (0, _react.useContext)(_checkboxGroupContext.CheckboxGroupContext); var persistedIsSelected = getItemState(groupId, id); var _useState = (0, _react.useState)( // Initial state is set depending on value being defined or not. // This state is only utilised if the checkbox is uncontrolled. function () { return persistedIsSelected !== undefined ? persistedIsSelected : defaultSelected || false; }), _useState2 = (0, _slicedToArray2.default)(_useState, 2), localIsSelected = _useState2[0], setLocalIsSelected = _useState2[1]; var setLocalState = (0, _react.useCallback)(function (newValue) { var nextValue = newValue(persistedIsSelected); setLocalIsSelected(nextValue); setItemState(groupId, id, nextValue); }, [setItemState, persistedIsSelected, groupId, id]); // Checkbox is controlled - do nothing! if (typeof isSelected === 'boolean') { return [isSelected, function () { return false; }]; } // Checkbox is going through its first render pass! if (persistedIsSelected === undefined) { // Set the item so we have this state to access next time the checkbox renders (either by mounting or re-rendering!) setItemState(groupId, id, defaultSelected || false); } // Return the value and setter! // Remember this flow is only returned if the checkbox is uncontrolled. return [localIsSelected, setLocalState]; }; var _default = exports.default = useCheckboxState;