manifold/web/components/avatar.tsx

81 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-01-27 23:14:18 +00:00
import Router from 'next/router'
import clsx from 'clsx'
import { MouseEvent, useEffect, useState } from 'react'
2022-06-23 17:55:41 +00:00
import { UserCircleIcon, UserIcon, UsersIcon } from '@heroicons/react/solid'
import Image from 'next/future/image'
2022-01-27 23:14:18 +00:00
export function Avatar(props: {
username?: string
avatarUrl?: string
noLink?: boolean
2022-03-14 21:56:53 +00:00
size?: number | 'xs' | 'sm'
className?: string
2022-01-27 23:14:18 +00:00
}) {
2022-08-15 23:33:02 +00:00
const { username, noLink, size, className } = props
const [avatarUrl, setAvatarUrl] = useState(props.avatarUrl)
useEffect(() => setAvatarUrl(props.avatarUrl), [props.avatarUrl])
2022-03-14 21:56:53 +00:00
const s = size == 'xs' ? 6 : size === 'sm' ? 8 : size || 10
const sizeInPx = s * 4
2022-01-27 23:14:18 +00:00
const onClick =
noLink && username
? undefined
: (e: MouseEvent) => {
2022-01-27 23:14:18 +00:00
e.stopPropagation()
Router.push(`/${username}`)
}
// there can be no avatar URL or username in the feed, we show a "submit comment"
// item with a fake grey user circle guy even if you aren't signed in
return avatarUrl ? (
<Image
width={sizeInPx}
height={sizeInPx}
className={clsx(
2022-06-09 20:00:31 +00:00
'flex-shrink-0 rounded-full bg-white object-cover',
`w-${s} h-${s}`,
!noLink && 'cursor-pointer',
className
)}
2022-07-18 14:34:20 +00:00
style={{ maxWidth: `${s * 0.25}rem` }}
src={avatarUrl}
onClick={onClick}
alt={username}
2022-08-15 23:33:02 +00:00
onError={() => {
// If the image doesn't load, clear the avatarUrl to show the default
// Mostly for localhost, when getting a 403 from googleusercontent
setAvatarUrl('')
}}
/>
) : (
<UserCircleIcon
className={clsx(
`flex-shrink-0 rounded-full bg-white w-${s} h-${s} text-gray-500`,
className
2022-02-04 18:30:56 +00:00
)}
aria-hidden="true"
/>
2022-01-27 23:14:18 +00:00
)
}
2022-06-23 17:55:41 +00:00
export function EmptyAvatar(props: {
className?: string
size?: number
multi?: boolean
}) {
const { className, size = 8, multi } = props
2022-06-23 17:55:41 +00:00
const insize = size - 3
const Icon = multi ? UsersIcon : UserIcon
return (
<div
className={clsx(
`flex flex-shrink-0 h-${size} w-${size} items-center justify-center rounded-full bg-gray-200`,
className
)}
2022-06-23 17:55:41 +00:00
>
<Icon className={`h-${insize} w-${insize} text-gray-500`} aria-hidden />
</div>
)
}