fix(admin): open the tab a link names while the admin page is already open

The active tab now follows ?tab= when only the query changes, so a help guide's go to screen link reaches the Services tab from the Security tab.
This commit is contained in:
Maurice
2026-11-23 15:37:48 +01:00
parent 464d5aa902
commit 2b21407cf9
2 changed files with 92 additions and 31 deletions
+75 -23
View File
@@ -1,14 +1,14 @@
// FE-ADMHOOK-001 to FE-ADMHOOK-058
// FE-ADMHOOK-001 to FE-ADMHOOK-059
import { http, HttpResponse } from 'msw';
import React from 'react';
import { MemoryRouter, useNavigate } from 'react-router';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { MemoryRouter } from 'react-router';
import { buildAdmin, buildUser } from '../../../tests/helpers/factories';
import { server } from '../../../tests/helpers/msw/server';
import { act, renderHook, waitFor } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { TranslationProvider } from '../../i18n/TranslationContext';
import { adminApi } from '../../api/client';
import { TranslationProvider } from '../../i18n/TranslationContext';
import { useAuthStore } from '../../store/authStore';
import { useAdmin } from './useAdmin';
@@ -65,7 +65,7 @@ describe('useAdmin', () => {
it('FE-ADMHOOK-001: loads users, stats and invites on mount', async () => {
const { result } = await mountAdmin();
expect(result.current.users.map(u => u.username)).toEqual(['admin', 'alice']);
expect(result.current.users.map((u) => u.username)).toEqual(['admin', 'alice']);
expect(result.current.stats).toMatchObject({ totalUsers: 2, totalTrips: 5, totalPlaces: 42, totalFiles: 8 });
expect(result.current.invites).toEqual([]);
expect(result.current.activeTab).toBe('users');
@@ -197,7 +197,11 @@ describe('useAdmin', () => {
HttpResponse.json({ chat: false, notes: true, polls: false, whatsnext: true })
),
http.get('/api/auth/app-settings', () =>
HttpResponse.json({ smtp_host: 'mail.test', webauthn_rp_id: 'trek.test', webauthn_origins: 'https://trek.test' })
HttpResponse.json({
smtp_host: 'mail.test',
webauthn_rp_id: 'trek.test',
webauthn_origins: 'https://trek.test',
})
)
);
@@ -242,9 +246,7 @@ describe('useAdmin', () => {
});
it('FE-ADMHOOK-013: handleToggleAuthSetting rolls back and toasts on failure', async () => {
server.use(
http.put('/api/auth/app-settings', () => HttpResponse.json({ error: 'locked' }, { status: 400 }))
);
server.use(http.put('/api/auth/app-settings', () => HttpResponse.json({ error: 'locked' }, { status: 400 })));
const { result } = await mountAdmin();
await act(async () => {
@@ -276,7 +278,7 @@ describe('useAdmin', () => {
});
expect(result.current.requireMfa).toBe(false);
expect(toastCalls.some(c => c.type === 'error')).toBe(true);
expect(toastCalls.some((c) => c.type === 'error')).toBe(true);
});
it('FE-ADMHOOK-050: handleTogglePlacesGoogleOnly flips the switch and PUTs it', async () => {
@@ -343,7 +345,7 @@ describe('useAdmin', () => {
await result.current.handleSaveWebauthn();
});
expect(toastCalls.some(c => c.type === 'error')).toBe(true);
expect(toastCalls.some((c) => c.type === 'error')).toBe(true);
expect(result.current.savingWebauthn).toBe(false);
});
@@ -385,7 +387,11 @@ describe('useAdmin', () => {
server.use(
http.get('/api/auth/me/settings', () =>
HttpResponse.json({
settings: { maps_api_key: null, unsplash_api_key: 'unsplash-k', env_keys: { maps_api_key: 'PLACES_API_KEY' } },
settings: {
maps_api_key: null,
unsplash_api_key: 'unsplash-k',
env_keys: { maps_api_key: 'PLACES_API_KEY' },
},
})
)
);
@@ -433,7 +439,7 @@ describe('useAdmin', () => {
await result.current.handleSaveApiKeys();
});
expect(toastCalls.some(c => c.type === 'error')).toBe(true);
expect(toastCalls.some((c) => c.type === 'error')).toBe(true);
expect(result.current.savingKeys).toBe(false);
});
@@ -513,7 +519,7 @@ describe('useAdmin', () => {
await result.current.handleCreateUser();
});
expect(toastCalls.some(c => c.type === 'error')).toBe(true);
expect(toastCalls.some((c) => c.type === 'error')).toBe(true);
expect(result.current.users).toHaveLength(2);
});
@@ -609,7 +615,12 @@ describe('useAdmin', () => {
it('FE-ADMHOOK-032: handleDeleteInvite removes it from the list', async () => {
server.use(
http.get('/api/admin/invites', () =>
HttpResponse.json({ invites: [{ id: 5, token: 'a' }, { id: 6, token: 'b' }] })
HttpResponse.json({
invites: [
{ id: 5, token: 'a' },
{ id: 6, token: 'b' },
],
})
)
);
const { result } = await mountAdmin();
@@ -618,7 +629,7 @@ describe('useAdmin', () => {
await result.current.handleDeleteInvite(5);
});
expect(result.current.invites.map(i => i.id)).toEqual([6]);
expect(result.current.invites.map((i) => i.id)).toEqual([6]);
expect(toastCalls).toContainEqual({ type: 'success', message: 'Invite link deleted' });
});
@@ -645,7 +656,9 @@ describe('useAdmin', () => {
act(() => result.current.copyInviteLink('tok-9'));
expect(writeText).toHaveBeenCalledWith(`${window.location.origin}/register?invite=tok-9`);
await waitFor(() => expect(toastCalls).toContainEqual({ type: 'success', message: 'Invite link copied to clipboard' }));
await waitFor(() =>
expect(toastCalls).toContainEqual({ type: 'success', message: 'Invite link copied to clipboard' })
);
});
it('FE-ADMHOOK-035: handleEditUser seeds the edit form from the user', async () => {
@@ -730,7 +743,15 @@ describe('useAdmin', () => {
server.use(
http.put('/api/admin/users/:id', ({ params }) =>
// The update answers with the account fields only.
HttpResponse.json({ user: { id: Number(params.id), username: 'alice2', email: 'a2@e.com', role: 'user', created_at: '2026-01-01 00:00:00' } })
HttpResponse.json({
user: {
id: Number(params.id),
username: 'alice2',
email: 'a2@e.com',
role: 'user',
created_at: '2026-01-01 00:00:00',
},
})
)
);
const { result } = await mountAdmin();
@@ -767,7 +788,7 @@ describe('useAdmin', () => {
expect(called).toBe(false);
expect(result.current.editingUser).not.toBeNull();
expect(toastCalls.some(c => c.type === 'error')).toBe(true);
expect(toastCalls.some((c) => c.type === 'error')).toBe(true);
});
it('FE-ADMHOOK-038: handleSaveUser forwards a long enough password', async () => {
@@ -845,7 +866,7 @@ describe('useAdmin', () => {
});
expect(deletedId).toBe('2');
expect(result.current.users.map(u => u.username)).toEqual(['admin']);
expect(result.current.users.map((u) => u.username)).toEqual(['admin']);
expect(toastCalls).toContainEqual({ type: 'success', message: 'User deleted' });
});
@@ -859,7 +880,7 @@ describe('useAdmin', () => {
});
expect(confirmSpy).not.toHaveBeenCalled();
expect(result.current.users.map(u => u.username)).toEqual(['admin']);
expect(result.current.users.map((u) => u.username)).toEqual(['admin']);
});
it('FE-ADMHOOK-043: a failing delete surfaces the server error', async () => {
@@ -923,7 +944,10 @@ describe('useAdmin', () => {
await act(() => result.current.saveDemoBaseline());
expect(save).toHaveBeenCalledTimes(1);
expect(toastCalls).toContainEqual({ type: 'success', message: 'Baseline saved! Resets will restore to this state.' });
expect(toastCalls).toContainEqual({
type: 'success',
message: 'Baseline saved! Resets will restore to this state.',
});
save.mockRejectedValueOnce({ response: { data: { error: 'Not a demo' } } });
await act(() => result.current.saveDemoBaseline());
@@ -956,7 +980,12 @@ describe('useAdmin', () => {
});
it('FE-ADMHOOK-057: a collab feature toggle saves only that key', async () => {
vi.spyOn(adminApi, 'getCollabFeatures').mockResolvedValue({ chat: true, notes: true, polls: true, whatsnext: true });
vi.spyOn(adminApi, 'getCollabFeatures').mockResolvedValue({
chat: true,
notes: true,
polls: true,
whatsnext: true,
});
const update = vi.spyOn(adminApi, 'updateCollabFeatures').mockResolvedValue({});
const { result } = await mountAdmin();
await waitFor(() => expect(result.current.collabFeatures.chat).toBe(true));
@@ -967,7 +996,12 @@ describe('useAdmin', () => {
});
it('FE-ADMHOOK-058: a failed collab toggle rolls back its own key and keeps a later one', async () => {
vi.spyOn(adminApi, 'getCollabFeatures').mockResolvedValue({ chat: true, notes: true, polls: true, whatsnext: true });
vi.spyOn(adminApi, 'getCollabFeatures').mockResolvedValue({
chat: true,
notes: true,
polls: true,
whatsnext: true,
});
let fail!: (e: unknown) => void;
vi.spyOn(adminApi, 'updateCollabFeatures')
.mockReturnValueOnce(new Promise((_, reject) => (fail = reject)))
@@ -986,4 +1020,22 @@ describe('useAdmin', () => {
});
expect(result.current.collabFeatures).toEqual({ chat: true, notes: false, polls: true, whatsnext: true });
});
it('FE-ADMHOOK-059: a link to another tab of the open admin page opens that tab', async () => {
const at = ({ children }: { children: React.ReactNode }) => (
<MemoryRouter initialEntries={['/admin?tab=security']}>
<TranslationProvider>{children}</TranslationProvider>
</MemoryRouter>
);
const { result } = renderHook(() => ({ admin: useAdmin(), navigate: useNavigate() }), { wrapper: at });
await waitFor(() => expect(result.current.admin.isLoading).toBe(false));
expect(result.current.admin.activeTab).toBe('security');
act(() => void result.current.navigate('/admin?tab=services'));
expect(result.current.admin.activeTab).toBe('services');
act(() => void result.current.navigate('/admin?tab=settings'));
expect(result.current.admin.activeTab).toBe('security');
act(() => result.current.admin.setActiveTab('audit'));
expect(result.current.admin.activeTab).toBe('audit');
});
});
+17 -8
View File
@@ -42,6 +42,13 @@ const ADMIN_TAB_ALIASES: Record<string, string> = { settings: 'security' }
*/
const MANAGED_HIDDEN = ['storage', 'github', 'backup', 'plugins']
/** The tab a ?tab= value opens: an old name by its new one, anything unknown on users. */
function tabFromParam(raw: string | null): string {
const asked = raw ? (ADMIN_TAB_ALIASES[raw] ?? raw) : null
const known = [...ADMIN_TAB_IDS, ...managedAdminTabs.map(tab => tab.id)]
return asked && known.includes(asked) ? asked : 'users'
}
/** How often the open users list asks again who is online and active. */
const USERS_REFRESH_MS = 30_000
@@ -67,15 +74,17 @@ export function useAdmin() {
// ?tab= makes a section linkable: a support reply, an onboarding mail or a
// bookmark can point at the one panel it is about instead of at the top of a
// page with eleven of them. Read once for the initial value and written back
// on every change, so the address bar keeps saying where the reader is.
// page with eleven of them. Written back on every change, so the address bar
// keeps saying where the reader is, and followed when only it changes: a help
// guide links to another tab of the page the reader is already on.
const [searchParams, setSearchParams] = useSearchParams()
const [activeTab, setActiveTabState] = useState<string>(() => {
const raw = searchParams.get('tab')
const asked = raw ? (ADMIN_TAB_ALIASES[raw] ?? raw) : null
const known = [...ADMIN_TAB_IDS, ...managedAdminTabs.map(tab => tab.id)]
return asked && known.includes(asked) ? asked : 'users'
})
const tabParam = searchParams.get('tab')
const [activeTab, setActiveTabState] = useState<string>(() => tabFromParam(tabParam))
const [followedParam, setFollowedParam] = useState(tabParam)
if (tabParam !== followedParam) {
setFollowedParam(tabParam)
setActiveTabState(tabFromParam(tabParam))
}
const setActiveTab = useCallback((tab: string) => {
setActiveTabState(tab)
// replace, not push: eleven tabs would otherwise fill the back button with