"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useSyncPropsWithMachine = exports.usePropagateChangesThroughOnChange = exports.useOnBlurAndOnFocus = exports.useMultiRef = exports.useIsFirstRender = exports.useFocusFromMachine = exports.useDelegateKeyDownToMachine = exports.useBatchedSend = exports.useAutofocus = void 0;
var _react = require("react");
var _scrollIntoViewIfNeeded = _interopRequireDefault(require("scroll-into-view-if-needed"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
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 useAutofocus = exports.useAutofocus = function useAutofocus(ref, enable) {
  (0, _react.useEffect)(function () {
    if (enable && ref && ref.current) ref.current.focus();
  }, [enable, ref]);
};
var useFocusFromMachine = exports.useFocusFromMachine = function useFocusFromMachine(machineState, buttonRef, itemRefs, searchRef, preventScroll) {
  var isInButtonFocusState = machineState.matches('interaction.enabled.active.focus.button');
  (0, _react.useEffect)(function () {
    if (machineState.matches('interaction.enabled.active.focus.listItem') && machineState.matches({
      open: 'on'
    })) {
      if (searchRef.current) {
        searchRef.current.focus({
          preventScroll: true
        });
        if (machineState.context.itemFocusIdx !== null && itemRefs[machineState.context.itemFocusIdx] && !preventScroll) {
          (0, _scrollIntoViewIfNeeded.default)(itemRefs[machineState.context.itemFocusIdx], {
            behavior: 'auto',
            block: 'center',
            inline: 'center'
          });
        }
      }
    } else if (isInButtonFocusState) {
      if (buttonRef.current) buttonRef.current.focus({
        preventScroll: true
      });
    }
  }, [machineState.context.itemFocusIdx, isInButtonFocusState]);
};
var useIsFirstRender = exports.useIsFirstRender = function useIsFirstRender() {
  var isFirstRender = (0, _react.useRef)(true);
  (0, _react.useEffect)(function () {
    isFirstRender.current = false;
  }, []);
  return isFirstRender.current;
};
var useBatchedSend = exports.useBatchedSend = function useBatchedSend(send) {
  var accumulatedArrowActions = (0, _react.useRef)([]);
  var currentTimeoutId = (0, _react.useRef)(null);
  return (0, _react.useCallback)(function (actionTypes) {
    var _accumulatedArrowActi;
    (_accumulatedArrowActi = accumulatedArrowActions.current).push.apply(_accumulatedArrowActi, _toConsumableArray(actionTypes));
    if (currentTimeoutId.current) clearTimeout(currentTimeoutId.current);
    currentTimeoutId.current = setTimeout(function () {
      currentTimeoutId.current = null;
      var actions = _toConsumableArray(accumulatedArrowActions.current);
      accumulatedArrowActions.current = [];
      send(actions);
    }, 0);
  }, [send]);
};
var useSyncPropsWithMachine = exports.useSyncPropsWithMachine = function useSyncPropsWithMachine(propsToSync, deps) {
  var send = deps[0];
  (0, _react.useEffect)(function () {
    send({
      type: 'SYNC',
      payload: propsToSync
    });
  }, deps);
};
var useMultiRef = exports.useMultiRef = function useMultiRef() {
  var itemRefs = (0, _react.useMemo)(function () {
    return [];
  }, []);
  var setItemRef = (0, _react.useCallback)(function (index) {
    return function (ref) {
      if (ref) itemRefs[index] = ref;
    };
  }, []);
  return [itemRefs, setItemRef];
};
var useDelegateKeyDownToMachine = exports.useDelegateKeyDownToMachine = function useDelegateKeyDownToMachine(send, selectOnSpace) {
  var sendBatched = useBatchedSend(send);
  var SPACE = ' ';
  var keyActionMap = new Map([['ArrowDown', 'FOCUS_NEXT_ITEM'], ['ArrowUp', 'FOCUS_PREV_ITEM'], ['Escape', 'TOGGLE'], ['Enter', 'SELECT_FOCUSED_ITEM'], ['Tab', '']]);
  if (selectOnSpace) {
    keyActionMap.set(SPACE, 'SELECT_FOCUSED_ITEM');
  }
  return function (e) {
    if (keyActionMap.has(e.key)) {
      sendBatched(['KEY_PRESS', keyActionMap.get(e.key)]);
      e.preventDefault();
      return false;
    }
    sendBatched(['KEY_PRESS']);
    return undefined;
  };
};
var usePropagateChangesThroughOnChange = exports.usePropagateChangesThroughOnChange = function usePropagateChangesThroughOnChange(machineState, send, onChange, isFirstRender) {
  var isChangeUncommitted = machineState.matches('selection.controlled.changeUncommitted') || machineState.matches('selection.uncontrolled.changeUncommitted');
  (0, _react.useEffect)(function () {
    if (isFirstRender) return;
    if (isChangeUncommitted) {
      var changes = machineState.context.uncommittedSelectedItems;
      var action = changes.find(function (x) {
        return typeof x.onSelect === 'function';
      });
      if (action) {
        action.onSelect();
        send(['CHANGE_COMMIT_ABORT', 'CLOSE']);
        return;
      }
      if (onChange) onChange(changes);
      send('CHANGE_COMMIT');
    }
  }, [isChangeUncommitted, onChange]);
};
var useOnBlurAndOnFocus = exports.useOnBlurAndOnFocus = function useOnBlurAndOnFocus(machineState, send, onBlur, onFocus, formFieldRef, isFirstRender, selectRef, listRef) {
  var isPassive = machineState.matches('interaction.enabled.idle');
  (0, _react.useEffect)(function () {
    if (!isFirstRender && isPassive && onBlur) onBlur({
      target: selectRef.current
    });
  }, [isPassive]);
  var isActive = machineState.matches('interaction.enabled.active');
  (0, _react.useEffect)(function () {
    if (isActive && onFocus) onFocus({
      target: selectRef.current
    });
  }, [isActive]);
  var handleFocus = (0, _react.useCallback)(function (_) {
    send('FOCUS');
  }, [send]);
  var handleBlur = (0, _react.useCallback)(function (_) {
    setTimeout(function () {
      var _listRef$current;
      if (formFieldRef.current && !formFieldRef.current.contains(document.activeElement) && !((_listRef$current = listRef.current) !== null && _listRef$current !== void 0 && _listRef$current.contains(document.activeElement))) {
        send('BLUR');
      }
    }, 1);
  }, [send, formFieldRef, listRef]);
  return {
    handleFocus: handleFocus,
    handleBlur: handleBlur
  };
};