"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getActiveDescendant = getActiveDescendant;
exports.getTextFieldChild = getTextFieldChild;
exports.removeUndefined = removeUndefined;
exports.renderReactStatelyItems = renderReactStatelyItems;
exports.renderStatusMessage = renderStatusMessage;
var _compat = require("preact/compat");
var _reactAria = require("../react-aria");
var _TextField = require("../TextField");
var _DropdownMenuOption = require("../Dropdown/DropdownMenuOption");
var _jsxRuntime = require("preact/compat/jsx-runtime");
// from react-stately

function renderReactStatelyItems(items, itemToString) {
  return items.map(item => {
    const {
      id,
      name,
      children,
      isResult,
      ...extraAttrs
    } = item;
    return /*#__PURE__*/(0, _compat.createElement)(_reactAria.Item, {
      ...extraAttrs,
      textValue: name ?? itemToString?.(item),
      key: id
    }, children ?? name);
  });
}
function renderStatusMessage(message) {
  return /*#__PURE__*/(0, _jsxRuntime.jsx)("li", {
    "aria-selected": "false",
    className: "ds-c-autocomplete__menu-item-message",
    role: "option",
    children: message
  });
}

/**
 * Determine if a React component is a TextField
 */
function isTextField(child) {
  if (!child || !(0, _compat.isValidElement)(child)) {
    return false;
  }

  // Check child.type first and as a fallback, check child.type.displayName follow by child.type.name
  const componentName = child.type?.displayName || child.type?.name;
  return child.type === _TextField.TextField || componentName === 'TextField';
}
function getTextFieldChild(children) {
  let textField;
  _compat.Children.forEach(children, child => {
    if (isTextField(child)) {
      textField = child;
    }
  });
  return textField;
}

/**
 * Assumes that it will find the item, so only use in cases where react-aria
 * would define an aria-activedescendent
 */
function getActiveDescendant(rootId, state, items) {
  const index = (items ?? []).findIndex(item => state.selectionManager.focusedKey === item.id);
  return (0, _DropdownMenuOption.getOptionId)(rootId, index);
}

/**
 * Mutates the original object, deleting properties whose values are undefined.
 * Returns the object.
 */
function removeUndefined(obj) {
  Object.keys(obj).forEach(key => obj[key] === undefined && delete obj[key]);
  return obj;
}