mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-20 09:01:17 -08:00
fix(profile): keep extended profile fields across cache refreshes (#1846)
<!-- Please read https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before submitting your pull request --> ### Description <!-- Please include a summary of the change. Please also include relevant motivation and context. List any dependencies that are required for this change. --> Fixes # #### Type of change - [x] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] This change requires a documentation update ### Checklist: - [ ] My code follows the style guidelines of this project - [ ] I have performed a self-review of my own code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings ### AI disclosure: - [ ] Partially AI assisted (clarify which code was AI assisted and briefly explain what it does). - [ ] Fully AI generated (explain what all the generated code does in moderate detail). <!-- Write any explanation required here, but do not generate the explanation using AI!! You must prove you understand what the code in this PR does. -->
This commit is contained in:
5 files changed
+366
-65
No files matched your search
@@ -5,6 +5,8 @@ import type { UserProfile } from '$hooks/useUserProfile';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { profilesCacheAtom } from '$state/userRoomProfile';
|
||||
import { showToast } from '$state/toast';
|
||||
import { invalidateUserProfileCache } from '$hooks/useUserProfile';
|
||||
import { Box, IconButton, Input, Text } from 'folds';
|
||||
import { useSetAtom } from 'jotai';
|
||||
import { useCallback, useEffect, useState, type ChangeEvent } from 'react';
|
||||
@@ -87,12 +89,15 @@ export function AnimalCosmetics({ profile, userId }: Readonly<AnimalCosmeticsPro
|
||||
|
||||
const handleSaveField = useCallback(
|
||||
async (key: string, value: unknown) => {
|
||||
await mx.setExtendedProfileProperty?.(key, value);
|
||||
setGlobalProfiles((prev) => {
|
||||
const newCache = { ...prev };
|
||||
delete newCache[userId];
|
||||
return newCache;
|
||||
});
|
||||
try {
|
||||
await mx.setExtendedProfileProperty?.(key, value);
|
||||
} catch (error) {
|
||||
showToast(
|
||||
`Failed to save profile field: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
invalidateUserProfileCache(mx, userId, setGlobalProfiles);
|
||||
},
|
||||
[mx, userId, setGlobalProfiles]
|
||||
);
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
import { render, within } from '@testing-library/react';
|
||||
import { act, render, within } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { ScreenSize, ScreenSizeProvider } from '$hooks/useScreenSize';
|
||||
import { SettingsLinkProvider } from '$features/settings/SettingsLinkContext';
|
||||
import { showToast } from '$state/toast';
|
||||
import { Profile } from './Profile';
|
||||
|
||||
vi.mock('$state/toast', () => ({
|
||||
showToast: vi.fn<(text: string) => void>(),
|
||||
}));
|
||||
|
||||
const timezoneEditorMock = vi.hoisted(() => ({
|
||||
props: undefined as { current?: string; onSave: (tz: string) => void } | undefined,
|
||||
}));
|
||||
|
||||
const mockMatrixClient = {
|
||||
getUserId: () => '@alice:example.org',
|
||||
setAvatarUrl: vi.fn<() => Promise<void>>(),
|
||||
@@ -72,7 +81,10 @@ vi.mock('jotai', async () => {
|
||||
});
|
||||
|
||||
vi.mock('./TimezoneEditor', () => ({
|
||||
TimezoneEditor: () => <div>Timezone</div>,
|
||||
TimezoneEditor: (props: { current?: string; onSave: (tz: string) => void }) => {
|
||||
timezoneEditorMock.props = props;
|
||||
return <div>Timezone</div>;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('./PronounEditor', () => ({
|
||||
@@ -119,4 +131,25 @@ describe('Profile', () => {
|
||||
within(customFieldTile as HTMLElement).queryByRole('button', { name: /copy settings link/i })
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('surfaces a toast when saving the timezone fails', async () => {
|
||||
mockMatrixClient.setExtendedProfileProperty.mockRejectedValue(
|
||||
new Error('Server does not support extended profiles')
|
||||
);
|
||||
|
||||
render(
|
||||
<ScreenSizeProvider value={ScreenSize.Desktop}>
|
||||
<SettingsLinkProvider value={{ section: 'account', baseUrl: 'https://app.example' }}>
|
||||
<Profile />
|
||||
</SettingsLinkProvider>
|
||||
</ScreenSizeProvider>
|
||||
);
|
||||
|
||||
expect(timezoneEditorMock.props).toBeDefined();
|
||||
await act(async () => {
|
||||
timezoneEditorMock.props?.onSave('Europe/Paris');
|
||||
});
|
||||
|
||||
expect(showToast).toHaveBeenCalledWith(expect.stringContaining('Failed to save profile field'));
|
||||
});
|
||||
});
|
||||
@@ -9,7 +9,7 @@ import { SettingMenuSelector } from '$components/setting-menu-selector';
|
||||
import { SettingTile } from '$components/setting-tile';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import type { UserProfile, MSC4440Bio, ColorSet } from '$hooks/useUserProfile';
|
||||
import { useUserProfile } from '$hooks/useUserProfile';
|
||||
import { invalidateUserProfileCache, useUserProfile } from '$hooks/useUserProfile';
|
||||
import { getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix';
|
||||
import { UserAvatar } from '$components/user-avatar';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
@@ -38,6 +38,7 @@ import { NameColorEditor } from './NameColorEditor';
|
||||
import { StatusEditor } from './StatusEditor';
|
||||
import { AnimalCosmetics } from './AnimalCosmetics';
|
||||
import * as prefix from '$unstable/prefixes';
|
||||
import { showToast } from '$state/toast';
|
||||
import { confirm } from '$components/confirm/confirm';
|
||||
import { AvatarUploadTile } from '$components/avatar-upload-tile/AvatarUploadTile';
|
||||
import { accessibleColor } from '$plugins/color';
|
||||
@@ -107,8 +108,9 @@ function ProfileAvatar({ profile, userId, propagateTo }: Readonly<ProfileProps>)
|
||||
);
|
||||
}
|
||||
|
||||
function ProfileBanner({ profile }: Readonly<Pick<ProfileProps, 'profile'>>) {
|
||||
function ProfileBanner({ profile, userId }: Readonly<Pick<ProfileProps, 'profile' | 'userId'>>) {
|
||||
const mx = useMatrixClient();
|
||||
const setGlobalProfiles = useSetAtom(profilesCacheAtom);
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const [stagedUrl, setStagedUrl] = useState<string>();
|
||||
const [isRemoving, setIsRemoving] = useState(false);
|
||||
@@ -144,15 +146,27 @@ function ProfileBanner({ profile }: Readonly<Pick<ProfileProps, 'profile'>>) {
|
||||
}, []);
|
||||
|
||||
const handleUploaded = useCallback(
|
||||
(upload: UploadSuccess) => {
|
||||
async (upload: UploadSuccess) => {
|
||||
const { mxc } = upload;
|
||||
|
||||
if (imageFileURL) setStagedUrl(imageFileURL);
|
||||
|
||||
mx.setExtendedProfileProperty?.(prefix.MATRIX_UNSTABLE_PROFILE_BANNER_PROPERTY_NAME, mxc);
|
||||
setImageFile(undefined);
|
||||
|
||||
try {
|
||||
await mx.setExtendedProfileProperty?.(
|
||||
prefix.MATRIX_UNSTABLE_PROFILE_BANNER_PROPERTY_NAME,
|
||||
mxc
|
||||
);
|
||||
} catch (error) {
|
||||
showToast(
|
||||
`Failed to save profile field: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
setStagedUrl(undefined);
|
||||
return;
|
||||
}
|
||||
invalidateUserProfileCache(mx, userId, setGlobalProfiles);
|
||||
},
|
||||
[mx, imageFileURL]
|
||||
[mx, userId, imageFileURL, setGlobalProfiles]
|
||||
);
|
||||
|
||||
const handleRemoveBanner = async () => {
|
||||
@@ -166,10 +180,19 @@ function ProfileBanner({ profile }: Readonly<Pick<ProfileProps, 'profile'>>) {
|
||||
setIsRemoving(true);
|
||||
setStagedUrl(undefined);
|
||||
setImageFile(undefined);
|
||||
await mx.setExtendedProfileProperty?.(
|
||||
prefix.MATRIX_UNSTABLE_PROFILE_BANNER_PROPERTY_NAME,
|
||||
null
|
||||
);
|
||||
try {
|
||||
await mx.setExtendedProfileProperty?.(
|
||||
prefix.MATRIX_UNSTABLE_PROFILE_BANNER_PROPERTY_NAME,
|
||||
null
|
||||
);
|
||||
} catch (error) {
|
||||
showToast(
|
||||
`Failed to save profile field: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
setIsRemoving(false);
|
||||
return;
|
||||
}
|
||||
invalidateUserProfileCache(mx, userId, setGlobalProfiles);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -406,12 +429,15 @@ function ProfileExtended({ profile, userId }: Readonly<ProfileProps>) {
|
||||
|
||||
const handleSaveField = useCallback(
|
||||
async (key: string, value: unknown) => {
|
||||
await mx.setExtendedProfileProperty?.(key, value);
|
||||
setGlobalProfiles((prev) => {
|
||||
const newCache = { ...prev };
|
||||
delete newCache[userId];
|
||||
return newCache;
|
||||
});
|
||||
try {
|
||||
await mx.setExtendedProfileProperty?.(key, value);
|
||||
} catch (error) {
|
||||
showToast(
|
||||
`Failed to save profile field: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
invalidateUserProfileCache(mx, userId, setGlobalProfiles);
|
||||
},
|
||||
[mx, userId, setGlobalProfiles]
|
||||
);
|
||||
@@ -715,7 +741,7 @@ export function Profile() {
|
||||
direction="Column"
|
||||
gap="400"
|
||||
>
|
||||
<ProfileBanner profile={profile} />
|
||||
<ProfileBanner profile={profile} userId={userId} />
|
||||
</SequenceCard>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
|
||||
@@ -5,9 +5,11 @@ import { Provider as JotaiProvider, createStore } from 'jotai';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type { MatrixClient } from '$types/matrix-sdk';
|
||||
import { profilesCacheAtom } from '$state/userRoomProfile';
|
||||
import { PROFILE_CACHE_FRESH_MS } from '$client/userProfileCache';
|
||||
import { MatrixClientProvider } from './useMatrixClient';
|
||||
import { IsInactivePanelProvider } from './useRoom';
|
||||
import { useUserProfile } from './useUserProfile';
|
||||
import { invalidateUserProfileCache, useUserProfile } from './useUserProfile';
|
||||
|
||||
vi.mock('$state/hooks/settings', () => ({
|
||||
useSetting: (_atom: unknown, key: string) => {
|
||||
@@ -117,4 +119,155 @@ describe('useUserProfile', () => {
|
||||
|
||||
expect(requested[4]).toBe(userIds[5]);
|
||||
});
|
||||
|
||||
it('keeps cached profile fields when a refetch response omits them', async () => {
|
||||
vi.useFakeTimers();
|
||||
const mx = {
|
||||
getProfileInfo: vi
|
||||
.fn<() => Promise<{ displayname: string }>>()
|
||||
.mockResolvedValue({ displayname: 'Alice' }),
|
||||
getUser: vi.fn<() => void>(),
|
||||
getUserId: vi.fn<() => string>().mockReturnValue('@me:example.org'),
|
||||
} as unknown as MatrixClient;
|
||||
|
||||
const store = createStore();
|
||||
store.set(profilesCacheAtom, {
|
||||
'@alice:example.org': {
|
||||
displayName: 'Alice',
|
||||
timezone: 'Europe/Paris',
|
||||
_fetched: true,
|
||||
_fetchedAt: Date.now() - PROFILE_CACHE_FRESH_MS - 1000,
|
||||
},
|
||||
});
|
||||
|
||||
const wrapper = ({ children }: { children: ReactNode }) =>
|
||||
createElement(
|
||||
JotaiProvider,
|
||||
{ store },
|
||||
createElement(
|
||||
MatrixClientProvider,
|
||||
{ value: mx },
|
||||
createElement(IsInactivePanelProvider, { value: false }, children)
|
||||
)
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useUserProfile('@alice:example.org'), { wrapper });
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(150);
|
||||
});
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
});
|
||||
|
||||
expect(mx.getProfileInfo).toHaveBeenCalledOnce();
|
||||
expect(result.current.timezone).toBe('Europe/Paris');
|
||||
});
|
||||
|
||||
it('updates cached timezone when a refetch response contains a new value', async () => {
|
||||
vi.useFakeTimers();
|
||||
const mx = {
|
||||
getProfileInfo: vi
|
||||
.fn<() => Promise<{ displayname: string; 'm.tz': string }>>()
|
||||
.mockResolvedValue({ displayname: 'Alice', 'm.tz': 'America/New_York' }),
|
||||
getUser: vi.fn<() => void>(),
|
||||
getUserId: vi.fn<() => string>().mockReturnValue('@me:example.org'),
|
||||
} as unknown as MatrixClient;
|
||||
|
||||
const store = createStore();
|
||||
store.set(profilesCacheAtom, {
|
||||
'@alice:example.org': {
|
||||
displayName: 'Alice',
|
||||
timezone: 'Europe/Paris',
|
||||
_fetched: true,
|
||||
_fetchedAt: Date.now() - PROFILE_CACHE_FRESH_MS - 1000,
|
||||
},
|
||||
});
|
||||
|
||||
const wrapper = ({ children }: { children: ReactNode }) =>
|
||||
createElement(
|
||||
JotaiProvider,
|
||||
{ store },
|
||||
createElement(
|
||||
MatrixClientProvider,
|
||||
{ value: mx },
|
||||
createElement(IsInactivePanelProvider, { value: false }, children)
|
||||
)
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useUserProfile('@alice:example.org'), { wrapper });
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(150);
|
||||
});
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
});
|
||||
|
||||
expect(result.current.timezone).toBe('America/New_York');
|
||||
});
|
||||
|
||||
it('discards an in-flight response captured before a profile write', async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
let resolveStale: ((info: { displayname: string; 'm.tz': string }) => void) | undefined;
|
||||
const mx = {
|
||||
getProfileInfo: vi
|
||||
.fn<() => Promise<{ displayname: string; 'm.tz': string }>>()
|
||||
.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
resolveStale = resolve;
|
||||
})
|
||||
)
|
||||
.mockResolvedValue({ displayname: 'Alice', 'm.tz': 'America/New_York' }),
|
||||
getUser: vi.fn<() => void>(),
|
||||
getUserId: vi.fn<() => string>().mockReturnValue('@me:example.org'),
|
||||
} as unknown as MatrixClient;
|
||||
|
||||
const store = createStore();
|
||||
store.set(profilesCacheAtom, {
|
||||
'@alice:example.org': {
|
||||
displayName: 'Alice',
|
||||
timezone: 'Europe/Paris',
|
||||
_fetched: true,
|
||||
_fetchedAt: Date.now() - PROFILE_CACHE_FRESH_MS - 1000,
|
||||
},
|
||||
});
|
||||
|
||||
const wrapper = ({ children }: { children: ReactNode }) =>
|
||||
createElement(
|
||||
JotaiProvider,
|
||||
{ store },
|
||||
createElement(
|
||||
MatrixClientProvider,
|
||||
{ value: mx },
|
||||
createElement(IsInactivePanelProvider, { value: false }, children)
|
||||
)
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useUserProfile('@alice:example.org'), { wrapper });
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(150);
|
||||
});
|
||||
expect(mx.getProfileInfo).toHaveBeenCalledOnce();
|
||||
|
||||
await act(async () => {
|
||||
invalidateUserProfileCache(mx, '@alice:example.org', (update) =>
|
||||
store.set(profilesCacheAtom, update)
|
||||
);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
resolveStale?.({ displayname: 'Alice', 'm.tz': 'Europe/Paris' });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
});
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
});
|
||||
|
||||
expect(mx.getProfileInfo).toHaveBeenCalledTimes(2);
|
||||
expect(result.current.timezone).toBe('America/New_York');
|
||||
});
|
||||
});
|
||||
+123
-39
@@ -24,6 +24,16 @@ const PROFILE_REQUEST_DWELL_MS = 150;
|
||||
const inFlightProfiles = new WeakMap<MatrixClient, Map<string, Promise<Record<string, unknown>>>>();
|
||||
const activeProfileRequests = new WeakMap<MatrixClient, number>();
|
||||
const profileRequestQueues = new WeakMap<MatrixClient, Array<() => void>>();
|
||||
const profileFetchGenerations = new WeakMap<MatrixClient, Map<string, number>>();
|
||||
|
||||
const getFetchGeneration = (mx: MatrixClient, userId: string): number =>
|
||||
profileFetchGenerations.get(mx)?.get(userId) ?? 0;
|
||||
|
||||
const bumpFetchGeneration = (mx: MatrixClient, userId: string): void => {
|
||||
const generations = profileFetchGenerations.get(mx) ?? new Map<string, number>();
|
||||
profileFetchGenerations.set(mx, generations);
|
||||
generations.set(userId, (generations.get(userId) ?? 0) + 1);
|
||||
};
|
||||
|
||||
export type ColorSet = {
|
||||
on_light?: string;
|
||||
@@ -118,48 +128,111 @@ const normalizeInfo = (info: Record<string, unknown>): UserProfile => {
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
const normalized: UserProfile = {
|
||||
avatarUrl: info.avatar_url as string | undefined,
|
||||
displayName: info.displayname as string | undefined,
|
||||
pronouns: info[prefix.MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME] as
|
||||
| PronounSet[]
|
||||
| undefined,
|
||||
timezone: (info[prefix.MATRIX_UNSTABLE_PROFILE_TIMEZONE_PROPERTY_NAME] ||
|
||||
info[prefix.MATRIX_STABLE_PROFILE_TIMEZONE_PROPERTY_NAME]) as string | undefined,
|
||||
bio:
|
||||
msc4440Bio?.['m.text']?.[0]?.body ||
|
||||
(info[prefix.MATRIX_SABLE_UNSTABLE_PROFILE_BIOGRAPHY_PROPERTY_NAME] as string | undefined) ||
|
||||
(info[prefix.MATRIX_COMMET_UNSTABLE_PROFILE_BIO_PROPERTY_NAME] as string | undefined),
|
||||
status: info[prefix.MATRIX_COMMET_UNSTABLE_PROFILE_STATUS_PROPERTY_NAME] as string | undefined,
|
||||
bannerUrl: info[prefix.MATRIX_UNSTABLE_PROFILE_BANNER_PROPERTY_NAME] as string | undefined,
|
||||
nameColor: info[prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_PROPERTY_NAME] as string | undefined,
|
||||
nameColorDark: info[prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_DARK_PROPERTY_NAME] as
|
||||
| string
|
||||
| undefined,
|
||||
nameColorLight: info[prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_LIGHT_PROPERTY_NAME] as
|
||||
| string
|
||||
| undefined,
|
||||
nameColors: info[prefix.MATRIX_UNSTABLE_COLORS] as ColorSet | undefined,
|
||||
heroColorScheme: info[prefix.MATRIX_COMMET_UNSTABLE_PROFILE_COLOR_SCHEME_PROPERTY_NAME] as
|
||||
| Record<string, string>
|
||||
| undefined,
|
||||
isCat: info[prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_IS_CAT_PROPERTY_NAME] as
|
||||
| boolean
|
||||
| undefined,
|
||||
hasCats: info[prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_HAS_CAT_PROPERTY_NAME] as
|
||||
| boolean
|
||||
| undefined,
|
||||
isAnimal: info[prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_IS_ANIMAL_PROPERTY_NAME] as string,
|
||||
hasAnimal: info[
|
||||
prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_HAS_ANIMAL_PROPERTY_NAME
|
||||
] as string,
|
||||
animalNeed: info[
|
||||
prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_ANIMAL_NEED_PROPERTY_NAME
|
||||
] as string,
|
||||
extended,
|
||||
_fetched: true,
|
||||
_fetchedAt: Date.now(),
|
||||
};
|
||||
|
||||
if (prefix.MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME in info) {
|
||||
normalized.pronouns = info[prefix.MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME] as
|
||||
| PronounSet[]
|
||||
| undefined;
|
||||
}
|
||||
if (
|
||||
prefix.MATRIX_UNSTABLE_PROFILE_TIMEZONE_PROPERTY_NAME in info ||
|
||||
prefix.MATRIX_STABLE_PROFILE_TIMEZONE_PROPERTY_NAME in info
|
||||
) {
|
||||
normalized.timezone = (info[prefix.MATRIX_UNSTABLE_PROFILE_TIMEZONE_PROPERTY_NAME] ||
|
||||
info[prefix.MATRIX_STABLE_PROFILE_TIMEZONE_PROPERTY_NAME]) as string | undefined;
|
||||
}
|
||||
if (
|
||||
prefix.MATRIX_UNSTABLE_PROFILE_BIOGRAPHY_PROPERTY_NAME in info ||
|
||||
prefix.MATRIX_SABLE_UNSTABLE_PROFILE_BIOGRAPHY_PROPERTY_NAME in info ||
|
||||
prefix.MATRIX_COMMET_UNSTABLE_PROFILE_BIO_PROPERTY_NAME in info
|
||||
) {
|
||||
normalized.bio =
|
||||
msc4440Bio?.['m.text']?.[0]?.body ||
|
||||
(info[prefix.MATRIX_SABLE_UNSTABLE_PROFILE_BIOGRAPHY_PROPERTY_NAME] as string | undefined) ||
|
||||
(info[prefix.MATRIX_COMMET_UNSTABLE_PROFILE_BIO_PROPERTY_NAME] as string | undefined);
|
||||
}
|
||||
if (prefix.MATRIX_COMMET_UNSTABLE_PROFILE_STATUS_PROPERTY_NAME in info) {
|
||||
normalized.status = info[prefix.MATRIX_COMMET_UNSTABLE_PROFILE_STATUS_PROPERTY_NAME] as
|
||||
| string
|
||||
| undefined;
|
||||
}
|
||||
if (prefix.MATRIX_UNSTABLE_PROFILE_BANNER_PROPERTY_NAME in info) {
|
||||
normalized.bannerUrl = info[prefix.MATRIX_UNSTABLE_PROFILE_BANNER_PROPERTY_NAME] as
|
||||
| string
|
||||
| undefined;
|
||||
}
|
||||
if (prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_PROPERTY_NAME in info) {
|
||||
normalized.nameColor = info[prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_PROPERTY_NAME] as
|
||||
| string
|
||||
| undefined;
|
||||
}
|
||||
if (prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_DARK_PROPERTY_NAME in info) {
|
||||
normalized.nameColorDark = info[prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_DARK_PROPERTY_NAME] as
|
||||
| string
|
||||
| undefined;
|
||||
}
|
||||
if (prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_LIGHT_PROPERTY_NAME in info) {
|
||||
normalized.nameColorLight = info[
|
||||
prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_LIGHT_PROPERTY_NAME
|
||||
] as string | undefined;
|
||||
}
|
||||
if (prefix.MATRIX_UNSTABLE_COLORS in info) {
|
||||
normalized.nameColors = info[prefix.MATRIX_UNSTABLE_COLORS] as ColorSet | undefined;
|
||||
}
|
||||
if (prefix.MATRIX_COMMET_UNSTABLE_PROFILE_COLOR_SCHEME_PROPERTY_NAME in info) {
|
||||
normalized.heroColorScheme = info[
|
||||
prefix.MATRIX_COMMET_UNSTABLE_PROFILE_COLOR_SCHEME_PROPERTY_NAME
|
||||
] as Record<string, string> | undefined;
|
||||
}
|
||||
if (prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_IS_CAT_PROPERTY_NAME in info) {
|
||||
normalized.isCat = info[prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_IS_CAT_PROPERTY_NAME] as
|
||||
| boolean
|
||||
| undefined;
|
||||
}
|
||||
if (prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_HAS_CAT_PROPERTY_NAME in info) {
|
||||
normalized.hasCats = info[
|
||||
prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_HAS_CAT_PROPERTY_NAME
|
||||
] as boolean | undefined;
|
||||
}
|
||||
if (prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_IS_ANIMAL_PROPERTY_NAME in info) {
|
||||
normalized.isAnimal = info[
|
||||
prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_IS_ANIMAL_PROPERTY_NAME
|
||||
] as string;
|
||||
}
|
||||
if (prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_HAS_ANIMAL_PROPERTY_NAME in info) {
|
||||
normalized.hasAnimal = info[
|
||||
prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_HAS_ANIMAL_PROPERTY_NAME
|
||||
] as string;
|
||||
}
|
||||
if (prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_ANIMAL_NEED_PROPERTY_NAME in info) {
|
||||
normalized.animalNeed = info[
|
||||
prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_ANIMAL_NEED_PROPERTY_NAME
|
||||
] as string;
|
||||
}
|
||||
if (Object.keys(extended).length > 0) {
|
||||
normalized.extended = extended;
|
||||
}
|
||||
|
||||
return normalized;
|
||||
};
|
||||
|
||||
export const invalidateUserProfileCache = (
|
||||
mx: MatrixClient,
|
||||
userId: string,
|
||||
setProfiles: (update: (prev: Record<string, UserProfile>) => Record<string, UserProfile>) => void
|
||||
): void => {
|
||||
bumpFetchGeneration(mx, userId);
|
||||
setProfiles((prev) => {
|
||||
const existing = prev[userId];
|
||||
if (!existing) return prev;
|
||||
return { ...prev, [userId]: { ...existing, _fetchedAt: 0 } };
|
||||
});
|
||||
};
|
||||
|
||||
export const isValidHex = (c: unknown): string | undefined => {
|
||||
@@ -227,11 +300,12 @@ export const useUserProfile = (
|
||||
useEffect(() => {
|
||||
if (!needsFetch) return undefined;
|
||||
|
||||
const timeoutId = window.setTimeout(() => {
|
||||
const startFetch = () => {
|
||||
const clientInFlight = inFlightProfiles.get(mx) ?? new Map();
|
||||
inFlightProfiles.set(mx, clientInFlight);
|
||||
if (clientInFlight.has(userId)) return;
|
||||
|
||||
const generation = getFetchGeneration(mx, userId);
|
||||
const fetchPromise = scheduleProfileRequest(mx, () => mx.getProfileInfo(userId)).finally(
|
||||
() => {
|
||||
clientInFlight.delete(userId);
|
||||
@@ -243,6 +317,10 @@ export const useUserProfile = (
|
||||
// the initiating row: a completed request remains useful after a fast virtualized scroll.
|
||||
fetchPromise
|
||||
.then((info: Record<string, unknown>) => {
|
||||
if (getFetchGeneration(mx, userId) !== generation) {
|
||||
startFetch();
|
||||
return;
|
||||
}
|
||||
const normalized = normalizeInfo(info);
|
||||
setGlobalProfiles((prev) => {
|
||||
const { [userId]: previousProfile, ...otherProfiles } = prev;
|
||||
@@ -253,12 +331,18 @@ export const useUserProfile = (
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
if (getFetchGeneration(mx, userId) !== generation) {
|
||||
startFetch();
|
||||
return;
|
||||
}
|
||||
setGlobalProfiles((prev) => ({
|
||||
...prev,
|
||||
[userId]: { ...prev[userId], _fetched: true, _fetchedAt: Date.now() },
|
||||
}));
|
||||
});
|
||||
}, PROFILE_REQUEST_DWELL_MS);
|
||||
};
|
||||
|
||||
const timeoutId = window.setTimeout(startFetch, PROFILE_REQUEST_DWELL_MS);
|
||||
|
||||
return () => window.clearTimeout(timeoutId);
|
||||
}, [userId, needsFetch, mx, setGlobalProfiles]);
|
||||
|
||||
Reference in new issue
Block a user