Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

4.7 KB
Raw Blame
import './ProfilePicture.scss'

import clsx from 'clsx'
import { useValues } from 'kea'
import React, { useEffect, useMemo, useRef, useState } from 'react'

import { HedgehogModeProfile } from 'lib/components/HedgehogMode/HedgehogModeStatic'
import { inStorybookTestRunner } from 'lib/utils/dom'
import { gravatarUrl as buildGravatarUrl } from 'lib/utils/gravatar'
import { fullName } from 'lib/utils/strings'
import { userLogic } from 'scenes/userLogic'

import { HedgehogConfig, MinimalHedgehogConfig, UserBasicType } from '~/types'

import { IconRobot } from '../icons'
import { Lettermark, LettermarkColor } from '../Lettermark/Lettermark'

export interface ProfilePictureProps {
    user?:
        | (Pick<Partial<UserBasicType>, 'first_name' | 'email' | 'last_name'> & {
              hedgehog_config?: MinimalHedgehogConfig | HedgehogConfig
          })
        | null
    name?: string
    size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'xxl'
    showName?: boolean
    className?: string
    title?: string
    index?: number
    type?: 'person' | 'bot' | 'system'
    /** Change this value to fetch the Gravatar again, bypassing the browser cache. */
    refreshKey?: number
}

export const ProfilePicture = React.forwardRef<HTMLSpanElement, ProfilePictureProps>(function ProfilePicture(
    { user, name, size = 'lg', showName, className, index, title, type = 'person', refreshKey },
    ref
) {
    const { user: currentUser } = useValues(userLogic)
    const [gravatarLoaded, setGravatarLoaded] = useState<boolean | undefined>()
    const imgRef = useRef<HTMLImageElement>(null)

    let email = user?.email

    if (user) {
        name = fullName(user)
        email = user.email
    }

    const combinedNameAndEmail = name && email ? `${name} <${email}>` : name || email

    const hedgehogProfile = !!user?.hedgehog_config?.use_as_profile

    const gravatarUrl = useMemo(() => {
        if (hedgehogProfile || inStorybookTestRunner()) {
            return // There are no guarantees on how long it takes to fetch a Gravatar, so we skip this in snapshots
        }
        // Check if Gravatar exists
        const identifier = email || (name?.includes('@') ? name : undefined)
        if (identifier) {
            return buildGravatarUrl(identifier, refreshKey)
        }
    }, [email, hedgehogProfile, name, refreshKey])

    useEffect(() => {
        const controller = new AbortController()
        const img = imgRef.current
        if (img) {
            // Check if already loaded before attaching listeners
            if (img.complete) {
                if (img.naturalHeight !== 0) {
                    setGravatarLoaded(true)
                } else {
                    setGravatarLoaded(false)
                }
            }
            const onLoad = (): void => setGravatarLoaded(true)
            const onError = (): void => setGravatarLoaded(false)
            img.addEventListener('load', onLoad, { signal: controller.signal })
            img.addEventListener('error', onError, { signal: controller.signal })
        }
        return () => {
            controller.abort()
        }
    }, [gravatarUrl])

    const pictureComponent = (
        <span className={clsx('ProfilePicture ph-no-capture', size, className)} ref={ref}>
            {hedgehogProfile && user.hedgehog_config ? (
                <HedgehogModeProfile config={user.hedgehog_config} size="100%" />
            ) : (
                gravatarLoaded !== true && (
                    <>
                        {type === 'bot' ? (
                            <IconRobot className="p-0.5" />
                        ) : (
                            <Lettermark
                                name={combinedNameAndEmail}
                                index={index}
                                rounded
                                color={type === 'system' ? LettermarkColor.Gray : undefined}
                            />
                        )}
                    </>
                )
            )}
            {gravatarUrl && gravatarLoaded !== false ? (
                <img
                    ref={imgRef}
                    className="absolute top-0 left-0 w-full h-full rounded-full"
                    src={gravatarUrl}
                    loading="lazy"
                    title={title || `This is the Gravatar for ${combinedNameAndEmail}`}
                    alt=""
                />
            ) : null}
        </span>
    )

    return !showName ? (
        pictureComponent
    ) : (
        <div className="profile-package" title={combinedNameAndEmail}>
            {pictureComponent}
            <span className="ph-no-capture profile-name">
                {currentUser?.email === email ? 'you' : name || email || 'an unknown user'}
            </span>
        </div>
    )
})