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.

feat(settings): add profile picture section to profile settings (#93080)

Charles Vien7e12bc860fb6
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index fee40fc51e22..1884988a0136 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -8381,9 +8381,13 @@ snapshots:
scenes-app-settings-user--settings-user-notifications--light:
hash: v1.k794b7964.22b7ef8dce439a47cc7ca3da644d7f647f2615a7b16c3a55a0837dcea0f3cc2a.QnD-njyuDUa0lrABBsIuNCY8TExZql8lQCQBW7Vw6q4
scenes-app-settings-user--settings-user-profile--dark:
- hash: v1.k794b7964.f6aff3447ed345a76c38966128dde52e4b99f4f2ba1475a003b3763a2b1d5696.MK6D9UYCfHMCwIkX_YDsPSshVAWGmrLqBB3iwvHpIdo
+ hash: v1.k794b7964.477a820fd8ddcbd96fb4789d7407a6e21d1b37d889323e8bdcfcb7b4c1b2215c.OiIp-MDSCgN7eFiofAkbaB_vFBF9lVAd-E6rXlfI40A
scenes-app-settings-user--settings-user-profile--light:
- hash: v1.k794b7964.309e988a79cb7d9d505a2d53fa80e874d244058708999c3ba594fecf58590dff.eLlA-q2geaN4iT6sG9eHkMQ99d-KBXtPM-l564tEEvQ
+ hash: v1.k794b7964.c5b1e953a68dcc2a7440de9061298b07a705a4f786b1948f385ff364fecd76bb.tpJwhfDqbEMdWhFcueay9wUV0sTGjxBSyQ63IWZgSqs
+ scenes-app-settings-user--settings-user-profile-hedgehog-avatar--dark:
+ hash: v1.k794b7964.c4331c34e1eca9ef27b39bf54eb2f63d1938d5860c58761289ef6f22553298b7.-fUQly4FV_2sclXXFOsbFrLvj52Hy1jGHUPvsBuyAdE
+ scenes-app-settings-user--settings-user-profile-hedgehog-avatar--light:
+ hash: v1.k794b7964.21df030ff0d23324c716f8da3ba1bcb157eda37de4456006591d24c4be43799a.VY-j0yn8MJtQDqWoRtkbNdH2rc1dZ6zRp3n8yfUJf3c
scenes-app-settings-user--settings-user-reminders-modal--dark:
hash: v1.k794b7964.242ae233bc621d826310883788ad4e89b47d5d9d9c2c09279c675165f94384ce.nApdQbX5odqe7aMVihM5X4WlwlneicqcFebSJ_N1hVE
scenes-app-settings-user--settings-user-reminders-modal--light:
diff --git a/frontend/src/lib/lemon-ui/ProfilePicture/ProfilePicture.tsx b/frontend/src/lib/lemon-ui/ProfilePicture/ProfilePicture.tsx
index 57af5c0e5c0b..1c3ed0012590 100644
--- a/frontend/src/lib/lemon-ui/ProfilePicture/ProfilePicture.tsx
+++ b/frontend/src/lib/lemon-ui/ProfilePicture/ProfilePicture.tsx
@@ -2,11 +2,11 @@ import './ProfilePicture.scss'
import clsx from 'clsx'
import { useValues } from 'kea'
-import md5 from 'md5'
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'
@@ -28,10 +28,12 @@ export interface ProfilePictureProps {
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' },
+ { user, name, size = 'lg', showName, className, index, title, type = 'person', refreshKey },
ref
) {
const { user: currentUser } = useValues(userLogic)
@@ -56,10 +58,9 @@ export const ProfilePicture = React.forwardRef<HTMLSpanElement, ProfilePicturePr
// Check if Gravatar exists
const identifier = email || (name?.includes('@') ? name : undefined)
if (identifier) {
- const hash = md5(identifier.trim().toLowerCase())
- return `https://www.gravatar.com/avatar/${hash}?s=96&d=404`
+ return buildGravatarUrl(identifier, refreshKey)
}
- }, [email, hedgehogProfile, name])
+ }, [email, hedgehogProfile, name, refreshKey])
useEffect(() => {
const controller = new AbortController()
diff --git a/frontend/src/lib/utils/gravatar.ts b/frontend/src/lib/utils/gravatar.ts
new file mode 100644
index 000000000000..8c1897e439e3
--- /dev/null
+++ b/frontend/src/lib/utils/gravatar.ts
@@ -0,0 +1,18 @@
+import md5 from 'md5'
+
+export const GRAVATAR_MANAGE_URL = 'https://gravatar.com/profile/avatars'
+
+export function gravatarUrl(identifier: string, refreshKey?: number): string {
+ const hash = md5(identifier.trim().toLowerCase())
+ const url = `https://www.gravatar.com/avatar/${hash}?s=96&d=404`
+ return refreshKey ? `${url}&_=${refreshKey}` : url
+}
+
+export function probeImage(url: string): Promise<boolean> {
+ return new Promise((resolve) => {
+ const image = new Image()
+ image.onload = () => resolve(true)
+ image.onerror = () => resolve(false)
+ image.src = url
+ })
+}
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index 84ddef59a2d5..cd148e95ec4c 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -178,6 +178,7 @@ import { OptOutCapture } from './user/OptOutCapture'
import { PasskeySettings } from './user/PasskeySettings'
import { PersonalAPIKeys } from './user/PersonalAPIKeys'
import { PersonalGitHubIntegrations, PersonalSlackIntegrations } from './user/PersonalIntegrations'
+import { ProfilePictureSettings } from './user/ProfilePictureSettings'
import { RealtimeNotificationPreferences } from './user/RealtimeNotificationPreferences'
import { Reminders } from './user/Reminders'
import { SidebarAutoSuggestSetting } from './user/SidebarProductSettings'
@@ -2014,6 +2015,12 @@ export const SETTINGS_MAP: SettingSection[] = [
id: 'user-profile',
title: 'Profile',
settings: [
+ {
+ id: 'profile-picture',
+ title: 'Profile picture',
+ component: <ProfilePictureSettings />,
+ keywords: ['avatar', 'gravatar', 'photo', 'picture', 'image', 'profile'],
+ },
{
id: 'details',
title: 'Details',
diff --git a/frontend/src/scenes/settings/stories/SettingsUser.stories.tsx b/frontend/src/scenes/settings/stories/SettingsUser.stories.tsx
index e0858a2d2f36..6403887143fb 100644
--- a/frontend/src/scenes/settings/stories/SettingsUser.stories.tsx
+++ b/frontend/src/scenes/settings/stories/SettingsUser.stories.tsx
@@ -1,4 +1,4 @@
-import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_TEAM, MOCK_DEFAULT_USER } from 'lib/api.mock'
import type { Meta, StoryObj } from '@storybook/react'
import { within } from '@testing-library/dom'
@@ -10,7 +10,9 @@ import { App } from 'scenes/App'
import { urls } from 'scenes/urls'
import { mswDecorator } from '~/mocks/browser'
+import { getAvailableProductFeatures } from '~/mocks/features'
import preflightJson from '~/mocks/fixtures/_preflight.json'
+import { HedgehogConfig } from '~/types'
import { SettingSectionId } from '../types'
@@ -36,6 +38,26 @@ const meta: Meta<StoryProps> = {
realm: 'cloud',
},
'/api/projects/:id/integrations': { results: [] },
+ '/api/users/@me/login_sessions/': [
+ {
+ id: '0190a1b2-0000-7000-8000-000000000001',
+ device: 'Chrome 113 on Mac OS X 13.4',
+ location: 'San Francisco, United States',
+ login_method: 'password',
+ created_at: '2023-05-20T10:00:00Z',
+ last_activity: '2023-05-25T09:00:00Z',
+ is_current: true,
+ },
+ {
+ id: '0190a1b2-0000-7000-8000-000000000002',
+ device: 'Firefox 113 on Windows 11',
+ location: 'London, United Kingdom',
+ login_method: 'google-oauth2',
+ created_at: '2023-05-10T10:00:00Z',
+ last_activity: '2023-05-24T09:00:00Z',
+ is_current: false,
+ },
+ ],
},
patch: {
'/api/projects/:id': async ({ request }) => {
@@ -63,6 +85,37 @@ export const SettingsUserProfile: Story = {
args: { sectionId: 'user-profile' },
}
+const HEDGEHOG_AVATAR_CONFIG: HedgehogConfig = {
+ version: 2,
+ enabled: false,
+ use_as_profile: true,
+ party_mode_enabled: false,
+ actor_options: { id: 'storybook-hedgehog', skin: 'default', color: 'green', accessories: ['tophat', 'sunglasses'] },
+}
+
+export const SettingsUserProfileHedgehogAvatar: Story = {
+ args: { sectionId: 'user-profile' },
+ parameters: {
+ msw: {
+ mocks: {
+ get: {
+ '/api/users/@me/': () => [
+ 200,
+ {
+ ...MOCK_DEFAULT_USER,
+ organization: {
+ ...MOCK_DEFAULT_ORGANIZATION,
+ available_product_features: getAvailableProductFeatures(),
+ },
+ hedgehog_config: HEDGEHOG_AVATAR_CONFIG,
+ },
+ ],
+ },
+ },
+ },
+ },
+}
+
export const SettingsUserApiKeys: Story = {
args: { sectionId: 'user-api-keys' },
}
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index efef9e57913f..13c268b1df50 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -236,6 +236,7 @@ export type SettingId =
| 'reminders'
| 'persons-on-events'
| 'posthog-mcp-configure'
+ | 'profile-picture'
| 'project-delete'
| 'project-move'
| 'realtime-notifications'
diff --git a/frontend/src/scenes/settings/user/LoginSessions.tsx b/frontend/src/scenes/settings/user/LoginSessions.tsx
index fd2c27e10f35..7a3a1a9cb77d 100644
--- a/frontend/src/scenes/settings/user/LoginSessions.tsx
+++ b/frontend/src/scenes/settings/user/LoginSessions.tsx
@@ -46,19 +46,19 @@ export function LoginSessions(): JSX.Element {
}
return (
- <div className="flex flex-col gap-2">
- <div className="flex justify-end">
- <LemonButton
- type="secondary"
- status="danger"
- size="small"
- loading={loginSessionsLoading}
- disabledReason={hasOtherSessions ? undefined : 'No other devices to log out'}
- onClick={handleRevokeOthers}
- >
- Log out everywhere else
- </LemonButton>
- </div>
+ <div className="flex flex-col gap-4">
+ <LemonButton
+ type="secondary"
+ status="danger"
+ icon={<IconLeave />}
+ className="self-start"
+ loading={loginSessionsLoading}
+ disabledReason={hasOtherSessions ? undefined : 'No other devices to log out'}
+ onClick={handleRevokeOthers}
+ data-attr="login-sessions-revoke-others"
+ >
+ Log out everywhere else
+ </LemonButton>
<LemonTable
dataSource={loginSessions}
loading={loginSessionsLoading}
diff --git a/frontend/src/scenes/settings/user/ProfilePictureSettings.tsx b/frontend/src/scenes/settings/user/ProfilePictureSettings.tsx
new file mode 100644
index 000000000000..d988ab36ff4d
--- /dev/null
+++ b/frontend/src/scenes/settings/user/ProfilePictureSettings.tsx
@@ -0,0 +1,93 @@
+import { useActions, useValues } from 'kea'
+
+import { IconRefresh } from '@posthog/icons'
+import { LemonButton, ProfilePicture } from '@posthog/lemon-ui'
+
+import { GRAVATAR_MANAGE_URL } from 'lib/utils/gravatar'
+import { urls } from 'scenes/urls'
+import { userLogic } from 'scenes/userLogic'
+
+import { GravatarStatus, profilePictureLogic } from './profilePictureLogic'
+
+function gravatarDescription(status: GravatarStatus, email: string): JSX.Element {
+ const maskedEmail = <span className="ph-no-capture">{email}</span>
+ switch (status) {
+ case 'unknown':
+ return <>Checking Gravatar for {maskedEmail}.</>
+ case 'found':
+ return (
+ <>
+ This picture comes from Gravatar, matched to {maskedEmail}. Change it there, then check again to see
+ it here.
+ </>
+ )
+ case 'missing':
+ return (
+ <>
+ No picture yet. Add one on Gravatar for {maskedEmail} and it shows here and anywhere teammates see
+ you.
+ </>
+ )
+ }
+}
+
+export function ProfilePictureSettings(): JSX.Element {
+ const { user } = useValues(userLogic)
+ const { gravatarStatus, gravatarChecking, gravatarEmail, gravatarRefreshKey, usesHedgehogAsProfilePicture } =
+ useValues(profilePictureLogic)
+ const { recheckGravatar } = useActions(profilePictureLogic)
+
+ const email = user?.email || 'your email'
+
+ return (
+ <div className="flex items-center gap-4">
+ <ProfilePicture
+ key={`${gravatarEmail}:${gravatarRefreshKey}`}
+ user={user}
+ size="xxl"
+ refreshKey={gravatarRefreshKey}
+ />
+ <div className="flex min-w-0 flex-col gap-2">
+ {usesHedgehogAsProfilePicture ? (
+ <>
+ <p className="m-0 text-sm text-secondary">
+ Your hedgehog is your profile picture. Turn that off to show your Gravatar instead.
+ </p>
+ <div className="flex flex-wrap gap-2">
+ <LemonButton
+ type="secondary"
+ to={urls.settings('user-customization', 'hedgehog-mode')}
+ data-attr="settings-profile-picture-hedgehog"
+ >
+ Hedgehog mode settings
+ </LemonButton>
+ </div>
+ </>
+ ) : (
+ <>
+ <p className="m-0 text-sm text-secondary">{gravatarDescription(gravatarStatus, email)}</p>
+ <div className="flex flex-wrap gap-2">
+ <LemonButton
+ type="secondary"
+ to={GRAVATAR_MANAGE_URL}
+ targetBlank
+ data-attr="settings-profile-picture-gravatar"
+ >
+ {gravatarStatus === 'found' ? 'Change on Gravatar' : 'Add on Gravatar'}
+ </LemonButton>
+ <LemonButton
+ type="secondary"
+ icon={<IconRefresh />}
+ loading={gravatarChecking}
+ onClick={recheckGravatar}
+ data-attr="settings-profile-picture-refresh"
+ >
+ Check again
+ </LemonButton>
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/settings/user/profilePictureLogic.test.ts b/frontend/src/scenes/settings/user/profilePictureLogic.test.ts
new file mode 100644
index 000000000000..040ed62868cd
--- /dev/null
+++ b/frontend/src/scenes/settings/user/profilePictureLogic.test.ts
@@ -0,0 +1,108 @@
+import { MOCK_DEFAULT_USER } from 'lib/api.mock'
+
+import { expectLogic } from 'kea-test-utils'
+
+import { userLogic } from 'scenes/userLogic'
+
+import { initKeaTests } from '~/test/init'
+import { HedgehogConfig } from '~/types'
+
+import { GravatarStatus, profilePictureLogic } from './profilePictureLogic'
+
+type ImageOutcome = 'load' | 'error'
+
+let imageOutcome: ImageOutcome = 'error'
+let requestedUrls: string[] = []
+
+class FakeImage {
+ onload: (() => void) | null = null
+ onerror: (() => void) | null = null
+
+ set src(value: string) {
+ requestedUrls.push(value)
+ setTimeout(() => (imageOutcome === 'load' ? this.onload?.() : this.onerror?.()), 0)
+ }
+}
+
+const HEDGEHOG_AVATAR_CONFIG: HedgehogConfig = {
+ version: 2,
+ enabled: false,
+ use_as_profile: true,
+ party_mode_enabled: false,
+ actor_options: { id: 'test-hedgehog', skin: 'default', color: 'green', accessories: [] },
+}
+
+describe('profilePictureLogic', () => {
+ let logic: ReturnType<typeof profilePictureLogic.build>
+ const RealImage = window.Image
+
+ beforeAll(() => {
+ window.Image = FakeImage as unknown as typeof Image
+ })
+
+ afterAll(() => {
+ window.Image = RealImage
+ })
+
+ beforeEach(() => {
+ initKeaTests()
+ requestedUrls = []
+ logic = profilePictureLogic()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ })
+
+ it.each<[GravatarStatus, ImageOutcome]>([
+ ['found', 'load'],
+ ['missing', 'error'],
+ ])('marks the gravatar as %s when the image fires %s', async (status, outcome) => {
+ imageOutcome = outcome
+ logic.mount()
+
+ await expectLogic(logic)
+ .toDispatchActions(['checkGravatar', 'setGravatarStatus'])
+ .toMatchValues({ gravatarStatus: status, gravatarChecking: false })
+ })
+
+ it('does not contact Gravatar when the hedgehog is the profile picture', async () => {
+ userLogic.mount()
+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, hedgehog_config: HEDGEHOG_AVATAR_CONFIG })
+ logic.mount()
+
+ await expectLogic(logic)
+ .toDispatchActions(['checkGravatar', 'setGravatarStatus'])
+ .toMatchValues({ gravatarChecking: false, gravatarStatus: 'unknown', usesHedgehogAsProfilePicture: true })
+ expect(requestedUrls).toEqual([])
+ })
+
+ it('probes again when the email changes', async () => {
+ imageOutcome = 'load'
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['setGravatarStatus']).toMatchValues({ gravatarStatus: 'found' })
+
+ imageOutcome = 'error'
+ userLogic.actions.loadUserSuccess({ ...MOCK_DEFAULT_USER, email: '[email protected]' })
+
+ await expectLogic(logic)
+ .toDispatchActions(['checkGravatar', 'setGravatarStatus'])
+ .toMatchValues({ gravatarStatus: 'missing' })
+ })
+
+ it('bypasses the browser cache when checking again', async () => {
+ imageOutcome = 'load'
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['setGravatarStatus'])
+ expect(requestedUrls[0]).not.toContain('&_=')
+
+ imageOutcome = 'error'
+ logic.actions.recheckGravatar()
+
+ await expectLogic(logic).toMatchValues({ gravatarChecking: true, gravatarStatus: 'found' })
+ await expectLogic(logic)
+ .toDispatchActions(['setGravatarStatus'])
+ .toMatchValues({ gravatarChecking: false, gravatarStatus: 'missing' })
+ expect(requestedUrls[1]).toContain(`&_=${logic.values.gravatarRefreshKey}`)
+ })
+})
diff --git a/frontend/src/scenes/settings/user/profilePictureLogic.ts b/frontend/src/scenes/settings/user/profilePictureLogic.ts
new file mode 100644
index 000000000000..cd4a44bdd37d
--- /dev/null
+++ b/frontend/src/scenes/settings/user/profilePictureLogic.ts
@@ -0,0 +1,185 @@
+import {
+ MakeLogicType,
+ actions,
+ afterMount,
+ connect,
+ kea,
+ listeners,
+ path,
+ reducers,
+ selectors,
+ sharedListeners,
+} from 'kea'
+import type { BreakPointFunction } from 'kea'
+
+import { gravatarUrl, probeImage } from 'lib/utils/gravatar'
+import { userLogic } from 'scenes/userLogic'
+
+import { UserType } from '~/types'
+
+export type GravatarStatus = 'unknown' | 'found' | 'missing'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface profilePictureLogicValues {
+ user: UserType | null // userLogic
+ gravatarChecking: boolean
+ gravatarEmail: string | null
+ gravatarRefreshKey: number
+ gravatarStatus: GravatarStatus
+ usesHedgehogAsProfilePicture: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface profilePictureLogicActions {
+ loadUserSuccess: (
+ user: UserType | null,
+ payload?:
+ | {
+ resetOnFailure: boolean | undefined
+ }
+ | undefined
+ ) => {
+ payload?: {
+ resetOnFailure: boolean | undefined
+ }
+ user: UserType | null
+ } // userLogic
+ updateUserSuccess: (
+ user: UserType,
+ payload?:
+ | {
+ successCallback: (() => void) | undefined
+ user: Partial<UserType>
+ }
+ | undefined
+ ) => {
+ payload?: {
+ successCallback: (() => void) | undefined
+ user: Partial<UserType>
+ }
+ user: UserType
+ } // userLogic
+ checkGravatar: () => {
+ value: true
+ }
+ recheckGravatar: () => {
+ refreshKey: number
+ }
+ setGravatarStatus: (status: GravatarStatus) => {
+ status: GravatarStatus
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface profilePictureLogicMeta {
+ sharedListeners: {
+ probeGravatar: (
+ payload: any,
+ breakpoint: BreakPointFunction,
+ action: {
+ type: string
+ payload: any
+ },
+ previousState: any
+ ) => void | Promise<void>
+ probeGravatarIfUserChanged: (
+ payload: any,
+ breakpoint: BreakPointFunction,
+ action: {
+ type: string
+ payload: any
+ },
+ previousState: any
+ ) => void | Promise<void>
+ }
+ __keaTypeGenInternalSelectorTypes: {
+ gravatarEmail: (user: UserType | null) => string | null
+ usesHedgehogAsProfilePicture: (user: UserType | null) => boolean
+ }
+}
+
+export type profilePictureLogicType = MakeLogicType<
+ profilePictureLogicValues,
+ profilePictureLogicActions,
+ Record<string, any>,
+ profilePictureLogicMeta
+>
+
+export const profilePictureLogic = kea<profilePictureLogicType>([
+ path(['scenes', 'settings', 'user', 'profilePictureLogic']),
+ connect(() => ({
+ values: [userLogic, ['user']],
+ actions: [userLogic, ['loadUserSuccess', 'updateUserSuccess']],
+ })),
+ actions({
+ checkGravatar: true,
+ recheckGravatar: () => ({ refreshKey: Date.now() }),
+ setGravatarStatus: (status: GravatarStatus) => ({ status }),
+ }),
+ reducers({
+ gravatarStatus: [
+ 'unknown' as GravatarStatus,
+ {
+ checkGravatar: () => 'unknown',
+ setGravatarStatus: (_, { status }) => status,
+ },
+ ],
+ gravatarChecking: [
+ false,
+ {
+ checkGravatar: () => true,
+ recheckGravatar: () => true,
+ setGravatarStatus: () => false,
+ },
+ ],
+ gravatarRefreshKey: [
+ 0,
+ {
+ recheckGravatar: (_, { refreshKey }) => refreshKey,
+ },
+ ],
+ }),
+ selectors({
+ gravatarEmail: [
+ (s) => [s.user],
+ (user: UserType | null): string | null => user?.email?.trim().toLowerCase() || null,
+ ],
+ usesHedgehogAsProfilePicture: [
+ (s) => [s.user],
+ (user: UserType | null): boolean => !!user?.hedgehog_config?.use_as_profile,
+ ],
+ }),
+ sharedListeners(({ values, actions, selectors }) => ({
+ probeGravatar: async (_, breakpoint) => {
+ const email = values.gravatarEmail
+ if (!email) {
+ actions.setGravatarStatus('missing')
+ return
+ }
+ if (values.usesHedgehogAsProfilePicture) {
+ actions.setGravatarStatus('unknown')
+ return
+ }
+ const loaded = await probeImage(gravatarUrl(email, values.gravatarRefreshKey))
+ breakpoint()
+ actions.setGravatarStatus(loaded ? 'found' : 'missing')
+ },
+ probeGravatarIfUserChanged: (_, __, ___, previousState) => {
+ const emailChanged = selectors.gravatarEmail(previousState) !== values.gravatarEmail
+ const hedgehogChanged =
+ selectors.usesHedgehogAsProfilePicture(previousState) !== values.usesHedgehogAsProfilePicture
+ if (emailChanged || hedgehogChanged) {
+ actions.checkGravatar()
+ }
+ },
+ })),
+ listeners(({ sharedListeners }) => ({
+ checkGravatar: sharedListeners.probeGravatar,
+ recheckGravatar: sharedListeners.probeGravatar,
+ loadUserSuccess: sharedListeners.probeGravatarIfUserChanged,
+ updateUserSuccess: sharedListeners.probeGravatarIfUserChanged,
+ })),
+ afterMount(({ actions }) => {
+ actions.checkGravatar()
+ }),
+])