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:
Zack
2026-08-17 09:43:59 +00:00
committed by GitHub
parent 11d770aedf
commit e97358ba3e
29 changed files with 1015 additions and 150 deletions
+1
View File
@@ -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}
/>
);
}
@@ -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";