"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _react = _interopRequireWildcard(require("react"));
var _TagListSt = require("./TagList.st.css.js");
var _Tag = _interopRequireDefault(require("../Tag"));
var _Tooltip = _interopRequireDefault(require("../Tooltip"));
var _TagListAction = _interopRequireDefault(require("./TagListAction"));
var _ToggleMoreButton = _interopRequireDefault(require("./ToggleMoreButton"));
var _TagList = require("./TagList.constants");
var _useResponsiveTagsLayout = require("./hooks/useResponsiveTagsLayout");
var _useId = require("../utils/useId");
var _excluded = ["className"];
var _jsxFileName = "/home/builduser/work/57e038ea7326c1ec/packages/wix-design-system/dist/cjs/TagList/TagList.tsx";
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(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 (var _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); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var buttonSize = {
  small: 'tiny',
  medium: 'small',
  large: 'medium'
};
var defaultOverflowTooltipContent = hiddenTags => hiddenTags.map((tag, i) => /*#__PURE__*/_react.default.createElement(_react.default.Fragment, {
  key: tag.id,
  __self: void 0,
  __source: {
    fileName: _jsxFileName,
    lineNumber: 26,
    columnNumber: 5
  }
}, i > 0 && ', ', tag.children));
var TagList = _ref => {
  var {
    dataHook,
    tags,
    actionButton,
    size = 'small',
    onTagRemove,
    maxVisibleTags = 3,
    toggleMoreButton,
    initiallyExpanded = false,
    overflowMode
  } = _ref;
  var overflowConfig = overflowMode === 'collapse' ? {
    type: 'collapse'
  } : typeof overflowMode === 'object' && overflowMode !== null ? overflowMode : undefined;
  var isCollapseOverflow = (overflowConfig == null ? void 0 : overflowConfig.type) === 'collapse';
  var renderTag = overflowConfig == null ? void 0 : overflowConfig.renderTag;
  var overflowTooltipContent = overflowConfig == null ? void 0 : overflowConfig.overflowTooltipContent;
  var [isExpanded, setIsExpanded] = (0, _react.useState)(initiallyExpanded);
  var closeButtonRefs = (0, _react.useRef)(new Map());
  var pendingFocusRef = (0, _react.useRef)(null);
  var containerRef = (0, _react.useRef)(null);
  var measureRef = (0, _react.useRef)(null);
  var trailingRef = (0, _react.useRef)(null);
  var overflowTooltipId = (0, _useId.useId)('tag-list-overflow-tooltip-');
  var staticVisibleTags = isExpanded ? tags : tags.slice(0, maxVisibleTags);
  var {
    visibleTags,
    hiddenTags,
    lastTruncatedWidth,
    lastTruncatedNaturalWidth
  } = (0, _useResponsiveTagsLayout.useResponsiveTagsLayout)({
    containerRef,
    measureRef,
    trailingRef: actionButton ? trailingRef : undefined,
    tags: isCollapseOverflow ? tags : staticVisibleTags,
    enabled: isCollapseOverflow
  });
  var actionButtonSize = buttonSize[size];
  var cleanupStaleRefs = (0, _react.useCallback)(() => {
    var currentTagIds = new Set(visibleTags.map(tag => tag.id));
    var refsToDelete = [];
    closeButtonRefs.current.forEach((_, tagId) => {
      if (!currentTagIds.has(tagId)) {
        refsToDelete.push(tagId);
      }
    });
    refsToDelete.forEach(tagId => closeButtonRefs.current.delete(tagId));
  }, [visibleTags]);
  (0, _react.useEffect)(() => {
    cleanupStaleRefs();
    if (pendingFocusRef.current) {
      var closeButtonToFocus = closeButtonRefs.current.get(pendingFocusRef.current);
      if (closeButtonToFocus) {
        closeButtonToFocus.focus();
      }
      pendingFocusRef.current = null;
    }
  }, [visibleTags, cleanupStaleRefs]);
  var handleTagRemove = (0, _react.useCallback)(tagId => {
    var currentIndex = visibleTags.findIndex(tag => tag.id === tagId);
    if (currentIndex !== -1) {
      var nextFocusIndex;
      if (currentIndex < visibleTags.length - 1) {
        nextFocusIndex = currentIndex + 1;
      } else if (currentIndex > 0) {
        nextFocusIndex = currentIndex - 1;
      } else {
        nextFocusIndex = -1;
      }
      if (nextFocusIndex !== -1) {
        var nextTag = visibleTags[nextFocusIndex];
        if (nextTag) {
          pendingFocusRef.current = nextTag.id;
        }
      }
    }
    onTagRemove == null || onTagRemove(tagId);
  }, [visibleTags, onTagRemove]);
  var setCloseButtonRef = (0, _react.useCallback)((tagId, element) => {
    if (element) {
      closeButtonRefs.current.set(tagId, element);
    } else {
      closeButtonRefs.current.delete(tagId);
    }
  }, []);
  var toggleExpanded = (0, _react.useCallback)(() => {
    setIsExpanded(previous => !previous);
  }, []);
  var renderTagWrapper = (0, _react.useCallback)((tag, _ref2, truncatedBracket) => {
    var {
      index,
      maxWidth
    } = _ref2;
    var {
        className
      } = tag,
      rest = (0, _objectWithoutProperties2.default)(tag, _excluded);
    // Fully-wired props shared by both render paths: the default `<Tag>`
    // and the consumer's `renderTag` (via `args.tagProps`), so a custom
    // tag keeps removal, focus, sizing and truncation.
    var tagProps = _objectSpread(_objectSpread({}, rest), {}, {
      className: truncatedBracket ? (0, _TagListSt.st)(_TagListSt.classes.truncatedTagFill, className) : className,
      size,
      onRemove: handleTagRemove,
      closeButtonRef: el => setCloseButtonRef(tag.id, el),
      maxWidth: maxWidth !== null && maxWidth !== void 0 ? maxWidth : tag.maxWidth
    });
    return /*#__PURE__*/_react.default.createElement("div", {
      key: tag.id,
      className: (0, _TagListSt.st)(_TagListSt.classes.item, truncatedBracket ? _TagListSt.classes.truncatedItem : undefined),
      style: truncatedBracket ? {
        minWidth: "".concat(truncatedBracket.min, "px"),
        maxWidth: "".concat(truncatedBracket.max, "px")
      } : undefined,
      __self: void 0,
      __source: {
        fileName: _jsxFileName,
        lineNumber: 166,
        columnNumber: 9
      }
    }, isCollapseOverflow && renderTag ? renderTag(tag, {
      index,
      maxWidth,
      tagProps
    }) : /*#__PURE__*/_react.default.createElement(_Tag.default, (0, _extends2.default)({}, tagProps, {
      __self: void 0,
      __source: {
        fileName: _jsxFileName,
        lineNumber: 184,
        columnNumber: 13
      }
    })));
  }, [handleTagRemove, isCollapseOverflow, renderTag, setCloseButtonRef, size]);
  var renderToggleMoreButton = () => {
    if (isCollapseOverflow) return null;
    var amountOfHiddenTags = tags.length - maxVisibleTags;
    if (!toggleMoreButton || amountOfHiddenTags <= 0) return null;
    return /*#__PURE__*/_react.default.createElement(_ToggleMoreButton.default, {
      size: actionButtonSize,
      toggleMoreButton: toggleMoreButton,
      amountOfHiddenTags: amountOfHiddenTags,
      isExpanded: isExpanded,
      dataHook: _TagList.DATA_HOOKS.toggleMoreButton,
      onClick: toggleExpanded,
      __self: void 0,
      __source: {
        fileName: _jsxFileName,
        lineNumber: 197,
        columnNumber: 7
      }
    });
  };
  var renderOverflowChip = () => {
    if (!isCollapseOverflow || hiddenTags.length === 0) return null;
    var hiddenCount = hiddenTags.length;
    var content = overflowTooltipContent ? overflowTooltipContent(hiddenTags) : defaultOverflowTooltipContent(hiddenTags);
    return /*#__PURE__*/_react.default.createElement("div", {
      className: _TagListSt.classes.item,
      __self: void 0,
      __source: {
        fileName: _jsxFileName,
        lineNumber: 215,
        columnNumber: 7
      }
    }, /*#__PURE__*/_react.default.createElement(_Tooltip.default, {
      content: content,
      appendTo: "window",
      "aria-describedby": overflowTooltipId,
      __self: void 0,
      __source: {
        fileName: _jsxFileName,
        lineNumber: 216,
        columnNumber: 9
      }
    }, /*#__PURE__*/_react.default.createElement("span", {
      tabIndex: 0,
      "data-hook": _TagList.DATA_HOOKS.overflowChip,
      className: _TagListSt.classes.overflowChipTrigger,
      __self: void 0,
      __source: {
        fileName: _jsxFileName,
        lineNumber: 221,
        columnNumber: 11
      }
    }, /*#__PURE__*/_react.default.createElement(_Tag.default, {
      id: _TagList.OVERFLOW_CHIP_ID,
      size: size,
      removable: false,
      __self: void 0,
      __source: {
        fileName: _jsxFileName,
        lineNumber: 226,
        columnNumber: 13
      }
    }, "+", hiddenCount))));
  };
  var renderMeasureLayer = () => {
    if (!isCollapseOverflow) return null;
    return /*#__PURE__*/_react.default.createElement("div", {
      ref: measureRef,
      className: _TagListSt.classes.measureLayer,
      "data-hook": _TagList.DATA_HOOKS.measureLayer,
      "aria-hidden": true,
      __self: void 0,
      __source: {
        fileName: _jsxFileName,
        lineNumber: 238,
        columnNumber: 7
      }
    }, tags.map((tag, index) => {
      var measureTag = _objectSpread(_objectSpread({}, tag), {}, {
        id: "".concat(tag.id, "-measure")
      });
      return /*#__PURE__*/_react.default.createElement("span", {
        key: measureTag.id,
        __self: void 0,
        __source: {
          fileName: _jsxFileName,
          lineNumber: 247,
          columnNumber: 13
        }
      }, renderTag ? renderTag(measureTag, {
        index,
        maxWidth: undefined,
        tagProps: _objectSpread(_objectSpread({}, measureTag), {}, {
          size
        })
      }) : /*#__PURE__*/_react.default.createElement(_Tag.default, (0, _extends2.default)({}, measureTag, {
        size: size,
        className: measureTag.className,
        __self: void 0,
        __source: {
          fileName: _jsxFileName,
          lineNumber: 255,
          columnNumber: 17
        }
      })));
    }), /*#__PURE__*/_react.default.createElement(_Tag.default, {
      id: "tag-list-overflow-measure",
      size: size,
      removable: false,
      __self: void 0,
      __source: {
        fileName: _jsxFileName,
        lineNumber: 264,
        columnNumber: 9
      }
    }, "+", '9'.repeat(String(tags.length).length)));
  };
  return /*#__PURE__*/_react.default.createElement("div", {
    ref: containerRef,
    className: (0, _TagListSt.st)(_TagListSt.classes.root, {
      collapseOverflow: isCollapseOverflow
    }),
    "data-hook": dataHook,
    __self: void 0,
    __source: {
      fileName: _jsxFileName,
      lineNumber: 272,
      columnNumber: 5
    }
  }, renderMeasureLayer(), visibleTags.map((tag, index) => {
    var isLastTruncated = lastTruncatedWidth !== null && index === visibleTags.length - 1;
    var maxWidth = isLastTruncated ? "".concat(lastTruncatedWidth, "px") : undefined;
    var truncatedBracket = isLastTruncated && lastTruncatedNaturalWidth !== null ? {
      // CSS min-width beats max-width, so cap min at natural —
      // else the wrapper stretches past the tag's content.
      min: Math.min(lastTruncatedWidth, lastTruncatedNaturalWidth),
      max: lastTruncatedNaturalWidth
    } : undefined;
    return renderTagWrapper(tag, {
      index,
      maxWidth
    }, truncatedBracket);
  }), renderToggleMoreButton(), renderOverflowChip(), actionButton && /*#__PURE__*/_react.default.createElement("span", {
    ref: trailingRef,
    className: _TagListSt.classes.item,
    __self: void 0,
    __source: {
      fileName: _jsxFileName,
      lineNumber: 301,
      columnNumber: 9
    }
  }, /*#__PURE__*/_react.default.createElement(_TagListAction.default, {
    dataHook: _TagList.DATA_HOOKS.actionButton,
    size: actionButtonSize,
    onClick: actionButton.onClick,
    __self: void 0,
    __source: {
      fileName: _jsxFileName,
      lineNumber: 302,
      columnNumber: 11
    }
  }, actionButton.label)));
};
TagList.displayName = 'TagList';
var _default = exports.default = TagList;
//# sourceMappingURL=TagList.js.map