function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _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(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _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(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
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
      });
    case 'updateOptions':
      return _objectSpread(_objectSpread({}, state), {}, {
        options: action.options
      });
    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.type === 'mouseup') && !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]);
  // There was an issue that was fixed in scope of UISP-215 https://procoretech.atlassian.net/browse/UISP-215
  // UseEffect is necessary for updating state in UseReducer because props don't automatically update state. (In this case: property "options")
  React.useEffect(function () {
    dispatch({
      type: 'updateOptions',
      options: flyoutOptions
    });
    dispatch({
      type: 'highlight',
      option: getFirst(flyoutOptions)
    });
  }, [flyoutOptions]);
  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