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 _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 _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 _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 _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 _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 _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 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 { autoUpdate, flip, offset, size, useClick, useDismiss, useFloating, useInteractions, useListNavigation } from '@floating-ui/react';
import { useId } from '@react-aria/utils';
import debounce from 'lodash.debounce';
import uniq from 'lodash.uniq';
import React from 'react';
import { ulid } from 'ulid';
import { useI18nContext } from '../_hooks/I18n';
import { useZIndexContext } from '../_hooks/ZIndex';
import { spacing } from '../_styles/spacing';
import * as defaultComponents from './SuperSelect.components';
import { draggableOptionIdSymbol } from './SuperSelect.constants';
import { collectGroupsInOrderOfOccurrence, createOptgroup, getBatchOptionFormatter, getIsAllOptionsUngrouped, getOptionIsOptgroup, getOptionsSortingAlgorithm, isMultiple, removeEmptyOptGroups, reorder, sortOptgroups } from './SuperSelect.utils';
var listContainerVerticalPadding = spacing.sm * 2;
function noop() {}
function defaultGetOptionValue(option) {
  return option === null || option === void 0 ? void 0 : option.value;
}
function defaultGetOptionIsBatch(option) {
  return Array.isArray(option === null || option === void 0 ? void 0 : option.value);
}
function defaultGetOptionIsDisabled(option) {
  var _option$disabled;
  return (_option$disabled = option === null || option === void 0 ? void 0 : option.disabled) !== null && _option$disabled !== void 0 ? _option$disabled : false;
}
function defaultGetOptionGroup(option) {
  var _option$group;
  return (_option$group = option === null || option === void 0 ? void 0 : option.group) !== null && _option$group !== void 0 ? _option$group : '';
}
function defaultSetOptionGroup(option, group) {
  return _objectSpread(_objectSpread({}, option), {}, {
    group: group
  });
}
function defaultGetOptionLabel(option) {
  var _option$label;
  return (_option$label = option === null || option === void 0 ? void 0 : option.label) !== null && _option$label !== void 0 ? _option$label : '';
}
function stringContains(str1, str2) {
  return str1.toLowerCase().includes(str2.toLowerCase());
}
function useTokenNavigation(context) {
  var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
    _ref$enabled = _ref.enabled,
    enabled = _ref$enabled === void 0 ? true : _ref$enabled,
    _ref$value = _ref.value,
    value = _ref$value === void 0 ? [] : _ref$value,
    _ref$activeIndex = _ref.activeIndex,
    activeIndex = _ref$activeIndex === void 0 ? null : _ref$activeIndex,
    _ref$onNavigate = _ref.onNavigate,
    onNavigate = _ref$onNavigate === void 0 ? noop : _ref$onNavigate,
    _ref$onChange = _ref.onChange,
    onChange = _ref$onChange === void 0 ? noop : _ref$onChange;
  return {
    reference: {
      onKeyDown: function onKeyDown(e) {
        if (!enabled || !Array.isArray(value)) {
          return;
        }
        if (e.key === 'ArrowLeft') {
          if (activeIndex !== null) {
            onNavigate(Math.max(0, activeIndex - 1));
          } else if (value.length > 0) {
            onNavigate(value.length - 1);
          }
        } else if (e.key === 'ArrowRight') {
          if (activeIndex !== null) {
            if (activeIndex === value.length - 1) {
              onNavigate(null);
            } else {
              onNavigate(activeIndex + 1);
            }
          }
        } else if (e.key === 'Backspace') {
          if (!e.repeat) {
            if (activeIndex !== null) {
              var nextVal = value.filter(function (_, i) {
                return i !== activeIndex;
              });
              onChange(nextVal);
              if (activeIndex >= nextVal.length) {
                onNavigate(null);
              }
            } else if (value.length > 0) {
              onChange(value.filter(function (_, i) {
                return i !== value.length - 1;
              }));
            }
          }
        }
      }
    }
  };
}
function useKeyboardSelection(context) {
  var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
    _ref2$enabled = _ref2.enabled,
    enabled = _ref2$enabled === void 0 ? true : _ref2$enabled,
    _ref2$onSelect = _ref2.onSelect,
    onSelect = _ref2$onSelect === void 0 ? function () {} : _ref2$onSelect;
  function onKeyDown(e) {
    if (!enabled) {
      return;
    }
    if (e.key === 'Enter') {
      onSelect();
    }
  }
  return {
    reference: {
      onKeyDown: onKeyDown
    },
    floating: {
      onKeyDown: onKeyDown
    }
  };
}
export function useSuperSelect(_ref3) {
  var _ref3$block = _ref3.block,
    block = _ref3$block === void 0 ? false : _ref3$block,
    customComponents = _ref3.components,
    defaultValue = _ref3.defaultValue,
    _ref3$disabled = _ref3.disabled,
    disabled = _ref3$disabled === void 0 ? false : _ref3$disabled,
    _ref3$draggable = _ref3.draggable,
    draggable = _ref3$draggable === void 0 ? false : _ref3$draggable,
    _ref3$emptyMessage = _ref3.emptyMessage,
    emptyMessage = _ref3$emptyMessage === void 0 ? 'No results' : _ref3$emptyMessage,
    error = _ref3.error,
    footer = _ref3.footer,
    _ref3$getOptionGroup = _ref3.getOptionGroup,
    getOptionGroup = _ref3$getOptionGroup === void 0 ? defaultGetOptionGroup : _ref3$getOptionGroup,
    _ref3$getOptionIsBatc = _ref3.getOptionIsBatch,
    getOptionIsBatch = _ref3$getOptionIsBatc === void 0 ? defaultGetOptionIsBatch : _ref3$getOptionIsBatc,
    _ref3$getOptionIsDisa = _ref3.getOptionIsDisabled,
    getOptionIsDisabled = _ref3$getOptionIsDisa === void 0 ? defaultGetOptionIsDisabled : _ref3$getOptionIsDisa,
    _ref3$getOptionLabel = _ref3.getOptionLabel,
    getOptionLabel = _ref3$getOptionLabel === void 0 ? defaultGetOptionLabel : _ref3$getOptionLabel,
    _ref3$getOptionValue = _ref3.getOptionValue,
    getOptionValue = _ref3$getOptionValue === void 0 ? defaultGetOptionValue : _ref3$getOptionValue,
    _ref3$onScrollBottom = _ref3.onScrollBottom,
    onScrollBottom = _ref3$onScrollBottom === void 0 ? noop : _ref3$onScrollBottom,
    _ref3$onOpenChange = _ref3.onOpenChange,
    _onOpenChange = _ref3$onOpenChange === void 0 ? noop : _ref3$onOpenChange,
    header = _ref3.header,
    _ref3$loading = _ref3.loading,
    loading = _ref3$loading === void 0 ? false : _ref3$loading,
    _ref3$multiple = _ref3.multiple,
    multiple = _ref3$multiple === void 0 ? false : _ref3$multiple,
    onChange = _ref3.onChange,
    onManualSort = _ref3.onManualSort,
    _ref3$options = _ref3.options,
    sourceOptions = _ref3$options === void 0 ? [] : _ref3$options,
    placeholder = _ref3.placeholder,
    _ref3$preset = _ref3.preset,
    preset = _ref3$preset === void 0 ? '' : _ref3$preset,
    presetProps = _ref3.presetProps,
    _ref3$search = _ref3.search,
    search = _ref3$search === void 0 ? true : _ref3$search,
    _ref3$selectionStyle = _ref3.selectionStyle,
    selectionStyle = _ref3$selectionStyle === void 0 ? 'highlight' : _ref3$selectionStyle,
    _ref3$setOptionGroup = _ref3.setOptionGroup,
    setOptionGroup = _ref3$setOptionGroup === void 0 ? defaultSetOptionGroup : _ref3$setOptionGroup,
    _ref3$sort = _ref3.sort,
    sort = _ref3$sort === void 0 ? true : _ref3$sort,
    _ref3$tabIndex = _ref3.tabIndex,
    tabIndex = _ref3$tabIndex === void 0 ? 0 : _ref3$tabIndex,
    value_ = _ref3.value;
  React.useEffect(function () {
    if (!draggable) {
      return;
    }
    var isUsingDefaultGetter = getOptionGroup === defaultGetOptionGroup;
    var isUsingDefaultSetter = setOptionGroup === defaultSetOptionGroup;
    if (isUsingDefaultGetter && !isUsingDefaultSetter || !isUsingDefaultGetter && isUsingDefaultSetter) {
      console.warn("SuperSelect: Using potentially conflicting \"getOptionGroup\" and \"setOptionGroup\" implementations.\n        Group reassignment after drag-and-drop operation might be broken.");
    }
  }, [draggable, getOptionGroup, setOptionGroup]);
  var i18n = useI18nContext();
  var initialValue = defaultValue !== null && defaultValue !== void 0 ? defaultValue : multiple ? [] : null;
  var _React$useState = React.useState(initialValue),
    _React$useState2 = _slicedToArray(_React$useState, 2),
    val = _React$useState2[0],
    setVal = _React$useState2[1];
  var value = value_ !== undefined ? value_ : val;
  function setValue(v) {
    if (!value_) {
      setVal(v);
    }
    if (onChange) {
      onChange(v);
    }
  }
  var navigationList = React.useRef([]);
  var virtuoso = React.useRef(null);
  var searchRef = React.useRef(null);
  var overlayId = useId(); // TODO use React 18 useId
  var listId = useId(); // TODO use React 18 useId

  var _React$useState3 = React.useState(false),
    _React$useState4 = _slicedToArray(_React$useState3, 2),
    open = _React$useState4[0],
    setOpen = _React$useState4[1];
  var _React$useState5 = React.useState(false),
    _React$useState6 = _slicedToArray(_React$useState5, 2),
    pointer = _React$useState6[0],
    setPointer = _React$useState6[1];
  var _React$useState7 = React.useState(248),
    _React$useState8 = _slicedToArray(_React$useState7, 2),
    width = _React$useState8[0],
    setWidth = _React$useState8[1];
  var _React$useState9 = React.useState(248),
    _React$useState10 = _slicedToArray(_React$useState9, 2),
    maxHeight = _React$useState10[0],
    setMaxHeight = _React$useState10[1];
  var _React$useState11 = React.useState(0),
    _React$useState12 = _slicedToArray(_React$useState11, 2),
    listHeight = _React$useState12[0],
    setListHeight = _React$useState12[1];
  var _React$useState13 = React.useState(0),
    _React$useState14 = _slicedToArray(_React$useState13, 2),
    searchHeight = _React$useState14[0],
    setSearchHeight = _React$useState14[1];
  var _React$useState15 = React.useState(0),
    _React$useState16 = _slicedToArray(_React$useState15, 2),
    footerHeight = _React$useState16[0],
    setFooterHeight = _React$useState16[1];
  var listContainerHeight = Math.min(maxHeight - searchHeight - footerHeight + listContainerVerticalPadding, listHeight + listContainerVerticalPadding);
  var _React$useState17 = React.useState(''),
    _React$useState18 = _slicedToArray(_React$useState17, 2),
    searchValue = _React$useState18[0],
    setSearchValue_ = _React$useState18[1];
  var setSearchValue = debounce(setSearchValue_, 250); // TODO use React 18 useDeferredValue

  var _React$useState19 = React.useState(null),
    _React$useState20 = _slicedToArray(_React$useState19, 2),
    activeMenuIndex = _React$useState20[0],
    setActiveMenuIndex = _React$useState20[1];
  var _React$useState21 = React.useState(null),
    _React$useState22 = _slicedToArray(_React$useState21, 2),
    activeTokenIndex = _React$useState22[0],
    setActiveTokenIndex = _React$useState22[1];
  var components = _objectSpread(_objectSpread({}, defaultComponents), customComponents || {});

  // TODO #memogetters: consider having getOption... getter functions memoized by consumers
  // Until then, exclude these callbacks from effect and memo dependencies
  var sortOptions = React.useMemo(function () {
    return getOptionsSortingAlgorithm({
      getOptionIsBatch: getOptionIsBatch,
      getOptionLabel: getOptionLabel
    });
  },
  // skip `getOptionIsBatch` and `getOptionLabel`
  []);
  var formatBatchOption = React.useMemo(function () {
    return getBatchOptionFormatter({
      value: value,
      multiple: multiple,
      getOptionIsBatch: getOptionIsBatch,
      getOptionValue: getOptionValue
    });
  },
  // skip `getOptionIsBatch` and `getOptionValue`, refer to TODO #memogetters
  [value, multiple]);

  // collect groups, sort them and populate them with options, and sort the options inside the groups
  var enforceOptionsSortingOrder = React.useCallback(function groupAndSort(opts) {
    var _collectGroupsInOrder = collectGroupsInOrderOfOccurrence(opts, getOptionGroup),
      groups = _collectGroupsInOrder.groups,
      groupedOptions = _collectGroupsInOrder.groupedOptions;
    if (getIsAllOptionsUngrouped(groups)) {
      return opts.sort(sortOptions);
    }
    return Object.entries(groupedOptions).sort(function (_ref4, _ref5) {
      var _ref6 = _slicedToArray(_ref4, 1),
        groupA = _ref6[0];
      var _ref7 = _slicedToArray(_ref5, 1),
        groupB = _ref7[0];
      return sortOptgroups(groupA, groupB);
    }).flatMap(function (_ref8) {
      var _ref9 = _slicedToArray(_ref8, 2),
        groupName = _ref9[0],
        groupOptions = _ref9[1];
      return createOptgroup(groupName, groupOptions.sort(sortOptions));
    });
  },
  // skip `getOptionGroup`, refer to TODO #memogetters
  [sortOptions]);

  // collect groups and populate them with options
  var deriveOptionsSortingOrder = React.useCallback(function (opts) {
    var _collectGroupsInOrder2 = collectGroupsInOrderOfOccurrence(opts, getOptionGroup),
      groups = _collectGroupsInOrder2.groups,
      groupedOptions = _collectGroupsInOrder2.groupedOptions;
    if (getIsAllOptionsUngrouped(groups)) {
      return opts;
    }

    // display optgroups in the order of occurrence, as they are considered pre-sorted
    return groups.flatMap(function (group) {
      var groupOptions = groupedOptions[group];
      return createOptgroup(group, groupOptions);
    });
  },
  // skip `getOptionGroup`, refer to TODO #memogetters
  []);
  var groupAndSortAlgorithm = React.useMemo(function () {
    return sort ? enforceOptionsSortingOrder : deriveOptionsSortingOrder;
  }, [sort, enforceOptionsSortingOrder, deriveOptionsSortingOrder]);
  var options = React.useMemo(function () {
    var queried = searchValue ? sourceOptions.filter(function (opt) {
      return stringContains(getOptionLabel(opt), searchValue);
    }) : _toConsumableArray(sourceOptions); // make a copy of source options to prevent the mutation when sorting

    return groupAndSortAlgorithm(queried).map(formatBatchOption);
  },
  // skip `getOptionLabel`, refer to TODO #memogetters
  [groupAndSortAlgorithm, formatBatchOption, searchValue, sourceOptions]);
  var _React$useState23 = React.useState([]),
    _React$useState24 = _slicedToArray(_React$useState23, 2),
    draggableOptions = _React$useState24[0],
    setDraggableOptions = _React$useState24[1];
  React.useEffect(function () {
    if (!draggable) {
      return;
    }
    // make a copy of source options to prevent the mutation when sorting
    var opts = groupAndSortAlgorithm(sourceOptions.map(function (opt) {
      return _objectSpread(_objectSpread({}, opt), {}, _defineProperty({}, draggableOptionIdSymbol, ulid()));
    }));
    setDraggableOptions(opts);
  },
  // in draggable mode, sourceOptions must be memoized, othewise reorder will not work
  [draggable, sourceOptions, groupAndSortAlgorithm]);
  var queriedDraggableOptions = React.useMemo(function () {
    if (!draggable) {
      return [];
    }
    var queried = searchValue ? removeEmptyOptGroups(draggableOptions.filter(function (opt) {
      if (!getOptionIsOptgroup(opt)) {
        return stringContains(getOptionLabel(opt), searchValue);
      }
      return true;
    })) : draggableOptions;
    return queried.map(formatBatchOption);
  },
  // skip `getOptionLabel`, refer to TODO #memogetters
  [draggable, draggableOptions, searchValue, formatBatchOption]);
  var groupIndices = React.useMemo(function () {
    return options.reduce(function (acc, opt, i) {
      if (getOptionIsOptgroup(opt)) {
        acc.push(i);
      }
      return acc;
    }, []);
  }, [options]);
  var selectedIndex = React.useMemo(function () {
    return options.findIndex(function (option) {
      return isSelectableOption(option) && getOptionValue(option) === value;
    });
  }, [options, value]);
  var selectedOption = React.useMemo(function () {
    var val = Array.isArray(value) ? value[0] : value;
    return options.find(function (option) {
      return getOptionValue(option) === val;
    });
  }, [options, value]);
  var selectedLabel = React.useMemo(function () {
    return selectedOption ? getOptionLabel(selectedOption) : '';
  }, [selectedOption]);
  function isSelectableOption(o) {
    return !getOptionIsOptgroup(o) && !getOptionIsDisabled(o);
  }
  function getFirstSelectableOptionIndex() {
    return options.findIndex(isSelectableOption);
  }
  function onSelect(option) {
    if (getOptionIsDisabled(option)) {
      return;
    }
    var optionValue = getOptionValue(option);
    if (isMultiple(multiple, value)) {
      if (Array.isArray(optionValue)) {
        setValue(uniq([].concat(_toConsumableArray(value), _toConsumableArray(optionValue))));
      } else {
        setValue(value.includes(optionValue) ? value.filter(function (val) {
          return val !== optionValue;
        }) : [].concat(_toConsumableArray(value), [optionValue]));
      }
    } else {
      setValue(optionValue);
    }
  }
  function onKeyboardSelect() {
    if (activeMenuIndex !== null) {
      var option = options[activeMenuIndex];
      if (option) {
        onSelect(option);
      }
    }
  }
  function getOptionIsSelected(option) {
    return Array.isArray(value) ? value.includes(getOptionValue(option)) : value === getOptionValue(option);
  }
  function isEmpty() {
    return Array.isArray(value) ? value.length === 0 : value === null;
  }
  var boundWidthRef = React.useRef(open);
  React.useEffect(function () {
    boundWidthRef.current = open;
  }, [open]);
  var floating = useFloating({
    open: open,
    onOpenChange: function onOpenChange(open) {
      setOpen(open);
      _onOpenChange(open);
    },
    whileElementsMounted: autoUpdate,
    strategy: 'fixed',
    middleware: [offset(2), flip(), size({
      apply: function apply(_ref10) {
        var availableHeight = _ref10.availableHeight,
          elements = _ref10.elements;
        if (boundWidthRef.current) {
          boundWidthRef.current = false;
          setWidth(elements.reference.getBoundingClientRect().width);
        }
        setMaxHeight(availableHeight);
      },
      padding: 10
    })]
  });
  var _useZIndexContext = useZIndexContext(),
    zIndex = _useZIndexContext.value;
  var _useInteractions = useInteractions([useClick(floating.context, {
      enabled: !disabled,
      keyboardHandlers: false
    }), useDismiss(floating.context, {
      enabled: !disabled
    }), useListNavigation(floating.context, {
      activeIndex: activeMenuIndex,
      disabledIndices: groupIndices,
      enabled: !disabled,
      listRef: navigationList,
      loop: true,
      onNavigate: function onNavigate(i) {
        return setActiveMenuIndex(function () {
          return i;
        });
      },
      selectedIndex: selectedIndex,
      virtual: true
    }), useTokenNavigation(floating.context, {
      activeIndex: activeTokenIndex,
      enabled: !disabled && multiple && searchValue === '',
      onChange: setValue,
      onNavigate: function onNavigate(i) {
        return setActiveTokenIndex(function () {
          return i;
        });
      },
      value: value
    }), useKeyboardSelection(floating.context, {
      enabled: !disabled,
      onSelect: onKeyboardSelect
    }), {
      reference: {
        $block: block,
        $disabled: disabled,
        $error: error,
        $hasClearIcon: !disabled && !loading,
        $loading: loading,
        $multiple: multiple,
        $open: open,
        $placeholder: !selectedLabel,
        'aria-controls': search ? overlayId : listId,
        'aria-expanded': open,
        'aria-haspopup': search ? 'dialog' : 'listbox',
        onKeyDown: function onKeyDown() {
          setPointer(false);
        },
        role: 'combobox',
        search: search,
        tabIndex: disabled ? -1 : tabIndex
      },
      // TODO fix type
      floating: {
        role: search ? 'dialog' : 'none',
        id: overlayId,
        onKeyDown: function onKeyDown() {
          setPointer(false);
        },
        onPointerMove: function onPointerMove() {
          setPointer(true);
        },
        style: {
          position: floating.strategy,
          left: floating.x || 0,
          top: floating.y || 0,
          width: width,
          maxHeight: maxHeight,
          zIndex: zIndex
        }
      }
    }]),
    getReferenceProps = _useInteractions.getReferenceProps,
    getFloatingProps = _useInteractions.getFloatingProps,
    getItemProps = _useInteractions.getItemProps;
  function getLabelProps() {
    return {
      $hoverable: false
    };
  }
  function getMultiInputProps() {
    return {
      ref: searchRef,
      placeholder: isEmpty() ? placeholder : '',
      disabled: disabled,
      'aria-controls': listId,
      onKeyDown: function onKeyDown(e) {
        if (e.key === 'Tab') {
          if (open) {
            var _floating$refs$floati;
            e.preventDefault();
            e.stopPropagation();
            (_floating$refs$floati = floating.refs.floating.current) === null || _floating$refs$floati === void 0 ? void 0 : _floating$refs$floati.focus();
          }
        }
      },
      onChange: function onChange(e) {
        setSearchValue(e.currentTarget.value);
        setActiveTokenIndex(null);
      },
      style: {
        opacity: activeTokenIndex === null ? 1 : 0
      }
    };
  }
  function getMultiValueProps(index) {
    return {
      onClick: function onClick(e) {
        // prevent the menu from closing
        e.stopPropagation();
        if (isMultiple(multiple, value)) {
          setValue(value.filter(function (_, i) {
            return i !== index;
          }));
        }
      }
    };
  }
  function getSearchContainerProps() {
    return {
      ref: function ref(el) {
        var _el$clientHeight;
        setSearchHeight((_el$clientHeight = el === null || el === void 0 ? void 0 : el.clientHeight) !== null && _el$clientHeight !== void 0 ? _el$clientHeight : 0);
      }
    };
  }
  function getSearchProps() {
    return {
      'aria-controls': listId,
      onChange: function onChange(value) {
        setSearchValue(value);
        setActiveTokenIndex(null);
      },
      placeholder: i18n.t('core.select.search')
    };
  }
  function getHeaderProps() {
    return {
      ref: function ref(el) {}
    };
  }
  function getFooterProps() {
    return {
      ref: function ref(el) {
        var _el$clientHeight2;
        setFooterHeight((_el$clientHeight2 = el === null || el === void 0 ? void 0 : el.clientHeight) !== null && _el$clientHeight2 !== void 0 ? _el$clientHeight2 : 0);
      },
      onKeyDown: function onKeyDown(e) {
        if (e.key !== 'Escape') {
          e.stopPropagation();
        }
      }
    };
  }
  function getEmptyMessageProps() {
    return {
      emptyMessage: emptyMessage
    };
  }
  function getClearProps() {
    return {
      'aria-hidden': true,
      'aria-label': i18n.t('core.select.clear'),
      onClick: function onClick(e) {
        // prevent the menu from closing
        e.stopPropagation();
        setActiveTokenIndex(null);
        setValue(multiple ? [] : null);
        setOpen(true);
      }
    };
  }
  function getMenuProps() {
    return {
      scrollable: false,
      style: {
        height: listContainerHeight
      }
    };
  }
  function getVirtuosoProps() {
    var atBottomStateChange = function atBottomStateChange(atBottom) {
      if (atBottom) {
        onScrollBottom();
      }
    };
    return {
      role: 'listbox',
      id: overlayId,
      data: draggable ? queriedDraggableOptions : options,
      components: {
        Item: components === null || components === void 0 ? void 0 : components.Item // TODO fix type
      },

      initialTopMostItemIndex: selectedIndex >= 0 ? selectedIndex : 0,
      style: {
        flex: '1 1 auto'
      },
      tabIndex: -1,
      totalListHeightChanged: setListHeight,
      atBottomStateChange: atBottomStateChange
    };
  }
  var onDragEnd = React.useCallback(function (result) {
    if (!result.destination) {
      return;
    }
    if (result.source.index === result.destination.index) {
      return;
    }
    var startIndex = result.source.index;
    var destinationIndex = result.destination.index;
    setDraggableOptions(function (options) {
      var _reorder = reorder(options, startIndex, destinationIndex),
        nextOptions = _reorder.nextOptions,
        prevGroup = _reorder.prevGroup,
        nextGroup = _reorder.nextGroup;
      var adjustedOptions = prevGroup !== nextGroup ? nextOptions.map(function (option, index) {
        if (index === destinationIndex) {
          return setOptionGroup(option, nextGroup);
        }
        return option;
      }) : nextOptions;
      if (typeof onManualSort === 'function') {
        setTimeout(function () {
          onManualSort(adjustedOptions.filter(function (option) {
            return !getOptionIsOptgroup(option);
          }));
        }, 0);
      }
      return adjustedOptions;
    });
  }, []);

  // run effect when the `open` state changes
  //
  // if it was closed and is now open, reset the highlighted index to be
  // the first selectable option
  //
  // if it was open and is now closed, reset the search value and focused token index
  React.useEffect(function () {
    if (open) {
      setActiveMenuIndex(function () {
        return selectedIndex >= 0 ? selectedIndex : getFirstSelectableOptionIndex();
      });
    } else {
      setSearchValue(function () {
        return '';
      });
      setActiveTokenIndex(function () {
        return null;
      });
    }
  }, [open]);

  // run the effect when user enters a serach value
  //
  // if the select is currently open then reset highlighted item to be the first
  // selectable option
  React.useEffect(function () {
    if (open) {
      setActiveMenuIndex(function () {
        return getFirstSelectableOptionIndex();
      });
    }
  }, [searchValue]);

  // when we change the value then close the overlay, but only if we have
  // actually selected a value
  //
  // multiple mode forces the overlay to stay open
  React.useEffect(function () {
    if (!multiple && value !== null) {
      setOpen(function () {
        return false;
      });
    }
  }, [value]);

  // recreate the array to hold dom refs when our options change
  React.useEffect(function () {
    navigationList.current = _toConsumableArray(Array(options.length).fill(null));
  }, [options]);

  // scroll virtuoso list activeMenuIndex into view when the index changes
  React.useLayoutEffect(function () {
    if (activeMenuIndex !== null) {
      if (!pointer) {
        var _virtuoso$current;
        (_virtuoso$current = virtuoso.current) === null || _virtuoso$current === void 0 ? void 0 : _virtuoso$current.scrollIntoView({
          index: activeMenuIndex
        });
      }
    }
  }, [activeMenuIndex, open]);
  return {
    config: {
      block: block,
      disabled: disabled,
      draggable: draggable,
      emptyMessage: emptyMessage,
      error: error,
      footer: footer,
      header: header,
      placeholder: placeholder,
      preset: preset,
      presetProps: presetProps,
      selectionStyle: selectionStyle,
      tabIndex: tabIndex,
      loading: loading,
      multiple: multiple
    },
    components: components,
    state: {
      activeMenuIndex: activeMenuIndex,
      activeTokenIndex: activeTokenIndex,
      isEmpty: isEmpty,
      listContainerHeight: listContainerHeight,
      listId: listId,
      maxHeight: maxHeight,
      onDragEnd: onDragEnd,
      onSelect: onSelect,
      open: open,
      options: draggable ? queriedDraggableOptions : options,
      overlayId: overlayId,
      searchValue: searchValue,
      selectedIndex: selectedIndex,
      selectedLabel: selectedLabel,
      selectedOption: selectedOption,
      setOpen: setOpen,
      setPointer: setPointer,
      setSearchValue: setSearchValue,
      sourceOptions: sourceOptions,
      value: value,
      width: width
    },
    props: {
      clear: getClearProps,
      emptyMessage: getEmptyMessageProps,
      footer: getFooterProps,
      header: getHeaderProps,
      item: getItemProps,
      label: getLabelProps,
      menu: getMenuProps,
      multiInput: getMultiInputProps,
      overlay: getFloatingProps,
      search: getSearchProps,
      searchContainer: getSearchContainerProps,
      tokenClear: getMultiValueProps,
      trigger: getReferenceProps,
      virtuoso: getVirtuosoProps
    },
    option: {
      group: getOptionGroup,
      isBatch: getOptionIsBatch,
      isSelected: getOptionIsSelected,
      isDisabled: getOptionIsDisabled,
      isOptgroup: getOptionIsOptgroup,
      label: getOptionLabel,
      value: getOptionValue
    },
    refs: {
      floating: floating,
      navigationList: navigationList,
      virtuoso: virtuoso
    }
  };
}
export var SuperSelectContext = /*#__PURE__*/React.createContext(null);
export function useSuperSelectContext() {
  var ctx = React.useContext(SuperSelectContext);
  if (!ctx) {
    throw new Error('Invalid SuperSelectContext');
  }
  return ctx;
}
//# sourceMappingURL=useSuperSelect.js.map