UNPKG

@atlaskit/dropdown-menu

Version:

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

62 lines (58 loc) • 2.82 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 _fg = require("@atlaskit/platform-feature-flags/fg"); var _checkboxGroupContext = require("../context/checkbox-group-context"); var _selectionStoreContext = require("../context/selection-store-context"); /** * 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)(_selectionStoreContext.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) { // With `platform-dst-top-layer`, read the store when the callback runs, not the value // from render time. The first render writes the default to the store during render, so // a value captured in that render is still `undefined`. var nextValue = newValue((0, _fg.fg)('platform-dst-top-layer') ? getItemState(groupId, id) : persistedIsSelected); setLocalIsSelected(nextValue); setItemState(groupId, id, nextValue); }, [setItemState, getItemState, 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;