// Copyright 2021 Signal Messenger, LLC // SPDX-License-Identifier: AGPL-3.0-only import React, { useCallback, useEffect, useRef, useState } from 'react'; import * as log from '../logging/log'; import type { AvatarColorType } from '../types/Colors'; import { AvatarColors } from '../types/Colors'; import type { AvatarDataType, DeleteAvatarFromDiskActionType, ReplaceAvatarActionType, SaveAvatarToDiskActionType, } from '../types/Avatar'; import { AvatarEditor } from './AvatarEditor'; import { AvatarPreview } from './AvatarPreview'; import { Button, ButtonVariant } from './Button'; import { ConfirmDiscardDialog } from './ConfirmDiscardDialog'; import { Emoji } from './emoji/Emoji'; import type { Props as EmojiButtonProps } from './emoji/EmojiButton'; import { EmojiButton } from './emoji/EmojiButton'; import type { EmojiPickDataType } from './emoji/EmojiPicker'; import { Input } from './Input'; import { Intl } from './Intl'; import type { LocalizerType, ReplacementValuesType } from '../types/Util'; import { Modal } from './Modal'; import { PanelRow } from './conversation/conversation-details/PanelRow'; import type { ProfileDataType } from '../state/ducks/conversations'; import { getEmojiData, unifiedToEmoji } from './emoji/lib'; import { missingCaseError } from '../util/missingCaseError'; import { ConfirmationDialog } from './ConfirmationDialog'; import { ConversationDetailsIcon, IconType, } from './conversation/conversation-details/ConversationDetailsIcon'; import { Spinner } from './Spinner'; import { UsernameSaveState } from '../state/ducks/conversationsEnums'; export enum EditState { None = 'None', BetterAvatar = 'BetterAvatar', ProfileName = 'ProfileName', Bio = 'Bio', Username = 'Username', } enum UsernameEditState { Editing = 'Editing', ConfirmingDelete = 'ConfirmingDelete', ShowingErrorPopup = 'ShowingErrorPopup', Saving = 'Saving', } type PropsExternalType = { onEditStateChanged: (editState: EditState) => unknown; onProfileChanged: ( profileData: ProfileDataType, avatarBuffer?: Uint8Array ) => unknown; }; export type PropsDataType = { aboutEmoji?: string; aboutText?: string; avatarPath?: string; color?: AvatarColorType; conversationId: string; familyName?: string; firstName: string; i18n: LocalizerType; isUsernameFlagEnabled: boolean; usernameSaveState: UsernameSaveState; userAvatarData: Array; username?: string; } & Pick; type PropsActionType = { clearUsernameSave: () => unknown; deleteAvatarFromDisk: DeleteAvatarFromDiskActionType; onSetSkinTone: (tone: number) => unknown; replaceAvatar: ReplaceAvatarActionType; saveAvatarToDisk: SaveAvatarToDiskActionType; saveUsername: (options: { username: string | undefined; previousUsername: string | undefined; }) => unknown; }; export type PropsType = PropsDataType & PropsActionType & PropsExternalType; type DefaultBio = { i18nLabel: string; shortName: string; }; const DEFAULT_BIOS: Array = [ { i18nLabel: 'Bio--speak-freely', shortName: 'wave', }, { i18nLabel: 'Bio--encrypted', shortName: 'zipper_mouth_face', }, { i18nLabel: 'Bio--free-to-chat', shortName: '+1', }, { i18nLabel: 'Bio--coffee-lover', shortName: 'coffee', }, { i18nLabel: 'Bio--taking-break', shortName: 'mobile_phone_off', }, ]; function getUsernameInvalidKey( username: string | undefined ): { key: string; replacements?: ReplacementValuesType } | undefined { if (!username) { return undefined; } const min = 3; if (username.length < min) { return { key: 'ProfileEditor--username--check-character-min', replacements: { min }, }; } if (!/^[0-9a-z_]+$/.test(username)) { return { key: 'ProfileEditor--username--check-characters' }; } if (/^[0-9]/.test(username)) { return { key: 'ProfileEditor--username--check-starting-character' }; } const max = 25; if (username.length > max) { return { key: 'ProfileEditor--username--check-character-max', replacements: { max }, }; } return undefined; } function mapSaveStateToEditState({ clearUsernameSave, i18n, setEditState, setUsernameEditState, setUsernameError, usernameSaveState, }: { clearUsernameSave: () => unknown; i18n: LocalizerType; setEditState: (state: EditState) => unknown; setUsernameEditState: (state: UsernameEditState) => unknown; setUsernameError: (errorText: string) => unknown; usernameSaveState: UsernameSaveState; }): void { if (usernameSaveState === UsernameSaveState.None) { return; } if (usernameSaveState === UsernameSaveState.Saving) { setUsernameEditState(UsernameEditState.Saving); return; } clearUsernameSave(); if (usernameSaveState === UsernameSaveState.Success) { setEditState(EditState.None); setUsernameEditState(UsernameEditState.Editing); return; } if (usernameSaveState === UsernameSaveState.UsernameMalformedError) { setUsernameEditState(UsernameEditState.Editing); setUsernameError(i18n('ProfileEditor--username--check-characters')); return; } if (usernameSaveState === UsernameSaveState.UsernameTakenError) { setUsernameEditState(UsernameEditState.Editing); setUsernameError(i18n('ProfileEditor--username--check-username-taken')); return; } if (usernameSaveState === UsernameSaveState.GeneralError) { setUsernameEditState(UsernameEditState.ShowingErrorPopup); return; } if (usernameSaveState === UsernameSaveState.DeleteFailed) { setUsernameEditState(UsernameEditState.Editing); return; } const state: never = usernameSaveState; log.error( `ProfileEditor: useEffect username didn't handle usernameSaveState '${state})'` ); setEditState(EditState.None); } export const ProfileEditor = ({ aboutEmoji, aboutText, avatarPath, clearUsernameSave, color, conversationId, deleteAvatarFromDisk, familyName, firstName, i18n, isUsernameFlagEnabled, onEditStateChanged, onProfileChanged, onSetSkinTone, recentEmojis, replaceAvatar, saveAvatarToDisk, saveUsername, skinTone, userAvatarData, username, usernameSaveState, }: PropsType): JSX.Element => { const focusInputRef = useRef(null); const [editState, setEditState] = useState(EditState.None); const [confirmDiscardAction, setConfirmDiscardAction] = useState< (() => unknown) | undefined >(undefined); // This is here to avoid component re-render jitters in the time it takes // redux to come back with the correct state const [fullName, setFullName] = useState({ familyName, firstName, }); const [fullBio, setFullBio] = useState({ aboutEmoji, aboutText, }); const [newUsername, setNewUsername] = useState(username); const [usernameError, setUsernameError] = useState(); const [usernameEditState, setUsernameEditState] = useState( UsernameEditState.Editing ); const [avatarBuffer, setAvatarBuffer] = useState( undefined ); const [stagedProfile, setStagedProfile] = useState({ aboutEmoji, aboutText, familyName, firstName, }); // To make AvatarEditor re-render less often const handleBack = useCallback(() => { setEditState(EditState.None); onEditStateChanged(EditState.None); }, [setEditState, onEditStateChanged]); // To make EmojiButton re-render less often const setAboutEmoji = useCallback( (ev: EmojiPickDataType) => { const emojiData = getEmojiData(ev.shortName, skinTone); setStagedProfile(profileData => ({ ...profileData, aboutEmoji: unifiedToEmoji(emojiData.unified), })); }, [setStagedProfile, skinTone] ); // To make AvatarEditor re-render less often const handleAvatarChanged = useCallback( (avatar: Uint8Array | undefined) => { setAvatarBuffer(avatar); setEditState(EditState.None); onProfileChanged(stagedProfile, avatar); }, [onProfileChanged, stagedProfile] ); const getFullNameText = () => { return [fullName.firstName, fullName.familyName].filter(Boolean).join(' '); }; useEffect(() => { const focusNode = focusInputRef.current; if (!focusNode) { return; } focusNode.focus(); focusNode.setSelectionRange(focusNode.value.length, focusNode.value.length); }, [editState]); useEffect(() => { onEditStateChanged(editState); }, [editState, onEditStateChanged]); // If there's some in-process username save, or just an unacknowledged save // completion/error, we clear it out on mount, and then again on unmount. useEffect(() => { clearUsernameSave(); return () => { clearUsernameSave(); }; }); useEffect(() => { mapSaveStateToEditState({ clearUsernameSave, i18n, setEditState, setUsernameEditState, setUsernameError, usernameSaveState, }); }, [ clearUsernameSave, i18n, setEditState, setUsernameEditState, setUsernameError, usernameSaveState, ]); useEffect(() => { // Whenever the user makes a change, we'll get rid of the red error text setUsernameError(undefined); // And then we'll check the validity of that new username const timeout = setTimeout(() => { const key = getUsernameInvalidKey(newUsername); if (key) { setUsernameError(i18n(key.key, key.replacements)); } }, 1000); return () => { clearTimeout(timeout); }; }, [newUsername, i18n, setUsernameError]); const isCurrentlySaving = usernameEditState === UsernameEditState.Saving; const shouldDisableUsernameSave = Boolean( newUsername === username || !newUsername || usernameError || isCurrentlySaving ); const checkThenSaveUsername = () => { if (isCurrentlySaving) { log.error('checkThenSaveUsername: Already saving! Returning early'); return; } if (shouldDisableUsernameSave) { return; } const invalidKey = getUsernameInvalidKey(newUsername); if (invalidKey) { setUsernameError(i18n(invalidKey.key, invalidKey.replacements)); return; } setUsernameError(undefined); setUsernameEditState(UsernameEditState.Saving); saveUsername({ username: newUsername, previousUsername: username }); }; const deleteUsername = () => { if (isCurrentlySaving) { log.error('deleteUsername: Already saving! Returning early'); return; } setNewUsername(undefined); setUsernameError(undefined); setUsernameEditState(UsernameEditState.Saving); saveUsername({ username: undefined, previousUsername: username }); }; // To make AvatarEditor re-render less often const handleAvatarLoaded = useCallback(avatar => { setAvatarBuffer(avatar); }, []); let content: JSX.Element; if (editState === EditState.BetterAvatar) { content = ( ); } else if (editState === EditState.ProfileName) { const shouldDisableSave = !stagedProfile.firstName || (stagedProfile.firstName === fullName.firstName && stagedProfile.familyName === fullName.familyName); content = ( <> { setStagedProfile(profileData => ({ ...profileData, firstName: String(newFirstName), })); }} placeholder={i18n('ProfileEditor--first-name')} ref={focusInputRef} value={stagedProfile.firstName} /> { setStagedProfile(profileData => ({ ...profileData, familyName: newFamilyName, })); }} placeholder={i18n('ProfileEditor--last-name')} value={stagedProfile.familyName} /> ); } else if (editState === EditState.Bio) { const shouldDisableSave = stagedProfile.aboutText === fullBio.aboutText && stagedProfile.aboutEmoji === fullBio.aboutEmoji; content = ( <> } maxLengthCount={140} maxByteCount={512} moduleClassName="ProfileEditor__about-input" onChange={value => { if (value) { setStagedProfile(profileData => ({ ...profileData, aboutEmoji: stagedProfile.aboutEmoji, aboutText: value.replace(/(\r\n|\n|\r)/gm, ''), })); } else { setStagedProfile(profileData => ({ ...profileData, aboutEmoji: undefined, aboutText: '', })); } }} ref={focusInputRef} placeholder={i18n('ProfileEditor--about-placeholder')} value={stagedProfile.aboutText} whenToShowRemainingCount={40} /> {DEFAULT_BIOS.map(defaultBio => ( } label={i18n(defaultBio.i18nLabel)} onClick={() => { const emojiData = getEmojiData(defaultBio.shortName, skinTone); setStagedProfile(profileData => ({ ...profileData, aboutEmoji: unifiedToEmoji(emojiData.unified), aboutText: i18n(defaultBio.i18nLabel), })); }} /> ))} ); } else if (editState === EditState.Username) { content = ( <> { setUsernameError(undefined); setNewUsername(changedUsername); }} onEnter={checkThenSaveUsername} placeholder={i18n('ProfileEditor--username--placeholder')} ref={focusInputRef} value={newUsername} />
{usernameError}
); } else if (editState === EditState.None) { content = ( <> { setEditState(EditState.BetterAvatar); }} style={{ height: 80, width: 80, }} />
} label={getFullNameText()} onClick={() => { setEditState(EditState.ProfileName); }} /> {isUsernameFlagEnabled ? ( } label={username || i18n('ProfileEditor--username')} onClick={ usernameEditState !== UsernameEditState.Saving ? () => { setNewUsername(username); setEditState(EditState.Username); } : undefined } actions={ username ? ( { setUsernameEditState(UsernameEditState.ConfirmingDelete); }} /> ) : null } /> ) : null} ) : ( ) } label={fullBio.aboutText || i18n('ProfileEditor--about')} onClick={() => { setEditState(EditState.Bio); }} />
{i18n('ProfileEditor--learnMore')} ), }} />
); } else { throw missingCaseError(editState); } return ( <> {usernameEditState === UsernameEditState.ConfirmingDelete && ( setUsernameEditState(UsernameEditState.Editing)} actions={[ { text: i18n('ProfileEditor--username--confirm-delete-button'), style: 'negative', action: () => deleteUsername(), }, ]} > {i18n('ProfileEditor--username--confirm-delete-body')} )} {usernameEditState === UsernameEditState.ShowingErrorPopup && ( setUsernameEditState(UsernameEditState.Editing)} > {i18n('ProfileEditor--username--general-error')} )} {confirmDiscardAction && ( setConfirmDiscardAction(undefined)} /> )}
{content}
); };