mirror of
https://github.com/Novaloop-AG/healthchat-web.git
synced 2026-11-24 18:59:17 +00:00
Refactor RoomAvatar to MVVM pattern (#33937)
* Refactor RoomAvatar to MVVM pattern * Fix OXFMT failing passes * Fix stories build issue * add snapshot images + fix props issue * Fix Eslint error * Fix RoomAvatarViewModel test client setup * Remove dead code left over from RoomAvatar refactor * Update snapshot * Fix RoomHeader avatar label and update RoomView snapshots * Update snapshots * Update snapshots * Update Snapshots * Update snapshots * Update snapshot * Fix room avatar component naming * Simplify room avatar view model updates * Update decorated room avatar view tests * Document room avatar view model props * Fix Oxlint error * Fix image (correct image now) * Fix mistake * Use VM disposables for room avatar listeners * Move room avatar view attrs into snapshot * Update image * Fix room avatar oxlint filename errors * Format room avatar MVVM files * Update room avatar VM test setter * Update snapshot * Use scoped room avatar listener disposables * Use VM disposables * Restore scoped disposables
This commit is contained in:
@@ -82,7 +82,7 @@ function tooltipText(variant: Icon): string | undefined {
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use {@link RoomAvatarView} instead.
|
||||
* @deprecated Use {@link DecoratedRoomAvatarView} instead.
|
||||
*/
|
||||
export default class DecoratedRoomAvatar extends React.PureComponent<IProps, IState> {
|
||||
private _dmUser: User | null = null;
|
||||
|
||||
+4
-2
@@ -22,7 +22,7 @@ import { AvatarBadgeDecoration, useRoomAvatarViewModel } from "../../viewmodels/
|
||||
import { _t } from "../../../languageHandler";
|
||||
import { Presence } from "./WithPresenceIndicator";
|
||||
|
||||
interface RoomAvatarViewProps {
|
||||
interface DecoratedRoomAvatarViewProps {
|
||||
/**
|
||||
* The room to display the avatar for.
|
||||
*/
|
||||
@@ -33,7 +33,9 @@ interface RoomAvatarViewProps {
|
||||
* Component to display the avatar of a room.
|
||||
* Currently only 32px size is supported.
|
||||
*/
|
||||
export const RoomAvatarView = memo(function RoomAvatarView({ room }: RoomAvatarViewProps): JSX.Element {
|
||||
export const DecoratedRoomAvatarView = memo(function DecoratedRoomAvatarView({
|
||||
room,
|
||||
}: DecoratedRoomAvatarViewProps): JSX.Element {
|
||||
const vm = useRoomAvatarViewModel(room);
|
||||
// No decoration, we just show the avatar
|
||||
if (!vm.badgeDecoration) return <RoomAvatar size="32px" room={room} />;
|
||||
@@ -1,99 +1,157 @@
|
||||
/*
|
||||
Copyright 2024, 2025 New Vector Ltd.
|
||||
Copyright 2015, 2016 OpenMarket Ltd
|
||||
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.
|
||||
*/
|
||||
|
||||
import React, { useCallback, useMemo, type ComponentProps } from "react";
|
||||
import { type Room, RoomType, KnownMembership, EventType, RoomEvent } from "matrix-js-sdk/src/matrix";
|
||||
import { type RoomAvatarEventContent } from "matrix-js-sdk/src/types";
|
||||
import React, { type JSX, type Ref, useEffect } from "react";
|
||||
import classNames from "classnames";
|
||||
import { type Room } from "matrix-js-sdk/src/matrix";
|
||||
import {
|
||||
RoomAvatarView as RoomAvatarPresentationView,
|
||||
type RoomAvatarViewSnapshot,
|
||||
useCreateAutoDisposedViewModel,
|
||||
} from "@element-hq/web-shared-components";
|
||||
|
||||
import BaseAvatar from "./BaseAvatar";
|
||||
import ImageView from "../elements/ImageView";
|
||||
import Modal from "../../../Modal";
|
||||
import * as Avatar from "../../../Avatar";
|
||||
import { mediaFromMxc } from "../../../customisations/Media";
|
||||
import { type IOOBData } from "../../../stores/ThreepidInviteStore";
|
||||
import { filterBoolean } from "../../../utils/arrays";
|
||||
import { useSettingValue } from "../../../hooks/useSettings";
|
||||
import { useRoomState } from "../../../hooks/useRoomState";
|
||||
import { useRoomIdName } from "../../../hooks/room/useRoomIdName";
|
||||
import { MediaPreviewValue } from "../../../@types/media_preview";
|
||||
import { useTypedEventEmitterState } from "../../../hooks/useEventEmitter";
|
||||
import { RoomAvatarViewModel } from "../../../viewmodels/avatars/RoomAvatarViewModel";
|
||||
|
||||
interface IProps extends Omit<ComponentProps<typeof BaseAvatar>, "name" | "idName" | "url" | "onClick" | "size"> {
|
||||
// Room may be left unset here, but if it is,
|
||||
// oobData.avatarUrl should be set (else there
|
||||
// would be nowhere to get the avatar from)
|
||||
room?: Room;
|
||||
// Optional here.
|
||||
size?: ComponentProps<typeof BaseAvatar>["size"];
|
||||
oobData?: IOOBData & {
|
||||
interface Props {
|
||||
/**
|
||||
* The room whose avatar should be displayed.
|
||||
* When omitted, `oobData.avatarUrl` must be provided.
|
||||
*/
|
||||
"room"?: Room;
|
||||
/**
|
||||
* Out-of-band data used when the room object is not yet available,
|
||||
* e.g. during a three-pid invite flow.
|
||||
*/
|
||||
"oobData"?: IOOBData & {
|
||||
roomId?: string;
|
||||
};
|
||||
viewAvatarOnClick?: boolean;
|
||||
onClick?(this: void): void;
|
||||
/**
|
||||
* When `true`, clicking the avatar opens a full-size lightbox.
|
||||
* Defaults to `false`; `false` and `undefined` are equivalent.
|
||||
*/
|
||||
"viewAvatarOnClick"?: boolean;
|
||||
/**
|
||||
* Custom click handler. Takes precedence over the lightbox when both are set.
|
||||
*/
|
||||
"onClick"?(): void;
|
||||
/**
|
||||
* Rendered size of the avatar in CSS units. Defaults to `"36px"`.
|
||||
*/
|
||||
"size"?: string;
|
||||
/**
|
||||
* Avatar shape override. When omitted, the ViewModel derives `"square"` for
|
||||
* spaces and `"round"` for all other rooms and invites.
|
||||
*/
|
||||
"type"?: "round" | "square";
|
||||
/**
|
||||
* Optional additional CSS class names.
|
||||
*/
|
||||
"className"?: string;
|
||||
/**
|
||||
* Accessible label announced by assistive technologies.
|
||||
*/
|
||||
"altText"?: string;
|
||||
/**
|
||||
* Browser tooltip shown on hover.
|
||||
*/
|
||||
"title"?: string;
|
||||
/**
|
||||
* Tab index forwarded to the avatar element.
|
||||
*/
|
||||
"tabIndex"?: number;
|
||||
/**
|
||||
* ARIA role override for the avatar element.
|
||||
*/
|
||||
"role"?: RoomAvatarViewSnapshot["role"];
|
||||
/**
|
||||
* When `true`, hides the avatar from the accessibility tree.
|
||||
*/
|
||||
"aria-hidden"?: boolean;
|
||||
/**
|
||||
* Ref forwarded to the underlying avatar element.
|
||||
*/
|
||||
"ref"?: Ref<HTMLButtonElement | HTMLSpanElement>;
|
||||
}
|
||||
|
||||
const RoomAvatar: React.FC<IProps> = ({ room, viewAvatarOnClick, onClick, oobData, size = "36px", ...otherProps }) => {
|
||||
const name = useTypedEventEmitterState(room, RoomEvent.Name, () => room?.name);
|
||||
const roomName = name ?? oobData?.name ?? "?";
|
||||
const avatarEvent = useRoomState(room, (state) => state.getStateEvents(EventType.RoomAvatar, ""));
|
||||
const roomIdName = useRoomIdName(room, oobData);
|
||||
|
||||
const showAvatarsOnInvites =
|
||||
useSettingValue("mediaPreviewConfig", room?.roomId).invite_avatars === MediaPreviewValue.On;
|
||||
|
||||
const onRoomAvatarClick = useCallback(() => {
|
||||
const avatarUrl = Avatar.avatarUrlForRoom(room ?? null);
|
||||
if (!avatarUrl) return;
|
||||
const params = {
|
||||
src: avatarUrl,
|
||||
name: room?.name,
|
||||
};
|
||||
|
||||
Modal.createDialog(ImageView, params, "mx_Dialog_lightbox", undefined, true);
|
||||
}, [room]);
|
||||
|
||||
const urls = useMemo(() => {
|
||||
const myMembership = room?.getMyMembership();
|
||||
if (!showAvatarsOnInvites && (myMembership === KnownMembership.Invite || !myMembership)) {
|
||||
// The user has opted out of showing avatars, so return no urls here.
|
||||
return [];
|
||||
}
|
||||
|
||||
// parseInt ignores suffixes.
|
||||
const sizeInt = parseInt(size, 10);
|
||||
let oobAvatar: string | null = null;
|
||||
if (oobData?.avatarUrl) {
|
||||
oobAvatar = mediaFromMxc(oobData?.avatarUrl).getThumbnailOfSourceHttp(sizeInt, sizeInt, "crop");
|
||||
}
|
||||
|
||||
return filterBoolean([
|
||||
oobAvatar, // highest priority
|
||||
Avatar.avatarUrlForRoom(
|
||||
room ?? null,
|
||||
sizeInt,
|
||||
sizeInt,
|
||||
"crop",
|
||||
avatarEvent?.getContent<RoomAvatarEventContent>().url,
|
||||
),
|
||||
]);
|
||||
}, [showAvatarsOnInvites, room, size, avatarEvent, oobData]);
|
||||
|
||||
return (
|
||||
<BaseAvatar
|
||||
{...otherProps}
|
||||
size={size}
|
||||
type={(room?.getType() ?? oobData?.roomType) === RoomType.Space ? "square" : "round"}
|
||||
name={roomName}
|
||||
idName={roomIdName}
|
||||
urls={urls}
|
||||
onClick={viewAvatarOnClick && urls[0] ? onRoomAvatarClick : onClick}
|
||||
/>
|
||||
/**
|
||||
* Public room avatar component backed by MVVM.
|
||||
*
|
||||
* Wires a {@link RoomAvatarViewModel} to the shared room avatar view and
|
||||
* synchronises changing props into the ViewModel via targeted setters.
|
||||
* The MVVM split is an implementation detail for consumers.
|
||||
*/
|
||||
function RoomAvatar({
|
||||
room,
|
||||
viewAvatarOnClick = false,
|
||||
onClick,
|
||||
oobData,
|
||||
size = "36px",
|
||||
type,
|
||||
className,
|
||||
altText,
|
||||
title,
|
||||
tabIndex,
|
||||
role,
|
||||
"aria-hidden": ariaHidden,
|
||||
ref,
|
||||
}: Readonly<Props>): JSX.Element {
|
||||
const avatarClassName = classNames("mx_BaseAvatar", className);
|
||||
const vm = useCreateAutoDisposedViewModel(
|
||||
() =>
|
||||
new RoomAvatarViewModel({
|
||||
room,
|
||||
size,
|
||||
oobData,
|
||||
viewAvatarOnClick,
|
||||
onClick,
|
||||
type,
|
||||
className: avatarClassName,
|
||||
altText,
|
||||
title,
|
||||
tabIndex,
|
||||
role,
|
||||
ariaHidden,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
vm.setRoom(room);
|
||||
}, [room, vm]);
|
||||
|
||||
useEffect(() => {
|
||||
vm.setOobData(oobData);
|
||||
}, [oobData, vm]);
|
||||
|
||||
useEffect(() => {
|
||||
vm.setViewAvatarOnClick(viewAvatarOnClick);
|
||||
}, [viewAvatarOnClick, vm]);
|
||||
|
||||
useEffect(() => {
|
||||
vm.setOnClick(onClick);
|
||||
}, [onClick, vm]);
|
||||
|
||||
useEffect(() => {
|
||||
vm.setType(type);
|
||||
}, [type, vm]);
|
||||
|
||||
useEffect(() => {
|
||||
vm.setViewProps({
|
||||
size,
|
||||
className: avatarClassName,
|
||||
altText,
|
||||
title,
|
||||
tabIndex,
|
||||
role,
|
||||
ariaHidden,
|
||||
});
|
||||
}, [size, avatarClassName, altText, title, tabIndex, role, ariaHidden, vm]);
|
||||
|
||||
return <RoomAvatarPresentationView vm={vm} ref={ref} />;
|
||||
}
|
||||
|
||||
export default RoomAvatar;
|
||||
|
||||
@@ -30,7 +30,7 @@ const PillRoomAvatar: React.FC<{
|
||||
}
|
||||
|
||||
if (room) {
|
||||
return <RoomAvatar room={room} size="16px" aria-hidden="true" />;
|
||||
return <RoomAvatar room={room} size="16px" aria-hidden={true} />;
|
||||
}
|
||||
return linkIcon;
|
||||
};
|
||||
|
||||
@@ -43,7 +43,7 @@ import { Box, Flex, HistoryVisibilityBadge, LinkedText, StatusTextView } from "@
|
||||
|
||||
import BaseCard from "./BaseCard.tsx";
|
||||
import { _t } from "../../../languageHandler";
|
||||
import RoomAvatar from "../avatars/RoomAvatar.tsx";
|
||||
import RoomAvatar from "../avatars/RoomAvatar";
|
||||
import { E2EStatus } from "../../../utils/ShieldUtils.ts";
|
||||
import { type RoomPermalinkCreator } from "../../../utils/permalinks/Permalinks.ts";
|
||||
import { topicToHtml } from "../../../HtmlUtils.tsx";
|
||||
|
||||
@@ -36,7 +36,7 @@ import { useEncryptionStatus } from "../../../../hooks/useEncryptionStatus.ts";
|
||||
import { E2EStatus } from "../../../../utils/ShieldUtils.ts";
|
||||
import FacePile from "../../elements/FacePile.tsx";
|
||||
import { useRoomState } from "../../../../hooks/useRoomState.ts";
|
||||
import RoomAvatar from "../../avatars/RoomAvatar.tsx";
|
||||
import RoomAvatar from "../../avatars/RoomAvatar";
|
||||
import { formatCount } from "../../../../utils/FormattingUtils.ts";
|
||||
import PosthogTrackers from "../../../../PosthogTrackers.ts";
|
||||
import { VideoRoomChatButton } from "./VideoRoomChatButton.tsx";
|
||||
@@ -472,7 +472,7 @@ export default function RoomHeader({
|
||||
oobData={oobData}
|
||||
onClick={room instanceof LocalRoom ? undefined : onAvatarClick}
|
||||
tabIndex={-1}
|
||||
aria-label={_t("room|header_avatar_open_settings_label")}
|
||||
altText={_t("room|header_avatar_open_settings_label")}
|
||||
/>
|
||||
</WithPresenceIndicator>
|
||||
{/* Disable on-click actions until the room is created */}
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
} from "@element-hq/web-shared-components";
|
||||
import { type Room } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import { RoomAvatarView } from "../../avatars/RoomAvatarView";
|
||||
import { DecoratedRoomAvatarView } from "../../avatars/DecoratedRoomAvatarView";
|
||||
import { getKeyBindingsManager } from "../../../../KeyBindingsManager";
|
||||
import { KeyBindingAction } from "../../../../accessibility/KeyboardShortcuts";
|
||||
import { Landmark, LandmarkNavigation } from "../../../../accessibility/LandmarkNavigation";
|
||||
@@ -38,7 +38,7 @@ export function RoomListView(): JSX.Element {
|
||||
|
||||
// Render avatar for each room - memoized to prevent re-renders
|
||||
const renderAvatar = useCallback((room: SharedRoom): ReactNode => {
|
||||
return <RoomAvatarView room={room as Room} />;
|
||||
return <DecoratedRoomAvatarView room={room as Room} />;
|
||||
}, []);
|
||||
|
||||
// Handle keyboard navigation for landmarks
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
/*
|
||||
Copyright 2025 New Vector 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.
|
||||
*/
|
||||
|
||||
import { type Room } from "matrix-js-sdk/src/matrix";
|
||||
|
||||
import { useDmMember } from "../../components/views/avatars/WithPresenceIndicator.tsx";
|
||||
import { LocalRoom } from "../../models/LocalRoom.ts";
|
||||
|
||||
/**
|
||||
* Determine a stable ID for generating hash colours. If the room
|
||||
* is a DM (or local room), then the other user's ID will be used.
|
||||
* @param oobData - out-of-band information about the room
|
||||
* @returns An ID string, or undefined if the room and oobData are undefined.
|
||||
*/
|
||||
export function useRoomIdName(room?: Room, oobData?: { roomId?: string }): string | undefined {
|
||||
const dmMember = useDmMember(room);
|
||||
if (dmMember) {
|
||||
// If the room is a DM, we use the other user's ID for the color hash
|
||||
// in order to match the room avatar with their avatar
|
||||
return dmMember.userId;
|
||||
} else if (room instanceof LocalRoom && room.targets.length === 1) {
|
||||
return room.targets[0].userId;
|
||||
} else if (room) {
|
||||
return room.roomId;
|
||||
} else {
|
||||
return oobData?.roomId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
/*
|
||||
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.
|
||||
*/
|
||||
|
||||
import {
|
||||
ClientEvent,
|
||||
EventType,
|
||||
KnownMembership,
|
||||
RoomEvent,
|
||||
RoomStateEvent,
|
||||
RoomType,
|
||||
type Room,
|
||||
type RoomMember,
|
||||
} from "matrix-js-sdk/src/matrix";
|
||||
import { type RoomAvatarEventContent } from "matrix-js-sdk/src/types";
|
||||
import {
|
||||
BaseViewModel,
|
||||
Disposables,
|
||||
type RoomAvatarViewModel as RoomAvatarViewModelInterface,
|
||||
type RoomAvatarViewSnapshot,
|
||||
} from "@element-hq/web-shared-components";
|
||||
|
||||
import * as Avatar from "../../Avatar";
|
||||
import Modal from "../../Modal";
|
||||
import ImageView from "../../components/views/elements/ImageView";
|
||||
import { mediaFromMxc } from "../../customisations/Media";
|
||||
import { LocalRoom } from "../../models/LocalRoom";
|
||||
import { type IOOBData } from "../../stores/ThreepidInviteStore";
|
||||
import SettingsStore from "../../settings/SettingsStore";
|
||||
import DMRoomMap from "../../utils/DMRoomMap";
|
||||
import { arrayHasDiff, filterBoolean } from "../../utils/arrays";
|
||||
import { MediaPreviewValue } from "../../@types/media_preview";
|
||||
|
||||
interface Props {
|
||||
/**
|
||||
* Room whose avatar data should be rendered.
|
||||
*/
|
||||
room?: Room;
|
||||
/**
|
||||
* Rendered avatar size in CSS units, used when requesting thumbnail URLs.
|
||||
*/
|
||||
size: string;
|
||||
/**
|
||||
* Out-of-band room data used when the room object is not available yet.
|
||||
*/
|
||||
oobData?: IOOBData & {
|
||||
/**
|
||||
* Room ID to use for hash-colour generation before the room exists locally.
|
||||
*/
|
||||
roomId?: string;
|
||||
};
|
||||
/**
|
||||
* Whether clicking the avatar should open the full-size avatar lightbox.
|
||||
*/
|
||||
viewAvatarOnClick?: boolean;
|
||||
/**
|
||||
* Optional click handler invoked when lightbox behaviour is disabled.
|
||||
*/
|
||||
onClick?: () => void;
|
||||
/**
|
||||
* Optional shape override. When omitted, the VM derives the shape from the room type.
|
||||
*/
|
||||
type?: "round" | "square";
|
||||
/**
|
||||
* Optional additional CSS class names applied to the avatar element.
|
||||
*/
|
||||
className?: string;
|
||||
/**
|
||||
* Accessible label announced by assistive technologies.
|
||||
*/
|
||||
altText?: string;
|
||||
/**
|
||||
* Browser tooltip shown on hover.
|
||||
*/
|
||||
title?: string;
|
||||
/**
|
||||
* Tab index forwarded to the avatar element.
|
||||
*/
|
||||
tabIndex?: number;
|
||||
/**
|
||||
* ARIA role override for the avatar element.
|
||||
*/
|
||||
role?: RoomAvatarViewSnapshot["role"];
|
||||
/**
|
||||
* Whether to hide the avatar from the accessibility tree.
|
||||
*/
|
||||
ariaHidden?: boolean;
|
||||
}
|
||||
|
||||
type ViewProps = Pick<Props, "size" | "className" | "altText" | "title" | "tabIndex" | "role" | "ariaHidden">;
|
||||
|
||||
export class RoomAvatarViewModel
|
||||
extends BaseViewModel<RoomAvatarViewSnapshot, Props>
|
||||
implements RoomAvatarViewModelInterface
|
||||
{
|
||||
private roomListenerDisposables?: Disposables;
|
||||
private mediaPreviewSettingDisposables?: Disposables;
|
||||
|
||||
public constructor(props: Props) {
|
||||
super(props, RoomAvatarViewModel.computeSnapshot(props));
|
||||
this.bindRoomListeners(props.room);
|
||||
this.bindMediaPreviewSettingWatcher(props.room);
|
||||
|
||||
this.disposables.track(() => {
|
||||
this.roomListenerDisposables?.dispose();
|
||||
this.clearMediaPreviewSettingWatcher();
|
||||
});
|
||||
}
|
||||
|
||||
public setRoom(room?: Room): void {
|
||||
this.props = { ...this.props, room };
|
||||
this.bindRoomListeners(room);
|
||||
this.bindMediaPreviewSettingWatcher(room);
|
||||
this.refreshSnapshot();
|
||||
}
|
||||
|
||||
public setViewProps(viewProps: ViewProps): void {
|
||||
this.props = { ...this.props, ...viewProps };
|
||||
this.refreshSnapshot();
|
||||
}
|
||||
|
||||
public setOobData(oobData?: IOOBData & { roomId?: string }): void {
|
||||
this.props = { ...this.props, oobData };
|
||||
this.refreshSnapshot();
|
||||
}
|
||||
|
||||
public setViewAvatarOnClick(viewAvatarOnClick?: boolean): void {
|
||||
this.props = { ...this.props, viewAvatarOnClick };
|
||||
this.refreshSnapshot();
|
||||
}
|
||||
|
||||
public setOnClick(onClick?: () => void): void {
|
||||
this.props = { ...this.props, onClick };
|
||||
this.refreshSnapshot();
|
||||
}
|
||||
|
||||
public setType(type?: "round" | "square"): void {
|
||||
this.props = { ...this.props, type };
|
||||
this.refreshSnapshot();
|
||||
}
|
||||
|
||||
public onClick = (): void => {
|
||||
if (this.props.viewAvatarOnClick && this.snapshot.current.urls[0]) {
|
||||
const avatarUrl = Avatar.avatarUrlForRoom(this.props.room ?? null);
|
||||
if (!avatarUrl) return;
|
||||
|
||||
Modal.createDialog(
|
||||
ImageView,
|
||||
{
|
||||
src: avatarUrl,
|
||||
name: this.props.room?.name,
|
||||
},
|
||||
"mx_Dialog_lightbox",
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
this.props.onClick?.();
|
||||
};
|
||||
|
||||
private static computeSnapshot(props: Props): RoomAvatarViewSnapshot {
|
||||
const urls = RoomAvatarViewModel.computeUrls(props);
|
||||
|
||||
return {
|
||||
size: props.size,
|
||||
name: RoomAvatarViewModel.computeName(props.room, props.oobData),
|
||||
idName: RoomAvatarViewModel.computeIdName(props.room, props.oobData),
|
||||
urls,
|
||||
type: RoomAvatarViewModel.computeType(props),
|
||||
isClickable: Boolean(props.onClick || (props.viewAvatarOnClick && urls[0])),
|
||||
className: props.className,
|
||||
altText: props.altText,
|
||||
title: props.title,
|
||||
tabIndex: props.tabIndex,
|
||||
role: props.role,
|
||||
ariaHidden: props.ariaHidden,
|
||||
};
|
||||
}
|
||||
|
||||
private static computeName(room?: Room, oobData?: IOOBData & { roomId?: string }): string {
|
||||
return room?.name ?? oobData?.name ?? "?";
|
||||
}
|
||||
|
||||
private static computeIdName(room?: Room, oobData?: IOOBData & { roomId?: string }): string | undefined {
|
||||
const dmMember = RoomAvatarViewModel.getDmMember(room);
|
||||
if (dmMember) return dmMember.userId;
|
||||
|
||||
if (room instanceof LocalRoom && room.targets.length === 1) return room.targets[0].userId;
|
||||
|
||||
if (room) return room.roomId;
|
||||
|
||||
return oobData?.roomId;
|
||||
}
|
||||
|
||||
private static computeType(props: Props): "round" | "square" {
|
||||
if (props.type) return props.type;
|
||||
return (props.room?.getType() ?? props.oobData?.roomType) === RoomType.Space ? "square" : "round";
|
||||
}
|
||||
|
||||
private static computeUrls(props: Props): string[] {
|
||||
const myMembership = props.room?.getMyMembership();
|
||||
const showAvatarsOnInvites =
|
||||
SettingsStore.getValue("mediaPreviewConfig", props.room?.roomId).invite_avatars === MediaPreviewValue.On;
|
||||
|
||||
if (!showAvatarsOnInvites && (myMembership === KnownMembership.Invite || !myMembership)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const sizeInt = parseInt(props.size, 10);
|
||||
let oobAvatar: string | null = null;
|
||||
if (props.oobData?.avatarUrl) {
|
||||
oobAvatar = mediaFromMxc(props.oobData.avatarUrl).getThumbnailOfSourceHttp(sizeInt, sizeInt, "crop");
|
||||
}
|
||||
|
||||
return filterBoolean([
|
||||
oobAvatar,
|
||||
Avatar.avatarUrlForRoom(
|
||||
props.room ?? null,
|
||||
sizeInt,
|
||||
sizeInt,
|
||||
"crop",
|
||||
props.room?.currentState.getStateEvents(EventType.RoomAvatar, "")?.getContent<RoomAvatarEventContent>()
|
||||
.url,
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
private static getDmMember(room?: Room): RoomMember | null {
|
||||
if (!room) return null;
|
||||
|
||||
const otherUserId = DMRoomMap.shared().getUserIdForRoomId(room.roomId);
|
||||
return otherUserId ? room.getMember(otherUserId) : null;
|
||||
}
|
||||
|
||||
private refreshSnapshot = (): void => {
|
||||
const nextSnapshot = RoomAvatarViewModel.computeSnapshot(this.props);
|
||||
const current = this.snapshot.current;
|
||||
|
||||
this.snapshot.merge({
|
||||
...nextSnapshot,
|
||||
urls: arrayHasDiff(current.urls, nextSnapshot.urls) ? nextSnapshot.urls : current.urls,
|
||||
});
|
||||
};
|
||||
|
||||
private bindRoomListeners(room?: Room): void {
|
||||
this.roomListenerDisposables?.dispose();
|
||||
this.roomListenerDisposables = undefined;
|
||||
if (!room) return;
|
||||
|
||||
const roomListenerDisposables = new Disposables();
|
||||
roomListenerDisposables.trackListener(room, RoomEvent.Name, this.refreshSnapshot);
|
||||
roomListenerDisposables.trackListener(room, RoomEvent.MyMembership, this.refreshSnapshot);
|
||||
roomListenerDisposables.trackListener(room, RoomStateEvent.Update, this.refreshSnapshot);
|
||||
roomListenerDisposables.trackListener(room.currentState, RoomStateEvent.Update, this.refreshSnapshot);
|
||||
roomListenerDisposables.trackListener(room.currentState, RoomStateEvent.Members, this.refreshSnapshot);
|
||||
roomListenerDisposables.trackListener(room.client, ClientEvent.AccountData, this.refreshSnapshot);
|
||||
|
||||
this.roomListenerDisposables = roomListenerDisposables;
|
||||
}
|
||||
|
||||
private bindMediaPreviewSettingWatcher(room?: Room): void {
|
||||
this.clearMediaPreviewSettingWatcher();
|
||||
this.mediaPreviewSettingDisposables = new Disposables();
|
||||
|
||||
const mediaPreviewSettingWatcherRef = SettingsStore.watchSetting(
|
||||
"mediaPreviewConfig",
|
||||
room?.roomId ?? null,
|
||||
this.onMediaPreviewSettingChanged,
|
||||
);
|
||||
this.mediaPreviewSettingDisposables.track(() => SettingsStore.unwatchSetting(mediaPreviewSettingWatcherRef));
|
||||
}
|
||||
|
||||
private clearMediaPreviewSettingWatcher(): void {
|
||||
this.mediaPreviewSettingDisposables?.dispose();
|
||||
this.mediaPreviewSettingDisposables = undefined;
|
||||
}
|
||||
|
||||
private readonly onMediaPreviewSettingChanged = (): void => {
|
||||
this.refreshSnapshot();
|
||||
};
|
||||
}
|
||||
@@ -10,7 +10,6 @@ exports[`RoomView for a local room in state CREATING should match the snapshot 1
|
||||
style="--mx-flex-display: flex; --mx-flex-direction: row; --mx-flex-align: center; --mx-flex-justify: start; --mx-flex-gap: var(--cpd-space-3x); --mx-flex-wrap: nowrap;"
|
||||
>
|
||||
<span
|
||||
aria-label="Open room settings"
|
||||
class="_avatar_va14e_8 mx_BaseAvatar _avatar-imageless_va14e_55"
|
||||
data-color="3"
|
||||
data-testid="avatar-img"
|
||||
@@ -95,7 +94,6 @@ exports[`RoomView for a local room in state ERROR should match the snapshot 1`]
|
||||
style="--mx-flex-display: flex; --mx-flex-direction: row; --mx-flex-align: center; --mx-flex-justify: start; --mx-flex-gap: var(--cpd-space-3x); --mx-flex-wrap: nowrap;"
|
||||
>
|
||||
<span
|
||||
aria-label="Open room settings"
|
||||
class="_avatar_va14e_8 mx_BaseAvatar _avatar-imageless_va14e_55"
|
||||
data-color="3"
|
||||
data-testid="avatar-img"
|
||||
@@ -292,7 +290,6 @@ exports[`RoomView for a local room in state NEW should match the snapshot 1`] =
|
||||
style="--mx-flex-display: flex; --mx-flex-direction: row; --mx-flex-align: center; --mx-flex-justify: start; --mx-flex-gap: var(--cpd-space-3x); --mx-flex-wrap: nowrap;"
|
||||
>
|
||||
<span
|
||||
aria-label="Open room settings"
|
||||
class="_avatar_va14e_8 mx_BaseAvatar _avatar-imageless_va14e_55"
|
||||
data-color="3"
|
||||
data-testid="avatar-img"
|
||||
@@ -680,7 +677,6 @@ exports[`RoomView for a local room in state NEW that is encrypted should match t
|
||||
style="--mx-flex-display: flex; --mx-flex-direction: row; --mx-flex-align: center; --mx-flex-justify: start; --mx-flex-gap: var(--cpd-space-3x); --mx-flex-wrap: nowrap;"
|
||||
>
|
||||
<span
|
||||
aria-label="Open room settings"
|
||||
class="_avatar_va14e_8 mx_BaseAvatar _avatar-imageless_va14e_55"
|
||||
data-color="3"
|
||||
data-testid="avatar-img"
|
||||
|
||||
+7
-7
@@ -9,7 +9,7 @@ import React from "react";
|
||||
import { render, screen } from "jest-matrix-react";
|
||||
import { mocked } from "jest-mock";
|
||||
|
||||
import { RoomAvatarView } from "../../../../../src/components/views/avatars/RoomAvatarView";
|
||||
import { DecoratedRoomAvatarView } from "../../../../../src/components/views/avatars/DecoratedRoomAvatarView";
|
||||
import { mkStubRoom, stubClient } from "../../../../test-utils";
|
||||
import {
|
||||
AvatarBadgeDecoration,
|
||||
@@ -24,7 +24,7 @@ jest.mock("../../../../../src/components/viewmodels/avatars/RoomAvatarViewModel"
|
||||
useRoomAvatarViewModel: jest.fn(),
|
||||
}));
|
||||
|
||||
describe("<RoomAvatarView />", () => {
|
||||
describe("<DecoratedRoomAvatarView />", () => {
|
||||
const matrixClient = stubClient();
|
||||
const room = mkStubRoom("roomId", "roomName", matrixClient);
|
||||
|
||||
@@ -44,7 +44,7 @@ describe("<RoomAvatarView />", () => {
|
||||
|
||||
it("should not render a decoration", () => {
|
||||
mocked(useRoomAvatarViewModel).mockReturnValue({ ...defaultValue });
|
||||
const { asFragment } = render(<RoomAvatarView room={room} />);
|
||||
const { asFragment } = render(<DecoratedRoomAvatarView room={room} />);
|
||||
expect(asFragment()).toMatchSnapshot();
|
||||
});
|
||||
|
||||
@@ -53,7 +53,7 @@ describe("<RoomAvatarView />", () => {
|
||||
...defaultValue,
|
||||
badgeDecoration: AvatarBadgeDecoration.LowPriority,
|
||||
});
|
||||
const { asFragment } = render(<RoomAvatarView room={room} />);
|
||||
const { asFragment } = render(<DecoratedRoomAvatarView room={room} />);
|
||||
|
||||
expect(screen.getByLabelText("This is a low priority room")).toBeInTheDocument();
|
||||
expect(asFragment()).toMatchSnapshot();
|
||||
@@ -64,7 +64,7 @@ describe("<RoomAvatarView />", () => {
|
||||
...defaultValue,
|
||||
badgeDecoration: AvatarBadgeDecoration.VideoRoom,
|
||||
});
|
||||
const { asFragment } = render(<RoomAvatarView room={room} />);
|
||||
const { asFragment } = render(<DecoratedRoomAvatarView room={room} />);
|
||||
|
||||
expect(screen.getByLabelText("This room is a video room")).toBeInTheDocument();
|
||||
expect(asFragment()).toMatchSnapshot();
|
||||
@@ -75,7 +75,7 @@ describe("<RoomAvatarView />", () => {
|
||||
...defaultValue,
|
||||
badgeDecoration: AvatarBadgeDecoration.PublicRoom,
|
||||
});
|
||||
const { asFragment } = render(<RoomAvatarView room={room} />);
|
||||
const { asFragment } = render(<DecoratedRoomAvatarView room={room} />);
|
||||
|
||||
expect(screen.getByLabelText("This room is public")).toBeInTheDocument();
|
||||
expect(asFragment()).toMatchSnapshot();
|
||||
@@ -92,7 +92,7 @@ describe("<RoomAvatarView />", () => {
|
||||
badgeDecoration: AvatarBadgeDecoration.Presence,
|
||||
presence,
|
||||
});
|
||||
const { asFragment } = render(<RoomAvatarView room={room} />);
|
||||
const { asFragment } = render(<DecoratedRoomAvatarView room={room} />);
|
||||
|
||||
expect(screen.getByLabelText(label)).toBeInTheDocument();
|
||||
expect(asFragment()).toMatchSnapshot();
|
||||
+16
-8
@@ -1,6 +1,6 @@
|
||||
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
|
||||
|
||||
exports[`<RoomAvatarView /> should not render a decoration 1`] = `
|
||||
exports[`<DecoratedRoomAvatarView /> should not render a decoration 1`] = `
|
||||
<DocumentFragment>
|
||||
<span
|
||||
aria-label="Avatar"
|
||||
@@ -8,6 +8,7 @@ exports[`<RoomAvatarView /> should not render a decoration 1`] = `
|
||||
data-color="1"
|
||||
data-testid="avatar-img"
|
||||
data-type="round"
|
||||
role="img"
|
||||
style="--cpd-avatar-size: 32px;"
|
||||
>
|
||||
<img
|
||||
@@ -24,7 +25,7 @@ exports[`<RoomAvatarView /> should not render a decoration 1`] = `
|
||||
</DocumentFragment>
|
||||
`;
|
||||
|
||||
exports[`<RoomAvatarView /> should render a low priority room decoration 1`] = `
|
||||
exports[`<DecoratedRoomAvatarView /> should render a low priority room decoration 1`] = `
|
||||
<DocumentFragment>
|
||||
<div
|
||||
class="_flex_4dswl_9 mx_RoomAvatarView"
|
||||
@@ -36,6 +37,7 @@ exports[`<RoomAvatarView /> should render a low priority room decoration 1`] = `
|
||||
data-color="1"
|
||||
data-testid="avatar-img"
|
||||
data-type="round"
|
||||
role="img"
|
||||
style="--cpd-avatar-size: 32px;"
|
||||
>
|
||||
<img
|
||||
@@ -68,7 +70,7 @@ exports[`<RoomAvatarView /> should render a low priority room decoration 1`] = `
|
||||
</DocumentFragment>
|
||||
`;
|
||||
|
||||
exports[`<RoomAvatarView /> should render a public room decoration 1`] = `
|
||||
exports[`<DecoratedRoomAvatarView /> should render a public room decoration 1`] = `
|
||||
<DocumentFragment>
|
||||
<div
|
||||
class="_flex_4dswl_9 mx_RoomAvatarView"
|
||||
@@ -80,6 +82,7 @@ exports[`<RoomAvatarView /> should render a public room decoration 1`] = `
|
||||
data-color="1"
|
||||
data-testid="avatar-img"
|
||||
data-type="round"
|
||||
role="img"
|
||||
style="--cpd-avatar-size: 32px;"
|
||||
>
|
||||
<img
|
||||
@@ -112,7 +115,7 @@ exports[`<RoomAvatarView /> should render a public room decoration 1`] = `
|
||||
</DocumentFragment>
|
||||
`;
|
||||
|
||||
exports[`<RoomAvatarView /> should render a video room decoration 1`] = `
|
||||
exports[`<DecoratedRoomAvatarView /> should render a video room decoration 1`] = `
|
||||
<DocumentFragment>
|
||||
<div
|
||||
class="_flex_4dswl_9 mx_RoomAvatarView"
|
||||
@@ -124,6 +127,7 @@ exports[`<RoomAvatarView /> should render a video room decoration 1`] = `
|
||||
data-color="1"
|
||||
data-testid="avatar-img"
|
||||
data-type="round"
|
||||
role="img"
|
||||
style="--cpd-avatar-size: 32px;"
|
||||
>
|
||||
<img
|
||||
@@ -156,7 +160,7 @@ exports[`<RoomAvatarView /> should render a video room decoration 1`] = `
|
||||
</DocumentFragment>
|
||||
`;
|
||||
|
||||
exports[`<RoomAvatarView /> should render the busy presence 1`] = `
|
||||
exports[`<DecoratedRoomAvatarView /> should render the busy presence 1`] = `
|
||||
<DocumentFragment>
|
||||
<div
|
||||
class="_flex_4dswl_9 mx_RoomAvatarView"
|
||||
@@ -168,6 +172,7 @@ exports[`<RoomAvatarView /> should render the busy presence 1`] = `
|
||||
data-color="1"
|
||||
data-testid="avatar-img"
|
||||
data-type="round"
|
||||
role="img"
|
||||
style="--cpd-avatar-size: 32px;"
|
||||
>
|
||||
<img
|
||||
@@ -215,7 +220,7 @@ exports[`<RoomAvatarView /> should render the busy presence 1`] = `
|
||||
</DocumentFragment>
|
||||
`;
|
||||
|
||||
exports[`<RoomAvatarView /> should render the offline presence 1`] = `
|
||||
exports[`<DecoratedRoomAvatarView /> should render the offline presence 1`] = `
|
||||
<DocumentFragment>
|
||||
<div
|
||||
class="_flex_4dswl_9 mx_RoomAvatarView"
|
||||
@@ -227,6 +232,7 @@ exports[`<RoomAvatarView /> should render the offline presence 1`] = `
|
||||
data-color="1"
|
||||
data-testid="avatar-img"
|
||||
data-type="round"
|
||||
role="img"
|
||||
style="--cpd-avatar-size: 32px;"
|
||||
>
|
||||
<img
|
||||
@@ -274,7 +280,7 @@ exports[`<RoomAvatarView /> should render the offline presence 1`] = `
|
||||
</DocumentFragment>
|
||||
`;
|
||||
|
||||
exports[`<RoomAvatarView /> should render the online presence 1`] = `
|
||||
exports[`<DecoratedRoomAvatarView /> should render the online presence 1`] = `
|
||||
<DocumentFragment>
|
||||
<div
|
||||
class="_flex_4dswl_9 mx_RoomAvatarView"
|
||||
@@ -286,6 +292,7 @@ exports[`<RoomAvatarView /> should render the online presence 1`] = `
|
||||
data-color="1"
|
||||
data-testid="avatar-img"
|
||||
data-type="round"
|
||||
role="img"
|
||||
style="--cpd-avatar-size: 32px;"
|
||||
>
|
||||
<img
|
||||
@@ -331,7 +338,7 @@ exports[`<RoomAvatarView /> should render the online presence 1`] = `
|
||||
</DocumentFragment>
|
||||
`;
|
||||
|
||||
exports[`<RoomAvatarView /> should render the unavailable presence 1`] = `
|
||||
exports[`<DecoratedRoomAvatarView /> should render the unavailable presence 1`] = `
|
||||
<DocumentFragment>
|
||||
<div
|
||||
class="_flex_4dswl_9 mx_RoomAvatarView"
|
||||
@@ -343,6 +350,7 @@ exports[`<RoomAvatarView /> should render the unavailable presence 1`] = `
|
||||
data-color="1"
|
||||
data-testid="avatar-img"
|
||||
data-type="round"
|
||||
role="img"
|
||||
style="--cpd-avatar-size: 32px;"
|
||||
>
|
||||
<img
|
||||
+1
@@ -23,6 +23,7 @@ exports[`RoomAvatar should render an avatar for a room the user is invited to 1`
|
||||
data-color="6"
|
||||
data-testid="avatar-img"
|
||||
data-type="round"
|
||||
role="img"
|
||||
style="--cpd-avatar-size: 36px;"
|
||||
>
|
||||
<img
|
||||
|
||||
+1
@@ -120,6 +120,7 @@ exports[`<ManageRestrictedJoinRuleDialog /> should list spaces which are not par
|
||||
>
|
||||
<div>
|
||||
<span
|
||||
aria-label="Avatar"
|
||||
class="_avatar_va14e_8 mx_BaseAvatar _avatar-imageless_va14e_55"
|
||||
data-color="1"
|
||||
data-testid="avatar-img"
|
||||
|
||||
+3
-1
@@ -156,6 +156,7 @@ exports[`<TextualBody /> renders formatted m.text correctly pills appear for eve
|
||||
data-color="1"
|
||||
data-testid="avatar-img"
|
||||
data-type="round"
|
||||
role="img"
|
||||
style="--cpd-avatar-size: 16px;"
|
||||
>
|
||||
<img
|
||||
@@ -203,6 +204,7 @@ exports[`<TextualBody /> renders formatted m.text correctly pills appear for roo
|
||||
data-color="1"
|
||||
data-testid="avatar-img"
|
||||
data-type="round"
|
||||
role="img"
|
||||
style="--cpd-avatar-size: 16px;"
|
||||
>
|
||||
<img
|
||||
@@ -600,7 +602,7 @@ exports[`<TextualBody /> renders plain-text m.text correctly should pillify a ke
|
||||
|
||||
exports[`<TextualBody /> renders plain-text m.text correctly should pillify a permalink to a message in the same room with the label »Message from Member« 1`] = `"Visit <bdi><a class="mx_Pill mx_EventPill" href="https://matrix.to/#/!room1:example.com/%event_id%"><span aria-label="Profile picture" aria-hidden="true" data-testid="avatar-img" data-type="round" data-color="2" class="_avatar_va14e_8 mx_BaseAvatar" style="--cpd-avatar-size: 16px;"><img loading="lazy" alt="" referrerpolicy="no-referrer" class="_image_va14e_43" data-type="round" width="16px" height="16px" src="mxc://avatar.url/image.png"></span><span class="mx_Pill_text">Message from Member</span></a></bdi>"`;
|
||||
|
||||
exports[`<TextualBody /> renders plain-text m.text correctly should pillify a permalink to an event in another room with the label »Message in Room 2« 1`] = `"Visit <bdi><a class="mx_Pill mx_EventPill" href="https://matrix.to/#/!room2:example.com/%event_id%"><span aria-label="Avatar" aria-hidden="true" data-testid="avatar-img" data-type="round" data-color="2" class="_avatar_va14e_8 mx_BaseAvatar" style="--cpd-avatar-size: 16px;"><img loading="lazy" alt="" referrerpolicy="no-referrer" class="_image_va14e_43" data-type="round" width="16px" height="16px" src="mxc://avatar.url/room.png"></span><span class="mx_Pill_text">Message in Room 2</span></a></bdi>"`;
|
||||
exports[`<TextualBody /> renders plain-text m.text correctly should pillify a permalink to an event in another room with the label »Message in Room 2« 1`] = `"Visit <bdi><a class="mx_Pill mx_EventPill" href="https://matrix.to/#/!room2:example.com/%event_id%"><span role="img" aria-label="Avatar" aria-hidden="true" data-testid="avatar-img" data-type="round" data-color="2" class="_avatar_va14e_8 mx_BaseAvatar" style="--cpd-avatar-size: 16px;"><img loading="lazy" alt="" referrerpolicy="no-referrer" class="_image_va14e_43" data-type="round" width="16px" height="16px" src="mxc://avatar.url/room.png"></span><span class="mx_Pill_text">Message in Room 2</span></a></bdi>"`;
|
||||
|
||||
exports[`<TextualBody /> renders plain-text m.text correctly should pillify a permalink to an unknown message in the same room with the label »Message« 1`] = `
|
||||
<div
|
||||
|
||||
+1
@@ -31,6 +31,7 @@ exports[`<AddExistingToSpaceDialog /> looks as expected 1`] = `
|
||||
data-color="2"
|
||||
data-testid="avatar-img"
|
||||
data-type="square"
|
||||
role="img"
|
||||
style="--cpd-avatar-size: 40px;"
|
||||
>
|
||||
<img
|
||||
|
||||
+9
-6
@@ -95,13 +95,14 @@ exports[`SpaceItem should render a space with subspaces 1`] = `
|
||||
class="_avatar_va14e_8 mx_BaseAvatar"
|
||||
data-color="3"
|
||||
data-testid="avatar-img"
|
||||
data-type="round"
|
||||
data-type="square"
|
||||
role="img"
|
||||
style="--cpd-avatar-size: 32px;"
|
||||
>
|
||||
<img
|
||||
alt=""
|
||||
class="_image_va14e_43"
|
||||
data-type="round"
|
||||
data-type="square"
|
||||
height="32px"
|
||||
loading="lazy"
|
||||
referrerpolicy="no-referrer"
|
||||
@@ -184,13 +185,14 @@ exports[`SpaceItem should render a space with subspaces 2`] = `
|
||||
class="_avatar_va14e_8 mx_BaseAvatar"
|
||||
data-color="3"
|
||||
data-testid="avatar-img"
|
||||
data-type="round"
|
||||
data-type="square"
|
||||
role="img"
|
||||
style="--cpd-avatar-size: 32px;"
|
||||
>
|
||||
<img
|
||||
alt=""
|
||||
class="_image_va14e_43"
|
||||
data-type="round"
|
||||
data-type="square"
|
||||
height="32px"
|
||||
loading="lazy"
|
||||
referrerpolicy="no-referrer"
|
||||
@@ -252,13 +254,14 @@ exports[`SpaceItem should render a space with subspaces 2`] = `
|
||||
class="_avatar_va14e_8 mx_BaseAvatar"
|
||||
data-color="4"
|
||||
data-testid="avatar-img"
|
||||
data-type="round"
|
||||
data-type="square"
|
||||
role="img"
|
||||
style="--cpd-avatar-size: 24px;"
|
||||
>
|
||||
<img
|
||||
alt=""
|
||||
class="_image_va14e_43"
|
||||
data-type="round"
|
||||
data-type="square"
|
||||
height="24px"
|
||||
loading="lazy"
|
||||
referrerpolicy="no-referrer"
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
import { type MatrixClient, RoomEvent, RoomMember } from "matrix-js-sdk/src/matrix";
|
||||
import { act } from "react";
|
||||
|
||||
import { RoomAvatarViewModel } from "../../../src/viewmodels/avatars/RoomAvatarViewModel";
|
||||
import { LocalRoom } from "../../../src/models/LocalRoom";
|
||||
import { createTestClient, mkStubRoom } from "../../test-utils";
|
||||
import DMRoomMap from "../../../src/utils/DMRoomMap";
|
||||
import { DirectoryMember } from "../../../src/utils/direct-messages";
|
||||
|
||||
jest.mock("../../../src/customisations/Media", () => ({
|
||||
mediaFromMxc: jest.fn(() => ({
|
||||
srcHttp: "https://example.org/avatar.png",
|
||||
getThumbnailOfSourceHttp: jest.fn(() => "https://example.org/avatar-thumbnail.png"),
|
||||
})),
|
||||
}));
|
||||
|
||||
describe("RoomAvatarViewModel", () => {
|
||||
let client: MatrixClient;
|
||||
|
||||
beforeEach(() => {
|
||||
client = createTestClient();
|
||||
DMRoomMap.setShared({
|
||||
getUserIdForRoomId: jest.fn().mockReturnValue(undefined),
|
||||
} as unknown as DMRoomMap);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("uses the room data in the initial snapshot", () => {
|
||||
const room = mkStubRoom("!room:example.com", "Room name", client);
|
||||
room.name = "Room name";
|
||||
|
||||
const vm = new RoomAvatarViewModel({ room, size: "36px" });
|
||||
|
||||
expect(vm.getSnapshot()).toMatchObject({
|
||||
name: "Room name",
|
||||
idName: room.roomId,
|
||||
type: "round",
|
||||
isClickable: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("updates the snapshot when the room name changes", () => {
|
||||
const room = mkStubRoom("!room:example.com", "Room name", client);
|
||||
room.name = "Room name";
|
||||
|
||||
const vm = new RoomAvatarViewModel({ room, size: "36px" });
|
||||
const listener = jest.fn();
|
||||
vm.subscribe(listener);
|
||||
|
||||
room.name = "Updated room name";
|
||||
|
||||
act(() => {
|
||||
room.emit(RoomEvent.Name, room);
|
||||
});
|
||||
|
||||
expect(vm.getSnapshot().name).toBe("Updated room name");
|
||||
expect(listener).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("skips snapshot updates for unchanged values", () => {
|
||||
const room = mkStubRoom("!room:example.com", "Room name", client);
|
||||
room.name = "Room name";
|
||||
|
||||
const vm = new RoomAvatarViewModel({ room, size: "36px" });
|
||||
const listener = jest.fn();
|
||||
vm.subscribe(listener);
|
||||
|
||||
vm.setViewProps({ size: "36px" });
|
||||
vm.setRoom(room);
|
||||
vm.setViewAvatarOnClick(undefined);
|
||||
vm.setOnClick(undefined);
|
||||
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("derives a DM identity name when available", () => {
|
||||
const room = mkStubRoom("!room:example.com", "DM room", client);
|
||||
const userId = "@dm_user:example.com";
|
||||
jest.spyOn(room, "getMember").mockReturnValue(new RoomMember(room.roomId, userId));
|
||||
|
||||
jest.spyOn(DMRoomMap.shared(), "getUserIdForRoomId").mockReturnValue(userId);
|
||||
const vm = new RoomAvatarViewModel({ room, size: "36px" });
|
||||
|
||||
expect(vm.getSnapshot().idName).toBe(userId);
|
||||
});
|
||||
|
||||
it("prefers the local room target when there is one", () => {
|
||||
const localRoom = new LocalRoom("local+room", client, client.getSafeUserId());
|
||||
localRoom.targets.push(new DirectoryMember({ user_id: "@local:example.com" }));
|
||||
|
||||
const vm = new RoomAvatarViewModel({ room: localRoom, size: "36px" });
|
||||
|
||||
expect(vm.getSnapshot().idName).toBe("@local:example.com");
|
||||
});
|
||||
|
||||
it("invokes the supplied click handler when avatar lightbox is disabled", () => {
|
||||
const room = mkStubRoom("!room:example.com", "Room name", client);
|
||||
room.name = "Room name";
|
||||
const onClick = jest.fn();
|
||||
const vm = new RoomAvatarViewModel({ room, size: "36px", onClick });
|
||||
|
||||
vm.onClick();
|
||||
|
||||
expect(onClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("respects an explicit type override", () => {
|
||||
const room = mkStubRoom("!room:example.com", "Room name", client);
|
||||
|
||||
const vm = new RoomAvatarViewModel({ room, size: "36px", type: "square" });
|
||||
|
||||
expect(vm.getSnapshot().type).toBe("square");
|
||||
});
|
||||
|
||||
it("skips snapshot update when setType is called with the same value", () => {
|
||||
const room = mkStubRoom("!room:example.com", "Room name", client);
|
||||
|
||||
const vm = new RoomAvatarViewModel({ room, size: "36px", type: "square" });
|
||||
const listener = jest.fn();
|
||||
vm.subscribe(listener);
|
||||
|
||||
vm.setType("square");
|
||||
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
BIN
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
@@ -96,6 +96,7 @@ export * from "./core/utils/ToastContext";
|
||||
export * from "./core/i18n/I18nApi";
|
||||
export * from "./core/utils/linkify";
|
||||
export type * from "./core/userStatus.ts";
|
||||
export * from "./room/avatar/RoomAvatar";
|
||||
export * from "./status/SetStatusView";
|
||||
export * from "./status/StatusTextView";
|
||||
export * from "./status/UserStatusIconView";
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
import React, { type JSX } from "react";
|
||||
import { fn } from "storybook/test";
|
||||
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { useMockedViewModel } from "../../../core/viewmodel";
|
||||
import avatarUrl from "../../../../static/element.png";
|
||||
import { withViewDocs } from "../../../../.storybook/withViewDocs";
|
||||
import { RoomAvatarView, type RoomAvatarViewActions, type RoomAvatarViewSnapshot } from "./RoomAvatarView";
|
||||
|
||||
type WrapperProps = RoomAvatarViewSnapshot & Partial<RoomAvatarViewActions>;
|
||||
|
||||
const RoomAvatarViewWrapperImpl = ({ onClick, ...snapshotProps }: WrapperProps): JSX.Element => {
|
||||
const vm = useMockedViewModel(snapshotProps, {
|
||||
onClick: onClick ?? fn(),
|
||||
});
|
||||
|
||||
return <RoomAvatarView vm={vm} />;
|
||||
};
|
||||
|
||||
const RoomAvatarViewWrapper = withViewDocs(RoomAvatarViewWrapperImpl, RoomAvatarView);
|
||||
|
||||
const meta = {
|
||||
title: "Room/RoomAvatar",
|
||||
component: RoomAvatarViewWrapper,
|
||||
tags: ["autodocs"],
|
||||
args: {
|
||||
size: "36px",
|
||||
name: "Test Room",
|
||||
idName: "!room:example.com",
|
||||
urls: [],
|
||||
type: "round",
|
||||
isClickable: false,
|
||||
},
|
||||
} satisfies Meta<typeof RoomAvatarViewWrapper>;
|
||||
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const Default: Story = {};
|
||||
|
||||
export const WithAvatar: Story = {
|
||||
args: {
|
||||
urls: [avatarUrl],
|
||||
},
|
||||
};
|
||||
|
||||
export const SpaceRoom: Story = {
|
||||
args: {
|
||||
type: "square",
|
||||
name: "My Space",
|
||||
idName: "!space:example.com",
|
||||
},
|
||||
};
|
||||
|
||||
export const Clickable: Story = {
|
||||
args: {
|
||||
isClickable: true,
|
||||
urls: [avatarUrl],
|
||||
},
|
||||
};
|
||||
|
||||
export const LargeAvatar: Story = {
|
||||
args: {
|
||||
size: "80px",
|
||||
name: "Big Room",
|
||||
idName: "!bigroom:example.com",
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
import { composeStories } from "@storybook/react-vite";
|
||||
import { fireEvent, render, screen } from "@test-utils";
|
||||
import React from "react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { MockViewModel } from "../../../core/viewmodel";
|
||||
import {
|
||||
RoomAvatarView,
|
||||
type RoomAvatarViewActions,
|
||||
type RoomAvatarViewModel,
|
||||
type RoomAvatarViewSnapshot,
|
||||
} from "./RoomAvatarView";
|
||||
import * as stories from "./RoomAvatar.stories";
|
||||
|
||||
const { Default, SpaceRoom, Clickable } = composeStories(stories);
|
||||
|
||||
describe("RoomAvatarView", () => {
|
||||
it("renders a round avatar with initial letter", () => {
|
||||
const { container } = render(<Default />);
|
||||
expect(container).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it("renders a square avatar for a space", () => {
|
||||
const { container } = render(<SpaceRoom />);
|
||||
expect(container).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it("renders a clickable avatar", () => {
|
||||
const { container } = render(<Clickable />);
|
||||
expect(container).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it("invokes the click action when the avatar is clicked", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onClick = vi.fn();
|
||||
|
||||
class TestRoomAvatarViewModel extends MockViewModel<RoomAvatarViewSnapshot> implements RoomAvatarViewActions {
|
||||
public onClick: () => void;
|
||||
|
||||
public constructor(snapshot: RoomAvatarViewSnapshot, actions: RoomAvatarViewActions) {
|
||||
super(snapshot);
|
||||
this.onClick = actions.onClick;
|
||||
}
|
||||
}
|
||||
|
||||
const vm = new TestRoomAvatarViewModel(
|
||||
{
|
||||
size: "36px",
|
||||
name: "Test Room",
|
||||
idName: "!room:example.com",
|
||||
urls: ["https://example.com/avatar.png"],
|
||||
type: "round",
|
||||
isClickable: true,
|
||||
},
|
||||
{ onClick },
|
||||
) as RoomAvatarViewModel;
|
||||
|
||||
render(<RoomAvatarView vm={vm} />);
|
||||
|
||||
await user.click(screen.getByTestId("avatar-img"));
|
||||
|
||||
expect(onClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("cycles to the next URL on image load error", () => {
|
||||
const vm = new MockViewModel<RoomAvatarViewSnapshot>({
|
||||
size: "36px",
|
||||
name: "Test Room",
|
||||
idName: "!room:example.com",
|
||||
urls: ["https://example.com/first.png", "https://example.com/fallback.png"],
|
||||
type: "round",
|
||||
isClickable: false,
|
||||
}) as unknown as RoomAvatarViewModel;
|
||||
|
||||
render(<RoomAvatarView vm={vm} />);
|
||||
|
||||
// The image lives inside the avatar root rendered with data-testid="avatar-img".
|
||||
const getImg = (): HTMLImageElement => screen.getByTestId("avatar-img").querySelector("img")!;
|
||||
|
||||
// Verify initial URL is the first one.
|
||||
expect(getImg()).toHaveAttribute("src", "https://example.com/first.png");
|
||||
|
||||
// Trigger image error on the <img> itself to cycle to the fallback URL.
|
||||
fireEvent.error(getImg());
|
||||
|
||||
expect(getImg()).toHaveAttribute("src", "https://example.com/fallback.png");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,161 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
import React, { type AriaRole, type JSX, type Ref, useCallback, useEffect, useState } from "react";
|
||||
import { Avatar } from "@vector-im/compound-web";
|
||||
|
||||
import { type ViewModel, useViewModel } from "../../../core/viewmodel";
|
||||
|
||||
/**
|
||||
* Data provided by the ViewModel to render a room avatar.
|
||||
*/
|
||||
export interface RoomAvatarViewSnapshot {
|
||||
/**
|
||||
* Rendered size of the avatar in CSS units, e.g. `"36px"`.
|
||||
*/
|
||||
size: string;
|
||||
/**
|
||||
* Display name of the room, used for the initial-letter fallback.
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* Room ID (or DM user ID) used for consistent hash-colour generation.
|
||||
*/
|
||||
idName?: string;
|
||||
/**
|
||||
* Priority-ordered list of avatar image URLs to try. The view cycles
|
||||
* through them on image load error.
|
||||
*/
|
||||
urls: string[];
|
||||
/**
|
||||
* Avatar shape – round for regular rooms, square for spaces.
|
||||
*/
|
||||
type: "round" | "square";
|
||||
/**
|
||||
* Whether the avatar should respond to clicks.
|
||||
*/
|
||||
isClickable: boolean;
|
||||
/**
|
||||
* Optional additional CSS class names applied to the avatar element.
|
||||
*/
|
||||
className?: string;
|
||||
/**
|
||||
* Accessible label announced by assistive technologies.
|
||||
* Defaults to `"Avatar"`.
|
||||
*/
|
||||
altText?: string;
|
||||
/**
|
||||
* Browser tooltip shown on hover.
|
||||
*/
|
||||
title?: string;
|
||||
/**
|
||||
* Tab index forwarded to the avatar element.
|
||||
*/
|
||||
tabIndex?: number;
|
||||
/**
|
||||
* ARIA role override for the avatar element.
|
||||
*/
|
||||
role?: AriaRole;
|
||||
/**
|
||||
* When `true`, hides the avatar from the accessibility tree.
|
||||
*/
|
||||
ariaHidden?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Actions the host application can invoke on the room avatar ViewModel.
|
||||
*/
|
||||
export interface RoomAvatarViewActions {
|
||||
/**
|
||||
* Invoked when the user clicks the avatar.
|
||||
*/
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Combined ViewModel type accepted by {@link RoomAvatarView}.
|
||||
*/
|
||||
export type RoomAvatarViewModel = ViewModel<RoomAvatarViewSnapshot, RoomAvatarViewActions>;
|
||||
|
||||
interface RoomAvatarViewProps {
|
||||
/**
|
||||
* ViewModel providing room avatar state and the click action.
|
||||
*/
|
||||
vm: RoomAvatarViewModel;
|
||||
/**
|
||||
* Ref forwarded to the underlying avatar element.
|
||||
*/
|
||||
ref?: Ref<HTMLButtonElement | HTMLSpanElement>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a room avatar image with initial-letter fallback.
|
||||
*
|
||||
* Rendering data, styling hooks, and accessibility attributes are supplied
|
||||
* through the ViewModel snapshot.
|
||||
*/
|
||||
export function RoomAvatarView({ vm, ref }: Readonly<RoomAvatarViewProps>): JSX.Element {
|
||||
const {
|
||||
name,
|
||||
idName,
|
||||
urls,
|
||||
type,
|
||||
size,
|
||||
isClickable,
|
||||
className,
|
||||
altText = "Avatar",
|
||||
title,
|
||||
tabIndex,
|
||||
role,
|
||||
ariaHidden,
|
||||
} = useViewModel(vm);
|
||||
|
||||
const [urlIndex, setUrlIndex] = useState(0);
|
||||
|
||||
// Reset to the first URL whenever the list changes.
|
||||
useEffect(() => {
|
||||
setUrlIndex(0);
|
||||
}, [urls]);
|
||||
|
||||
const onError = useCallback(() => {
|
||||
setUrlIndex((i) => i + 1);
|
||||
}, []);
|
||||
|
||||
const src = urls[urlIndex];
|
||||
|
||||
// Avatar's default role="img" is invalid ARIA once it renders as a <button> (onClick set).
|
||||
const extraProps: { "role"?: AriaRole; "aria-live"?: "off"; "aria-label"?: string } = {};
|
||||
if (role) {
|
||||
extraProps.role = role;
|
||||
} else if (isClickable) {
|
||||
extraProps.role = "button";
|
||||
extraProps["aria-live"] = "off";
|
||||
} else if (!src) {
|
||||
extraProps.role = "presentation";
|
||||
extraProps["aria-label"] = undefined;
|
||||
}
|
||||
|
||||
return (
|
||||
<Avatar
|
||||
ref={ref}
|
||||
src={src}
|
||||
id={idName ?? ""}
|
||||
name={name}
|
||||
type={type}
|
||||
size={size}
|
||||
className={className}
|
||||
aria-label={altText}
|
||||
onError={onError}
|
||||
title={title}
|
||||
onClick={isClickable ? vm.onClick : undefined}
|
||||
tabIndex={tabIndex}
|
||||
aria-hidden={ariaHidden}
|
||||
data-testid="avatar-img"
|
||||
{...extraProps}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`RoomAvatarView > renders a clickable avatar 1`] = `
|
||||
<div>
|
||||
<button
|
||||
aria-label="Avatar"
|
||||
aria-live="off"
|
||||
class="_avatar_va14e_8"
|
||||
data-color="6"
|
||||
data-testid="avatar-img"
|
||||
data-type="round"
|
||||
role="button"
|
||||
style="--cpd-avatar-size: 36px;"
|
||||
>
|
||||
<img
|
||||
alt=""
|
||||
class="_image_va14e_43"
|
||||
data-type="round"
|
||||
height="36px"
|
||||
loading="lazy"
|
||||
referrerpolicy="no-referrer"
|
||||
src="/static/element.png"
|
||||
width="36px"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
exports[`RoomAvatarView > renders a round avatar with initial letter 1`] = `
|
||||
<div>
|
||||
<span
|
||||
class="_avatar_va14e_8 _avatar-imageless_va14e_55"
|
||||
data-color="6"
|
||||
data-testid="avatar-img"
|
||||
data-type="round"
|
||||
role="presentation"
|
||||
style="--cpd-avatar-size: 36px;"
|
||||
>
|
||||
T
|
||||
</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
exports[`RoomAvatarView > renders a square avatar for a space 1`] = `
|
||||
<div>
|
||||
<span
|
||||
class="_avatar_va14e_8 _avatar-imageless_va14e_55"
|
||||
data-color="1"
|
||||
data-testid="avatar-img"
|
||||
data-type="square"
|
||||
role="presentation"
|
||||
style="--cpd-avatar-size: 36px;"
|
||||
>
|
||||
M
|
||||
</span>
|
||||
</div>
|
||||
`;
|
||||
@@ -0,0 +1,13 @@
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
export {
|
||||
RoomAvatarView,
|
||||
type RoomAvatarViewSnapshot,
|
||||
type RoomAvatarViewActions,
|
||||
type RoomAvatarViewModel,
|
||||
} from "./RoomAvatarView";
|
||||
Reference in New Issue
Block a user