diff --git a/apps/web/src/hooks/useUserStatus.ts b/apps/web/src/hooks/useUserStatus.ts index 131e43f9aec..4b4afaff9aa 100644 --- a/apps/web/src/hooks/useUserStatus.ts +++ b/apps/web/src/hooks/useUserStatus.ts @@ -6,14 +6,14 @@ Please see LICENSE files in the repository root for full details. */ import { useEffect, useState } from "react"; -import { ClientEvent, MatrixError } from "matrix-js-sdk/src/matrix"; +import { ClientEvent } from "matrix-js-sdk/src/matrix"; import { logger as rootLogger } from "matrix-js-sdk/src/logger"; import { type UserStatus } from "@element-hq/web-shared-components"; import { useMatrixClientContext } from "../contexts/MatrixClientContext"; import { useTypedEventEmitter } from "./useEventEmitter"; import { useFeatureEnabled } from "./useSettings"; -import { validateUserStatus } from "../utils/userStatus"; +import { fetchUserStatus, validateUserStatus } from "../utils/userStatus"; const logger = rootLogger.getChild("useUserStatus"); @@ -27,14 +27,14 @@ const logger = rootLogger.getChild("useUserStatus"); export function useUserStatus(userId: string | undefined): UserStatus | undefined { const isEnabled = useFeatureEnabled("feature_user_status"); const matrixClient = useMatrixClientContext(); - const [rawUserStatus, setRawUserStatus] = useState(); + const [userStatus, setUserStatus] = useState(); useTypedEventEmitter(matrixClient, ClientEvent.UserProfileUpdate, (syncedUserId, syncProfile) => { if (syncedUserId !== userId) { return; } - setRawUserStatus(syncProfile["org.matrix.msc4426.status"]); + setUserStatus(validateUserStatus(syncProfile["org.matrix.msc4426.status"])); }); useEffect(() => { (async () => { @@ -42,22 +42,18 @@ export function useUserStatus(userId: string | undefined): UserStatus | undefine return; } if (!userId) { - setRawUserStatus(undefined); + setUserStatus(undefined); return; } if ((await matrixClient.doesServerSupportExtendedProfiles()) === false) { - setRawUserStatus(undefined); + setUserStatus(undefined); return; } try { - const result = await matrixClient.getExtendedProfileProperty(userId, "org.matrix.msc4426.status"); - setRawUserStatus(result); + const result = await fetchUserStatus(matrixClient, userId); + setUserStatus(result); } catch (ex) { - if (ex instanceof MatrixError && ex.errcode === "M_NOT_FOUND") { - setRawUserStatus(undefined); - } else { - logger.warn(`Failed to get userStatus for ${userId}`, ex); - } + logger.warn(`Failed to get userStatus for ${userId}`, ex); } })(); }, [isEnabled, userId, matrixClient]); @@ -65,5 +61,5 @@ export function useUserStatus(userId: string | undefined): UserStatus | undefine return; } - return validateUserStatus(rawUserStatus); + return userStatus; } diff --git a/apps/web/src/utils/userStatus.ts b/apps/web/src/utils/userStatus.ts index 6020b6bf893..5315f7d9187 100644 --- a/apps/web/src/utils/userStatus.ts +++ b/apps/web/src/utils/userStatus.ts @@ -6,17 +6,32 @@ Please see LICENSE files in the repository root for full details. */ import { type UserStatus } from "@element-hq/web-shared-components"; -import { type MatrixClient } from "matrix-js-sdk/src/matrix"; +import { type MatrixClient, MatrixError } from "matrix-js-sdk/src/matrix"; +import { logger } from "matrix-js-sdk/src/logger"; // MSC4426 defines the maximum length of a status to be 256 bytes of UTF-8, // so we truncate anything longer than that. const MAX_STATUS_TEXT_BYTES = 256; +// Static Intl.Segmenter for grabbing the first grapheme of a user status emoji. +// We make one and keep it for performance. +const intlSegmenter = new Intl.Segmenter(); + +/** + * Checks if a given text is within the maximum allowed length for a user status. + * @param text The text to check. + * @returns True if the text is within the maximum length, false otherwise. + */ export function userStatusTextWithinMaxLength(text: string): boolean { const textEncoder = new TextEncoder(); return textEncoder.encode(text).length <= MAX_STATUS_TEXT_BYTES; } +/** + * Validates an object from a user profile and returns a UserStatus object if it contains a valid user status. + * @param rawUserStatus The raw user status object to validate. + * @returns A UserStatus object if valid, otherwise undefined. + */ export function validateUserStatus(rawUserStatus: unknown): UserStatus | undefined { if (typeof rawUserStatus !== "object" || rawUserStatus === null) { return undefined; @@ -28,13 +43,40 @@ export function validateUserStatus(rawUserStatus: unknown): UserStatus | undefin return undefined; } return { - emoji: rawUserStatus.emoji, + emoji: [...intlSegmenter.segment(rawUserStatus.emoji)][0]?.segment, text: userStatusTextWithinMaxLength(rawUserStatus.text) ? rawUserStatus.text : `${rawUserStatus.text.slice(0, MAX_STATUS_TEXT_BYTES)}…`, }; } +/** + * Fetch the MSC4426 user status of the given user. Returns undefined if the server does not + * support extended profiles, the user has no (valid) status, or the status could not be fetched. + * + * @param client The Matrix client to fetch the status with. + * @param userId The ID of the user whose status is being fetched. + */ +export async function fetchUserStatus(client: MatrixClient, userId: string): Promise { + if ((await client.doesServerSupportExtendedProfiles()) === false) { + return undefined; + } + try { + return validateUserStatus(await client.getExtendedProfileProperty(userId, "org.matrix.msc4426.status")); + } catch (ex) { + if (!(ex instanceof MatrixError && ex.errcode === "M_NOT_FOUND")) { + logger.warn(`Failed to get userStatus for ${userId}`, ex); + } + return undefined; + } +} + +/** + * Sets the MSC4426 user status for the given user. + * + * @param client The Matrix client to use. + * @param userStatus The user status to set. + */ export function setUserStatus(client: MatrixClient, userStatus: UserStatus): Promise { return client.setExtendedProfileProperty("org.matrix.msc4426.status", { emoji: userStatus.emoji, @@ -42,6 +84,11 @@ export function setUserStatus(client: MatrixClient, userStatus: UserStatus): Pro }); } +/** + * Clears the MSC4426 user status for the given user. + * + * @param client The Matrix client to use. + */ export function clearUserStatus(client: MatrixClient): Promise { return client.setExtendedProfileProperty("org.matrix.msc4426.status", null); } diff --git a/apps/web/src/viewmodels/room-list/RoomListItemViewModel.ts b/apps/web/src/viewmodels/room-list/RoomListItemViewModel.ts index f7f285271ab..fc6d21c6946 100644 --- a/apps/web/src/viewmodels/room-list/RoomListItemViewModel.ts +++ b/apps/web/src/viewmodels/room-list/RoomListItemViewModel.ts @@ -11,11 +11,13 @@ import { type RoomListItemViewSnapshot, type RoomListItemViewActions, type Section, + type UserStatus, } from "@element-hq/web-shared-components"; -import { RoomEvent } from "matrix-js-sdk/src/matrix"; +import { ClientEvent, RoomEvent } from "matrix-js-sdk/src/matrix"; import { CallType } from "matrix-js-sdk/src/webrtc/call"; +import { logger } from "matrix-js-sdk/src/logger"; -import type { Room, MatrixClient, RoomMember } from "matrix-js-sdk/src/matrix"; +import type { Room, MatrixClient, RoomMember, ClientEventHandlerMap } from "matrix-js-sdk/src/matrix"; import type { RoomNotificationState } from "../../stores/notifications/RoomNotificationState"; import { RoomNotificationStateStore } from "../../stores/notifications/RoomNotificationStateStore"; import { NotificationStateEvents } from "../../stores/notifications/NotificationState"; @@ -41,6 +43,7 @@ import { type Call, CallEvent } from "../../models/Call"; import RoomListStoreV3 from "../../stores/room-list-v3/RoomListStoreV3"; import { getCustomSectionData, isDefaultSectionTag } from "../../stores/room-list-v3/section"; import { _t } from "../../languageHandler"; +import { fetchUserStatus, validateUserStatus } from "../../utils/userStatus"; /** * View section type without `isSelected` field @@ -75,6 +78,11 @@ export class RoomListItemViewModel */ private availableSections: Sections; + /** + * The user ID of the other user if this room is a DM, used to show their user status. + */ + private readonly dmUserId?: string; + public constructor(props: RoomItemProps) { // Get notification state first so we can generate a complete initial snapshot const notifState = RoomNotificationStateStore.instance.getRoomState(props.room); @@ -141,6 +149,17 @@ export class RoomListItemViewModel // Load message preview asynchronously (sync data is already complete) void this.loadAndSetMessagePreview(); + + // If this room is a DM, show the MSC4426 user status of the other user + this.dmUserId = DMRoomMap.shared().getUserIdForRoomId(props.room.roomId) ?? undefined; + if (this.dmUserId) { + props.client.on(ClientEvent.UserProfileUpdate, this.onUserProfileUpdate); + this.disposables.track(() => { + props.client.off(ClientEvent.UserProfileUpdate, this.onUserProfileUpdate); + }); + + this.updateUserStatus(); + } } public dispose(): void { @@ -268,6 +287,30 @@ export class RoomListItemViewModel this.snapshot.merge({ messagePreview }); } + /** + * Handler for profile updates received via sync, to keep the DM user's status up to date. + */ + private onUserProfileUpdate: ClientEventHandlerMap[ClientEvent.UserProfileUpdate] = (userId, profile) => { + if (userId !== this.dmUserId || !SettingsStore.getValue("feature_user_status")) return; + this.snapshot.merge({ userStatus: validateUserStatus(profile?.["org.matrix.msc4426.status"]) }); + }; + + /** + * Fetch and set the user status of the DM user, if the feature is enabled. + */ + private updateUserStatus(): void { + (async () => { + let userStatus: UserStatus | undefined; + if (this.dmUserId && SettingsStore.getValue("feature_user_status")) { + userStatus = await fetchUserStatus(this.props.client, this.dmUserId); + } + if (this.disposables.isDisposed) return; + this.snapshot.merge({ userStatus }); + })().catch((ex) => { + logger.warn(`Failed to update userStatus for ${this.dmUserId}`, ex); + }); + } + /** * Generate a complete RoomListItem with all synchronous data. * Message preview is loaded separately to avoid blocking initial render. diff --git a/apps/web/test/unit-tests/utils/userStatus-test.ts b/apps/web/test/unit-tests/utils/userStatus-test.ts index 5ae29dcded9..6c07bfc6983 100644 --- a/apps/web/test/unit-tests/utils/userStatus-test.ts +++ b/apps/web/test/unit-tests/utils/userStatus-test.ts @@ -5,9 +5,15 @@ SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Com Please see LICENSE files in the repository root for full details. */ -import { type MatrixClient } from "matrix-js-sdk/src/matrix"; +import { type MatrixClient, MatrixError } from "matrix-js-sdk/src/matrix"; +import { mocked } from "jest-mock"; -import { clearUserStatus, setUserStatus, userStatusTextWithinMaxLength } from "../../../src/utils/userStatus"; +import { + clearUserStatus, + fetchUserStatus, + setUserStatus, + userStatusTextWithinMaxLength, +} from "../../../src/utils/userStatus"; import { stubClient } from "../../test-utils"; describe("userStatus utils", () => { @@ -39,6 +45,60 @@ describe("userStatus utils", () => { }); }); + describe("fetchUserStatus", () => { + let client: MatrixClient; + + beforeEach(() => { + client = stubClient(); + client.doesServerSupportExtendedProfiles = jest.fn(); + }); + + it("returns undefined if the server does not support extended profiles", async () => { + mocked(client.doesServerSupportExtendedProfiles).mockResolvedValue(false); + + await expect(fetchUserStatus(client, "@alice:example.com")).resolves.toBeUndefined(); + expect(client.getExtendedProfileProperty).not.toHaveBeenCalled(); + }); + + it("returns the validated status if the server supports extended profiles and has a status set", async () => { + mocked(client.doesServerSupportExtendedProfiles).mockResolvedValue(true); + mocked(client.getExtendedProfileProperty).mockResolvedValue({ emoji: "🐳", text: "Feeling a little blue" }); + + await expect(fetchUserStatus(client, "@alice:example.com")).resolves.toEqual({ + emoji: "🐳", + text: "Feeling a little blue", + }); + expect(client.getExtendedProfileProperty).toHaveBeenCalledWith( + "@alice:example.com", + "org.matrix.msc4426.status", + ); + }); + + it("returns undefined if the status is invalid", async () => { + mocked(client.doesServerSupportExtendedProfiles).mockResolvedValue(true); + mocked(client.getExtendedProfileProperty).mockResolvedValue({ text: "Feeling a little blue" }); + + await expect(fetchUserStatus(client, "@alice:example.com")).resolves.toBeUndefined(); + }); + + it("returns undefined if the user has no status set", async () => { + mocked(client.doesServerSupportExtendedProfiles).mockResolvedValue(true); + mocked(client.getExtendedProfileProperty).mockRejectedValue( + new MatrixError({ errcode: "M_NOT_FOUND" }, 404), + ); + + await expect(fetchUserStatus(client, "@alice:example.com")).resolves.toBeUndefined(); + }); + + it("returns undefined and logs a warning if fetching the status fails unexpectedly", async () => { + mocked(client.doesServerSupportExtendedProfiles).mockResolvedValue(true); + const error = new Error("network error"); + mocked(client.getExtendedProfileProperty).mockRejectedValue(error); + + await expect(fetchUserStatus(client, "@alice:example.com")).resolves.toBeUndefined(); + }); + }); + describe("clearUserStatus", () => { let client: MatrixClient; diff --git a/packages/shared-components/__vis__/linux/__baselines__/room-list/VirtualizedRoomListView/RoomListItemWrapper/RoomListItemView/RoomListItemView.stories.tsx/with-user-status-auto.png b/packages/shared-components/__vis__/linux/__baselines__/room-list/VirtualizedRoomListView/RoomListItemWrapper/RoomListItemView/RoomListItemView.stories.tsx/with-user-status-auto.png new file mode 100644 index 00000000000..fddb8cd7ef9 Binary files /dev/null and b/packages/shared-components/__vis__/linux/__baselines__/room-list/VirtualizedRoomListView/RoomListItemWrapper/RoomListItemView/RoomListItemView.stories.tsx/with-user-status-auto.png differ diff --git a/packages/shared-components/src/core/userStatus.ts b/packages/shared-components/src/core/userStatus.ts index 6aada947ef0..65144bd7d5c 100644 --- a/packages/shared-components/src/core/userStatus.ts +++ b/packages/shared-components/src/core/userStatus.ts @@ -10,6 +10,12 @@ Please see LICENSE files in the repository root for full details. * The emoji should be a single grapheme cluster. */ export interface UserStatus { + /** + * The emoji representing the user's status. This must be a single grapheme cluster. + */ emoji: string; + /** + * The text representing the user's status. + */ text: string; } diff --git a/packages/shared-components/src/room-list/VirtualizedRoomListView/RoomListItemWrapper/RoomListItemView/RoomListItemContent.tsx b/packages/shared-components/src/room-list/VirtualizedRoomListView/RoomListItemWrapper/RoomListItemView/RoomListItemContent.tsx index 4843a3463f5..d1937ef7a00 100644 --- a/packages/shared-components/src/room-list/VirtualizedRoomListView/RoomListItemWrapper/RoomListItemView/RoomListItemContent.tsx +++ b/packages/shared-components/src/room-list/VirtualizedRoomListView/RoomListItemWrapper/RoomListItemView/RoomListItemContent.tsx @@ -6,7 +6,7 @@ */ import React, { type JSX, memo, type ReactNode } from "react"; -import { Text } from "@vector-im/compound-web"; +import { Text, Tooltip } from "@vector-im/compound-web"; import classNames from "classnames"; import { Flex } from "../../../../core/utils/Flex"; @@ -54,7 +54,15 @@ export const RoomListItemContent = memo(function RoomListItemContent({
{item.name} + {item.userStatus && ( + + + {item.userStatus.emoji} + + + )}
+ {item.messagePreview && ( {item.messagePreview} diff --git a/packages/shared-components/src/room-list/VirtualizedRoomListView/RoomListItemWrapper/RoomListItemView/RoomListItemView.module.css b/packages/shared-components/src/room-list/VirtualizedRoomListView/RoomListItemWrapper/RoomListItemView/RoomListItemView.module.css index 4359634380e..f6a46413989 100644 --- a/packages/shared-components/src/room-list/VirtualizedRoomListView/RoomListItemWrapper/RoomListItemView/RoomListItemView.module.css +++ b/packages/shared-components/src/room-list/VirtualizedRoomListView/RoomListItemWrapper/RoomListItemView/RoomListItemView.module.css @@ -99,6 +99,15 @@ text-overflow: ellipsis; } +.roomName { + /* Allow the room name to shrink and truncate when displayed next to the user status emoji */ + min-width: 0; +} + +.userStatusEmoji { + padding-left: var(--cpd-space-1-5x); +} + .selected { .container { background-color: var(--cpd-color-bg-action-tertiary-selected); diff --git a/packages/shared-components/src/room-list/VirtualizedRoomListView/RoomListItemWrapper/RoomListItemView/RoomListItemView.stories.tsx b/packages/shared-components/src/room-list/VirtualizedRoomListView/RoomListItemWrapper/RoomListItemView/RoomListItemView.stories.tsx index 1cd951673d4..6834c552418 100644 --- a/packages/shared-components/src/room-list/VirtualizedRoomListView/RoomListItemWrapper/RoomListItemView/RoomListItemView.stories.tsx +++ b/packages/shared-components/src/room-list/VirtualizedRoomListView/RoomListItemWrapper/RoomListItemView/RoomListItemView.stories.tsx @@ -314,3 +314,12 @@ export const SectionDisabled: Story = { areSectionsEnabled: false, }, }; + +export const WithUserStatus: Story = { + args: { + userStatus: { + emoji: "🌭", + text: "Hot", + }, + }, +}; diff --git a/packages/shared-components/src/room-list/VirtualizedRoomListView/RoomListItemWrapper/RoomListItemView/RoomListItemView.tsx b/packages/shared-components/src/room-list/VirtualizedRoomListView/RoomListItemWrapper/RoomListItemView/RoomListItemView.tsx index 1f3e4bf86c6..2f395df6560 100644 --- a/packages/shared-components/src/room-list/VirtualizedRoomListView/RoomListItemWrapper/RoomListItemView/RoomListItemView.tsx +++ b/packages/shared-components/src/room-list/VirtualizedRoomListView/RoomListItemWrapper/RoomListItemView/RoomListItemView.tsx @@ -16,6 +16,7 @@ import { RoomListItemContent } from "./RoomListItemContent"; import { type RoomNotifState } from "./RoomNotifs"; import styles from "./RoomListItemView.module.css"; import { useViewModel, type ViewModel } from "../../../../core/viewmodel"; +import { type UserStatus } from "../../../../core/userStatus"; import { _t } from "../../../../core/i18n/i18n"; /** @@ -72,6 +73,8 @@ export interface RoomListItemViewSnapshot { isBold: boolean; /** Optional message preview text */ messagePreview?: string; + /** The MSC4426 user status of the other user in a DM room, if any */ + userStatus?: UserStatus; /** Notification decoration data */ notification: NotificationDecorationData; /** Whether the more options menu should be shown */ diff --git a/packages/shared-components/src/room/timeline/event-tile/EventTileView/DisambiguatedProfile/DisambiguatedProfileView.tsx b/packages/shared-components/src/room/timeline/event-tile/EventTileView/DisambiguatedProfile/DisambiguatedProfileView.tsx index f7a3a2b62a9..fd710674433 100644 --- a/packages/shared-components/src/room/timeline/event-tile/EventTileView/DisambiguatedProfile/DisambiguatedProfileView.tsx +++ b/packages/shared-components/src/room/timeline/event-tile/EventTileView/DisambiguatedProfile/DisambiguatedProfileView.tsx @@ -91,7 +91,7 @@ interface DisambiguatedProfileViewProps { export function DisambiguatedProfileView({ vm, className }: Readonly): JSX.Element { const { displayName, colorClass, displayIdentifier, title, emphasizeDisplayName, userStatus } = useViewModel(vm); - const userStatusEmoji = userStatus && [...new Intl.Segmenter().segment(userStatus.emoji)][0]?.segment; + const userStatusEmoji = userStatus && userStatus.emoji; const displayNameClasses = classNames(colorClass, { [styles.disambiguatedProfile_displayName]: emphasizeDisplayName,