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); }
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 = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) 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; }
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) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
import React from 'react';
import { ulid } from 'ulid';
import { StyledDropdownFlyoutExpandIcon, StyledDropdownFlyoutLabel } from './DropdownFlyout.styles';
import { rootId } from './DropdownFlyout.types';
export function noop() {}
export function returnFalse() {
  return false;
}
function getFirst(arr) {
  return arr[0];
}
function isRootOption(optionId) {
  return optionId === rootId;
}
export function hasChildren(option) {
  return Array.isArray(option.children);
}
function reducer(state, action) {
  switch (action.type) {
    case 'highlight':
      return _objectSpread(_objectSpread({}, state), {}, {
        highlighted: action.option
      });
    case 'expand':
      return _objectSpread(_objectSpread({}, state), {}, {
        highlighted: action.option,
        expanded: [].concat(_toConsumableArray(collectParentIds(state.options, action.option.id)), [action.option.id])
      });
    case 'collapse':
      return _objectSpread(_objectSpread({}, state), {}, {
        highlighted: action.option,
        expanded: collectParentIds(state.options, action.option.id)
      });
    case 'close':
      return _objectSpread(_objectSpread({}, state), {}, {
        expanded: [],
        highlighted: getFirst(state.options),
        isOpen: false
      });
    case 'open':
      return _objectSpread(_objectSpread({}, state), {}, {
        isOpen: true
      });
    case 'setMouseOver':
      return _objectSpread(_objectSpread({}, state), {}, {
        isMouseOver: action.isMouseOver
      });
    case 'setFocused':
      return _objectSpread(_objectSpread({}, state), {}, {
        isFocused: action.isFocused
      });
    default:
      return state;
  }
}
function findById(options, optionId) {
  var initialValue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : getFirst(options);
  return options.reduce(function (result, current) {
    if (current.id === optionId) {
      return current;
    }
    if (current.children) {
      return findById(current.children, optionId, result);
    }
    return result;
  }, initialValue);
}
export function transformOption(options, parentId) {
  return options.reduce(function (acc, option) {
    var id = ulid();
    var updatedOption = _objectSpread({
      id: id,
      parentId: parentId,
      origin: option
    }, Array.isArray(option.children) && {
      children: transformOption(option.children, id)
    });
    return [].concat(_toConsumableArray(acc), [updatedOption]);
  }, []);
}
function collectParentIds(options, optionId) {
  var option = findById(options, optionId);
  if (!isRootOption(option.parentId)) {
    return [].concat(_toConsumableArray(collectParentIds(options, option.parentId)), [option.parentId]);
  }
  return [option.parentId];
}
export function useDropdownFlyout(_ref) {
  var flyoutOptions = _ref.flyoutOptions,
    _ref$onClick = _ref.onClick,
    _onClick = _ref$onClick === void 0 ? noop : _ref$onClick,
    _onKeyDown = _ref.onKeyDown;
  var _React$useReducer = React.useReducer(reducer, {
      options: flyoutOptions,
      expanded: [],
      highlighted: getFirst(flyoutOptions),
      isMouseOver: false,
      isFocused: false,
      isOpen: false
    }),
    _React$useReducer2 = _slicedToArray(_React$useReducer, 2),
    _React$useReducer2$ = _React$useReducer2[0],
    options = _React$useReducer2$.options,
    expanded = _React$useReducer2$.expanded,
    highlighted = _React$useReducer2$.highlighted,
    isOpen = _React$useReducer2$.isOpen,
    isMouseOver = _React$useReducer2$.isMouseOver,
    isFocused = _React$useReducer2$.isFocused,
    dispatch = _React$useReducer2[1];
  var setMouseOver = React.useCallback(function (isMouseOver) {
    return dispatch({
      type: 'setMouseOver',
      isMouseOver: isMouseOver
    });
  }, []);
  var setFocused = React.useCallback(function (isFocused) {
    return dispatch({
      type: 'setFocused',
      isFocused: isFocused
    });
  }, []);
  var isExpanded = function isExpanded(option) {
    return expanded.includes(option.id);
  };
  var isHighlighted = function isHighlighted(option) {
    var parentIds = collectParentIds(options, highlighted.id);
    var isCorrectId = option.id === highlighted.id || parentIds.some(function (id) {
      return id === option.id;
    });
    return (isMouseOver || isFocused) && isCorrectId;
  };
  var findOptionById = React.useCallback(function (id) {
    return findById(options, id);
  }, [options]);
  var expand = React.useCallback(function (option) {
    return dispatch({
      type: 'expand',
      option: option
    });
  }, []);
  var collapse = React.useCallback(function (option) {
    return dispatch({
      type: 'collapse',
      option: option
    });
  }, []);
  var highlight = React.useCallback(function (option) {
    return dispatch({
      type: 'highlight',
      option: option
    });
  }, []);
  var traversingHighlight = React.useCallback(function (item) {
    var tier = isRootOption(highlighted.parentId) ? options : findOptionById(highlighted.parentId).children || [];
    var optionIndex = tier.findIndex(function (item) {
      return item.id === highlighted.id;
    });
    switch (item) {
      case 'next':
        var nextIndex = optionIndex + 1 >= tier.length ? 0 : optionIndex + 1;
        highlight(tier[nextIndex]);
        break;
      case 'prev':
        var prevIndex = optionIndex - 1 < 0 ? tier.length - 1 : optionIndex - 1;
        highlight(tier[prevIndex]);
        break;
      case 'children':
        if (Array.isArray(highlighted.children)) {
          expand(highlighted);
          highlight(getFirst(highlighted.children));
        }
        break;
      case 'parent':
        if (!isRootOption(highlighted.parentId)) {
          var parentOption = findOptionById(highlighted.parentId);
          collapse(parentOption);
        }
        break;
      default:
        return;
    }
  }, [options, findOptionById, collapse, highlighted, expand, highlight]);
  var closeDropdown = React.useCallback(function () {
    dispatch({
      type: 'close'
    });
  }, []);
  var closeSelectedDropdown = React.useCallback(function (e) {
    if (e && e.type === 'click' && !e.composedPath().some(function (node) {
      var _dataset;
      return (_dataset = node.dataset) === null || _dataset === void 0 ? void 0 : _dataset.flyout;
    })) {
      dispatch({
        type: 'close'
      });
    }
  }, []);
  var openDropdown = React.useCallback(function () {
    dispatch({
      type: 'open'
    });
  }, []);
  var onClick = React.useCallback(function (option) {
    if (!hasChildren(option.origin)) {
      _onClick(option.origin);
      closeDropdown();
    }
  }, [_onClick, closeDropdown]);
  var onKeyDown = React.useCallback(function (e) {
    var key = e.key;
    switch (key) {
      case 'Enter':
        e.preventDefault();
        if (!isOpen && isFocused) {
          openDropdown();
        } else {
          if (hasChildren(highlighted.origin)) {
            traversingHighlight('children');
          } else {
            onClick(highlighted);
          }
        }
        break;
      case 'Escape':
      case 'Esc':
        e.preventDefault();
        if (isRootOption(highlighted.parentId)) {
          if (isOpen) {
            var _e$stopPropagation;
            (_e$stopPropagation = e.stopPropagation) === null || _e$stopPropagation === void 0 ? void 0 : _e$stopPropagation.call(e);
          }
          closeDropdown();
        } else {
          var _e$stopPropagation2;
          (_e$stopPropagation2 = e.stopPropagation) === null || _e$stopPropagation2 === void 0 ? void 0 : _e$stopPropagation2.call(e);
          traversingHighlight('parent');
        }
        break;
      case 'ArrowDown':
      case 'Down':
        e.preventDefault();
        traversingHighlight('next');
        break;
      case 'ArrowUp':
      case 'Up':
        e.preventDefault();
        traversingHighlight('prev');
        break;
    }
    _onKeyDown === null || _onKeyDown === void 0 ? void 0 : _onKeyDown(e);
  }, [closeDropdown, openDropdown, traversingHighlight, highlighted, isOpen, isFocused, onClick, _onKeyDown]);
  return {
    isFocused: isFocused,
    isMouseOver: isMouseOver,
    isOpen: isOpen,
    options: options,
    expanded: expanded,
    highlighted: highlighted,
    expand: expand,
    collapse: collapse,
    isHighlighted: isHighlighted,
    isExpanded: isExpanded,
    closeDropdown: closeDropdown,
    closeSelectedDropdown: closeSelectedDropdown,
    openDropdown: openDropdown,
    onKeyDown: onKeyDown,
    onClick: onClick,
    setMouseOver: setMouseOver,
    setFocused: setFocused
  };
}
export function defaultOptionRenderer(option) {
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(StyledDropdownFlyoutLabel, null, option.label), hasChildren(option) && /*#__PURE__*/React.createElement(StyledDropdownFlyoutExpandIcon, {
    "data-qa": "core-dropdown-flyout-option-expand-icon"
  }));
}
export var DropdownFlyoutContext = /*#__PURE__*/React.createContext({
  onClick: noop,
  expand: noop,
  collapse: noop,
  optionRenderer: defaultOptionRenderer,
  isExpanded: returnFalse,
  isHighlighted: returnFalse
});
export var useDropdownFlyoutContext = function useDropdownFlyoutContext() {
  return React.useContext(DropdownFlyoutContext);
};
//# sourceMappingURL=DropdownFlyout.helpers.js.map