refactor: split avatar component to handle displaynames

Signed-off-by: Tilman Vatteroth <git@tilmanvatteroth.de>
This commit is contained in:
Tilman Vatteroth 2023-03-24 13:16:35 +01:00
parent 3a06f84af1
commit e97a426680
9 changed files with 88 additions and 44 deletions

View file

@ -4,15 +4,14 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { getUser } from '../../../api/users'
import type { UserInfo } from '../../../api/users/types'
import { AsyncLoadingBoundary } from '../async-loading-boundary/async-loading-boundary'
import type { UserAvatarProps } from './user-avatar'
import { UserAvatar } from './user-avatar'
import React from 'react'
import React, { Fragment, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { useAsync } from 'react-use'
export interface UserAvatarForUsernameProps extends Omit<UserAvatarProps, 'user'> {
export interface UserAvatarForUsernameProps extends Omit<UserAvatarProps, 'photoUrl' | 'displayName'> {
username: string | null
}
@ -27,20 +26,21 @@ export interface UserAvatarForUsernameProps extends Omit<UserAvatarProps, 'user'
*/
export const UserAvatarForUsername: React.FC<UserAvatarForUsernameProps> = ({ username, ...props }) => {
const { t } = useTranslation()
const { error, value, loading } = useAsync(async (): Promise<UserInfo> => {
if (username) {
return await getUser(username)
}
return {
displayName: t('common.guestUser'),
photo: `public/img/avatar.png`,
username: ''
}
const { error, value, loading } = useAsync(async (): Promise<{ displayName: string; photo?: string }> => {
return username
? await getUser(username)
: {
displayName: t('common.guestUser')
}
}, [username, t])
const avatar = useMemo(() => {
return !value ? <Fragment /> : <UserAvatar displayName={value.displayName} photoUrl={value.photo} {...props} />
}, [props, value])
return (
<AsyncLoadingBoundary loading={loading || !value} error={error} componentName={'UserAvatarForUsername'}>
<UserAvatar user={value as UserInfo} {...props} />
{avatar}
</AsyncLoadingBoundary>
)
}