diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 5d4d11f4b..64f41acf7 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -152,8 +152,8 @@ import { useRoomCreators } from '$hooks/useRoomCreators'; import { useRoomPermissions } from '$hooks/useRoomPermissions'; import { AutocompleteNotice } from '$components/editor/autocomplete/AutocompleteNotice'; import { - getCurrentlyUsedPerMessageProfileForRoom, - PerMessageProfile, + convertPerMessageProfileToBeeperFormat, + perMessageProfileAtomFamily, } from '$hooks/usePerMessageProfile'; import { getSupportedAudioExtension } from '$plugins/voice-recorder-kit/supportedCodec'; import { SchedulePickerDialog } from './schedule-send'; @@ -275,18 +275,7 @@ export const RoomInput = forwardRef( ); // Add state to cache the profile - const [perMessageProfile, setPerMessageProfile] = useState(null); - - // Fetch and cache the profile when the roomId changes - useEffect(() => { - const fetchPmP = async () => { - const profile = await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId); - console.debug('Fetched per-message profile:', { profile, roomId }); - setPerMessageProfile(profile ?? null); // Convert undefined to null - }; - - fetchPmP(); - }, [mx, roomId]); + const perMessageProfile = useAtomValue(perMessageProfileAtomFamily(roomId)); const [uploadBoard, setUploadBoard] = useState(true); const [selectedFiles, setSelectedFiles] = useAtom(roomIdToUploadItemsAtomFamily(draftKey)); @@ -655,12 +644,8 @@ export const RoomInput = forwardRef( perMessageProfile.name, perMessageProfile.avatarUrl ); - content['com.beeper.per_message_profile'] = { - id: perMessageProfile.id, - displayname: perMessageProfile.name, - avatar_url: perMessageProfile.avatarUrl, - 'io.fsky.nyx.pronouns': perMessageProfile.pronouns, - }; + content['com.beeper.per_message_profile'] = + convertPerMessageProfileToBeeperFormat(perMessageProfile); } if (replyDraft && !silentReply) { diff --git a/src/app/features/room/message/Message.tsx b/src/app/features/room/message/Message.tsx index b3b299265..b09562714 100644 --- a/src/app/features/room/message/Message.tsx +++ b/src/app/features/room/message/Message.tsx @@ -85,6 +85,10 @@ import { addStickerToDefaultPack, doesStickerExistInDefaultPack, } from '$utils/addStickerToDefaultStickerPack'; +import { + convertBeeperFormatToOurPerMessageProfile, + PerMessageProfileBeeperFormat, +} from '$hooks/usePerMessageProfile'; import { MessageEditor } from './MessageEditor'; import * as css from './styles.css'; @@ -376,22 +380,33 @@ function MessageInternal( const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); - const pmp = useMemo( + const pmp: PerMessageProfileBeeperFormat | undefined = useMemo( () => mEvent.event.content?.['com.beeper.per_message_profile'] as - | { - avatar_url: string | undefined; - displayname: string | undefined; - id: string | undefined; - } + | PerMessageProfileBeeperFormat | undefined, [mEvent] ); + /** + * We convert the per-message profile from the Beeper format to our internal format here in the message component + */ + const parsedPMPContent = useMemo(() => { + if (!pmp) return undefined; + return convertBeeperFormatToOurPerMessageProfile(pmp); + }, [pmp]); + // Profiles and Colors const profile = useUserProfile(senderId, room); const { color: usernameColor, font: usernameFont } = useSableCosmetics(senderId, room); + /** + * If there is a per-message profile, we want to use the per message pronouns, + * otherwise we fall back to the profile pronouns. + * This allows users to set pronouns on a per-message basis, while still falling back to their profile pronouns if they don't set any for a specific message. + */ + const pronouns = parsedPMPContent?.pronouns ?? profile.pronouns; + // Avatars // Prefer the room-scoped member avatar (m.room.member) over the global profile // avatar so per-room avatar overrides are respected in the timeline. @@ -472,7 +487,7 @@ function MessageInternal( {showPronouns && ( - + )} {tagIconSrc && } diff --git a/src/app/features/settings/Profiles/PerMessageProfileEditor.tsx b/src/app/features/settings/Profiles/PerMessageProfileEditor.tsx index 616820659..0c237155c 100644 --- a/src/app/features/settings/Profiles/PerMessageProfileEditor.tsx +++ b/src/app/features/settings/Profiles/PerMessageProfileEditor.tsx @@ -9,7 +9,7 @@ import { useObjectURL } from '$hooks/useObjectURL'; import { createUploadAtom } from '$state/upload'; import { UserAvatar } from '$components/user-avatar'; import { CompactUploadCardRenderer } from '$components/upload-card'; -import { addOrUpdatePerMessageProfile, deletePerMessageProfile } from '$hooks/usePerMessageProfile'; +import { addOrUpdatePerMessageProfile, deletePerMessageProfile, invalidatePerMessageProfileForProfileId } from '$hooks/usePerMessageProfile'; import { SequenceCardStyle } from '../styles.css'; import { parsePronounsStringToPronounsSetArray, PronounSet } from '$utils/pronouns'; @@ -47,12 +47,12 @@ export function PerMessageProfileEditor({ return [pronounsString] as const; }, [currentPronouns]); const [newPronouns, setNewPronouns] = useState(pronouns); - const newPronounsString = useMemo(() => { + const [newPronounsString, setNewPronounsString] = useState(() => { const pronounsString = Array.isArray(newPronouns) ? newPronouns.map((p) => `${p.language ? `${p.language}:` : ''}${p.summary}`).join(', ') : ''; return pronounsString; - }, [newPronouns]); + }); const [newDisplayName, setNewDisplayName] = useState(currentDisplayName); const [imageFile, setImageFile] = useState(); @@ -100,25 +100,37 @@ export function PerMessageProfileEditor({ [newDisplayName, currentDisplayName, newPronouns, currentPronouns, imageFile] ); - // Reset handler for display name + /** + * Reset handler to reset the display name and pronouns to their current values, and clear the image file if there is one. + */ const handleReset = useCallback(() => { setNewDisplayName(currentDisplayName); setNewPronouns(currentPronouns); + setNewPronounsString( + Array.isArray(currentPronouns) + ? currentPronouns.map((p) => `${p.language ? `${p.language}:` : ''}${p.summary}`).join(', ') + : '' + ); setChangingDisplayName(false); setDisableSetDisplayname(false); }, [currentDisplayName, currentPronouns]); + /** + * persisting the data :3 + */ const handleSave = useCallback(() => { addOrUpdatePerMessageProfile(mx, { id: profileId, name: newDisplayName, avatarUrl: avatarMxc, + pronouns: newPronouns, }).then(() => { setCurrentDisplayName(newDisplayName); setCurrentPronouns(newPronouns); }); setChangingDisplayName(false); setDisableSetDisplayname(false); + invalidatePerMessageProfileForProfileId(mx, profileId, () => {}); }, [mx, profileId, newDisplayName, avatarMxc, newPronouns]); const handleDelete = useCallback(() => { @@ -129,9 +141,10 @@ export function PerMessageProfileEditor({ }); }, [mx, profileId, onDelete]); - const handlePronounsChange = useCallback(() => { - return setNewPronouns(parsePronounsStringToPronounsSetArray(newPronounsString)); - }, [newPronounsString]); + const handlePronounsChange = useCallback((e: React.ChangeEvent) => { + setNewPronounsString(e.target.value); + return setNewPronouns(parsePronounsStringToPronounsSetArray(e.target.value)); + }, []); return ( { room, mx.getSafeUserId() ); + invalidatePerMessageProfileForProfileId(mx, profileId, () => {}); }) .catch(() => { sendFeedback( @@ -549,6 +552,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { room, mx.getSafeUserId() ); + invalidatePerMessageProfileForProfileId(mx, profileId, () => {}); }) .catch(() => { sendFeedback( @@ -591,6 +595,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { room, mx.getSafeUserId() ); + invalidatePerMessageProfile(room.roomId, () => {}); }) .catch(() => { sendFeedback( diff --git a/src/app/hooks/usePerMessageProfile.ts b/src/app/hooks/usePerMessageProfile.ts index 7f6457319..1ded9ebe8 100644 --- a/src/app/hooks/usePerMessageProfile.ts +++ b/src/app/hooks/usePerMessageProfile.ts @@ -1,5 +1,8 @@ import { PronounSet } from '$utils/pronouns'; +import { atom } from 'jotai'; +import { atomFamily } from 'jotai/utils'; import { MatrixClient } from 'matrix-js-sdk'; +import { useMatrixClient } from './useMatrixClient'; const ACCOUNT_DATA_PREFIX = 'fyi.cisnt.permessageprofile'; @@ -21,9 +24,74 @@ export type PerMessageProfile = { * the avatar url to use for messages using this profile. */ avatarUrl?: string; + /** + * a per message profile can also include pronouns + * @see PronounSet for the format of the pronouns, and how to parse them from a string input + */ pronouns?: PronounSet[]; }; +/** + * the format used by Beeper for per message profiles + * This is the format that Beeper expects when applying a profile to a message before sending it + */ +export type PerMessageProfileBeeperFormat = { + /** + * the unique id for this profile, which is used to identify the profile when applying it to a message, and also used as the key when storing the profile in account data. + */ + id: string; + /** + * the display name to use for messages using this profile. This is required because otherwise the profile would have no effect on the message. + */ + displayname: string; + /** + * the avatar url to use for messages using this profile. + * Beeper expects this to be a mxc url. + */ + avatar_url?: string; + /** + * using the unstable prefix for pronouns, under which it is also stored in profiles + */ + 'io.fsky.nyx.pronouns'?: PronounSet[]; +}; + +/** + * converts a per message profile from our format to the format used by Beeper, which is used when applying the profile to a message before sending it. + * We have out own format because we want to have more control over the data and how it's stored in account data. + * @export + * @param {PerMessageProfile} profile the per message profile in our format + * @return {*} {PerMessageProfileBeeperFormat} the per message profile in Beeper's format, which can be applied to a message before sending it + */ +export function convertPerMessageProfileToBeeperFormat( + profile: PerMessageProfile +): PerMessageProfileBeeperFormat { + return { + id: profile.id, + displayname: profile.name, + avatar_url: profile.avatarUrl, + 'io.fsky.nyx.pronouns': profile.pronouns, + }; +} + +/** + * converts a per message profile from Beeper's format to our format, which is used when storing the profile in account data and using it in the app. + * We have our own format because we want to have more control over the data and how it's stored in account data. + * + * @export + * @param {PerMessageProfileBeeperFormat} beeperProfile the per message profile in Beeper's format + * @return {*} {PerMessageProfile} the per message profile in our format, which can be stored in account data and used in the app + */ +export function convertBeeperFormatToOurPerMessageProfile( + beeperProfile: PerMessageProfileBeeperFormat +): PerMessageProfile { + return { + id: beeperProfile.id, + name: beeperProfile.displayname, + avatarUrl: beeperProfile.avatar_url, + pronouns: beeperProfile['io.fsky.nyx.pronouns'], + }; +} + type PerMessageProfileIndex = { /** * a list of all profile ids, used to list all profiles when the user wants to manage them. @@ -72,6 +140,7 @@ export async function getAllPerMessageProfiles(mx: MatrixClient): Promise { + const accountData = mx.getAccountData(`${ACCOUNT_DATA_PREFIX}.roomassociation` as any); + const content = accountData?.getContent()?.associations as + | PerMessageProfileRoomAssociation[] + | undefined; + + if (!Array.isArray(content)) { + // If content is not an array, return empty list + return []; + } + + const roomsUsingProfile = content + .filter( + (assoc: PerMessageProfileRoomAssociation) => + assoc.profileId === profileId && (!assoc.validUntil || assoc.validUntil > Date.now()) + ) + .map((assoc: PerMessageProfileRoomAssociation) => assoc.roomId); + + return roomsUsingProfile; +} + /** * gets the per message profile to be used for messages in a room * @param mx matrix client @@ -158,3 +251,30 @@ export function setCurrentlyUsedPerMessageProfileIdForRoom( }; return mx.setAccountData(`${ACCOUNT_DATA_PREFIX}.roomassociation` as any, wrapper as any); } + +// Atom to trigger refresh +const refreshProfileAtomFamily = atomFamily(() => atom(0)); + +// Atom family to fetch profile for a room +export const perMessageProfileAtomFamily = atomFamily((roomId: string) => + atom(async (get) => { + get(refreshProfileAtomFamily(roomId)); // depend on refresh signal + const mx = useMatrixClient(); // You need to provide this atom for MatrixClient + return getCurrentlyUsedPerMessageProfileForRoom(mx, roomId); + }) +); + +/** + * TO-DO + */ +export const invalidatePerMessageProfile = (roomId: string, set: any) => { + set(refreshProfileAtomFamily(roomId), (v: number) => v + 1); +}; + +export function invalidatePerMessageProfileForProfileId(mx: MatrixClient, profileId: string, set: any) { + getListOfRoomsUsingProfile(mx, profileId).then((roomIds) => { + roomIds.forEach((roomId) => { + set(refreshProfileAtomFamily(roomId), (v: number) => v + 1); + }); + }); +}