{"version":3,"file":"Avatar.mjs","sources":["../../../src/components/Avatar/Avatar.tsx"],"sourcesContent":["import clsx from 'clsx';\n\nimport React from 'react';\nimport { type IconOrContent, type UserData } from '../../util/utility-types';\nimport type { Preset, Size } from '../../util/variant-types';\nimport { hasSlotContent, IconSlot } from '../Icon';\nimport Text from '../Text';\nimport styles from './Avatar.module.css';\n\ntype AvatarProps = {\n  // Component API\n  /**\n   * Label for the given avatar. Defaults to a string using user data.\n   */\n  ariaLabel?: string;\n  /**\n   * CSS class names that can be appended to the component.\n   */\n  className?: string;\n  /**\n   * The URL to an image resource (loaded lazily)\n   */\n  src?: string;\n  /**\n   * CSS properties defined for the HTML element. Includes the component's CSS Custom Properties:\n   *\n   * - `--avatar__bg`\n   * - `--avatar__border`\n   * - `--avatar__fg`\n   */\n  style?: AvatarCSSProperties;\n  /**\n   * The user associated with this avatar\n   *\n   * `UserData` takes the format (`[]` key-values are optional):\n   *\n   * ```\n   * - fullName (string)\n   * - [id] (string | number)\n   * - [displayName] (string)\n   * - [key:string] (string | number | boolean)\n   * ```\n   */\n  user?: UserData;\n  // Design API\n  /**\n   * Set the behavior of the avatar, based on the specified user data.\n   *\n   * - `default` selects a color from a set, using the user data as a \"key\"\n   * - `fixed` selects a static color that does not change based on the user data\n   *\n   * **Default is `\"default\"`**.\n   */\n  color?: 'default' | 'fixed';\n  /**\n   * Content for the `\"icon\"` variant of the avatar. Takes an EDS icon name, or any content\n   * to render in its place, sized to match `size`. Default is \"person\"\n   */\n  icon?: IconOrContent;\n  /**\n   * Marking whether the Avatar is intended to be interactive (have focus/hover states)\n   */\n  isInteractive?: boolean;\n  /**\n   * The size of the avatar\n   */\n  size?: Extract<Size, 'sm' | 'md' | 'lg' | 'xl'>;\n  /**\n   * Variants of how the avatar will be portrayed\n   */\n  variant?: 'icon' | 'text' | 'image';\n};\n\nexport interface AvatarCSSProperties extends React.CSSProperties {\n  /**\n   * Custom property to customize the background color of this component (e.g., background color)\n   */\n  '--avatar__bg'?: string;\n\n  /**\n   * Custom property to customize the border color of this component\n   */\n  '--avatar__border'?: string;\n\n  /**\n   * Custom property to customize the foreground color of this component (e.g., text, icon, etc.)\n   */\n  '--avatar__fg'?: string;\n}\n\nconst NUM_COLORS = 6; // this count should match the zero-indexed color schemes in the CSS Module\n\nlet graphemeSegmenter: Intl.Segmenter | undefined;\n\n/**\n * Use Intl.Segmenter to take a name part, and select the first grapheme (emoji, surrogate pair, ASCII character)\n */\nfunction produceAbbreviation(fromName: string): string {\n  graphemeSegmenter ??= new Intl.Segmenter(undefined, {\n    granularity: 'grapheme',\n  });\n  const [first] = graphemeSegmenter.segment(fromName);\n  return first?.segment ?? '?';\n}\n\n/**\n * Use the user's name to determine a pseudo-random color scheme/style in their avatar.\n *\n * @param fromName string representing a user's name, or some other string\n * @returns offset used to determine a \"random\" color for the user's avatar\n */\nfunction calculateColorOffset(fromName: string): number {\n  return (\n    fromName\n      .split('') // chop into individal characters\n      .filter((c) => c !== '') // strip out any spaces\n      .map((character) => character.codePointAt(0)) // convert to numbered code-points (accounting for UTF-16)\n      .filter((cp) => cp !== undefined) // remove any undefined codepoints\n      .reduce((charNumber, accumulator) => charNumber + accumulator, 0) %\n    NUM_COLORS // accumulate the values, starting with zero\n  );\n}\n\nexport function getInitials(fromName: string): string {\n  /**\n   * Scenarios:\n   * - User's name is spelled as first and last name: John Smith => JS\n   * - User's name has a middle name or initial: John C. Smith => JS\n   * - User's Name has dashes in it: Kelly Davis-Johnson => KD\n   */\n  const initials = fromName\n    .split(' ')\n    .filter((part) => part !== '')\n    .map(produceAbbreviation)\n    .reduce(\n      (prev, curr, idx, arr) =>\n        idx === 0 || idx === arr.length - 1 ? prev + curr : prev,\n      '',\n    )\n    .toUpperCase();\n  return initials;\n}\n\n/**\n * ## Usage\n *\n * Avatars represent a single user in the system. The representation can be generated (using a color derived from the\n * user data), or include an image for each user. `Avatar` supports text, images, and multi-byte characters (e.g., emoji),\n * and can reference flexible metadata for the associated user.\n *\n * | Type/Use | Description | Example |\n * |----------|-------------|---------|\n * | Text | Initials generated from `user.fullName`, or a `displayName` you supply directly. | Comment authors. Member lists. Emoji stand-ins. |\n * | Image | A profile photo loaded from `src`, falling back to text when no source is set. | Account menus. Profile pages. |\n * | Icon | A named EDS icon instead of user-specific content. | Unidentified users. \"Add a person\" affordances. |\n *\n * ### Best Practices\n *\n * * Use avatars in places where we want to show a user as identified and logged in.\n * * Avatars can be used in place of regular `Button`s for triggers in certain components (e.g., `Menu`, `Tooltip`).\n *\n * ## Interaction\n *\n * Avatars support focus rings and can exist in the tab order when used as a trigger. Set `isInteractive` to get focus\n * and hover states.\n *\n * `Avatar` instances in a collection can overlap by 50% for efficient use of space. A hover state on the container\n * holding multiple instances can then remove the overlap and show every `Avatar` in full.\n *\n * ## Content & Accessibility\n *\n * ### Do's\n *\n * * Use `Avatar` to represent users in `AppHeader` when logged in.\n * * Use the large size `Avatar` when the component is shown in the main page area. For menus and navigation, use a smaller `Avatar`.\n *\n * ### Don'ts\n *\n * * Avoid relying on the icon or text as the only indication of which user is being represented. Use adjacent text, or `aria-*` tags for screen-reader support.\n * * Avoid using very large image files for user profiles in `Avatar`. Save a specific, low-resolution file for user avatar images.\n *\n * ## Resources\n *\n * * https://github.com/flmnt/graphemer\n */\nexport const Avatar = React.forwardRef<HTMLDivElement, AvatarProps>(\n  (\n    {\n      ariaLabel,\n      className,\n      color = 'default',\n      icon = 'person',\n      isInteractive,\n      size = 'md',\n      user,\n      variant = 'text',\n      src,\n      ...other\n    }: AvatarProps,\n    ref,\n  ) => {\n    const componentClassName = clsx(\n      styles['avatar'],\n      isInteractive && styles['avatar--is-interactive'],\n      size && styles[`avatar--${size}`],\n      variant && styles[`avatar--${variant}`],\n      color === 'default' &&\n        styles[\n          `avatar--color-scheme-${calculateColorOffset(user?.fullName || 'unknown')}`\n        ],\n      className,\n    );\n\n    const descriptiveLabel =\n      ariaLabel ??\n      `Avatar for ${user ? '' : 'unknown '}user ${user?.fullName || ''}`;\n\n    // use the display name if prop is provided. Otherwise, try to calculate initials\n    let avatarDisplayName = user ? getInitials(user.fullName) : '??';\n\n    if (user?.displayName) {\n      avatarDisplayName = user.displayName;\n    }\n\n    // trim text to one character when size=sm\n    if (size === 'sm') {\n      avatarDisplayName = produceAbbreviation(avatarDisplayName);\n    }\n\n    const presetMap: Record<NonNullable<AvatarProps['size']>, Preset> = {\n      sm: 'label-sm',\n      md: 'label-sm',\n      lg: 'label-lg',\n      xl: 'label-xl',\n    };\n\n    const iconSizeMap: Record<NonNullable<AvatarProps['size']>, number> = {\n      sm: 16,\n      md: 24,\n      lg: 32,\n      xl: 40,\n    };\n\n    return (\n      <div\n        aria-label={descriptiveLabel}\n        className={componentClassName}\n        role=\"img\"\n        {...other}\n      >\n        {variant === 'text' && (\n          <Text as=\"span\" preset={presetMap[size]}>\n            {avatarDisplayName}\n          </Text>\n        )}\n        {variant === 'icon' && hasSlotContent(icon) && (\n          <IconSlot\n            content={icon}\n            purpose=\"decorative\"\n            size={`${iconSizeMap[size]}px`}\n          />\n        )}\n        {variant === 'image' && src && (\n          <img alt=\"user\" className={styles['avatar__image']} src={src} />\n        )}\n        {variant === 'image' && !src && (\n          <Text as=\"span\" preset={presetMap[size]}>\n            {avatarDisplayName}\n          </Text>\n        )}\n      </div>\n    );\n  },\n);\n\nAvatar.displayName = 'Avatar';\n"],"names":["React"],"mappings":";;;;;;;;AA0FA,MAAM,UAAU,GAAG,CAAC,CAAC;AAErB,IAAI,iBAA6C;AAEjD;;AAEG;AACH,SAAS,mBAAmB,CAAC,QAAgB,EAAA;;AAC3C,IAAA,iBAAiB,KAAA,IAAA,IAAjB,iBAAiB,KAAA,MAAA,GAAjB,iBAAiB,IAAjB,iBAAiB,GAAK,IAAI,IAAI,CAAC,SAAS,CAAC,SAAS,EAAE;AAClD,QAAA,WAAW,EAAE,UAAU;AACxB,KAAA,CAAC,CAAA;IACF,MAAM,CAAC,KAAK,CAAC,GAAG,iBAAiB,CAAC,OAAO,CAAC,QAAQ,CA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