Fix persona picker displaying wrong in change persona menu & refactor

This commit is contained in:
Delta authored and Josie committed 2026-08-09 14:11:59 +01:00
1 parent a6122cbc5c
commit 62fe517b1d
4 files changed
+395 -220

No files matched your search

@@ -430,7 +430,6 @@ function OptionsReproxyPersonaPicker({
<>
<TemporaryPersonaPicker
mx={mx}
hideTabs={true}
onPersonaSelect={reproxyMessage}
requestClose={closeMenu}
anchor={anchor}
+3 -3
View File
@@ -212,7 +212,7 @@ import { AudioMessageRecorder } from './AudioMessageRecorder';
import * as prefix from '$unstable/prefixes';
import { PollDialog } from './poll-modals';
import { useClientConfig } from '$hooks/useClientConfig';
import { PersistentPersonaPicker, type PersonaPickerTab } from './persona-picker/PersonaPicker.tsx';
import { PersonaPicker, type PersonaPickerTab } from './persona-picker/PersonaPicker.tsx';
import { createComposerController, type ComposerController } from './composerController';
import { buildEditReplacement, buildOutgoingMessage } from './composerMessage';
import { pickNativeFile } from './nativeFilePicker';
@@ -2356,8 +2356,8 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
</IconButton>
</>
)}
{pmpPickerEnable && !editingEvent && (
<PersistentPersonaPicker
{pmpPickerEnable && (isMobileOrTablet() ? !editingEvent : true) && (
<PersonaPicker
tab={personaPickerTab}
mx={mx}
roomId={roomId}
@@ -3,7 +3,7 @@ import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { MatrixClient } from 'matrix-js-sdk';
import type { PerMessageProfileMsc4461 } from '$app/persona';
import { TemporaryPersonaPicker, PersonaPickerTab } from './PersonaPicker';
import { PersonaPicker, PersonaPickerTab } from './PersonaPicker';
const mocked = vi.hoisted(() => ({
getAll: vi.fn<(mx: MatrixClient) => Promise<PerMessageProfileMsc4461[]>>(),
@@ -128,7 +128,7 @@ const profiles: PerMessageProfileMsc4461[] = [
function renderPicker(mx = {} as MatrixClient, tab = PersonaPickerTab.Global) {
return render(
<TemporaryPersonaPicker
<PersonaPicker
tab={tab}
mx={mx}
roomId="!room:example.org"
@@ -160,7 +160,7 @@ describe('PersonaPicker async flows', () => {
const view = renderPicker(firstClient);
view.rerender(
<TemporaryPersonaPicker
<PersonaPicker
mx={secondClient}
roomId="!room:example.org"
suppressEditorRefocus={vi.fn<() => void>()}
@@ -230,7 +230,7 @@ describe('PersonaPicker async flows', () => {
fireEvent.click(grabPersonaButton('First'));
view.rerender(
<TemporaryPersonaPicker
<PersonaPicker
tab={PersonaPickerTab.PerRoom}
mx={mx}
roomId="!room:example.org"
@@ -249,7 +249,7 @@ describe('PersonaPicker async flows', () => {
});
view.rerender(
<TemporaryPersonaPicker
<PersonaPicker
tab={PersonaPickerTab.Global}
mx={mx}
roomId="!room:example.org"
@@ -7,7 +7,7 @@ import {
import { ResponsiveMenu } from '$components/ResponsiveMenu';
import { UserAvatar } from '$components/user-avatar/UserAvatar.tsx';
import { useMediaAuthentication } from '$hooks/useMediaAuthentication.ts';
import type { PerMessageProfileMsc4461 } from '$app/persona';
import type { PerMessageProfileMsc4461, Persona } from '$app/persona';
import { ProfileCatalog } from '$app/persona/catalog';
import { mxcUrlToHttp } from '$utils/matrix.ts';
import { isMobileOrTablet } from '$utils/platform';
@@ -29,6 +29,7 @@ import {
} from 'folds';
import type { MatrixClient } from 'matrix-js-sdk';
import {
type RefObject,
useCallback,
useEffect,
useRef,
@@ -69,49 +70,17 @@ type PersonaPickerProps = {
hideTabs?: boolean;
anchor?: RectCords;
};
type TemporaryPersonaPickerProps = {
mx: MatrixClient;
suppressEditorRefocus?: () => void;
onPersonaSelect: (persona: PerMessageProfileMsc4461 | undefined) => void | Promise<void>;
requestClose: () => void;
anchor?: RectCords;
};
export function TemporaryPersonaPicker(props: PersonaPickerProps) {
return (
<PersonaPickerMenu {...props} presentation={PersonaPickerPresentation.TemporarySelectorMenu} />
);
}
export function PersistentPersonaPicker(props: PersonaPickerProps) {
return <PersonaPickerMenu {...props} presentation={PersonaPickerPresentation.PersistentPicker} />;
}
function PersonaPickerMenu({
tab: tabProp = PersonaPickerTab.Global,
mx,
roomId,
suppressEditorRefocus,
onTabChange,
latchedPersona,
onPersonaSelect,
anchor,
requestClose,
}: PersonaPickerProps & { presentation: PersonaPickerPresentation }) {
function useProfileCosmetics(mx: MatrixClient) {
const useAuthentication = useMediaAuthentication();
const [tab, setTab] = useState(tabProp);
const activeTheme = useActiveTheme();
const [AddPersonaMenuAnchor, setAddPersonaMenuAnchor] = useState<RectCords | undefined>(anchor);
const [profiles, setProfiles] = useState<PerMessageProfileMsc4461[] | undefined>(undefined);
const [selectedGlobalPersona, setSelectedGlobalPersona] =
useState<PerMessageProfileMsc4461 | null>(null);
const [selectedRoomPersona, setSelectedRoomPersona] = useState<PerMessageProfileMsc4461 | null>(
latchedPersona ?? null
);
const mountedRef = useRef(false);
const profileFetchGenerationRef = useRef(0);
// Bumped on each click so an in-flight sync cannot undo a fresher choice. Global and
// per-room selections are independent, so one must not invalidate the other's rollback.
const globalSelectionRef = useRef(0);
const roomSelectionRef = useRef(0);
const isPickerMenuItemSelected = (persona: PerMessageProfileMsc4461) => {
const selectedPersona =
tab === PersonaPickerTab.Global ? selectedGlobalPersona : selectedRoomPersona;
return persona.id === selectedPersona?.id ? true : undefined;
};
const nameColor = useCallback(
(persona: PerMessageProfileMsc4461) =>
@@ -121,30 +90,143 @@ function PersonaPickerMenu({
[activeTheme]
);
const defactoPersona = () => selectedRoomPersona ?? selectedGlobalPersona;
const searchInputRef = useRef<HTMLInputElement>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const [filteredProfiles, setFilteredProfiles] = useState<PerMessageProfileMsc4461[] | undefined>(
undefined
const avatarUrl = useCallback(
(profile: PerMessageProfileMsc4461) => {
if (profile.avatar_url !== undefined) {
return mxcUrlToHttp(mx, profile.avatar_url, useAuthentication, 96, 96, 'crop') ?? undefined;
} else {
return undefined;
}
},
[mx, useAuthentication]
);
return { nameColor, avatarUrl };
}
function useProfiles(
mx: MatrixClient,
mountedRef: MutableRefObject<boolean>,
profileFetchGenerationRef: MutableRefObject<number>
) {
const [profiles, setProfiles] = useState<PerMessageProfileMsc4461[] | undefined>(undefined);
const fetchProfiles = useCallback(async () => {
const fetchGeneration = ++profileFetchGenerationRef.current;
try {
const fetchedProfiles = await new ProfileCatalog(mx).list();
if (!mountedRef.current || fetchGeneration !== profileFetchGenerationRef.current) {
return;
}
setProfiles(fetchedProfiles);
} catch {
// Profile loading is best effort; keep the existing list when it fails.
}
}, [mountedRef, mx, profileFetchGenerationRef]);
useEffect(() => {
void fetchProfiles();
return () => {
profileFetchGenerationRef.current += 1;
};
}, [fetchProfiles, profileFetchGenerationRef]);
return { profiles, fetchProfiles };
}
function useFilteredProfiles(
profiles: Persona[],
mountedRef: MutableRefObject<boolean>,
searchInputRef: RefObject<HTMLInputElement>,
profileFetchGenerationRef: MutableRefObject<number>
) {
const [filteredProfiles, setFilteredProfiles] = useState<PerMessageProfileMsc4461[] | undefined>(
profiles ?? undefined
);
//
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
profileFetchGenerationRef.current += 1;
};
}, []);
}, [mountedRef, profileFetchGenerationRef]);
const clearFilterInput = () => {
const clearFilter = () => {
if (searchInputRef.current) {
searchInputRef.current.value = '';
}
setFilteredProfiles(profiles);
};
const filter = useCallback(
(e: FormEvent) => {
const term = (e.target as HTMLInputElement).value.toLocaleLowerCase();
const filtered = term
? profiles?.filter((profile) =>
searchInputRef.current
? profile.displayname.toLocaleLowerCase().includes(searchInputRef.current?.value) ||
profile.id.toLocaleLowerCase().includes(searchInputRef.current?.value)
: true
)
: profiles;
setFilteredProfiles(filtered);
},
[profiles, searchInputRef]
);
useEffect(() => {
setFilteredProfiles(profiles);
}, [profiles]);
return { filteredProfiles, filter, clearFilter };
}
function useSelectedProfiles(
mx: MatrixClient,
roomId: string,
latchedPersona: Persona | undefined,
mountedRef: MutableRefObject<boolean>
) {
const [selectedGlobalPersona, setSelectedGlobalPersona] =
useState<PerMessageProfileMsc4461 | null>(null);
const [selectedRoomPersona, setSelectedRoomPersona] = useState<PerMessageProfileMsc4461 | null>(
latchedPersona ?? null
);
// Bumped on each click so an in-flight sync cannot undo a fresher choice. Global and
// per-room selections are independent, so one must not invalidate the other's rollback.
const globalSelectionRef = useRef(0);
const roomSelectionRef = useRef(0);
const toggle = async (profile: Persona, isGlobal: boolean) => {
const previousPersona = isGlobal ? selectedGlobalPersona : selectedRoomPersona;
const disabling = profile.id === previousPersona?.id;
const setPersona = isGlobal ? setSelectedGlobalPersona : setSelectedRoomPersona;
const generationRef = isGlobal ? globalSelectionRef : roomSelectionRef;
const selectionGeneration = ++generationRef.current;
setPersona(disabling ? null : profile);
try {
await new ProfileCatalog(mx).setSelection(
isGlobal ? 'account' : { roomId: roomId! },
disabling ? undefined : profile.id,
undefined,
disabling
);
} catch {
if (mountedRef.current && selectionGeneration === generationRef.current) {
setPersona(previousPersona);
}
}
};
const setGlobal = async (profile: Persona) => toggle(profile, true);
const setRoom = async (profile: Persona) => toggle(profile, false);
useEffect(() => {
let cancelled = false;
@@ -184,55 +266,56 @@ function PersonaPickerMenu({
};
}, [mx, roomId, latchedPersona, selectedRoomPersona]);
const fetchProfiles = useCallback(async (mx_: MatrixClient) => {
const fetchGeneration = ++profileFetchGenerationRef.current;
try {
const fetchedProfiles = await new ProfileCatalog(mx_).list();
if (!mountedRef.current || fetchGeneration !== profileFetchGenerationRef.current) {
return;
}
setProfiles(fetchedProfiles);
setFilteredProfiles(fetchedProfiles);
} catch {
// Profile loading is best effort; keep the existing list when it fails.
}
}, []);
return {
room: selectedRoomPersona,
global: selectedGlobalPersona,
setRoom,
setGlobal,
};
}
useEffect(() => {
void fetchProfiles(mx);
return () => {
profileFetchGenerationRef.current += 1;
};
}, [fetchProfiles, mx]);
export function PersonaPicker({
tab: tabProp = PersonaPickerTab.Global,
mx,
roomId,
suppressEditorRefocus,
onTabChange,
latchedPersona,
anchor,
}: PersonaPickerProps) {
const [tab, setTab] = useState(tabProp);
const [AddPersonaMenuAnchor, setAddPersonaMenuAnchor] = useState<RectCords | undefined>(anchor);
const mountedRef = useRef(false);
const profileFetchGenerationRef = useRef(0);
const filter = useCallback(
(e: FormEvent) => {
const term = (e.target as HTMLInputElement).value.toLocaleLowerCase();
const { profiles } = useProfiles(mx, mountedRef, profileFetchGenerationRef);
const filtered = term
? profiles?.filter((profile) =>
searchInputRef.current
? profile.displayname.toLocaleLowerCase().includes(searchInputRef.current?.value) ||
profile.id.toLocaleLowerCase().includes(searchInputRef.current?.value)
: true
)
: profiles;
setFilteredProfiles(filtered);
},
[profiles]
const searchInputRef = useRef<HTMLInputElement>(null);
const { filteredProfiles, filter, clearFilter } = useFilteredProfiles(
profiles ?? [],
mountedRef,
searchInputRef,
profileFetchGenerationRef
);
const avatarUrl = useCallback(
(profile: PerMessageProfileMsc4461) => {
if (profile.avatar_url !== undefined) {
return mxcUrlToHttp(mx, profile.avatar_url, useAuthentication, 96, 96, 'crop') ?? undefined;
} else {
return undefined;
}
},
[mx, useAuthentication]
);
const {
room: selectedRoomPersona,
global: selectedGlobalPersona,
setRoom,
setGlobal,
} = useSelectedProfiles(mx, roomId ?? '', latchedPersona, mountedRef);
const isPickerMenuItemSelected = (persona: PerMessageProfileMsc4461) => {
const selectedPersona =
tab === PersonaPickerTab.Global ? selectedGlobalPersona : selectedRoomPersona;
return persona.id === selectedPersona?.id ? true : undefined;
};
const { nameColor, avatarUrl } = useProfileCosmetics(mx);
const defactoPersona = () => selectedRoomPersona ?? selectedGlobalPersona;
const scrollRef = useRef<HTMLDivElement>(null);
return (
<ResponsiveMenu
@@ -243,7 +326,7 @@ function PersonaPickerMenu({
alignOffset={-44}
requestClose={() => {
setAddPersonaMenuAnchor(undefined);
clearFilterInput();
clearFilter();
}}
menu={
<Menu>
@@ -284,123 +367,92 @@ function PersonaPickerMenu({
</Text>
</Badge>
</Box>
<Input
ref={searchInputRef}
variant="SurfaceVariant"
size="400"
placeholder="Search"
maxLength={50}
autoFocus={!isMobileOrTablet()}
onChange={filter}
before={menuIcon(MagnifyingGlass)}
/>
<>
<Input
ref={searchInputRef}
variant="SurfaceVariant"
size="400"
placeholder="Search"
maxLength={50}
autoFocus={!isMobileOrTablet()}
onChange={filter}
before={menuIcon(MagnifyingGlass)}
/>
<Scroll hideTrack ref={scrollRef} size="400" style={{ maxHeight: '10rem' }}>
{filteredProfiles?.map((profile) => (
<MenuItem
key={profile.id}
size="400"
radii="300"
className={css.PersonaPickerMenuItem}
aria-selected={isPickerMenuItemSelected(profile)}
onClick={async () => {
if (onPersonaSelect) {
await onPersonaSelect(profile);
requestClose?.();
return;
}
const isGlobal = tab === PersonaPickerTab.Global;
const previousPersona = isGlobal
? selectedGlobalPersona
: selectedRoomPersona;
const disabling = profile.id === previousPersona?.id;
const setPersona = isGlobal
? setSelectedGlobalPersona
: setSelectedRoomPersona;
const generationRef = isGlobal ? globalSelectionRef : roomSelectionRef;
const selectionGeneration = ++generationRef.current;
setPersona(disabling ? null : profile);
try {
await new ProfileCatalog(mx).setSelection(
isGlobal ? 'account' : { roomId: roomId! },
disabling ? undefined : profile.id,
undefined,
disabling
);
} catch {
if (mountedRef.current && selectionGeneration === generationRef.current) {
setPersona(previousPersona);
}
}
}}
before={
<Avatar
size="300"
radii="400"
style={{
width: 28,
height: 28,
marginLeft: -6,
}}
aria-label="Profile avatar"
>
<UserAvatar
userId={profile.id}
src={avatarUrl(profile)}
fallbackColor={profile['eu.she-a.color']?.on_light ?? undefined}
renderFallback={() => (
<Text as="span" size="H4" aria-label="Avatar fallback">
{nameInitials(profile.displayname)}
</Text>
)}
alt={`Avatar for profile ${profile.id}`}
/>
</Avatar>
}
>
<Box direction="Column">
<Text
truncate
style={{ color: nameColor(profile) ?? undefined, maxWidth: toRem(150) }}
>
{profile.displayname}
</Text>
<Text
truncate
size="T200"
style={{
color: `color-mix(${color.Surface.OnContainer}, transparent 20%)`,
maxWidth: toRem(150),
}}
>
{profile.id}
</Text>
</Box>
</MenuItem>
))}
</Scroll>
<InfoCard
before={menuIcon(InfoIcon, { weight: 'fill' })}
variant="Primary"
description={
selectedRoomPersona ? (
<>
Message will use your <em>per-room</em> persona.
</>
) : selectedGlobalPersona ? (
<>
Message will use your <em>global</em> persona.
</>
) : (
<>No persona chosen.</>
)
}
/>
</>
<Scroll hideTrack ref={scrollRef} size="400" style={{ maxHeight: '10rem' }}>
{filteredProfiles?.map((profile) => (
<MenuItem
key={profile.id}
size="400"
radii="300"
className={css.PersonaPickerMenuItem}
aria-selected={isPickerMenuItemSelected(profile)}
onClick={async () => {
const setPersona = tab === PersonaPickerTab.Global ? setGlobal : setRoom;
setPersona(profile);
}}
before={
<Avatar
size="300"
radii="400"
style={{
width: 28,
height: 28,
marginLeft: -6,
}}
aria-label="Profile avatar"
>
<UserAvatar
userId={profile.id}
src={avatarUrl(profile)}
fallbackColor={profile['eu.she-a.color']?.on_light ?? undefined}
renderFallback={() => (
<Text as="span" size="H4" aria-label="Avatar fallback">
{nameInitials(profile.displayname)}
</Text>
)}
alt={`Avatar for profile ${profile.id}`}
/>
</Avatar>
}
>
<Box direction="Column">
<Text
truncate
style={{ color: nameColor(profile) ?? undefined, maxWidth: toRem(150) }}
>
{profile.displayname}
</Text>
<Text
truncate
size="T200"
style={{
color: `color-mix(${color.Surface.OnContainer}, transparent 20%)`,
maxWidth: toRem(150),
}}
>
{profile.id}
</Text>
</Box>
</MenuItem>
))}
</Scroll>
<InfoCard
before={menuIcon(InfoIcon, { weight: 'fill' })}
variant="Primary"
description={
selectedRoomPersona ? (
<>
Message will use your <em>per-room</em> persona.
</>
) : selectedGlobalPersona ? (
<>
Message will use your <em>global</em> persona.
</>
) : (
<>No persona chosen.</>
)
}
/>
</Box>
</Menu>
}
@@ -447,3 +499,127 @@ function PersonaPickerMenu({
</ResponsiveMenu>
);
}
export function TemporaryPersonaPicker({
mx,
onPersonaSelect,
anchor,
requestClose,
}: TemporaryPersonaPickerProps) {
const [AddPersonaMenuAnchor, setAddPersonaMenuAnchor] = useState<RectCords | undefined>(anchor);
// const [selectedGlobalPersona, setSelectedGlobalPersona] =
// useState<PerMessageProfileMsc4461 | null>(null);
// const [selectedRoomPersona, setSelectedRoomPersona] = useState<PerMessageProfileMsc4461 | null>(
// latchedPersona ?? null
// );
const mountedRef = useRef(false);
const profileFetchGenerationRef = useRef(0);
const { profiles } = useProfiles(mx, mountedRef, profileFetchGenerationRef);
const searchInputRef = useRef<HTMLInputElement>(null);
const { filteredProfiles, filter, clearFilter } = useFilteredProfiles(
profiles ?? [],
mountedRef,
searchInputRef,
profileFetchGenerationRef
);
const { nameColor, avatarUrl } = useProfileCosmetics(mx);
const scrollRef = useRef<HTMLDivElement>(null);
return (
<ResponsiveMenu
anchor={AddPersonaMenuAnchor}
position={'Left'}
align="Start"
offset={16}
alignOffset={-44}
requestClose={() => {
setAddPersonaMenuAnchor(undefined);
clearFilter();
requestClose();
}}
menu={
<Menu>
<Box
direction="Column"
gap="100"
style={{ padding: config.space.S200, minWidth: '18rem' }}
>
<Input
ref={searchInputRef}
variant="SurfaceVariant"
size="400"
placeholder="Search"
maxLength={50}
autoFocus={!isMobileOrTablet()}
onChange={filter}
before={menuIcon(MagnifyingGlass)}
/>
<Scroll hideTrack ref={scrollRef} size="400" style={{ maxHeight: '10rem' }}>
{filteredProfiles?.map((profile) => (
<MenuItem
key={profile.id}
size="400"
radii="300"
className={css.PersonaPickerMenuItem}
onClick={async () => {
await onPersonaSelect(profile);
requestClose();
return;
}}
before={
<Avatar
size="300"
radii="400"
style={{
width: 28,
height: 28,
marginLeft: -6,
}}
aria-label="Profile avatar"
>
<UserAvatar
userId={profile.id}
src={avatarUrl(profile)}
fallbackColor={profile['eu.she-a.color']?.on_light ?? undefined}
renderFallback={() => (
<Text as="span" size="H4" aria-label="Avatar fallback">
{nameInitials(profile.displayname)}
</Text>
)}
alt={`Avatar for profile ${profile.id}`}
/>
</Avatar>
}
>
<Box direction="Column">
<Text
truncate
style={{ color: nameColor(profile) ?? undefined, maxWidth: toRem(150) }}
>
{profile.displayname}
</Text>
<Text
truncate
size="T200"
style={{
color: `color-mix(${color.Surface.OnContainer}, transparent 20%)`,
maxWidth: toRem(150),
}}
>
{profile.id}
</Text>
</Box>
</MenuItem>
))}
</Scroll>
</Box>
</Menu>
}
></ResponsiveMenu>
);
}