UNPKG

@atlaskit/dropdown-menu

Version:

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

51 lines (48 loc) 2.11 kB
import _slicedToArray from "@babel/runtime/helpers/slicedToArray"; import { useCallback, useContext, useState } from 'react'; import { CheckboxGroupContext } from '../context/checkbox-group-context'; import { SelectionStoreContext } from '../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 = useContext(SelectionStoreContext), setItemState = _useContext.setItemState, getItemState = _useContext.getItemState; var groupId = useContext(CheckboxGroupContext); var persistedIsSelected = getItemState(groupId, id); var _useState = 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 = _slicedToArray(_useState, 2), localIsSelected = _useState2[0], setLocalIsSelected = _useState2[1]; var setLocalState = 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]; }; export default useCheckboxState;