diff --git a/src/components/Avatar.tsx b/src/components/Avatar.tsx deleted file mode 100644 index f207ea9eb301..000000000000 --- a/src/components/Avatar.tsx +++ /dev/null @@ -1,217 +0,0 @@ -import useDefaultAvatars from '@hooks/useDefaultAvatars'; -import useNetwork from '@hooks/useNetwork'; -import useOnyx from '@hooks/useOnyx'; -import useStyleUtils from '@hooks/useStyleUtils'; -import useTheme from '@hooks/useTheme'; -import useThemeStyles from '@hooks/useThemeStyles'; - -import {findLocalAvatarForURL} from '@libs/Avatars/AvatarLookup'; -import type {LetterAvatarColorStyle} from '@libs/Avatars/letterAvatarPalette'; -import {isLetterAvatarSchemeKey, LETTER_AVATAR_SCHEMES} from '@libs/Avatars/letterAvatarPalette'; -import {getDefaultWorkspaceAvatar, getDefaultWorkspaceAvatarTestID} from '@libs/ReportUtils'; -import type {AvatarSource} from '@libs/UserAvatarUtils'; -import {getAvatar, parseLetterAvatarURL} from '@libs/UserAvatarUtils'; - -import type {AvatarSizeName} from '@styles/utils'; - -import CONST from '@src/CONST'; -import ONYXKEYS from '@src/ONYXKEYS'; -import {avatarStyleColorSelector} from '@src/selectors/PersonalDetails'; -import type {AvatarType} from '@src/types/onyx/OnyxCommon'; - -import type {ImageStyle, StyleProp, ViewStyle} from 'react-native'; - -import React, {useState} from 'react'; -import {View} from 'react-native'; - -import Icon from './Icon'; -import Image from './Image'; -import UserInitialsAvatar from './UserInitialsAvatar'; - -type AvatarProps = { - /** Source for the avatar. Can be a URL or an icon. */ - source?: AvatarSource; - - /** Extra styles to pass to Image */ - imageStyles?: StyleProp; - - /** Additional styles to pass to Icon */ - iconAdditionalStyles?: StyleProp; - - /** Extra styles to pass to View wrapper */ - containerStyles?: StyleProp; - - /** Set the size of Avatar */ - size?: AvatarSizeName; - - /** - * The fill color for the icon. Can be hex, rgb, rgba, or valid react-native named color such as 'red' or 'blue' - * If the avatar is type === workspace, this fill color will be ignored and decided based on the name prop. - */ - fill?: string; - - /** A fallback avatar icon to display when there is an error on loading avatar from remote URL. - * If the avatar is type === workspace, this fallback icon will be ignored and decided based on the name prop. - */ - fallbackIcon?: AvatarSource; - - /** Used to locate fallback icon in end-to-end tests. */ - fallbackIconTestID?: string; - - /** Owner of the avatar. If user, displayName. If workspace, policy name */ - name?: string; - - /** Denotes whether it is an avatar or a workspace avatar */ - type: AvatarType; - - /** Optional account id if it's user avatar or policy id if it's workspace avatar */ - avatarID?: number | string; - - /** Test ID for the Avatar component */ - testID?: string; -}; - -type UserLetterAvatarProps = { - /** Initials parsed from the generated letter-avatar URL */ - initials: string; - - /** Colors encoded in the generated letter-avatar URL */ - urlColors: LetterAvatarColorStyle; - - /** Account whose picked avatarStyle color overrides the URL colors */ - accountID: number | undefined; - - /** Avatar size in pixels */ - size: number; -}; - -function UserLetterAvatar({initials, urlColors, accountID, size}: UserLetterAvatarProps) { - // A picked avatarStyle color is authoritative over the color encoded in the URL. - const [pickedColorKey] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST, { - selector: avatarStyleColorSelector(accountID), - }); - const colors = pickedColorKey && isLetterAvatarSchemeKey(pickedColorKey) ? LETTER_AVATAR_SCHEMES[pickedColorKey] : urlColors; - - return ( - - ); -} - -function Avatar({ - source: originalSource, - imageStyles, - iconAdditionalStyles, - containerStyles, - size = CONST.AVATAR_SIZE.DEFAULT, - fill, - fallbackIcon, - fallbackIconTestID = '', - type, - name = '', - avatarID, - testID = 'Avatar', -}: AvatarProps) { - const defaultAvatars = useDefaultAvatars(); - const theme = useTheme(); - const styles = useThemeStyles(); - const StyleUtils = useStyleUtils(); - const [errorSource, setErrorSource] = useState(undefined); - const imageError = errorSource !== undefined && errorSource === originalSource; - - useNetwork({onReconnect: () => setErrorSource(undefined)}); - - const isWorkspace = type === CONST.ICON_TYPE_WORKSPACE; - const userAccountID = isWorkspace ? undefined : (avatarID as number); - - const source = isWorkspace - ? originalSource - : getAvatar({ - avatarSource: originalSource, - accountID: userAccountID, - defaultAvatars, - }); - - // Read the color and initials directly from the generated letter-avatar URL. - const letterAvatarParts = parseLetterAvatarURL(source); - - let optimizedSource = source; - const localFromCatalog = findLocalAvatarForURL(source); - - if (localFromCatalog) { - optimizedSource = localFromCatalog; - } - const useFallBackAvatar = imageError || !source || source === defaultAvatars.FallbackAvatar; - const fallbackAvatar = isWorkspace ? getDefaultWorkspaceAvatar(name) : (fallbackIcon ?? defaultAvatars.FallbackAvatar) || defaultAvatars.FallbackAvatar; - const fallbackAvatarTestID = isWorkspace ? getDefaultWorkspaceAvatarTestID(name) : fallbackIconTestID || 'SvgFallbackAvatar Icon'; - const avatarSource = useFallBackAvatar ? fallbackAvatar : optimizedSource; - - // We pass the color styles down to the SVG for the workspace and fallback avatar. - const iconSize = StyleUtils.getAvatarSize(size); - const imageStyle: StyleProp = [StyleUtils.getAvatarStyle(size), imageStyles, styles.noBorderRadius]; - const iconStyle = imageStyles ? [StyleUtils.getAvatarStyle(size), styles.bgTransparent, imageStyles] : undefined; - - let iconColors; - if (isWorkspace) { - iconColors = StyleUtils.getDefaultWorkspaceAvatarColor(avatarID?.toString() ?? ''); - // Assign the icon fill color only for the default fallback avatar - } else if (useFallBackAvatar && avatarSource === defaultAvatars.FallbackAvatar) { - iconColors = StyleUtils.getBackgroundColorAndFill(theme.buttonHoveredBG, theme.icon); - } else { - iconColors = null; - } - - if (!isWorkspace && letterAvatarParts) { - return ( - - - - - - ); - } - - return ( - - {typeof avatarSource === 'string' ? ( - - {/* eslint-disable-next-line react-native-a11y/has-valid-accessibility-ignores-invert-colors -- Custom Image wrapper does not support this prop. */} - setErrorSource(typeof originalSource === 'string' ? originalSource : undefined)} - cachePolicy="memory-disk" - /> - - ) : ( - - - - )} - - ); -} - -export type {AvatarProps}; -export default Avatar; diff --git a/src/components/Avatar/UserAvatar.tsx b/src/components/Avatar/UserAvatar.tsx new file mode 100644 index 000000000000..4aeec0d4865a --- /dev/null +++ b/src/components/Avatar/UserAvatar.tsx @@ -0,0 +1,120 @@ +import useDefaultAvatars from '@hooks/useDefaultAvatars'; +import useStyleUtils from '@hooks/useStyleUtils'; +import useTheme from '@hooks/useTheme'; + +import type {AvatarSource} from '@libs/UserAvatarUtils'; +import {getAvatar, optimizeAvatarSource, parseLetterAvatarURL} from '@libs/UserAvatarUtils'; + +import CONST from '@src/CONST'; + +import React from 'react'; + +import type {AvatarCommonProps} from './types'; + +import useAvatarLoadError from './hooks/useAvatarLoadError'; +import AvatarContainer from './primitives/AvatarContainer'; +import AvatarIcon from './primitives/AvatarIcon'; +import AvatarImage from './primitives/AvatarImage'; +import AvatarLetter from './primitives/AvatarLetter'; + +type UserAvatarProps = AvatarCommonProps & { + /** A fallback avatar icon to display when there is an error on loading avatar from remote URL. */ + fallbackIcon?: AvatarSource; + + /** Used to locate fallback icon in end-to-end tests. */ + fallbackIconTestID?: string; + + /** Owning account ID. Picks the default avatar when `source` is a default or absent. */ + accountID: number; +}; + +/** Renders a user avatar, falling back to a default icon when no source is available. */ +function UserAvatar({ + source, + imageStyles, + iconAdditionalStyles, + containerStyles, + size = CONST.AVATAR_SIZE.DEFAULT, + fill, + fallbackIcon, + fallbackIconTestID = '', + accountID, + testID, +}: UserAvatarProps) { + const defaultAvatars = useDefaultAvatars(); + const theme = useTheme(); + const StyleUtils = useStyleUtils(); + const {hasImageError, onImageError} = useAvatarLoadError(source); + + const resolvedSource = getAvatar({avatarSource: source, accountID, defaultAvatars}); + + // Generated letter-avatar URLs are not fetched — their color and initials are parsed out and drawn locally. + const letterAvatar = parseLetterAvatarURL(resolvedSource); + if (letterAvatar) { + return ( + + + + ); + } + + const optimizedSource = optimizeAvatarSource(resolvedSource); + const useFallBackAvatar = hasImageError || !resolvedSource || resolvedSource === defaultAvatars.FallbackAvatar; + const fallbackAvatar = (fallbackIcon ?? defaultAvatars.FallbackAvatar) || defaultAvatars.FallbackAvatar; + const fallbackAvatarTestID = fallbackIconTestID || 'SvgFallbackAvatar Icon'; + const avatarSource = useFallBackAvatar ? fallbackAvatar : (optimizedSource ?? fallbackAvatar); + + if (typeof avatarSource === 'string') { + return ( + + + + ); + } + + let iconColors = null; + if (useFallBackAvatar && avatarSource === defaultAvatars.FallbackAvatar) { + iconColors = StyleUtils.getBackgroundColorAndFill(theme.buttonHoveredBG, theme.icon); + } + + return ( + + + + ); +} + +export default UserAvatar; diff --git a/src/components/Avatar/WorkspaceAvatar.tsx b/src/components/Avatar/WorkspaceAvatar.tsx new file mode 100644 index 000000000000..ded7d21b527c --- /dev/null +++ b/src/components/Avatar/WorkspaceAvatar.tsx @@ -0,0 +1,79 @@ +import useDefaultAvatars from '@hooks/useDefaultAvatars'; +import useStyleUtils from '@hooks/useStyleUtils'; +import useTheme from '@hooks/useTheme'; + +import {getDefaultWorkspaceAvatar, getDefaultWorkspaceAvatarTestID} from '@libs/ReportUtils'; +import {optimizeAvatarSource} from '@libs/UserAvatarUtils'; + +import CONST from '@src/CONST'; + +import React from 'react'; + +import type {AvatarCommonProps} from './types'; + +import useAvatarLoadError from './hooks/useAvatarLoadError'; +import AvatarContainer from './primitives/AvatarContainer'; +import AvatarIcon from './primitives/AvatarIcon'; +import AvatarImage from './primitives/AvatarImage'; + +type WorkspaceAvatarProps = AvatarCommonProps & { + /** Workspace name. Seeds the default workspace avatar (icon + test ID) used when `source` is missing. */ + name: string; + + /** Workspace/policy ID. Picks the background color of the default workspace avatar. */ + avatarID: number | string; +}; + +/** Renders a workspace avatar, falling back to a default icon derived from the workspace name. */ +function WorkspaceAvatar({source, imageStyles, iconAdditionalStyles, containerStyles, size = CONST.AVATAR_SIZE.DEFAULT, fill, name, avatarID, testID}: WorkspaceAvatarProps) { + const theme = useTheme(); + const StyleUtils = useStyleUtils(); + const defaultAvatars = useDefaultAvatars(); + const {hasImageError, onImageError} = useAvatarLoadError(source); + + const optimizedSource = optimizeAvatarSource(source); + const shouldUseFallBackAvatar = hasImageError || !source || source === defaultAvatars.FallbackAvatar; + const fallbackAvatar = getDefaultWorkspaceAvatar(name); + const fallbackAvatarTestID = getDefaultWorkspaceAvatarTestID(name); + const avatarSource = shouldUseFallBackAvatar ? fallbackAvatar : (optimizedSource ?? fallbackAvatar); + + if (typeof avatarSource === 'string') { + return ( + + + + ); + } + + const iconColors = StyleUtils.getDefaultWorkspaceAvatarColor(avatarID.toString()); + + return ( + + + + ); +} + +export default WorkspaceAvatar; diff --git a/src/components/Avatar/hooks/useAvatarLoadError.ts b/src/components/Avatar/hooks/useAvatarLoadError.ts new file mode 100644 index 000000000000..6dfcd966366b --- /dev/null +++ b/src/components/Avatar/hooks/useAvatarLoadError.ts @@ -0,0 +1,21 @@ +import useNetwork from '@hooks/useNetwork'; + +import type {AvatarSource} from '@libs/UserAvatarUtils'; + +import {useState} from 'react'; + +/** Tracks whether the avatar's remote image failed to load, resetting the error state on network reconnect or source change. */ +function useAvatarLoadError(originalSource?: AvatarSource) { + const [errorSource, setErrorSource] = useState(); + const hasImageError = errorSource !== undefined && errorSource === originalSource; + + useNetwork({onReconnect: () => setErrorSource(undefined)}); + + const onImageError = () => { + setErrorSource(originalSource); + }; + + return {hasImageError, onImageError}; +} + +export default useAvatarLoadError; diff --git a/src/components/Avatar/index.tsx b/src/components/Avatar/index.tsx new file mode 100644 index 000000000000..519a74d5d193 --- /dev/null +++ b/src/components/Avatar/index.tsx @@ -0,0 +1,83 @@ +import type {AvatarSource} from '@libs/UserAvatarUtils'; + +import CONST from '@src/CONST'; +import type {AvatarType} from '@src/types/onyx/OnyxCommon'; + +import React from 'react'; + +import type {AvatarCommonProps} from './types'; + +import UserAvatar from './UserAvatar'; +import WorkspaceAvatar from './WorkspaceAvatar'; + +type AvatarProps = AvatarCommonProps & { + /** ID of the avatar owner: account ID for user avatars, policy ID for workspace avatars. Falls back to the anonymous default when omitted. */ + avatarID?: number | string; + + /** A fallback avatar icon to display when there is an error on loading avatar from remote URL. Only used for user avatars. */ + fallbackIcon?: AvatarSource; + + /** Used to locate fallback icon in end-to-end tests. Only used for user avatars. */ + fallbackIconTestID?: string; + + /** Workspace name. Only used for workspace avatars — seeds the default workspace avatar. */ + name?: string; + + /** Denotes whether it is an avatar or a workspace avatar */ + type: AvatarType; +}; + +/** Renders a user or workspace avatar depending on the `type` prop. + * This wrapper exists for backward compatibility. If possible use WorkspaceAvatar and UserAvatar directly. + */ +function Avatar({ + type, + name = '', + fallbackIcon, + fallbackIconTestID, + source, + imageStyles, + iconAdditionalStyles, + containerStyles, + size, + fill, + testID, + avatarID = CONST.DEFAULT_NUMBER_ID, +}: AvatarProps) { + if (type === CONST.ICON_TYPE_WORKSPACE) { + return ( + + ); + } + + const accountID = typeof avatarID === 'string' ? parseInt(avatarID, 10) : avatarID; + + return ( + + ); +} + +export default Avatar; + +export type {AvatarProps}; diff --git a/src/components/Avatar/primitives/AvatarContainer.tsx b/src/components/Avatar/primitives/AvatarContainer.tsx new file mode 100644 index 000000000000..e6b7c992ed17 --- /dev/null +++ b/src/components/Avatar/primitives/AvatarContainer.tsx @@ -0,0 +1,31 @@ +import useThemeStyles from '@hooks/useThemeStyles'; + +import type {PropsWithChildren} from 'react'; +import type {StyleProp, ViewStyle} from 'react-native'; + +import React from 'react'; +import {View} from 'react-native'; + +type AvatarContainerProps = PropsWithChildren<{ + /** Extra styles to pass to the wrapping View */ + containerStyles?: StyleProp; + + /** Test ID used to locate the avatar in tests */ + testID?: string; +}>; + +/** Shared root wrapper for avatar components. Applies container styles, disables pointer events and exposes the test ID. */ +function AvatarContainer({containerStyles, testID = 'Avatar', children}: AvatarContainerProps) { + const styles = useThemeStyles(); + + return ( + + {children} + + ); +} + +export default AvatarContainer; diff --git a/src/components/Avatar/primitives/AvatarIcon.tsx b/src/components/Avatar/primitives/AvatarIcon.tsx new file mode 100644 index 000000000000..462d43c8e290 --- /dev/null +++ b/src/components/Avatar/primitives/AvatarIcon.tsx @@ -0,0 +1,58 @@ +import type {AvatarPrimitivesCommonProps} from '@components/Avatar/types'; +import Icon from '@components/Icon'; + +import useStyleUtils from '@hooks/useStyleUtils'; +import useThemeStyles from '@hooks/useThemeStyles'; + +import type {SVGAvatarColorStyle} from '@styles/utils/types'; + +import type IconAsset from '@src/types/utils/IconAsset'; + +import type {ImageStyle, StyleProp, ViewStyle} from 'react-native'; + +import React from 'react'; +import {View} from 'react-native'; + +type AvatarIconProps = AvatarPrimitivesCommonProps & { + /** Icon asset to render as the avatar. */ + avatarSource: IconAsset; + + /** Test ID used for the fallback avatar. */ + fallbackAvatarTestID: string; + + /** Styles for View wrapping Icon / Image. */ + iconContainerStyles?: StyleProp; + + /** Fill and background colors for the icon, or null to use the defaults. */ + iconColors: SVGAvatarColorStyle | null; + + /** The fill color for the icon */ + fill?: string; + + /** Additional styles for Icon */ + iconAdditionalStyles?: StyleProp; +}; + +/** Renders an avatar as an SVG icon. */ +function AvatarIcon({avatarSource, size, type, iconContainerStyles, iconAdditionalStyles, fallbackAvatarTestID, iconColors, fill}: AvatarIconProps) { + const styles = useThemeStyles(); + const StyleUtils = useStyleUtils(); + const iconSize = StyleUtils.getAvatarSize(size); + const containerStyles = iconContainerStyles ? [StyleUtils.getAvatarStyle(size), styles.bgTransparent, iconContainerStyles] : undefined; + const additionalStyles = [StyleUtils.getAvatarBorderStyle(size, type), iconColors, iconAdditionalStyles]; + + return ( + + + + ); +} + +export default AvatarIcon; diff --git a/src/components/Avatar/primitives/AvatarImage.tsx b/src/components/Avatar/primitives/AvatarImage.tsx new file mode 100644 index 000000000000..5f4b2aea7dc4 --- /dev/null +++ b/src/components/Avatar/primitives/AvatarImage.tsx @@ -0,0 +1,46 @@ +import type {AvatarPrimitivesCommonProps} from '@components/Avatar/types'; +import Image from '@components/Image'; + +import useStyleUtils from '@hooks/useStyleUtils'; +import useThemeStyles from '@hooks/useThemeStyles'; + +import type {ImageStyle, StyleProp, ViewStyle} from 'react-native'; + +import React from 'react'; +import {View} from 'react-native'; + +type AvatarImageProps = AvatarPrimitivesCommonProps & { + /** URL of the remote avatar image. */ + avatarSource: string; + + /** Callback invoked when the avatar image fails to load. */ + onImageError: () => void; + + /** Styles for View wrapping Icon / Image. */ + imageStyles?: StyleProp; + + /** Additional styles for Icon */ + imageContainerAdditionalStyles?: StyleProp; +}; + +/** Renders an avatar as a remote image. */ +function AvatarImage({avatarSource, size, type, imageStyles, imageContainerAdditionalStyles, onImageError}: AvatarImageProps) { + const styles = useThemeStyles(); + const StyleUtils = useStyleUtils(); + const imageStyle = [StyleUtils.getAvatarStyle(size), imageStyles, styles.noBorderRadius]; + const imageContainerStyle = imageStyles ? [StyleUtils.getAvatarStyle(size), styles.bgTransparent, imageStyles] : undefined; + + return ( + + {/* eslint-disable-next-line react-native-a11y/has-valid-accessibility-ignores-invert-colors -- Custom Image wrapper does not support this prop. */} + + + ); +} + +export default AvatarImage; diff --git a/src/components/Avatar/primitives/AvatarLetter.tsx b/src/components/Avatar/primitives/AvatarLetter.tsx new file mode 100644 index 000000000000..bed219fcf274 --- /dev/null +++ b/src/components/Avatar/primitives/AvatarLetter.tsx @@ -0,0 +1,59 @@ +import type {AvatarPrimitivesCommonProps} from '@components/Avatar/types'; +import UserInitialsAvatar from '@components/UserInitialsAvatar'; + +import useOnyx from '@hooks/useOnyx'; +import useStyleUtils from '@hooks/useStyleUtils'; +import useThemeStyles from '@hooks/useThemeStyles'; + +import {isLetterAvatarSchemeKey, LETTER_AVATAR_SCHEMES} from '@libs/Avatars/letterAvatarPalette'; +import type {LetterAvatarColorStyle} from '@libs/Avatars/letterAvatarPalette'; + +import ONYXKEYS from '@src/ONYXKEYS'; +import {avatarStyleColorSelector} from '@src/selectors/PersonalDetails'; + +import type {ImageStyle, StyleProp, ViewStyle} from 'react-native'; + +import React from 'react'; +import {View} from 'react-native'; + +type AvatarLetterProps = AvatarPrimitivesCommonProps & { + /** Initials parsed from the generated letter-avatar URL */ + initials: string; + + /** Colors encoded in the generated letter-avatar URL */ + urlColors: LetterAvatarColorStyle; + + /** Account whose picked avatarStyle color overrides the URL colors */ + accountID: number | undefined; + + /** Styles for View wrapping the initials. */ + containerStyles?: StyleProp; + + /** Additional styles for the wrapping View. */ + containerAdditionalStyles?: StyleProp; +}; + +function AvatarLetter({initials, urlColors, accountID, size, type, containerStyles, containerAdditionalStyles: initialsAdditionalStyles}: AvatarLetterProps) { + const styles = useThemeStyles(); + const StyleUtils = useStyleUtils(); + const avatarSize = StyleUtils.getAvatarSize(size); + const baseContainerStyles = containerStyles ? [StyleUtils.getAvatarStyle(size), styles.bgTransparent, containerStyles] : undefined; + + // A picked avatarStyle color is authoritative over the color encoded in the URL. + const [pickedColorKey] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST, { + selector: avatarStyleColorSelector(accountID), + }); + const colors = pickedColorKey && isLetterAvatarSchemeKey(pickedColorKey) ? LETTER_AVATAR_SCHEMES[pickedColorKey] : urlColors; + + return ( + + + + ); +} + +export default AvatarLetter; diff --git a/src/components/Avatar/types.ts b/src/components/Avatar/types.ts new file mode 100644 index 000000000000..246437324d1d --- /dev/null +++ b/src/components/Avatar/types.ts @@ -0,0 +1,43 @@ +import type {AvatarSource} from '@libs/UserAvatarUtils'; + +import type {AvatarSizeName} from '@styles/utils'; + +import type {AvatarType} from '@src/types/onyx/OnyxCommon'; + +import type {ImageStyle, StyleProp, ViewStyle} from 'react-native'; + +type AvatarCommonProps = { + /** Source for the avatar. Can be a URL or an icon. */ + source?: AvatarSource; + + /** Extra styles for the rendered image, or for the container of the rendered icon/initials */ + imageStyles?: StyleProp; + + /** Additional styles for the rendered icon/initials, or for the container of the rendered image */ + iconAdditionalStyles?: StyleProp; + + /** Extra styles to pass to View wrapper */ + containerStyles?: StyleProp; + + /** Set the size of Avatar */ + size?: AvatarSizeName; + + /** + * The fill color for the icon. Can be hex, rgb, rgba, or valid react-native named color such as 'red' or 'blue' + * For workspace avatars this fill color is ignored — the colors are derived from the avatarID prop instead. + */ + fill?: string; + + /** Test ID for the Avatar component */ + testID?: string; +}; + +type AvatarPrimitivesCommonProps = { + /** Size of Avatar */ + size: AvatarSizeName; + + /** Denotes whether it is an avatar or a workspace avatar */ + type: AvatarType; +}; + +export type {AvatarCommonProps, AvatarPrimitivesCommonProps}; diff --git a/src/libs/UserAvatarUtils.ts b/src/libs/UserAvatarUtils.ts index 95bc277c2c49..b4aca7c364e7 100644 --- a/src/libs/UserAvatarUtils.ts +++ b/src/libs/UserAvatarUtils.ts @@ -478,6 +478,14 @@ function getSmallSizeAvatar(args: GetAvatarArgsType & DefaultAvatarsType): Avata return `${source.substring(0, lastPeriodIndex)}_128${source.substring(lastPeriodIndex)}`; } +/** + * Swaps a catalog-backed avatar URL for its bundled local SVG so it renders without a network request. + * Non-catalog sources (uploaded image URLs, SVG components, or undefined) are returned unchanged. + */ +function optimizeAvatarSource(source?: AvatarSource): AvatarSource | undefined { + return findLocalAvatarForURL(source) ?? source; +} + export { getAvatar, getAvatarURL, @@ -495,5 +503,6 @@ export { isDefaultAvatar, isGeneratedLetterAvatarURL, isLetterAvatar, + optimizeAvatarSource, }; export type {AvatarSource}; diff --git a/src/styles/utils/index.ts b/src/styles/utils/index.ts index 368e7e856d25..89716ac31b22 100644 --- a/src/styles/utils/index.ts +++ b/src/styles/utils/index.ts @@ -313,7 +313,7 @@ function getAvatarSubscriptIconContainerStyle(iconWidth = 16, iconHeight = 16): /** * Helper method to return workspace avatar color styles */ -function getDefaultWorkspaceAvatarColor(text: string): ViewStyle { +function getDefaultWorkspaceAvatarColor(text: string): SVGAvatarColorStyle { const colorHash = hashText(text.trim(), workspaceColorOptions.length); return workspaceColorOptions.at(colorHash) ?? DEFAULT_WORKSPACE_COLOR; } diff --git a/tests/unit/AvatarTest.tsx b/tests/unit/AvatarTest.tsx new file mode 100644 index 000000000000..8b9973888d7d --- /dev/null +++ b/tests/unit/AvatarTest.tsx @@ -0,0 +1,335 @@ +import {render, screen} from '@testing-library/react-native'; + +import Avatar from '@components/Avatar'; +import UserAvatar from '@components/Avatar/UserAvatar'; +import WorkspaceAvatar from '@components/Avatar/WorkspaceAvatar'; +import ComposeProviders from '@components/ComposeProviders'; +import {LocaleContextProvider} from '@components/LocaleContextProvider'; +import OnyxListItemProvider from '@components/OnyxListItemProvider'; +import ThemeProvider from '@components/ThemeProvider'; +import ThemeStylesProvider from '@components/ThemeStylesContextProvider'; + +import {USER_AVATARS} from '@libs/Avatars/UserAvatarCatalog'; +import {getDefaultWorkspaceAvatarTestID} from '@libs/ReportUtils'; + +import CONST from '@src/CONST'; + +import React from 'react'; +import {View} from 'react-native'; + +import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; + +const UPLOADED_AVATAR_URL = 'https://example.com/uploaded-avatar.jpg'; +const DEFAULT_AVATAR_URL = USER_AVATARS.entries['default-avatar_1'].url; +const LETTER_AVATAR_INITIALS = 'JD'; +const LETTER_AVATAR_URL = `${CONST.CLOUDFRONT_URL}${CONST.GENERATED_LETTER_AVATAR_PATH}v1/blue100/${LETTER_AVATAR_INITIALS}.png`; +const SMALL_LETTER_AVATAR_URL = `${CONST.CLOUDFRONT_URL}${CONST.GENERATED_LETTER_AVATAR_PATH}v1/blue100/${LETTER_AVATAR_INITIALS}_128.png`; +const FALLBACK_ICON_TEST_ID = 'SvgFallbackAvatar Icon'; +const CUSTOM_FALLBACK_ICON_TEST_ID = 'CustomFallback Icon'; +const AVATAR_IMAGE_TEST_ID = 'AvatarImage'; +const WORKSPACE_NAME = "Cathy's Croissants"; + +function CustomFallbackIcon() { + return mockRenderView({testID: 'CustomFallbackIconSvg'}); +} + +// Captures the mocked 's onError callback so tests can simulate a failed image load. +const mockImageErrorHandlerRef: {current?: () => void} = {current: undefined}; + +// Renders a bare React Native as a stand-in for a mocked component. Prefixed with +// `mock` so the hoisted jest.mock factories below are allowed to reference it. +function mockRenderView({testID, accessibilityLabel}: {testID?: string; accessibilityLabel?: string}) { + return ( + + ); +} + +jest.mock('@hooks/useLazyAsset', () => { + function FallbackAvatar() { + return mockRenderView({testID: 'MockFallbackAvatar'}); + } + + return { + useMemoizedLazyExpensifyIcons: () => ({ + ConciergeAvatar: FallbackAvatar, + NotificationsAvatar: FallbackAvatar, + FallbackAvatar, + }), + }; +}); + +jest.mock('@hooks/useNetwork', () => jest.fn(() => ({isOffline: false}))); + +jest.mock('@components/Image', () => { + function MockImage({source, onError}: {source?: {uri?: string}; onError?: () => void}) { + mockImageErrorHandlerRef.current = onError; + return mockRenderView({testID: 'AvatarImage', accessibilityLabel: source?.uri}); + } + + return {__esModule: true, default: MockImage}; +}); + +function ThemeProviderWithLight({children}: {children: React.ReactNode}) { + return {children}; +} + +const hiddenElementOptions = {includeHiddenElements: true}; + +function getHiddenTestId(testID: string) { + return screen.getByTestId(testID, hiddenElementOptions); +} + +function queryHiddenTestId(testID: string) { + return screen.queryByTestId(testID, hiddenElementOptions); +} + +function renderAvatar(props: React.ComponentProps) { + return render( + + + , + ); +} + +describe('Avatar', () => { + beforeEach(() => { + jest.clearAllMocks(); + mockImageErrorHandlerRef.current = undefined; + }); + + describe('user avatar', () => { + it('renders the Image branch for an uploaded URL source', async () => { + renderAvatar({ + type: CONST.ICON_TYPE_AVATAR, + source: UPLOADED_AVATAR_URL, + avatarID: 1, + }); + + await waitForBatchedUpdates(); + + expect(screen.getByTestId('Avatar')).toBeTruthy(); + expect(screen.getByTestId(AVATAR_IMAGE_TEST_ID)).toBeTruthy(); + expect(screen.getByTestId(AVATAR_IMAGE_TEST_ID).props.accessibilityLabel).toBe(UPLOADED_AVATAR_URL); + expect(queryHiddenTestId(FALLBACK_ICON_TEST_ID)).toBeNull(); + }); + + it('renders the Icon branch for a default catalog avatar URL', async () => { + renderAvatar({ + type: CONST.ICON_TYPE_AVATAR, + source: DEFAULT_AVATAR_URL, + avatarID: 1, + }); + + await waitForBatchedUpdates(); + + expect(screen.queryByTestId(AVATAR_IMAGE_TEST_ID)).toBeNull(); + expect(getHiddenTestId(FALLBACK_ICON_TEST_ID)).toBeTruthy(); + }); + + it('renders the fallback Icon when no source is provided', async () => { + renderAvatar({ + type: CONST.ICON_TYPE_AVATAR, + avatarID: 1, + }); + + await waitForBatchedUpdates(); + + expect(screen.queryByTestId(AVATAR_IMAGE_TEST_ID)).toBeNull(); + expect(getHiddenTestId(FALLBACK_ICON_TEST_ID)).toBeTruthy(); + }); + + it('switches from the Image branch to the fallback Icon when the image fails to load', async () => { + renderAvatar({ + type: CONST.ICON_TYPE_AVATAR, + source: UPLOADED_AVATAR_URL, + avatarID: 1, + }); + + await waitForBatchedUpdates(); + + expect(screen.getByTestId(AVATAR_IMAGE_TEST_ID)).toBeTruthy(); + expect(queryHiddenTestId(FALLBACK_ICON_TEST_ID)).toBeNull(); + + mockImageErrorHandlerRef.current?.(); + + await waitForBatchedUpdates(); + + expect(screen.queryByTestId(AVATAR_IMAGE_TEST_ID)).toBeNull(); + expect(getHiddenTestId(FALLBACK_ICON_TEST_ID)).toBeTruthy(); + }); + + it('renders the custom fallback Icon when no source is provided', async () => { + renderAvatar({ + type: CONST.ICON_TYPE_AVATAR, + avatarID: 1, + fallbackIcon: CustomFallbackIcon, + fallbackIconTestID: CUSTOM_FALLBACK_ICON_TEST_ID, + }); + + await waitForBatchedUpdates(); + + expect(screen.queryByTestId(AVATAR_IMAGE_TEST_ID)).toBeNull(); + expect(getHiddenTestId(CUSTOM_FALLBACK_ICON_TEST_ID)).toBeTruthy(); + expect(queryHiddenTestId(FALLBACK_ICON_TEST_ID)).toBeNull(); + }); + + it('switches from the Image branch to the custom fallback Icon when the image fails to load', async () => { + renderAvatar({ + type: CONST.ICON_TYPE_AVATAR, + source: UPLOADED_AVATAR_URL, + avatarID: 1, + fallbackIcon: CustomFallbackIcon, + fallbackIconTestID: CUSTOM_FALLBACK_ICON_TEST_ID, + }); + + await waitForBatchedUpdates(); + + expect(screen.getByTestId(AVATAR_IMAGE_TEST_ID)).toBeTruthy(); + expect(queryHiddenTestId(CUSTOM_FALLBACK_ICON_TEST_ID)).toBeNull(); + expect(queryHiddenTestId(FALLBACK_ICON_TEST_ID)).toBeNull(); + + mockImageErrorHandlerRef.current?.(); + + await waitForBatchedUpdates(); + + expect(screen.queryByTestId(AVATAR_IMAGE_TEST_ID)).toBeNull(); + expect(getHiddenTestId(CUSTOM_FALLBACK_ICON_TEST_ID)).toBeTruthy(); + expect(queryHiddenTestId(FALLBACK_ICON_TEST_ID)).toBeNull(); + }); + + it('renders locally drawn initials for a generated letter-avatar URL instead of fetching the image', async () => { + renderAvatar({ + type: CONST.ICON_TYPE_AVATAR, + source: LETTER_AVATAR_URL, + avatarID: 1, + }); + + await waitForBatchedUpdates(); + + expect(screen.getByText(LETTER_AVATAR_INITIALS, hiddenElementOptions)).toBeTruthy(); + expect(screen.queryByTestId(AVATAR_IMAGE_TEST_ID)).toBeNull(); + expect(queryHiddenTestId(FALLBACK_ICON_TEST_ID)).toBeNull(); + }); + + it('renders locally drawn initials for the small-size (_128) letter-avatar URL variant', async () => { + renderAvatar({ + type: CONST.ICON_TYPE_AVATAR, + source: SMALL_LETTER_AVATAR_URL, + avatarID: 1, + }); + + await waitForBatchedUpdates(); + + expect(screen.getByText(LETTER_AVATAR_INITIALS, hiddenElementOptions)).toBeTruthy(); + expect(screen.queryByTestId(AVATAR_IMAGE_TEST_ID)).toBeNull(); + }); + }); + + describe('workspace avatar', () => { + it('renders the Image branch for a letter-avatar URL because initials are user-avatar-only', async () => { + renderAvatar({ + type: CONST.ICON_TYPE_WORKSPACE, + source: LETTER_AVATAR_URL, + name: WORKSPACE_NAME, + avatarID: 'policy_123', + }); + + await waitForBatchedUpdates(); + + expect(screen.getByTestId(AVATAR_IMAGE_TEST_ID)).toBeTruthy(); + expect(screen.queryByText(LETTER_AVATAR_INITIALS, hiddenElementOptions)).toBeNull(); + }); + + it('renders the Image branch for an uploaded workspace logo URL', async () => { + renderAvatar({ + type: CONST.ICON_TYPE_WORKSPACE, + source: UPLOADED_AVATAR_URL, + name: WORKSPACE_NAME, + avatarID: 'policy_123', + }); + + await waitForBatchedUpdates(); + + expect(screen.getByTestId(AVATAR_IMAGE_TEST_ID)).toBeTruthy(); + expect(screen.getByTestId(AVATAR_IMAGE_TEST_ID).props.accessibilityLabel).toBe(UPLOADED_AVATAR_URL); + expect(queryHiddenTestId(getDefaultWorkspaceAvatarTestID(WORKSPACE_NAME))).toBeNull(); + }); + + it('renders the default workspace Icon when no source is provided', async () => { + const workspaceFallbackTestID = getDefaultWorkspaceAvatarTestID(WORKSPACE_NAME); + + renderAvatar({ + type: CONST.ICON_TYPE_WORKSPACE, + name: WORKSPACE_NAME, + avatarID: 'policy_123', + }); + + await waitForBatchedUpdates(); + + expect(screen.queryByTestId(AVATAR_IMAGE_TEST_ID)).toBeNull(); + expect(getHiddenTestId(workspaceFallbackTestID)).toBeTruthy(); + }); + + it('switches from the Image branch to the default workspace Icon when the uploaded logo fails to load', async () => { + const workspaceFallbackTestID = getDefaultWorkspaceAvatarTestID(WORKSPACE_NAME); + + renderAvatar({ + type: CONST.ICON_TYPE_WORKSPACE, + source: UPLOADED_AVATAR_URL, + name: WORKSPACE_NAME, + avatarID: 'policy_123', + }); + + await waitForBatchedUpdates(); + + expect(screen.getByTestId(AVATAR_IMAGE_TEST_ID)).toBeTruthy(); + expect(queryHiddenTestId(workspaceFallbackTestID)).toBeNull(); + + mockImageErrorHandlerRef.current?.(); + + await waitForBatchedUpdates(); + + expect(screen.queryByTestId(AVATAR_IMAGE_TEST_ID)).toBeNull(); + expect(getHiddenTestId(workspaceFallbackTestID)).toBeTruthy(); + }); + }); + + describe('UserAvatar and WorkspaceAvatar', () => { + it('UserAvatar renders the same as the back-compat default for user avatars', async () => { + render( + + + , + ); + + await waitForBatchedUpdates(); + + expect(screen.getByTestId('Avatar')).toBeTruthy(); + expect(screen.getByTestId(AVATAR_IMAGE_TEST_ID)).toBeTruthy(); + }); + + it('WorkspaceAvatar renders the same as the back-compat default for workspace avatars', async () => { + const workspaceFallbackTestID = getDefaultWorkspaceAvatarTestID(WORKSPACE_NAME); + + render( + + + , + ); + + await waitForBatchedUpdates(); + + expect(screen.queryByTestId(AVATAR_IMAGE_TEST_ID)).toBeNull(); + expect(getHiddenTestId(workspaceFallbackTestID)).toBeTruthy(); + }); + }); +});