"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AccordionPanel = exports.AccordionHeader = exports.AccordionIcon = exports.AccordionItem = exports.Accordion = void 0;

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _autoId = require("@reach/auto-id");

var _ChevronDownIcon = _interopRequireDefault(require("mdi-react/ChevronDownIcon"));

var _react = _interopRequireWildcard(require("react"));

var _Box = require("../Box");

var _Collapse = require("../Collapse");

var _PseudoBox = require("../PseudoBox");

var _styles = _interopRequireDefault(require("./styles"));

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

var __jsx = _react["default"].createElement;

/**
 * The accordion component delivers large amounts of content in a small space through progressive disclosure.
 *
 * By default, only one item may be expanded and it can only be collapsed again by expanding another.
 */

/**
 * Accordions allow users to expand and collapse sections of content.
 * It composes `Box` component.
 */
var Accordion = function Accordion(_ref) {
  var allowMultiple = _ref.allowMultiple,
      allowToggle = _ref.allowToggle,
      index = _ref.index,
      defaultIndex = _ref.defaultIndex,
      _onChange = _ref.onChange,
      children = _ref.children,
      rest = (0, _objectWithoutProperties2["default"])(_ref, ["allowMultiple", "allowToggle", "index", "defaultIndex", "onChange", "children"]);

  var initializeState = function initializeState() {
    if (allowMultiple) {
      return defaultIndex || [];
    }

    return defaultIndex || 0;
  };

  var getExpandCondition = function getExpandCondition(i, itemIndex) {
    if (Array.isArray(i)) {
      return i.includes(itemIndex);
    }

    return i === itemIndex;
  };

  var _useState = (0, _react.useState)(initializeState),
      expandedIndex = _useState[0],
      setExpandedIndex = _useState[1];

  var _useRef = (0, _react.useRef)(index != null),
      isControlled = _useRef.current;

  var _useAccordionStyle = (0, _styles["default"])({}),
      accordionStyleProps = _useAccordionStyle.root;

  var _index = isControlled ? index : expandedIndex;

  var clones = _react.Children.map(children, function (child, childIndex) {
    if (! /*#__PURE__*/(0, _react.isValidElement)(child)) {
      return null;
    }

    return /*#__PURE__*/(0, _react.cloneElement)(child, {
      isOpen: getExpandCondition(_index, childIndex),
      onChange: function onChange(isExpanded) {
        if (allowMultiple) {
          if (isExpanded) {
            var newIndexes = [].concat((0, _toConsumableArray2["default"])(_index), [childIndex]);

            if (!isControlled) {
              setExpandedIndex(newIndexes);
            }

            if (_onChange) {
              _onChange(newIndexes);
            }
          } else {
            var _newIndexes = _index.filter(function (itemIndex) {
              return itemIndex !== childIndex;
            });

            if (!isControlled) {
              setExpandedIndex(_newIndexes);
            }

            if (_onChange) {
              _onChange(_newIndexes);
            }
          }
        } else if (isExpanded) {
          if (!isControlled) {
            setExpandedIndex(childIndex);
          }

          if (_onChange) {
            _onChange(childIndex);
          }
        } else if (allowToggle) {
          if (!isControlled) {
            setExpandedIndex(null);
          }

          if (_onChange) {
            _onChange(null);
          }
        }
      }
    });
  });

  return __jsx(_Box.Box, (0, _extends2["default"])({
    "data-accordion": ""
  }, accordionStyleProps, rest), clones);
};

exports.Accordion = Accordion;
var AccordionItemContext = /*#__PURE__*/(0, _react.createContext)({});

var useAccordionItemContext = function useAccordionItemContext() {
  return (0, _react.useContext)(AccordionItemContext);
};
/**
 * The content of the accordion.
 * The children must be the `AccordionHeader` and `AccordionPanel` components.
 */


var AccordionItem = /*#__PURE__*/(0, _react.forwardRef)(function (_ref2, ref) {
  var isOpen = _ref2.isOpen,
      defaultIsOpen = _ref2.defaultIsOpen,
      id = _ref2.id,
      isDisabled = _ref2.isDisabled,
      onChange = _ref2.onChange,
      children = _ref2.children,
      rest = (0, _objectWithoutProperties2["default"])(_ref2, ["isOpen", "defaultIsOpen", "id", "isDisabled", "onChange", "children"]);

  var _useState2 = (0, _react.useState)(defaultIsOpen || false),
      isExpanded = _useState2[0],
      setIsExpanded = _useState2[1];

  var _useRef2 = (0, _react.useRef)(isOpen != null),
      isControlled = _useRef2.current;

  var _isExpanded = isControlled ? isOpen : isExpanded;

  var _useAccordionStyle2 = (0, _styles["default"])({}),
      accordionItemStyleProps = _useAccordionStyle2.item;

  var onToggle = function onToggle() {
    if (onChange) {
      onChange(!_isExpanded);
    }

    if (!isControlled) {
      setIsExpanded(!isExpanded);
    }
  };

  var uuid = (0, _autoId.useId)();
  var uniqueId = id || uuid;
  var headerId = "accordion-header-".concat(uniqueId);
  var panelId = "accordion-panel-".concat(uniqueId);
  return __jsx(AccordionItemContext.Provider, {
    value: {
      isExpanded: _isExpanded,
      isDisabled: isDisabled,
      headerId: headerId,
      panelId: panelId,
      onToggle: onToggle
    }
  }, __jsx(_PseudoBox.PseudoBox, (0, _extends2["default"])({
    "data-accordion-item": "",
    ref: ref
  }, accordionItemStyleProps, rest), typeof children === 'function' ? children({
    isExpanded: _isExpanded,
    isDisabled: isDisabled
  }) : children));
});
/**
 * AccordionHeader component composes `PseudoBox`, this means you can use
 * the `_expanded`, `_disabled`, `_hover`, etc. props to style them
 */

exports.AccordionItem = AccordionItem;
var AccordionHeader = /*#__PURE__*/(0, _react.forwardRef)(function (_ref3, ref) {
  var _onClick = _ref3.onClick,
      props = (0, _objectWithoutProperties2["default"])(_ref3, ["onClick"]);

  var _useAccordionItemCont = useAccordionItemContext(),
      isExpanded = _useAccordionItemCont.isExpanded,
      panelId = _useAccordionItemCont.panelId,
      headerId = _useAccordionItemCont.headerId,
      isDisabled = _useAccordionItemCont.isDisabled,
      onToggle = _useAccordionItemCont.onToggle;

  var _useAccordionStyle3 = (0, _styles["default"])({}),
      accordionHeaderStyleProps = _useAccordionStyle3.header;

  return __jsx(_PseudoBox.PseudoBox, (0, _extends2["default"])({
    ref: ref,
    as: "button",
    type: "button",
    disabled: isDisabled,
    "aria-disabled": isDisabled,
    "aria-expanded": isExpanded,
    onClick: function onClick(event) {
      onToggle();

      if (_onClick) {
        _onClick(event);
      }
    },
    id: headerId,
    "aria-controls": panelId
  }, accordionHeaderStyleProps, props));
});
/**
 * AccordionPanel component composes `Collapse` to provide the height animation
 */

exports.AccordionHeader = AccordionHeader;
var AccordionPanel = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var _useAccordionItemCont2 = useAccordionItemContext(),
      isExpanded = _useAccordionItemCont2.isExpanded,
      panelId = _useAccordionItemCont2.panelId,
      headerId = _useAccordionItemCont2.headerId;

  var _useAccordionStyle4 = (0, _styles["default"])({}),
      accordionPanelStyleProps = _useAccordionStyle4.panel;

  return __jsx(_Collapse.Collapse, (0, _extends2["default"])({
    ref: ref,
    "data-accordion-panel": "",
    role: "region",
    id: panelId,
    "aria-labelledby": headerId,
    "aria-hidden": !isExpanded,
    isOpen: isExpanded
  }, accordionPanelStyleProps, props));
});
exports.AccordionPanel = AccordionPanel;

var AccordionIcon = function AccordionIcon(props) {
  var _useAccordionItemCont3 = useAccordionItemContext(),
      isExpanded = _useAccordionItemCont3.isExpanded,
      isDisabled = _useAccordionItemCont3.isDisabled;

  var _useAccordionStyle5 = (0, _styles["default"])({
    isDisabled: isDisabled,
    isExpanded: isExpanded
  }),
      accordionIconStyleProps = _useAccordionStyle5.icon;

  return __jsx(_Box.Box, (0, _extends2["default"])({}, accordionIconStyleProps, props), __jsx(_ChevronDownIcon["default"], null));
};

exports.AccordionIcon = AccordionIcon;
//# sourceMappingURL=Accordion.js.map