"use strict";

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); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.Dropdown = void 0;
var _compat = _interopRequireWildcard(require("preact/compat"));
var _DropdownMenu = _interopRequireDefault(require("./DropdownMenu"));
var _debounce = _interopRequireDefault(require("../utilities/debounce"));
var _describeField = _interopRequireDefault(require("../utilities/describeField"));
var _classnames = _interopRequireDefault(require("classnames"));
var _cleanFieldProps = _interopRequireDefault(require("../utilities/cleanFieldProps"));
var _mergeRefs = _interopRequireDefault(require("../utilities/mergeRefs"));
var _useClickOutsideHandler = _interopRequireDefault(require("../utilities/useClickOutsideHandler"));
var _useId = _interopRequireDefault(require("../utilities/useId"));
var _useAutoFocus = _interopRequireDefault(require("../utilities/useAutoFocus"));
var _Label = require("../Label");
var _Icons = require("../Icons");
var _utils = require("./utils");
var _reactAria = require("../react-aria");
var _useLabelProps = require("../Label/useLabelProps");
var _useHint2 = require("../Hint/useHint");
var _useInlineError2 = require("../InlineError/useInlineError");
var _excluded = ["autoFocus", "children", "className", "fieldClassName", "onBlur", "onChange", "options", "size", "defaultValue", "value", "inputRef", "inversed", "getA11yStatusMessage", "getA11ySelectionMessage"],
  _excluded2 = ["label", "value"],
  _excluded3 = ["label", "options"]; // from react-stately
// from react-aria
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
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; }
var caretIcon = /*#__PURE__*/_compat.default.createElement(_Icons.SvgIcon, {
  title: "",
  viewBox: "0 0 448 512",
  className: "ds-u-font-size--sm"
}, /*#__PURE__*/_compat.default.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/).
 */
var Dropdown = function Dropdown(props) {
  (0, _utils.validateProps)(props);
  var id = (0, _useId.default)('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 : (0, _utils.parseChildren)(children);
  var renderReactStatelyItem = function renderReactStatelyItem(item) {
    var label = item.label,
      value = item.value,
      extraAttrs = _objectWithoutProperties(item, _excluded2);
    return /*#__PURE__*/_compat.default.createElement(_reactAria.Item, _extends({}, extraAttrs, {
      key: value
    }), label);
  };
  var reactStatelyItems = optionsAndGroups.map(function (item, index) {
    if ((0, _utils.isOptGroup)(item)) {
      var label = item.label,
        _options = item.options,
        extraAttrs = _objectWithoutProperties(item, _excluded3);
      return /*#__PURE__*/_compat.default.createElement(_reactAria.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 = (0, _utils.getFirstOptionValue)(optionsAndGroups);
  }
  var _useState = (0, _compat.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 = (0, _reactAria.useSelectState)(_objectSpread(_objectSpread({}, props), {}, {
    children: reactStatelyItems,
    selectedKey: selectedKey,
    onSelectionChange: onSelectionChange
  }));
  var _useInlineError = (0, _useInlineError2.useInlineError)(_objectSpread(_objectSpread({}, props), {}, {
      id: id
    })),
    errorId = _useInlineError.errorId,
    topError = _useInlineError.topError,
    bottomError = _useInlineError.bottomError,
    invalid = _useInlineError.invalid;
  var _useHint = (0, _useHint2.useHint)(_objectSpread(_objectSpread({}, props), {}, {
      id: id
    })),
    hintId = _useHint.hintId,
    hintElement = _useHint.hintElement;
  var onBlur = (0, _compat.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.
  (0, _debounce.default)(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 = (0, _compat.useRef)();
  var useSelectProps = (0, _reactAria.useSelect)(_objectSpread(_objectSpread({}, props), {}, {
    onBlur: onBlur,
    isDisabled: props.disabled
  }), state, triggerRef);
  var useButtonProps = (0, _reactAria.useButton)(useSelectProps.triggerProps, triggerRef);
  var labelProps = _objectSpread(_objectSpread(_objectSpread({}, useSelectProps.labelProps), (0, _useLabelProps.useLabelProps)(_objectSpread(_objectSpread({}, props), {}, {
    id: id
  }))), {}, {
    fieldId: id
  });
  var buttonProps = _objectSpread(_objectSpread(_objectSpread({}, useButtonProps.buttonProps), (0, _cleanFieldProps.default)(extraProps)), {}, {
    id: id,
    name: undefined,
    className: (0, _classnames.default)('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: (0, _mergeRefs.default)([triggerRef, inputRef, (0, _useAutoFocus.default)(props.autoFocus)]),
    'aria-controls': menuId,
    'aria-labelledby': "".concat(buttonContentId, " ").concat(labelProps.id),
    'aria-invalid': invalid,
    'aria-describedby': (0, _describeField.default)(_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 = (0, _compat.useRef)();
  (0, _useClickOutsideHandler.default)([wrapperRef], function () {
    return state.setOpen(false);
  });
  return /*#__PURE__*/_compat.default.createElement("div", {
    className: (0, _classnames.default)('ds-c-dropdown', className, state.isOpen && 'ds-c-dropdown--open'),
    ref: wrapperRef
  }, /*#__PURE__*/_compat.default.createElement(_Label.Label, labelProps), hintElement, topError, /*#__PURE__*/_compat.default.createElement(_reactAria.HiddenSelect, {
    isDisabled: props.disabled,
    state: state,
    triggerRef: triggerRef,
    label: props.label,
    name: props.name
  }), /*#__PURE__*/_compat.default.createElement("button", buttonProps, /*#__PURE__*/_compat.default.createElement("span", {
    id: buttonContentId,
    className: "ds-u-truncate"
  }, state.selectedItem ? state.selectedItem.rendered : ''), /*#__PURE__*/_compat.default.createElement("span", {
    className: "ds-c-dropdown__caret"
  }, caretIcon)), state.isOpen && /*#__PURE__*/_compat.default.createElement(_DropdownMenu.default, _extends({}, useSelectProps.menuProps, {
    componentClass: "ds-c-dropdown",
    labelId: labelProps.id,
    menuId: menuId,
    rootId: id,
    size: size,
    state: state,
    triggerRef: triggerRef
  })), bottomError);
};
exports.Dropdown = Dropdown;
var _default = Dropdown;
exports.default = _default;