mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 02:14:05 +00:00
fix(client): give the desktop halves the same fixes their mobile twins got
Several of the fixes in this branch landed on a mobile screen while the desktop component with the identical bug sat in another package and was left alone, which leaves the two disagreeing about the same handler. So: the appearance tab flushes its debounced write on unmount, the journey share copy guards navigator.clipboard (undefined on a plain-HTTP self-hosted install), the admin collab toggle rolls back from a scoped snapshot instead of a stale one, the reservation modal parses metadata through the guarded helper rather than a bare JSON.parse that takes the route down, and the notification toggle surfaces its failures and stops racing concurrent toggles. The Journey components reached the memories provider-status endpoint with a raw fetch(), past every apiClient interceptor; they go through a small memoriesApi now. And the server half of the OSM menu_url finding: the client renders it through safeHttpUrl, so place-enrichment should not be handing a javascript: value out in the first place. The share section hides itself when the server says the link is not this user's to manage, rather than offering a create button that 403s.
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { delay, http, HttpResponse } from 'msw';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { buildAdmin } from '../../tests/helpers/factories';
|
||||
import { server } from '../../tests/helpers/msw/server';
|
||||
@@ -27,16 +27,21 @@ vi.mock('../components/Admin/AddonManager', () => ({
|
||||
default: ({
|
||||
bagTrackingEnabled,
|
||||
onToggleBagTracking,
|
||||
collabFeatures,
|
||||
onToggleCollabFeature,
|
||||
}: {
|
||||
bagTrackingEnabled: boolean;
|
||||
onToggleBagTracking: () => void;
|
||||
collabFeatures: Record<string, boolean>;
|
||||
onToggleCollabFeature: (key: string) => void;
|
||||
}) => (
|
||||
<div data-testid="addon-manager">
|
||||
<span data-testid="bag-tracking-state">{String(bagTrackingEnabled)}</span>
|
||||
<span data-testid="collab-chat-state">{String(collabFeatures?.chat)}</span>
|
||||
<span data-testid="collab-notes-state">{String(collabFeatures?.notes)}</span>
|
||||
<button onClick={() => onToggleBagTracking()}>toggle bag tracking</button>
|
||||
<button onClick={() => onToggleCollabFeature('chat')}>toggle chat</button>
|
||||
<button onClick={() => onToggleCollabFeature('notes')}>toggle notes</button>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
@@ -1569,8 +1574,38 @@ describe('AdminPage', () => {
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /toggle chat/i }));
|
||||
|
||||
// The rollback re-renders the stub; the addon panel stays mounted either way
|
||||
await waitFor(() => expect(screen.getByTestId('addon-manager')).toBeInTheDocument());
|
||||
await waitFor(() => expect(screen.getByTestId('collab-chat-state')).toHaveTextContent('true'));
|
||||
});
|
||||
|
||||
// A snapshot-wide rollback would undo the second toggle as well, leaving the
|
||||
// panel disagreeing with the server until a reload.
|
||||
it('a failing collab toggle keeps a second toggle made while it was in flight', async () => {
|
||||
server.use(
|
||||
http.get('/api/admin/collab-features', () =>
|
||||
HttpResponse.json({ chat: true, notes: true, polls: true, whatsnext: true })
|
||||
),
|
||||
http.put('/api/admin/collab-features', async ({ request }) => {
|
||||
const body = (await request.json()) as Record<string, unknown>;
|
||||
if ('chat' in body) {
|
||||
await delay(30);
|
||||
return HttpResponse.json({}, { status: 500 });
|
||||
}
|
||||
return HttpResponse.json({ success: true });
|
||||
})
|
||||
);
|
||||
|
||||
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
|
||||
render(<AdminPage />);
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument());
|
||||
fireEvent.click(screen.getByRole('button', { name: /^addons$/i }));
|
||||
await waitFor(() => expect(screen.getByTestId('collab-chat-state')).toHaveTextContent('true'));
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /toggle chat/i }));
|
||||
fireEvent.click(screen.getByRole('button', { name: /toggle notes/i }));
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('collab-chat-state')).toHaveTextContent('true'));
|
||||
expect(screen.getByTestId('collab-notes-state')).toHaveTextContent('false');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -161,9 +161,15 @@ function AdminPageDesktop(): React.ReactElement {
|
||||
setBagTrackingEnabled(next)
|
||||
try { await adminApi.updateBagTracking(next) } catch { setBagTrackingEnabled(!next) }
|
||||
}} collabFeatures={collabFeatures} onToggleCollabFeature={async (key: string) => {
|
||||
const next = { ...collabFeatures, [key]: !collabFeatures[key] }
|
||||
setCollabFeatures(next)
|
||||
try { await adminApi.updateCollabFeatures({ [key]: next[key] }) } catch { setCollabFeatures(collabFeatures) }
|
||||
const previous = collabFeatures[key]
|
||||
setCollabFeatures({ ...collabFeatures, [key]: !previous })
|
||||
try {
|
||||
await adminApi.updateCollabFeatures({ [key]: !previous })
|
||||
} catch {
|
||||
// Only this key rolls back — a slower request must not undo a toggle
|
||||
// the admin made in the meantime.
|
||||
setCollabFeatures(prev => ({ ...prev, [key]: previous }))
|
||||
}
|
||||
}} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -3720,13 +3720,15 @@ describe('JourneyDetailPage', () => {
|
||||
it('clicking Copy on share link copies to clipboard', async () => {
|
||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
||||
|
||||
// Mock clipboard
|
||||
// Mock clipboard. jsdom leaves isSecureContext undefined, which the copy
|
||||
// handler reads as plain HTTP and answers with its execCommand fallback.
|
||||
const mockWriteText = vi.fn().mockResolvedValue(undefined);
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
value: { writeText: mockWriteText },
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
Object.defineProperty(window, 'isSecureContext', { value: true, writable: true, configurable: true });
|
||||
|
||||
server.use(
|
||||
http.get('/api/journeys/1/share-link', () => {
|
||||
|
||||
@@ -98,7 +98,7 @@ function buildHook(over: Record<string, unknown> = {}): Record<string, unknown>
|
||||
unlinkTrip: null, setUnlinkTrip: vi.fn(),
|
||||
showSettings: false, setShowSettings: vi.fn(),
|
||||
hideSkeletons: false, setHideSkeletons: vi.fn(),
|
||||
mapRef: { current: null }, fullMapRef: { current: null },
|
||||
mapRef: { current: null }, fullMapRef: { current: null }, galleryUploadRef: { current: null },
|
||||
activeLocationId: null, handleMarkerClick: vi.fn(), handleLocationClick: vi.fn(),
|
||||
mapEntries: [], sidebarMapItems: [], tripDates: new Set<string>(), isMobile: false,
|
||||
feedEdge: { atTop: true, atBottom: true }, scrollFeedTo: vi.fn(),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-ADMHOOK-001 to FE-ADMHOOK-045
|
||||
// FE-ADMHOOK-001 to FE-ADMHOOK-049
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import React from 'react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
@@ -32,8 +32,13 @@ function wrapper({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
|
||||
/** Mounts the hook and waits until the initial parallel loads have settled. */
|
||||
async function mountAdmin() {
|
||||
const view = renderHook(() => useAdmin(), { wrapper });
|
||||
async function mountAdmin(url = '/admin') {
|
||||
const at = ({ children }: { children: React.ReactNode }) => (
|
||||
<MemoryRouter initialEntries={[url]}>
|
||||
<TranslationProvider>{children}</TranslationProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
const view = renderHook(() => useAdmin(), { wrapper: url === '/admin' ? wrapper : at });
|
||||
await waitFor(() => expect(view.result.current.isLoading).toBe(false));
|
||||
return view;
|
||||
}
|
||||
@@ -732,6 +737,36 @@ describe('useAdmin', () => {
|
||||
expect(result.current.users).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('FE-ADMHOOK-046: opens on the tab the URL asks for', async () => {
|
||||
const { result } = await mountAdmin('/admin?tab=audit');
|
||||
expect(result.current.activeTab).toBe('audit');
|
||||
});
|
||||
|
||||
/*
|
||||
* A tab id with no panel behind it — a typo, or a link from an install that
|
||||
* has tabs this one does not — used to open the page on an empty content
|
||||
* area with nothing selected in the sidebar.
|
||||
*/
|
||||
it('FE-ADMHOOK-047: falls back to users when the URL names a tab that does not exist', async () => {
|
||||
const { result } = await mountAdmin('/admin?tab=nonsense');
|
||||
expect(result.current.activeTab).toBe('users');
|
||||
});
|
||||
|
||||
/*
|
||||
* The sidebar entries are built conditionally but the panels are not, so a
|
||||
* hosted install had its hidden panels one URL away.
|
||||
*/
|
||||
it('FE-ADMHOOK-048: refuses a tab a managed install hides', async () => {
|
||||
seedStore(useAuthStore, { isAuthenticated: true, user: me, managed: true });
|
||||
const { result } = await mountAdmin('/admin?tab=backup');
|
||||
await waitFor(() => expect(result.current.activeTab).toBe('users'));
|
||||
});
|
||||
|
||||
it('FE-ADMHOOK-049: keeps that same tab on an install that runs itself', async () => {
|
||||
const { result } = await mountAdmin('/admin?tab=backup');
|
||||
expect(result.current.activeTab).toBe('backup');
|
||||
});
|
||||
|
||||
it('FE-ADMHOOK-044: mcpEnabled follows the addon store', async () => {
|
||||
const { result } = await mountAdmin();
|
||||
|
||||
|
||||
@@ -7,8 +7,32 @@ import { useAddonStore } from '../../store/addonStore'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { getApiErrorMessage } from '../../types'
|
||||
import { useToast } from '../../components/shared/Toast'
|
||||
import { managedAdminTabs } from '../../managed'
|
||||
import type { AdminUser, AdminStats, OidcConfig, UpdateInfo } from './adminModel'
|
||||
|
||||
/**
|
||||
* Every tab id AdminPage can render a panel for, whatever this install offers.
|
||||
*
|
||||
* ?tab= is user input and was taken as read: an id with no panel behind it —
|
||||
* a typo, or a link from an install that has tabs this one does not — opened
|
||||
* the admin page on an empty content area with nothing selected in the
|
||||
* sidebar. Labels and icons stay in AdminPage; this is only the vocabulary.
|
||||
*/
|
||||
const ADMIN_TAB_IDS = [
|
||||
'users', 'defaults', 'config', 'settings', 'addons', 'plugins', 'storage',
|
||||
'notifications', 'mcp-tokens', 'github', 'backup', 'audit', 'dev-notifications',
|
||||
]
|
||||
|
||||
/**
|
||||
* The ones a managed install deliberately does not offer.
|
||||
*
|
||||
* The sidebar entries are built conditionally, but the panels are not, so
|
||||
* ?tab=backup opened a backup schedule that competes with the real one on a
|
||||
* hosted instance. Checked in an effect rather than in the initial state
|
||||
* because `managed` arrives with /app-config, after the first render.
|
||||
*/
|
||||
const MANAGED_HIDDEN = ['storage', 'github', 'backup']
|
||||
|
||||
/**
|
||||
* Admin page logic — owns every admin data slice (users, stats, invites, auth
|
||||
* toggles, OIDC, feature flags, API keys, SMTP, version/update) plus the CRUD
|
||||
@@ -29,7 +53,11 @@ export function useAdmin() {
|
||||
// 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.
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
const [activeTab, setActiveTabState] = useState<string>(() => searchParams.get('tab') || 'users')
|
||||
const [activeTab, setActiveTabState] = useState<string>(() => {
|
||||
const asked = searchParams.get('tab')
|
||||
const known = [...ADMIN_TAB_IDS, ...managedAdminTabs.map(tab => tab.id)]
|
||||
return asked && known.includes(asked) ? asked : 'users'
|
||||
})
|
||||
const setActiveTab = useCallback((tab: string) => {
|
||||
setActiveTabState(tab)
|
||||
// replace, not push: eleven tabs would otherwise fill the back button with
|
||||
@@ -41,6 +69,10 @@ export function useAdmin() {
|
||||
return next
|
||||
}, { replace: true })
|
||||
}, [setSearchParams])
|
||||
useEffect(() => {
|
||||
if (managed && MANAGED_HIDDEN.includes(activeTab)) setActiveTab('users')
|
||||
}, [managed, activeTab, setActiveTab])
|
||||
|
||||
const [users, setUsers] = useState<AdminUser[]>([])
|
||||
const [stats, setStats] = useState<AdminStats | null>(null)
|
||||
const [isLoading, setIsLoading] = useState<boolean>(true)
|
||||
|
||||
Reference in New Issue
Block a user