Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -818,7 +818,8 @@
"src/CONST/index.ts",
"src/libs/SearchParser/*",
"modules/group-ib-fp",
"web/snippets/gib.js"
"web/snippets/gib.js",
"tests/unit/hooks/useLetterAvatars.test.tsx"
],
"ignoreRegExpList": ["@assets/.*"],
"useGitignore": true
Expand Down
13 changes: 10 additions & 3 deletions src/components/AvatarCropModal/AvatarCropModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ type AvatarCropModalProps = {
/** Callback to be called when user closes the modal */
onClose?: () => void;

/** Callback to be called when user presses the back button */
onBackButtonPress?: () => void;

/** Callback to be called when user saves the image */
onSave?: (newImage: File | CustomRNImageManipulatorResult) => void;

Expand All @@ -49,10 +52,13 @@ type AvatarCropModalProps = {

/** Image crop vector mask */
maskImage?: IconAsset;

/** Custom primary action label text */
buttonLabel?: string;
};

// This component can't be written using class since reanimated API uses hooks.
function AvatarCropModal({imageUri = '', imageName = '', imageType = '', onClose, onSave, isVisible, maskImage}: AvatarCropModalProps) {
function AvatarCropModal({imageUri = '', imageName = '', imageType = '', onClose, onSave, onBackButtonPress, isVisible, maskImage, buttonLabel}: AvatarCropModalProps) {
const theme = useTheme();
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
Expand All @@ -66,6 +72,7 @@ function AvatarCropModal({imageUri = '', imageName = '', imageType = '', onClose
const isPressableEnabled = useSharedValue(true);

const {translate} = useLocalize();
const buttonText = buttonLabel ?? translate('common.save');
const {shouldUseNarrowLayout} = useResponsiveLayout();

// Check if image cropping, saving or uploading is in progress
Expand Down Expand Up @@ -367,7 +374,7 @@ function AvatarCropModal({imageUri = '', imageName = '', imageType = '', onClose
{shouldUseNarrowLayout && <HeaderGap />}
<HeaderWithBackButton
title={translate('avatarCropModal.title')}
onBackButtonPress={onClose}
onBackButtonPress={onBackButtonPress ?? onClose}
/>
<Text style={[styles.mh5]}>{translate('avatarCropModal.description')}</Text>
<GestureHandlerRootView
Expand Down Expand Up @@ -434,7 +441,7 @@ function AvatarCropModal({imageUri = '', imageName = '', imageType = '', onClose
onPress={cropAndSaveImage}
pressOnEnter
large
text={translate('common.save')}
text={buttonText}
/>
</ScreenWrapper>
</Modal>
Expand Down
44 changes: 20 additions & 24 deletions src/components/AvatarSelector.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import React, {useState} from 'react';
import React from 'react';
import {View} from 'react-native';
import useLetterAvatars from '@hooks/useLetterAvatars';
import useLocalize from '@hooks/useLocalize';
import useStyleUtils from '@hooks/useStyleUtils';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import type {ALL_CUSTOM_AVATARS} from '@libs/Avatars/CustomAvatarCatalog';
import {CUSTOM_AVATAR_CATALOG} from '@libs/Avatars/CustomAvatarCatalog';
// import {CUSTOM_AVATAR_CATALOG} from '@libs/Avatars/CustomAvatarCatalog';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need this?

import type {AvatarSizeName} from '@styles/utils';
import CONST from '@src/CONST';
import Avatar from './Avatar';
Expand All @@ -13,10 +13,13 @@ import Text from './Text';

type AvatarSelectorProps = {
/** Currently selected avatar ID */
selectedID?: keyof typeof ALL_CUSTOM_AVATARS;
selectedID?: string;

/** Called when an avatar is selected */
onSelect: (id: keyof typeof ALL_CUSTOM_AVATARS) => void;
onSelect: (id: string) => void;

/** Used to generate letter avatars */
name?: string;

/** Optional: size of avatars in grid */
size?: AvatarSizeName;
Expand All @@ -27,42 +30,35 @@ type AvatarSelectorProps = {

/**
* AvatarSelector — renders a grid of selectable avatars.
* Note: This component should be placed inside a ScrollView.
*/
function AvatarSelector({selectedID, onSelect, label, size = CONST.AVATAR_SIZE.MEDIUM}: AvatarSelectorProps) {
const theme = useTheme();
function AvatarSelector({selectedID, onSelect, label, name, size = CONST.AVATAR_SIZE.MEDIUM}: AvatarSelectorProps) {
const {translate} = useLocalize();
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const [selected, setSelected] = useState(selectedID);

const handleSelect = (id: keyof typeof ALL_CUSTOM_AVATARS) => {
setSelected(id);
onSelect(id);
};
const {avatarList} = useLetterAvatars(name, size);

return (
<>
{!!label && (
<View style={[styles.pt5, styles.ph2]}>
<Text style={StyleUtils.combineStyles([styles.sidebarLinkText, styles.optionAlternateText, styles.textLabelSupporting, styles.pre])}>{label}</Text>
</View>
{!!label && avatarList?.length > 0 && (
<Text style={StyleUtils.combineStyles([styles.sidebarLinkText, styles.optionAlternateText, styles.textLabelSupporting, styles.pre, styles.ph2])}>{label}</Text>
)}
<View style={styles.avatarSelectorListContainer}>
{CUSTOM_AVATAR_CATALOG.map(({id, local}) => {
const isSelected = selected === id;
{avatarList.map(({id, StyledLetterAvatar}) => {
const isSelected = selectedID === id;

return (
<PressableWithFeedback
key={id}
accessible
accessibilityRole="button"
accessibilityLabel="Select Avatar"
onPress={() => handleSelect(id)}
style={[styles.avatarSelectorWrapper, isSelected && {borderColor: theme.success, borderWidth: 2}]}
accessibilityLabel={translate('avatarPage.selectAvatar')}
onPress={() => onSelect(id)}
style={[styles.avatarSelectorWrapper, isSelected && styles.avatarSelected]}
>
<Avatar
type={CONST.ICON_TYPE_AVATAR}
source={local}
source={StyledLetterAvatar}
size={size}
containerStyles={styles.avatarSelectorContainer}
testID={`AvatarSelector_${id}`}
Expand Down
44 changes: 44 additions & 0 deletions src/components/ColoredLetterAvatar.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import React from 'react';
import {View} from 'react-native';
import type {SvgProps} from 'react-native-svg';
import useStyleUtils from '@hooks/useStyleUtils';
import type {AvatarSizeName} from '@styles/utils';
import CONST from '@src/CONST';
import ImageSVG from './ImageSVG';

type ColoredLetterAvatarProps = {
/** The SVG component to render */
component: React.FC<SvgProps>;
/** Background color for the circular background */
backgroundColor: string;
/** Fill color for the SVG icon */
fillColor: string;
/** Size of the avatar */
size?: AvatarSizeName;
};

/**
* ColoredLetterAvatar renders an SVG component with a colored circular background.
* Used for letter avatars and other colored icon avatars.
*/
function ColoredLetterAvatar({component, backgroundColor, fillColor, size = CONST.AVATAR_SIZE.MEDIUM}: ColoredLetterAvatarProps) {
const StyleUtils = useStyleUtils();
const avatarSize = StyleUtils.getAvatarSize(size);
return (
<View
style={{width: avatarSize, height: avatarSize, backgroundColor}}
dataSet={{id: 'colored-avatar'}}
>
<ImageSVG
src={component}
width={avatarSize}
height={avatarSize}
fill={fillColor}
/>
</View>
);
}

ColoredLetterAvatar.displayName = 'ColoredLetterAvatar';

export default ColoredLetterAvatar;
82 changes: 82 additions & 0 deletions src/hooks/useAvatarMenu.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import {useCallback} from 'react';
import type {DropdownOption} from '@components/ButtonWithDropdownMenu/types';
import * as Expensicons from '@components/Icon/Expensicons';
import Navigation from '@libs/Navigation/Navigation';
import ROUTES from '@src/ROUTES';
import type {FileObject} from '@src/types/utils/Attachment';
import useLocalize from './useLocalize';

type OpenPicker = (options: {onPicked: (files: FileObject[]) => void}) => void;

type UseAvatarMenuParams = {
/** Whether the user is using a default avatar */
isUsingDefaultAvatar: boolean;
/** Whether the user has chosen a new avatar in the form but hasn't uploaded it yet */
isAvatarSelected: boolean;
/** Account ID for navigation */
accountID: number;
/** Callback when avatar is removed */
onImageRemoved: () => void;
/** Callback to show avatar crop modal */
showAvatarCropModal: (image: FileObject) => void;
/** Callback to clear errors */
clearError: () => void;
};

/**
* Custom hook to create avatar menu items
*/
function useAvatarMenu({isUsingDefaultAvatar, isAvatarSelected, accountID, onImageRemoved, showAvatarCropModal, clearError}: UseAvatarMenuParams) {
const {translate} = useLocalize();

/**
* Create menu items list for avatar menu
*/
const createMenuItems = useCallback(
(openPicker: OpenPicker): Array<DropdownOption<null>> => {
const menuItems: Array<DropdownOption<null>> = [
{
icon: Expensicons.Upload,
text: translate('avatarWithImagePicker.uploadPhoto'),
onSelected: () => {
openPicker({
onPicked: (data) => showAvatarCropModal(data.at(0) ?? {}),
});
},
value: null,
},
];
// If current avatar is a default avatar and for no avatar is selected in the form, only show upload option
if (isUsingDefaultAvatar && !isAvatarSelected) {
return menuItems;
}
menuItems.push({
icon: Expensicons.Trashcan,
text: translate('avatarWithImagePicker.removePhoto'),
value: null,
onSelected: () => {
clearError();
onImageRemoved();
},
});
// If an avatar is selected in the form do NOT show view photo
if (isAvatarSelected) {
return menuItems;
}
return [
...menuItems,
{
value: null,
icon: Expensicons.Eye,
text: translate('avatarWithImagePicker.viewPhoto'),
onSelected: () => Navigation.navigate(ROUTES.PROFILE_AVATAR.getRoute(accountID)),
},
];
},
[accountID, isUsingDefaultAvatar, onImageRemoved, showAvatarCropModal, translate, clearError, isAvatarSelected],
);

return {createMenuItems};
}

export default useAvatarMenu;
76 changes: 76 additions & 0 deletions src/hooks/useLetterAvatars.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import React, {useMemo} from 'react';
import type {SvgProps} from 'react-native-svg';
import ColoredLetterAvatar from '@components/ColoredLetterAvatar';
import {getLetterAvatar, LETTER_AVATAR_COLOR_OPTIONS} from '@libs/Avatars/CustomAvatarCatalog';
import getFirstAlphaNumericCharacter from '@libs/getFirstAlphaNumericCharacter';
import type {AvatarSizeName} from '@styles/utils';

/**
* Represents a single letter avatar item with its unique identifier and styled component.
*/
type LetterAvatarItem = {
/** Unique identifier combining background color, fill color, and initial letter */
id: string;
/** Styled letter avatar component with applied colors */
StyledLetterAvatar: React.FC<SvgProps>;
};

/**
* Return type for useLetterAvatars hook containing avatar data in multiple formats.
*/
type LetterAvatarsResult = {
/** Array of avatar items for use in AvatarSelector component, containing all color variations */
avatarList: LetterAvatarItem[];
/** Object mapping avatar IDs to components for quick lookup in AvatarPage component */
avatarMap: Record<string, React.FC<SvgProps>>;
};

/**
* Generates letter avatars based on a user's name initial in all available color combinations.
*
* @param name - The user's name from which the first alphanumeric character is extracted
* @param size - Optional size for the avatars
* @returns Object with avatarList (array for AvatarSelector) and avatarMap (lookup for AvatarPage)
*/
function useLetterAvatars(name: string | undefined, size?: AvatarSizeName): LetterAvatarsResult {
return useMemo(() => {
const avatarComponent = getLetterAvatar(name);

if (!avatarComponent) {
return {avatarList: [], avatarMap: {}};
}

const avatarList: LetterAvatarItem[] = [];
const avatarMap: Record<string, React.FC<SvgProps>> = {};

LETTER_AVATAR_COLOR_OPTIONS.forEach(({fillColor, backgroundColor}) => {
function StyledLetterAvatar() {
return (
<ColoredLetterAvatar
fillColor={fillColor}
backgroundColor={backgroundColor}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
component={avatarComponent!}
size={size}
/>
);
}
const id = `letter-avatar-${backgroundColor}-${fillColor}-${getFirstAlphaNumericCharacter(name)}`;

avatarList.push({
id,
StyledLetterAvatar,
});

avatarMap[id] = StyledLetterAvatar;
});

return {
avatarList,
avatarMap,
};
}, [name, size]);
}

export default useLetterAvatars;
export type {LetterAvatarItem, LetterAvatarsResult};
8 changes: 7 additions & 1 deletion src/languages/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7325,7 +7325,13 @@ ${amount} für ${merchant} - ${date}`,
exportInProgress: 'Export läuft',
conciergeWillSend: 'Concierge sendet dir die Datei in Kürze.',
},
avatarPage: {title: 'Profilbild bearbeiten', uploadPhoto: 'Foto hochladen'},
avatarPage: {
title: 'Profilbild bearbeiten',
upload: 'Hochladen',
uploadPhoto: 'Foto hochladen',
selectAvatar: 'Avatar auswählen',
chooseCustomAvatar: 'Oder wählen Sie einen eigenen Avatar',
},
};
// IMPORTANT: This line is manually replaced in generate translation files by scripts/generateTranslations.ts,
// so if you change it here, please update it there as well.
Expand Down
3 changes: 3 additions & 0 deletions src/languages/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1515,7 +1515,10 @@ const translations = {
},
avatarPage: {
title: 'Edit profile picture',
upload: 'Upload',
uploadPhoto: 'Upload photo',
selectAvatar: 'Select avatar',
chooseCustomAvatar: 'Or choose a custom avatar',
},
modal: {
backdropLabel: 'Modal Backdrop',
Expand Down
3 changes: 3 additions & 0 deletions src/languages/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1507,7 +1507,10 @@ const translations = {
},
avatarPage: {
title: 'Editar foto de perfil',
upload: 'Subir',
uploadPhoto: 'Subir foto',
selectAvatar: 'Seleccionar avatar',
chooseCustomAvatar: 'O elige un avatar personalizado',
},
modal: {
backdropLabel: 'Fondo del Modal',
Expand Down
Loading