"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = AdaptiveList;
var _react = _interopRequireWildcard(require("react"));
var _resizeObserverPolyfill = _interopRequireDefault(require("resize-observer-polyfill"));
var _faEllipsisVertical = require("@fortawesome/free-solid-svg-icons/faEllipsisVertical");
var _dropdownMenu = require("../dropdown-menu");
var _adaptiveListUtils = require("./adaptive-list-utils");
var _useTranslation = require("../hooks/use-translation");
var _fontAwesomeIcon = require("../font-awesome-icon");
var _hooks = require("../hooks");
var _adaptiveListConstants = require("./adaptive-list-constants");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
/** Adaptive List
    @midnight-gray-supported
    @alpine-light-supported
 */
function AdaptiveList({
  options,
  Component,
  selected,
  onSelect = () => {},
  target = 'offsetWidth',
  triggerOffset = 44,
  dropdownMenuProps = {},
  truncatedView,
  triggerAriaLabelText,
  isSubNavItem = false,
  componentProps = {}
}) {
  const {
    t
  } = (0, _useTranslation.useTranslation)();
  const fontSize = (0, _hooks.useFontSizeObserver)();
  const [parentWidth, setParentWidth] = (0, _react.useState)(Infinity);
  const elements = (0, _react.useRef)({});
  const elementsWidth = (0, _react.useRef)({});
  const container = (0, _react.useRef)(null);
  const selectedArr = Array.isArray(selected) ? selected : [selected].filter(val => typeof val !== 'undefined');
  const [state, setState] = (0, _react.useState)(_adaptiveListConstants.DRAW_STATE.CALCULATING);
  (0, _react.useLayoutEffect)(() => {
    if (fontSize?.previousSize !== fontSize?.currentSize) {
      setState(_adaptiveListConstants.DRAW_STATE.CALCULATING);
    }
  }, [fontSize]);
  (0, _react.useLayoutEffect)(() => {
    setState(_adaptiveListConstants.DRAW_STATE.CALCULATING);
  }, [options]);
  (0, _react.useEffect)(() => {
    const outputWidth = () => {
      setParentWidth(container?.current?.[target] || 0);
    };
    if (container.current) {
      const observer = new _resizeObserverPolyfill.default(() => window.requestAnimationFrame(outputWidth));
      observer.observe(container.current);
      return () => observer.disconnect();
    }
  }, []);
  const {
    active,
    inActive
  } = (0, _react.useMemo)(() => (0, _adaptiveListUtils.sortOptions)({
    options,
    maxWidth: parentWidth,
    selected: selectedArr,
    optionsWidth: elementsWidth.current,
    startWidth: triggerOffset,
    state
  }), [options, parentWidth, selected, triggerOffset, state]);
  (0, _react.useLayoutEffect)(() => {
    if (state === _adaptiveListConstants.DRAW_STATE.CALCULATING) {
      elementsWidth.current = Object.keys(elements.current).reduce((acc, current) => ({
        ...acc,
        [current]: elements.current[current]?.[target] || 0
      }), {});
      setState(_adaptiveListConstants.DRAW_STATE.PAINTING);
    }
  }, [state]);
  (0, _react.useLayoutEffect)(() => {
    setParentWidth(container?.current?.[target] || 0);
  }, []);
  const isLimited = !!inActive.length;
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    ref: container,
    "test-id": "adaptive-list",
    className: "adaptive-list-container",
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: "adaptive-list",
      role: isSubNavItem ? 'tablist' : undefined,
      children: active.map(option => /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        ref: ref => {
          elements.current[option.key] = ref;
        },
        className: "adaptive-list-element",
        "test-id": "adaptive-list-element",
        role: isSubNavItem ? 'presentation' : undefined,
        children: Component({
          ...option,
          option,
          selected,
          onSelect,
          isLimited,
          ...componentProps
        })
      }, option.key))
    }), !!inActive.length && !truncatedView && !Array.isArray(selected) && /*#__PURE__*/(0, _jsxRuntime.jsx)(_dropdownMenu.DropdownMenu, {
      options: inActive,
      selectedKey: selected,
      onSelect: onSelect,
      triggerTestId: "adaptive-list-trigger",
      contentTestId: "adaptive-list-dropdown-content",
      triggerDynamicContent: () => /*#__PURE__*/(0, _jsxRuntime.jsx)(_fontAwesomeIcon.FontAwesomeIcon, {
        icon: _faEllipsisVertical.faEllipsisVertical
      }),
      triggerAriaLabelText: triggerAriaLabelText ?? t('Trigger another item'),
      triggerIsIcon: true,
      triggerHideChevron: true,
      ...dropdownMenuProps
    }), !!inActive.length && truncatedView && truncatedView({
      options: inActive,
      selected,
      onSelect,
      isLimited,
      ...componentProps
    })]
  });
}