"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.KEY_CODES = exports.AccordionContext = void 0;

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

var _classnames = _interopRequireDefault(require("classnames"));

var _useReducedMotion = _interopRequireDefault(require("../utils/useReducedMotion"));

var _utils = require("../utils");

var _responsiveProps = require("../utils/responsive-props");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

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; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

var KEY_CODES = {
  '32': 'space',
  '13': 'enter'
};
exports.KEY_CODES = KEY_CODES;
var AccordionContext = /*#__PURE__*/(0, React.createContext)({});
exports.AccordionContext = AccordionContext;

var Accordion = function Accordion(_ref) {
  var children = _ref.children,
      _ref$allowMultiple = _ref.allowMultiple,
      allowMultiple = _ref$allowMultiple === void 0 ? false : _ref$allowMultiple,
      _ref$className = _ref.className,
      className = _ref$className === void 0 ? '' : _ref$className,
      _ref$spacing = _ref.spacing,
      spacing = _ref$spacing === void 0 ? 's' : _ref$spacing,
      _ref$reduceMotion = _ref.reduceMotion,
      reduceMotion = _ref$reduceMotion === void 0 ? false : _ref$reduceMotion,
      defaultExpanded = _ref.defaultExpanded,
      expanded = _ref.expanded,
      onChange = _ref.onChange,
      ariaLabel = _ref['aria-label'],
      ariaLabelledby = _ref['aria-labelledby'];
  var wrapperRef = (0, React.useRef)(null);
  var isControlled = expanded !== undefined;

  var _useRef = (0, React.useRef)(isControlled),
      wasControlled = _useRef.current;

  if (_utils.__DEV__) {
    (0, _utils.invariant)(!(isControlled && !onChange), // eslint-disable-next-line max-len
    'You provided an `expanded` prop to an Accordion without an `onChange` handler. Users won`t be able to switch between expanded/collapsed state.');
    (0, _utils.invariant)(!(wasControlled && !isControlled), 'You cannot change Accordion component from controlled to uncontrolled variant.');
    (0, _utils.invariant)(!(!wasControlled && isControlled), 'You cannot change Accordion component from uncontrolled to controlled variant.');
    (0, _utils.invariant)(!(isControlled && allowMultiple), 'allowMultiple is not working in controlled Accordion');
    (0, _utils.invariant)(!(!allowMultiple && Array.isArray(defaultExpanded) && defaultExpanded.length > 1), // eslint-disable-next-line max-len
    'defaultExpanded is an array with more than 1 element but allowMultiple prop is not set. The first value from the array was picked as a default expanded. Set allowMultiple attribute or provide only one default expanded.');
  }

  var getUpdatedOpenedItems = (0, React.useCallback)(function (expanded, id, value) {
    if (value) {
      return allowMultiple ? _toConsumableArray(new Set([].concat(_toConsumableArray(expanded), [id]))) : [id];
    }

    return allowMultiple ? expanded.filter(function (item) {
      return item !== id;
    }) : [];
  }, [allowMultiple]);

  var _useReducer = (0, React.useReducer)(reducer, null, function () {
    if (isControlled) {
      return {
        expanded: [],
        focusedElementId: null
      };
    }

    if (defaultExpanded !== undefined) {
      var expandedArray = Array.isArray(defaultExpanded) ? defaultExpanded : [defaultExpanded];
      var newState = expandedArray.filter(function (item, idx) {
        return allowMultiple || idx < 1;
      });
      return {
        expanded: newState,
        focusedElementId: null
      };
    }

    return {
      expanded: [],
      focusedElementId: null
    };
  }),
      _useReducer2 = _slicedToArray(_useReducer, 2),
      state = _useReducer2[0],
      dispatch = _useReducer2[1];

  var hasReduceMotion = (0, _useReducedMotion.default)() || reduceMotion;
  (0, React.useEffect)(function () {
    var wrapper = wrapperRef.current;

    function handleKeyDown(event) {
      var key = KEY_CODES[event.keyCode];

      if (['space', 'enter'].includes(key)) {
        if (event.target instanceof HTMLElement && event.target.id === state.focusedElementId) {
          event.preventDefault();
        }

        dispatch({
          type: 'accordion/KEYBOARD_SET_EXPANDED'
        });
      }
    }

    if (!wrapper) return;
    wrapper.addEventListener('keydown', handleKeyDown);
    return function () {
      if (!wrapper) return;
      wrapper.removeEventListener('keydown', handleKeyDown);
    };
  }, [state.focusedElementId]);

  function reducer(state, action) {
    switch (action.type) {
      case 'accordion/TOGGLE_EXPAND':
        {
          var _action$payload = action.payload,
              _id = _action$payload.id,
              _expanded = _action$payload.expanded;
          return _objectSpread(_objectSpread({}, state), {}, {
            expanded: getUpdatedOpenedItems(state.expanded, _id, _expanded)
          });
        }

      case 'accordion/SET_EXPANDED':
        {
          var _expanded2 = action.payload.expanded;
          return _objectSpread(_objectSpread({}, state), {}, {
            expanded: _expanded2
          });
        }

      case 'accordion/KEYBOARD_SET_EXPANDED':
        {
          var _expanded3 = state.expanded,
              focusedElementId = state.focusedElementId;
          if (focusedElementId === null) return state;
          return _objectSpread(_objectSpread({}, state), {}, {
            expanded: getUpdatedOpenedItems(state.expanded, focusedElementId, !_expanded3.includes(focusedElementId))
          });
        }

      case 'accordion/SET_FOCUSED':
        {
          return _objectSpread(_objectSpread({}, state), {}, {
            focusedElementId: action.payload.id
          });
        }

      default:
        return state;
    }
  }

  var _useState = (0, React.useState)(''),
      _useState2 = _slicedToArray(_useState, 2),
      prevExpanded = _useState2[0],
      setPrevExpanded = _useState2[1];

  if (isControlled && expanded !== prevExpanded) {
    setPrevExpanded(expanded); // expanded || '' is to satisfy flow.
    // isControlled flag is true when expanded !== undefined but this condition is not interpreted
    // correctly by flow causing type error. Replacing isControlled with expanded !== undefined would work but using isControlled is more clear

    var expandedArray = Array.isArray(expanded) ? expanded : [expanded || ''];
    dispatch({
      type: 'accordion/SET_EXPANDED',
      payload: {
        expanded: expandedArray
      }
    });
  }

  var noGapBetweenElements = spacing === 'none';
  var onItemSelect = (0, React.useCallback)(function (id, value) {
    onChange && onChange(id);

    if (!isControlled) {
      dispatch({
        type: 'accordion/TOGGLE_EXPAND',
        payload: {
          id: id,
          expanded: value
        }
      });
    }
  }, [isControlled, onChange]);
  var context = (0, React.useMemo)(function () {
    return {
      noGapBetweenElements: noGapBetweenElements,
      expanded: state.expanded,
      focusedElementId: state.focusedElementId,
      dispatch: dispatch,
      reduceMotion: hasReduceMotion,
      onItemSelect: onItemSelect
    };
  }, [hasReduceMotion, noGapBetweenElements, onItemSelect, state.focusedElementId, state.expanded]);
  return /*#__PURE__*/React.createElement(AccordionContext.Provider, {
    value: context
  }, /*#__PURE__*/React.createElement("div", {
    ref: wrapperRef,
    className: _classnames.default.apply(void 0, _toConsumableArray((0, _responsiveProps.generateResponsiveClassNames)(function (spacing) {
      return "sg-space-y-".concat(String(spacing));
    }, spacing)).concat([className])),
    "aria-label": ariaLabel,
    "aria-labelledby": ariaLabelledby
  }, children));
};

var _default = Accordion;
exports.default = _default;