"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.findNextSafeIndex = exports.default = void 0;
var _react = require("react");
var _constants = require("../../constants");
var _classnames = _interopRequireDefault(require("classnames"));
var _Popper = _interopRequireDefault(require("../Popper"));
var _Menu = _interopRequireWildcard(require("../Menu"));
var _AutoClosable = _interopRequireDefault(require("../AutoClosable"));
var _utils = require("../utils");
var _jsxRuntime = require("react/jsx-runtime");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (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; }
// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

const findNextSafeIndex = (currIndex, diff, options) => {
  const maxIndex = options.length - 1;
  let attempt = 0;
  for (let i = currIndex + diff; attempt < options.length; i += diff) {
    attempt += 1;
    if (i > maxIndex) {
      i = 0;
    } else if (i < 0) {
      i = maxIndex;
    }
    if (options[i] && options[i].disabled === false) {
      return i;
    }
  }
  return -1;
};
exports.findNextSafeIndex = findNextSafeIndex;
const ComboBoxDropdown = _ref => {
  let {
    baseClassName = `${_constants.CLS_PREFIX}combobox-dropdown`,
    className,
    control,
    controlRef,
    opened,
    disabled,
    groups,
    options,
    onHighlightedIndexChange,
    onClose,
    value,
    highlightedIndex,
    onSelect,
    noOptions,
    emitter,
    ...props
  } = _ref;
  const rootRef = (0, _react.useRef)(null);
  const menuRef = (0, _react.useRef)(null);
  const [minWidth, setMinWidth] = (0, _react.useState)(0);
  (0, _react.useLayoutEffect)(() => {
    if (opened && rootRef.current) {
      const {
        width
      } = rootRef.current.getBoundingClientRect();
      if (width !== minWidth) {
        setMinWidth(width);
      }
    }
  }, [opened, minWidth]);
  (0, _react.useEffect)(() => {
    if (!opened) {
      return undefined;
    }
    const listener = () => {
      (0, _utils.safeInvoke)(onClose);
    };
    window.addEventListener('resize', listener, {
      once: true
    });
    return () => window.removeEventListener('resize', listener);
  }, [opened, onClose]);
  (0, _react.useEffect)(() => {
    if (!emitter) {
      return;
    }
    emitter.on('focus', index => {
      if (menuRef.current) {
        const target = menuRef.current.querySelector(`[data-index="${index}"]`);
        if (target) {
          (0, _utils.scrollIntoView)(target, {
            behavior: 'instant',
            block: 'nearest',
            boundary: menuRef.current
          });
        }
      }
    });
  }, [emitter]);
  const target = /*#__PURE__*/(0, _jsxRuntime.jsx)(_AutoClosable.default, {
    onClose: () => {
      setTimeout(() => {
        (0, _utils.safeInvoke)(onClose);
      }, 0);
    },
    ignoreNodes: () => [menuRef.current],
    nodeRef: controlRef,
    children: control
  });
  return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
    className: className,
    ...props,
    ref: rootRef,
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Popper.default, {
      target: target,
      targetRef: controlRef,
      show: opened && !disabled,
      className: `${baseClassName}__popper`,
      zIndex: _constants.Z_INDEX_DROPDOWN,
      children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_Menu.default, {
        style: {
          minWidth
        },
        ref: menuRef,
        className: `${baseClassName}__menu`,
        children: [groups.reduce((acc, group) => {
          if (group.label) {
            acc.push( /*#__PURE__*/(0, _react.createElement)(_Menu.MenuHeader, {
              ...group.props,
              key: `group_${group.label}`
            }, group.label));
          }
          group.options.forEach(option => {
            const optionIndex = options.indexOf(option);
            let onClick;
            let onMouseOver;
            let onMouseDown;
            if (!option.disabled) {
              onClick = e => {
                e.preventDefault();
                (0, _utils.safeInvoke)(onSelect, option.value);
              };
              onMouseOver = () => {
                // TODO: use throttle
                (0, _utils.safeInvoke)(onHighlightedIndexChange, optionIndex);
              };
              onMouseDown = e => {
                e.preventDefault();
              };
            }
            const menuItemProps = {
              ...option.props,
              active: value === option.value,
              className: (0, _classnames.default)(`${baseClassName}__option`, {
                [`${baseClassName}__option--selected`]: optionIndex === highlightedIndex
              }),
              disabled: option.disabled,
              onClick,
              onMouseOver,
              onMouseDown,
              'data-index': optionIndex
            };
            acc.push( /*#__PURE__*/(0, _jsxRuntime.jsx)(_Menu.MenuItem, {
              ...menuItemProps,
              children: option.children
            }, `option_${option.value}`));
          });
          return acc;
        }, []), options.length === 0 && noOptions && /*#__PURE__*/(0, _jsxRuntime.jsx)(_Menu.MenuItem, {
          disabled: true,
          className: `${baseClassName}__no-options`,
          children: noOptions
        })]
      })
    })
  });
};
var _default = exports.default = ComboBoxDropdown;