Refactor and redesign user menu (#32812)

* Initial quick settings menu

* Total refactor

* Quick design fixes.

* Refactor to use a view model.

* Remove unused strings

* Apply label

* Refactor naming

* Fixup most tests

* Remove specific theming for old user menu

* prettier

* Lots of cleanup

* Allow overriding the menu classes

* update snap

* Oops translations

* tidy

* Cleanup guest flows.

* Copyrights

* Remove unused classname

* Match guest view to designs

* Add guest screenshots

* Update guests

* snapshot

* Cleanup

* fix import

* Update tests

* More sceenshot fixes

* update collapsed

* move statements to prevent flake

* update snap

* Kick it along

* Click the room list

* Fiddle with the room video list.

* More screenshot adjustments

* fix imports

* fix another import

* Update snaps

* update snaps

* Fix snap flakes

* Refactor to move actions to view component, and callbacks to Actions

* Cleanup

* Cleanup

* Cleanup

* invert auth

* More bits

* fix

* Change md buttons to sm

* Try to assemble the snapshot component of the house of cards

* Consistent newlines between tests

* Update snapshot

Not sure why this was like this, this seems consistet for a logged in user

* Update snapshot

again these seem sensible for a guest

* Remove test

I don't really understand why the thing it asserts matters, so I'm removing
it for now.

* Update snapshot

* screenshot

* Don't show profile picture for guests

I'm not really sure what it meant for this interface to have a
property with a default value, so I've removed it and added the
property to the view model.

* Show avatar in story

* update snapshots for showAvatar

* Update screenshots

& hopefully make hover consistent in one

* Use outline home icon

---------

Co-authored-by: David Baker <dbkr@users.noreply.github.com>
This commit is contained in:
Will Hunt
2026-05-06 09:34:36 +01:00
committed by GitHub
parent bbd2d81a08
commit d4f419d1b5
58 changed files with 1231 additions and 874 deletions
@@ -1,4 +1,5 @@
/*
Copyright 2026 Element Creations Ltd.
Copyright 2024 New Vector Ltd.
Copyright 2015-2023 The Matrix.org Foundation C.I.C.
@@ -64,6 +65,7 @@ describe("<LoggedInView />", () => {
const userId = "@alice:domain.org";
const mockClient = getMockClientWithEventEmitter({
...mockClientMethodsUser(userId),
getClientWellKnown: jest.fn(),
getAccountData: jest.fn(),
getRoom: jest.fn(),
getSyncState: jest.fn().mockReturnValue(null),
@@ -104,6 +106,7 @@ describe("<LoggedInView />", () => {
mockClient.setPushRuleActions.mockReset().mockResolvedValue({});
// @ts-expect-error
mockClient.pushProcessor = new PushProcessor(mockClient);
mockSdkContext.client = mockClient;
});
describe("synced push rules", () => {
@@ -1,177 +0,0 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2022 The Matrix.org Foundation C.I.C.
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 from "react";
import { fireEvent, render, screen, waitFor } from "jest-matrix-react";
import { DEVICE_CODE_SCOPE, type MatrixClient, type Room } from "matrix-js-sdk/src/matrix";
import { type CryptoApi } from "matrix-js-sdk/src/crypto-api";
import { mocked } from "jest-mock";
import fetchMock from "@fetch-mock/jest";
import UnwrappedUserMenu from "../../../../src/components/structures/UserMenu";
import { stubClient, wrapInSdkContext } from "../../../test-utils";
import { TestSdkContext } from "../../TestSdkContext";
import defaultDispatcher from "../../../../src/dispatcher/dispatcher";
import LogoutDialog from "../../../../src/components/views/dialogs/LogoutDialog";
import Modal from "../../../../src/Modal";
import { mockOpenIdConfiguration } from "../../../test-utils/oidc";
import { Action } from "../../../../src/dispatcher/actions";
import { UserTab } from "../../../../src/components/views/dialogs/UserTab";
import SettingsStore from "../../../../src/settings/SettingsStore.ts";
describe("<UserMenu>", () => {
let client: MatrixClient;
let sdkContext: TestSdkContext;
beforeEach(() => {
sdkContext = new TestSdkContext();
});
describe("<UserMenu> logout", () => {
beforeEach(() => {
client = stubClient();
});
it("should logout directly if no crypto", async () => {
const UserMenu = wrapInSdkContext(UnwrappedUserMenu, sdkContext);
render(<UserMenu isPanelCollapsed={true} />);
mocked(client.getRooms).mockReturnValue([
{
roomId: "!room0",
} as unknown as Room,
{
roomId: "!room1",
} as unknown as Room,
]);
jest.spyOn(client, "getCrypto").mockReturnValue(undefined);
const spy = jest.spyOn(defaultDispatcher, "dispatch");
screen.getByRole("button", { name: /User menu/i }).click();
(await screen.findByRole("menuitem", { name: /Remove this device/i })).click();
await waitFor(() => {
expect(spy).toHaveBeenCalledWith({ action: "logout" });
});
});
it("should logout directly if no encrypted rooms", async () => {
const UserMenu = wrapInSdkContext(UnwrappedUserMenu, sdkContext);
render(<UserMenu isPanelCollapsed={true} />);
mocked(client.getRooms).mockReturnValue([
{
roomId: "!room0",
} as unknown as Room,
{
roomId: "!room1",
} as unknown as Room,
]);
const crypto = client.getCrypto()!;
jest.spyOn(crypto, "isEncryptionEnabledInRoom").mockResolvedValue(false);
const spy = jest.spyOn(defaultDispatcher, "dispatch");
screen.getByRole("button", { name: /User menu/i }).click();
(await screen.findByRole("menuitem", { name: /Remove this device/i })).click();
await waitFor(() => {
expect(spy).toHaveBeenCalledWith({ action: "logout" });
});
});
it("should show dialog if some encrypted rooms", async () => {
const UserMenu = wrapInSdkContext(UnwrappedUserMenu, sdkContext);
render(<UserMenu isPanelCollapsed={true} />);
mocked(client.getRooms).mockReturnValue([
{
roomId: "!room0",
} as unknown as Room,
{
roomId: "!room1",
} as unknown as Room,
]);
const crypto = client.getCrypto()!;
jest.spyOn(crypto, "isEncryptionEnabledInRoom").mockImplementation(async (roomId: string) => {
return roomId === "!room0";
});
const spy = jest.spyOn(Modal, "createDialog");
screen.getByRole("button", { name: /User menu/i }).click();
(await screen.findByRole("menuitem", { name: /Remove this device/i })).click();
await waitFor(() => {
expect(spy).toHaveBeenCalledWith(LogoutDialog);
});
});
});
it("should render 'Link new device' button in OIDC native mode", async () => {
sdkContext.client = stubClient();
const openIdMetadata = mockOpenIdConfiguration("https://issuer/");
openIdMetadata.grant_types_supported.push(DEVICE_CODE_SCOPE);
fetchMock.get("https://issuer/.well-known/openid-configuration", openIdMetadata);
fetchMock.get("https://issuer/jwks", {
status: 200,
headers: {
"Content-Type": "application/json",
},
keys: [],
});
mocked(sdkContext.client.getVersions).mockResolvedValue({
versions: [],
unstable_features: {
"org.matrix.msc4108": true,
},
});
mocked(sdkContext.client.waitForClientWellKnown).mockResolvedValue({});
mocked(sdkContext.client.getCrypto).mockReturnValue({
isCrossSigningReady: jest.fn().mockResolvedValue(true),
exportSecretsBundle: jest.fn().mockResolvedValue({}),
} as unknown as CryptoApi);
const spy = jest.spyOn(defaultDispatcher, "dispatch");
const UserMenu = wrapInSdkContext(UnwrappedUserMenu, sdkContext);
render(<UserMenu isPanelCollapsed={true} />);
screen.getByRole("button", { name: /User menu/i }).click();
await expect(screen.findByText("Link new device")).resolves.toBeInTheDocument();
// Assert the QR code is shown directly
screen.getByRole("menuitem", { name: "Link new device" }).click();
await waitFor(() => {
expect(spy).toHaveBeenCalledWith({
action: Action.ViewUserSettings,
initialTabId: UserTab.SessionManager,
props: { showMsc4108QrCode: true },
});
});
});
it("should toggle theme on switcher click", async () => {
sdkContext.client = stubClient();
const spy = jest.spyOn(SettingsStore, "setValue");
const UserMenu = wrapInSdkContext(UnwrappedUserMenu, sdkContext);
render(<UserMenu isPanelCollapsed={true} />);
screen.getByRole("button", { name: /User menu/i }).click();
const themeSwitchButton = await screen.findByRole("button", { name: "Switch to dark mode" });
expect(themeSwitchButton).toBeInTheDocument();
expect(spy).not.toHaveBeenCalled();
fireEvent.click(themeSwitchButton);
expect(spy).toHaveBeenCalledWith("use_system_theme", null, "device", false);
expect(spy).toHaveBeenCalledWith("theme", null, "device", "dark");
fireEvent.click(themeSwitchButton);
expect(spy).toHaveBeenCalledWith("use_system_theme", null, "device", false);
expect(spy).toHaveBeenCalledWith("theme", null, "device", "light");
});
});
@@ -1,4 +1,5 @@
/*
Copyright 2026 Element Creations Ltd.
Copyright 2024 New Vector Ltd.
Copyright 2022 The Matrix.org Foundation C.I.C.
@@ -7,7 +8,7 @@ Please see LICENSE files in the repository root for full details.
*/
import React from "react";
import { render, screen, fireEvent, act, cleanup } from "jest-matrix-react";
import { render, screen, fireEvent, act, cleanup, waitFor } from "jest-matrix-react";
import { mocked } from "jest-mock";
import { type MatrixClient, type Room } from "matrix-js-sdk/src/matrix";
@@ -22,6 +23,8 @@ import DMRoomMap from "../../../../../src/utils/DMRoomMap";
import { type SpaceNotificationState } from "../../../../../src/stores/notifications/SpaceNotificationState";
import SettingsStore from "../../../../../src/settings/SettingsStore";
import UnwrappedSpacePanel from "../../../../../src/components/views/spaces/SpacePanel";
import defaultDispatcher from "../../../../../src/dispatcher/dispatcher";
import { Action } from "../../../../../src/dispatcher/actions";
// DND test utilities based on
// https://github.com/colinrobertbrooks/react-beautiful-dnd-test-utils/issues/18#issuecomment-1373388693
@@ -110,6 +113,7 @@ describe("<SpacePanel />", () => {
const mockClient = {
getUserId: jest.fn().mockReturnValue("@test:test"),
getSafeUserId: jest.fn().mockReturnValue("@test:test"),
getClientWellKnown: jest.fn(),
mxcUrlToHttp: jest.fn(),
getRoom: jest.fn(),
isGuest: jest.fn(),
@@ -125,6 +129,7 @@ describe("<SpacePanel />", () => {
beforeAll(() => {
jest.spyOn(MatrixClientPeg, "get").mockReturnValue(mockClient);
jest.spyOn(MatrixClientPeg, "safeGet").mockReturnValue(mockClient);
SdkContextClass.instance.client = mockClient;
});
beforeEach(() => {
@@ -189,4 +194,13 @@ describe("<SpacePanel />", () => {
expect(SpaceStore.instance.moveRootSpace).toHaveBeenCalledWith(0, 1);
});
it("should be able to open the user menu via dispatcher", async () => {
const { baseElement } = render(<SpacePanel />);
defaultDispatcher.dispatch({ action: Action.ToggleUserMenu });
await waitFor(() => {
// Menu exists outside the component due to Portals, so select it manually.
expect(baseElement.querySelector("div[aria-label='User menu']")).toBeInTheDocument();
});
});
});
@@ -6,50 +6,43 @@ exports[`<SpacePanel /> should show all activated MetaSpaces in the correct orde
aria-label="Spaces"
class="mx_SpacePanel collapsed newUi"
>
<div
class="mx_UserMenu"
<button
aria-expanded="false"
aria-haspopup="menu"
aria-label="User menu"
class="_triggerButton_3x4xf_50"
data-state="closed"
id="radix-_r_0_"
type="button"
>
<div
aria-expanded="false"
aria-haspopup="true"
aria-label="User menu"
class="mx_AccessibleButton mx_UserMenu_contextMenuButton"
role="button"
tabindex="0"
<span
aria-label="@test:test"
class="_avatar_va14e_8 _avatar-imageless_va14e_55"
data-color="5"
data-type="round"
role="img"
style="--cpd-avatar-size: 36px;"
>
<div
class="mx_UserMenu_userAvatar"
>
<span
class="_avatar_va14e_8 mx_BaseAvatar mx_UserMenu_userAvatar_BaseAvatar _avatar-imageless_va14e_55"
data-color="5"
data-testid="avatar-img"
data-type="round"
role="presentation"
style="--cpd-avatar-size: 32px;"
>
t
</span>
</div>
</div>
<div
aria-label="Expand"
class="mx_AccessibleButton mx_SpacePanel_toggleCollapse"
role="button"
tabindex="0"
t
</span>
</button>
<div
aria-label="Expand"
class="mx_AccessibleButton mx_SpacePanel_toggleCollapse"
role="button"
tabindex="0"
>
<svg
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<svg
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M8.7 17.3a.95.95 0 0 1-.275-.7q0-.425.275-.7l3.9-3.9-3.9-3.9a.95.95 0 0 1-.275-.7q0-.425.275-.7a.95.95 0 0 1 .7-.275q.425 0 .7.275l4.6 4.6q.15.15.213.325.062.175.062.375t-.062.375a.9.9 0 0 1-.213.325l-4.6 4.6a.95.95 0 0 1-.7.275.95.95 0 0 1-.7-.275"
/>
</svg>
</div>
<path
d="M8.7 17.3a.95.95 0 0 1-.275-.7q0-.425.275-.7l3.9-3.9-3.9-3.9a.95.95 0 0 1-.275-.7q0-.425.275-.7a.95.95 0 0 1 .7-.275q.425 0 .7.275l4.6 4.6q.15.15.213.325.062.175.062.375t-.062.375a.9.9 0 0 1-.213.325l-4.6 4.6a.95.95 0 0 1-.7.275.95.95 0 0 1-.7-.275"
/>
</svg>
</div>
<ul
aria-label="Spaces"
@@ -332,11 +325,11 @@ exports[`<SpacePanel /> should show all activated MetaSpaces in the correct orde
aria-expanded="false"
aria-haspopup="menu"
aria-label="Threads"
aria-labelledby="_r_12_"
aria-labelledby="_r_14_"
class="_icon-button_1215g_8 mx_ThreadsActivityCentreButton"
data-kind="primary"
data-state="closed"
id="radix-_r_10_"
id="radix-_r_12_"
role="button"
style="--cpd-icon-button-size: 32px;"
tabindex="0"
@@ -364,7 +357,7 @@ exports[`<SpacePanel /> should show all activated MetaSpaces in the correct orde
<button
aria-expanded="false"
aria-label="Quick settings"
aria-labelledby="_r_17_"
aria-labelledby="_r_19_"
class="_icon-button_1215g_8 mx_QuickSettingsButton"
data-kind="primary"
role="button"
@@ -0,0 +1,183 @@
/*
* 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 { MatrixError, type MatrixClient } from "matrix-js-sdk/src/matrix";
import { waitFor } from "jest-matrix-react";
import type { MockedObject } from "jest-mock";
import { UserMenuViewModel } from "../../../src/viewmodels/menus/UserMenuViewModel";
import { getMockClientWithEventEmitter, mockClientMethodsServer, mockClientMethodsUser } from "../../test-utils";
import { MatrixDispatcher } from "../../../src/dispatcher/dispatcher";
import { SdkContextClass } from "../../../src/contexts/SDKContext";
import SdkConfig from "../../../src/SdkConfig";
import { Action } from "../../../src/dispatcher/actions";
import { UserTab } from "../../../src/components/views/dialogs/UserTab";
import Modal from "../../../src/Modal";
import FeedbackDialog from "../../../src/components/views/dialogs/FeedbackDialog";
describe("UserMenuViewModel", () => {
let dispatcher: MatrixDispatcher;
let client: MockedObject<MatrixClient>;
beforeEach(() => {
dispatcher = new MatrixDispatcher();
client = getMockClientWithEventEmitter({
...mockClientMethodsUser(),
...mockClientMethodsServer(),
getAuthMetadata: jest.fn().mockRejectedValue(new MatrixError({ errcode: "M_UNRECOGNIZED" }, 404)),
});
SdkContextClass.instance.client = client;
});
afterEach(() => {
jest.resetAllMocks();
SdkConfig.reset();
SdkContextClass.instance.onLoggedOut();
SdkContextClass.instance.client = undefined;
});
it("should generate a menu options for a logged in client", () => {
const vm = new UserMenuViewModel(dispatcher, client, true);
vm.setOpen(true);
expect(vm.getSnapshot()).toMatchSnapshot();
});
it("should show a link for account management", async () => {
const vm = new UserMenuViewModel(dispatcher, client, true, "https://example.org/");
vm.setOpen(true);
expect(vm.getSnapshot().manageAccountHref).toEqual("https://example.org/");
});
it("should generate a menu options for a guest", () => {
client.isGuest.mockReturnValue(true);
const vm = new UserMenuViewModel(dispatcher, client, true);
vm.setOpen(true);
expect(vm.getSnapshot()).toMatchSnapshot();
});
it("should generate a menu options that include feedback", () => {
SdkConfig.put({ bug_report_endpoint_url: "https://example.org" });
const vm = new UserMenuViewModel(dispatcher, client, true);
vm.setOpen(true);
expect(vm.getSnapshot().actions.openFeedback).toEqual(true);
});
it("should generate a menu options that includes a home page", () => {
SdkConfig.put({ embedded_pages: { home_url: "https://example.org" } });
const vm = new UserMenuViewModel(dispatcher, client, true);
vm.setOpen(true);
expect(vm.getSnapshot().actions.openHomePage).toEqual(true);
});
it("can toggle menu", () => {
const vm = new UserMenuViewModel(dispatcher, client, true);
vm.setOpen(true);
expect(vm.getSnapshot().open).toEqual(true);
vm.setOpen(false);
expect(vm.getSnapshot().open).toEqual(false);
});
it("can toggle expanded state", () => {
const vm = new UserMenuViewModel(dispatcher, client, true);
vm.setExpanded(true);
expect(vm.getSnapshot().expanded).toEqual(true);
vm.setExpanded(false);
expect(vm.getSnapshot().expanded).toEqual(false);
});
it("can open the home menu", async () => {
SdkConfig.put({ embedded_pages: { home_url: "https://example.org" } });
const vm = new UserMenuViewModel(dispatcher, client, true);
const dispatcherSpy = jest.fn();
dispatcher.register(dispatcherSpy);
vm.setOpen(true);
vm.openHomePage();
await waitFor(() =>
expect(dispatcherSpy).toHaveBeenCalledWith({
action: Action.ViewHomePage,
}),
);
});
it("can open the 'link new device' settings menu", async () => {
const vm = new UserMenuViewModel(dispatcher, client, true);
const dispatcherSpy = jest.fn();
dispatcher.register(dispatcherSpy);
vm.setOpen(true);
vm.linkNewDevice();
await waitFor(() =>
expect(dispatcherSpy).toHaveBeenCalledWith({
action: Action.ViewUserSettings,
initialTabId: UserTab.SessionManager,
props: { showMsc4108QrCode: true },
}),
);
});
it("can open the 'security' settings menu", async () => {
const vm = new UserMenuViewModel(dispatcher, client, true);
const dispatcherSpy = jest.fn();
dispatcher.register(dispatcherSpy);
vm.setOpen(true);
vm.openSecurity();
await waitFor(() =>
expect(dispatcherSpy).toHaveBeenCalledWith({
action: Action.ViewUserSettings,
initialTabId: UserTab.Security,
}),
);
});
it("can open the 'feedback' settings menu", async () => {
jest.spyOn(Modal, "createDialog");
SdkConfig.put({ bug_report_endpoint_url: "https://example.org" });
const vm = new UserMenuViewModel(dispatcher, client, true);
const dispatcherSpy = jest.fn();
dispatcher.register(dispatcherSpy);
vm.setOpen(true);
vm.openFeedback();
expect(Modal.createDialog).toHaveBeenCalledWith(FeedbackDialog);
});
it("can open the settings menu", async () => {
const vm = new UserMenuViewModel(dispatcher, client, true);
const dispatcherSpy = jest.fn();
dispatcher.register(dispatcherSpy);
vm.setOpen(true);
vm.openSettings();
await waitFor(() =>
expect(dispatcherSpy).toHaveBeenCalledWith({
action: Action.ViewUserSettings,
}),
);
});
it("should be able to open the createAccount screen as a guest", async () => {
client.isGuest.mockReturnValue(true);
const dispatcherSpy = jest.fn();
dispatcher.register(dispatcherSpy);
const vm = new UserMenuViewModel(dispatcher, client, true);
vm.setOpen(true);
vm.createAccount();
await waitFor(() =>
expect(dispatcherSpy).toHaveBeenCalledWith({
action: "start_registration",
}),
);
});
it("should be able to open the onSignIn screen as a guest", async () => {
client.isGuest.mockReturnValue(true);
const dispatcherSpy = jest.fn();
dispatcher.register(dispatcherSpy);
const vm = new UserMenuViewModel(dispatcher, client, true);
vm.setOpen(true);
vm.signIn();
await waitFor(() =>
expect(dispatcherSpy).toHaveBeenCalledWith({
action: "start_login",
}),
);
});
});
@@ -0,0 +1,43 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`UserMenuViewModel should generate a menu options for a guest 1`] = `
{
"actions": {
"createAccount": true,
"linkNewDevice": false,
"openFeedback": false,
"openHomePage": false,
"openSecurity": false,
"openSettings": true,
"signIn": true,
},
"avatarUrl": undefined,
"displayName": "@alice:domain",
"expanded": false,
"manageAccountHref": undefined,
"open": true,
"showAvatar": false,
"userId": "@alice:domain",
}
`;
exports[`UserMenuViewModel should generate a menu options for a logged in client 1`] = `
{
"actions": {
"createAccount": false,
"linkNewDevice": true,
"openFeedback": false,
"openHomePage": false,
"openSecurity": true,
"openSettings": true,
"signIn": false,
},
"avatarUrl": undefined,
"displayName": "@alice:domain",
"expanded": false,
"manageAccountHref": undefined,
"open": true,
"showAvatar": true,
"userId": "@alice:domain",
}
`;