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); }
var _excluded = ["autoFocus", "children", "className", "fieldClassName", "onBlur", "onChange", "options", "size", "defaultValue", "value", "inputRef", "inversed", "getA11yStatusMessage", "getA11ySelectionMessage"],
  _excluded2 = ["label", "value"],
  _excluded3 = ["label", "options"];
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); }
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 _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import React, { useCallback, useRef, useState } from "preact/compat";
import DropdownMenu from "./DropdownMenu";
import debounce from "../utilities/debounce";
import describeField from "../utilities/describeField";
import classNames from 'classnames';
import cleanFieldProps from "../utilities/cleanFieldProps";
import mergeRefs from "../utilities/mergeRefs";
import useClickOutsideHandler from "../utilities/useClickOutsideHandler";
import useId from "../utilities/useId";
import useAutofocus from "../utilities/useAutoFocus";
import { Label } from "../Label";
import { SvgIcon } from "../Icons";
import { getFirstOptionValue, isOptGroup, parseChildren, validateProps } from "./utils";
import { Item, Section, useSelectState } from "../react-aria"; // from react-stately
import { HiddenSelect, useButton, useSelect } from "../react-aria"; // from react-aria
import { useLabelProps } from "../Label/useLabelProps";
import { useHint } from "../Hint/useHint";
import { useInlineError } from "../InlineError/useInlineError";
var caretIcon = /*#__PURE__*/React.createElement(SvgIcon, {
  title: "",
  viewBox: "0 0 448 512",
  className: "ds-u-font-size--sm"
}, /*#__PURE__*/React.createElement("path", {
  d: "M212.7 148.7c6.2-6.2 16.4-6.2 22.6 0l160 160c6.2 6.2 6.2 16.4 0 22.6s-16.4 6.2-22.6 0L224 182.6 75.3 331.3c-6.2 6.2-16.4 6.2-22.6 0s-6.2-16.4 0-22.6l160-160z"
}));
/**
 * For information about how and when to use this component,
 * [refer to its full documentation page](https://design.cms.gov/components/dropdown/).
 */
export var Dropdown = function Dropdown(props) {
  validateProps(props);
  var id = useId('dropdown__button--', props.id);
  var buttonContentId = "".concat(id, "__button-content");
  var menuId = "".concat(id, "__menu");

  // Draw out certain props that we don't want to pass through as attributes
  var autoFocus = props.autoFocus,
    children = props.children,
    className = props.className,
    fieldClassName = props.fieldClassName,
    userOnBlur = props.onBlur,
    onChange = props.onChange,
    options = props.options,
    size = props.size,
    defaultValue = props.defaultValue,
    value = props.value,
    inputRef = props.inputRef,
    inversed = props.inversed,
    getA11yStatusMessage = props.getA11yStatusMessage,
    getA11ySelectionMessage = props.getA11ySelectionMessage,
    extraProps = _objectWithoutProperties(props, _excluded);
  var optionsAndGroups = options !== null && options !== void 0 ? options : parseChildren(children);
  var renderReactStatelyItem = function renderReactStatelyItem(item) {
    var label = item.label,
      value = item.value,
      extraAttrs = _objectWithoutProperties(item, _excluded2);
    return /*#__PURE__*/React.createElement(Item, _extends({}, extraAttrs, {
      key: value
    }), label);
  };
  var reactStatelyItems = optionsAndGroups.map(function (item, index) {
    if (isOptGroup(item)) {
      var label = item.label,
        _options = item.options,
        extraAttrs = _objectWithoutProperties(item, _excluded3);
      return /*#__PURE__*/React.createElement(Section, _extends({}, extraAttrs, {
        key: "group-".concat(index),
        title: label
      }), _options.map(renderReactStatelyItem));
    } else {
      return renderReactStatelyItem(item);
    }
  });
  var isControlled = value !== undefined;
  var fallbackValue = defaultValue;
  if (!isControlled && fallbackValue === undefined) {
    fallbackValue = getFirstOptionValue(optionsAndGroups);
  }
  var _useState = useState(fallbackValue),
    _useState2 = _slicedToArray(_useState, 2),
    internalValueState = _useState2[0],
    setInternalValueState = _useState2[1];
  var selectedKey = isControlled ? value : internalValueState;
  var onSelectionChange = function onSelectionChange(value) {
    var _triggerRef$current, _triggerRef$current$f;
    (_triggerRef$current = triggerRef.current) === null || _triggerRef$current === void 0 ? void 0 : (_triggerRef$current$f = _triggerRef$current.focus) === null || _triggerRef$current$f === void 0 ? void 0 : _triggerRef$current$f.call(_triggerRef$current);
    if (onChange) {
      // Try to support the old API that passed an event object
      var target = {
        value: value,
        name: props.name
      };
      onChange({
        target: target,
        currentTarget: target
      });
    }
    if (!isControlled) {
      setInternalValueState(value);
    }
  };
  var state = useSelectState(_objectSpread(_objectSpread({}, props), {}, {
    children: reactStatelyItems,
    selectedKey: selectedKey,
    onSelectionChange: onSelectionChange
  }));
  var _useInlineError = useInlineError(_objectSpread(_objectSpread({}, props), {}, {
      id: id
    })),
    errorId = _useInlineError.errorId,
    topError = _useInlineError.topError,
    bottomError = _useInlineError.bottomError,
    invalid = _useInlineError.invalid;
  var _useHint = useHint(_objectSpread(_objectSpread({}, props), {}, {
      id: id
    })),
    hintId = _useHint.hintId,
    hintElement = _useHint.hintElement;
  var onBlur = useCallback(
  // The active element is always the document body during a focus transition,
  // so in order to check if the newly focused element is one of our other date
  // inputs, we're going to have to wait a bit. We also have an issue with
  // tabbing out firing two blur events, so debounce during that time too. In
  // order for the debounce to work, we need to wrap this in a useCallback so
  // don't create a new one on each render.
  debounce(function (event) {
    var _wrapperRef$current;
    // Only call the user's onBlur handler if focus leaves the whole component
    if (!((_wrapperRef$current = wrapperRef.current) !== null && _wrapperRef$current !== void 0 && _wrapperRef$current.contains(document.activeElement))) {
      userOnBlur === null || userOnBlur === void 0 ? void 0 : userOnBlur(event);
      state.setOpen(false);
    }
  }, 20), [userOnBlur, state]);
  var triggerRef = useRef();
  var useSelectProps = useSelect(_objectSpread(_objectSpread({}, props), {}, {
    onBlur: onBlur,
    isDisabled: props.disabled
  }), state, triggerRef);
  var useButtonProps = useButton(useSelectProps.triggerProps, triggerRef);
  var labelProps = _objectSpread(_objectSpread(_objectSpread({}, useSelectProps.labelProps), useLabelProps(_objectSpread(_objectSpread({}, props), {}, {
    id: id
  }))), {}, {
    fieldId: id
  });
  var buttonProps = _objectSpread(_objectSpread(_objectSpread({}, useButtonProps.buttonProps), cleanFieldProps(extraProps)), {}, {
    id: id,
    name: undefined,
    className: classNames('ds-c-dropdown__button', 'ds-c-field', props.errorMessage && 'ds-c-field--error', inversed && 'ds-c-field--inverse', size && "ds-c-field--".concat(size), fieldClassName),
    ref: mergeRefs([triggerRef, inputRef, useAutofocus(props.autoFocus)]),
    'aria-controls': menuId,
    'aria-labelledby': "".concat(buttonContentId, " ").concat(labelProps.id),
    'aria-invalid': invalid,
    'aria-describedby': describeField(_objectSpread(_objectSpread({}, props), {}, {
      hintId: hintId,
      errorId: errorId
    }))
    // TODO: Someday we may want to add this `combobox` role back to the button, but right
    // now desktop VoiceOver has an issue. It seems to interpret the selected value in the
    // button as user input that needs to be checked for spelling (default setting). It
    // therefore announces anything it deems misspelled as such. The `react-aria` authors
    // likely ran into the same issue, since they leave it off for `useSelect` buttons.
    // Adding the combobox role in the future can help because screen reader users are more
    // familiar with the combobox pattern.
    // role: 'combobox',
  });

  var wrapperRef = useRef();
  useClickOutsideHandler([wrapperRef], function () {
    return state.setOpen(false);
  });
  return /*#__PURE__*/React.createElement("div", {
    className: classNames('ds-c-dropdown', className, state.isOpen && 'ds-c-dropdown--open'),
    ref: wrapperRef
  }, /*#__PURE__*/React.createElement(Label, labelProps), hintElement, topError, /*#__PURE__*/React.createElement(HiddenSelect, {
    isDisabled: props.disabled,
    state: state,
    triggerRef: triggerRef,
    label: props.label,
    name: props.name
  }), /*#__PURE__*/React.createElement("button", buttonProps, /*#__PURE__*/React.createElement("span", {
    id: buttonContentId,
    className: "ds-u-truncate"
  }, state.selectedItem ? state.selectedItem.rendered : ''), /*#__PURE__*/React.createElement("span", {
    className: "ds-c-dropdown__caret"
  }, caretIcon)), state.isOpen && /*#__PURE__*/React.createElement(DropdownMenu, _extends({}, useSelectProps.menuProps, {
    componentClass: "ds-c-dropdown",
    labelId: labelProps.id,
    menuId: menuId,
    rootId: id,
    size: size,
    state: state,
    triggerRef: triggerRef
  })), bottomError);
};
export default Dropdown;