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); }
var _excluded = ["items", "title", "size", "getInitials", "getImageUrl"];
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 _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; }
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 _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); }
import { Building, People } from '@procore/core-icons';
import { useId } from '@react-aria/utils';
import React, { forwardRef, useMemo, useState } from 'react';
import { Avatar } from '../Avatar/Avatar';
import { Button } from '../Button/Button';
import { ContactItem } from '../ContactItem/ContactItem';
import { Link } from '../Link/Link';
import { Modal } from '../Modal/Modal';
import { Popover } from '../Popover/Popover';
import { Typography } from '../Typography/Typography';
import { useI18nContext } from '../_hooks/I18n';
import { colorsOrder, foldedItemsCap, restCountThreshold, visibleItemsCap } from './AvatarStack.constants';
import { StyledAvatar, StyledContactItem, StyledContactItems, StyledModalBody, StyledViewAllWrapper, StyledWrapper } from './AvatarStack.styles';
var defaultPopoverTrigger = ['hover', 'focus'];
export function getOverflowValues(items) {
  var foldedItems = [];
  var restCountLabel = null;
  var isViewAllNeeded = false;
  var visibleItems = items.length > visibleItemsCap ? items.slice(0, visibleItemsCap - 1) : items;
  var restItemsCount = items.length - visibleItems.length;
  if (restItemsCount > 0) {
    foldedItems = items.slice(visibleItems.length, visibleItems.length + foldedItemsCap);
    restCountLabel = restItemsCount > restCountThreshold ? "".concat(restCountThreshold, "+") : "+".concat(restItemsCount);
    isViewAllNeeded = restItemsCount > foldedItemsCap;
  }
  return {
    visibleItems: visibleItems,
    foldedItems: foldedItems,
    restCountLabel: restCountLabel,
    isViewAllNeeded: isViewAllNeeded
  };
}
export function getIcon(type, size) {
  switch (type) {
    case 'company':
      return /*#__PURE__*/React.createElement(Building, {
        size: size
      });
    case 'group':
      return /*#__PURE__*/React.createElement(People, {
        size: size
      });
    case 'user':
    default:
      return null;
  }
}
function getContactIcon(type) {
  return getIcon(type, 'md');
}
export function getAvatarIcon(type, size) {
  var avatarSize = size === 'lg' ? 'md' : 'sm';
  return getIcon(type, avatarSize);
}
export function getColorOrder(avatarItems) {
  return avatarItems.reduce(function (_ref, item) {
    var map = _ref.map,
      color = _ref.color;
    if (item.imageUrl) {
      return {
        map: map,
        color: color
      };
    }
    if (item.inactive) {
      map.set(item.id, 'gray70');
      return {
        map: map,
        color: color
      };
    }
    map.set(item.id, color);
    var currentColorIndex = colorsOrder.indexOf(color);
    var nextColorIndex = (currentColorIndex + 1) % colorsOrder.length;
    return {
      map: map,
      color: item.imageUrl ? color : colorsOrder[nextColorIndex]
    };
  }, {
    map: new Map(),
    color: colorsOrder[0]
  }).map;
}
export function AvatarStackContactItem(_ref2) {
  var id = _ref2.id,
    type = _ref2.type,
    imageUrl = _ref2.imageUrl,
    initials = _ref2.initials,
    inactive = _ref2.inactive,
    name = _ref2.name,
    linkUrl = _ref2.linkUrl,
    description = _ref2.description;
  return /*#__PURE__*/React.createElement(StyledContactItem, {
    key: id,
    imageUrl: imageUrl,
    initials: initials,
    icon: getContactIcon(type),
    disabled: inactive
  }, /*#__PURE__*/React.createElement(ContactItem.Title, null, !inactive && linkUrl ? /*#__PURE__*/React.createElement(Link, {
    href: linkUrl
  }, name) : name), /*#__PURE__*/React.createElement(ContactItem.Description, null, type === 'group' ? /*#__PURE__*/React.createElement(Typography, {
    color: "gray15"
  }, description) : description));
}
export function AvatarContent(_ref3) {
  var imageUrl = _ref3.imageUrl,
    initials = _ref3.initials,
    type = _ref3.type,
    size = _ref3.size;
  var avatarIcon = getAvatarIcon(type, size);
  if (imageUrl) {
    return /*#__PURE__*/React.createElement(Avatar.Portrait, {
      imageUrl: imageUrl
    });
  }
  if (avatarIcon) {
    return /*#__PURE__*/React.createElement(Avatar.Icon, {
      icon: avatarIcon
    });
  }
  if (initials) {
    return /*#__PURE__*/React.createElement(Avatar.Label, null, initials);
  }
  return null;
}
function AvatarWithPopover(_ref4) {
  var item = _ref4.item,
    size = _ref4.size,
    colors = _ref4.colors;
  var hasEnabledLink = item.linkUrl && !item.inactive;
  var avatarProps = hasEnabledLink ? {
    role: 'link',
    href: item.linkUrl
  } : {
    role: 'img',
    // Allow SR to open Popover as it cycles through. Keeps visual with audio.
    // The link or image is labelled, and focus does not enter the Popover.
    tabIndex: -1
  };
  return /*#__PURE__*/React.createElement(Popover, {
    key: item.id,
    trigger: defaultPopoverTrigger,
    overlay: /*#__PURE__*/React.createElement(Popover.Content, null, /*#__PURE__*/React.createElement(AvatarStackContactItem, {
      id: item.id,
      type: item.type,
      imageUrl: item.imageUrl,
      initials: item.initials,
      inactive: item.inactive,
      name: item.name,
      linkUrl: item.linkUrl,
      description: item.description
    }))
  }, /*#__PURE__*/React.createElement(StyledAvatar, _extends({}, avatarProps, {
    "aria-label": "".concat(item.name, ", ").concat(item.description),
    disabled: item.inactive,
    size: size,
    $color: colors.get(item.id)
  }), /*#__PURE__*/React.createElement(AvatarContent, {
    imageUrl: item.imageUrl,
    initials: item.initials,
    type: item.type,
    size: size
  })));
}
export function FoldedAvatarStack(_ref5) {
  var items = _ref5.items,
    onClickViewAll = _ref5.onClickViewAll,
    size = _ref5.size,
    restCountLabel = _ref5.restCountLabel,
    isViewAllNeeded = _ref5.isViewAllNeeded,
    title = _ref5.title;
  var I18n = useI18nContext();
  var overlayRef = React.useRef(null);
  var restAvatarId = useId();
  return /*#__PURE__*/React.createElement(Popover, {
    trigger: defaultPopoverTrigger,
    "aria-labelledby": restAvatarId,
    overlayRef: overlayRef,
    beforeHide: function beforeHide(e) {
      return e.type !== 'blur';
    },
    overlay: /*#__PURE__*/React.createElement(Popover.Content, null, /*#__PURE__*/React.createElement(StyledContactItems, null, items.map(function (item) {
      return /*#__PURE__*/React.createElement(AvatarStackContactItem, {
        key: item.id,
        id: item.id,
        type: item.type,
        imageUrl: item.imageUrl,
        initials: item.initials,
        inactive: item.inactive,
        name: item.name,
        linkUrl: item.linkUrl,
        description: item.description
      });
    })), isViewAllNeeded && /*#__PURE__*/React.createElement(StyledViewAllWrapper, null, /*#__PURE__*/React.createElement(Button, {
      "data-qa": "core-avatar-stack-view-all-modal-trigger",
      onClick: onClickViewAll,
      size: "sm",
      variant: "secondary"
    }, I18n.t('core.avatarStack.viewAll'))))
  }, /*#__PURE__*/React.createElement(StyledAvatar, {
    role: "button",
    onPress: onClickViewAll,
    id: restAvatarId,
    "aria-label": "".concat(restCountLabel, ", ").concat(title),
    "data-qa": "core-avatar-stack-folded-avatars-popover-trigger",
    size: size,
    $color: "gray85"
  }, /*#__PURE__*/React.createElement(Avatar.Label, {
    "aria-hidden": true
  }, /*#__PURE__*/React.createElement(Typography, {
    color: "black"
  }, restCountLabel))));
}
export function ViewAllModal(_ref6) {
  var isOpen = _ref6.isOpen,
    onClose = _ref6.onClose,
    title = _ref6.title,
    items = _ref6.items;
  var I18n = useI18nContext();
  var labelId = useId();
  return /*#__PURE__*/React.createElement(Modal, {
    role: "dialog",
    "aria-labelledby": labelId,
    open: isOpen,
    onClose: onClose
  }, /*#__PURE__*/React.createElement(Modal.Header, {
    onClose: onClose
  }, /*#__PURE__*/React.createElement("span", {
    id: labelId
  }, title, " (", items.length, ")")), /*#__PURE__*/React.createElement(StyledModalBody, null, items.map(function (item) {
    return /*#__PURE__*/React.createElement(AvatarStackContactItem, {
      key: item.id,
      id: item.id,
      type: item.type,
      imageUrl: item.imageUrl,
      initials: item.initials,
      inactive: item.inactive,
      name: item.name,
      linkUrl: item.linkUrl,
      description: item.description
    });
  })), /*#__PURE__*/React.createElement(Modal.Footer, null, /*#__PURE__*/React.createElement(Modal.FooterButtons, null, /*#__PURE__*/React.createElement(Button, {
    onClick: onClose
  }, I18n.t('core.avatarStack.close')))));
}
export function defaultInitials(item) {
  return item.initials;
}
export function defaultGetImageUrl(item) {
  return item.imageUrl;
}
export function getTransformedItems(_ref7) {
  var items = _ref7.items,
    getInitials = _ref7.getInitials,
    getImageUrl = _ref7.getImageUrl;
  return items.map(function (item) {
    return _objectSpread(_objectSpread({}, item), {}, {
      initials: getInitials(item),
      imageUrl: getImageUrl(item)
    });
  });
}
var _AvatarStack = function _AvatarStack(_ref8, ref) {
  var _items = _ref8.items,
    title = _ref8.title,
    _ref8$size = _ref8.size,
    size = _ref8$size === void 0 ? 'lg' : _ref8$size,
    _ref8$getInitials = _ref8.getInitials,
    getInitials = _ref8$getInitials === void 0 ? defaultInitials : _ref8$getInitials,
    _ref8$getImageUrl = _ref8.getImageUrl,
    getImageUrl = _ref8$getImageUrl === void 0 ? defaultGetImageUrl : _ref8$getImageUrl,
    props = _objectWithoutProperties(_ref8, _excluded);
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isModalOpen = _useState2[0],
    setIsModalOpen = _useState2[1];
  var items = useMemo(function () {
    return getTransformedItems({
      items: _items,
      getInitials: getInitials,
      getImageUrl: getImageUrl
    });
  }, [_items]);
  var _useMemo = useMemo(function () {
      return getOverflowValues(items);
    }, [items]),
    visibleItems = _useMemo.visibleItems,
    foldedItems = _useMemo.foldedItems,
    restCountLabel = _useMemo.restCountLabel,
    isViewAllNeeded = _useMemo.isViewAllNeeded;
  var visibleItemsColors = useMemo(function () {
    return getColorOrder(visibleItems);
  }, [visibleItems]);
  return /*#__PURE__*/React.createElement("div", _extends({
    ref: ref
  }, props), isViewAllNeeded && /*#__PURE__*/React.createElement(ViewAllModal, {
    isOpen: isModalOpen,
    onClose: function onClose() {
      return setIsModalOpen(false);
    },
    title: title,
    items: items
  }), /*#__PURE__*/React.createElement(StyledWrapper, null, visibleItems.map(function (item) {
    return /*#__PURE__*/React.createElement(AvatarWithPopover, {
      colors: visibleItemsColors,
      item: item,
      key: "".concat(item.name, "_").concat(item.id),
      size: size
    });
  }), foldedItems.length > 0 && /*#__PURE__*/React.createElement(FoldedAvatarStack, {
    restCountLabel: restCountLabel,
    isViewAllNeeded: isViewAllNeeded,
    items: foldedItems,
    onClickViewAll: function onClickViewAll() {
      return setIsModalOpen(true);
    },
    size: size,
    title: title
  })));
};

/**

 We use avatars to visually represent our users, places, and things in the app.
 These can be in the form of rich media or representative illustrations.

 @since 10.19.0

 @see [Storybook](https://procore.github.io/core/latest/?path=/story/demos-avatarstack--demo)

 @see [Design Guidelines](https://design.procore.com/avatar-stack)
 */
export var AvatarStack = /*#__PURE__*/forwardRef(_AvatarStack);

// @ts-ignore
AvatarStack.displayName = 'AvatarStack';
//# sourceMappingURL=AvatarStack.js.map