Add Account-wide persona toggle in Persona Picker

This commit is contained in:
Josie authored and Delta committed 2026-07-23 23:37:12 +01:00
1 parent e3ff86dfce
commit 522c37e86d
5 files changed
+268 -79

No files matched your search

@@ -0,0 +1,5 @@
---
default: minor
---
# Add Account-wide persona toggle in Persona Picker
+18 -4
View File
@@ -145,6 +145,7 @@ import { useRoomPermissions } from '$hooks/useRoomPermissions';
import { AutocompleteNotice } from '$components/editor/autocomplete/AutocompleteNotice';
import {
convertPerMessageProfileToBeeperFormat,
getCurrentlyUsedPerMessageProfileForAccount,
getCurrentlyUsedPerMessageProfileForRoom,
} from '$hooks/usePerMessageProfile';
import {
@@ -206,7 +207,7 @@ import { AudioMessageRecorder } from './AudioMessageRecorder';
import * as prefix from '$unstable/prefixes';
import { PollDialog } from './poll-modals';
import { useClientConfig } from '$hooks/useClientConfig';
import { PersonaPicker } from './persona-picker/PersonaPicker.tsx';
import { PersonaPicker, type PersonaPickerTab } from './persona-picker/PersonaPicker.tsx';
const LocationDialog = lazy(() =>
import('./location-modal').then((module) => ({ default: module.LocationDialog }))
@@ -517,6 +518,10 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const [emojiBoardTab, setEmojiBoardTab] = useState<EmojiBoardTab | undefined>(undefined);
// Android back closes the mobile emoji board instead of navigating away.
useDismissOnBack(() => setEmojiBoardTab(undefined), emojiBoardTab !== undefined);
const [personaPickerTab, setPersonaPickerTab] = useState<PersonaPickerTab | undefined>(
undefined
);
const [enableMediaGalleries] = useSetting(settingsAtom, 'enableMediaGalleries');
const [sendIndividualAttachmentAsCaption] = useSetting(
settingsAtom,
@@ -665,7 +670,9 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
* This allows the server to apply the correct profile-based transformations (e.g. font size adjustments) when processing the message,
* and also allows clients to display an accurate preview of how the message will look with the profile applied while it's being composed.
*/
const perMessageProfile = await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId);
const globalPerMessageProfile = await getCurrentlyUsedPerMessageProfileForAccount(mx);
const roomPerMessageProfile = await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId);
const perMessageProfile = roomPerMessageProfile ?? globalPerMessageProfile;
if (perMessageProfile) {
contents.forEach((c) => {
@@ -1102,7 +1109,10 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
* This allows the server to apply the correct profile-based transformations (e.g. font size adjustments) when processing the message,
* and also allows clients to display an accurate preview of how the message will look with the profile applied while it's being composed.
*/
let perMessageProfile = await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId);
const globalPerMessageProfile = await getCurrentlyUsedPerMessageProfileForAccount(mx);
const roomPerMessageProfile = await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId);
let perMessageProfile = roomPerMessageProfile ?? globalPerMessageProfile;
if (pmpProxyingEnable) {
if (proxiedPerMessageProfile) perMessageProfile = proxiedPerMessageProfile;
}
@@ -1452,7 +1462,9 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
* This allows the server to apply the correct profile-based transformations (e.g. font size adjustments) when processing the message,
* and also allows clients to display an accurate preview of how the message will look with the profile applied while it's being composed.
*/
const perMessageProfile = await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId);
const globalPerMessageProfile = await getCurrentlyUsedPerMessageProfileForAccount(mx);
const roomPerMessageProfile = await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId);
const perMessageProfile = roomPerMessageProfile ?? globalPerMessageProfile;
if (perMessageProfile) {
content[prefix.MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME] =
@@ -1867,9 +1879,11 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
)}
{pmpPickerEnable && (
<PersonaPicker
tab={personaPickerTab}
mx={mx}
roomId={roomId}
suppressEditorRefocus={suppressEditorRefocus}
onTabChange={setPersonaPickerTab}
/>
)}
</>
@@ -4,6 +4,7 @@ import { color, config, toRem } from 'folds';
export const PersonaPickerMenuItem = style({
backgroundColor: color.Surface.Container,
minWidth: toRem(200),
padding: '0',
selectors: {
'&:hover': {
backgroundColor: color.Surface.ContainerHover,
@@ -1,4 +1,9 @@
import { composerIcon, User as UserIcon } from '$components/icons/phosphor';
import {
composerIcon,
MagnifyingGlass,
menuIcon,
User as UserIcon,
} from '$components/icons/phosphor';
import { UserAvatar } from '$components/user-avatar/UserAvatar.tsx';
import { useMediaAuthentication } from '$hooks/useMediaAuthentication.ts';
import {
@@ -6,6 +11,8 @@ import {
getAllPerMessageProfiles,
type PerMessageProfile,
setCurrentlyUsedPerMessageProfileIdForRoom,
getCurrentlyUsedPerMessageProfileForAccount,
setCurrentlyUsedPerMessageProfileIdForAccount,
} from '$hooks/usePerMessageProfile';
import { stopPropagation } from '$utils/keyboard';
import { mxcUrlToHttp } from '$utils/matrix.ts';
@@ -25,24 +32,48 @@ import {
Scroll,
Text,
toRem,
Badge,
} from 'folds';
import type { MatrixClient } from 'matrix-js-sdk';
import { useCallback, useEffect, useRef, useState, type FormEvent } from 'react';
import * as css from './PersonaPicker.css.ts';
import { InfoCard } from '$components/info-card/InfoCard.tsx';
import { InfoIcon } from '@phosphor-icons/react';
export enum PersonaPickerTab {
Global = 'Global',
PerRoom = 'PerRoom',
}
type PersonaPickerProps = {
tab?: PersonaPickerTab;
mx: MatrixClient;
roomId: string;
suppressEditorRefocus: () => void;
onTabChange: (tab: PersonaPickerTab) => void;
};
export function PersonaPicker({ mx, roomId, suppressEditorRefocus }: PersonaPickerProps) {
export function PersonaPicker({
tab = PersonaPickerTab.Global,
mx,
roomId,
suppressEditorRefocus,
onTabChange,
}: PersonaPickerProps) {
const useAuthentication = useMediaAuthentication();
const [AddPersonaMenuAnchor, setAddPersonaMenuAnchor] = useState<RectCords>();
const [profiles, setProfiles] = useState<PerMessageProfile[] | undefined>(undefined);
const [selectedPersona, setSelectedPersona] = useState<PerMessageProfile | null>(null);
const isPickerMenuItemSelected = (persona: PerMessageProfile) =>
persona.id === selectedPersona?.id ? true : undefined;
const [selectedGlobalPersona, setSelectedGlobalPersona] = useState<PerMessageProfile | null>(
null
);
const [selectedRoomPersona, setSelectedRoomPersona] = useState<PerMessageProfile | null>(null);
const isPickerMenuItemSelected = (persona: PerMessageProfile) => {
const selectedPersona =
tab === PersonaPickerTab.Global ? selectedGlobalPersona : selectedRoomPersona;
return persona.id === selectedPersona?.id ? true : undefined;
};
const defactoPersona = () => selectedRoomPersona ?? selectedGlobalPersona;
const searchInputRef = useRef<HTMLInputElement>(null);
@@ -62,8 +93,11 @@ export function PersonaPicker({ mx, roomId, suppressEditorRefocus }: PersonaPick
useEffect(() => {
const syncProfile = async () => {
const syncedProfile = await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId);
setSelectedPersona(syncedProfile ?? null);
const syncedRoomProfile = await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId);
setSelectedRoomPersona(syncedRoomProfile ?? null);
const syncedGlobalProfile = await getCurrentlyUsedPerMessageProfileForAccount(mx);
setSelectedGlobalPersona(syncedGlobalProfile ?? null);
};
syncProfile();
}, [mx, roomId]);
@@ -132,72 +166,150 @@ export function PersonaPicker({ mx, roomId, suppressEditorRefocus }: PersonaPick
}}
>
<Menu>
<Box direction="Column" gap="100" style={{ padding: config.space.S200 }}>
<Text size="H6">Set persona for this room</Text>
<Input
ref={searchInputRef}
variant="SurfaceVariant"
size="400"
placeholder="Search"
maxLength={50}
autoFocus={!mobileOrTablet()}
onChange={filter}
/>
<Box
direction="Column"
gap="100"
style={{ padding: config.space.S200, minWidth: '18rem' }}
>
<Box gap="100">
<Badge
as="button"
variant="Secondary"
fill={tab == PersonaPickerTab.Global ? 'Solid' : 'None'}
size="500"
onClick={() => onTabChange(PersonaPickerTab.Global)}
>
<Text as="span" size="L400">
Global
</Text>
</Badge>
<Badge
as="button"
variant="Secondary"
fill={tab == PersonaPickerTab.PerRoom ? 'Solid' : 'None'}
size="500"
onClick={() => onTabChange(PersonaPickerTab.PerRoom)}
>
<Text as="span" size="L400">
Per-room
</Text>
</Badge>
</Box>
<Scroll ref={scrollRef} size="400" style={{ maxHeight: '14rem' }}>
{filteredProfiles?.map((profile) => (
<MenuItem
key={profile.id}
size="400"
radii="300"
className={css.PersonaPickerMenuItem}
aria-selected={isPickerMenuItemSelected(profile)}
onClick={async () => {
const disabling = profile.id === selectedPersona?.id;
<>
<Input
ref={searchInputRef}
variant="SurfaceVariant"
size="400"
placeholder="Search"
maxLength={50}
autoFocus={!mobileOrTablet()}
onChange={filter}
before={menuIcon(MagnifyingGlass)}
/>
if (!disabling) {
setSelectedPersona(profile);
await setCurrentlyUsedPerMessageProfileIdForRoom(mx, roomId, profile.id);
} else {
setSelectedPersona(null);
await setCurrentlyUsedPerMessageProfileIdForRoom(
mx,
roomId,
undefined,
undefined,
true
);
<Scroll
hideTrack
visibility="Hover"
ref={scrollRef}
size="400"
style={{ maxHeight: '10rem', paddingRight: 0 }}
>
{filteredProfiles?.map((profile) => (
<MenuItem
key={profile.id}
size="400"
radii="300"
className={css.PersonaPickerMenuItem}
aria-selected={isPickerMenuItemSelected(profile)}
onClick={async () => {
const isGlobal = tab === PersonaPickerTab.Global;
const selectedPersona = isGlobal
? selectedGlobalPersona
: selectedRoomPersona;
const disabling = profile.id === selectedPersona?.id;
if (!disabling) {
if (isGlobal) {
setSelectedGlobalPersona(profile);
await setCurrentlyUsedPerMessageProfileIdForAccount(mx, profile.id);
} else {
setSelectedRoomPersona(profile);
await setCurrentlyUsedPerMessageProfileIdForRoom(
mx,
roomId,
profile.id
);
}
} else {
if (isGlobal) {
setSelectedGlobalPersona(null);
await setCurrentlyUsedPerMessageProfileIdForAccount(
mx,
undefined,
undefined,
true
);
} else {
setSelectedRoomPersona(null);
await setCurrentlyUsedPerMessageProfileIdForRoom(
mx,
roomId,
undefined,
undefined,
true
);
}
}
}}
before={
<Avatar
size="300"
radii="400"
style={{
width: 28,
height: 28,
marginLeft: -6,
}}
aria-label="Profile avatar"
>
<UserAvatar
userId={profile.id}
src={avatarUrl(profile)}
renderFallback={() => (
<Text as="span" size="H4" aria-label="Avatar fallback">
{nameInitials(profile.name)}
</Text>
)}
alt={`Avatar for profile ${profile.id}`}
/>
</Avatar>
}
}}
before={
<Avatar
size="300"
radii="400"
style={{
width: '2rem',
height: '2rem',
}}
aria-label="Profile avatar"
>
<UserAvatar
userId={profile.id}
src={avatarUrl(profile)}
renderFallback={() => (
<Text as="span" size="H4" aria-label="Avatar fallback">
{nameInitials(profile.name)}
</Text>
)}
alt={`Avatar for profile ${profile.id}`}
/>
</Avatar>
}
>
<Text truncate style={{ maxWidth: toRem(150) }}>
{profile.name}
</Text>
</MenuItem>
))}
</Scroll>
>
<Text truncate style={{ maxWidth: toRem(150) }}>
{profile.name}
</Text>
</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>
</FocusTrap>
@@ -217,7 +329,7 @@ export function PersonaPicker({ mx, roomId, suppressEditorRefocus }: PersonaPick
title="Switch persona"
aria-label="Switch persona"
>
{selectedPersona ? (
{(selectedRoomPersona ?? selectedGlobalPersona) ? (
<Avatar
size="200"
radii="300"
@@ -230,14 +342,14 @@ export function PersonaPicker({ mx, roomId, suppressEditorRefocus }: PersonaPick
>
<UserAvatar
className={css.PersonaPickerButtonAvatarImage}
userId={selectedPersona.id}
src={avatarUrl(selectedPersona)}
userId={defactoPersona()!.id}
src={avatarUrl(defactoPersona()!)}
renderFallback={() => (
<Text as="span" size="H6" aria-label="Avatar fallback">
{nameInitials(selectedPersona.name)}
{nameInitials(defactoPersona()!.name)}
</Text>
)}
alt={`Avatar for profile ${selectedPersona.id}`}
alt={`Avatar for profile ${defactoPersona()!.id}`}
/>
</Avatar>
) : (
+57
View File
@@ -198,6 +198,21 @@ type PerMessageProfileRoomAssociationWrapper = {
compat?: AccountDataCompatVersion;
};
/**
* the shape of the account data for room associations, which is a wrapper around a list of associations.
* This is used to store the associations in account data, and allows us to easily add additional fields in the future if needed without breaking the existing data structure.
*/
type PerMessageProfileGlobalAssociationWrapper = {
/**
* Key-Value pairs of room ids and profile ids, used to apply a profile to all messages in a room without having to set the profile for each message individually.
* The key is the room id, and the value is the profile id. The profile id can then be used to fetch the profile data when applying the profile to a message before sending it.
*
* @type {Map<string, PerMessageProfileRoomAssociation>}
*/
association: PerMessageProfileRoomAssociation;
compat?: AccountDataCompatVersion;
};
/**
* unwrap a profile-room-associations-wrapper
* @param wrapper the wrapper to unwrap
@@ -384,6 +399,33 @@ export async function setCurrentlyUsedPerMessageProfileIdForRoom(
);
}
/**
* todo
*/
export async function setCurrentlyUsedPerMessageProfileIdForAccount(
mx: MatrixClient,
profileId: string | undefined,
validUntil?: number,
reset?: boolean
) {
if (reset) {
mx.deleteAccountData(
`${ACCOUNT_DATA_PREFIX}.globalassociation` as Parameters<typeof mx.setAccountData>[0]
);
return;
}
if (!profileId) {
throw new Error("profile Id is empty, yet it isn't a reset");
}
const association: PerMessageProfileRoomAssociation = { profileId, validUntil };
mx.setAccountData(
`${ACCOUNT_DATA_PREFIX}.globalassociation` as Parameters<typeof mx.setAccountData>[0],
{ association: association } as Parameters<typeof mx.setAccountData>[1]
);
}
/**
*
* @param mx the matrix client
@@ -568,3 +610,18 @@ export async function getCurrentlyUsedPerMessageProfileForRoom(
const pmp = profileId ? await getPerMessageProfileById(mx, profileId) : undefined;
return profileId ? pmp : undefined;
}
/**
* get the per message profile associated with the account todo
*/
export async function getCurrentlyUsedPerMessageProfileForAccount(
mx: MatrixClient
): Promise<PerMessageProfile | undefined> {
const accountData = mx.getAccountData(
`${ACCOUNT_DATA_PREFIX}.globalassociation` as Parameters<typeof mx.getAccountData>[0]
);
const content: PerMessageProfileGlobalAssociationWrapper | undefined = accountData?.getContent();
const profileId = content?.association.profileId;
const pmp = profileId ? await getPerMessageProfileById(mx, profileId) : undefined;
return profileId ? pmp : undefined;
}