Move the active tab in user settings to the dialog title (#12481)

* Convert tabbedview to functional component

The 'Tab' is still a class, so now it's a functional component that
has a supporting class, which is maybe a bit... jarring, but I think
is actually perfectly logical.

* put comment back

* Fix bad tab ID behaviour

* Make TabbedView a controlled component

This does mean the logic of keeping what tab is active is now in each
container component, but for a functional component, this is a single
line. It makes TabbedView simpler and the container components always
know exactly what tab is being displayed rather than having to effectively
keep the state separately themselves if they wanted it.

Based on https://github.com/matrix-org/matrix-react-sdk/pull/12478

* Move the active tab in user settings to the dialog title

Separated by a colon, as per the new design.

* Update snapshots

* Update a playwright test

* Fix more tests / snapshots

* Attempt to test all the cases of titleForTabID

* More tests
This commit is contained in:
David Baker 2024-05-07 10:32:24 +01:00 committed by GitHub
parent f8e040a890
commit 18ef97161a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
29 changed files with 186 additions and 85 deletions

View file

@ -25,8 +25,6 @@ test.describe("Appearance user settings tab", () => {
test("should be rendered properly", async ({ page, user, app }) => { test("should be rendered properly", async ({ page, user, app }) => {
const tab = await app.settings.openUserSettings("Appearance"); const tab = await app.settings.openUserSettings("Appearance");
await expect(tab.getByRole("heading", { name: "Customise your appearance" })).toBeVisible();
// Click "Show advanced" link button // Click "Show advanced" link button
await tab.getByRole("button", { name: "Show advanced" }).click(); await tab.getByRole("button", { name: "Show advanced" }).click();

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 54 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 72 KiB

After

Width:  |  Height:  |  Size: 71 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

After

Width:  |  Height:  |  Size: 57 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

After

Width:  |  Height:  |  Size: 64 KiB

Before After
Before After

View file

@ -53,7 +53,7 @@ interface IProps {
"top"?: React.ReactNode; "top"?: React.ReactNode;
// Title for the dialog. // Title for the dialog.
"title"?: JSX.Element | string; "title"?: React.ReactNode;
// Specific aria label to use, if not provided will set aria-labelledBy to mx_Dialog_title // Specific aria label to use, if not provided will set aria-labelledBy to mx_Dialog_title
"aria-label"?: string; "aria-label"?: string;

View file

@ -1536,7 +1536,7 @@ export default class InviteDialog extends React.PureComponent<Props, IInviteDial
); );
dialogContent = ( dialogContent = (
<React.Fragment> <React.Fragment>
<TabbedView <TabbedView<TabId>
tabs={tabs} tabs={tabs}
activeTabId={this.state.currentTabId} activeTabId={this.state.currentTabId}
tabLocation={TabLocation.TOP} tabLocation={TabLocation.TOP}

View file

@ -45,6 +45,38 @@ interface IProps {
onFinished(): void; onFinished(): void;
} }
function titleForTabID(tabId: UserTab): React.ReactNode {
const subs = {
strong: (sub: string) => <strong>{sub}</strong>,
};
switch (tabId) {
case UserTab.General:
return _t("settings|general|dialog_title", undefined, subs);
case UserTab.SessionManager:
return _t("settings|sessions|dialog_title", undefined, subs);
case UserTab.Appearance:
return _t("settings|appearance|dialog_title", undefined, subs);
case UserTab.Notifications:
return _t("settings|notifications|dialog_title", undefined, subs);
case UserTab.Preferences:
return _t("settings|preferences|dialog_title", undefined, subs);
case UserTab.Keyboard:
return _t("settings|keyboard|dialog_title", undefined, subs);
case UserTab.Sidebar:
return _t("settings|sidebar|dialog_title", undefined, subs);
case UserTab.Voice:
return _t("settings|voip|dialog_title", undefined, subs);
case UserTab.Security:
return _t("settings|security|dialog_title", undefined, subs);
case UserTab.Labs:
return _t("settings|labs|dialog_title", undefined, subs);
case UserTab.Mjolnir:
return _t("settings|labs_mjolnir|dialog_title", undefined, subs);
case UserTab.Help:
return _t("setting|help_about|dialog_title", undefined, subs);
}
}
export default function UserSettingsDialog(props: IProps): JSX.Element { export default function UserSettingsDialog(props: IProps): JSX.Element {
const voipEnabled = useSettingValue<boolean>(UIFeature.Voip); const voipEnabled = useSettingValue<boolean>(UIFeature.Voip);
const mjolnirEnabled = useSettingValue<boolean>("feature_mjolnir"); const mjolnirEnabled = useSettingValue<boolean>("feature_mjolnir");
@ -184,7 +216,7 @@ export default function UserSettingsDialog(props: IProps): JSX.Element {
className="mx_UserSettingsDialog" className="mx_UserSettingsDialog"
hasCancel={true} hasCancel={true}
onFinished={props.onFinished} onFinished={props.onFinished}
title={_t("common|settings")} title={titleForTabID(activeTabId)}
> >
<div className="mx_SettingsDialog_content"> <div className="mx_SettingsDialog_content">
<TabbedView <TabbedView

View file

@ -123,7 +123,7 @@ export default function NotificationSettings2(): JSX.Element {
)} )}
</SettingsBanner> </SettingsBanner>
)} )}
<SettingsSection heading={_t("notifications|enable_prompt_toast_title")}> <SettingsSection>
<div className="mx_SettingsSubsection_content mx_NotificationSettings2_flags"> <div className="mx_SettingsSubsection_content mx_NotificationSettings2_flags">
<LabelledToggleSwitch <LabelledToggleSwitch
label={_t("settings|notifications|enable_notifications_account")} label={_t("settings|notifications|enable_notifications_account")}

View file

@ -20,10 +20,25 @@ import React, { HTMLAttributes } from "react";
import Heading from "../../typography/Heading"; import Heading from "../../typography/Heading";
export interface SettingsSectionProps extends HTMLAttributes<HTMLDivElement> { export interface SettingsSectionProps extends HTMLAttributes<HTMLDivElement> {
heading: string | React.ReactNode; heading?: string | React.ReactNode;
children?: React.ReactNode; children?: React.ReactNode;
} }
function renderHeading(heading: string | React.ReactNode | undefined): React.ReactNode | undefined {
switch (typeof heading) {
case "string":
return (
<Heading as="h2" size="3">
{heading}
</Heading>
);
case "undefined":
return undefined;
default:
return heading;
}
}
/** /**
* A section of settings content * A section of settings content
* A SettingsTab may contain one or more SettingsSections * A SettingsTab may contain one or more SettingsSections
@ -43,13 +58,7 @@ export interface SettingsSectionProps extends HTMLAttributes<HTMLDivElement> {
*/ */
export const SettingsSection: React.FC<SettingsSectionProps> = ({ className, heading, children, ...rest }) => ( export const SettingsSection: React.FC<SettingsSectionProps> = ({ className, heading, children, ...rest }) => (
<div {...rest} className={classnames("mx_SettingsSection", className)}> <div {...rest} className={classnames("mx_SettingsSection", className)}>
{typeof heading === "string" ? ( {renderHeading(heading)}
<Heading as="h2" size="3">
{heading}
</Heading>
) : (
<>{heading}</>
)}
<div className="mx_SettingsSection_subSections">{children}</div> <div className="mx_SettingsSection_subSections">{children}</div>
</div> </div>
); );

View file

@ -32,7 +32,7 @@ import ThemeChoicePanel from "../../ThemeChoicePanel";
import ImageSizePanel from "../../ImageSizePanel"; import ImageSizePanel from "../../ImageSizePanel";
import SettingsTab from "../SettingsTab"; import SettingsTab from "../SettingsTab";
import { SettingsSection } from "../../shared/SettingsSection"; import { SettingsSection } from "../../shared/SettingsSection";
import SettingsSubsection, { SettingsSubsectionText } from "../../shared/SettingsSubsection"; import SettingsSubsection from "../../shared/SettingsSubsection";
import MatrixClientContext from "../../../../../contexts/MatrixClientContext"; import MatrixClientContext from "../../../../../contexts/MatrixClientContext";
interface IProps {} interface IProps {}
@ -152,12 +152,9 @@ export default class AppearanceUserSettingsTab extends React.Component<IProps, I
} }
public render(): React.ReactNode { public render(): React.ReactNode {
const brand = SdkConfig.get().brand;
return ( return (
<SettingsTab data-testid="mx_AppearanceUserSettingsTab"> <SettingsTab data-testid="mx_AppearanceUserSettingsTab">
<SettingsSection heading={_t("settings|appearance|heading")}> <SettingsSection>
<SettingsSubsectionText>{_t("settings|appearance|subheading", { brand })}</SettingsSubsectionText>
<ThemeChoicePanel /> <ThemeChoicePanel />
<LayoutSwitcher <LayoutSwitcher
userId={this.state.userId} userId={this.state.userId}

View file

@ -560,7 +560,7 @@ export default class GeneralUserSettingsTab extends React.Component<IProps, ISta
return ( return (
<SettingsTab data-testid="mx_GeneralUserSettingsTab"> <SettingsTab data-testid="mx_GeneralUserSettingsTab">
<SettingsSection heading={_t("common|general")}> <SettingsSection>
<ProfileSettings /> <ProfileSettings />
{this.renderAccountSection()} {this.renderAccountSection()}
{this.renderLanguageSection()} {this.renderLanguageSection()}

View file

@ -264,7 +264,7 @@ export default class HelpUserSettingsTab extends React.Component<IProps, IState>
return ( return (
<SettingsTab> <SettingsTab>
<SettingsSection heading={_t("setting|help_about|title")}> <SettingsSection>
{bugReportingSection} {bugReportingSection}
<SettingsSubsection heading={_t("common|faq")} description={faqText} /> <SettingsSubsection heading={_t("common|faq")} description={faqText} />
<SettingsSubsection heading={_t("setting|help_about|versions")}> <SettingsSubsection heading={_t("setting|help_about|versions")}>

View file

@ -73,7 +73,7 @@ const KeyboardShortcutSection: React.FC<IKeyboardShortcutSectionProps> = ({ cate
const KeyboardUserSettingsTab: React.FC = () => { const KeyboardUserSettingsTab: React.FC = () => {
return ( return (
<SettingsTab> <SettingsTab>
<SettingsSection heading={_t("settings|keyboard|title")}> <SettingsSection>
{visibleCategories.map(([categoryName, category]) => { {visibleCategories.map(([categoryName, category]) => {
return ( return (
<KeyboardShortcutSection key={categoryName} categoryName={categoryName} category={category} /> <KeyboardShortcutSection key={categoryName} categoryName={categoryName} category={category} />

View file

@ -254,7 +254,7 @@ export default class MjolnirUserSettingsTab extends React.Component<{}, IState>
return ( return (
<SettingsTab> <SettingsTab>
<SettingsSection heading={_t("labs_mjolnir|title")}> <SettingsSection>
<SettingsSubsectionText> <SettingsSubsectionText>
<strong className="warning">{_t("labs_mjolnir|advanced_warning")}</strong> <strong className="warning">{_t("labs_mjolnir|advanced_warning")}</strong>
<p>{_t("labs_mjolnir|explainer_1", { brand }, { code: (s) => <code>{s}</code> })}</p> <p>{_t("labs_mjolnir|explainer_1", { brand }, { code: (s) => <code>{s}</code> })}</p>

View file

@ -16,7 +16,6 @@ limitations under the License.
import React from "react"; import React from "react";
import { _t } from "../../../../../languageHandler";
import { Features } from "../../../../../settings/Settings"; import { Features } from "../../../../../settings/Settings";
import SettingsStore from "../../../../../settings/SettingsStore"; import SettingsStore from "../../../../../settings/SettingsStore";
import Notifications from "../../Notifications"; import Notifications from "../../Notifications";
@ -33,7 +32,7 @@ export default class NotificationUserSettingsTab extends React.Component {
{newNotificationSettingsEnabled ? ( {newNotificationSettingsEnabled ? (
<NotificationSettings2 /> <NotificationSettings2 />
) : ( ) : (
<SettingsSection heading={_t("notifications|enable_prompt_toast_title")}> <SettingsSection>
<Notifications /> <Notifications />
</SettingsSection> </SettingsSection>
)} )}

View file

@ -145,7 +145,7 @@ export default class PreferencesUserSettingsTab extends React.Component<IProps,
return ( return (
<SettingsTab data-testid="mx_PreferencesUserSettingsTab"> <SettingsTab data-testid="mx_PreferencesUserSettingsTab">
<SettingsSection heading={_t("common|preferences")}> <SettingsSection>
{roomListSettings.length > 0 && ( {roomListSettings.length > 0 && (
<SettingsSubsection heading={_t("settings|preferences|room_list_heading")}> <SettingsSubsection heading={_t("settings|preferences|room_list_heading")}>
{this.renderGroup(roomListSettings)} {this.renderGroup(roomListSettings)}

View file

@ -284,7 +284,7 @@ const SessionManagerTab: React.FC = () => {
return ( return (
<SettingsTab> <SettingsTab>
<SettingsSection heading={_t("settings|sessions|title")}> <SettingsSection>
<LoginWithQRSection <LoginWithQRSection
onShowQr={onShowQrClicked} onShowQr={onShowQrClicked}
versions={clientVersions} versions={clientVersions}

View file

@ -80,7 +80,7 @@ const SidebarUserSettingsTab: React.FC = () => {
return ( return (
<SettingsTab> <SettingsTab>
<SettingsSection heading={_t("settings|sidebar|title")}> <SettingsSection>
<SettingsSubsection <SettingsSubsection
heading={_t("settings|sidebar|metaspaces_subsection")} heading={_t("settings|sidebar|metaspaces_subsection")}
description={_t("settings|sidebar|spaces_explainer")} description={_t("settings|sidebar|spaces_explainer")}

View file

@ -180,7 +180,7 @@ export default class VoiceUserSettingsTab extends React.Component<{}, IState> {
return ( return (
<SettingsTab> <SettingsTab>
<SettingsSection heading={_t("settings|voip|title")}> <SettingsSection>
{requestButton} {requestButton}
<SettingsSubsection heading={_t("settings|voip|voice_section")} stretchContent> <SettingsSubsection heading={_t("settings|voip|voice_section")} stretchContent>
{speakerDropdown} {speakerDropdown}

View file

@ -2395,6 +2395,7 @@
"brand_version": "%(brand)s version:", "brand_version": "%(brand)s version:",
"clear_cache_reload": "Clear cache and reload", "clear_cache_reload": "Clear cache and reload",
"crypto_version": "Crypto version:", "crypto_version": "Crypto version:",
"dialog_title": "<strong>Settings:</strong> Help & About",
"help_link": "For help with using %(brand)s, click <a>here</a>.", "help_link": "For help with using %(brand)s, click <a>here</a>.",
"homeserver": "Homeserver is <code>%(homeserverUrl)s</code>", "homeserver": "Homeserver is <code>%(homeserverUrl)s</code>",
"identity_server": "Identity server is <code>%(identityServerUrl)s</code>", "identity_server": "Identity server is <code>%(identityServerUrl)s</code>",
@ -2417,15 +2418,14 @@
"custom_theme_invalid": "Invalid theme schema.", "custom_theme_invalid": "Invalid theme schema.",
"custom_theme_success": "Theme added!", "custom_theme_success": "Theme added!",
"custom_theme_url": "Custom theme URL", "custom_theme_url": "Custom theme URL",
"dialog_title": "<strong>Settings:</strong> Appearance",
"font_size": "Font size", "font_size": "Font size",
"font_size_default": "%(fontSize)s (default)", "font_size_default": "%(fontSize)s (default)",
"heading": "Customise your appearance",
"image_size_default": "Default", "image_size_default": "Default",
"image_size_large": "Large", "image_size_large": "Large",
"layout_bubbles": "Message bubbles", "layout_bubbles": "Message bubbles",
"layout_irc": "IRC (Experimental)", "layout_irc": "IRC (Experimental)",
"match_system_theme": "Match system theme", "match_system_theme": "Match system theme",
"subheading": "Appearance Settings only affect this %(brand)s session.",
"timeline_image_size": "Image size in the timeline", "timeline_image_size": "Image size in the timeline",
"use_high_contrast": "Use high contrast" "use_high_contrast": "Use high contrast"
}, },
@ -2467,6 +2467,7 @@
"deactivate_confirm_erase_label": "Hide my messages from new joiners", "deactivate_confirm_erase_label": "Hide my messages from new joiners",
"deactivate_section": "Deactivate Account", "deactivate_section": "Deactivate Account",
"deactivate_warning": "Deactivating your account is a permanent action — be careful!", "deactivate_warning": "Deactivating your account is a permanent action — be careful!",
"dialog_title": "<strong>Settings:</strong> General",
"discovery_email_empty": "Discovery options will appear once you have added an email above.", "discovery_email_empty": "Discovery options will appear once you have added an email above.",
"discovery_email_verification_instructions": "Verify the link in your inbox", "discovery_email_verification_instructions": "Verify the link in your inbox",
"discovery_msisdn_empty": "Discovery options will appear once you have added a phone number above.", "discovery_msisdn_empty": "Discovery options will appear once you have added a phone number above.",
@ -2574,12 +2575,20 @@
"phrase_strong_enough": "Great! This passphrase looks strong enough" "phrase_strong_enough": "Great! This passphrase looks strong enough"
}, },
"keyboard": { "keyboard": {
"dialog_title": "<strong>Settings:</strong> Keyboard",
"title": "Keyboard" "title": "Keyboard"
}, },
"labs": {
"dialog_title": "<strong>Settings:</strong> Labs"
},
"labs_mjolnir": {
"dialog_title": "<strong>Settings:</strong> Ignored Users"
},
"notifications": { "notifications": {
"default_setting_description": "This setting will be applied by default to all your rooms.", "default_setting_description": "This setting will be applied by default to all your rooms.",
"default_setting_section": "I want to be notified for (Default Setting)", "default_setting_section": "I want to be notified for (Default Setting)",
"desktop_notification_message_preview": "Show message preview in desktop notification", "desktop_notification_message_preview": "Show message preview in desktop notification",
"dialog_title": "<strong>Settings:</strong> Notifications",
"email_description": "Receive an email summary of missed notifications", "email_description": "Receive an email summary of missed notifications",
"email_section": "Email summary", "email_section": "Email summary",
"email_select": "Select which emails you want to send summaries to. Manage your emails in <button>General</button>.", "email_select": "Select which emails you want to send summaries to. Manage your emails in <button>General</button>.",
@ -2638,6 +2647,7 @@
"code_blocks_heading": "Code blocks", "code_blocks_heading": "Code blocks",
"compact_modern": "Use a more compact 'Modern' layout", "compact_modern": "Use a more compact 'Modern' layout",
"composer_heading": "Composer", "composer_heading": "Composer",
"dialog_title": "<strong>Settings:</strong> Preferences",
"enable_hardware_acceleration": "Enable hardware acceleration", "enable_hardware_acceleration": "Enable hardware acceleration",
"enable_tray_icon": "Show tray icon and minimise window to it on close", "enable_tray_icon": "Show tray icon and minimise window to it on close",
"keyboard_heading": "Keyboard shortcuts", "keyboard_heading": "Keyboard shortcuts",
@ -2687,6 +2697,7 @@
"dehydrated_device_enabled": "Offline device enabled", "dehydrated_device_enabled": "Offline device enabled",
"delete_backup": "Delete Backup", "delete_backup": "Delete Backup",
"delete_backup_confirm_description": "Are you sure? You will lose your encrypted messages if your keys are not backed up properly.", "delete_backup_confirm_description": "Are you sure? You will lose your encrypted messages if your keys are not backed up properly.",
"dialog_title": "<strong>Settings:</strong> Security & Privacy",
"e2ee_default_disabled_warning": "Your server admin has disabled end-to-end encryption by default in private rooms & Direct Messages.", "e2ee_default_disabled_warning": "Your server admin has disabled end-to-end encryption by default in private rooms & Direct Messages.",
"enable_message_search": "Enable message search in encrypted rooms", "enable_message_search": "Enable message search in encrypted rooms",
"encryption_individual_verification_mode": "Individually verify each session used by a user to mark it as trusted, not trusting cross-signed devices.", "encryption_individual_verification_mode": "Individually verify each session used by a user to mark it as trusted, not trusting cross-signed devices.",
@ -2766,6 +2777,7 @@
"device_unverified_description_current": "Verify your current session for enhanced secure messaging.", "device_unverified_description_current": "Verify your current session for enhanced secure messaging.",
"device_verified_description": "This session is ready for secure messaging.", "device_verified_description": "This session is ready for secure messaging.",
"device_verified_description_current": "Your current session is ready for secure messaging.", "device_verified_description_current": "Your current session is ready for secure messaging.",
"dialog_title": "<strong>Settings:</strong> Sessions",
"error_pusher_state": "Failed to set pusher state", "error_pusher_state": "Failed to set pusher state",
"error_set_name": "Failed to set session name", "error_set_name": "Failed to set session name",
"filter_all": "All", "filter_all": "All",
@ -2849,6 +2861,7 @@
"show_typing_notifications": "Show typing notifications", "show_typing_notifications": "Show typing notifications",
"showbold": "Show all activity in the room list (dots or number of unread messages)", "showbold": "Show all activity in the room list (dots or number of unread messages)",
"sidebar": { "sidebar": {
"dialog_title": "<strong>Settings:</strong> Sidebar",
"metaspaces_favourites_description": "Group all your favourite rooms and people in one place.", "metaspaces_favourites_description": "Group all your favourite rooms and people in one place.",
"metaspaces_home_all_rooms": "Show all rooms", "metaspaces_home_all_rooms": "Show all rooms",
"metaspaces_home_all_rooms_description": "Show all your rooms in Home, even if they're in a space.", "metaspaces_home_all_rooms_description": "Show all your rooms in Home, even if they're in a space.",
@ -2878,6 +2891,7 @@
"audio_output_empty": "No Audio Outputs detected", "audio_output_empty": "No Audio Outputs detected",
"auto_gain_control": "Automatic gain control", "auto_gain_control": "Automatic gain control",
"connection_section": "Connection", "connection_section": "Connection",
"dialog_title": "<strong>Settings:</strong> Voice & Video",
"echo_cancellation": "Echo cancellation", "echo_cancellation": "Echo cancellation",
"enable_fallback_ice_server": "Allow fallback call assist server (%(server)s)", "enable_fallback_ice_server": "Allow fallback call assist server (%(server)s)",
"enable_fallback_ice_server_description": "Only applies if your homeserver does not offer one. Your IP address would be shared during a call.", "enable_fallback_ice_server_description": "Only applies if your homeserver does not offer one. Your IP address would be shared during a call.",

View file

@ -15,7 +15,7 @@ limitations under the License.
*/ */
import React, { ReactElement } from "react"; import React, { ReactElement } from "react";
import { render } from "@testing-library/react"; import { render, screen } from "@testing-library/react";
import { mocked, MockedObject } from "jest-mock"; import { mocked, MockedObject } from "jest-mock";
import { MatrixClient } from "matrix-js-sdk/src/matrix"; import { MatrixClient } from "matrix-js-sdk/src/matrix";
@ -29,6 +29,8 @@ import {
mockClientMethodsServer, mockClientMethodsServer,
mockPlatformPeg, mockPlatformPeg,
mockClientMethodsCrypto, mockClientMethodsCrypto,
mockClientMethodsRooms,
useMockMediaDevices,
} from "../../../test-utils"; } from "../../../test-utils";
import { UIFeature } from "../../../../src/settings/UIFeature"; import { UIFeature } from "../../../../src/settings/UIFeature";
import { SettingLevel } from "../../../../src/settings/SettingLevel"; import { SettingLevel } from "../../../../src/settings/SettingLevel";
@ -48,6 +50,10 @@ jest.mock("../../../../src/settings/SettingsStore", () => ({
unwatchSetting: jest.fn(), unwatchSetting: jest.fn(),
getFeatureSettingNames: jest.fn(), getFeatureSettingNames: jest.fn(),
getBetaInfo: jest.fn(), getBetaInfo: jest.fn(),
getDisplayName: jest.fn(),
getDescription: jest.fn(),
shouldHaveWarning: jest.fn(),
disabledMessage: jest.fn(),
})); }));
jest.mock("../../../../src/SdkConfig", () => ({ jest.mock("../../../../src/SdkConfig", () => ({
@ -72,31 +78,32 @@ describe("<UserSettingsDialog />", () => {
...mockClientMethodsUser(userId), ...mockClientMethodsUser(userId),
...mockClientMethodsServer(), ...mockClientMethodsServer(),
...mockClientMethodsCrypto(), ...mockClientMethodsCrypto(),
...mockClientMethodsRooms(),
getIgnoredUsers: jest.fn().mockResolvedValue([]),
getPushers: jest.fn().mockResolvedValue([]),
getProfileInfo: jest.fn().mockResolvedValue({}),
}); });
sdkContext = new SdkContextClass(); sdkContext = new SdkContextClass();
sdkContext.client = mockClient; sdkContext.client = mockClient;
mockSettingsStore.getValue.mockReturnValue(false); mockSettingsStore.getValue.mockReturnValue(false);
mockSettingsStore.getValueAt.mockReturnValue(false);
mockSettingsStore.getFeatureSettingNames.mockReturnValue([]); mockSettingsStore.getFeatureSettingNames.mockReturnValue([]);
mockSdkConfig.get.mockReturnValue({ brand: "Test" }); mockSdkConfig.get.mockReturnValue({ brand: "Test" });
}); });
const getActiveTabLabel = (container: Element) => const getActiveTabLabel = (container: Element) =>
container.querySelector(".mx_TabbedView_tabLabel_active")?.textContent; container.querySelector(".mx_TabbedView_tabLabel_active")?.textContent;
const getActiveTabHeading = (container: Element) =>
container.querySelector(".mx_SettingsSection .mx_Heading_h3")?.textContent;
it("should render general settings tab when no initialTabId", () => { it("should render general settings tab when no initialTabId", () => {
const { container } = render(getComponent()); const { container } = render(getComponent());
expect(getActiveTabLabel(container)).toEqual("General"); expect(getActiveTabLabel(container)).toEqual("General");
expect(getActiveTabHeading(container)).toEqual("General");
}); });
it("should render initial tab when initialTabId is set", () => { it("should render initial tab when initialTabId is set", () => {
const { container } = render(getComponent({ initialTabId: UserTab.Help })); const { container } = render(getComponent({ initialTabId: UserTab.Help }));
expect(getActiveTabLabel(container)).toEqual("Help & About"); expect(getActiveTabLabel(container)).toEqual("Help & About");
expect(getActiveTabHeading(container)).toEqual("Help & About");
}); });
it("should render general tab if initialTabId tab cannot be rendered", () => { it("should render general tab if initialTabId tab cannot be rendered", () => {
@ -104,7 +111,6 @@ describe("<UserSettingsDialog />", () => {
const { container } = render(getComponent({ initialTabId: UserTab.Mjolnir })); const { container } = render(getComponent({ initialTabId: UserTab.Mjolnir }));
expect(getActiveTabLabel(container)).toEqual("General"); expect(getActiveTabLabel(container)).toEqual("General");
expect(getActiveTabHeading(container)).toEqual("General");
}); });
it("renders tabs correctly", () => { it("renders tabs correctly", () => {
@ -124,9 +130,95 @@ describe("<UserSettingsDialog />", () => {
expect(getByTestId(`settings-tab-${UserTab.Voice}`)).toBeTruthy(); expect(getByTestId(`settings-tab-${UserTab.Voice}`)).toBeTruthy();
}); });
it("renders session manager tab", () => { it("renders with session manager tab selected", () => {
const { getByTestId } = render(getComponent()); const { getByTestId } = render(getComponent({ initialTabId: UserTab.SessionManager }));
expect(getByTestId(`settings-tab-${UserTab.SessionManager}`)).toBeTruthy(); expect(getByTestId(`settings-tab-${UserTab.SessionManager}`)).toBeTruthy();
expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent("Settings: Sessions");
});
it("renders with appearance tab selected", () => {
const { container } = render(getComponent({ initialTabId: UserTab.Appearance }));
expect(getActiveTabLabel(container)).toEqual("Appearance");
expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent("Settings: Appearance");
});
it("renders with notifications tab selected", () => {
const { container } = render(getComponent({ initialTabId: UserTab.Notifications }));
expect(getActiveTabLabel(container)).toEqual("Notifications");
expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent("Settings: Notifications");
});
it("renders with preferences tab selected", () => {
const { container } = render(getComponent({ initialTabId: UserTab.Preferences }));
expect(getActiveTabLabel(container)).toEqual("Preferences");
expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent("Settings: Preferences");
});
it("renders with keyboard tab selected", () => {
const { container } = render(getComponent({ initialTabId: UserTab.Keyboard }));
expect(getActiveTabLabel(container)).toEqual("Keyboard");
expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent("Settings: Keyboard");
});
it("renders with sidebar tab selected", () => {
const { container } = render(getComponent({ initialTabId: UserTab.Sidebar }));
expect(getActiveTabLabel(container)).toEqual("Sidebar");
expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent("Settings: Sidebar");
});
it("renders with voip tab selected", () => {
useMockMediaDevices();
mockSettingsStore.getValue.mockImplementation((settingName): any => settingName === UIFeature.Voip);
const { container } = render(getComponent({ initialTabId: UserTab.Voice }));
expect(getActiveTabLabel(container)).toEqual("Voice & Video");
expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent("Settings: Voice & Video");
});
it("renders with secutity tab selected", () => {
const { container } = render(getComponent({ initialTabId: UserTab.Security }));
expect(getActiveTabLabel(container)).toEqual("Security & Privacy");
expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent("Settings: Security & Privacy");
});
it("renders with labs tab selected", () => {
// @ts-ignore I give up trying to get the types right here
// why do we have functions that return different things depending on what they're passed?
mockSdkConfig.get.mockImplementation((x) => {
const mockConfig = { show_labs_settings: true, brand: "Test" };
switch (x) {
case "show_labs_settings":
case "brand":
// @ts-ignore
return mockConfig[x];
default:
return mockConfig;
}
});
const { container } = render(getComponent({ initialTabId: UserTab.Labs }));
expect(getActiveTabLabel(container)).toEqual("Labs");
expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent("Settings: Labs");
});
it("renders with mjolnir tab selected", () => {
mockSettingsStore.getValue.mockImplementation((settingName): any => settingName === "feature_mjolnir");
const { container } = render(getComponent({ initialTabId: UserTab.Mjolnir }));
expect(getActiveTabLabel(container)).toEqual("Ignored users");
expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent("Ignored Users");
});
it("renders with help tab selected", () => {
const { container } = render(getComponent({ initialTabId: UserTab.Help }));
expect(getActiveTabLabel(container)).toEqual("Help & About");
expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent("Settings: Help & About");
}); });
it("renders labs tab when show_labs_settings is enabled in config", () => { it("renders labs tab when show_labs_settings is enabled in config", () => {

View file

@ -8,11 +8,6 @@ exports[`<Notifications /> correctly handles the loading/disabled state 1`] = `
<div <div
class="mx_SettingsSection" class="mx_SettingsSection"
> >
<h2
class="mx_Heading_h3"
>
Notifications
</h2>
<div <div
class="mx_SettingsSection_subSections" class="mx_SettingsSection_subSections"
> >
@ -781,11 +776,6 @@ exports[`<Notifications /> matches the snapshot 1`] = `
<div <div
class="mx_SettingsSection" class="mx_SettingsSection"
> >
<h2
class="mx_Heading_h3"
>
Notifications
</h2>
<div <div
class="mx_SettingsSection_subSections" class="mx_SettingsSection_subSections"
> >

View file

@ -12,19 +12,9 @@ exports[`AppearanceUserSettingsTab should render 1`] = `
<div <div
class="mx_SettingsSection" class="mx_SettingsSection"
> >
<h2
class="mx_Heading_h3"
>
Customise your appearance
</h2>
<div <div
class="mx_SettingsSection_subSections" class="mx_SettingsSection_subSections"
> >
<div
class="mx_SettingsSubsection_text"
>
Appearance Settings only affect this Element session.
</div>
<div <div
class="mx_SettingsSubsection" class="mx_SettingsSubsection"
data-testid="mx_ThemeChoicePanel" data-testid="mx_ThemeChoicePanel"

View file

@ -11,11 +11,6 @@ exports[`KeyboardUserSettingsTab renders list of keyboard shortcuts 1`] = `
<div <div
class="mx_SettingsSection" class="mx_SettingsSection"
> >
<h2
class="mx_Heading_h3"
>
Keyboard
</h2>
<div <div
class="mx_SettingsSection_subSections" class="mx_SettingsSection_subSections"
> >

View file

@ -11,11 +11,6 @@ exports[`<MjolnirUserSettingsTab /> renders correctly when user has no ignored u
<div <div
class="mx_SettingsSection" class="mx_SettingsSection"
> >
<h2
class="mx_Heading_h3"
>
Ignored users
</h2>
<div <div
class="mx_SettingsSection_subSections" class="mx_SettingsSection_subSections"
> >

View file

@ -12,11 +12,6 @@ exports[`PreferencesUserSettingsTab should render 1`] = `
<div <div
class="mx_SettingsSection" class="mx_SettingsSection"
> >
<h2
class="mx_Heading_h3"
>
Preferences
</h2>
<div <div
class="mx_SettingsSection_subSections" class="mx_SettingsSection_subSections"
> >

View file

@ -11,11 +11,6 @@ exports[`<SidebarUserSettingsTab /> renders sidebar settings with guest spa url
<div <div
class="mx_SettingsSection" class="mx_SettingsSection"
> >
<h2
class="mx_Heading_h3"
>
Sidebar
</h2>
<div <div
class="mx_SettingsSection_subSections" class="mx_SettingsSection_subSections"
> >
@ -257,11 +252,6 @@ exports[`<SidebarUserSettingsTab /> renders sidebar settings without guest spa u
<div <div
class="mx_SettingsSection" class="mx_SettingsSection"
> >
<h2
class="mx_Heading_h3"
>
Sidebar
</h2>
<div <div
class="mx_SettingsSection_subSections" class="mx_SettingsSection_subSections"
> >

View file

@ -17,7 +17,7 @@ limitations under the License.
import EventEmitter from "events"; import EventEmitter from "events";
import { MethodLikeKeys, mocked, MockedObject, PropertyLikeKeys } from "jest-mock"; import { MethodLikeKeys, mocked, MockedObject, PropertyLikeKeys } from "jest-mock";
import { Feature, ServerSupport } from "matrix-js-sdk/src/feature"; import { Feature, ServerSupport } from "matrix-js-sdk/src/feature";
import { MatrixClient, User } from "matrix-js-sdk/src/matrix"; import { MatrixClient, Room, User } from "matrix-js-sdk/src/matrix";
import { MatrixClientPeg } from "../../src/MatrixClientPeg"; import { MatrixClientPeg } from "../../src/MatrixClientPeg";
@ -173,4 +173,9 @@ export const mockClientMethodsCrypto = (): Partial<
getOwnDeviceKeys: jest.fn(), getOwnDeviceKeys: jest.fn(),
getCrossSigningKeyId: jest.fn(), getCrossSigningKeyId: jest.fn(),
}), }),
getDeviceEd25519Key: jest.fn(),
});
export const mockClientMethodsRooms = (rooms: Room[] = []): Partial<Record<MethodLikeKeys<MatrixClient>, unknown>> => ({
getRooms: jest.fn().mockReturnValue(rooms),
}); });