Add user status on user profile icon (#33653)

* Add user status on user profile icon

Currently unstyled & no tests

* Style the user status icon

* Update snapshot

for avatar wrapper

* More snapshot updates

* add if braces

* Split out user status functions

to avoid circular dep which has the weird effect of just breaking
jest's mocking.

* type imports

* Update imports

* Update snapshot

* Tests

* baseline image

* Just snapshot the component itself

---------

Co-authored-by: Michael Telatynski <7t3chguy@gmail.com>
This commit is contained in:
David Baker
2026-06-04 15:15:19 +00:00
committed by GitHub
co-authored by Michael Telatynski
parent f65a53a174
commit bb07f84e41
17 changed files with 398 additions and 169 deletions
+2 -31
View File
@@ -12,21 +12,10 @@ import { logger as rootLogger } from "matrix-js-sdk/src/logger";
import { useMatrixClientContext } from "../contexts/MatrixClientContext";
import { useTypedEventEmitter } from "./useEventEmitter";
import { useFeatureEnabled } from "./useSettings";
import { type UserStatus, validateUserStatus } from "../utils/userStatus";
const logger = rootLogger.getChild("useUserStatus");
export interface UserStatus {
emoji: string;
text: string;
}
const MAX_STATUS_TEXT_BYTES = 256;
export function userStatusTextWithinMaxLength(text: string): boolean {
const textEncoder = new TextEncoder();
return textEncoder.encode(text).length <= MAX_STATUS_TEXT_BYTES;
}
/**
* Hook to get the MSC4426 user status for a given user ID. Returns undefined if the feature is disabled,
* the user does not have a status, or if there was an error fetching the status.
@@ -76,23 +65,5 @@ export function useUserStatus(userId: string | undefined): UserStatus | undefine
return;
}
if (typeof rawUserStatus !== "object" || rawUserStatus === null) {
logger.warn(`value of "org.matrix.msc4426.status" was not an object for ${userId}`);
return;
}
if ("emoji" in rawUserStatus === false || typeof rawUserStatus.emoji !== "string" || !rawUserStatus.emoji) {
logger.warn(`"emoji" property was not a valid string for ${userId}`);
return;
}
if ("text" in rawUserStatus === false || typeof rawUserStatus.text !== "string" || !rawUserStatus.text) {
logger.warn(`"text" property was not a valid string for ${userId}`);
return;
}
return {
emoji: rawUserStatus.emoji,
text: userStatusTextWithinMaxLength(rawUserStatus.text)
? rawUserStatus.text
: `${rawUserStatus.text.slice(0, MAX_STATUS_TEXT_BYTES)}`,
};
return validateUserStatus(rawUserStatus);
}
+1 -1
View File
@@ -11,8 +11,8 @@ import { Command, CommandCategories, splitAtFirstSpace } from "./SlashCommands";
import SettingsStore from "../settings/SettingsStore";
import { reject, success } from "./utils";
import { UserFriendlyError } from "../languageHandler";
import { userStatusTextWithinMaxLength } from "../hooks/useUserStatus";
import { TimelineRenderingType } from "../contexts/RoomContext";
import { userStatusTextWithinMaxLength } from "../utils/userStatus";
export const statusCommand = new Command({
command: "status",
+33
View File
@@ -13,6 +13,7 @@ import {
type User,
UserEvent,
EventType,
ClientEvent,
} from "matrix-js-sdk/src/matrix";
import { throttle } from "lodash";
@@ -22,11 +23,14 @@ import defaultDispatcher from "../dispatcher/dispatcher";
import { MatrixClientPeg } from "../MatrixClientPeg";
import { _t } from "../languageHandler";
import { mediaFromMxc } from "../customisations/Media";
import SettingsStore from "../settings/SettingsStore";
import { type UserStatus, validateUserStatus } from "../utils/userStatus";
interface IState {
displayName?: string;
avatarUrl?: string;
fetchedAt?: number;
userStatus?: UserStatus;
}
const KEY_DISPLAY_NAME = "mx_profile_displayname";
@@ -81,6 +85,10 @@ export class OwnProfileStore extends AsyncStoreWithClient<IState> {
return this.state.avatarUrl || null;
}
public get userStatus(): UserStatus | undefined {
return this.state.userStatus;
}
/**
* Gets the user's avatar as an HTTP URL of the given size. If the user's
* avatar is not present, this returns null.
@@ -105,6 +113,9 @@ export class OwnProfileStore extends AsyncStoreWithClient<IState> {
this.monitoredUser.removeListener(UserEvent.AvatarUrl, this.onProfileUpdate);
}
this.matrixClient?.removeListener(RoomStateEvent.Events, this.onStateEvents);
if (SettingsStore.getValue("feature_user_status")) {
this.matrixClient?.removeListener(ClientEvent.UserProfileUpdate, this.onExtendedProfileUpdate);
}
await this.reset({});
}
@@ -117,11 +128,16 @@ export class OwnProfileStore extends AsyncStoreWithClient<IState> {
this.monitoredUser.on(UserEvent.AvatarUrl, this.onProfileUpdate);
}
if (SettingsStore.getValue("feature_user_status")) {
this.matrixClient.on(ClientEvent.UserProfileUpdate, this.onExtendedProfileUpdate);
}
// We also have to listen for membership events for ourselves as the above User events
// are fired only with presence, which matrix.org (and many others) has disabled.
this.matrixClient.on(RoomStateEvent.Events, this.onStateEvents);
await this.onProfileUpdate(); // trigger an initial update
await this.refreshUserStatus(); // trigger an update for the user status
}
protected async onAction(payload: ActionPayload): Promise<void> {
@@ -175,6 +191,23 @@ export class OwnProfileStore extends AsyncStoreWithClient<IState> {
{ trailing: true, leading: true },
);
private onExtendedProfileUpdate = async (syncedUserId: string): Promise<void> => {
if (syncedUserId === this.matrixClient?.getSafeUserId()) {
await this.refreshUserStatus();
}
};
private refreshUserStatus = async (): Promise<void> => {
if (!this.matrixClient) return;
if (!SettingsStore.getValue("feature_user_status")) return;
const rawUserStatus = await this.matrixClient.getExtendedProfileProperty(
this.matrixClient.getSafeUserId(),
"org.matrix.msc4426.status",
);
await this.updateState({ userStatus: validateUserStatus(rawUserStatus) });
};
private onStateEvents = async (ev: MatrixEvent): Promise<void> => {
const myUserId = MatrixClientPeg.safeGet().getUserId();
if (ev.getType() === EventType.RoomMember && ev.getSender() === myUserId && ev.getStateKey() === myUserId) {
+36
View File
@@ -0,0 +1,36 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE files in the repository root for full details.
*/
const MAX_STATUS_TEXT_BYTES = 256;
export interface UserStatus {
emoji: string;
text: string;
}
export function userStatusTextWithinMaxLength(text: string): boolean {
const textEncoder = new TextEncoder();
return textEncoder.encode(text).length <= MAX_STATUS_TEXT_BYTES;
}
export function validateUserStatus(rawUserStatus: unknown): UserStatus | undefined {
if (typeof rawUserStatus !== "object" || rawUserStatus === null) {
return undefined;
}
if ("emoji" in rawUserStatus === false || typeof rawUserStatus.emoji !== "string" || !rawUserStatus.emoji) {
return undefined;
}
if ("text" in rawUserStatus === false || typeof rawUserStatus.text !== "string" || !rawUserStatus.text) {
return undefined;
}
return {
emoji: rawUserStatus.emoji,
text: userStatusTextWithinMaxLength(rawUserStatus.text)
? rawUserStatus.text
: `${rawUserStatus.text.slice(0, MAX_STATUS_TEXT_BYTES)}`,
};
}
@@ -42,6 +42,7 @@ export class UserMenuViewModel extends BaseViewModel<UserMenuSnapshot, undefined
expanded: !isPanelCollapsed,
manageAccountHref: accountManagementEndpoint,
showAvatar: isAuthenticated,
statusEmoji: OwnProfileStore.instance.userStatus?.emoji,
actions: {
createAccount: !isAuthenticated,
signIn: !isAuthenticated,
@@ -72,7 +73,8 @@ export class UserMenuViewModel extends BaseViewModel<UserMenuSnapshot, undefined
public readonly recalculateProfile = (): void => {
const displayName = OwnProfileStore.instance.displayName || this.snapshot.current.userId;
const avatarUrl = OwnProfileStore.instance.getHttpAvatarUrl(AVATAR_PX) ?? undefined;
this.snapshot.merge({ displayName, avatarUrl });
const statusEmoji = OwnProfileStore.instance.userStatus?.emoji;
this.snapshot.merge({ displayName, avatarUrl, statusEmoji });
};
public readonly setOpen = (isOpen: boolean): void => {
@@ -15,7 +15,7 @@ import { type MouseEvent } from "react";
import { _t } from "../../../../languageHandler";
import { getUserNameColorClass } from "../../../../utils/FormattingUtils";
import UserIdentifier from "../../../../customisations/UserIdentifier";
import type { UserStatus } from "../../../../hooks/useUserStatus";
import { type UserStatus } from "../../../../utils/userStatus";
/**
* Information about a member for disambiguation purposes.