feat: make settings route-driven

This commit is contained in:
hazre committed 2026-03-26 23:45:35 +01:00
1 parent 0ec294405c
commit f786860947
4 files changed
+391 -125

No files matched your search

+154 -121
View File
@@ -28,17 +28,19 @@ import { stopPropagation } from '$utils/keyboard';
import { LogoutDialog } from '$components/LogoutDialog';
import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
import { Notifications } from './notifications';
import { Devices } from './devices';
import { EmojisStickers } from './emojis-stickers';
import { DeveloperTools } from './developer-tools';
import { About } from './about';
import { Account } from './account';
import { General } from './general';
import { Cosmetics } from './cosmetics/Cosmetics';
import { DeveloperTools } from './developer-tools';
import { Devices } from './devices';
import { EmojisStickers } from './emojis-stickers';
import { Experimental } from './experimental/Experimental';
import { General } from './general';
import { KeyboardShortcuts } from './keyboard-shortcuts';
import { Notifications } from './notifications';
import { PerMessageProfilePage } from './Persona/ProfilesPage';
import { settingsSections, type SettingsSectionId } from './routes';
import { useSettingsFocus } from './useSettingsFocus';
export enum SettingsPages {
GeneralPage,
@@ -55,84 +57,99 @@ export enum SettingsPages {
}
type SettingsMenuItem = {
page: SettingsPages;
id: SettingsSectionId;
name: string;
icon: IconSrc;
activeIcon?: IconSrc;
};
const useSettingsMenuItems = (showPersona: boolean): SettingsMenuItem[] =>
useMemo(() => {
const items: SettingsMenuItem[] = [
{
page: SettingsPages.GeneralPage,
name: 'General',
icon: Icons.Setting,
},
{
page: SettingsPages.AccountPage,
name: 'Account',
icon: Icons.User,
},
{
page: SettingsPages.CosmeticsPage,
name: 'Appearance',
icon: Icons.Alphabet,
activeIcon: Icons.AlphabetUnderline,
},
{
page: SettingsPages.NotificationPage,
name: 'Notifications',
icon: Icons.Bell,
},
{
page: SettingsPages.DevicesPage,
name: 'Devices',
icon: Icons.Monitor,
},
{
page: SettingsPages.EmojisStickersPage,
name: 'Emojis & Stickers',
icon: Icons.Smile,
},
{
page: SettingsPages.DeveloperToolsPage,
name: 'Developer Tools',
icon: Icons.Terminal,
},
{
page: SettingsPages.ExperimentalPage,
name: 'Experimental',
icon: Icons.Funnel,
},
{
page: SettingsPages.AboutPage,
name: 'About',
icon: Icons.Info,
},
{
page: SettingsPages.KeyboardShortcutsPage,
name: 'Keyboard Shortcuts',
icon: Icons.BlockCode,
},
];
if (showPersona) {
items.splice(2, 0, {
page: SettingsPages.PerMessageProfilesPage,
name: 'Persona',
icon: Icons.User,
});
}
return items;
}, [showPersona]);
type SettingsProps = {
initialPage?: SettingsPages;
requestClose: () => void;
const settingsMenuIcons: Record<
SettingsSectionId,
Pick<SettingsMenuItem, 'icon' | 'activeIcon'>
> = {
general: { icon: Icons.Setting },
account: { icon: Icons.User },
persona: { icon: Icons.User },
appearance: { icon: Icons.Alphabet, activeIcon: Icons.AlphabetUnderline },
notifications: { icon: Icons.Bell },
devices: { icon: Icons.Monitor },
emojis: { icon: Icons.Smile },
'developer-tools': { icon: Icons.Terminal },
experimental: { icon: Icons.Funnel },
about: { icon: Icons.Info },
'keyboard-shortcuts': { icon: Icons.BlockCode },
};
export function Settings({ initialPage, requestClose }: SettingsProps) {
const settingsPageToSectionId: Record<SettingsPages, SettingsSectionId> = {
[SettingsPages.GeneralPage]: 'general',
[SettingsPages.AccountPage]: 'account',
[SettingsPages.PerMessageProfilesPage]: 'persona',
[SettingsPages.NotificationPage]: 'notifications',
[SettingsPages.DevicesPage]: 'devices',
[SettingsPages.EmojisStickersPage]: 'emojis',
[SettingsPages.CosmeticsPage]: 'appearance',
[SettingsPages.DeveloperToolsPage]: 'developer-tools',
[SettingsPages.ExperimentalPage]: 'experimental',
[SettingsPages.AboutPage]: 'about',
[SettingsPages.KeyboardShortcutsPage]: 'keyboard-shortcuts',
};
const settingsSectionIdToPage: Record<SettingsSectionId, SettingsPages> = {
general: SettingsPages.GeneralPage,
account: SettingsPages.AccountPage,
persona: SettingsPages.PerMessageProfilesPage,
appearance: SettingsPages.CosmeticsPage,
notifications: SettingsPages.NotificationPage,
devices: SettingsPages.DevicesPage,
emojis: SettingsPages.EmojisStickersPage,
'developer-tools': SettingsPages.DeveloperToolsPage,
experimental: SettingsPages.ExperimentalPage,
about: SettingsPages.AboutPage,
'keyboard-shortcuts': SettingsPages.KeyboardShortcutsPage,
};
const settingsSectionComponents: Record<
SettingsSectionId,
(props: { requestClose: () => void }) => JSX.Element
> = {
general: General,
account: Account,
persona: PerMessageProfilePage,
appearance: Cosmetics,
notifications: Notifications,
devices: Devices,
emojis: EmojisStickers,
'developer-tools': DeveloperTools,
experimental: Experimental,
about: About,
'keyboard-shortcuts': KeyboardShortcuts,
};
type ControlledSettingsProps = {
activeSection?: SettingsSectionId | null;
onSelectSection?: (section: SettingsSectionId) => void;
requestClose: () => void;
initialPage?: SettingsPages;
};
function SettingsSectionViewport({
section,
requestClose,
}: {
section: SettingsSectionId;
requestClose: () => void;
}) {
useSettingsFocus();
const Section = settingsSectionComponents[section];
return <Section requestClose={requestClose} />;
}
export function Settings({
activeSection,
onSelectSection,
requestClose,
initialPage,
}: ControlledSettingsProps) {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
const userId = mx.getUserId()!;
@@ -143,9 +160,10 @@ export function Settings({ initialPage, requestClose }: SettingsProps) {
: undefined;
const [showPersona] = useSetting(settingsAtom, 'showPersonaSetting');
const screenSize = useScreenSizeContext();
const [activePage, setActivePage] = useState<SettingsPages | undefined>(() => {
const isControlled = activeSection !== undefined;
const [legacyActivePage, setLegacyActivePage] = useState<SettingsPages | undefined>(() => {
if (initialPage === SettingsPages.PerMessageProfilesPage && !showPersona) {
return SettingsPages.GeneralPage;
}
@@ -153,20 +171,59 @@ export function Settings({ initialPage, requestClose }: SettingsProps) {
return screenSize === ScreenSize.Mobile ? undefined : SettingsPages.GeneralPage;
});
const menuItems = useSettingsMenuItems(showPersona);
const visibleSection = useMemo<SettingsSectionId | null>(() => {
if (isControlled) return activeSection;
const handlePageRequestClose = () => {
if (screenSize === ScreenSize.Mobile) {
setActivePage(undefined);
if (legacyActivePage === undefined) {
return null;
}
const section = settingsPageToSectionId[legacyActivePage];
if (section === 'persona' && !showPersona) {
return 'general';
}
return section;
}, [activeSection, isControlled, legacyActivePage, showPersona]);
const menuItems = useMemo<SettingsMenuItem[]>(
() =>
settingsSections
.filter((section) => showPersona || section.id !== 'persona')
.map((section) => ({
id: section.id,
name: section.label,
...settingsMenuIcons[section.id],
})),
[showPersona]
);
const handleSelectSection = (section: SettingsSectionId) => {
if (isControlled) {
onSelectSection?.(section);
return;
}
setLegacyActivePage(settingsSectionIdToPage[section]);
};
const handleRequestClose = () => {
if (isControlled) {
requestClose();
return;
}
if (screenSize === ScreenSize.Mobile) {
setLegacyActivePage(undefined);
return;
}
requestClose();
};
return (
<PageRoot
nav={
screenSize === ScreenSize.Mobile && activePage !== undefined ? undefined : (
screenSize === ScreenSize.Mobile && visibleSection !== null ? undefined : (
<PageNav size="300">
<PageNavHeader outlined={false}>
<Box grow="Yes" gap="200">
@@ -183,7 +240,11 @@ export function Settings({ initialPage, requestClose }: SettingsProps) {
</Box>
<Box shrink="No">
{screenSize === ScreenSize.Mobile && (
<IconButton onClick={requestClose} variant="Background">
<IconButton
aria-label="Close settings"
onClick={handleRequestClose}
variant="Background"
>
<Icon src={Icons.Cross} />
</IconButton>
)}
@@ -194,23 +255,23 @@ export function Settings({ initialPage, requestClose }: SettingsProps) {
<div style={{ flexGrow: 1 }}>
{menuItems.map((item) => {
const currentIcon =
activePage === item.page && item.activeIcon ? item.activeIcon : item.icon;
visibleSection === item.id && item.activeIcon ? item.activeIcon : item.icon;
return (
<MenuItem
key={item.name}
key={item.id}
variant="Background"
radii="400"
aria-pressed={activePage === item.page}
aria-pressed={visibleSection === item.id}
before={
<Icon src={currentIcon} size="100" filled={activePage === item.page} />
<Icon src={currentIcon} size="100" filled={visibleSection === item.id} />
}
onClick={() => setActivePage(item.page)}
onClick={() => handleSelectSection(item.id)}
>
<Text
style={{
fontWeight:
activePage === item.page ? config.fontWeight.W600 : undefined,
visibleSection === item.id ? config.fontWeight.W600 : undefined,
}}
size="T300"
truncate
@@ -260,36 +321,8 @@ export function Settings({ initialPage, requestClose }: SettingsProps) {
)
}
>
{activePage === SettingsPages.GeneralPage && (
<General requestClose={handlePageRequestClose} />
)}
{activePage === SettingsPages.AccountPage && (
<Account requestClose={handlePageRequestClose} />
)}
{activePage === SettingsPages.PerMessageProfilesPage && showPersona && (
<PerMessageProfilePage requestClose={handlePageRequestClose} />
)}
{activePage === SettingsPages.CosmeticsPage && (
<Cosmetics requestClose={handlePageRequestClose} />
)}
{activePage === SettingsPages.NotificationPage && (
<Notifications requestClose={handlePageRequestClose} />
)}
{activePage === SettingsPages.DevicesPage && (
<Devices requestClose={handlePageRequestClose} />
)}
{activePage === SettingsPages.EmojisStickersPage && (
<EmojisStickers requestClose={handlePageRequestClose} />
)}
{activePage === SettingsPages.DeveloperToolsPage && (
<DeveloperTools requestClose={handlePageRequestClose} />
)}
{activePage === SettingsPages.ExperimentalPage && (
<Experimental requestClose={handlePageRequestClose} />
)}
{activePage === SettingsPages.AboutPage && <About requestClose={handlePageRequestClose} />}
{activePage === SettingsPages.KeyboardShortcutsPage && (
<KeyboardShortcuts requestClose={handlePageRequestClose} />
{visibleSection && (
<SettingsSectionViewport section={visibleSection} requestClose={handleRequestClose} />
)}
</PageRoot>
);
@@ -1,12 +1,98 @@
import { act, render, screen } from '@testing-library/react';
import { MemoryRouter, useLocation } from 'react-router-dom';
import { act, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
import { describe, expect, it, vi } from 'vitest';
import { SettingTile } from '$components/setting-tile';
import { ScreenSize, ScreenSizeProvider } from '$hooks/useScreenSize';
import { getSettingsPath } from '$pages/pathUtils';
import { SettingsRoute } from './SettingsRoute';
import { SettingsSectionPage } from './SettingsSectionPage';
import { focusedSettingTile } from './styles.css';
import { useSettingsFocus } from './useSettingsFocus';
const { mockMatrixClient, mockProfile, mockUseSetting, createSectionMock } = vi.hoisted(() => {
const mockSettingsHook = vi.fn(() => [true, vi.fn()] as const);
const createMockSection = (title: string) =>
function MockSection({ requestClose }: { requestClose: () => void }) {
return (
<div>
<h1>{title}</h1>
<button type="button" onClick={requestClose}>
Back
</button>
</div>
);
};
return {
mockMatrixClient: { getUserId: () => '@alice:server' },
mockProfile: { displayName: 'Alice', avatarUrl: undefined },
mockUseSetting: mockSettingsHook,
createSectionMock: createMockSection,
};
});
vi.mock('$hooks/useMatrixClient', () => ({
useMatrixClient: () => mockMatrixClient,
}));
vi.mock('$hooks/useUserProfile', () => ({
useUserProfile: () => mockProfile,
}));
vi.mock('$hooks/useMediaAuthentication', () => ({
useMediaAuthentication: () => false,
}));
vi.mock('$state/hooks/settings', () => ({
useSetting: mockUseSetting,
}));
vi.mock('./general', () => ({
General: createSectionMock('General section'),
}));
vi.mock('./account', () => ({
Account: createSectionMock('Account section'),
}));
vi.mock('./cosmetics/Cosmetics', () => ({
Cosmetics: createSectionMock('Appearance section'),
}));
vi.mock('./notifications', () => ({
Notifications: createSectionMock('Notifications section'),
}));
vi.mock('./devices', () => ({
Devices: createSectionMock('Devices section'),
}));
vi.mock('./emojis-stickers', () => ({
EmojisStickers: createSectionMock('Emojis & Stickers section'),
}));
vi.mock('./developer-tools/DevelopTools', () => ({
DeveloperTools: createSectionMock('Developer Tools section'),
}));
vi.mock('./experimental/Experimental', () => ({
Experimental: createSectionMock('Experimental section'),
}));
vi.mock('./about', () => ({
About: createSectionMock('About section'),
}));
vi.mock('./keyboard-shortcuts', () => ({
KeyboardShortcuts: createSectionMock('Keyboard Shortcuts section'),
}));
vi.mock('./Persona/ProfilesPage', () => ({
PerMessageProfilePage: createSectionMock('Persona section'),
}));
function FocusFixture() {
useSettingsFocus();
@@ -19,7 +105,25 @@ function FocusFixture() {
function LocationProbe() {
const location = useLocation();
return <div data-testid="location-probe">{location.search}</div>;
return (
<div data-testid="location-probe">
{location.pathname}
{location.search}
</div>
);
}
function renderSettingsRoute(path: string, screenSize: ScreenSize) {
return render(
<MemoryRouter initialEntries={[path]}>
<ScreenSizeProvider value={screenSize}>
<LocationProbe />
<Routes>
<Route path="/settings/:section?/" element={<SettingsRoute />} />
</Routes>
</ScreenSizeProvider>
</MemoryRouter>
);
}
describe('SettingsSectionPage', () => {
@@ -50,6 +154,66 @@ describe('SettingsSectionPage', () => {
});
});
describe('SettingsRoute', () => {
it('renders the menu index on mobile /settings', () => {
renderSettingsRoute('/settings', ScreenSize.Mobile);
expect(screen.getByText('Settings')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Notifications' })).toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'General section' })).not.toBeInTheDocument();
});
it('shows the general section by default on desktop /settings without mutating the URL', () => {
renderSettingsRoute('/settings', ScreenSize.Desktop);
expect(screen.getByRole('heading', { name: 'General section' })).toBeInTheDocument();
expect(screen.getByTestId('location-probe')).toHaveTextContent('/settings');
});
it('renders the requested section at /settings/devices', () => {
renderSettingsRoute('/settings/devices', ScreenSize.Mobile);
expect(screen.getByRole('heading', { name: 'Devices section' })).toBeInTheDocument();
});
it('redirects invalid sections back to /settings', async () => {
renderSettingsRoute('/settings/not-a-real-section', ScreenSize.Mobile);
await waitFor(() =>
expect(screen.getByTestId('location-probe')).toHaveTextContent(getSettingsPath())
);
expect(screen.getByText('Settings')).toBeInTheDocument();
});
it('navigates when a menu item is clicked', async () => {
const user = userEvent.setup();
renderSettingsRoute('/settings', ScreenSize.Mobile);
await user.click(screen.getByRole('button', { name: 'Notifications' }));
await waitFor(() =>
expect(screen.getByTestId('location-probe')).toHaveTextContent(
getSettingsPath('notifications')
)
);
expect(screen.getByRole('heading', { name: 'Notifications section' })).toBeInTheDocument();
});
it('returns to /settings when a section back button is clicked', async () => {
const user = userEvent.setup();
renderSettingsRoute('/settings/devices', ScreenSize.Mobile);
await user.click(screen.getByRole('button', { name: 'Back' }));
await waitFor(() =>
expect(screen.getByTestId('location-probe')).toHaveTextContent(getSettingsPath())
);
expect(screen.getByText('Settings')).toBeInTheDocument();
});
});
describe('useSettingsFocus', () => {
it('highlights a focus target from the query string', async () => {
vi.useFakeTimers();
@@ -77,7 +241,7 @@ describe('useSettingsFocus', () => {
await act(async () => {
await vi.advanceTimersByTimeAsync(1);
});
expect(screen.getByTestId('location-probe')).toHaveTextContent('');
expect(screen.getByTestId('location-probe')).toHaveTextContent('/settings/appearance');
expect(target).not.toHaveClass(focusedSettingTile);
} finally {
vi.useRealTimers();
@@ -0,0 +1,68 @@
import { useEffect } from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize';
import { getSettingsPath } from '$pages/pathUtils';
import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
import { Settings } from './Settings';
import { isSettingsSectionId, type SettingsSectionId } from './routes';
function resolveSettingsSection(
section: string | undefined,
screenSize: ScreenSize,
showPersona: boolean
): SettingsSectionId | null {
if (section === undefined) {
return screenSize === ScreenSize.Mobile ? null : 'general';
}
if (!isSettingsSectionId(section)) {
return null;
}
if (section === 'persona' && !showPersona) {
return null;
}
return section;
}
export function SettingsRoute() {
const { section } = useParams<{ section?: string }>();
const navigate = useNavigate();
const location = useLocation();
const screenSize = useScreenSizeContext();
const [showPersona] = useSetting(settingsAtom, 'showPersonaSetting');
const activeSection = resolveSettingsSection(section, screenSize, showPersona);
const shouldRedirectToIndex = section !== undefined && activeSection === null;
useEffect(() => {
if (!shouldRedirectToIndex) return;
navigate(getSettingsPath(), { replace: true, state: location.state });
}, [location.state, navigate, shouldRedirectToIndex]);
if (shouldRedirectToIndex) return null;
const requestClose = () => {
if (activeSection === null) {
navigate(-1);
return;
}
navigate(getSettingsPath(), { replace: true });
};
const handleSelectSection = (nextSection: SettingsSectionId) => {
navigate(getSettingsPath(nextSection));
};
return (
<Settings
activeSection={activeSection}
onSelectSection={handleSelectSection}
requestClose={requestClose}
/>
);
}
+1
View File
@@ -1,2 +1,3 @@
export * from './Settings';
export * from './SettingsRoute';
export * from './routes';