import { useViewerID } from '@self.id/framework'
import { Avatar, Box, Button, DropButton, Spinner, Text } from 'grommet'
import Link from 'next/link'
import Image from 'next/image'
import { useRouter } from 'next/router'
import { forwardRef, useCallback, useMemo, useState } from 'react'
import type { ForwardedRef } from 'react'
import { useAuthConnection, useViewerProfile } from '../../hooks'
import linkIcon from '../../images/icons/link.svg'
import { formatDID, getImageURL } from '../../utils'
import AvatarPlaceholder from '../AvatarPlaceholder'
type DisplayAvatarProps = {
did?: string
label: string
loading?: boolean
src?: string | null
}
function DisplayAvatar({ did, label, loading, src }: DisplayAvatarProps) {
const avatar = loading ? (
) : src ? (
) : (
)
return (
{avatar}
{label}
)
}
type MenuButtonProps = {
href?: string
label: string
loading?: boolean
onClick?: () => void
}
const MenuButton = forwardRef(function MenuButtonComponent(
{ label, loading, ...props }: MenuButtonProps,
ref: ForwardedRef
) {
return (
) : (
)
}
label={
{label}
}
plain
/>
)
})
export default function AccountButton() {
const router = useRouter()
const [connection, login, logout] = useAuthConnection()
const viewerID = useViewerID()
const profileRecord = useViewerProfile()
const [isMenuOpen, setMenuOpen] = useState(false)
const [isLoadingProfile, setLoadingProfile] = useState(false)
const toProfile = useCallback(
(id: string | null) => {
if (id != null) {
if (router.route === '/[id]' && router.query.id === id) {
// Already on wanted profile page
setMenuOpen(false)
} else {
// Navigate to profile page
setLoadingProfile(true)
void router.push(`/${id}`).then(() => {
setMenuOpen(false)
setLoadingProfile(false)
})
}
}
},
[router]
)
const onClickLogin = useCallback(() => {
if (connection.status !== 'connecting') {
void login().then((self) => {
return self ? toProfile(self.id) : null
})
}
}, [connection.status, login, toProfile])
const [displayName, avatarSrc] = useMemo(() => {
if (viewerID == null) {
return ['', null]
}
const name = profileRecord.content?.name ?? formatDID(viewerID.id)
const src = getImageURL(profileRecord.content?.image, { height: 60, width: 60 })
return [name, src]
}, [viewerID, profileRecord.content])
if (viewerID != null) {
const content = (
{avatarSrc ? (
) : (
)}
{displayName}
toProfile(viewerID.id)}
/>
setMenuOpen(false)} />
logout()} />
)
return (
{
setMenuOpen(false)
}}
onOpen={() => {
setMenuOpen(true)
}}
open={isMenuOpen}>
)
}
return connection.status === 'connecting' ? (
) : (
)
}