The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
test(components): cover map, collections, settings, journey and admin
Mauricebbb0f93af278
diff --git a/client/src/components/Admin/AddonManager.test.tsx b/client/src/components/Admin/AddonManager.test.tsxindex 206f063d5..20c6c1a5c 100644--- a/client/src/components/Admin/AddonManager.test.tsx+++ b/client/src/components/Admin/AddonManager.test.tsx@@ -1,7 +1,7 @@-// FE-ADMIN-ADDON-001 to FE-ADMIN-ADDON-011+// FE-ADMIN-ADDON-001 to FE-ADMIN-ADDON-025import { render, screen, waitFor, within } from '../../../tests/helpers/render';import userEvent from '@testing-library/user-event';-import { http, HttpResponse } from 'msw';+import { delay, http, HttpResponse } from 'msw';import { server } from '../../../tests/helpers/msw/server';import { resetAllStores, seedStore } from '../../../tests/helpers/store';import { useSettingsStore } from '../../store/settingsStore';@@ -21,6 +21,45 @@ function buildAddon(overrides = {}) {};}+function addonsRoute(addons: ReturnType<typeof buildAddon>[]) {+ return http.get('/api/admin/addons', () => HttpResponse.json({ addons }));+}++function llmAddon(config: Record<string, unknown> = {}) {+ return buildAddon({+ id: 'llm_parsing',+ name: 'AI Parsing',+ description: 'Extract bookings from files',+ icon: 'Sparkles',+ type: 'integration',+ enabled: true,+ config,+ });+}++function modelsRoute(names: string[], seen?: (string | null)[]) {+ return http.get('/api/admin/llm/local/models', ({ request }) => {+ seen?.push(new URL(request.url).searchParams.get('baseUrl'));+ return HttpResponse.json({ models: names.map(name => ({ name, size: 1 })) });+ });+}++/** The pill toggle of a top-level addon row. */+function addonToggle(name: string): HTMLElement {+ const row = screen.getByText(name).closest('.px-6.py-4') as HTMLElement;+ return within(row).getByRole('button');+}++/** The pill toggle of an indented sub-row (bag tracking, collab feature, photo provider). */+function subToggle(label: string): HTMLElement {+ const row = screen.getByText(label).closest('.flex.items-center.gap-4') as HTMLElement;+ return within(row).getByRole('button');+}++function isOn(toggle: HTMLElement): boolean {+ return toggle.style.background === 'var(--text-primary)';+}+beforeAll(() => {Object.defineProperty(window, 'matchMedia', {writable: true,@@ -229,4 +268,330 @@ describe('AddonManager', () => {expect(() => render(<AddonManager />)).not.toThrow();await screen.findByText('Mystery Addon');});++ it('FE-ADMIN-ADDON-012: a failing load toasts the addon error and shows the empty state', async () => {+ server.use(http.get('/api/admin/addons', () => HttpResponse.error()));+ render(<><ToastContainer /><AddonManager /></>);++ await screen.findByText('Failed to update addon');+ expect(screen.getByText('No addons available')).toBeInTheDocument();+ });++ it('FE-ADMIN-ADDON-013: dark mode swaps the wordmark in the header', async () => {+ seedStore(useSettingsStore, { settings: { dark_mode: 'dark' } });+ render(<AddonManager />);++ await screen.findByText('No addons available');+ expect(screen.getByAltText('TREK')).toHaveAttribute('src', '/text-light.svg');+ });++ it('FE-ADMIN-ADDON-014: photo-flavoured trip addons are hidden from the trip section', async () => {+ server.use(addonsRoute([+ buildAddon({ id: 'photos', name: 'Memories', icon: 'Image' }),+ buildAddon({ id: 'gallery', name: 'Trip Photos', icon: 'Puzzle', description: 'Share your photo stream' }),+ buildAddon({ id: 'todo', name: 'Todo List' }),+ ]));+ render(<AddonManager />);++ await screen.findByText('Todo List');+ expect(screen.queryByText('Memories')).not.toBeInTheDocument();+ expect(screen.queryByText('Trip Photos')).not.toBeInTheDocument();+ });++ it('FE-ADMIN-ADDON-015: provider sub-rows carry their vendor icons and toggle state', async () => {+ server.use(addonsRoute([+ buildAddon({ id: 'journey', name: 'Journey', type: 'global', icon: 'Compass', enabled: true }),+ buildAddon({ id: 'immich', name: 'Immich', description: 'Self-hosted photos', type: 'photo_provider', enabled: true }),+ buildAddon({ id: 'synologyphotos', name: 'Synology Photos', description: 'NAS photos', type: 'photo_provider', enabled: false }),+ buildAddon({ id: 'unsplash', name: 'Unsplash', description: 'Stock photos', type: 'photo_provider', enabled: false }),+ ]));+ render(<AddonManager />);++ await screen.findByText('Immich');+ // immich and synologyphotos ship a vendor glyph, unsplash does not+ const immichRow = screen.getByText('Immich').closest('.flex.items-center.gap-4') as HTMLElement;+ expect(immichRow.querySelector('svg')).toBeInTheDocument();+ const synologyRow = screen.getByText('Synology Photos').closest('.flex.items-center.gap-4') as HTMLElement;+ expect(synologyRow.querySelector('svg')).toBeInTheDocument();+ const unsplashRow = screen.getByText('Unsplash').closest('.flex.items-center.gap-4') as HTMLElement;+ expect(unsplashRow.querySelector('svg')).not.toBeInTheDocument();++ expect(isOn(subToggle('Immich'))).toBe(true);+ expect(isOn(subToggle('Unsplash'))).toBe(false);+ });++ it('FE-ADMIN-ADDON-016: toggling a photo provider persists it and refreshes the global addons', async () => {+ const user = userEvent.setup();+ let body: unknown = null;+ server.use(+ addonsRoute([+ buildAddon({ id: 'journey', name: 'Journey', type: 'global', icon: 'Compass', enabled: true }),+ buildAddon({ id: 'immich', name: 'Immich', description: 'Self-hosted photos', type: 'photo_provider', enabled: false }),+ ]),+ http.put('/api/admin/addons/immich', async ({ request }) => {+ body = await request.json();+ return HttpResponse.json({ success: true });+ }),+ );+ render(<><ToastContainer /><AddonManager /></>);+ await screen.findByText('Immich');++ await user.click(subToggle('Immich'));++ await waitFor(() => expect(body).toEqual({ enabled: true }));+ await screen.findByText('Addon updated');+ expect(isOn(subToggle('Immich'))).toBe(true);+ });++ it('FE-ADMIN-ADDON-017: a failing photo-provider toggle rolls the sub-row back', async () => {+ const user = userEvent.setup();+ server.use(+ addonsRoute([+ buildAddon({ id: 'journey', name: 'Journey', type: 'global', icon: 'Compass', enabled: true }),+ buildAddon({ id: 'unsplash', name: 'Unsplash', description: 'Stock photos', type: 'photo_provider', enabled: true }),+ ]),+ http.put('/api/admin/addons/unsplash', () => HttpResponse.error()),+ );+ render(<><ToastContainer /><AddonManager /></>);+ await screen.findByText('Unsplash');++ await user.click(subToggle('Unsplash'));++ await screen.findByText('Failed to update addon');+ await waitFor(() => expect(isOn(subToggle('Unsplash'))).toBe(true));+ });++ it('FE-ADMIN-ADDON-018: the collab sub-features render their state and report the toggled key', async () => {+ const user = userEvent.setup();+ const onToggleCollabFeature = vi.fn();+ server.use(addonsRoute([buildAddon({ id: 'collab', name: 'Collab', enabled: true })]));+ render(+ <AddonManager+ collabFeatures={{ chat: true, notes: false, polls: false, whatsnext: true }}+ onToggleCollabFeature={onToggleCollabFeature}+ />,+ );++ await screen.findByText('Chat');+ expect(screen.getByText('Notes')).toBeInTheDocument();+ expect(screen.getByText('Polls')).toBeInTheDocument();+ expect(screen.getByText("What's Next")).toBeInTheDocument();+ expect(isOn(subToggle('Chat'))).toBe(true);+ expect(isOn(subToggle('Notes'))).toBe(false);++ await user.click(subToggle('Polls'));+ expect(onToggleCollabFeature).toHaveBeenCalledWith('polls');+ });++ it('FE-ADMIN-ADDON-019: collab sub-features stay hidden without the handler props', async () => {+ server.use(addonsRoute([buildAddon({ id: 'collab', name: 'Collab', enabled: true })]));+ render(<AddonManager />);++ await screen.findByText('Collab');+ expect(screen.queryByText('Polls')).not.toBeInTheDocument();+ });++ it('FE-ADMIN-ADDON-020: a disabled AI-parsing addon renders the row without its config block', async () => {+ server.use(addonsRoute([{ ...llmAddon({ provider: 'local' }), enabled: false }]));+ render(<AddonManager />);++ await screen.findByText('AI Parsing');+ expect(screen.getByText('Extract bookings from files')).toBeInTheDocument();+ expect(screen.queryByText('Connection')).not.toBeInTheDocument();+ });++ it('FE-ADMIN-ADDON-021: the local provider lists installed models and a chip fills the model field', async () => {+ const user = userEvent.setup();+ const urls: (string | null)[] = [];+ server.use(addonsRoute([llmAddon({ provider: 'local' })]), modelsRoute(['qwen3:8b', 'llama3:8b'], urls));+ render(<AddonManager />);++ await screen.findByText('Installed on the server');+ await screen.findByRole('button', { name: 'llama3:8b' });+ expect(urls[0]).toBe('http://localhost:11434/v1');++ await user.click(screen.getByRole('button', { name: 'llama3:8b' }));+ expect(screen.getByPlaceholderText('select or pull below')).toHaveValue('llama3:8b');++ // qwen3:8b is already installed, so the recommended row offers "Use" instead of "Pull"+ await user.click(screen.getByRole('button', { name: 'Use' }));+ expect(screen.getByPlaceholderText('select or pull below')).toHaveValue('qwen3:8b');+ expect(screen.getByRole('button', { name: 'Selected' })).toBeDisabled();+ });++ it('FE-ADMIN-ADDON-022: an unreachable Ollama shows the error and Refresh retries', async () => {+ const user = userEvent.setup();+ let calls = 0;+ server.use(+ addonsRoute([llmAddon({ provider: 'local' })]),+ http.get('/api/admin/llm/local/models', () => {+ calls += 1;+ return calls === 1+ ? HttpResponse.json({ error: 'down' }, { status: 500 })+ : HttpResponse.json({ models: [] });+ }),+ );+ render(<AddonManager />);++ await screen.findByText(/Request failed with status code 500/);++ await user.click(screen.getByRole('button', { name: 'Refresh' }));+ await screen.findByText('No models installed yet — pull one below.');+ expect(calls).toBe(2);+ });++ it('FE-ADMIN-ADDON-023: switching providers swaps the base URL field, the model hint and the Ollama block', async () => {+ const user = userEvent.setup();+ const urls: (string | null)[] = [];+ server.use(addonsRoute([llmAddon({ provider: 'local', apiKey: '••••••••' })]), modelsRoute([], urls));+ render(<AddonManager />);++ await screen.findByText('Installed on the server');+ expect(screen.getByPlaceholderText('••••••••')).toBeInTheDocument();++ // A hand-typed base URL is used for the next lookup on blur+ await user.type(screen.getByPlaceholderText('http://localhost:11434/v1'), 'http://ollama.lan:11434/v1');+ await user.tab();+ await waitFor(() => expect(urls).toContain('http://ollama.lan:11434/v1'));++ await user.click(screen.getByRole('button', { name: /Local · OpenAI-compatible/ }));+ await user.click(screen.getByRole('button', { name: 'OpenAI' }));+ expect(screen.getByPlaceholderText('https://api.openai.com/v1')).toBeInTheDocument();+ expect(screen.getByPlaceholderText('gpt-4o')).toBeInTheDocument();+ expect(screen.queryByText('Installed on the server')).not.toBeInTheDocument();++ await user.click(screen.getByRole('button', { name: 'OpenAI' }));+ await user.click(screen.getByRole('button', { name: 'Anthropic' }));+ expect(screen.queryByPlaceholderText('https://api.openai.com/v1')).not.toBeInTheDocument();+ expect(screen.getByPlaceholderText('claude-opus-4-8')).toBeInTheDocument();+ expect(screen.getByText(/Anthropic reads PDFs/)).toBeInTheDocument();+ });++ it('FE-ADMIN-ADDON-024: pulling a model streams progress and then selects it', async () => {+ const user = userEvent.setup();+ let pulled: unknown = null;+ let modelCalls = 0;+ server.use(+ addonsRoute([llmAddon({ provider: 'local' })]),+ http.get('/api/admin/llm/local/models', () => {+ modelCalls += 1;+ return HttpResponse.json({ models: modelCalls === 1 ? [] : [{ name: 'qwen3:8b', size: 1 }] });+ }),+ http.post('/api/admin/llm/local/pull', async ({ request }) => {+ pulled = await request.json();+ await delay(150);+ return new HttpResponse(+ '{"status":"pulling manifest"}\n{"status":"downloading","total":100,"completed":40}\nnot-json\n',+ { headers: { 'Content-Type': 'application/x-ndjson' } },+ );+ }),+ );+ render(<><ToastContainer /><AddonManager /></>);++ await screen.findByText('No models installed yet — pull one below.');+ await user.click(screen.getByRole('button', { name: 'Pull' }));++ await screen.findByText('Pulling…');+ expect(screen.getByText('starting…')).toBeInTheDocument();++ await screen.findByText('Model pulled');+ expect(pulled).toEqual({ baseUrl: 'http://localhost:11434/v1', model: 'qwen3:8b' });+ expect(screen.getByPlaceholderText('select or pull below')).toHaveValue('qwen3:8b');+ await waitFor(() => expect(screen.getByRole('button', { name: 'Selected' })).toBeDisabled());+ });++ it('FE-ADMIN-ADDON-025: a failing pull surfaces the server error and saving reports both outcomes', async () => {+ const user = userEvent.setup();+ const bodies: unknown[] = [];+ server.use(+ addonsRoute([llmAddon({ provider: 'local', model: 'qwen3:8b', baseUrl: '', apiKey: '••••••••', multimodal: true })]),+ modelsRoute([]),+ http.post('/api/admin/llm/local/pull', () => HttpResponse.json({ error: 'no disk space' }, { status: 500 })),+ http.put('/api/admin/addons/llm_parsing', async ({ request }) => {+ bodies.push(await request.json());+ return bodies.length === 1 ? HttpResponse.json({ success: true }) : HttpResponse.error();+ }),+ );+ render(<><ToastContainer /><AddonManager /></>);++ await screen.findByText('No models installed yet — pull one below.');+ await user.click(screen.getByRole('button', { name: 'Pull' }));+ await screen.findByText('no disk space');+ expect(screen.getByRole('button', { name: 'Pull' })).toBeEnabled();++ await user.click(screen.getByRole('button', { name: 'Save' }));+ await screen.findByText('Saved');+ expect(bodies[0]).toEqual({+ config: { provider: 'local', model: 'qwen3:8b', baseUrl: '', apiKey: '••••••••', multimodal: true },+ });++ await user.click(screen.getByRole('button', { name: 'Save' }));+ await screen.findByText('Failed to save');+ });++ it('FE-ADMIN-ADDON-026: model and API key are editable and their hints follow the provider', async () => {+ const user = userEvent.setup();+ const bodies: unknown[] = [];+ server.use(+ addonsRoute([llmAddon({ provider: 'local' })]),+ modelsRoute([]),+ http.put('/api/admin/addons/llm_parsing', async ({ request }) => {+ bodies.push(await request.json());+ return HttpResponse.json({ success: true });+ }),+ );+ render(<><ToastContainer /><AddonManager /></>);++ await screen.findByText('Installed on the server');+ expect(screen.getByPlaceholderText('(often not required)')).toBeInTheDocument();++ await user.type(screen.getByPlaceholderText('select or pull below'), ' mistral:7b ');+ await user.type(screen.getByPlaceholderText('(often not required)'), 'sk-live');++ await user.click(screen.getByRole('button', { name: /Local · OpenAI-compatible/ }));+ await user.click(screen.getByRole('button', { name: 'OpenAI' }));+ expect(screen.getByPlaceholderText('sk-…')).toHaveValue('sk-live');++ await user.click(screen.getByRole('button', { name: 'Save' }));+ await screen.findByText('Saved');+ // The model is trimmed before it is stored, the key is sent verbatim+ expect(bodies[0]).toEqual({+ config: { provider: 'openai', model: 'mistral:7b', baseUrl: '', apiKey: 'sk-live', multimodal: false },+ });+ });++ it('FE-ADMIN-ADDON-027: an error frame in the pull stream is tolerated and the row returns to idle', async () => {+ const user = userEvent.setup();+ server.use(+ addonsRoute([llmAddon({ provider: 'local' })]),+ modelsRoute([]),+ http.post('/api/admin/llm/local/pull', () => new HttpResponse(+ '{"status":"pulling manifest"}\n{"error":"manifest not found"}\n',+ { headers: { 'Content-Type': 'application/x-ndjson' } },+ )),+ );+ render(<><ToastContainer /><AddonManager /></>);++ await screen.findByText('No models installed yet — pull one below.');+ await user.click(screen.getByRole('button', { name: 'Pull' }));++ await waitFor(() => expect(screen.getByRole('button', { name: 'Pull' })).toBeEnabled());+ expect(screen.queryByText('Pulling…')).not.toBeInTheDocument();+ });++ it('FE-ADMIN-ADDON-028: blurring the base URL under a cloud provider queries no local models', async () => {+ const user = userEvent.setup();+ const urls: (string | null)[] = [];+ server.use(addonsRoute([llmAddon({ provider: 'openai' })]), modelsRoute([], urls));+ render(<AddonManager />);++ await screen.findByText('Connection');+ expect(screen.queryByText('Installed on the server')).not.toBeInTheDocument();++ await user.type(screen.getByPlaceholderText('https://api.openai.com/v1'), 'https://proxy.local/v1');+ await user.tab();++ await waitFor(() => expect(screen.getByDisplayValue('https://proxy.local/v1')).toBeInTheDocument());+ expect(urls).toHaveLength(0);+ });});diff --git a/client/src/components/Admin/AdminPluginsPanel.test.tsx b/client/src/components/Admin/AdminPluginsPanel.test.tsxindex 8c1884818..fa6ad9615 100644--- a/client/src/components/Admin/AdminPluginsPanel.test.tsx+++ b/client/src/components/Admin/AdminPluginsPanel.test.tsx@@ -1,8 +1,10 @@import { http, HttpResponse } from 'msw'-import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import userEvent from '@testing-library/user-event'import { server } from '../../../tests/helpers/msw/server'-import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render'+import { fireEvent, render, screen, waitFor, within } from '../../../tests/helpers/render'import { resetAllStores } from '../../../tests/helpers/store'+import { ToastContainer } from '../shared/Toast'import AdminPluginsPanel from './AdminPluginsPanel'/**@@ -482,3 +484,825 @@ describe('AdminPluginsPanel — TREK-version compatibility', () => {expect(await screen.findByText(/needs trek >=3\.2\.0 <4\.0\.0/i)).toBeInTheDocument()})})++/**+ * The rest of the panel: load states, the toolbar, sideloading, the row actions behind the+ * ⋯ menu, and the dialog each 409 routes to.+ */+function panelWith(+ plugins: Record<string, unknown>[],+ opts: { enabled?: boolean; devLink?: boolean; registry?: Record<string, unknown>[] } = {},+) {+ server.use(+ http.get('*/api/admin/plugins', () => HttpResponse.json({+ enabled: opts.enabled ?? true, devLink: opts.devLink ?? false, plugins,+ })),+ http.get('*/api/admin/plugins/registry', () => HttpResponse.json(opts.registry ?? [])),+ )+}++function withToast() {+ return render(<><ToastContainer /><AdminPluginsPanel /></>)+}++/** The Discover tab is a role="tab"; the empty state offers a plain button with the same label. */+async function clickDiscover() {+ const tabs = await screen.findAllByRole('tab', { name: /^discover/i })+ fireEvent.click(tabs[0])+}++/** The panel root, which owns the drag-and-drop handlers. */+function panelRoot(container: HTMLElement): HTMLElement {+ return (container.querySelector('input[type="file"]') as HTMLElement).parentElement as HTMLElement+}++/** Opens one of the toolbar dropdowns (identified by its current title) and picks an option. */+async function pickFilter(trigger: RegExp, option: RegExp) {+ fireEvent.click(await screen.findByTitle(trigger))+ fireEvent.click(await screen.findByRole('button', { name: option }))+}++/** The enable toggle of a named installed row. */+function rowToggle(name: string): HTMLElement {+ const row = screen.getByText(name).closest('.group') as HTMLElement+ return within(row).getByRole('button', { name: 'Enable plugin' })+}++describe('AdminPluginsPanel — load states and toolbar', () => {+ it('FE-COMP-PLUGINS-PANEL-001: a failing plugin list shows the load error instead of an empty list', async () => {+ server.use(http.get('*/api/admin/plugins', () => HttpResponse.error()))+ render(<AdminPluginsPanel />)++ expect(await screen.findByText('Could not load plugins.')).toBeInTheDocument()+ expect(screen.queryByPlaceholderText('Search plugins…')).not.toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-002: a disabled runtime replaces the whole body with the notice', async () => {+ panelWith([plugin()], { enabled: false })+ render(<AdminPluginsPanel />)++ expect(await screen.findByText('Plugins are disabled')).toBeInTheDocument()+ expect(screen.queryByText('Gotify')).not.toBeInTheDocument()+ expect(screen.queryByText('Runtime on')).not.toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-003: with nothing installed the empty state jumps to Discover', async () => {+ panelWith([])+ render(<AdminPluginsPanel />)++ await screen.findByText('No plugins installed yet.')+ expect(screen.getByText('Runtime on')).toBeInTheDocument()+ fireEvent.click(screen.getAllByRole('button', { name: /^discover/i }).pop()!)++ expect(await screen.findByText('No plugins available in the registry yet.')).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-004: the search box filters the installed list and says when nothing matches', async () => {+ panelWith([plugin({ id: 'a', name: 'Gotify' }), plugin({ id: 'b', name: 'Ntfy', description: 'Push too' })])+ render(<AdminPluginsPanel />)+ await screen.findByText('Gotify')++ fireEvent.change(screen.getByPlaceholderText('Search plugins…'), { target: { value: 'ntfy' } })+ expect(screen.queryByText('Gotify')).not.toBeInTheDocument()+ expect(screen.getByText('Ntfy')).toBeInTheDocument()++ fireEvent.change(screen.getByPlaceholderText('Search plugins…'), { target: { value: 'zzz' } })+ expect(screen.getByText('No installed plugins match your search.')).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-005: the type filter narrows the list and marks itself active', async () => {+ panelWith([+ plugin({ id: 'a', name: 'Gotify', type: 'integration' }),+ plugin({ id: 'b', name: 'Countdown', type: 'widget' }),+ ])+ render(<AdminPluginsPanel />)+ await screen.findByText('Gotify')++ await pickFilter(/^Type: All types$/, /^Widget$/)++ expect(await screen.findByTitle('Type: Widget')).toBeInTheDocument()+ expect(screen.getByText('Countdown')).toBeInTheDocument()+ expect(screen.queryByText('Gotify')).not.toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-006: the status filter separates off, error and update-available rows', async () => {+ panelWith([+ plugin({ id: 'trek-gotify', name: 'OnOne', enabled: 1, status: 'active', version: '1.0.0', source_repo: 'acme/gotify' }),+ plugin({ id: 'off-one', name: 'OffOne', enabled: 0, status: 'inactive' }),+ plugin({ id: 'bad-one', name: 'BadOne', enabled: 1, status: 'error', last_error: 'boom' }),+ ], { registry: [registryEntry({ latest: '2.0.0' })] })+ render(<AdminPluginsPanel />)+ await screen.findByText('OnOne')++ await pickFilter(/^Status: All$/, /^Off$/)+ expect(await screen.findByText('OffOne')).toBeInTheDocument()+ expect(screen.queryByText('OnOne')).not.toBeInTheDocument()++ await pickFilter(/^Status: Off$/, /^Error$/)+ expect(await screen.findByText('BadOne')).toBeInTheDocument()+ expect(screen.getByText('boom')).toBeInTheDocument()++ await pickFilter(/^Status: Error$/, /^Update available$/)+ expect(await screen.findByText('OnOne')).toBeInTheDocument()+ expect(screen.queryByText('BadOne')).not.toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-007: an installed-only sort key snaps back to Name on the Discover tab', async () => {+ panelWith([plugin()], { registry: [registryEntry()] })+ render(<AdminPluginsPanel />)+ await screen.findByText('Gotify')++ await pickFilter(/^Sort: Name$/, /^Updates first$/)+ expect(await screen.findByTitle('Sort: Updates first')).toBeInTheDocument()++ await clickDiscover()+ await waitFor(() => expect(screen.getByTitle('Sort: Name')).toBeInTheDocument())+ })++ it('FE-COMP-PLUGINS-PANEL-008: rescan re-pulls the registry past its cache and confirms with a toast', async () => {+ const refreshFlags: (string | null)[] = []+ panelWith([plugin()])+ server.use(+ http.post('*/api/admin/plugins/rescan', () => HttpResponse.json({ ok: true })),+ http.get('*/api/admin/plugins/registry', ({ request }) => {+ refreshFlags.push(new URL(request.url).searchParams.get('refresh'))+ return HttpResponse.json([registryEntry({ latest: '2.0.0' })])+ }),+ )+ withToast()+ await screen.findByText('Gotify')++ fireEvent.click(screen.getAllByTitle('Rescan')[0])++ expect(await screen.findByText('Rescanned the plugins folder')).toBeInTheDocument()+ expect(refreshFlags).toContain('1')+ })+})++describe('AdminPluginsPanel — sideloading', () => {+ const zip = () => new File(['zip'], 'plugin.zip', { type: 'application/zip' })++ it('FE-COMP-PLUGINS-PANEL-009: the toolbar button opens the hidden picker and uploads the pick', async () => {+ panelWith([plugin()])+ server.use(http.post('*/api/admin/plugins/upload', () => HttpResponse.json({ id: 'trek-new' })))+ const { container } = withToast()+ await screen.findByText('Gotify')++ const input = container.querySelector('input[type="file"]') as HTMLInputElement+ const clickSpy = vi.spyOn(input, 'click').mockImplementation(() => {})+ fireEvent.click(screen.getAllByTitle('Upload plugin')[0])+ expect(clickSpy).toHaveBeenCalled()+ clickSpy.mockRestore()++ await userEvent.upload(input, zip())+ expect(await screen.findByText(/trek-new.*uploaded/i)).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-010: a rejected upload surfaces the server message', async () => {+ panelWith([plugin()])+ server.use(http.post('*/api/admin/plugins/upload', () => HttpResponse.json({ error: 'not a plugin archive' }, { status: 400 })))+ const { container } = withToast()+ await screen.findByText('Gotify')++ await userEvent.upload(container.querySelector('input[type="file"]') as HTMLInputElement, zip())++ expect(await screen.findByText('not a plugin archive')).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-011: dragging a file over the panel offers a drop target and installs it', async () => {+ let uploaded = false+ panelWith([plugin()])+ server.use(http.post('*/api/admin/plugins/upload', () => { uploaded = true; return HttpResponse.json({ id: 'trek-dropped' }) }))+ const { container } = withToast()+ await screen.findByText('Gotify')++ const panel = panelRoot(container)+ const dataTransfer = { types: ['Files'], files: [zip()] }+ fireEvent.dragEnter(panel, { dataTransfer })+ expect(await screen.findByText('Drop a plugin .zip to install')).toBeInTheDocument()++ fireEvent.dragLeave(panel, { dataTransfer })+ await waitFor(() => expect(screen.queryByText('Drop a plugin .zip to install')).not.toBeInTheDocument())++ fireEvent.dragEnter(panel, { dataTransfer })+ fireEvent.dragOver(panel, { dataTransfer })+ fireEvent.drop(panel, { dataTransfer })++ await waitFor(() => expect(uploaded).toBe(true))+ expect(await screen.findByText(/trek-dropped.*uploaded/i)).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-012: a drag that carries no files is ignored', async () => {+ panelWith([plugin()])+ const { container } = render(<AdminPluginsPanel />)+ await screen.findByText('Gotify')++ fireEvent.dragEnter(panelRoot(container), { dataTransfer: { types: ['text/plain'], files: [] } })++ expect(screen.queryByText('Drop a plugin .zip to install')).not.toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-013: the dev-link form registers a local path and reports failures', async () => {+ const paths: string[] = []+ panelWith([plugin()], { devLink: true })+ server.use(http.post('*/api/admin/plugins/link', async ({ request }) => {+ const body = await request.json() as { path: string }+ paths.push(body.path)+ return paths.length === 1+ ? HttpResponse.json({ id: 'trek-local' })+ : HttpResponse.json({ error: 'no manifest there' }, { status: 400 })+ }))+ withToast()+ const input = await screen.findByPlaceholderText('/absolute/path/to/your/plugin')++ expect(screen.getByRole('button', { name: /^link$/i })).toBeDisabled()++ fireEvent.change(input, { target: { value: '/srv/plugins/mine' } })+ fireEvent.click(screen.getByRole('button', { name: /^link$/i }))+ expect(await screen.findByText(/linked trek-local/i)).toBeInTheDocument()+ expect(paths).toEqual(['/srv/plugins/mine'])++ fireEvent.change(screen.getByPlaceholderText('/absolute/path/to/your/plugin'), { target: { value: '/nope' } })+ fireEvent.click(screen.getByRole('button', { name: /^link$/i }))+ expect(await screen.findByText('no manifest there')).toBeInTheDocument()+ })+})++describe('AdminPluginsPanel — row actions', () => {+ async function openRowMenu(p: Record<string, unknown> = plugin()) {+ panelWith([p])+ withToast()+ fireEvent.click(await screen.findByTestId(`plugin-row-menu-btn-${p.id}`))+ }++ /** Every modal in the panel closes by clicking its backdrop. */+ function closeModal() {+ fireEvent.click(document.querySelector('.fixed.inset-0.z-50') as HTMLElement)+ }++ it('FE-COMP-PLUGINS-PANEL-014: the error log lists what the runtime recorded', async () => {+ server.use(http.get('*/api/admin/plugins/trek-gotify/errors', () =>+ HttpResponse.json({ errors: [{ ts: '2026-01-01T00:00:00Z', level: 'error', message: 'connect ECONNREFUSED' }] })))+ await openRowMenu()++ fireEvent.click(screen.getByText('View error log'))+ expect(await screen.findByText('connect ECONNREFUSED')).toBeInTheDocument()+ expect(screen.getByText('error')).toBeInTheDocument()++ closeModal()+ await waitFor(() => expect(screen.queryByText('connect ECONNREFUSED')).not.toBeInTheDocument())+ })++ it('FE-COMP-PLUGINS-PANEL-015: an unreachable error log still opens, empty', async () => {+ server.use(http.get('*/api/admin/plugins/trek-gotify/errors', () => HttpResponse.error()))+ await openRowMenu()++ fireEvent.click(screen.getByText('View error log'))++ expect(await screen.findByText('No errors logged.')).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-016: allowed hosts can be added and removed, and a rejected save says why', async () => {+ let hosts: string[] = []+ let puts = 0+ server.use(+ http.get('*/api/admin/plugins/trek-gotify/egress-hosts', () => HttpResponse.json({ supported: true, hosts })),+ http.put('*/api/admin/plugins/trek-gotify/egress-hosts', async ({ request }) => {+ puts += 1+ const body = await request.json() as { hosts: string[] }+ if (puts === 3) return HttpResponse.json({ error: 'not a valid host' }, { status: 400 })+ hosts = body.hosts+ return HttpResponse.json({ hosts })+ }),+ )+ await openRowMenu()++ fireEvent.click(screen.getByText('Allowed hosts'))+ expect(await screen.findByText('No hosts added yet.')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /^add$/i })).toBeDisabled()++ fireEvent.change(screen.getByPlaceholderText('gotify.example.com'), { target: { value: 'gotify.lan' } })+ fireEvent.click(screen.getByRole('button', { name: /^add$/i }))+ expect(await screen.findByText('gotify.lan')).toBeInTheDocument()++ fireEvent.click(screen.getAllByLabelText('Delete')[0])+ await waitFor(() => expect(screen.getByText('No hosts added yet.')).toBeInTheDocument())++ fireEvent.change(screen.getByPlaceholderText('gotify.example.com'), { target: { value: 'bad host' } })+ fireEvent.click(screen.getByRole('button', { name: /^add$/i }))+ expect(await screen.findByText('not a valid host')).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-017: a plugin whose hosts are fixed in its manifest says the list is unsupported', async () => {+ server.use(http.get('*/api/admin/plugins/trek-gotify/egress-hosts', () => HttpResponse.error()))+ await openRowMenu()++ fireEvent.click(screen.getByText('Allowed hosts'))++ expect(await screen.findByText(/does not use operator-supplied hosts/i)).toBeInTheDocument()+ expect(screen.queryByPlaceholderText('gotify.example.com')).not.toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-018: Delete asks first, then uninstalls with its data', async () => {+ let body: unknown = null+ server.use(http.post('*/api/admin/plugins/trek-gotify/uninstall', async ({ request }) => {+ body = await request.json()+ return HttpResponse.json({ ok: true })+ }))+ await openRowMenu()++ fireEvent.click(screen.getByText('Delete'))+ expect(await screen.findByText('Uninstall plugin?')).toBeInTheDocument()++ fireEvent.click(screen.getAllByRole('button', { name: /^delete$/i }).pop()!)++ expect(await screen.findByText('Plugin uninstalled')).toBeInTheDocument()+ expect(body).toEqual({ deleteData: true })+ })++ it('FE-COMP-PLUGINS-PANEL-019: Restart cycles the plugin off and on again', async () => {+ const seen: string[] = []+ server.use(+ http.post('*/api/admin/plugins/trek-gotify/deactivate', () => { seen.push('deactivate'); return HttpResponse.json({ ok: true }) }),+ http.post('*/api/admin/plugins/trek-gotify/activate', () => { seen.push('activate'); return HttpResponse.json({ ok: true }) }),+ )+ await openRowMenu(plugin({ enabled: 1, status: 'active' }))++ fireEvent.click(screen.getByText('Restart'))++ expect(await screen.findByText('Plugin restarted')).toBeInTheDocument()+ expect(seen).toEqual(['deactivate', 'activate'])+ })++ it('FE-COMP-PLUGINS-PANEL-020: a disabled plugin offers no Restart', async () => {+ await openRowMenu(plugin({ enabled: 0, status: 'inactive' }))++ expect(screen.getByText('View error log')).toBeInTheDocument()+ expect(screen.queryByText('Restart')).not.toBeInTheDocument()+ })+})++describe('AdminPluginsPanel — enabling a plugin', () => {+ it('FE-COMP-PLUGINS-PANEL-021: turning a plugin off deactivates it', async () => {+ let called = false+ panelWith([plugin({ enabled: 1, status: 'active' })])+ server.use(http.post('*/api/admin/plugins/trek-gotify/deactivate', () => { called = true; return HttpResponse.json({ ok: true }) }))+ withToast()+ await screen.findByText('Gotify')++ fireEvent.click(rowToggle('Gotify'))++ expect(await screen.findByText('Plugin deactivated')).toBeInTheDocument()+ expect(called).toBe(true)+ })++ it('FE-COMP-PLUGINS-PANEL-022: turning one on also reports the dependencies it enabled first', async () => {+ panelWith([+ plugin({ enabled: 0, status: 'inactive', dependencies: { pluginDependencies: [{ id: 'trek-core', version: '^1.0.0' }] } }),+ plugin({ id: 'trek-core', name: 'Core', enabled: 0, status: 'inactive' }),+ ])+ server.use(http.post('*/api/admin/plugins/trek-gotify/activate', () => HttpResponse.json({ ok: true })))+ withToast()+ await screen.findByText('Gotify')++ fireEvent.click(rowToggle('Gotify'))++ expect(await screen.findByText('Plugin activated')).toBeInTheDocument()+ expect(await screen.findByText(/enabled required plugin\(s\) first: core/i)).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-023: a disabled required addon is reported as a toast, not a dialog', async () => {+ panelWith([plugin({ enabled: 0, status: 'inactive' })])+ server.use(http.post('*/api/admin/plugins/trek-gotify/activate', () =>+ HttpResponse.json({ code: 'ADDON_DISABLED', addons: ['journey'] }, { status: 409 })))+ withToast()+ await screen.findByText('Gotify')++ fireEvent.click(rowToggle('Gotify'))++ expect(await screen.findByText(/enable the required addon\(s\) first: journey/i)).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-024: any other activation failure surfaces the server message', async () => {+ panelWith([plugin({ enabled: 0, status: 'inactive' })])+ server.use(http.post('*/api/admin/plugins/trek-gotify/activate', () =>+ HttpResponse.json({ code: 'DEPENDENCY_CYCLE', error: 'circular dependency' }, { status: 409 })))+ withToast()+ await screen.findByText('Gotify')++ fireEvent.click(rowToggle('Gotify'))++ expect(await screen.findByText('circular dependency')).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-025: a missing dependency opens the resolve dialog and one click fixes it', async () => {+ let activates = 0+ let installed: unknown = null+ panelWith([plugin({ enabled: 0, status: 'inactive' })])+ server.use(+ http.post('*/api/admin/plugins/trek-gotify/activate', () => {+ activates += 1+ return activates === 1+ ? HttpResponse.json({+ code: 'DEPENDENCY_MISSING',+ missing: [{ id: 'trek-core', version: '^1.0.0' }],+ versionMismatch: [{ id: 'trek-old', wanted: '^2.0.0', installed: '1.0.0' }],+ }, { status: 409 })+ : HttpResponse.json({ ok: true })+ }),+ http.post('*/api/admin/plugins/install', async ({ request }) => {+ installed = await request.json()+ return HttpResponse.json({ installed: ['trek-core'], requiredAddons: ['journey'] })+ }),+ )+ withToast()+ await screen.findByText('Gotify')++ fireEvent.click(rowToggle('Gotify'))+ expect(await screen.findByText('Missing dependencies')).toBeInTheDocument()+ expect(screen.getByText('Requires ^1.0.0')).toBeInTheDocument()+ expect(screen.getByText('Needs ^2.0.0 — 1.0.0 is installed')).toBeInTheDocument()+ expect(screen.getByText(/downloads the latest compatible version/i)).toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: /^download$/i }))++ expect(await screen.findByText('Downloaded trek-core')).toBeInTheDocument()+ expect(installed).toEqual({ id: 'trek-core', constraint: '^1.0.0', withDependencies: true })+ expect(await screen.findByText(/enable the required addon\(s\) first: journey/i)).toBeInTheDocument()+ await waitFor(() => expect(screen.queryByText('Missing dependencies')).not.toBeInTheDocument())+ })++ it('FE-COMP-PLUGINS-PANEL-026: the resolve dialog can be dismissed without downloading anything', async () => {+ let installs = 0+ panelWith([plugin({ enabled: 0, status: 'inactive' })])+ server.use(+ http.post('*/api/admin/plugins/trek-gotify/activate', () =>+ HttpResponse.json({ code: 'DEPENDENCY_MISSING', missing: [{ id: 'trek-core', version: '^1.0.0' }], versionMismatch: [] }, { status: 409 })),+ http.post('*/api/admin/plugins/install', () => { installs += 1; return HttpResponse.json({}) }),+ )+ withToast()+ await screen.findByText('Gotify')++ fireEvent.click(rowToggle('Gotify'))+ fireEvent.click(await screen.findByRole('button', { name: /^cancel$/i }))++ await waitFor(() => expect(screen.queryByText('Missing dependencies')).not.toBeInTheDocument())+ expect(installs).toBe(0)+ })++ it('FE-COMP-PLUGINS-PANEL-027: widened permissions route to the consent dialog, which can be deferred', async () => {+ panelWith([plugin({ enabled: 0, status: 'inactive', source_repo: 'acme/gotify', signed: false })])+ server.use(http.post('*/api/admin/plugins/trek-gotify/activate', () =>+ HttpResponse.json({ code: 'CONSENT_REQUIRED', newPermissions: ['db:read:trips', 'weird:perm'], newEgress: ['api.acme.io'] }, { status: 409 })))+ withToast()+ await screen.findByText('Gotify')++ fireEvent.click(rowToggle('Gotify'))++ expect(await screen.findByText('This update needs new permissions')).toBeInTheDocument()+ expect(screen.getByText('Read trips the acting user can access')).toBeInTheDocument()+ // An unknown permission is still shown — as its raw code+ expect(screen.getByText('weird:perm')).toBeInTheDocument()+ expect(screen.getByText('api.acme.io')).toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: /keep off for now/i }))+ expect(await screen.findByText(/left off until you approve/i)).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-028: approving consent re-activates with the consent flag', async () => {+ const bodies: unknown[] = []+ panelWith([plugin({ enabled: 0, status: 'inactive' })])+ server.use(http.post('*/api/admin/plugins/trek-gotify/activate', async ({ request }) => {+ bodies.push(await request.json())+ return bodies.length === 1+ ? HttpResponse.json({ code: 'CONSENT_REQUIRED', newPermissions: ['db:read:trips'], newEgress: [] }, { status: 409 })+ : HttpResponse.json({ ok: true })+ }))+ withToast()+ await screen.findByText('Gotify')++ fireEvent.click(rowToggle('Gotify'))+ fireEvent.click(await screen.findByRole('button', { name: /approve & turn on/i }))++ expect(await screen.findByText('Plugin updated')).toBeInTheDocument()+ expect(bodies[1]).toEqual({ consent: true })+ })+})++describe('AdminPluginsPanel — updates', () => {+ const outdated = plugin({ source_repo: 'acme/gotify', version: '1.0.0', operatorEgress: false })++ it('FE-COMP-PLUGINS-PANEL-029: the update banner updates every outdated plugin at once', async () => {+ const updated: string[] = []+ panelWith(+ [outdated, plugin({ id: 'trek-ntfy', name: 'Ntfy', source_repo: 'acme/ntfy', version: '1.0.0', operatorEgress: false })],+ { registry: [registryEntry({ latest: '2.0.0' }), registryEntry({ id: 'trek-ntfy', latest: '3.0.0' })] },+ )+ server.use(http.post('*/api/admin/plugins/:id/update', ({ params }) => {+ updated.push(String(params.id))+ return HttpResponse.json({ version: '2.0.0', activated: true, newPermissions: [], newEgress: [] })+ }))+ withToast()++ expect(await screen.findByText('2 updates available for your plugins.')).toBeInTheDocument()+ fireEvent.click(screen.getByRole('button', { name: /update all/i }))++ await waitFor(() => expect([...updated].sort()).toEqual(['trek-gotify', 'trek-ntfy']))+ expect((await screen.findAllByText('Plugin updated')).length).toBeGreaterThan(0)+ })++ it('FE-COMP-PLUGINS-PANEL-030: an update that widens permissions queues the consent dialog', async () => {+ panelWith([outdated], { registry: [registryEntry({ latest: '2.0.0', signed: false })] })+ server.use(http.post('*/api/admin/plugins/trek-gotify/update', () =>+ HttpResponse.json({ version: '2.0.0', activated: false, newPermissions: ['db:read:users'], newEgress: [] })))+ withToast()++ fireEvent.click(await screen.findByRole('button', { name: /update → v2\.0\.0/i }))++ expect(await screen.findByText('This update needs new permissions')).toBeInTheDocument()+ expect(screen.getByText(/read basic profile info/i)).toBeInTheDocument()+ // The registry says the new code is unsigned — say so where the rights get widened+ expect(screen.getByText(/nothing ties this version to its author/i)).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-031: a failed update that is not a signature refusal is a plain toast', async () => {+ panelWith([outdated], { registry: [registryEntry({ latest: '2.0.0' })] })+ server.use(http.post('*/api/admin/plugins/trek-gotify/update', () =>+ HttpResponse.json({ error: 'registry unreachable' }, { status: 502 })))+ withToast()++ fireEvent.click(await screen.findByRole('button', { name: /update → v2\.0\.0/i }))++ expect(await screen.findByText('registry unreachable')).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-032: a re-trusted update that widens rights still asks for consent', async () => {+ panelWith([plugin({+ source_repo: 'acme/gotify', version: '1.0.0', keyFingerprint: 'OLDAAAAA…BBBBBBBB', operatorEgress: false,+ updateBlock: { code: 'SIGNATURE_KEY_CHANGED', version: '2.0.0', detail: 'key rotated' },+ })], { registry: [registryEntry({ latest: '2.0.0' })] })+ server.use(http.post('*/api/admin/plugins/trek-gotify/retrust', () =>+ HttpResponse.json({ version: '2.0.0', activated: false, newPermissions: ['db:read:trips'], newEgress: ['api.acme.io'] })))+ withToast()++ fireEvent.click(await screen.findByRole('button', { name: /^review$/i }))+ fireEvent.click(await screen.findByRole('button', { name: /trust the new key/i }))++ expect(await screen.findByText('This update needs new permissions')).toBeInTheDocument()+ expect(screen.getByText('api.acme.io')).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-033: a failed re-trust surfaces the server message', async () => {+ panelWith([plugin({+ source_repo: 'acme/gotify', version: '1.0.0', keyFingerprint: 'OLDAAAAA…BBBBBBBB', operatorEgress: false,+ updateBlock: { code: 'SIGNATURE_KEY_CHANGED', version: '2.0.0', detail: 'key rotated' },+ })], { registry: [registryEntry({ latest: '2.0.0' })] })+ server.use(http.post('*/api/admin/plugins/trek-gotify/retrust', () =>+ HttpResponse.json({ error: 'key does not match' }, { status: 400 })))+ withToast()++ fireEvent.click(await screen.findByRole('button', { name: /^review$/i }))+ fireEvent.click(await screen.findByRole('button', { name: /trust the new key/i }))++ expect(await screen.findByText('key does not match')).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-034a: a stable release counts as newer than the prerelease of the same version', async () => {+ panelWith([plugin({ source_repo: 'acme/gotify', version: '2.0.0-beta.1', operatorEgress: false })], {+ registry: [registryEntry({ latest: '2.0.0' })],+ })+ render(<AdminPluginsPanel />)++ expect(await screen.findByRole('button', { name: /update → v2\.0\.0/i })).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-034: a block with no recorded version stands while the registry is silent', async () => {+ panelWith([plugin({+ source_repo: 'acme/gotify', operatorEgress: false,+ updateBlock: { code: 'SIGNATURE_INVALID', version: null, detail: 'digest mismatch' },+ })], { registry: [] })+ render(<AdminPluginsPanel />)++ expect(await screen.findByText(/update blocked — digest mismatch/i)).toBeInTheDocument()+ })+})++describe('AdminPluginsPanel — capability and dependency chips', () => {+ it('FE-COMP-PLUGINS-PANEL-035: a permission-rich plugin renders one chip per capability', async () => {+ panelWith([plugin({+ operatorEgress: false,+ permissions: JSON.stringify([+ 'db:read:trips', 'db:read:users', 'db:write:costs', 'db:read:packing', 'db:read:files',+ 'db:write:places', 'db:write:days', 'db:write:itinerary', 'db:write:trips', 'db:meta',+ 'ws:broadcast:trip', 'hook:photo-provider', 'hook:calendar-source', 'hook:place-detail-provider',+ 'hook:trip-warning-provider', 'hook:map-layer-provider', 'hook:route-provider',+ 'hook:day-schedule-provider', 'geolocation:read', 'events:subscribe', 'http:outbound:api.acme.io',+ ]),+ capabilities: JSON.stringify({ widget: { slot: 'hero' }, tripPage: { replaces: ['places'] } }),+ })])+ render(<AdminPluginsPanel />)+ await screen.findByText('Gotify')++ for (const label of [+ 'Reads your trips', 'Reads basic profiles', 'Adds costs', 'Reads packing lists', 'Reads trip files',+ 'Edits places', 'Edits days', 'Edits itinerary', 'Edits trips', 'Adds metadata',+ 'Boarding-pass widget', 'Replaces planner tabs', 'Real-time updates', 'Provides photos',+ 'Provides calendar events', 'Enriches places', 'Flags issues', 'Draws on the map', 'Offers routing',+ 'Adds plan times', 'Reads your position', 'Reacts to activity', 'api.acme.io',+ ]) {+ expect(screen.getByText(label)).toBeInTheDocument()+ }+ })++ it('FE-COMP-PLUGINS-PANEL-036: read-only costs and a slotted widget each get their own wording', async () => {+ panelWith([plugin({+ operatorEgress: false,+ permissions: JSON.stringify(['db:read:costs']),+ capabilities: JSON.stringify({ widget: { slot: 'place-detail' } }),+ })])+ render(<AdminPluginsPanel />)+ await screen.findByText('Gotify')++ expect(screen.getByText('Reads your costs')).toBeInTheDocument()+ expect(screen.getByText('Place detail')).toBeInTheDocument()+ expect(screen.queryByText('Adds costs')).not.toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-037: an unparseable capabilities blob degrades to the plain widget chip', async () => {+ panelWith([plugin({ operatorEgress: false, permissions: 'not json', capabilities: JSON.stringify({ widget: {} }) })])+ render(<AdminPluginsPanel />)+ await screen.findByText('Gotify')++ expect(screen.getByText('Dashboard widget')).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-038: dependency chips flag the addon and plugin the row is waiting on', async () => {+ panelWith([plugin({+ operatorEgress: false,+ dependencies: { requiredAddons: ['journey'], pluginDependencies: [{ id: 'trek-core', version: '^1.0.0' }] },+ dependencyIssues: { disabledAddons: ['journey'], missing: [{ id: 'trek-core', version: '^1.0.0' }], versionMismatch: [] },+ })])+ render(<AdminPluginsPanel />)++ expect(await screen.findByText('Requires journey')).toBeInTheDocument()+ expect(screen.getByText('Needs trek-core ^1.0.0')).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-039: a plugin that names no TREK range says so', async () => {+ panelWith([plugin({ operatorEgress: false, dependencyStatus: 'hostIncompatible' })])+ render(<AdminPluginsPanel />)++ expect(await screen.findByText('Does not say which TREK versions it supports')).toBeInTheDocument()+ })+})++describe('AdminPluginsPanel — Discover cards and the detail modal', () => {+ function discoverWith(entry: Record<string, unknown>, detail?: Record<string, unknown>) {+ server.use(+ http.get('*/api/admin/plugins', () => HttpResponse.json({ enabled: true, devLink: false, plugins: [] })),+ http.get('*/api/admin/plugins/registry', () => HttpResponse.json([registryEntry(entry)])),+ http.get('*/api/admin/plugins/registry/trek-gotify', () =>+ detail ? HttpResponse.json(detail) : HttpResponse.json({ error: 'gone' }, { status: 404 })),+ )+ }++ function manifestDetail(over: Record<string, unknown> = {}, manifest: Record<string, unknown> = {}) {+ return {+ id: 'trek-gotify', name: 'Gotify', author: 'Acme', description: 'Push', repo: 'acme/gotify',+ type: 'integration', tags: [], size: 4096, publishedAt: null, latest: '2.0.0',+ manifest: { permissions: [], egress: [], settings: [], license: 'MIT', icon: null, operatorEgress: false, ...manifest },+ ...over,+ }+ }++ it('FE-COMP-PLUGINS-PANEL-040: a card shows its compact download count and falls back on a broken shot', async () => {+ discoverWith({ downloadCount: 1234, screenshotUrl: 'https://example.com/shot.png', reviewedAt: '2026-01-05T00:00:00Z' })+ const { container } = render(<AdminPluginsPanel />)+ await clickDiscover()++ expect(await screen.findByText('1.2k')).toBeInTheDocument()+ const img = container.querySelector('img') as HTMLImageElement+ expect(screen.getByText('Reviewed')).toBeInTheDocument()+ expect(img).toBeInTheDocument()+ fireEvent.error(img)+ await waitFor(() => expect(container.querySelector('img')).not.toBeInTheDocument())+ })++ it('FE-COMP-PLUGINS-PANEL-040a: a two-digit download count is printed verbatim', async () => {+ discoverWith({ downloadCount: 42 })+ render(<AdminPluginsPanel />)+ await clickDiscover()++ expect(await screen.findByText('42')).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-041: opening a card by keyboard shows the modal, and a failed lookup says so', async () => {+ discoverWith({})+ render(<AdminPluginsPanel />)+ await clickDiscover()++ const card = (await screen.findByText('Gotify')).closest('[role="button"]') as HTMLElement+ fireEvent.keyDown(card, { key: 'Enter' })++ expect(await screen.findByText('Could not load plugin details.')).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-042: the detail modal lists setup fields, metadata and a separate homepage', async () => {+ discoverWith(+ { downloadCount: 999_500, reviewedAt: '2026-01-05T00:00:00Z', homepage: 'https://gotify.example', trek: '>=3.2.0' },+ manifestDetail({}, {+ permissions: ['db:own'],+ settings: [{ key: 'url', label: 'Server URL', scope: 'instance', required: true }],+ }),+ )+ render(<AdminPluginsPanel />)+ await clickDiscover()+ fireEvent.click(await screen.findByText('Gotify'))++ expect(await screen.findByText('Server URL')).toBeInTheDocument()+ expect(screen.getByText('Instance-wide')).toBeInTheDocument()+ expect(screen.getByText('Required')).toBeInTheDocument()+ expect(screen.getByText('4 KB')).toBeInTheDocument()+ expect(screen.getByText('TREK >=3.2.0')).toBeInTheDocument()+ expect(screen.getByText('Store its own data in an isolated database')).toBeInTheDocument()+ expect(screen.getByRole('link', { name: /homepage/i })).toHaveAttribute('href', 'https://gotify.example')+ // 999 500 rounds to a whole megabyte on the card, never "1000k"+ expect(screen.getByText('1M')).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-043: a manifest with no readable access says exactly that', async () => {+ discoverWith({ minTrekVersion: '3.2.0' }, manifestDetail({ size: 0 }))+ render(<AdminPluginsPanel />)+ await clickDiscover()+ fireEvent.click(await screen.findByText('Gotify'))++ expect(await screen.findByText('Needs no special access.')).toBeInTheDocument()+ expect(screen.getByText('TREK 3.2.0+')).toBeInTheDocument()+ expect(screen.queryByText('Connects to')).not.toBeInTheDocument()+ expect(screen.queryByText('Setup')).not.toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-044: an incompatible entry explains the blocked button in the modal body', async () => {+ discoverWith({ compatible: false, latestCompatible: null, trek: '>=4.0.0', hostVersion: '3.3.0' })+ render(<AdminPluginsPanel />)+ await clickDiscover()+ fireEvent.click(await screen.findByText('Gotify'))++ const explanations = await screen.findAllByText(/needs trek >=4\.0\.0 — this server runs 3\.3\.0/i)+ expect(explanations.length).toBeGreaterThan(0)+ })++ it('FE-COMP-PLUGINS-PANEL-045: searching Discover with no hit says the registry has no match', async () => {+ discoverWith({})+ render(<AdminPluginsPanel />)+ await clickDiscover()+ await screen.findByText('Gotify')++ fireEvent.change(screen.getByPlaceholderText('Search plugins…'), { target: { value: 'nothing' } })++ expect(screen.getByText('No plugins in the registry match your search.')).toBeInTheDocument()+ })++ it('FE-COMP-PLUGINS-PANEL-046: installing from a card posts the offered version', async () => {+ let body: unknown = null+ discoverWith({ compatible: false, latestCompatible: '1.5.0', trek: '>=4.0.0', hostVersion: '3.3.0' })+ server.use(http.post('*/api/admin/plugins/install', async ({ request }) => {+ body = await request.json()+ return HttpResponse.json({ ok: true })+ }))+ withToast()+ await clickDiscover()++ fireEvent.click(await screen.findByRole('button', { name: /^install 1\.5\.0$/i }))++ await waitFor(() => expect(body).toEqual({ id: 'trek-gotify', version: '1.5.0' }))+ })++ it('FE-COMP-PLUGINS-PANEL-047: an unreachable registry leaves Discover empty rather than spinning', async () => {+ server.use(+ http.get('*/api/admin/plugins', () => HttpResponse.json({ enabled: true, devLink: false, plugins: [] })),+ http.get('*/api/admin/plugins/registry', () => HttpResponse.error()),+ )+ render(<AdminPluginsPanel />)+ await screen.findByText('No plugins installed yet.')++ await clickDiscover()++ expect(await screen.findByText('No plugins available in the registry yet.')).toBeInTheDocument()+ })+})++describe('AdminPluginsPanel — security footer', () => {+ it('FE-COMP-PLUGINS-PANEL-048: the containment note expands into its sections', async () => {+ panelWith([])+ render(<AdminPluginsPanel />)+ await screen.findByText('No plugins installed yet.')++ expect(screen.queryByText('Every plugin runs boxed in')).not.toBeInTheDocument()+ fireEvent.click(screen.getByText('How plugins are contained — and the limits'))++ expect(screen.getByText('Every plugin runs boxed in')).toBeInTheDocument()+ expect(screen.getByText('What "Reviewed" means')).toBeInTheDocument()+ expect(screen.getByText('What "Signed" means')).toBeInTheDocument()+ })+})diff --git a/client/src/components/Admin/BackupPanel.test.tsx b/client/src/components/Admin/BackupPanel.test.tsxindex 210117959..77f4b7dca 100644--- a/client/src/components/Admin/BackupPanel.test.tsx+++ b/client/src/components/Admin/BackupPanel.test.tsx@@ -310,4 +310,292 @@ describe('BackupPanel', () => {expect(screen.getByRole('button', { name: /^save$/i })).not.toBeDisabled()})})++ // BKP-015: List request fails+ it('FE-ADMIN-BKP-015: a failing list request toasts and keeps the empty state', async () => {+ server.use(http.get('/api/backup/list', () => HttpResponse.error()))+ render(<><ToastContainer /><BackupPanel /></>)++ expect(await screen.findByText('Failed to load backups')).toBeInTheDocument()+ expect(screen.getByText('No backups yet')).toBeInTheDocument()+ })++ // BKP-016: Create fails+ it('FE-ADMIN-BKP-016: a failing create toasts the error and re-enables the button', async () => {+ const user = userEvent.setup()+ server.use(http.post('/api/backup/create', () => HttpResponse.error()))+ render(<><ToastContainer /><BackupPanel /></>)+ await screen.findByText('backup-2025-01-15.zip')++ await user.click(screen.getByTitle('Create Backup'))++ expect(await screen.findByText('Failed to create backup')).toBeInTheDocument()+ await waitFor(() => expect(screen.getByTitle('Create Backup')).toBeEnabled())+ })++ // BKP-017: Restore fails+ it('FE-ADMIN-BKP-017: a failing restore surfaces the server message and clears the spinner', async () => {+ const user = userEvent.setup()+ server.use(+ http.post('/api/backup/restore/:filename', () =>+ HttpResponse.json({ error: 'archive is corrupt' }, { status: 400 }),+ ),+ )+ render(<><ToastContainer /><BackupPanel /></>)+ await screen.findByText('backup-2025-01-15.zip')++ await user.click(screen.getAllByText('Restore')[0])+ await user.click(await screen.findByText('Yes, restore'))++ expect(await screen.findByText('archive is corrupt')).toBeInTheDocument()+ await waitFor(() => expect(screen.getAllByText('Restore')[0].closest('button')).toBeEnabled())+ })++ // BKP-018: Upload & restore happy path+ it('FE-ADMIN-BKP-018: picking a file opens the modal and uploads it on confirm', async () => {+ const user = userEvent.setup()+ let uploaded = false+ server.use(+ http.post('/api/backup/upload-restore', () => {+ uploaded = true+ return HttpResponse.json({ success: true })+ }),+ )+ render(<><ToastContainer /><BackupPanel /></>)+ await screen.findByText('backup-2025-01-15.zip')++ const reloadMock = vi.fn()+ vi.stubGlobal('location', { ...window.location, reload: reloadMock })++ const input = document.querySelector('input[type="file"]') as HTMLInputElement+ await user.upload(input, new File(['zip'], 'restore-me.zip', { type: 'application/zip' }))++ expect(await screen.findByText('Restore Backup?')).toBeInTheDocument()+ expect(screen.getByText('restore-me.zip')).toBeInTheDocument()+ // The picked file is cleared from the input so the same file can be chosen again+ expect(input.value).toBe('')++ await user.click(screen.getByText('Yes, restore'))+ await waitFor(() => expect(uploaded).toBe(true))+ expect(await screen.findByText('Backup restored. Page will reload…')).toBeInTheDocument()+ vi.unstubAllGlobals()+ })++ // BKP-019: Upload & restore failure+ it('FE-ADMIN-BKP-019: a failing upload restore toasts and re-enables the upload button', async () => {+ const user = userEvent.setup()+ server.use(+ http.post('/api/backup/upload-restore', () => HttpResponse.json({ error: 'not a backup' }, { status: 400 })),+ )+ render(<><ToastContainer /><BackupPanel /></>)+ await screen.findByText('backup-2025-01-15.zip')++ const input = document.querySelector('input[type="file"]') as HTMLInputElement+ await user.upload(input, new File(['zip'], 'broken.zip', { type: 'application/zip' }))+ await user.click(await screen.findByText('Yes, restore'))++ expect(await screen.findByText('not a backup')).toBeInTheDocument()+ await waitFor(() => expect(screen.getByTitle('Upload Backup')).toBeEnabled())+ })++ // BKP-020: Upload button forwards the click to the hidden file input+ it('FE-ADMIN-BKP-020: the Upload button opens the hidden file picker', async () => {+ const user = userEvent.setup()+ render(<BackupPanel />)+ await screen.findByText('backup-2025-01-15.zip')++ const input = document.querySelector('input[type="file"]') as HTMLInputElement+ const clickSpy = vi.spyOn(input, 'click').mockImplementation(() => {})+ await user.click(screen.getByTitle('Upload Backup'))++ expect(clickSpy).toHaveBeenCalled()+ })++ // BKP-021: Delete declined / failing+ it('FE-ADMIN-BKP-021: declining the confirm keeps the backup, a failing delete toasts', async () => {+ const user = userEvent.setup()+ let deleteCalls = 0+ server.use(+ http.delete('/api/backup/:filename', () => {+ deleteCalls += 1+ return HttpResponse.json({ error: 'file is locked' }, { status: 500 })+ }),+ )+ const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false)+ render(<><ToastContainer /><BackupPanel /></>)+ await screen.findByText('backup-2025-01-15.zip')++ const trashBtn = Array.from(document.querySelectorAll('button')).find(+ b => b.querySelector('svg.lucide-trash2'),+ ) as HTMLElement+ await user.click(trashBtn)+ expect(deleteCalls).toBe(0)+ expect(screen.getByText('backup-2025-01-15.zip')).toBeInTheDocument()++ confirmSpy.mockReturnValue(true)+ await user.click(trashBtn)++ expect(await screen.findByText('Failed to delete')).toBeInTheDocument()+ expect(screen.getByText('backup-2025-01-15.zip')).toBeInTheDocument()+ })++ // BKP-022: Auto settings save fails+ it('FE-ADMIN-BKP-022: a failing auto-settings save toasts and keeps the form dirty', async () => {+ const user = userEvent.setup()+ server.use(http.put('/api/backup/auto-settings', () => HttpResponse.error()))+ render(<><ToastContainer /><BackupPanel /></>)+ await screen.findByText('Enable auto-backup')++ await user.click(getToggleButton())+ await user.click(screen.getByRole('button', { name: /^save$/i }))++ expect(await screen.findByText('Failed to save settings')).toBeInTheDocument()+ await waitFor(() => expect(screen.getByRole('button', { name: /^save$/i })).toBeEnabled())+ })++ // BKP-023: Size/date fallbacks+ it('FE-ADMIN-BKP-023: missing size and date render as a dash, kilobytes are formatted', async () => {+ server.use(+ http.get('/api/backup/list', () =>+ HttpResponse.json({+ backups: [+ { filename: 'empty.zip', created_at: null, size: 0 },+ { filename: 'small.zip', created_at: '2025-03-01T08:00:00Z', size: 5120 },+ ],+ }),+ ),+ )+ render(<BackupPanel />)+ await screen.findByText('empty.zip')++ expect(screen.getAllByText('-')).toHaveLength(2)+ expect(screen.getByText('5.0 KB')).toBeInTheDocument()+ })++ // BKP-024: Invalid server timezone+ it('FE-ADMIN-BKP-024: an unusable server timezone falls back to the raw timestamp', async () => {+ server.use(+ http.get('/api/backup/auto-settings', () =>+ HttpResponse.json({+ settings: { enabled: false, interval: 'daily', keep_days: 7, hour: 2, day_of_week: 0, day_of_month: 1 },+ timezone: 'Not/AZone',+ }),+ ),+ )+ render(<BackupPanel />)+ await screen.findByText('backup-2025-01-15.zip')++ await waitFor(() => expect(screen.getByText('2025-01-15T10:00:00Z')).toBeInTheDocument())+ })++ // BKP-025: 12h hour picker+ it('FE-ADMIN-BKP-025: the hour picker uses AM/PM labels for 12h users and stores the pick', async () => {+ const user = userEvent.setup()+ seedStore(useSettingsStore, { settings: { time_format: '12h' } } as any)+ let saved: Record<string, unknown> | null = null+ server.use(+ http.get('/api/backup/auto-settings', () =>+ HttpResponse.json({+ settings: { enabled: true, interval: 'daily', keep_days: 7, hour: 0, day_of_week: 0, day_of_month: 1 },+ timezone: 'UTC',+ }),+ ),+ http.put('/api/backup/auto-settings', async ({ request }) => {+ saved = await request.json() as Record<string, unknown>+ return HttpResponse.json({ settings: saved })+ }),+ )+ render(<><ToastContainer /><BackupPanel /></>)+ await screen.findByText('Run at hour')++ expect(screen.getByText('Server local time (12h format) (Timezone: UTC)')).toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: '12:00 AM' }))+ await user.click(await screen.findByRole('button', { name: '2:00 PM' }))+ await user.click(screen.getByRole('button', { name: /^save$/i }))++ await waitFor(() => expect(saved).toMatchObject({ hour: 14 }))+ })++ // BKP-026: Monthly interval+ it('FE-ADMIN-BKP-026: the monthly interval offers a day-of-month picker', async () => {+ const user = userEvent.setup()+ let saved: Record<string, unknown> | null = null+ server.use(+ http.get('/api/backup/auto-settings', () =>+ HttpResponse.json({+ settings: { enabled: true, interval: 'monthly', keep_days: 7, hour: 2, day_of_week: 0, day_of_month: 1 },+ timezone: '',+ }),+ ),+ http.put('/api/backup/auto-settings', async ({ request }) => {+ saved = await request.json() as Record<string, unknown>+ return HttpResponse.json({ settings: saved })+ }),+ )+ render(<><ToastContainer /><BackupPanel /></>)+ await screen.findByText('Day of month')++ // No timezone from the server → the hint carries no timezone suffix+ expect(screen.getByText('Server local time (24h format)')).toBeInTheDocument()+ expect(screen.queryByText('Sun')).not.toBeInTheDocument()++ await user.click(screen.getByRole('button', { name: '1' }))+ await user.click(await screen.findByRole('button', { name: '15' }))+ await user.click(screen.getByRole('button', { name: /^save$/i }))++ await waitFor(() => expect(saved).toMatchObject({ day_of_month: 15 }))+ })++ // BKP-027: Day of week + retention+ it('FE-ADMIN-BKP-027: day-of-week and retention picks are stored together', async () => {+ const user = userEvent.setup()+ let saved: Record<string, unknown> | null = null+ server.use(+ http.get('/api/backup/auto-settings', () =>+ HttpResponse.json({+ settings: { enabled: true, interval: 'weekly', keep_days: 7, hour: 2, day_of_week: 0, day_of_month: 1 },+ timezone: 'UTC',+ }),+ ),+ http.put('/api/backup/auto-settings', async ({ request }) => {+ saved = await request.json() as Record<string, unknown>+ return HttpResponse.json({ settings: saved })+ }),+ )+ render(<><ToastContainer /><BackupPanel /></>)+ await screen.findByText('Day of week')++ await user.click(screen.getByText('Fri'))+ await user.click(screen.getByText('Keep forever'))+ await user.click(screen.getByRole('button', { name: /^save$/i }))++ await waitFor(() => expect(saved).toMatchObject({ day_of_week: 5, keep_days: 0 }))+ })++ // BKP-028: Download failure+ it('FE-ADMIN-BKP-028: a failing download toasts the download error', async () => {+ const user = userEvent.setup()+ server.use(http.get('/api/backup/download/:filename', () => HttpResponse.error()))+ render(<><ToastContainer /><BackupPanel /></>)+ await screen.findByText('backup-2025-01-15.zip')++ await user.click(screen.getByText('Download'))++ expect(await screen.findByText('Download failed')).toBeInTheDocument()+ })++ // BKP-029: Confirm button hover styling+ it('FE-ADMIN-BKP-029: the destructive confirm button darkens on hover', async () => {+ const user = userEvent.setup()+ render(<BackupPanel />)+ await screen.findByText('backup-2025-01-15.zip')++ await user.click(screen.getAllByText('Restore')[0])+ const confirmBtn = await screen.findByText('Yes, restore')++ fireEvent.mouseEnter(confirmBtn)+ expect(confirmBtn.style.background).toBe('rgb(185, 28, 28)')+ fireEvent.mouseLeave(confirmBtn)+ expect(confirmBtn.style.background).toBe('rgb(220, 38, 38)')+ })})diff --git a/client/src/components/Admin/CategoryManager.test.tsx b/client/src/components/Admin/CategoryManager.test.tsxindex 5145d468f..d3e5173cb 100644--- a/client/src/components/Admin/CategoryManager.test.tsx+++ b/client/src/components/Admin/CategoryManager.test.tsx@@ -1,5 +1,5 @@-// FE-COMP-CAT-001 to FE-COMP-CAT-012-import { render, screen, waitFor } from '../../../tests/helpers/render';+// FE-COMP-CAT-001 to FE-COMP-CAT-020+import { render, screen, waitFor, fireEvent, within } from '../../../tests/helpers/render';import userEvent from '@testing-library/user-event';import { http, HttpResponse } from 'msw';import { server } from '../../../tests/helpers/msw/server';@@ -156,4 +156,148 @@ describe('CategoryManager', () => {await user.click(screen.getByText('Cancel'));expect(screen.queryByPlaceholderText('Category name')).not.toBeInTheDocument();});++ it('FE-COMP-CAT-013: a failing list request toasts and falls back to the empty state', async () => {+ server.use(http.get('/api/categories', () => HttpResponse.error()));+ render(<><ToastContainer /><CategoryManager /></>);++ expect(await screen.findByText('Failed to load categories')).toBeInTheDocument();+ expect(screen.getByText('No categories yet')).toBeInTheDocument();+ });++ it('FE-COMP-CAT-014: editing a category sends a PUT and replaces the row', async () => {+ const user = userEvent.setup();+ let body: Record<string, unknown> | null = null;+ server.use(+ http.get('/api/categories', () =>+ HttpResponse.json({ categories: [buildCategory({ id: 5, name: 'Hotels', color: '#6366f1', icon: 'MapPin' })] })+ ),+ http.put('/api/categories/5', async ({ request }) => {+ body = await request.json() as Record<string, unknown>;+ return HttpResponse.json({ category: buildCategory({ id: 5, name: 'Lodging', color: '#ef4444', icon: 'BedDouble' }) });+ }),+ );+ render(<><ToastContainer /><CategoryManager /></>);+ await screen.findByText('Hotels');++ await user.click(screen.getAllByRole('button').filter(b => !b.textContent?.includes('New Category'))[0]);+ const nameInput = screen.getByDisplayValue('Hotels');+ await user.clear(nameInput);+ await user.type(nameInput, 'Lodging');+ await user.click(screen.getByTitle('Hotel'));+ await user.click(screen.getByText('Update'));++ expect(await screen.findByText('Category updated')).toBeInTheDocument();+ expect(body).toEqual({ name: 'Lodging', color: '#6366f1', icon: 'BedDouble' });+ expect(screen.getByText('Lodging')).toBeInTheDocument();+ });++ it('FE-COMP-CAT-015: a failing save surfaces the server message', async () => {+ const user = userEvent.setup();+ server.use(+ http.post('/api/categories', () => HttpResponse.json({ error: 'name already taken' }, { status: 409 })),+ );+ render(<><ToastContainer /><CategoryManager /></>);+ await screen.findByText('New Category');++ await user.click(screen.getByText('New Category'));+ await user.type(screen.getByPlaceholderText('Category name'), 'Parks');+ await user.click(screen.getByText('Create'));++ expect(await screen.findByText('name already taken')).toBeInTheDocument();+ // The form stays open so the name can be corrected+ expect(screen.getByDisplayValue('Parks')).toBeInTheDocument();+ });++ it('FE-COMP-CAT-016: declining the delete confirm keeps the category', async () => {+ const user = userEvent.setup();+ let deleteCalled = false;+ server.use(+ http.get('/api/categories', () => HttpResponse.json({ categories: [buildCategory({ id: 9, name: 'Parks' })] })),+ http.delete('/api/categories/9', () => { deleteCalled = true; return HttpResponse.json({ success: true }); }),+ );+ vi.spyOn(window, 'confirm').mockReturnValue(false);+ render(<CategoryManager />);+ await screen.findByText('Parks');++ const actionBtns = screen.getAllByRole('button').filter(b => !b.textContent?.includes('New Category'));+ await user.click(actionBtns[1]);++ expect(deleteCalled).toBe(false);+ expect(screen.getByText('Parks')).toBeInTheDocument();+ vi.restoreAllMocks();+ });++ it('FE-COMP-CAT-017: a failing delete toasts and keeps the row', async () => {+ const user = userEvent.setup();+ server.use(+ http.get('/api/categories', () => HttpResponse.json({ categories: [buildCategory({ id: 9, name: 'Parks' })] })),+ http.delete('/api/categories/9', () => HttpResponse.json({ error: 'category in use' }, { status: 409 })),+ );+ vi.spyOn(window, 'confirm').mockReturnValue(true);+ render(<><ToastContainer /><CategoryManager /></>);+ await screen.findByText('Parks');++ const actionBtns = screen.getAllByRole('button').filter(b => !b.textContent?.includes('New Category'));+ await user.click(actionBtns[1]);++ expect(await screen.findByText('category in use')).toBeInTheDocument();+ expect(screen.getByText('Parks')).toBeInTheDocument();+ vi.restoreAllMocks();+ });++ it('FE-COMP-CAT-018: picking an icon and a preset colour updates the live preview', async () => {+ const user = userEvent.setup();+ render(<CategoryManager />);+ await screen.findByText('New Category');+ await user.click(screen.getByText('New Category'));++ // Empty name → the preview falls back to the generic label+ expect(screen.getByText('Category')).toBeInTheDocument();+ await user.type(screen.getByPlaceholderText('Category name'), 'Beach day');+ await user.click(screen.getByTitle('Beach'));++ const preview = screen.getByText('Beach day');+ expect(preview).toHaveStyle({ color: '#6366f1' });++ await user.click(document.querySelectorAll('button[style*="background-color: rgb(239, 68, 68)"]')[0]);+ expect(screen.getByText('Beach day')).toHaveStyle({ color: '#ef4444' });+ });++ it('FE-COMP-CAT-019: the custom colour swatch opens the native picker and adopts its value', async () => {+ const user = userEvent.setup();+ render(<CategoryManager />);+ await screen.findByText('New Category');+ await user.click(screen.getByText('New Category'));++ const colorInput = document.querySelector('input[type="color"]') as HTMLInputElement;+ const clickSpy = vi.spyOn(colorInput, 'click').mockImplementation(() => {});+ await user.click(screen.getByTitle('Choose custom color'));+ expect(clickSpy).toHaveBeenCalled();++ fireEvent.change(colorInput, { target: { value: '#123456' } });+ await waitFor(() => expect(screen.getByText('Category')).toHaveStyle({ color: '#123456' }));+ // A non-preset colour fills the custom swatch instead of showing the pipette+ expect(screen.getByTitle('Choose custom color')).toHaveStyle({ backgroundColor: '#123456' });+ vi.restoreAllMocks();+ });++ it('FE-COMP-CAT-020: starting an edit closes the create form', async () => {+ const user = userEvent.setup();+ server.use(+ http.get('/api/categories', () => HttpResponse.json({ categories: [buildCategory({ id: 3, name: 'Hotels' })] })),+ );+ render(<CategoryManager />);+ await screen.findByText('Hotels');++ await user.click(screen.getByText('New Category'));+ expect(screen.getByPlaceholderText('Category name')).toHaveValue('');++ const row = screen.getByText('Hotels').closest('.p-3') as HTMLElement;+ await user.click(within(row).getAllByRole('button')[0]);++ // Only the inline edit form remains, pre-filled with the row's name+ expect(screen.getAllByPlaceholderText('Category name')).toHaveLength(1);+ expect(screen.getByDisplayValue('Hotels')).toBeInTheDocument();+ });});diff --git a/client/src/components/Admin/DefaultUserSettingsTab.test.tsx b/client/src/components/Admin/DefaultUserSettingsTab.test.tsxnew file mode 100644index 000000000..f61fc4e03--- /dev/null+++ b/client/src/components/Admin/DefaultUserSettingsTab.test.tsx@@ -0,0 +1,422 @@+// FE-ADMIN-DUS-001 to FE-ADMIN-DUS-025+import { render, screen, waitFor, within, fireEvent } from '../../../tests/helpers/render';+import userEvent from '@testing-library/user-event';+import { http, HttpResponse } from 'msw';+import { server } from '../../../tests/helpers/msw/server';+import { resetAllStores, seedStore } from '../../../tests/helpers/store';+import { buildAdmin } from '../../../tests/helpers/factories';+import { useAuthStore } from '../../store/authStore';+import { ToastContainer } from '../shared/Toast';+import DefaultUserSettingsTab from './DefaultUserSettingsTab';++// The tile preview would pull Leaflet into jsdom; the panel only needs it to render.+vi.mock('../Map/MapView', () => ({+ MapView: ({ tileUrl }: { tileUrl?: string }) => <div data-testid="map-preview" data-tile={tileUrl} />,+}));++const MAPBOX_STANDARD = 'mapbox://styles/mapbox/standard';+const MAPBOX_DARK = 'mapbox://styles/mapbox/dark-v11';+const MAPBOX_NAV_NIGHT = 'mapbox://styles/mapbox/navigation-night-v1';+const OFM_LIBERTY = 'https://tiles.openfreemap.org/styles/liberty';+const TILE_PLACEHOLDER = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';++/** Stateful stand-in for the admin defaults endpoint: PUT merges, null deletes. */+function stubDefaults(initial: Record<string, unknown> = {}) {+ const state: Record<string, unknown> = { ...initial };+ const puts: Record<string, unknown>[] = [];+ server.use(+ http.get('/api/admin/default-user-settings', () => HttpResponse.json(state)),+ http.put('/api/admin/default-user-settings', async ({ request }) => {+ const body = await request.json() as Record<string, unknown>;+ puts.push(body);+ for (const [key, value] of Object.entries(body)) {+ if (value === null) delete state[key];+ else state[key] = value;+ }+ return HttpResponse.json({ ...state });+ }),+ );+ return { puts, state };+}++function withToast() {+ return render(<><ToastContainer /><DefaultUserSettingsTab /></>);+}++/** The selected option button is the one drawn with the strong border token. */+function isActive(button: HTMLElement): boolean {+ return (button.style.border || '').includes('var(--text-primary)');+}++/**+ * The reset link sits inside the field's own <label>; because a button is a labelable+ * element the wrapping label becomes its accessible name, so it is queried positionally.+ */+function resetLink(label: string): HTMLElement {+ const el = screen.getAllByText(label).find(node => node.tagName === 'LABEL');+ if (!el) throw new Error(`no label found for ${label}`);+ return within(el).getByRole('button');+}++function hasResetLink(label: string): boolean {+ const el = screen.getAllByText(label).find(node => node.tagName === 'LABEL');+ return !!el && within(el).queryByRole('button') !== null;+}++/** Opens a CustomSelect by its trigger label and picks an option from the portal. */+async function pickFromSelect(user: ReturnType<typeof userEvent.setup>, trigger: string, option: string) {+ await user.click(screen.getByRole('button', { name: trigger }));+ const choices = await screen.findAllByRole('button', { name: option });+ await user.click(choices[choices.length - 1]);+}++describe('DefaultUserSettingsTab', () => {+ beforeEach(() => {+ resetAllStores();+ seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });+ stubDefaults();+ });++ it('FE-ADMIN-DUS-001: shows the loading placeholder until the defaults arrive', async () => {+ render(<DefaultUserSettingsTab />);+ expect(screen.getByText('Loading…')).toBeInTheDocument();++ expect(await screen.findByText('Default User Settings')).toBeInTheDocument();+ expect(screen.queryByText('Loading…')).not.toBeInTheDocument();+ });++ it('FE-ADMIN-DUS-002: renders every field with no reset links while nothing is set', async () => {+ render(<DefaultUserSettingsTab />);+ await screen.findByText('Default User Settings');++ for (const name of ['Light', 'Dark', 'Auto', '°C Celsius', 'km Metric', '24h (14:30)', 'On', 'Off']) {+ expect(isActive(screen.getByRole('button', { name }))).toBe(false);+ }+ for (const label of ['Color Mode', 'Temperature Unit', 'Distance Unit', 'Time Format', 'Display currency', 'Map Template']) {+ expect(hasResetLink(label)).toBe(false);+ }+ expect(screen.getByTestId('map-preview')).toBeInTheDocument();+ });++ it('FE-ADMIN-DUS-003: a failing load still renders the panel with built-in defaults', async () => {+ server.use(http.get('/api/admin/default-user-settings', () => HttpResponse.json({}, { status: 500 })));+ render(<DefaultUserSettingsTab />);++ expect(await screen.findByText('Default User Settings')).toBeInTheDocument();+ expect(hasResetLink('Map engine')).toBe(false);+ expect(isActive(screen.getByRole('button', { name: 'Standard (free)' }))).toBe(true);+ });++ it('FE-ADMIN-DUS-004: picking a colour mode saves it and confirms with a toast', async () => {+ const user = userEvent.setup();+ const { puts } = stubDefaults();+ withToast();+ await screen.findByText('Default User Settings');++ await user.click(screen.getByRole('button', { name: 'Dark' }));++ expect(await screen.findByText('Default saved')).toBeInTheDocument();+ expect(puts).toEqual([{ dark_mode: 'dark' }]);+ await waitFor(() => expect(isActive(screen.getByRole('button', { name: 'Dark' }))).toBe(true));+ expect(resetLink('Color Mode')).toBeInTheDocument();+ });++ it('FE-ADMIN-DUS-005: a legacy boolean dark_mode still highlights the matching option', async () => {+ stubDefaults({ dark_mode: true });+ const { unmount } = render(<DefaultUserSettingsTab />);+ await screen.findByText('Default User Settings');+ expect(isActive(screen.getByRole('button', { name: 'Dark' }))).toBe(true);+ expect(isActive(screen.getByRole('button', { name: 'Light' }))).toBe(false);+ unmount();++ stubDefaults({ dark_mode: false });+ render(<DefaultUserSettingsTab />);+ await screen.findByText('Default User Settings');+ expect(isActive(screen.getByRole('button', { name: 'Light' }))).toBe(true);+ expect(isActive(screen.getByRole('button', { name: 'Auto' }))).toBe(false);+ });++ it('FE-ADMIN-DUS-006: unit and time-format options each save their own key', async () => {+ const user = userEvent.setup();+ const { puts } = stubDefaults();+ render(<DefaultUserSettingsTab />);+ await screen.findByText('Default User Settings');++ await user.click(screen.getByRole('button', { name: '°F Fahrenheit' }));+ await waitFor(() => expect(resetLink('Temperature Unit')).toBeInTheDocument());+ await user.click(screen.getByRole('button', { name: 'mi Imperial' }));+ await waitFor(() => expect(resetLink('Distance Unit')).toBeInTheDocument());+ await user.click(screen.getByRole('button', { name: '12h (2:30 PM)' }));++ await waitFor(() => expect(puts).toEqual([+ { temperature_unit: 'fahrenheit' },+ { distance_unit: 'imperial' },+ { time_format: '12h' },+ ]));+ });++ it('FE-ADMIN-DUS-007: a set default gets a reset link that clears it server-side', async () => {+ const user = userEvent.setup();+ const { puts, state } = stubDefaults({ temperature_unit: 'celsius' });+ withToast();+ await screen.findByText('Default User Settings');++ expect(isActive(screen.getByRole('button', { name: '°C Celsius' }))).toBe(true);+ await user.click(resetLink('Temperature Unit'));++ expect(await screen.findByText('Reset to built-in default')).toBeInTheDocument();+ expect(puts).toEqual([{ temperature_unit: null }]);+ expect(state.temperature_unit).toBeUndefined();+ await waitFor(() => expect(hasResetLink('Temperature Unit')).toBe(false));+ });++ it('FE-ADMIN-DUS-008: the currency picker saves the chosen code and can be reset', async () => {+ const user = userEvent.setup();+ const { puts } = stubDefaults({ default_currency: 'USD' });+ render(<DefaultUserSettingsTab />);+ await screen.findByText('Default User Settings');++ await pickFromSelect(user, 'USD $', 'EUR €');+ await waitFor(() => expect(puts).toEqual([{ default_currency: 'EUR' }]));+ await waitFor(() => expect(screen.getByRole('button', { name: 'EUR €' })).toBeInTheDocument());++ await user.click(resetLink('Display currency'));+ await waitFor(() => expect(puts).toHaveLength(2));+ expect(puts[1]).toEqual({ default_currency: null });+ });++ it('FE-ADMIN-DUS-009: the blur-booking-codes options save booleans', async () => {+ const user = userEvent.setup();+ const { puts } = stubDefaults();+ render(<DefaultUserSettingsTab />);+ await screen.findByText('Default User Settings');++ await user.click(screen.getByRole('button', { name: 'On' }));+ await waitFor(() => expect(isActive(screen.getByRole('button', { name: 'On' }))).toBe(true));+ await user.click(screen.getByRole('button', { name: 'Off' }));++ await waitFor(() => expect(puts).toEqual([+ { blur_booking_codes: true },+ { blur_booking_codes: false },+ ]));+ });++ it('FE-ADMIN-DUS-010: the tile preset dropdown fills the URL field and hands it to the preview', async () => {+ const user = userEvent.setup();+ const { puts } = stubDefaults();+ render(<DefaultUserSettingsTab />);+ await screen.findByText('Default User Settings');++ await pickFromSelect(user, 'Select template...', 'CartoDB Dark');++ const url = 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png';+ await waitFor(() => expect(puts).toEqual([{ map_tile_url: url }]));+ expect(screen.getByPlaceholderText(TILE_PLACEHOLDER)).toHaveValue(url);+ expect(screen.getByTestId('map-preview')).toHaveAttribute('data-tile', url);+ });++ it('FE-ADMIN-DUS-011: a hand-typed tile URL is saved on blur', async () => {+ const user = userEvent.setup();+ const { puts } = stubDefaults();+ render(<DefaultUserSettingsTab />);+ await screen.findByText('Default User Settings');++ const input = screen.getByPlaceholderText(TILE_PLACEHOLDER);+ // userEvent reads {...} as key descriptors, so the placeholders are omitted here+ await user.type(input, 'https://tiles.example.org/tile.png');+ fireEvent.blur(input);++ await waitFor(() => expect(puts).toEqual([{ map_tile_url: 'https://tiles.example.org/tile.png' }]));+ expect(screen.getByTestId('map-preview')).toHaveAttribute('data-tile', 'https://tiles.example.org/tile.png');+ });++ it('FE-ADMIN-DUS-012: resetting the tile URL clears the input too', async () => {+ const user = userEvent.setup();+ const { puts } = stubDefaults({ map_tile_url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' });+ render(<DefaultUserSettingsTab />);+ await screen.findByText('Default User Settings');++ expect(screen.getByRole('button', { name: 'OpenStreetMap DE' })).toBeInTheDocument();+ await user.click(resetLink('Map Template'));++ await waitFor(() => expect(puts).toEqual([{ map_tile_url: null }]));+ await waitFor(() => expect(screen.getByPlaceholderText(TILE_PLACEHOLDER)).toHaveValue(''));+ });++ it('FE-ADMIN-DUS-013: leaflet hides the GL-only token and style fields', async () => {+ render(<DefaultUserSettingsTab />);+ await screen.findByText('Default User Settings');++ expect(isActive(screen.getByRole('button', { name: 'Standard (free)' }))).toBe(true);+ expect(screen.queryByText('Map style')).not.toBeInTheDocument();+ expect(screen.queryByText('Shared Mapbox token')).not.toBeInTheDocument();+ });++ it('FE-ADMIN-DUS-014: switching to Mapbox stores the provider with its own style slot', async () => {+ const user = userEvent.setup();+ const { puts } = stubDefaults();+ render(<DefaultUserSettingsTab />);+ await screen.findByText('Default User Settings');++ await user.click(screen.getByRole('button', { name: 'Mapbox (3D)' }));++ await waitFor(() => expect(puts).toEqual([{ map_provider: 'mapbox-gl', mapbox_style: MAPBOX_STANDARD }]));+ expect(await screen.findByText('Shared Mapbox token')).toBeInTheDocument();+ expect(screen.getByDisplayValue(MAPBOX_STANDARD)).toBeInTheDocument();+ });++ it('FE-ADMIN-DUS-015: switching to MapLibre stores the OpenFreeMap default and hides the token field', async () => {+ const user = userEvent.setup();+ const { puts } = stubDefaults();+ render(<DefaultUserSettingsTab />);+ await screen.findByText('Default User Settings');++ await user.click(screen.getByRole('button', { name: 'MapLibre (OpenFreeMap)' }));++ await waitFor(() => expect(puts).toEqual([{ map_provider: 'maplibre-gl', maplibre_style: OFM_LIBERTY }]));+ expect(await screen.findByText('Map style')).toBeInTheDocument();+ expect(screen.queryByText('Shared Mapbox token')).not.toBeInTheDocument();+ expect(screen.getByDisplayValue(OFM_LIBERTY)).toBeInTheDocument();+ });++ it('FE-ADMIN-DUS-016: switching back to the standard engine only stores the provider', async () => {+ const user = userEvent.setup();+ const { puts } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_style: MAPBOX_STANDARD });+ render(<DefaultUserSettingsTab />);+ await screen.findByText('Map style');++ await user.click(screen.getByRole('button', { name: 'Standard (free)' }));++ await waitFor(() => expect(puts).toEqual([{ map_provider: 'leaflet' }]));+ await waitFor(() => expect(screen.queryByText('Map style')).not.toBeInTheDocument());+ });++ it('FE-ADMIN-DUS-017: a Mapbox default holding an OpenFreeMap style falls back to the Mapbox standard', async () => {+ stubDefaults({ map_provider: 'mapbox-gl', mapbox_style: OFM_LIBERTY });+ render(<DefaultUserSettingsTab />);+ await screen.findByText('Map style');++ expect(screen.getByDisplayValue(MAPBOX_STANDARD)).toBeInTheDocument();+ });++ it('FE-ADMIN-DUS-018: a stored Mapbox style survives while the standard engine is active', async () => {+ const user = userEvent.setup();+ const { puts } = stubDefaults({ map_provider: 'leaflet', mapbox_style: MAPBOX_DARK });+ render(<DefaultUserSettingsTab />);+ await screen.findByText('Default User Settings');++ expect(screen.queryByText('Map style')).not.toBeInTheDocument();+ // Switching to Mapbox re-uses the stored slot instead of resetting it+ await user.click(screen.getByRole('button', { name: 'Mapbox (3D)' }));++ await waitFor(() => expect(puts).toEqual([{ map_provider: 'mapbox-gl', mapbox_style: MAPBOX_DARK }]));+ expect(screen.getByDisplayValue(MAPBOX_DARK)).toBeInTheDocument();+ });++ it('FE-ADMIN-DUS-019: the shared Mapbox token is stored on blur and cleared by its reset link', async () => {+ const user = userEvent.setup();+ const { puts } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_access_token: 'pk.old' });+ render(<DefaultUserSettingsTab />);+ await screen.findByText('Shared Mapbox token');++ const input = screen.getByPlaceholderText('pk.eyJ…');+ expect(input).toHaveValue('pk.old');+ await user.clear(input);+ await user.type(input, 'pk.new');+ fireEvent.blur(input);+ await waitFor(() => expect(puts).toEqual([{ mapbox_access_token: 'pk.new' }]));++ // Clicking the reset link also blurs the field again, so only the last PUT is checked+ await user.click(resetLink('Shared Mapbox token'));+ await waitFor(() => expect(puts[puts.length - 1]).toEqual({ mapbox_access_token: null }));+ await waitFor(() => expect(screen.getByPlaceholderText('pk.eyJ…')).toHaveValue(''));+ });++ it('FE-ADMIN-DUS-020: a hand-typed MapLibre style is normalised to OpenFreeMap on blur', async () => {+ const user = userEvent.setup();+ const { puts } = stubDefaults({ map_provider: 'maplibre-gl', maplibre_style: OFM_LIBERTY });+ render(<DefaultUserSettingsTab />);+ await screen.findByText('Map style');++ const input = screen.getByDisplayValue(OFM_LIBERTY);+ await user.clear(input);+ await user.type(input, 'https://example.com/custom.json');+ fireEvent.blur(input);++ await waitFor(() => expect(puts).toEqual([{ maplibre_style: OFM_LIBERTY }]));+ expect(input).toHaveValue(OFM_LIBERTY);+ });++ it('FE-ADMIN-DUS-021: the style dropdown writes the picked preset into the active provider slot', async () => {+ const user = userEvent.setup();+ const { puts } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_style: MAPBOX_STANDARD });+ render(<DefaultUserSettingsTab />);+ await screen.findByText('Map style');++ await pickFromSelect(user, 'Mapbox Standard', 'Navigation Night');++ await waitFor(() => expect(puts).toEqual([{ mapbox_style: MAPBOX_NAV_NIGHT }]));+ expect(screen.getByDisplayValue(MAPBOX_NAV_NIGHT)).toBeInTheDocument();+ });++ it('FE-ADMIN-DUS-022: resetting the style restores the provider default in the field', async () => {+ const user = userEvent.setup();+ const { puts } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_style: MAPBOX_DARK });+ render(<DefaultUserSettingsTab />);+ await screen.findByText('Map style');++ await user.click(resetLink('Map style'));++ await waitFor(() => expect(puts).toEqual([{ mapbox_style: null }]));+ await waitFor(() => expect(screen.getByDisplayValue(MAPBOX_STANDARD)).toBeInTheDocument());+ });++ it('FE-ADMIN-DUS-023: the Mapbox 3D and quality options start on their built-in defaults and save their own keys', async () => {+ const user = userEvent.setup();+ const { puts } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_style: MAPBOX_STANDARD });+ render(<DefaultUserSettingsTab />);+ await screen.findByText('3D buildings & terrain');++ // 3D defaults to on, quality mode to off when neither is stored+ const threeD = within(screen.getByText('3D buildings & terrain').closest('div') as HTMLElement);+ expect(isActive(threeD.getByRole('button', { name: 'On' }))).toBe(true);+ const quality = within(screen.getByText('High-quality mode').closest('div') as HTMLElement);+ expect(isActive(quality.getByRole('button', { name: 'Off' }))).toBe(true);++ await user.click(threeD.getByRole('button', { name: 'Off' }));+ await waitFor(() => expect(puts).toEqual([{ mapbox_3d_enabled: false }]));+ await user.click(quality.getByRole('button', { name: 'On' }));+ await waitFor(() => expect(puts).toHaveLength(2));+ expect(puts[1]).toEqual({ mapbox_quality_mode: true });+ });++ it('FE-ADMIN-DUS-024: a rejected save surfaces the request error instead of a success toast', async () => {+ const user = userEvent.setup();+ server.use(+ http.get('/api/admin/default-user-settings', () => HttpResponse.json({})),+ http.put('/api/admin/default-user-settings', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),+ );+ withToast();+ await screen.findByText('Default User Settings');++ await user.click(screen.getByRole('button', { name: 'Dark' }));++ expect(await screen.findByText(/Request failed with status code 500/)).toBeInTheDocument();+ expect(screen.queryByText('Default saved')).not.toBeInTheDocument();+ });++ it('FE-ADMIN-DUS-025: a rejected reset surfaces the request error', async () => {+ const user = userEvent.setup();+ server.use(+ http.get('/api/admin/default-user-settings', () => HttpResponse.json({ time_format: '12h' })),+ http.put('/api/admin/default-user-settings', () => HttpResponse.json({ error: 'nope' }, { status: 503 })),+ );+ withToast();+ await screen.findByText('Default User Settings');++ await user.click(resetLink('Time Format'));++ expect(await screen.findByText(/Request failed with status code 503/)).toBeInTheDocument();+ expect(screen.queryByText('Reset to built-in default')).not.toBeInTheDocument();+ });+});diff --git a/client/src/components/Admin/DevNotificationsPanel.test.tsx b/client/src/components/Admin/DevNotificationsPanel.test.tsxindex 734c9b11c..9402586ab 100644--- a/client/src/components/Admin/DevNotificationsPanel.test.tsx+++ b/client/src/components/Admin/DevNotificationsPanel.test.tsx@@ -1,5 +1,5 @@-// FE-ADMIN-DEVNOTIF-001 to FE-ADMIN-DEVNOTIF-010-import { render, screen, waitFor } from '../../../tests/helpers/render';+// FE-ADMIN-DEVNOTIF-001 to FE-ADMIN-DEVNOTIF-016+import { render, screen, waitFor, fireEvent } from '../../../tests/helpers/render';import userEvent from '@testing-library/user-event';import { http, HttpResponse } from 'msw';import { server } from '../../../tests/helpers/msw/server';@@ -157,4 +157,141 @@ describe('DevNotificationsPanel', () => {await screen.findByText('User-Scoped Events');expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument();});++ it('FE-ADMIN-DEVNOTIF-011: the remaining self/admin type buttons each fire their own event', async () => {+ const bodies: Record<string, unknown>[] = [];+ server.use(+ http.post('/api/admin/dev/test-notification', async ({ request }) => {+ bodies.push(await request.json() as Record<string, unknown>);+ return HttpResponse.json({ ok: true });+ }),+ );+ const user = userEvent.setup();+ render(<><ToastContainer /><DevNotificationsPanel /></>);+ await screen.findByText('Type Testing');++ await user.click(screen.getByText('Boolean → Me').closest('button')!);+ await screen.findByText('Sent: boolean-me');+ await user.click(screen.getByText('Navigate → Me').closest('button')!);+ await screen.findByText('Sent: navigate-me');+ await user.click(screen.getByText('Simple → All Admins').closest('button')!);+ await screen.findByText('Sent: simple-admins');+ await user.click(screen.getByText('version_available').closest('button')!);+ await screen.findByText('Sent: version_available');++ expect(bodies[0]).toMatchObject({+ event: 'test_boolean',+ scope: 'user',+ targetId: ADMIN_USER.id,+ inApp: {+ type: 'boolean',+ positiveCallback: { action: 'test_approve', payload: {} },+ negativeCallback: { action: 'test_deny', payload: {} },+ },+ });+ expect(bodies[1]).toMatchObject({ event: 'test_navigate', scope: 'user', targetId: ADMIN_USER.id });+ expect(bodies[2]).toMatchObject({ event: 'test_simple', scope: 'admin', targetId: 0 });+ expect(bodies[3]).toMatchObject({ event: 'version_available', scope: 'admin', targetId: 0, params: { version: '9.9.9-test' } });+ });++ it('FE-ADMIN-DEVNOTIF-012: every trip-scoped button carries the selected trip and the actor', async () => {+ const bodies: Record<string, unknown>[] = [];+ server.use(+ http.post('/api/admin/dev/test-notification', async ({ request }) => {+ bodies.push(await request.json() as Record<string, unknown>);+ return HttpResponse.json({ ok: true });+ }),+ );+ const user = userEvent.setup();+ render(<><ToastContainer /><DevNotificationsPanel /></>);+ await screen.findByText('Trip-Scoped Events');++ const [tripSelect] = screen.getAllByRole('combobox');+ const tripId = Number((tripSelect as HTMLSelectElement).value);++ for (const label of ['trip_reminder', 'photos_shared', 'collab_message', 'packing_tagged']) {+ await user.click(screen.getByText(label).closest('button')!);+ await screen.findByText(`Sent: ${label}`);+ }++ expect(bodies.map(b => b.event)).toEqual(['trip_reminder', 'photos_shared', 'collab_message', 'packing_tagged']);+ for (const body of bodies) {+ expect(body.scope).toBe('trip');+ expect(body.targetId).toBe(tripId);+ expect(body.params).toMatchObject({ trip: 'Paris Adventure', tripId: String(tripId) });+ }+ expect(bodies[1].params).toMatchObject({ actor: 'testadmin', count: '5' });+ expect(bodies[2].params).toMatchObject({ preview: 'This is a test message preview.' });+ expect(bodies[3].params).toMatchObject({ category: 'Clothing' });+ });++ it('FE-ADMIN-DEVNOTIF-013: user-scoped events target the picked recipient', async () => {+ const bodies: Record<string, unknown>[] = [];+ server.use(+ http.post('/api/admin/dev/test-notification', async ({ request }) => {+ bodies.push(await request.json() as Record<string, unknown>);+ return HttpResponse.json({ ok: true });+ }),+ );+ const user = userEvent.setup();+ render(<><ToastContainer /><DevNotificationsPanel /></>);+ await screen.findByText('User-Scoped Events');++ const userSelect = screen.getAllByRole('combobox')[1] as HTMLSelectElement;+ const aliceOption = Array.from(userSelect.querySelectorAll('option')).find(+ o => (o.textContent ?? '').includes('alice'),+ )!;+ await user.selectOptions(userSelect, aliceOption.value);+ const aliceId = Number(aliceOption.value);++ await user.click(screen.getByText('trip_invite').closest('button')!);+ await screen.findByText(`Sent: trip_invite-${aliceId}`);+ await user.click(screen.getByText('vacay_invite').closest('button')!);+ await screen.findByText(`Sent: vacay_invite-${aliceId}`);++ expect(bodies[0]).toMatchObject({+ event: 'trip_invite',+ scope: 'user',+ targetId: aliceId,+ params: { actor: 'testadmin', invitee: '[email protected]' },+ });+ expect(bodies[1]).toMatchObject({+ event: 'vacay_invite',+ scope: 'user',+ targetId: aliceId,+ params: { actor: 'testadmin', planId: '1' },+ });+ });++ it('FE-ADMIN-DEVNOTIF-014: the User-Scoped section is hidden when no users come back', async () => {+ server.use(http.get('/api/admin/users', () => HttpResponse.json({ users: [] })));+ render(<><ToastContainer /><DevNotificationsPanel /></>);++ await screen.findByText('Trip-Scoped Events');+ expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();+ });++ it('FE-ADMIN-DEVNOTIF-015: failing lookups leave both scoped sections out without crashing', async () => {+ server.use(+ http.get('/api/trips', () => HttpResponse.error()),+ http.get('/api/admin/users', () => HttpResponse.error()),+ );+ render(<><ToastContainer /><DevNotificationsPanel /></>);++ expect(await screen.findByText('Type Testing')).toBeInTheDocument();+ await waitFor(() => expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument());+ expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();+ expect(screen.getByText('Admin-Scoped Events')).toBeInTheDocument();+ });++ it('FE-ADMIN-DEVNOTIF-016: hovering a trigger paints and restores its background', async () => {+ render(<><ToastContainer /><DevNotificationsPanel /></>);+ await screen.findByText('Type Testing');++ const btn = screen.getByText('Simple → Me').closest('button')!;+ fireEvent.mouseEnter(btn);+ expect(btn.style.background).toBe('var(--bg-hover)');+ fireEvent.mouseLeave(btn);+ expect(btn.style.background).toBe('var(--bg-card)');+ });});diff --git a/client/src/components/Admin/PackingTemplateManager.test.tsx b/client/src/components/Admin/PackingTemplateManager.test.tsxindex dedfc90f3..1e150a2aa 100644--- a/client/src/components/Admin/PackingTemplateManager.test.tsx+++ b/client/src/components/Admin/PackingTemplateManager.test.tsx@@ -1,5 +1,5 @@-// FE-ADMIN-PKG-001 to FE-ADMIN-PKG-020-import { render, screen, waitFor } from '../../../tests/helpers/render';+// FE-ADMIN-PKG-001 to FE-ADMIN-PKG-032+import { render, screen, waitFor, within } from '../../../tests/helpers/render';import userEvent from '@testing-library/user-event';import { http, HttpResponse } from 'msw';import { server } from '../../../tests/helpers/msw/server';@@ -18,6 +18,23 @@ beforeEach(() => {resetAllStores();});+/** Template rows carry [chevron, edit, delete]; category headers [add item, edit, delete]. */+function rowButtons(name: string, selector: string): HTMLElement[] {+ const row = screen.getByText(name).closest(selector) as HTMLElement;+ return within(row).getAllByRole('button');+}++const templateButtons = (name: string) => rowButtons(name, '.px-5.py-3');+const categoryButtons = (name: string) => rowButtons(name, '.bg-slate-50');+const itemButtons = (name: string) => rowButtons(name, '.group');++/** Expands the single fixture template and waits for its content. */+async function expandBeachTrip(user: ReturnType<typeof userEvent.setup>, firstChild: string) {+ await screen.findByText('Beach Trip');+ await user.click(screen.getByText('Beach Trip'));+ await screen.findByText(firstChild);+}+describe('PackingTemplateManager', () => {it('FE-ADMIN-PKG-001: shows loading spinner on mount', async () => {server.use(@@ -508,4 +525,296 @@ describe('PackingTemplateManager', () => {expect(screen.queryByPlaceholderText('Template name (e.g. Beach Holiday)')).not.toBeInTheDocument());});++ it('FE-ADMIN-PKG-021: a failing template list toasts and shows the empty state', async () => {+ server.use(http.get('/api/admin/packing-templates', () => HttpResponse.error()));+ render(<><ToastContainer /><PackingTemplateManager /></>);++ expect(await screen.findByText('Failed to load templates')).toBeInTheDocument();+ expect(screen.getByText('No templates created yet')).toBeInTheDocument();+ });++ it('FE-ADMIN-PKG-022: a failing expand toasts and leaves the template without content', async () => {+ const user = userEvent.setup();+ server.use(+ http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates: [tmpl1] })),+ http.get('/api/admin/packing-templates/1', () => HttpResponse.error()),+ );+ render(<><ToastContainer /><PackingTemplateManager /></>);+ await screen.findByText('Beach Trip');++ await user.click(screen.getByText('Beach Trip'));++ expect(await screen.findByText('Failed to load templates')).toBeInTheDocument();+ expect(screen.getByText('Add category')).toBeInTheDocument();+ });++ it('FE-ADMIN-PKG-023: an empty name is not submitted and a failing create toasts', async () => {+ const user = userEvent.setup();+ let posts = 0;+ server.use(+ http.post('/api/admin/packing-templates', () => {+ posts += 1;+ return HttpResponse.json({ error: 'nope' }, { status: 500 });+ }),+ );+ render(<><ToastContainer /><PackingTemplateManager /></>);+ await screen.findByText('No templates created yet');++ await user.click(screen.getByRole('button', { name: /new template/i }));+ const input = screen.getByPlaceholderText('Template name (e.g. Beach Holiday)');+ await user.type(input, ' {Enter}');+ expect(posts).toBe(0);++ await user.clear(input);+ await user.type(input, 'Ski trip{Enter}');+ expect(await screen.findByText('Failed to create template')).toBeInTheDocument();+ expect(posts).toBe(1);+ });++ it('FE-ADMIN-PKG-024: deleting the expanded template collapses it, a failing delete toasts', async () => {+ const user = userEvent.setup();+ let calls = 0;+ server.use(+ http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates: [tmpl1] })),+ http.get('/api/admin/packing-templates/1', () => HttpResponse.json({ categories: [cat1], items: [item1] })),+ http.delete('/api/admin/packing-templates/1', () => {+ calls += 1;+ return calls === 1+ ? HttpResponse.json({ error: 'in use' }, { status: 500 })+ : HttpResponse.json({ success: true });+ }),+ );+ render(<><ToastContainer /><PackingTemplateManager /></>);+ await expandBeachTrip(user, 'Clothing');++ await user.click(templateButtons('Beach Trip')[2]);+ expect(await screen.findByText('Failed to delete template')).toBeInTheDocument();+ expect(screen.getByText('Clothing')).toBeInTheDocument();++ await user.click(templateButtons('Beach Trip')[2]);+ await screen.findByText('Template deleted');+ await waitFor(() => expect(screen.queryByText('Clothing')).not.toBeInTheDocument());+ expect(screen.getByText('No templates created yet')).toBeInTheDocument();+ });++ it('FE-ADMIN-PKG-025: a blank rename closes the editor, a failing rename toasts, blur commits', async () => {+ const user = userEvent.setup();+ let puts = 0;+ server.use(+ http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates: [tmpl1] })),+ http.put('/api/admin/packing-templates/1', () => {+ puts += 1;+ return HttpResponse.json({ error: 'nope' }, { status: 500 });+ }),+ );+ render(<><ToastContainer /><PackingTemplateManager /></>);+ await screen.findByText('Beach Trip');++ await user.click(templateButtons('Beach Trip')[1]);+ await user.clear(screen.getByDisplayValue('Beach Trip'));+ await user.type(screen.getByRole('textbox'), '{Enter}');+ await waitFor(() => expect(screen.getByText('Beach Trip')).toBeInTheDocument());+ expect(puts).toBe(0);++ // Blurring the field commits the pending name — here the request fails+ await user.click(templateButtons('Beach Trip')[1]);+ const input = screen.getByDisplayValue('Beach Trip');+ await user.clear(input);+ await user.type(input, 'Winter');+ await user.tab();+ expect(await screen.findByText('Failed to save')).toBeInTheDocument();+ expect(puts).toBe(1);+ });++ it('FE-ADMIN-PKG-026: a blank category is not posted, a failing add toasts and X cancels', async () => {+ const user = userEvent.setup();+ let posts = 0;+ server.use(+ http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates: [tmpl1] })),+ http.get('/api/admin/packing-templates/1', () => HttpResponse.json({ categories: [], items: [] })),+ http.post('/api/admin/packing-templates/1/categories', () => {+ posts += 1;+ return HttpResponse.json({ error: 'nope' }, { status: 500 });+ }),+ );+ render(<><ToastContainer /><PackingTemplateManager /></>);+ await expandBeachTrip(user, 'Add category');++ await user.click(screen.getByText('Add category'));+ const catInput = screen.getByPlaceholderText('Category name (e.g. Clothing)');+ await user.type(catInput, ' {Enter}');+ expect(posts).toBe(0);++ await user.clear(catInput);+ await user.type(catInput, 'Electronics{Enter}');+ expect(await screen.findByText('Failed to save')).toBeInTheDocument();++ const cancel = within(catInput.parentElement as HTMLElement).getAllByRole('button')[1];+ await user.click(cancel);+ await waitFor(() =>+ expect(screen.queryByPlaceholderText('Category name (e.g. Clothing)')).not.toBeInTheDocument(),+ );+ });++ it('FE-ADMIN-PKG-027: a blank category rename closes the editor and a failing rename toasts', async () => {+ const user = userEvent.setup();+ let puts = 0;+ server.use(+ http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates: [tmpl1] })),+ http.get('/api/admin/packing-templates/1', () => HttpResponse.json({ categories: [cat1], items: [] })),+ http.put('/api/admin/packing-templates/1/categories/10', () => {+ puts += 1;+ return HttpResponse.json({ error: 'nope' }, { status: 500 });+ }),+ );+ render(<><ToastContainer /><PackingTemplateManager /></>);+ await expandBeachTrip(user, 'Clothing');++ await user.click(categoryButtons('Clothing')[1]);+ await user.clear(screen.getByDisplayValue('Clothing'));+ await user.tab();+ await waitFor(() => expect(screen.getByText('Clothing')).toBeInTheDocument());+ expect(puts).toBe(0);++ await user.click(categoryButtons('Clothing')[1]);+ const catInput = screen.getByDisplayValue('Clothing');+ await user.clear(catInput);+ await user.type(catInput, 'Shoes{Enter}');+ expect(await screen.findByText('Failed to save')).toBeInTheDocument();+ expect(puts).toBe(1);+ });++ it('FE-ADMIN-PKG-028: a failing category delete toasts and keeps the category', async () => {+ const user = userEvent.setup();+ server.use(+ http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates: [tmpl1] })),+ http.get('/api/admin/packing-templates/1', () => HttpResponse.json({ categories: [cat1], items: [item1] })),+ http.delete('/api/admin/packing-templates/1/categories/10', () => HttpResponse.error()),+ );+ render(<><ToastContainer /><PackingTemplateManager /></>);+ await expandBeachTrip(user, 'Clothing');++ await user.click(categoryButtons('Clothing')[2]);++ expect(await screen.findByText('Failed to delete template')).toBeInTheDocument();+ expect(screen.getByText('Clothing')).toBeInTheDocument();+ expect(screen.getByText('T-shirt')).toBeInTheDocument();+ });++ it('FE-ADMIN-PKG-029: the add-item button posts the item, a failing add toasts and X closes the row', async () => {+ const user = userEvent.setup();+ let posts = 0;+ server.use(+ http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates: [tmpl1] })),+ http.get('/api/admin/packing-templates/1', () => HttpResponse.json({ categories: [cat1], items: [] })),+ http.post('/api/admin/packing-templates/1/categories/10/items', () => {+ posts += 1;+ return posts === 1+ ? HttpResponse.json({ item: { id: 102, category_id: 10, name: 'Sandals', sort_order: 0 } })+ : HttpResponse.json({ error: 'nope' }, { status: 500 });+ }),+ );+ render(<><ToastContainer /><PackingTemplateManager /></>);+ await expandBeachTrip(user, 'Clothing');++ await user.click(categoryButtons('Clothing')[0]);+ const itemInput = screen.getByPlaceholderText('Item name');+ const addRow = itemInput.parentElement as HTMLElement;+ expect(within(addRow).getAllByRole('button')[0]).toBeDisabled();++ await user.type(itemInput, 'Sandals');+ await user.click(within(addRow).getAllByRole('button')[0]);+ await screen.findByText('Sandals');++ await user.type(screen.getByPlaceholderText('Item name'), 'Towel');+ await user.click(within(addRow).getAllByRole('button')[0]);+ expect(await screen.findByText('Failed to save')).toBeInTheDocument();++ await user.click(within(addRow).getAllByRole('button')[1]);+ await waitFor(() => expect(screen.queryByPlaceholderText('Item name')).not.toBeInTheDocument());+ });++ it('FE-ADMIN-PKG-030: the item editor commits on the check button, cancels on X and ignores a blank name', async () => {+ const user = userEvent.setup();+ let puts = 0;+ server.use(+ http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates: [tmpl1] })),+ http.get('/api/admin/packing-templates/1', () => HttpResponse.json({ categories: [cat1], items: [item1] })),+ http.put('/api/admin/packing-templates/1/items/100', () => {+ puts += 1;+ return puts === 1+ ? HttpResponse.json({ success: true })+ : HttpResponse.json({ error: 'nope' }, { status: 500 });+ }),+ );+ render(<><ToastContainer /><PackingTemplateManager /></>);+ await expandBeachTrip(user, 'T-shirt');++ // A blank name just closes the editor+ await user.click(itemButtons('T-shirt')[0]);+ const blank = screen.getByDisplayValue('T-shirt');+ await user.clear(blank);+ await user.click(within(blank.parentElement as HTMLElement).getAllByRole('button')[0]);+ await waitFor(() => expect(screen.getByText('T-shirt')).toBeInTheDocument());+ expect(puts).toBe(0);++ // X discards the pending name+ await user.click(itemButtons('T-shirt')[0]);+ const editing = screen.getByDisplayValue('T-shirt');+ await user.clear(editing);+ await user.type(editing, 'Discarded');+ await user.click(within(editing.parentElement as HTMLElement).getAllByRole('button')[1]);+ await waitFor(() => expect(screen.getByText('T-shirt')).toBeInTheDocument());+ expect(puts).toBe(0);++ // The check button commits+ await user.click(itemButtons('T-shirt')[0]);+ const editing2 = screen.getByDisplayValue('T-shirt');+ await user.clear(editing2);+ await user.type(editing2, 'Tank Top');+ await user.click(within(editing2.parentElement as HTMLElement).getAllByRole('button')[0]);+ await screen.findByText('Tank Top');+ expect(puts).toBe(1);++ // A failing rename keeps the editor open and toasts+ await user.click(itemButtons('Tank Top')[0]);+ const editing3 = screen.getByDisplayValue('Tank Top');+ await user.clear(editing3);+ await user.type(editing3, 'Vest{Enter}');+ expect(await screen.findByText('Failed to save')).toBeInTheDocument();+ expect(screen.getByDisplayValue('Vest')).toBeInTheDocument();+ });++ it('FE-ADMIN-PKG-031: a failing item delete toasts and keeps the item', async () => {+ const user = userEvent.setup();+ server.use(+ http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates: [tmpl1] })),+ http.get('/api/admin/packing-templates/1', () => HttpResponse.json({ categories: [cat1], items: [item1] })),+ http.delete('/api/admin/packing-templates/1/items/100', () => HttpResponse.error()),+ );+ render(<><ToastContainer /><PackingTemplateManager /></>);+ await expandBeachTrip(user, 'T-shirt');++ await user.click(itemButtons('T-shirt')[1]);++ expect(await screen.findByText('Failed to delete template')).toBeInTheDocument();+ expect(screen.getByText('T-shirt')).toBeInTheDocument();+ });++ it('FE-ADMIN-PKG-032: the chevron button expands and collapses the template', async () => {+ const user = userEvent.setup();+ server.use(+ http.get('/api/admin/packing-templates', () => HttpResponse.json({ templates: [tmpl1] })),+ http.get('/api/admin/packing-templates/1', () => HttpResponse.json({ categories: [cat1], items: [item1] })),+ );+ render(<PackingTemplateManager />);+ await screen.findByText('Beach Trip');++ await user.click(templateButtons('Beach Trip')[0]);+ await screen.findByText('Clothing');++ await user.click(templateButtons('Beach Trip')[0]);+ await waitFor(() => expect(screen.queryByText('Clothing')).not.toBeInTheDocument());+ });});diff --git a/client/src/components/BackgroundTasks/BackgroundTasksWidget.extra.test.tsx b/client/src/components/BackgroundTasks/BackgroundTasksWidget.extra.test.tsxnew file mode 100644index 000000000..6b708ba38--- /dev/null+++ b/client/src/components/BackgroundTasks/BackgroundTasksWidget.extra.test.tsx@@ -0,0 +1,247 @@+// FE-W4BGT-001 to FE-W4BGT-020+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { screen, act, waitFor } from '@testing-library/react'+import { render, fireEvent } from '../../../tests/helpers/render'+import { reservationsApi, healthApi } from '../../api/client'+import { addListener } from '../../api/websocket'+import { useBackgroundTasksStore, type BackgroundImportTask } from '../../store/backgroundTasksStore'+import BackgroundTasksWidget from './BackgroundTasksWidget'++const navigate = vi.fn()+vi.mock('react-router-dom', async () => {+ const actual = await vi.importActual<typeof import('react-router-dom')>('react-router-dom')+ return { ...actual, useNavigate: () => navigate }+})+vi.mock('../../api/websocket', () => ({ addListener: vi.fn(), removeListener: vi.fn() }))+vi.mock('../../api/client', () => ({+ reservationsApi: { importJobStatus: vi.fn(), importBookingAsync: vi.fn() },+ healthApi: { features: vi.fn() },+}))+vi.mock('../../db/offlineDb', () => ({ saveImportFiles: vi.fn(() => Promise.resolve()) }))++const task = (overrides: Partial<BackgroundImportTask> = {}): BackgroundImportTask => ({+ id: 'j1', tripId: 't1', label: 'voucher.pdf', status: 'done', done: 0, total: 1, items: [], warnings: [],+ ...overrides,+})++type WsHandler = (e: Record<string, unknown>) => void++beforeEach(() => {+ vi.clearAllMocks()+ vi.mocked(healthApi.features).mockReturnValue(new Promise(() => {}))+ vi.mocked(reservationsApi.importJobStatus).mockReturnValue(new Promise(() => {}))+ useBackgroundTasksStore.setState({ tasks: [] })+})++afterEach(() => {+ vi.useRealTimers()+})++describe('BackgroundTasksWidget — rendering', () => {+ it('FE-W4BGT-001: renders nothing without tasks', () => {+ const { container, baseElement } = render(<BackgroundTasksWidget />)++ expect(container).toBeEmptyDOMElement()+ expect(baseElement.querySelectorAll('button')).toHaveLength(0)+ })++ it('FE-W4BGT-002: a running job shows the spinner, the parsing note and no close button', () => {+ useBackgroundTasksStore.setState({ tasks: [task({ status: 'running', done: 1, total: 3 })] })+ const { baseElement } = render(<BackgroundTasksWidget />)++ expect(screen.getByText('voucher.pdf')).toBeInTheDocument()+ expect(screen.getByText(/· 1\/3$/)).toBeInTheDocument()+ expect(baseElement.querySelector('.animate-spin')).not.toBeNull()+ expect(screen.queryByLabelText('Close')).toBeNull()+ })++ it('FE-W4BGT-003: a single-file job omits the counter', () => {+ useBackgroundTasksStore.setState({ tasks: [task({ status: 'running', done: 0, total: 1 })] })+ render(<BackgroundTasksWidget />)++ expect(screen.queryByText(/·/)).toBeNull()+ })++ it('FE-W4BGT-004: a restored done job without items still reads as parsing', () => {+ useBackgroundTasksStore.setState({ tasks: [task({ status: 'done', items: undefined })] })+ const { baseElement } = render(<BackgroundTasksWidget />)++ expect(baseElement.querySelector('.animate-spin')).not.toBeNull()+ expect(screen.getByLabelText('Close')).toBeInTheDocument()+ })++ it('FE-W4BGT-005: a finished job with items offers the review action', () => {+ useBackgroundTasksStore.setState({ tasks: [task({ items: [{ id: 1 }] as never })] })+ render(<BackgroundTasksWidget />)++ fireEvent.click(screen.getByRole('button', { name: 'Import' }))++ expect(useBackgroundTasksStore.getState().tasks[0].reviewRequested).toBe(true)+ expect(navigate).toHaveBeenCalledWith('/trips/t1')+ })++ it('FE-W4BGT-006: a failed job shows the error message', () => {+ useBackgroundTasksStore.setState({ tasks: [task({ status: 'error', error: 'AI quota exhausted' })] })+ render(<BackgroundTasksWidget />)++ expect(screen.getByText('AI quota exhausted')).toBeInTheDocument()+ })++ it('FE-W4BGT-007: the close button drops the card', () => {+ useBackgroundTasksStore.setState({ tasks: [task()] })+ render(<BackgroundTasksWidget />)++ fireEvent.click(screen.getByLabelText('Close'))++ expect(useBackgroundTasksStore.getState().tasks).toHaveLength(0)+ })+})++describe('BackgroundTasksWidget — websocket', () => {+ it('FE-W4BGT-008: import:progress updates the running card', () => {+ useBackgroundTasksStore.setState({ tasks: [task({ status: 'running', total: 4 })] })+ render(<BackgroundTasksWidget />)+ const handler = vi.mocked(addListener).mock.calls[0][0] as WsHandler++ act(() => { handler({ type: 'import:progress', jobId: 'j1', tripId: 't1', done: 2, total: 4 }) })++ expect(screen.getByText(/· 2\/4$/)).toBeInTheDocument()+ })++ it('FE-W4BGT-009: import:done attaches the parsed items', () => {+ useBackgroundTasksStore.setState({ tasks: [task({ status: 'running', items: undefined })] })+ render(<BackgroundTasksWidget />)+ const handler = vi.mocked(addListener).mock.calls[0][0] as WsHandler++ act(() => { handler({ type: 'import:done', jobId: 'j1', tripId: 't1', result: { items: [{ id: 1 }], warnings: [] } }) })++ expect(screen.getByRole('button', { name: 'Import' })).toBeInTheDocument()+ })++ it('FE-W4BGT-010: import:error surfaces the message', () => {+ useBackgroundTasksStore.setState({ tasks: [task({ status: 'running' })] })+ render(<BackgroundTasksWidget />)+ const handler = vi.mocked(addListener).mock.calls[0][0] as WsHandler++ act(() => { handler({ type: 'import:error', jobId: 'j1', tripId: 't1', message: 'boom' }) })++ expect(screen.getByText('boom')).toBeInTheDocument()+ })++ it('FE-W4BGT-011: unrelated events and events without a job id are ignored', () => {+ useBackgroundTasksStore.setState({ tasks: [task({ status: 'running', total: 4 })] })+ render(<BackgroundTasksWidget />)+ const handler = vi.mocked(addListener).mock.calls[0][0] as WsHandler++ act(() => {+ handler({ type: 'place:updated', jobId: 'j1' })+ handler({ type: 'import:progress', done: 3, total: 4 })+ handler({ done: 3 })+ })++ expect(screen.getByText(/· 0\/4$/)).toBeInTheDocument()+ })+})++describe('BackgroundTasksWidget — rehydrate', () => {+ it('FE-W4BGT-012: a restored job that the server finished gets its items back', async () => {+ useBackgroundTasksStore.setState({ tasks: [task({ status: 'running', items: undefined })] })+ vi.mocked(reservationsApi.importJobStatus).mockResolvedValue({+ status: 'done', done: 1, total: 1, result: { items: [{ id: 1 }], warnings: [] },+ } as never)++ render(<BackgroundTasksWidget />)++ expect(await screen.findByRole('button', { name: 'Import' })).toBeInTheDocument()+ expect(reservationsApi.importJobStatus).toHaveBeenCalledWith('t1', 'j1')+ })++ it('FE-W4BGT-013: a restored job the server reports as failed shows the error', async () => {+ useBackgroundTasksStore.setState({ tasks: [task({ status: 'running', items: undefined })] })+ vi.mocked(reservationsApi.importJobStatus).mockResolvedValue({ status: 'error', error: 'expired', done: 0, total: 1 } as never)++ render(<BackgroundTasksWidget />)++ expect(await screen.findByText('expired')).toBeInTheDocument()+ })++ it('FE-W4BGT-014: a restored job the server has dropped is removed', async () => {+ useBackgroundTasksStore.setState({ tasks: [task({ status: 'running', items: undefined })] })+ vi.mocked(reservationsApi.importJobStatus).mockRejectedValue({ response: { status: 404 } })++ render(<BackgroundTasksWidget />)++ await waitFor(() => expect(useBackgroundTasksStore.getState().tasks).toHaveLength(0))+ })++ it('FE-W4BGT-015: a non-404 failure keeps the card', async () => {+ useBackgroundTasksStore.setState({ tasks: [task({ status: 'running', items: undefined })] })+ vi.mocked(reservationsApi.importJobStatus).mockRejectedValue({ response: { status: 500 } })++ render(<BackgroundTasksWidget />)++ await waitFor(() => expect(reservationsApi.importJobStatus).toHaveBeenCalled())+ expect(useBackgroundTasksStore.getState().tasks).toHaveLength(1)+ })+})++describe('BackgroundTasksWidget — AI retry', () => {+ const withFiles = () => task({+ items: [], sourceFiles: [new File(['%PDF'], 'voucher.pdf', { type: 'application/pdf' })],+ })++ it('FE-W4BGT-016: offers the AI retry only when the feature is on', async () => {+ vi.mocked(healthApi.features).mockResolvedValue({ aiParsing: true } as never)+ useBackgroundTasksStore.setState({ tasks: [withFiles()] })++ render(<BackgroundTasksWidget />)++ expect(await screen.findByRole('button', { name: /AI/i })).toBeInTheDocument()+ })++ it('FE-W4BGT-017: hides the retry when the feature probe fails', async () => {+ vi.mocked(healthApi.features).mockRejectedValue(new Error('down'))+ useBackgroundTasksStore.setState({ tasks: [withFiles()] })++ render(<BackgroundTasksWidget />)++ await waitFor(() => expect(healthApi.features).toHaveBeenCalled())+ expect(screen.queryByRole('button', { name: /AI/i })).toBeNull()+ })++ it('FE-W4BGT-018: hides the retry on a job that already ran with force-ai', async () => {+ vi.mocked(healthApi.features).mockResolvedValue({ aiParsing: true } as never)+ useBackgroundTasksStore.setState({ tasks: [task({ items: [], mode: 'force-ai', sourceFiles: [new File([''], 'a.pdf')] })] })++ render(<BackgroundTasksWidget />)++ await waitFor(() => expect(healthApi.features).toHaveBeenCalled())+ expect(screen.queryByRole('button', { name: /AI/i })).toBeNull()+ })++ it('FE-W4BGT-019: retrying swaps the card for the new force-ai job', async () => {+ vi.mocked(healthApi.features).mockResolvedValue({ aiParsing: true } as never)+ vi.mocked(reservationsApi.importBookingAsync).mockResolvedValue({ jobId: 'j2' } as never)+ useBackgroundTasksStore.setState({ tasks: [withFiles()] })+ render(<BackgroundTasksWidget />)++ fireEvent.click(await screen.findByRole('button', { name: /AI/i }))++ await waitFor(() => {+ const tasks = useBackgroundTasksStore.getState().tasks+ expect(tasks).toHaveLength(1)+ expect(tasks[0]).toMatchObject({ id: 'j2', mode: 'force-ai', tripId: 't1' })+ })+ })++ it('FE-W4BGT-020: a refused retry surfaces the server error on the original card', async () => {+ vi.mocked(healthApi.features).mockResolvedValue({ aiParsing: true } as never)+ vi.mocked(reservationsApi.importBookingAsync).mockRejectedValue({ response: { data: { error: 'No model configured' } } })+ useBackgroundTasksStore.setState({ tasks: [withFiles()] })+ render(<BackgroundTasksWidget />)++ fireEvent.click(await screen.findByRole('button', { name: /AI/i }))++ expect(await screen.findByText('No model configured')).toBeInTheDocument()+ })+})diff --git a/client/src/components/Budget/BudgetPanelAddItemRow.test.tsx b/client/src/components/Budget/BudgetPanelAddItemRow.test.tsxnew file mode 100644index 000000000..f65a3d135--- /dev/null+++ b/client/src/components/Budget/BudgetPanelAddItemRow.test.tsx@@ -0,0 +1,119 @@+// FE-W4AIR-001 to FE-W4AIR-009+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { render, screen, fireEvent } from '../../../tests/helpers/render'+import AddItemRow from './BudgetPanelAddItemRow'++const t = (key: string) => key++function setup() {+ const onAdd = vi.fn()+ const utils = render(<table><tbody><AddItemRow onAdd={onAdd} t={t} /></tbody></table>)+ return { onAdd, ...utils }+}++const nameInput = () => screen.getByPlaceholderText('budget.newEntry')+const priceInput = () => screen.getByPlaceholderText('0,00')+const noteInput = () => screen.getByPlaceholderText('budget.table.note')+const numberInputs = () => screen.getAllByPlaceholderText('-')++beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true })+})++afterEach(() => {+ vi.useRealTimers()+})++describe('BudgetPanelAddItemRow', () => {+ it('FE-W4AIR-001: the add button stays disabled until a name is typed', () => {+ setup()+ const button = screen.getByRole('button', { name: 'reservations.add' })++ expect(button).toBeDisabled()+ fireEvent.change(nameInput(), { target: { value: 'Ferry' } })+ expect(button).toBeEnabled()+ })++ it('FE-W4AIR-002: submits the trimmed name with parsed numbers', () => {+ const { onAdd } = setup()++ fireEvent.change(nameInput(), { target: { value: ' Ferry ' } })+ fireEvent.change(priceInput(), { target: { value: '129,90' } })+ fireEvent.change(numberInputs()[0], { target: { value: '2' } })+ fireEvent.change(numberInputs()[1], { target: { value: '3' } })+ fireEvent.change(noteInput(), { target: { value: ' one way ' } })+ fireEvent.click(screen.getByRole('button', { name: 'reservations.add' }))++ expect(onAdd).toHaveBeenCalledWith({+ name: 'Ferry', total_price: 129.9, persons: 2, days: 3, note: 'one way', expense_date: null,+ })+ })++ it('FE-W4AIR-003: falls back to zero price and null optionals', () => {+ const { onAdd } = setup()++ fireEvent.change(nameInput(), { target: { value: 'Ferry' } })+ fireEvent.click(screen.getByRole('button', { name: 'reservations.add' }))++ expect(onAdd).toHaveBeenCalledWith({+ name: 'Ferry', total_price: 0, persons: null, days: null, note: null, expense_date: null,+ })+ })++ it('FE-W4AIR-004: ignores a whitespace-only name', () => {+ const { onAdd } = setup()++ fireEvent.change(nameInput(), { target: { value: ' ' } })+ fireEvent.keyDown(nameInput(), { key: 'Enter' })++ expect(onAdd).not.toHaveBeenCalled()+ })++ it('FE-W4AIR-005: Enter in any field submits the row', () => {+ const { onAdd } = setup()+ fireEvent.change(nameInput(), { target: { value: 'Ferry' } })++ fireEvent.keyDown(priceInput(), { key: 'Enter' })+ expect(onAdd).toHaveBeenCalledTimes(1)+ })++ it('FE-W4AIR-006: a non-Enter key does not submit', () => {+ const { onAdd } = setup()+ fireEvent.change(nameInput(), { target: { value: 'Ferry' } })++ fireEvent.keyDown(nameInput(), { key: 'a' })++ expect(onAdd).not.toHaveBeenCalled()+ })++ it('FE-W4AIR-007: clears the row and refocuses the name field after adding', () => {+ setup()+ fireEvent.change(nameInput(), { target: { value: 'Ferry' } })+ fireEvent.change(priceInput(), { target: { value: '12' } })++ fireEvent.click(screen.getByRole('button', { name: 'reservations.add' }))++ expect(nameInput()).toHaveValue('')+ expect(priceInput()).toHaveValue('')+ vi.advanceTimersByTime(60)+ expect(nameInput()).toHaveFocus()+ })++ it('FE-W4AIR-008: pasting a formatted amount normalizes the separators', () => {+ setup()++ fireEvent.paste(priceInput(), { clipboardData: { getData: () => '1.234,56 EUR' } })+ expect(priceInput()).toHaveValue('1234.56')++ fireEvent.paste(priceInput(), { clipboardData: { getData: () => '$2,345.67' } })+ expect(priceInput()).toHaveValue('2345.67')+ })++ it('FE-W4AIR-009: pasting a separator-free amount keeps the digits', () => {+ setup()++ fireEvent.paste(priceInput(), { clipboardData: { getData: () => 'EUR 4200' } })++ expect(priceInput()).toHaveValue('4200')+ })+})diff --git a/client/src/components/Budget/BudgetPanelCategoryTable.test.tsx b/client/src/components/Budget/BudgetPanelCategoryTable.test.tsxnew file mode 100644index 000000000..da7a57e70--- /dev/null+++ b/client/src/components/Budget/BudgetPanelCategoryTable.test.tsx@@ -0,0 +1,609 @@+// FE-W4BCT-001 to FE-W4BCT-053+import type { CSSProperties } from 'react'+import { describe, it, expect, vi, beforeEach } from 'vitest'+import type { BudgetItem } from '../../types'+import { render, screen, fireEvent, createEvent, within } from '../../../tests/helpers/render'+import BudgetCategoryTable from './BudgetPanelCategoryTable'+import type { TripMember } from './BudgetPanelMemberChips'++const contribFor = vi.fn((_id: number) => [] as unknown[])++vi.mock('../Plugins/PluginContributions', () => ({+ usePluginViewContributions: () => contribFor,+ PluginCardFooter: ({ items }: { items: unknown[] }) => <div data-testid="plugin-footer">{items.length}</div>,+}))++const TRIP_MEMBERS: TripMember[] = [+ { id: 1, username: 'ada', avatar_url: null },+ { id: 2, username: 'bob', avatar_url: null },+]++function budgetItem(overrides: Partial<BudgetItem> = {}): BudgetItem {+ return {+ id: 1, trip_id: 7, category: 'Food', name: 'Ferry', total_price: 100,+ persons: 2, days: 5, note: null, expense_date: null, reservation_id: null, members: [],+ ...overrides,+ } as unknown as BudgetItem+}++type Props = Parameters<typeof BudgetCategoryTable>[0]++function setup(overrides: Partial<Props> = {}, items: BudgetItem[] = [budgetItem()]) {+ const spies = {+ setEditingCat: vi.fn(),+ setDragCat: vi.fn(),+ setDragOverCat: vi.fn(),+ setDragItem: vi.fn(),+ setDragOverItem: vi.fn(),+ setDragItemCat: vi.fn(),+ reorderBudgetCategories: vi.fn(async () => {}),+ reorderBudgetItems: vi.fn(async () => {}),+ handleRenameCategory: vi.fn(async () => {}),+ handleDeleteCategory: vi.fn(async () => {}),+ handleDeleteItem: vi.fn(async () => {}),+ handleUpdateField: vi.fn(async () => {}),+ handleAddItem: vi.fn(async () => {}),+ setBudgetItemMembers: vi.fn(async () => ({ members: [], item: {} })),+ toggleBudgetMemberPaid: vi.fn(async () => {}),+ }+ const props = {+ cat: 'Food',+ grouped: new Map([['Food', items]]),+ categoryColor: () => '#ef4444',+ canEdit: true,+ editingCat: null,+ dragCat: null,+ dragOverCat: null,+ dragItem: null,+ dragOverItem: null,+ dragItemCat: null,+ categoryNames: ['Transport', 'Food', 'Hotels'],+ tripId: 7,+ currency: 'EUR',+ locale: 'en-US',+ t: (key: string) => key,+ fmt: (v: number | null | undefined, cur: string) => `${v ?? '-'} ${cur}`,+ hasMultipleMembers: false,+ tripMembers: TRIP_MEMBERS,+ th: {} as CSSProperties,+ td: {} as CSSProperties,+ ...spies,+ ...overrides,+ } as unknown as Props++ const utils = render(<BudgetCategoryTable {...props} />)+ return { ...spies, ...utils }+}++/** dragleave carrying a relatedTarget — jsdom lacks DragEvent, so fireEvent drops it. */+function dragLeaveInto(target: Element, relatedTarget: Element) {+ const event = createEvent.dragLeave(target)+ Object.defineProperty(event, 'relatedTarget', { value: relatedTarget })+ fireEvent(target, event)+}++beforeEach(() => {+ contribFor.mockReset()+ contribFor.mockReturnValue([])+})++describe('BudgetCategoryTable — header', () => {+ it('FE-W4BCT-001: shows the category name and the summed subtotal', () => {+ setup({}, [budgetItem(), budgetItem({ id: 2, total_price: 50 })])++ expect(screen.getByText('Food')).toBeInTheDocument()+ expect(screen.getByText('150 EUR')).toBeInTheDocument()+ })++ it('FE-W4BCT-002: treats a priceless item as zero in the subtotal', () => {+ const { container } = setup({}, [budgetItem({ total_price: null } as Partial<BudgetItem>)])++ // The subtotal sits in the black category header, before the table.+ expect(container.querySelectorAll('span')[1]).toHaveTextContent('0 EUR')+ })++ it('FE-W4BCT-003: renders an empty category with only the add row', () => {+ setup({ grouped: new Map() } as Partial<Props>)++ expect(screen.getByPlaceholderText('budget.newEntry')).toBeInTheDocument()+ expect(screen.queryByDisplayValue('Ferry')).toBeNull()+ })++ it('FE-W4BCT-004: the pencil starts renaming the category', () => {+ const { setEditingCat } = setup()++ fireEvent.click(screen.getAllByRole('button')[0])++ expect(setEditingCat).toHaveBeenCalledWith({ name: 'Food', value: 'Food' })+ })++ it('FE-W4BCT-005: Enter in the rename input commits and closes the editor', () => {+ const { handleRenameCategory, setEditingCat } = setup({ editingCat: { name: 'Food', value: 'Groceries' } })+ const input = screen.getByDisplayValue('Groceries')++ fireEvent.keyDown(input, { key: 'Enter' })++ expect(handleRenameCategory).toHaveBeenCalledWith('Food', 'Groceries')+ expect(setEditingCat).toHaveBeenCalledWith(null)+ })++ it('FE-W4BCT-006: blurring the rename input commits it', () => {+ const { handleRenameCategory } = setup({ editingCat: { name: 'Food', value: 'Groceries' } })++ fireEvent.blur(screen.getByDisplayValue('Groceries'))++ expect(handleRenameCategory).toHaveBeenCalledWith('Food', 'Groceries')+ })++ it('FE-W4BCT-007: Escape abandons the rename', () => {+ const { handleRenameCategory, setEditingCat } = setup({ editingCat: { name: 'Food', value: 'Groceries' } })++ fireEvent.keyDown(screen.getByDisplayValue('Groceries'), { key: 'Escape' })++ expect(handleRenameCategory).not.toHaveBeenCalled()+ expect(setEditingCat).toHaveBeenCalledWith(null)+ })++ it('FE-W4BCT-008: typing updates the pending rename value', () => {+ const { setEditingCat } = setup({ editingCat: { name: 'Food', value: 'Food' } })++ fireEvent.change(screen.getByDisplayValue('Food'), { target: { value: 'Fuel' } })++ expect(setEditingCat).toHaveBeenCalledWith({ name: 'Food', value: 'Fuel' })+ })++ it('FE-W4BCT-009: the trash button deletes the category', () => {+ const { handleDeleteCategory } = setup()++ fireEvent.click(screen.getByTitle('budget.deleteCategory'))++ expect(handleDeleteCategory).toHaveBeenCalledWith('Food')+ })++ it('FE-W4BCT-010: a read-only table hides every editing affordance', () => {+ setup({ canEdit: false })++ expect(screen.queryByTitle('budget.deleteCategory')).toBeNull()+ expect(screen.queryByTitle('common.delete')).toBeNull()+ expect(screen.queryByPlaceholderText('budget.newEntry')).toBeNull()+ expect(document.querySelectorAll('[draggable="true"]')).toHaveLength(0)+ })+})++describe('BudgetCategoryTable — rows', () => {+ it('FE-W4BCT-011: derives the per-person, per-day and per-person-day figures', () => {+ setup({}, [budgetItem({ total_price: 100, persons: 2, days: 5 })])++ expect(screen.getByText('50 EUR')).toBeInTheDocument()+ expect(screen.getByText('20 EUR')).toBeInTheDocument()+ expect(screen.getByText('10 EUR')).toBeInTheDocument()+ })++ it('FE-W4BCT-012: blanks the per-person columns for a custom member split', () => {+ setup({}, [budgetItem({+ total_price: 100, persons: 2, days: 5,+ members: [{ user_id: 1, username: 'ada', amount: 70 }, { user_id: 2, username: 'bob', amount: 30 }],+ } as unknown as Partial<BudgetItem>)])++ // per-day still resolves; per-person and per-person-day are dashed out.+ expect(screen.getByText('20 EUR')).toBeInTheDocument()+ expect(screen.getAllByText('-').length).toBeGreaterThanOrEqual(2)+ })++ it('FE-W4BCT-013: deleting a row reports its id', () => {+ const { handleDeleteItem } = setup()++ fireEvent.click(screen.getByTitle('common.delete'))++ expect(handleDeleteItem).toHaveBeenCalledWith(1)+ })++ it('FE-W4BCT-014: editing the name cell saves through handleUpdateField', () => {+ const { handleUpdateField } = setup()++ fireEvent.click(screen.getByText('Ferry'))+ const input = screen.getByDisplayValue('Ferry')+ fireEvent.change(input, { target: { value: 'Bus' } })+ fireEvent.keyDown(input, { key: 'Enter' })++ expect(handleUpdateField).toHaveBeenCalledWith(1, 'name', 'Bus')+ })++ it('FE-W4BCT-015: a reservation-linked row locks the name cell', () => {+ setup({}, [budgetItem({ reservation_id: 42 } as Partial<BudgetItem>)])++ fireEvent.click(screen.getByText('Ferry'))++ expect(screen.queryByDisplayValue('Ferry')).toBeNull()+ expect(screen.getByText('Ferry')).not.toHaveAttribute('title')+ })++ it('FE-W4BCT-016: the persons cell coerces the entry to an integer', () => {+ const { handleUpdateField } = setup()++ fireEvent.click(screen.getByText('2'))+ const input = screen.getByDisplayValue('2')+ fireEvent.change(input, { target: { value: '4.7' } })+ fireEvent.keyDown(input, { key: 'Enter' })++ expect(handleUpdateField).toHaveBeenCalledWith(1, 'persons', 4)+ })++ it('FE-W4BCT-017: clearing the days cell stores null', () => {+ const { handleUpdateField } = setup()++ fireEvent.click(screen.getByText('5'))+ const input = screen.getByDisplayValue('5')+ fireEvent.change(input, { target: { value: '' } })+ fireEvent.keyDown(input, { key: 'Enter' })++ expect(handleUpdateField).toHaveBeenCalledWith(1, 'days', null)+ })++ it('FE-W4BCT-018: swaps the persons cell for member chips on a multi-member trip', () => {+ setup({ hasMultipleMembers: true }, [budgetItem({ members: [{ user_id: 1, username: 'ada', paid: 0 }] } as unknown as Partial<BudgetItem>)])++ // One chip in the persons column and one in the mobile stack under the name.+ expect(screen.getAllByText('A')).toHaveLength(2)+ })++ it('FE-W4BCT-019: shows the raw expense date instead of a picker when read-only', () => {+ setup({ canEdit: false }, [budgetItem({ expense_date: '2026-06-15' } as Partial<BudgetItem>)])++ expect(screen.getByText('2026-06-15')).toBeInTheDocument()+ })++ it('FE-W4BCT-020: falls back to an em dash for a read-only row without a date', () => {+ setup({ canEdit: false })++ expect(screen.getByText('—')).toBeInTheDocument()+ })++ it('FE-W4BCT-021: appends a plugin footer row when a plugin contributes', () => {+ contribFor.mockReturnValue([{ kind: 'column' }])+ setup()++ expect(screen.getByTestId('plugin-footer')).toHaveTextContent('1')+ })++ it('FE-W4BCT-022: adding an item routes the payload into the category', () => {+ const { handleAddItem } = setup()++ fireEvent.change(screen.getByPlaceholderText('budget.newEntry'), { target: { value: 'Taxi' } })+ fireEvent.click(screen.getByTitle('reservations.add'))++ expect(handleAddItem).toHaveBeenCalledWith('Food', expect.objectContaining({ name: 'Taxi' }))+ })+})++describe('BudgetCategoryTable — drag and drop', () => {+ it('FE-W4BCT-023: the category handle starts and ends a category drag', () => {+ const { setDragCat, setDragOverCat, container } = setup()+ const handle = container.querySelectorAll('[draggable="true"]')[0] as HTMLElement++ fireEvent.dragStart(handle, { dataTransfer: { effectAllowed: '', setData: vi.fn() } })+ expect(setDragCat).toHaveBeenCalledWith('Food')++ fireEvent.dragEnd(handle)+ expect(setDragCat).toHaveBeenLastCalledWith(null)+ expect(setDragOverCat).toHaveBeenCalledWith(null)+ })++ it('FE-W4BCT-024: dragging another category over this one marks the drop line', () => {+ const { setDragOverCat, container } = setup({ dragCat: 'Transport' })++ fireEvent.dragOver(container.firstElementChild!, { dataTransfer: { dropEffect: '' } })++ expect(setDragOverCat).toHaveBeenCalledWith('Food')+ })++ it('FE-W4BCT-025: ignores a drag-over from the same category or from an item', () => {+ const same = setup({ dragCat: 'Food' })+ fireEvent.dragOver(same.container.firstElementChild!, { dataTransfer: { dropEffect: '' } })+ expect(same.setDragOverCat).not.toHaveBeenCalled()++ const item = setup({ dragCat: 'Transport', dragItem: 5 })+ fireEvent.dragOver(item.container.firstElementChild!, { dataTransfer: { dropEffect: '' } })+ expect(item.setDragOverCat).not.toHaveBeenCalled()+ })++ it('FE-W4BCT-026: dropping a category reorders the list around this one', () => {+ const { reorderBudgetCategories, setDragCat, container } = setup({ dragCat: 'Hotels' })++ fireEvent.drop(container.firstElementChild!)++ expect(reorderBudgetCategories).toHaveBeenCalledWith(7, ['Transport', 'Hotels', 'Food'])+ expect(setDragCat).toHaveBeenCalledWith(null)+ })++ it('FE-W4BCT-027: dropping a category on itself only clears the drag state', () => {+ const { reorderBudgetCategories, setDragOverCat, container } = setup({ dragCat: 'Food' })++ fireEvent.drop(container.firstElementChild!)++ expect(reorderBudgetCategories).not.toHaveBeenCalled()+ expect(setDragOverCat).toHaveBeenCalledWith(null)+ })++ it('FE-W4BCT-028: leaving the category clears the drop marker', () => {+ const { setDragOverCat, container } = setup({ dragCat: 'Transport' })++ fireEvent.dragLeave(container.firstElementChild!, { relatedTarget: document.body })++ expect(setDragOverCat).toHaveBeenCalledWith(null)+ })++ it('FE-W4BCT-029: dragging a row over a sibling marks it as the target', () => {+ const rows = [budgetItem(), budgetItem({ id: 2, name: 'Bus' })]+ const { setDragOverItem, container } = setup({ dragItem: 2, dragItemCat: 'Food' }, rows)++ fireEvent.dragOver(container.querySelectorAll('tbody tr')[0], { dataTransfer: { dropEffect: '' } })++ expect(setDragOverItem).toHaveBeenCalledWith(1)+ })++ it('FE-W4BCT-030: dropping a row reorders the ids inside the category', () => {+ const rows = [budgetItem(), budgetItem({ id: 2, name: 'Bus' }), budgetItem({ id: 3, name: 'Taxi' })]+ const { reorderBudgetItems, setDragItem, container } = setup({ dragItem: 3, dragItemCat: 'Food' }, rows)++ fireEvent.drop(container.querySelectorAll('tbody tr')[0])++ expect(reorderBudgetItems).toHaveBeenCalledWith(7, [3, 1, 2])+ expect(setDragItem).toHaveBeenCalledWith(null)+ })++ it('FE-W4BCT-031: a row from another category is not reordered here', () => {+ const { reorderBudgetItems, container } = setup({ dragItem: 9, dragItemCat: 'Transport' })++ fireEvent.drop(container.querySelectorAll('tbody tr')[0])++ expect(reorderBudgetItems).not.toHaveBeenCalled()+ })++ it('FE-W4BCT-032: the row handle starts and ends an item drag', () => {+ const { setDragItem, setDragItemCat, container } = setup()+ const handle = container.querySelectorAll('[draggable="true"]')[1] as HTMLElement++ fireEvent.dragStart(handle, { dataTransfer: { effectAllowed: '' } })+ expect(setDragItem).toHaveBeenCalledWith(1)+ expect(setDragItemCat).toHaveBeenCalledWith('Food')++ fireEvent.dragEnd(handle)+ expect(setDragItem).toHaveBeenLastCalledWith(null)+ expect(setDragItemCat).toHaveBeenLastCalledWith(null)+ })++ it('FE-W4BCT-033: leaving a row clears the item drop marker', () => {+ const { setDragOverItem, container } = setup()++ fireEvent.dragLeave(container.querySelectorAll('tbody tr')[0], { relatedTarget: document.body })++ expect(setDragOverItem).toHaveBeenCalledWith(null)+ })++ it('FE-W4BCT-034: dims the dragged category and marks the drop line', () => {+ const dragged = setup({ dragCat: 'Food' })+ expect((dragged.container.firstElementChild as HTMLElement).style.opacity).toBe('0.4')++ const over = setup({ dragCat: 'Transport', dragOverCat: 'Food' })+ const marker = within(over.container.firstElementChild as HTMLElement).getAllByRole('generic')+ expect(marker.length).toBeGreaterThan(0)+ expect((over.container.firstElementChild as HTMLElement).firstElementChild).toHaveStyle({ height: '4px' })+ })++ it('FE-W4BCT-035: dims the dragged row and outlines the drop target', () => {+ const dragged = setup({ dragItem: 1 })+ expect((dragged.container.querySelector('tbody tr') as HTMLElement).style.opacity).toBe('0.4')++ const over = setup({ dragOverItem: 1 })+ expect((over.container.querySelector('tbody tr') as HTMLElement).style.boxShadow).toBe('inset 4px 0 0 0 var(--accent)')+ })++ it('FE-W4BCT-036: the table body accepts a category drop only while one is being dragged', () => {+ const dragging = setup({ dragCat: 'Transport' })+ const activeTransfer = { dropEffect: '' }+ fireEvent.dragOver(dragging.container.querySelector('table')!.parentElement!, { dataTransfer: activeTransfer })+ expect(activeTransfer.dropEffect).toBe('move')++ const idle = setup()+ const idleTransfer = { dropEffect: '' }+ fireEvent.dragOver(idle.container.querySelector('table')!.parentElement!, { dataTransfer: idleTransfer })+ expect(idleTransfer.dropEffect).toBe('')+ })++ it('FE-W4BCT-037: a row accepts a dragged category without becoming an item drop target', () => {+ const { setDragOverItem, container } = setup({ dragCat: 'Transport' })+ const transfer = { dropEffect: '' }++ fireEvent.dragOver(container.querySelectorAll('tbody tr')[0], { dataTransfer: transfer })++ expect(transfer.dropEffect).toBe('move')+ expect(setDragOverItem).not.toHaveBeenCalled()+ })++ it('FE-W4BCT-038: moving between a row and its own cells keeps the drop marker', () => {+ const { setDragOverItem, setDragOverCat, container } = setup({ dragCat: 'Transport', dragItem: 2, dragItemCat: 'Food' })+ const row = container.querySelectorAll('tbody tr')[0]++ // jsdom has no DragEvent, so relatedTarget has to be attached by hand.+ dragLeaveInto(row, row.querySelector('td')!)+ dragLeaveInto(container.firstElementChild as HTMLElement, container.querySelector('table')!)++ expect(setDragOverItem).not.toHaveBeenCalled()+ expect(setDragOverCat).not.toHaveBeenCalled()+ })+})++describe('BudgetCategoryTable — hover affordances', () => {+ it('FE-W4BCT-039: the rename pencil brightens while hovered', () => {+ setup()+ const pencil = screen.getAllByRole('button')[0]++ fireEvent.mouseEnter(pencil)+ expect(pencil.style.color).toBe('rgb(255, 255, 255)')++ fireEvent.mouseLeave(pencil)+ expect(pencil.style.color).toBe('rgba(255, 255, 255, 0.4)')+ })++ it('FE-W4BCT-040: the delete-category button fades in while hovered', () => {+ setup()+ const trash = screen.getByTitle('budget.deleteCategory')++ fireEvent.mouseEnter(trash)+ expect(trash.style.opacity).toBe('1')++ fireEvent.mouseLeave(trash)+ expect(trash.style.opacity).toBe('0.6')+ })++ it('FE-W4BCT-041: a row highlights while hovered', () => {+ const { container } = setup()+ const row = container.querySelector('tbody tr') as HTMLElement++ fireEvent.mouseEnter(row)+ expect(row.style.background).toBe('var(--bg-hover)')++ fireEvent.mouseLeave(row)+ expect(row.style.background).toBe('transparent')+ })++ it('FE-W4BCT-042: the delete-row button turns red while hovered', () => {+ setup()+ const trash = screen.getByTitle('common.delete')++ fireEvent.mouseEnter(trash)+ expect(trash.style.color).toBe('rgb(239, 68, 68)')++ fireEvent.mouseLeave(trash)+ expect(trash.style.color).toBe('rgb(209, 213, 219)')+ })+})++describe('BudgetCategoryTable — remaining cells', () => {+ it('FE-W4BCT-043: editing the total saves the parsed number', () => {+ const { handleUpdateField } = setup()++ fireEvent.click(screen.getByText('100.00'))+ const input = screen.getByDisplayValue('100')+ fireEvent.change(input, { target: { value: '120,50' } })+ fireEvent.keyDown(input, { key: 'Enter' })++ expect(handleUpdateField).toHaveBeenCalledWith(1, 'total_price', 120.5)+ })++ it('FE-W4BCT-044: a zero-decimal currency drops the decimals from the amount placeholder', () => {+ setup({ currency: 'JPY' }, [budgetItem({ total_price: null } as Partial<BudgetItem>)])++ expect(screen.getByText('0')).toBeInTheDocument()+ expect(screen.queryByText('0,00')).toBeNull()+ })++ it('FE-W4BCT-045: editing the note saves it', () => {+ const { handleUpdateField } = setup({}, [budgetItem({ note: 'Return trip' } as Partial<BudgetItem>)])++ fireEvent.click(screen.getByText('Return trip'))+ const input = screen.getByDisplayValue('Return trip')+ fireEvent.change(input, { target: { value: 'One way' } })+ fireEvent.keyDown(input, { key: 'Enter' })++ expect(handleUpdateField).toHaveBeenCalledWith(1, 'note', 'One way')+ })++ it('FE-W4BCT-046: picking a day from the date cell stores the ISO date', () => {+ const { handleUpdateField, container } = setup({}, [budgetItem({ expense_date: '2026-06-15' } as Partial<BudgetItem>)])+ const dateCell = container.querySelectorAll('tbody tr')[0].querySelectorAll('td')[7]++ fireEvent.click(dateCell.querySelector('button')!)+ const day20 = screen.getAllByRole('button').find(b => b.textContent?.trim() === '20')+ fireEvent.click(day20!)++ expect(handleUpdateField).toHaveBeenCalledWith(1, 'expense_date', '2026-06-20')+ })++ it('FE-W4BCT-047: clearing the date cell stores null', () => {+ const { handleUpdateField, container } = setup({}, [budgetItem({ expense_date: '2026-06-15' } as Partial<BudgetItem>)])+ const dateCell = container.querySelectorAll('tbody tr')[0].querySelectorAll('td')[7]++ fireEvent.click(dateCell.querySelector('button')!)+ fireEvent.click(screen.getByLabelText('Clear date'))++ expect(handleUpdateField).toHaveBeenCalledWith(1, 'expense_date', null)+ })++ it('FE-W4BCT-048: a non-numeric persons entry stores null', () => {+ const { handleUpdateField } = setup()++ fireEvent.click(screen.getByText('2'))+ const input = screen.getByDisplayValue('2')+ fireEvent.change(input, { target: { value: 'abc' } })+ fireEvent.keyDown(input, { key: 'Enter' })++ expect(handleUpdateField).toHaveBeenCalledWith(1, 'persons', null)+ })++ it('FE-W4BCT-049: zero days is stored as null rather than 0', () => {+ const { handleUpdateField } = setup()++ fireEvent.click(screen.getByText('5'))+ const input = screen.getByDisplayValue('5')+ fireEvent.change(input, { target: { value: '0' } })+ fireEvent.keyDown(input, { key: 'Enter' })++ expect(handleUpdateField).toHaveBeenCalledWith(1, 'days', null)+ })++ it('FE-W4BCT-050: an item without persons, days or members dashes out every derived column', () => {+ const { container } = setup({}, [budgetItem({ persons: null, days: null, members: undefined } as unknown as Partial<BudgetItem>)])+ const cells = container.querySelectorAll('tbody tr')[0].querySelectorAll('td')++ // per person, per day, per person-day — none of them is derivable.+ expect(cells[4]).toHaveTextContent('-')+ expect(cells[5]).toHaveTextContent('-')+ expect(cells[6]).toHaveTextContent('-')+ expect(screen.queryByText('100.00 EUR')).toBeNull()+ })+})++describe('BudgetCategoryTable — member chips', () => {+ const withMembers = () => setup(+ { hasMultipleMembers: true },+ [budgetItem({ members: [{ user_id: 1, username: 'ada', paid: 0 }] } as unknown as Partial<BudgetItem>)],+ )++ it('FE-W4BCT-051: tapping a chip toggles that member’s paid flag', () => {+ const { toggleBudgetMemberPaid } = withMembers()++ // The chip is rendered twice: the mobile stack under the name and the persons column.+ const chips = screen.getAllByText('A')+ fireEvent.click(chips[0])+ fireEvent.click(chips[1])++ expect(toggleBudgetMemberPaid).toHaveBeenCalledTimes(2)+ expect(toggleBudgetMemberPaid).toHaveBeenCalledWith(7, 1, 1, true)+ })++ it('FE-W4BCT-052: picking a member from either chip dropdown sets the item members', () => {+ const { setBudgetItemMembers, container } = withMembers()+ // The mobile stack under the name and the persons column both carry an editor.+ const editors = container.querySelectorAll('td button')++ fireEvent.click(editors[0])+ fireEvent.click(screen.getByText('bob'))+ fireEvent.click(editors[1])+ fireEvent.click(screen.getByText('bob'))++ expect(setBudgetItemMembers).toHaveBeenCalledTimes(2)+ expect(setBudgetItemMembers).toHaveBeenCalledWith(7, 1, [1, 2])+ })++ it('FE-W4BCT-053: read-only member chips expose no editing controls', () => {+ setup(+ { hasMultipleMembers: true, canEdit: false },+ [budgetItem({ members: [{ user_id: 1, username: 'ada', paid: 1 }] } as unknown as Partial<BudgetItem>)],+ )++ expect(screen.getAllByText('A')).toHaveLength(2)+ expect(document.querySelectorAll('table button')).toHaveLength(0)+ })+})diff --git a/client/src/components/Budget/BudgetPanelInlineEditCell.test.tsx b/client/src/components/Budget/BudgetPanelInlineEditCell.test.tsxnew file mode 100644index 000000000..8a191633c--- /dev/null+++ b/client/src/components/Budget/BudgetPanelInlineEditCell.test.tsx@@ -0,0 +1,166 @@+// FE-W4IEC-001 to FE-W4IEC-016+import { describe, it, expect, vi } from 'vitest'+import { render, screen, fireEvent } from '../../../tests/helpers/render'+import InlineEditCell from './BudgetPanelInlineEditCell'++function setup(props: Partial<Parameters<typeof InlineEditCell>[0]> = {}) {+ const onSave = vi.fn()+ const utils = render(<InlineEditCell value="Ferry" onSave={onSave} locale="en-US" {...props} />)+ return { onSave, ...utils }+}++function paste(input: HTMLElement, text: string) {+ fireEvent.paste(input, { clipboardData: { getData: () => text } })+}++describe('InlineEditCell — display', () => {+ it('FE-W4IEC-001: shows the raw text value', () => {+ setup()+ expect(screen.getByText('Ferry')).toBeInTheDocument()+ })++ it('FE-W4IEC-002: formats a number with the given decimals and locale', () => {+ setup({ value: 1234.5, type: 'number' })+ expect(screen.getByText('1,234.50')).toBeInTheDocument()+ })++ it('FE-W4IEC-003: honours a custom decimal count', () => {+ setup({ value: 12, type: 'number', decimals: 0 })+ expect(screen.getByText('12')).toBeInTheDocument()+ })++ it('FE-W4IEC-004: falls back to the placeholder, then to a dash', () => {+ const { unmount } = setup({ value: null, placeholder: 'Add note' })+ expect(screen.getByText('Add note')).toBeInTheDocument()+ unmount()++ setup({ value: null })+ expect(screen.getByText('-')).toBeInTheDocument()+ })++ it('FE-W4IEC-005: exposes the edit tooltip and hover feedback when editable', () => {+ const { container } = setup({ editTooltip: 'Click to edit' })+ const cell = container.firstElementChild as HTMLElement++ expect(cell).toHaveAttribute('title', 'Click to edit')+ fireEvent.mouseEnter(cell)+ expect(cell.style.background).toBe('var(--bg-hover)')+ fireEvent.mouseLeave(cell)+ expect(cell.style.background).toBe('transparent')+ })++ it('FE-W4IEC-006: a read-only cell has no tooltip, no hover and cannot be opened', () => {+ const { container } = setup({ readOnly: true, editTooltip: 'Click to edit' })+ const cell = container.firstElementChild as HTMLElement++ expect(cell).not.toHaveAttribute('title')+ fireEvent.mouseEnter(cell)+ expect(cell.style.background).toBe('')++ fireEvent.click(cell)+ expect(screen.queryByRole('textbox')).toBeNull()+ })++ it('FE-W4IEC-007: centres the content when the caller centres the text', () => {+ const { container } = setup({ style: { textAlign: 'center' } })++ expect((container.firstElementChild as HTMLElement).style.justifyContent).toBe('center')+ })+})++describe('InlineEditCell — editing', () => {+ it('FE-W4IEC-008: clicking opens a focused, pre-selected input', () => {+ const { container } = setup()+ fireEvent.click(container.firstElementChild!)++ const input = screen.getByRole('textbox') as HTMLInputElement+ expect(input).toHaveValue('Ferry')+ expect(input).toHaveFocus()+ })++ it('FE-W4IEC-009: Enter saves the changed value', () => {+ const { onSave, container } = setup()+ fireEvent.click(container.firstElementChild!)++ const input = screen.getByRole('textbox')+ fireEvent.change(input, { target: { value: 'Bus' } })+ fireEvent.keyDown(input, { key: 'Enter' })++ expect(onSave).toHaveBeenCalledWith('Bus')+ expect(screen.queryByRole('textbox')).toBeNull()+ })++ it('FE-W4IEC-010: blur saves and an unchanged value does not fire onSave', () => {+ const { onSave, container } = setup()+ fireEvent.click(container.firstElementChild!)++ fireEvent.blur(screen.getByRole('textbox'))++ expect(onSave).not.toHaveBeenCalled()+ })++ it('FE-W4IEC-011: Escape restores the original value without saving', () => {+ const { onSave, container } = setup()+ fireEvent.click(container.firstElementChild!)++ const input = screen.getByRole('textbox')+ fireEvent.change(input, { target: { value: 'Bus' } })+ fireEvent.keyDown(input, { key: 'Escape' })++ expect(onSave).not.toHaveBeenCalled()+ expect(screen.getByText('Ferry')).toBeInTheDocument()+ })++ it('FE-W4IEC-012: a numeric cell parses a comma decimal and uses a decimal keypad', () => {+ const { onSave, container } = setup({ value: 10, type: 'number' })+ fireEvent.click(container.firstElementChild!)++ const input = screen.getByRole('textbox')+ expect(input).toHaveAttribute('inputmode', 'decimal')+ fireEvent.change(input, { target: { value: '12,50' } })+ fireEvent.keyDown(input, { key: 'Enter' })++ expect(onSave).toHaveBeenCalledWith(12.5)+ })++ it('FE-W4IEC-013: an unparseable numeric entry saves null', () => {+ const { onSave, container } = setup({ value: 10, type: 'number' })+ fireEvent.click(container.firstElementChild!)++ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'abc' } })+ fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter' })++ expect(onSave).toHaveBeenCalledWith(null)+ })++ it('FE-W4IEC-014: pasting a formatted amount normalizes separators', () => {+ const { container } = setup({ value: 0, type: 'number' })+ fireEvent.click(container.firstElementChild!)+ const input = screen.getByRole('textbox')++ paste(input, '1.234,56 EUR')+ expect(input).toHaveValue('1234.56')++ paste(input, '$2,345.67')+ expect(input).toHaveValue('2345.67')+ })++ it('FE-W4IEC-015: pasting a separator-free amount keeps the digits', () => {+ const { container } = setup({ value: 0, type: 'number' })+ fireEvent.click(container.firstElementChild!)+ const input = screen.getByRole('textbox')++ paste(input, 'EUR 4200')+ expect(input).toHaveValue('4200')+ })++ it('FE-W4IEC-016: a text cell leaves pasted content to the browser', () => {+ const { container } = setup()+ fireEvent.click(container.firstElementChild!)+ const input = screen.getByRole('textbox')++ paste(input, '1.234,56')++ expect(input).toHaveValue('Ferry')+ })+})diff --git a/client/src/components/Budget/BudgetPanelMemberChips.test.tsx b/client/src/components/Budget/BudgetPanelMemberChips.test.tsxnew file mode 100644index 000000000..50c913999--- /dev/null+++ b/client/src/components/Budget/BudgetPanelMemberChips.test.tsx@@ -0,0 +1,178 @@+// FE-W4BMC-001 to FE-W4BMC-016+import { describe, it, expect, vi } from 'vitest'+import type { BudgetItemMember } from '../../types'+import { render, screen, fireEvent } from '../../../tests/helpers/render'+import BudgetMemberChips, { ChipWithTooltip, type TripMember } from './BudgetPanelMemberChips'++const TRIP_MEMBERS: TripMember[] = [+ { id: 1, username: 'ada', avatar_url: '/uploads/avatars/ada.png' },+ { id: 2, username: 'bob', avatar_url: null },+]++function member(overrides: Partial<BudgetItemMember> = {}): BudgetItemMember {+ return { user_id: 1, username: 'ada', avatar_url: null, paid: 0, ...overrides } as unknown as BudgetItemMember+}++function setup(props: Partial<Parameters<typeof BudgetMemberChips>[0]> = {}) {+ const onSetMembers = vi.fn()+ const onTogglePaid = vi.fn()+ const utils = render(+ <BudgetMemberChips members={[member()]} tripMembers={TRIP_MEMBERS} onSetMembers={onSetMembers} onTogglePaid={onTogglePaid} {...props} />,+ )+ return { onSetMembers, onTogglePaid, ...utils }+}++describe('ChipWithTooltip', () => {+ it('FE-W4BMC-001: falls back to the uppercased initial', () => {+ const { container } = render(<ChipWithTooltip label="ada" avatarUrl={null} />)++ expect(container.firstElementChild).toHaveTextContent('A')+ })++ it('FE-W4BMC-002: renders the avatar when one is given', () => {+ const { container } = render(<ChipWithTooltip label="ada" avatarUrl="/uploads/avatars/ada.png" />)++ expect(container.querySelector('img')).toHaveAttribute('src', '/uploads/avatars/ada.png')+ })++ it('FE-W4BMC-003: hovering portals a name tooltip and leaving removes it', () => {+ const { container } = render(<ChipWithTooltip label="Ada Lovelace" avatarUrl={null} />)+ const chip = container.firstElementChild as HTMLElement++ fireEvent.mouseEnter(chip)+ expect(screen.getByText('Ada Lovelace')).toBeInTheDocument()++ fireEvent.mouseLeave(chip)+ expect(screen.queryByText('Ada Lovelace')).toBeNull()+ })++ it('FE-W4BMC-004: a paid chip turns green and the tooltip carries a Paid tag', () => {+ const { container } = render(<ChipWithTooltip label="ada" avatarUrl={null} paid />)+ const chip = container.firstElementChild as HTMLElement++ expect(chip.style.border).toBe('2px solid rgb(34, 197, 94)')+ fireEvent.mouseEnter(chip)+ expect(screen.getByText('Paid')).toBeInTheDocument()+ })++ it('FE-W4BMC-005: only a clickable chip gets the pointer cursor', () => {+ const onClick = vi.fn()+ const { container, unmount } = render(<ChipWithTooltip label="ada" avatarUrl={null} onClick={onClick} />)+ const chip = container.firstElementChild as HTMLElement++ expect(chip.style.cursor).toBe('pointer')+ fireEvent.click(chip)+ expect(onClick).toHaveBeenCalledOnce()+ unmount()++ const plain = render(<ChipWithTooltip label="ada" avatarUrl={null} />)+ expect((plain.container.firstElementChild as HTMLElement).style.cursor).toBe('default')+ })+})++describe('BudgetMemberChips', () => {+ it('FE-W4BMC-006: renders one chip per assigned member plus the picker button', () => {+ setup({ members: [member(), member({ user_id: 2, username: 'bob' })] })++ expect(screen.getByText('A')).toBeInTheDocument()+ expect(screen.getByText('B')).toBeInTheDocument()+ expect(screen.getByRole('button')).toBeInTheDocument()+ })++ it('FE-W4BMC-007: uses the people icon while nobody is assigned and the pencil afterwards', () => {+ const { container, unmount } = setup({ members: [] })+ expect(container.querySelector('.lucide-users')).not.toBeNull()+ unmount()++ const withMembers = setup()+ expect(withMembers.container.querySelector('.lucide-pencil')).not.toBeNull()+ })++ it('FE-W4BMC-008: clicking a chip toggles that member paid flag', () => {+ const { onTogglePaid } = setup()++ fireEvent.click(screen.getByText('A'))++ expect(onTogglePaid).toHaveBeenCalledWith(1, true)+ })++ it('FE-W4BMC-009: clicking an already-paid chip clears the flag', () => {+ const { onTogglePaid } = setup({ members: [member({ paid: 1 })] })++ fireEvent.click(screen.getByText('A'))++ expect(onTogglePaid).toHaveBeenCalledWith(1, false)+ })++ it('FE-W4BMC-010: a read-only strip has no picker and no paid toggling', () => {+ const { onTogglePaid } = setup({ readOnly: true })++ expect(screen.queryByRole('button')).toBeNull()+ fireEvent.click(screen.getByText('A'))+ expect(onTogglePaid).not.toHaveBeenCalled()+ })++ it('FE-W4BMC-011: the picker lists every trip member and marks the assigned ones', () => {+ setup()+ fireEvent.click(screen.getByRole('button'))++ const rows = screen.getAllByRole('button').slice(1)+ expect(rows).toHaveLength(2)+ expect(rows[0]).toHaveTextContent('ada')+ expect(rows[0].querySelector('.lucide-check')).not.toBeNull()+ expect(rows[1].querySelector('.lucide-check')).toBeNull()+ expect(rows[0].querySelector('img')).toHaveAttribute('src', '/uploads/avatars/ada.png')+ expect(rows[1]).toHaveTextContent('B')+ })++ it('FE-W4BMC-012: picking an unassigned member adds them', () => {+ const { onSetMembers } = setup()+ fireEvent.click(screen.getByRole('button'))++ fireEvent.click(screen.getAllByRole('button')[2])++ expect(onSetMembers).toHaveBeenCalledWith([1, 2])+ })++ it('FE-W4BMC-013: picking an assigned member removes them', () => {+ const { onSetMembers } = setup()+ fireEvent.click(screen.getByRole('button'))++ fireEvent.click(screen.getAllByRole('button')[1])++ expect(onSetMembers).toHaveBeenCalledWith([])+ })++ it('FE-W4BMC-014: a mousedown outside closes the picker, inside keeps it', () => {+ setup()+ const trigger = screen.getByRole('button')+ fireEvent.click(trigger)++ fireEvent.mouseDown(screen.getAllByRole('button')[1])+ expect(screen.getAllByRole('button')).toHaveLength(3)++ fireEvent.mouseDown(trigger)+ expect(screen.getAllByRole('button')).toHaveLength(3)++ fireEvent.mouseDown(document.body)+ expect(screen.getAllByRole('button')).toHaveLength(1)+ })++ it('FE-W4BMC-015: the trigger toggles the picker closed again', () => {+ setup()+ const trigger = screen.getByRole('button')++ fireEvent.click(trigger)+ expect(screen.getAllByRole('button')).toHaveLength(3)++ fireEvent.click(trigger)+ expect(screen.getAllByRole('button')).toHaveLength(1)+ })++ it('FE-W4BMC-016: the non-compact variant renders larger chips', () => {+ setup({ compact: false })++ expect(screen.getByText('A')).toHaveStyle({ width: '30px' })+ expect((screen.getByRole('button') as HTMLElement).style.width).toBe('28px')+ })+})diff --git a/client/src/components/Budget/BudgetPanelPieChart.test.tsx b/client/src/components/Budget/BudgetPanelPieChart.test.tsxnew file mode 100644index 000000000..884287378--- /dev/null+++ b/client/src/components/Budget/BudgetPanelPieChart.test.tsx@@ -0,0 +1,54 @@+// FE-W4PIE-001 to FE-W4PIE-006+import { describe, it, expect } from 'vitest'+import { render, screen } from '../../../tests/helpers/render'+import PieChart from './BudgetPanelPieChart'++const SEGMENTS = [+ { label: 'Food', value: 300, color: '#ef4444' },+ { label: 'Hotels', value: 100, color: '#3b82f6' },+]++describe('BudgetPanelPieChart', () => {+ it('FE-W4PIE-001: renders nothing without segments', () => {+ const { container } = render(<PieChart segments={[]} totalLabel="1.200 €" />)+ expect(container).toBeEmptyDOMElement()+ })++ it('FE-W4PIE-002: renders nothing when every segment is zero', () => {+ const { container } = render(+ <PieChart segments={[{ label: 'Food', value: 0, color: '#ef4444' }]} totalLabel="0 €" />,+ )+ expect(container).toBeEmptyDOMElement()+ })++ it('FE-W4PIE-003: turns the segment shares into consecutive conic-gradient stops', () => {+ const { container } = render(<PieChart segments={SEGMENTS} totalLabel="400 €" />)+ const pie = container.querySelector('.trek-pie-reveal') as HTMLElement++ expect(pie.style.background).toBe('conic-gradient(rgb(239, 68, 68) 0deg 270deg, rgb(59, 130, 246) 270deg 360deg)')+ })++ it('FE-W4PIE-004: shows the total label in the donut hole', () => {+ render(<PieChart segments={SEGMENTS} totalLabel="400 €" />)++ expect(screen.getByText('400 €')).toBeInTheDocument()+ })++ it('FE-W4PIE-005: defaults to a 200px pie with a 55% hole', () => {+ const { container } = render(<PieChart segments={SEGMENTS} totalLabel="400 €" />)+ const root = container.firstElementChild as HTMLElement+ const hole = screen.getByText('400 €').parentElement as HTMLElement++ expect(root.style.width).toBe('200px')+ expect(Math.round(parseFloat(hole.style.width))).toBe(110)+ })++ it('FE-W4PIE-006: scales pie and hole from the size prop', () => {+ const { container } = render(<PieChart segments={SEGMENTS} size={120} totalLabel="400 €" />)+ const root = container.firstElementChild as HTMLElement+ const hole = screen.getByText('400 €').parentElement as HTMLElement++ expect(root.style.height).toBe('120px')+ expect(Math.round(parseFloat(hole.style.height))).toBe(66)+ })+})diff --git a/client/src/components/Collab/CollabChatMessages.test.tsx b/client/src/components/Collab/CollabChatMessages.test.tsxnew file mode 100644index 000000000..9edd8f37b--- /dev/null+++ b/client/src/components/Collab/CollabChatMessages.test.tsx@@ -0,0 +1,300 @@+// FE-W5CCM-001 to FE-W5CCM-022+// ChatMessages is a pure presentational component — every piece of state arrives+// as a prop from useCollabChat, so the tests drive it directly instead of going+// through CollabChat (that path is covered in CollabChat.test.tsx).++vi.mock('./CollabChatLinkPreview', () => ({+ LinkPreview: ({ url, onLoad }: { url: string; onLoad?: () => void }) => (+ <button type="button" data-testid={`preview-${url}`} onClick={() => onLoad?.()}>+ preview+ </button>+ ),+}))++import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render'+import { ChatMessages } from './CollabChatMessages'++interface ChatMsg {+ id: number+ user_id: number+ username: string+ text: string+ created_at: string+ user_avatar?: string | null+ reply_text?: string | null+ reply_username?: string | null+ reply_to?: number | null+ reactions?: { emoji: string; count: number; users: { user_id: number; username: string }[] }[]+ _deleted?: boolean+}++const currentUser = { id: 1, username: 'me' }++function buildMsg(overrides: Partial<ChatMsg> = {}): ChatMsg {+ return {+ id: 1,+ user_id: 2,+ username: 'alice',+ text: 'hello',+ created_at: '2025-06-01T10:00:00.000Z',+ reactions: [],+ ...overrides,+ }+}++interface Handles {+ setHoveredId: ReturnType<typeof vi.fn>+ setReplyTo: ReturnType<typeof vi.fn>+ setReactMenu: ReturnType<typeof vi.fn>+ handleDelete: ReturnType<typeof vi.fn>+ handleReact: ReturnType<typeof vi.fn>+ handleLoadMore: ReturnType<typeof vi.fn>+ scrollToBottom: ReturnType<typeof vi.fn>+}++function renderMessages(+ messages: ChatMsg[],+ overrides: Record<string, unknown> = {},+): Handles {+ const handles: Handles = {+ setHoveredId: vi.fn(),+ setReplyTo: vi.fn(),+ setReactMenu: vi.fn(),+ handleDelete: vi.fn(),+ handleReact: vi.fn(),+ handleLoadMore: vi.fn(),+ scrollToBottom: vi.fn(),+ }+ const props = {+ currentUser,+ tripId: 1,+ t: (key: string) => key,+ is12h: false,+ canEdit: true,+ messages,+ loading: false,+ hasMore: false,+ loadingMore: false,+ hoveredId: null,+ deletingIds: new Set<number>(),+ scrollRef: { current: null },+ isAtBottom: { current: false },+ checkAtBottom: vi.fn(),+ isOwn: (m: ChatMsg) => String(m.user_id) === String(currentUser.id),+ isEmojiOnly: (text: string) => /^\p{Extended_Pictographic}$/u.test(text),+ ...handles,+ ...overrides,+ }+ render(<ChatMessages {...props} />)+ return handles+}++describe('ChatMessages', () => {+ it('FE-W5CCM-001: renders the empty state when there are no messages', () => {+ renderMessages([])+ expect(screen.getByText('collab.chat.empty')).toBeInTheDocument()+ expect(screen.queryByRole('button')).not.toBeInTheDocument()+ })++ it('FE-W5CCM-002: the load-more button reports its loading state and calls back', () => {+ const { handleLoadMore } = renderMessages([buildMsg()], { hasMore: true })+ const btn = screen.getByRole('button', { name: 'collab.chat.loadMore' })+ fireEvent.click(btn)+ expect(handleLoadMore).toHaveBeenCalledTimes(1)+ })++ it('FE-W5CCM-003: the load-more button is disabled and shows an ellipsis while loading', () => {+ renderMessages([buildMsg()], { hasMore: true, loadingMore: true })+ const btn = screen.getByText('...').closest('button')+ expect(btn).toBeDisabled()+ })++ it('FE-W5CCM-004: a deleted message renders the placeholder line with its author', () => {+ renderMessages([buildMsg({ _deleted: true })])+ expect(screen.getByText(/collab\.chat\.deletedMessage/)).toBeInTheDocument()+ expect(screen.queryByText('hello')).not.toBeInTheDocument()+ })++ it('FE-W5CCM-005: the deleted placeholder falls back to English when the key is missing', () => {+ renderMessages([buildMsg({ _deleted: true })], {+ t: (key: string) => (key === 'collab.chat.deletedMessage' ? '' : key),+ })+ expect(screen.getByText(/deleted a message/)).toBeInTheDocument()+ })++ it('FE-W5CCM-006: a message not at the end of its group keeps the rounded tail', () => {+ renderMessages([+ buildMsg({ id: 1, user_id: 1, username: 'me', text: 'first' }),+ buildMsg({ id: 2, user_id: 1, username: 'me', text: 'second' }),+ ])+ const first = screen.getByText('first').closest('div[style]')!+ const last = screen.getByText('second').closest('div[style]')!+ expect(first.getAttribute('style')).toContain('border-radius: 18px 18px 18px 18px')+ expect(last.getAttribute('style')).toContain('border-radius: 18px 18px 4px 18px')+ })++ it('FE-W5CCM-007: the avatar image is rendered for a foreign author who has one', () => {+ renderMessages([buildMsg({ user_avatar: '/uploads/avatars/alice.png' })])+ const avatar = document.querySelector('img[src="/uploads/avatars/alice.png"]')+ expect(avatar).toBeInTheDocument()+ })++ it('FE-W5CCM-008: the avatar initial falls back to a question mark without a username', () => {+ renderMessages([buildMsg({ username: '' })])+ expect(screen.getByText('?')).toBeInTheDocument()+ })++ it('FE-W5CCM-009: hovering a bubble reports the hovered id and clears it on leave', () => {+ const { setHoveredId } = renderMessages([buildMsg({ id: 7 })])+ const bubble = screen.getByText('hello').closest('div[style="position: relative;"]')!+ fireEvent.mouseEnter(bubble)+ expect(setHoveredId).toHaveBeenCalledWith(7)+ fireEvent.mouseLeave(bubble)+ expect(setHoveredId).toHaveBeenLastCalledWith(null)+ })++ it('FE-W5CCM-010: the hover actions become visible for the hovered message only', () => {+ renderMessages(+ [buildMsg({ id: 1, text: 'one' }), buildMsg({ id: 2, text: 'two' })],+ { hoveredId: 1 },+ )+ const actions = screen.getAllByTitle('collab.chat.reply').map(b => b.parentElement!)+ expect(actions[0].getAttribute('style')).toContain('opacity: 1')+ expect(actions[1].getAttribute('style')).toContain('opacity: 0')+ })++ it('FE-W5CCM-011: right-clicking a bubble opens the reaction menu at the cursor', () => {+ const { setReactMenu } = renderMessages([buildMsg({ id: 9 })])+ const bubble = screen.getByText('hello').closest('div[style="position: relative;"]')!+ fireEvent.contextMenu(bubble, { clientX: 120, clientY: 240 })+ expect(setReactMenu).toHaveBeenCalledWith({ msgId: 9, x: 120, y: 240 })+ })++ it('FE-W5CCM-012: right-clicking does nothing without edit rights', () => {+ const { setReactMenu } = renderMessages([buildMsg()], { canEdit: false })+ const bubble = screen.getByText('hello').closest('div[style="position: relative;"]')!+ fireEvent.contextMenu(bubble, { clientX: 10, clientY: 20 })+ expect(setReactMenu).not.toHaveBeenCalled()+ })++ it('FE-W5CCM-013: a single tap only records the tap, a double tap opens the reaction menu', () => {+ const { setReactMenu } = renderMessages([buildMsg({ id: 4 })])+ const bubble = screen.getByText('hello').closest('div[style="position: relative;"]') as HTMLElement+ fireEvent.touchEnd(bubble, { changedTouches: [{ clientX: 5, clientY: 6 }] })+ expect(setReactMenu).not.toHaveBeenCalled()+ expect(bubble.dataset.lastTap).toBeTruthy()++ fireEvent.touchEnd(bubble, { changedTouches: [{ clientX: 33, clientY: 44 }] })+ expect(setReactMenu).toHaveBeenCalledWith({ msgId: 4, x: 33, y: 44 })+ })++ it('FE-W5CCM-014: a double tap without touch coordinates does not open the menu', () => {+ const { setReactMenu } = renderMessages([buildMsg()])+ const bubble = screen.getByText('hello').closest('div[style="position: relative;"]') as HTMLElement+ fireEvent.touchEnd(bubble, { changedTouches: [] })+ fireEvent.touchEnd(bubble, { changedTouches: [] })+ expect(setReactMenu).not.toHaveBeenCalled()+ })++ it('FE-W5CCM-015: a double tap is ignored without edit rights', () => {+ const { setReactMenu } = renderMessages([buildMsg()], { canEdit: false })+ const bubble = screen.getByText('hello').closest('div[style="position: relative;"]') as HTMLElement+ fireEvent.touchEnd(bubble, { changedTouches: [{ clientX: 1, clientY: 2 }] })+ fireEvent.touchEnd(bubble, { changedTouches: [{ clientX: 1, clientY: 2 }] })+ expect(setReactMenu).not.toHaveBeenCalled()+ })++ it('FE-W5CCM-016: an own reply quote shows the quoted author and a truncated body', () => {+ const longQuote = 'q'.repeat(120)+ renderMessages([+ buildMsg({ user_id: 1, username: 'me', reply_username: 'alice', reply_text: longQuote }),+ ])+ expect(screen.getByText('alice')).toBeInTheDocument()+ expect(screen.getByText('q'.repeat(80))).toBeInTheDocument()+ })++ it('FE-W5CCM-017: a reply without stored quote data renders empty quote fields', () => {+ renderMessages([buildMsg({ reply_to: 55, reply_text: null, reply_username: null })])+ const quote = screen.getByText('hello').closest('div[style]')!.parentElement!+ // The quote block renders before the message text with both fields blank+ expect(quote.textContent).toBe('hello')+ })++ it('FE-W5CCM-018: a resolved link preview scrolls down when the view is pinned to the bottom', async () => {+ const { scrollToBottom } = renderMessages(+ [buildMsg({ text: 'look at https://example.com/a' })],+ { isAtBottom: { current: true } },+ )+ fireEvent.click(screen.getByTestId('preview-https://example.com/a'))+ await waitFor(() => expect(scrollToBottom).toHaveBeenCalledWith('smooth'))+ })++ it('FE-W5CCM-019: a resolved link preview does not scroll when the user scrolled up', async () => {+ const { scrollToBottom } = renderMessages(+ [buildMsg({ text: 'look at https://example.com/b' })],+ { isAtBottom: { current: false } },+ )+ fireEvent.click(screen.getByTestId('preview-https://example.com/b'))+ await new Promise(r => setTimeout(r, 80))+ expect(scrollToBottom).not.toHaveBeenCalled()+ })++ it('FE-W5CCM-020: the reply and delete buttons react to hover and fire their handlers', () => {+ const { setReplyTo, handleDelete } = renderMessages([+ buildMsg({ id: 3, user_id: 1, username: 'me', text: 'mine' }),+ ])+ const replyBtn = screen.getByTitle('collab.chat.reply')+ fireEvent.mouseEnter(replyBtn)+ expect(replyBtn.style.transform).toBe('scale(1.2)')+ fireEvent.mouseLeave(replyBtn)+ expect(replyBtn.style.transform).toBe('scale(1)')+ fireEvent.click(replyBtn)+ expect(setReplyTo).toHaveBeenCalledWith(expect.objectContaining({ id: 3 }))++ const deleteBtn = screen.getByTitle('common.delete')+ fireEvent.mouseEnter(deleteBtn)+ expect(deleteBtn.style.background).toBe('rgb(239, 68, 68)')+ fireEvent.mouseLeave(deleteBtn)+ expect(deleteBtn.style.background).toBe('var(--accent)')+ fireEvent.click(deleteBtn)+ expect(handleDelete).toHaveBeenCalledWith(3)+ })++ it('FE-W5CCM-021: clicking a reaction badge on an own message reacts again', () => {+ const { handleReact } = renderMessages([+ buildMsg({+ id: 8,+ user_id: 1,+ username: 'me',+ reactions: [{ emoji: '🔥', count: 2, users: [{ user_id: 1, username: 'me' }] }],+ }),+ ])+ fireEvent.click(screen.getByAltText('🔥').closest('button')!)+ expect(handleReact).toHaveBeenCalledWith(8, '🔥')+ })++ it('FE-W5CCM-022: reaction badges are inert without edit rights', () => {+ const { handleReact } = renderMessages(+ [+ buildMsg({+ reactions: [{ emoji: '👍', count: 1, users: [{ user_id: 2, username: 'alice' }] }],+ }),+ ],+ { canEdit: false },+ )+ fireEvent.click(screen.getByAltText('👍').closest('button')!)+ expect(handleReact).not.toHaveBeenCalled()+ })++ it('FE-W5CCM-023: a message being deleted collapses instead of disappearing instantly', () => {+ renderMessages([buildMsg({ id: 12 })], { deletingIds: new Set([12]) })+ const row = screen.getByText('hello').closest('div[style*="row"]')!+ expect(row.getAttribute('style')).toContain('opacity: 0')+ })++ it('FE-W5CCM-024: a single emoji message renders without a bubble background', () => {+ renderMessages([buildMsg({ text: '🎉' })])+ const big = screen.getByText('🎉')+ expect(big.getAttribute('style')).toContain('font-size: calc(40px')+ })+})diff --git a/client/src/components/Collab/CollabChatSmall.test.tsx b/client/src/components/Collab/CollabChatSmall.test.tsxnew file mode 100644index 000000000..5087f171a--- /dev/null+++ b/client/src/components/Collab/CollabChatSmall.test.tsx@@ -0,0 +1,158 @@+// FE-W4CCS-001 to FE-W4CCS-014+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render'+import type { ChatReaction } from './CollabChat.types'+import type { NoteAuthor } from './CollabNotes.types'++const linkPreview = vi.fn(async (_tripId: number, _url: string) => ({ title: 'TREK', image: null as string | null }))+vi.mock('../../api/client', () => ({ collabApi: { linkPreview: (tripId: number, url: string) => linkPreview(tripId, url) } }))++import { TwemojiImg } from './CollabChatTwemojiImg'+import { ReactionBadge } from './CollabChatReactionBadge'+import { UserAvatar } from './CollabNotesUserAvatar'+import { WebsiteThumbnail } from './CollabNotesWebsiteThumbnail'++function reaction(overrides: Partial<ChatReaction> = {}): ChatReaction {+ return { emoji: '👍', count: 1, users: [{ id: 1, username: 'ada' }], ...overrides } as unknown as ChatReaction+}++beforeEach(() => {+ linkPreview.mockReset()+ linkPreview.mockResolvedValue({ title: 'TREK', image: null })+})++describe('TwemojiImg', () => {+ it('FE-W4CCS-001: renders the twemoji asset for the codepoint', () => {+ const { container } = render(<TwemojiImg emoji="👍" />)+ const img = container.querySelector('img') as HTMLImageElement++ expect(img).toHaveAttribute('alt', '👍')+ expect(img.getAttribute('src')).toContain('/1f44d.png')+ expect(img).toHaveStyle({ width: '20px', height: '20px' })+ })++ it('FE-W4CCS-002: strips the variation selector from a multi-codepoint emoji', () => {+ const { container } = render(<TwemojiImg emoji="❤️" size={16} />)++ expect((container.querySelector('img') as HTMLImageElement).getAttribute('src')).toContain('/2764.png')+ })++ it('FE-W4CCS-003: falls back to the plain glyph when the asset fails to load', () => {+ const { container } = render(<TwemojiImg emoji="👍" size={24} />)++ fireEvent.error(container.querySelector('img')!)++ expect(container.querySelector('img')).toBeNull()+ expect(screen.getByText('👍')).toHaveStyle({ fontSize: '24px' })+ })+})++describe('ReactionBadge', () => {+ it('FE-W4CCS-004: hides the counter for a single reactor', () => {+ render(<ReactionBadge reaction={reaction()} currentUserId={1} onReact={() => {}} />)++ expect(screen.queryByText('1')).toBeNull()+ })++ it('FE-W4CCS-005: shows the counter once more than one person reacted', () => {+ render(+ <ReactionBadge+ reaction={reaction({ count: 3, users: [{ id: 1, username: 'ada' }, { id: 2, username: 'bob' }] } as Partial<ChatReaction>)}+ currentUserId={1}+ onReact={() => {}}+ />,+ )++ expect(screen.getByText('3')).toBeInTheDocument()+ })++ it('FE-W4CCS-006: clicking toggles the own reaction', () => {+ const onReact = vi.fn()+ render(<ReactionBadge reaction={reaction()} currentUserId={1} onReact={onReact} />)++ fireEvent.click(screen.getByRole('button'))++ expect(onReact).toHaveBeenCalledOnce()+ })++ it('FE-W4CCS-007: hovering portals the list of reactors and leaving removes it', () => {+ render(+ <ReactionBadge+ reaction={reaction({ users: [{ id: 1, username: 'ada' }, { id: 2, username: 'bob' }] } as Partial<ChatReaction>)}+ currentUserId={1}+ onReact={() => {}}+ />,+ )+ const badge = screen.getByRole('button')++ fireEvent.mouseEnter(badge)+ expect(screen.getByText('ada, bob')).toBeInTheDocument()++ fireEvent.mouseLeave(badge)+ expect(screen.queryByText('ada, bob')).toBeNull()+ })++ it('FE-W4CCS-008: shows no tooltip when nobody is named', () => {+ render(<ReactionBadge reaction={reaction({ users: [] } as Partial<ChatReaction>)} currentUserId={1} onReact={() => {}} />)++ fireEvent.mouseEnter(screen.getByRole('button'))++ expect(document.body.querySelectorAll('[style*="translate(-50%, -100%)"]')).toHaveLength(0)+ })+})++describe('UserAvatar', () => {+ it('FE-W4CCS-009: renders nothing without a user', () => {+ const { container } = render(<UserAvatar user={null} />)+ expect(container).toBeEmptyDOMElement()+ })++ it('FE-W4CCS-010: renders the avatar image when one is set', () => {+ const { container } = render(<UserAvatar user={{ username: 'ada', avatar: '/uploads/avatars/ada.png' } as NoteAuthor} size={20} />)+ const img = container.querySelector('img') as HTMLImageElement++ expect(img).toHaveAttribute('src', '/uploads/avatars/ada.png')+ expect(img).toHaveAttribute('alt', 'ada')+ expect(img).toHaveStyle({ width: '20px' })+ })++ it('FE-W4CCS-011: falls back to the first letter, and to ? without a name', () => {+ const { unmount } = render(<UserAvatar user={{ username: 'ada', avatar: null } as NoteAuthor} />)+ expect(screen.getByText('a')).toBeInTheDocument()+ unmount()++ render(<UserAvatar user={{ username: '', avatar: null } as NoteAuthor} />)+ expect(screen.getByText('?')).toBeInTheDocument()+ })+})++describe('WebsiteThumbnail', () => {+ it('FE-W4CCS-012: shows the domain until an OG image arrives', async () => {+ render(<WebsiteThumbnail url="https://www.liketrek.com/docs" tripId={4} color="#000" />)++ expect(screen.getByText('liketrek.com')).toBeInTheDocument()+ await waitFor(() => expect(screen.getByRole('link')).toHaveAttribute('title', 'TREK'))+ expect(linkPreview).toHaveBeenCalledWith(4, 'https://www.liketrek.com/docs')+ })++ it('FE-W4CCS-013: renders the OG image once the preview resolves', async () => {+ linkPreview.mockResolvedValue({ title: 'Docs', image: 'https://cdn.example/og.png' })+ const { container } = render(<WebsiteThumbnail url="https://example.com/a" tripId={4} color="#000" />)++ await waitFor(() => expect(container.querySelector('img')).not.toBeNull())+ expect(container.querySelector('img')).toHaveAttribute('src', 'https://cdn.example/og.png')++ // A broken OG image falls back to the domain chip.+ fireEvent.error(container.querySelector('img')!)+ expect(screen.getByText('example.com')).toBeInTheDocument()+ })++ it('FE-W4CCS-014: falls back to a link label for an unparseable url and a failing preview', async () => {+ linkPreview.mockRejectedValue(new Error('blocked'))+ render(<WebsiteThumbnail url="not a url" tripId={4} color="#000" />)++ expect(screen.getByText('link')).toBeInTheDocument()+ await waitFor(() => expect(linkPreview).toHaveBeenCalled())+ expect(screen.getByRole('link')).toHaveAttribute('title', 'not a url')+ })+})diff --git a/client/src/components/Collab/CollabNotes.helpers.test.ts b/client/src/components/Collab/CollabNotes.helpers.test.tsnew file mode 100644index 000000000..43dc9ad36--- /dev/null+++ b/client/src/components/Collab/CollabNotes.helpers.test.ts@@ -0,0 +1,65 @@+// FE-W4CNH-001 to FE-W4CNH-008+import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'+import { formatTimestamp } from './CollabNotes.helpers'++// The helper feeds t() with a key and params; echo them so the branches are visible.+const t = (key: string, params?: Record<string, number>) =>+ params ? `${key}:${Object.values(params)[0]}` : key++const NOW = new Date('2026-06-15T12:00:00Z')++beforeAll(() => {+ vi.useFakeTimers()+ vi.setSystemTime(NOW)+})++afterAll(() => {+ vi.useRealTimers()+})++function ago(minutes: number): string {+ return new Date(NOW.getTime() - minutes * 60_000).toISOString().replace('Z', '')+}++describe('formatTimestamp', () => {+ it('FE-W4CNH-001: renders an empty string for a missing timestamp', () => {+ expect(formatTimestamp(null, t, 'en')).toBe('')+ expect(formatTimestamp('', t, 'en')).toBe('')+ })++ it('FE-W4CNH-002: labels the last minute as just now', () => {+ expect(formatTimestamp(ago(0), t, 'en')).toBe('collab.chat.justNow')+ })++ it('FE-W4CNH-003: counts minutes below the hour', () => {+ expect(formatTimestamp(ago(5), t, 'en')).toBe('collab.chat.minutesAgo:5')+ expect(formatTimestamp(ago(59), t, 'en')).toBe('collab.chat.minutesAgo:59')+ })++ it('FE-W4CNH-004: counts hours below the day', () => {+ expect(formatTimestamp(ago(60), t, 'en')).toBe('collab.chat.hoursAgo:1')+ expect(formatTimestamp(ago(60 * 23), t, 'en')).toBe('collab.chat.hoursAgo:23')+ })++ it('FE-W4CNH-005: counts days below a week', () => {+ expect(formatTimestamp(ago(60 * 24), t, 'en')).toBe('collab.notes.daysAgo:1')+ expect(formatTimestamp(ago(60 * 24 * 6), t, 'en')).toBe('collab.notes.daysAgo:6')+ })++ it('FE-W4CNH-006: falls back to a localized short date beyond a week', () => {+ expect(formatTimestamp(ago(60 * 24 * 10), t, 'en-US')).toBe('Jun 5')+ })++ it('FE-W4CNH-007: treats a naive timestamp as UTC and accepts an explicit Z', () => {+ const withZ = new Date(NOW.getTime() - 5 * 60_000).toISOString()+ expect(formatTimestamp(withZ, t, 'en')).toBe('collab.chat.minutesAgo:5')+ })++ it('FE-W4CNH-008: falls back to English labels when the translation is missing', () => {+ const empty = () => ''+ expect(formatTimestamp(ago(0), empty, 'en')).toBe('just now')+ expect(formatTimestamp(ago(5), empty, 'en')).toBe('5m ago')+ expect(formatTimestamp(ago(120), empty, 'en')).toBe('2h ago')+ expect(formatTimestamp(ago(60 * 24 * 2), empty, 'en')).toBe('2d ago')+ })+})diff --git a/client/src/components/Collab/CollabNotes.test.tsx b/client/src/components/Collab/CollabNotes.test.tsxindex 73aa6c3bd..e0f109e60 100644--- a/client/src/components/Collab/CollabNotes.test.tsx+++ b/client/src/components/Collab/CollabNotes.test.tsx@@ -10,7 +10,7 @@ vi.mock('../../api/websocket', () => ({removeListener: vi.fn(),}));-import { render, screen, waitFor, act } from '../../../tests/helpers/render';+import { render, screen, waitFor, act, fireEvent, within } from '../../../tests/helpers/render';import userEvent from '@testing-library/user-event';import { http, HttpResponse } from 'msw';import { server } from '../../../tests/helpers/msw/server';@@ -19,6 +19,7 @@ import { useTripStore } from '../../store/tripStore';import { resetAllStores, seedStore } from '../../../tests/helpers/store';import { buildUser, buildTrip } from '../../../tests/helpers/factories';import CollabNotes from './CollabNotes';+import { addListener } from '../../api/websocket';const currentUser = buildUser({ id: 1, username: 'testuser' });@@ -1268,3 +1269,497 @@ describe('CollabNotes', () => {expect(document.body.innerHTML.indexOf('Pinned')).toBeLessThan(document.body.innerHTML.indexOf('Unpinned'));});});++// FE-W5CNT-001 to FE-W5CNT-026+// Fills in the load/error/attachment/category branches of useCollabNotes and the+// view modal that the smoke tests above do not reach.++type AddToast = NonNullable<typeof window.__addToast>;++const buildNote = (overrides: Record<string, unknown> = {}) => ({+ id: 1,+ trip_id: 1,+ user_id: 1,+ author_username: 'testuser',+ author_avatar: null,+ title: 'A note',+ content: 'Body text',+ category: null,+ website: null,+ color: '#3b82f6',+ pinned: false,+ files: [],+ attachments: [],+ created_at: '2025-06-01T10:00:00.000Z',+ updated_at: '2025-06-01T10:00:00.000Z',+ ...overrides,+});++function serveNotes(payload: unknown) {+ server.use(http.get('/api/trips/1/collab/notes', () => HttpResponse.json(payload)));+}++/** Serves a different payload per GET so reload-after-upload can be observed. */+function serveNotesSequence(payloads: unknown[]) {+ let call = 0;+ server.use(+ http.get('/api/trips/1/collab/notes', () => {+ const payload = payloads[Math.min(call, payloads.length - 1)];+ call += 1;+ return HttpResponse.json(payload);+ }),+ );+}++function pasteFile(name: string, type = 'image/png') {+ const file = new File(['x'], name, { type });+ fireEvent.paste(document.querySelector('form')!, {+ clipboardData: { items: [{ type, getAsFile: () => file }] },+ });+}++function wsHandler(): (msg: Record<string, unknown>) => void {+ return (addListener as ReturnType<typeof vi.fn>).mock.calls[0][0];+}++describe('CollabNotes details', () => {+ let addToast: ReturnType<typeof vi.fn<AddToast>>;+ let filesChanged: number;+ let onFilesChanged: () => void;++ beforeEach(() => {+ vi.clearAllMocks();+ localStorage.clear();+ addToast = vi.fn<AddToast>(() => 0);+ window.__addToast = addToast;+ filesChanged = 0;+ onFilesChanged = () => { filesChanged += 1; };+ window.addEventListener('collab-files-changed', onFilesChanged);+ });++ afterEach(() => {+ window.removeEventListener('collab-files-changed', onFilesChanged);+ delete window.__addToast;+ localStorage.clear();+ });++ it('FE-W5CNT-001: a corrupt category cache in localStorage is ignored', async () => {+ localStorage.setItem('collab-cats-1', '{not json');+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('No notes yet');+ });++ it('FE-W5CNT-002: a category without a stored colour falls back to the first palette entry', async () => {+ serveNotes({ notes: [buildNote({ category: 'Ideas', color: null })] });+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('A note');+ // The card chip is a span, the filter pill above the grid is a button+ const chip = screen.getAllByText('Ideas').find(el => el.tagName === 'SPAN')!;+ expect(chip.style.color).toBe('rgb(99, 102, 241)');+ });++ it('FE-W5CNT-003: without a trip id nothing is fetched and the panel stays in its loading state', () => {+ render(<CollabNotes tripId={0} currentUser={currentUser} />);+ expect(screen.getByRole('heading', { name: 'Notes' })).toBeInTheDocument();+ expect(screen.queryByText('New Note')).not.toBeInTheDocument();+ });++ it('FE-W5CNT-004: notes served as a bare array are rendered', async () => {+ serveNotes([buildNote({ title: 'Array note' })]);+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('Array note');+ });++ it('FE-W5CNT-005: an empty payload yields an empty list', async () => {+ serveNotes(null);+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('No notes yet');+ });++ it('FE-W5CNT-006: a failing load falls back to the empty state', async () => {+ server.use(+ http.get('/api/trips/1/collab/notes', () => new HttpResponse(null, { status: 500 })),+ );+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('No notes yet');+ });++ it('FE-W5CNT-007: a WebSocket create for a note already in the list does not duplicate it', async () => {+ serveNotes({ notes: [buildNote({ id: 4, title: 'Already here' })] });+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('Already here');+ const handler = wsHandler();+ await act(async () => {+ handler({ type: 'collab:note:created', note: buildNote({ id: 4, title: 'Already here' }) });+ });+ expect(screen.getAllByText('Already here')).toHaveLength(1);+ });++ it('FE-W5CNT-008: a WebSocket update only touches the matching note', async () => {+ serveNotes({+ notes: [buildNote({ id: 1, title: 'First' }), buildNote({ id: 2, title: 'Second' })],+ });+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('Second');+ const handler = wsHandler();+ await act(async () => {+ handler({ type: 'collab:note:updated', note: { id: 2, title: 'Second renamed' } });+ });+ expect(await screen.findByText('Second renamed')).toBeInTheDocument();+ expect(screen.getByText('First')).toBeInTheDocument();+ });++ it('FE-W5CNT-009: a WebSocket delete accepts a plain id and ignores events without one', async () => {+ serveNotes({ notes: [buildNote({ id: 9, title: 'Doomed' })] });+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('Doomed');+ const handler = wsHandler();+ await act(async () => { handler({ type: 'collab:note:deleted' }); });+ expect(screen.getByText('Doomed')).toBeInTheDocument();+ await act(async () => { handler({ type: 'collab:note:deleted', id: 9 }); });+ await waitFor(() => expect(screen.queryByText('Doomed')).not.toBeInTheDocument());+ });++ it('FE-W5CNT-010: an unwrapped create response is prepended to the list', async () => {+ const user = userEvent.setup();+ server.use(+ http.post('/api/trips/1/collab/notes', () =>+ HttpResponse.json(buildNote({ id: 20, title: 'Fresh note' })),+ ),+ );+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('No notes yet');+ await user.click(screen.getByText('New Note'));+ await user.type(await screen.findByPlaceholderText('Note title'), 'Fresh note');+ await user.click(screen.getByRole('button', { name: 'Create' }));+ await screen.findByText('Fresh note');+ });++ it('FE-W5CNT-011: an empty create response leaves the list untouched', async () => {+ const user = userEvent.setup();+ server.use(http.post('/api/trips/1/collab/notes', () => HttpResponse.json(null)));+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('No notes yet');+ await user.click(screen.getByText('New Note'));+ await user.type(await screen.findByPlaceholderText('Note title'), 'Ghost note');+ await user.click(screen.getByRole('button', { name: 'Create' }));+ await waitFor(() => expect(screen.queryByPlaceholderText('Note title')).not.toBeInTheDocument());+ expect(screen.getByText('No notes yet')).toBeInTheDocument();+ });++ it('FE-W5CNT-012: a failing create reports an error and keeps the modal open', async () => {+ const user = userEvent.setup();+ server.use(+ http.post('/api/trips/1/collab/notes', () => new HttpResponse(null, { status: 500 })),+ );+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('No notes yet');+ await user.click(screen.getByText('New Note'));+ await user.type(await screen.findByPlaceholderText('Note title'), 'Doomed note');+ await user.click(screen.getByRole('button', { name: 'Create' }));+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));+ expect(screen.getByPlaceholderText('Note title')).toBeInTheDocument();+ });++ it('FE-W5CNT-013: a pasted attachment is uploaded and the list is reloaded afterwards', async () => {+ const user = userEvent.setup();+ let uploaded = 0;+ serveNotesSequence([+ { notes: [] },+ { notes: [buildNote({ id: 30, title: 'With file' })] },+ ]);+ server.use(+ http.post('/api/trips/1/collab/notes', () =>+ HttpResponse.json({ note: buildNote({ id: 30, title: 'With file' }) }),+ ),+ http.post('/api/trips/1/collab/notes/30/files', () => {+ uploaded += 1;+ return HttpResponse.json({ file: { id: 1 } });+ }),+ );+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('No notes yet');+ await user.click(screen.getByText('New Note'));+ await user.type(await screen.findByPlaceholderText('Note title'), 'With file');+ pasteFile('screenshot.png');+ await user.click(screen.getByRole('button', { name: 'Create' }));+ await screen.findByText('With file');+ expect(uploaded).toBe(1);+ expect(filesChanged).toBe(1);+ });++ it('FE-W5CNT-014: a failing upload reports an error and the array-shaped reload is ignored', async () => {+ const user = userEvent.setup();+ serveNotesSequence([{ notes: [] }, [buildNote({ id: 31, title: 'Never shown' })]]);+ server.use(+ http.post('/api/trips/1/collab/notes', () =>+ HttpResponse.json({ note: buildNote({ id: 31, title: 'Upload fails' }) }),+ ),+ http.post('/api/trips/1/collab/notes/31/files', () => new HttpResponse(null, { status: 500 })),+ );+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('No notes yet');+ await user.click(screen.getByText('New Note'));+ await user.type(await screen.findByPlaceholderText('Note title'), 'Upload fails');+ pasteFile('broken.png');+ await user.click(screen.getByRole('button', { name: 'Create' }));+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));+ await waitFor(() => expect(filesChanged).toBe(1));+ expect(screen.queryByText('Never shown')).not.toBeInTheDocument();+ });++ it('FE-W5CNT-015: pinning a note applies the unwrapped response to that note only', async () => {+ const user = userEvent.setup();+ serveNotes({+ notes: [buildNote({ id: 1, title: 'Pin me' }), buildNote({ id: 2, title: 'Leave me' })],+ });+ server.use(+ http.put('/api/trips/1/collab/notes/1', () =>+ HttpResponse.json(buildNote({ id: 1, title: 'Pinned now', pinned: true })),+ ),+ );+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('Pin me');+ const pinBtn = screen.getAllByTitle('Pin')[0];+ await user.click(pinBtn);+ await screen.findByText('Pinned now');+ expect(screen.getByText('Leave me')).toBeInTheDocument();+ });++ it('FE-W5CNT-016: an empty update response leaves the note as it was', async () => {+ const user = userEvent.setup();+ serveNotes({ notes: [buildNote({ id: 1, title: 'Unchanged' })] });+ server.use(http.put('/api/trips/1/collab/notes/1', () => HttpResponse.json(null)));+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('Unchanged');+ await user.click(screen.getByTitle('Pin'));+ await waitFor(() => expect(screen.getByText('Unchanged')).toBeInTheDocument());+ expect(screen.getByTitle('Pin')).toBeInTheDocument();+ });++ it('FE-W5CNT-017: a failing edit reports an error and keeps the edit modal open', async () => {+ const user = userEvent.setup();+ serveNotes({ notes: [buildNote({ id: 3, title: 'Edit me' })] });+ server.use(+ http.put('/api/trips/1/collab/notes/3', () => new HttpResponse(null, { status: 500 })),+ );+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('Edit me');+ await user.click(screen.getByTitle('Edit'));+ const titleInput = await screen.findByDisplayValue('Edit me');+ await user.type(titleInput, ' v2');+ await user.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));+ expect(screen.getByDisplayValue('Edit me v2')).toBeInTheDocument();+ });++ it('FE-W5CNT-018: saving a new category colour rewrites every note in that category', async () => {+ const user = userEvent.setup();+ const bodies: Record<string, unknown>[] = [];+ serveNotes({ notes: [buildNote({ id: 1, title: 'Sushi', category: 'Food', color: '#ef4444' })] });+ server.use(+ http.put('/api/trips/1/collab/notes/1', async ({ request }) => {+ bodies.push((await request.json()) as Record<string, unknown>);+ return HttpResponse.json({ note: buildNote({ id: 1, title: 'Sushi', category: 'Food', color: '#10b981' }) });+ }),+ );+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('Sushi');+ await user.click(screen.getByTitle('Manage Categories'));+ const label = (await screen.findAllByText('Food')).find(el => el.title === 'Click to rename')!;+ const swatches = label.parentElement!.querySelectorAll('button');+ await user.click(swatches[3]);+ await user.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(bodies).toEqual([{ color: '#10b981' }]));+ });++ it('FE-W5CNT-019: attaching a file while editing uploads it and refreshes the note', async () => {+ const user = userEvent.setup();+ let uploaded = 0;+ serveNotesSequence([+ { notes: [buildNote({ id: 3, title: 'Edit me' })] },+ { notes: [buildNote({ id: 3, title: 'Edited', attachments: [] })] },+ ]);+ server.use(+ http.put('/api/trips/1/collab/notes/3', () =>+ HttpResponse.json({ note: buildNote({ id: 3, title: 'Edited' }) }),+ ),+ http.post('/api/trips/1/collab/notes/3/files', () => {+ uploaded += 1;+ return HttpResponse.json({ file: { id: 2 } });+ }),+ );+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('Edit me');+ await user.click(screen.getByTitle('Edit'));+ await screen.findByDisplayValue('Edit me');+ pasteFile('attachment.png');+ await user.click(screen.getByRole('button', { name: 'Save' }));+ await screen.findByText('Edited');+ expect(uploaded).toBe(1);+ expect(filesChanged).toBe(1);+ });++ it('FE-W5CNT-020: a failing upload during an edit reports an error', async () => {+ const user = userEvent.setup();+ serveNotes({ notes: [buildNote({ id: 3, title: 'Edit me' })] });+ server.use(+ http.put('/api/trips/1/collab/notes/3', () =>+ HttpResponse.json({ note: buildNote({ id: 3, title: 'Edit me' }) }),+ ),+ http.post('/api/trips/1/collab/notes/3/files', () => new HttpResponse(null, { status: 500 })),+ );+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('Edit me');+ await user.click(screen.getByTitle('Edit'));+ await screen.findByDisplayValue('Edit me');+ pasteFile('nope.png');+ await user.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));+ });++ it('FE-W5CNT-021: a failing attachment removal reports an error', async () => {+ const user = userEvent.setup();+ serveNotes({+ notes: [buildNote({+ id: 3,+ title: 'Has file',+ attachments: [{ id: 9, filename: 's.pdf', original_name: 'plan.pdf', mime_type: 'application/pdf', url: '/uploads/plan.pdf' }],+ })],+ });+ server.use(+ http.delete('/api/trips/1/collab/notes/3/files/9', () => new HttpResponse(null, { status: 500 })),+ );+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('Has file');+ await user.click(screen.getByTitle('Edit'));+ const chip = (await screen.findByText('plan.pdf')).closest('div')!;+ await user.click(chip.querySelector('button')!);+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));+ expect(filesChanged).toBe(1);+ });++ it('FE-W5CNT-022: pinned notes sort first and notes without timestamps sort last', async () => {+ serveNotes({+ notes: [+ buildNote({ id: 1, title: 'No timestamps', updated_at: null, created_at: null }),+ buildNote({ id: 2, title: 'Pinned one', pinned: true }),+ buildNote({ id: 3, title: 'Created only', updated_at: null, created_at: '2025-06-02T10:00:00.000Z' }),+ ],+ });+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('Pinned one');+ const titles = Array.from(document.querySelectorAll('span'))+ .filter(el => el.childElementCount === 0)+ .map(el => el.textContent)+ .filter(text => ['No timestamps', 'Pinned one', 'Created only'].includes(text ?? ''));+ expect(titles).toEqual(['Pinned one', 'Created only', 'No timestamps']);+ });++ it('FE-W5CNT-023: clicking the active category pill clears the filter again', async () => {+ const user = userEvent.setup();+ serveNotes({+ notes: [+ buildNote({ id: 1, title: 'Food note', category: 'Food', color: '#ef4444' }),+ buildNote({ id: 2, title: 'Plain note' }),+ ],+ });+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('Plain note');+ const pill = screen.getAllByRole('button').find(b => b.textContent === 'Food')!;+ await user.click(pill);+ await waitFor(() => expect(screen.queryByText('Plain note')).not.toBeInTheDocument());+ await user.click(pill);+ expect(await screen.findByText('Plain note')).toBeInTheDocument();+ });++ it('FE-W5CNT-024: a narrow viewport lays the grid out in a single column', async () => {+ const original = window.innerWidth;+ Object.defineProperty(window, 'innerWidth', { value: 500, writable: true, configurable: true });+ try {+ serveNotes({ notes: [buildNote({ title: 'Mobile note' })] });+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('Mobile note');+ const grid = document.querySelector('[style*="grid-template-columns"]') as HTMLElement;+ expect(grid.style.gridTemplateColumns).toBe('1fr');+ } finally {+ Object.defineProperty(window, 'innerWidth', { value: original, writable: true, configurable: true });+ }+ });++ it('FE-W5CNT-025: the expanded note closes on a backdrop click and its buttons highlight on hover', async () => {+ const user = userEvent.setup();+ serveNotes({ notes: [buildNote({ id: 5, title: 'Long note', content: 'Full body', category: 'Food', color: '#ef4444' })] });+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('Long note');+ await user.click(screen.getByTitle('collab.notes.expand'));+ const modal = await waitFor(() => {+ const md = document.querySelector('.collab-note-md-full')+ if (!md) throw new Error('view modal not open yet')+ return md.closest('div[style*="position: fixed"]') as HTMLElement+ });+ expect(within(modal).getByText('Full body')).toBeInTheDocument();++ const [editBtn, closeBtn] = Array.from(modal.querySelectorAll('button'));+ fireEvent.mouseEnter(editBtn);+ expect(editBtn.style.color).toBe('var(--text-primary)');+ fireEvent.mouseLeave(editBtn);+ expect(editBtn.style.color).toBe('var(--text-faint)');+ fireEvent.mouseEnter(closeBtn);+ expect(closeBtn.style.color).toBe('var(--text-primary)');+ fireEvent.mouseLeave(closeBtn);+ expect(closeBtn.style.color).toBe('var(--text-faint)');++ fireEvent.click(modal);+ await waitFor(() => expect(document.querySelector('.collab-note-md-full')).toBeNull());+ });++ it('FE-W5CNT-026: attachments in the expanded note open the preview and react to hover', async () => {+ const user = userEvent.setup();+ serveNotes({+ notes: [buildNote({+ id: 6,+ title: 'Trip docs',+ content: 'See attachments',+ attachments: [+ { id: 1, filename: 'a.png', original_name: 'map.png', mime_type: 'image/png', url: '/uploads/map.png' },+ { id: 2, filename: 'b.txt', original_name: 'itinerary.txt', mime_type: 'text/plain', url: '/uploads/itinerary.txt' },+ { id: 3, filename: 'c', url: '/uploads/c' },+ ],+ })],+ });+ render(<CollabNotes {...defaultProps} />);+ await screen.findByText('Trip docs');+ await user.click(screen.getByTitle('collab.notes.expand'));+ const modal = await waitFor(() => {+ const md = document.querySelector('.collab-note-md-full')+ if (!md) throw new Error('view modal not open yet')+ return md.closest('div[style*="position: fixed"]') as HTMLElement+ });++ // Unknown mime type and missing name fall back to a "?" tile+ expect(within(modal).getByText('?')).toBeInTheDocument();++ const txtTile = within(modal).getByTitle('itinerary.txt');+ expect(txtTile.style.background).toBe('var(--bg-secondary)');+ fireEvent.mouseEnter(txtTile);+ expect(txtTile.style.transform).toBe('scale(1.06)');+ fireEvent.mouseLeave(txtTile);+ expect(txtTile.style.transform).toBe('scale(1)');+ fireEvent.click(txtTile);+ // FilePreviewPortal shows a download action for non-image files+ expect(await screen.findByText('Download itinerary.txt')).toBeInTheDocument();++ const image = await waitFor(() => {+ const img = modal.querySelector('img[alt="map.png"]') as HTMLImageElement | null;+ if (!img) throw new Error('image attachment not rendered yet');+ return img;+ });+ fireEvent.mouseEnter(image);+ expect(image.style.transform).toBe('scale(1.06)');+ fireEvent.mouseLeave(image);+ expect(image.style.transform).toBe('scale(1)');+ fireEvent.click(image);+ await waitFor(() => expect(screen.queryByText('Download itinerary.txt')).not.toBeInTheDocument());+ });+});diff --git a/client/src/components/Collab/CollabNotesFormModal.test.tsx b/client/src/components/Collab/CollabNotesFormModal.test.tsxnew file mode 100644index 000000000..3e690d3fe--- /dev/null+++ b/client/src/components/Collab/CollabNotesFormModal.test.tsx@@ -0,0 +1,301 @@+// FE-W5CNF-001 to FE-W5CNF-018+// NoteFormModal takes everything it needs as props, so the tests drive it+// directly rather than through CollabNotes.++import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render'+import userEvent from '@testing-library/user-event'+import { useAuthStore } from '../../store/authStore'+import { useTripStore } from '../../store/tripStore'+import { usePermissionsStore } from '../../store/permissionsStore'+import { resetAllStores, seedStore } from '../../../tests/helpers/store'+import { buildUser, buildTrip } from '../../../tests/helpers/factories'+import { NoteFormModal } from './CollabNotesFormModal'+import type { CollabNote, NoteFile } from './CollabNotes.types'++const identity = (key: string) => key++function buildAttachment(overrides: Partial<NoteFile> = {}): NoteFile {+ return {+ id: 1,+ filename: 'stored.png',+ original_name: 'photo.png',+ mime_type: 'image/png',+ url: '/uploads/collab/photo.png',+ ...overrides,+ }+}++function buildNote(overrides: Partial<CollabNote> = {}): CollabNote {+ return {+ id: 42,+ trip_id: 1,+ title: 'Existing note',+ content: 'Existing content',+ category: 'Food',+ website: 'https://example.com',+ pinned: false,+ color: '#6366f1',+ username: 'tester',+ avatar_url: null,+ avatar: null,+ user_id: 1,+ created_at: '2025-06-01T10:00:00.000Z',+ attachments: [],+ ...overrides,+ } as CollabNote+}++interface ModalOverrides {+ note?: CollabNote | null+ onClose?: () => void+ onSubmit?: (data: Record<string, unknown>) => Promise<void>+ onDeleteFile?: (noteId: number, fileId: number) => Promise<void>+ existingCategories?: string[]+ categoryColors?: Record<string, string>+ t?: (key: string) => string+}++function renderModal(overrides: ModalOverrides = {}) {+ const onSubmit = overrides.onSubmit ?? vi.fn(async () => {})+ const onClose = overrides.onClose ?? vi.fn(() => {})+ render(+ <NoteFormModal+ note={overrides.note ?? null}+ tripId={1}+ onClose={onClose}+ onSubmit={onSubmit as unknown as React.ComponentProps<typeof NoteFormModal>['onSubmit']}+ onDeleteFile={overrides.onDeleteFile}+ existingCategories={overrides.existingCategories ?? []}+ categoryColors={overrides.categoryColors as Record<string, string>}+ getCategoryColor={(cat: string) => (cat === 'Food' ? '#ef4444' : '#6366f1')}+ t={overrides.t ?? identity}+ />,+ )+ return { onSubmit, onClose }+}++beforeEach(() => {+ resetAllStores()+ seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true })+ seedStore(useTripStore, { trip: buildTrip({ id: 1, user_id: 1 }) })+})++describe('NoteFormModal', () => {+ it('FE-W5CNF-001: falls back to an empty color map when none is supplied', () => {+ renderModal({ existingCategories: ['Food'] })+ expect(screen.getByRole('button', { name: 'Food' })).toBeInTheDocument()+ })++ it('FE-W5CNF-002: submitting with a blank title does nothing', async () => {+ const { onSubmit, onClose } = renderModal()+ const form = document.querySelector('form')!+ fireEvent.submit(form)+ await waitFor(() => expect(onSubmit).not.toHaveBeenCalled())+ expect(onClose).not.toHaveBeenCalled()+ })++ it('FE-W5CNF-003: a filled-in note is submitted trimmed and the modal closes', async () => {+ const user = userEvent.setup()+ const { onSubmit, onClose } = renderModal({ existingCategories: ['Food'] })+ await user.type(screen.getByPlaceholderText('collab.notes.titlePlaceholder'), ' Dinner ')+ await user.type(screen.getByPlaceholderText('collab.notes.contentPlaceholder'), 'Book a table')+ await user.type(screen.getByPlaceholderText('collab.notes.websitePlaceholder'), ' https://trek.test ')+ await user.click(screen.getByRole('button', { name: 'collab.notes.create' }))+ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))+ expect(onSubmit).toHaveBeenCalledWith({+ title: 'Dinner',+ content: 'Book a table',+ category: 'Food',+ color: '#ef4444',+ website: 'https://trek.test',+ _pendingFiles: [],+ })+ expect(onClose).toHaveBeenCalled()+ })++ it('FE-W5CNF-004: a note without a category submits null instead of an empty string', async () => {+ const user = userEvent.setup()+ const { onSubmit } = renderModal()+ await user.type(screen.getByPlaceholderText('collab.notes.titlePlaceholder'), 'Loose note')+ await user.click(screen.getByRole('button', { name: 'collab.notes.create' }))+ await waitFor(() => expect(onSubmit).toHaveBeenCalled())+ expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ category: null, website: null }))+ })++ it('FE-W5CNF-005: a rejected submit keeps the modal open and re-enables the button', async () => {+ const user = userEvent.setup()+ const onSubmit = vi.fn(async () => { throw new Error('boom') })+ const { onClose } = renderModal({ onSubmit })+ await user.type(screen.getByPlaceholderText('collab.notes.titlePlaceholder'), 'Fails')+ const submit = screen.getByRole('button', { name: 'collab.notes.create' })+ await user.click(submit)+ await waitFor(() => expect(onSubmit).toHaveBeenCalled())+ expect(onClose).not.toHaveBeenCalled()+ expect(submit).toBeEnabled()+ })++ it('FE-W5CNF-006: edit mode prefills the fields and uses the save label', () => {+ renderModal({ note: buildNote() })+ expect(screen.getByDisplayValue('Existing note')).toBeInTheDocument()+ expect(screen.getByDisplayValue('Existing content')).toBeInTheDocument()+ expect(screen.getByDisplayValue('https://example.com')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'collab.notes.save' })).toBeInTheDocument()+ expect(screen.getByText('collab.notes.edit')).toBeInTheDocument()+ })++ it('FE-W5CNF-007: the close button calls back without submitting', async () => {+ const user = userEvent.setup()+ const { onClose, onSubmit } = renderModal()+ const header = screen.getByText('collab.notes.new').parentElement!+ await user.click(header.querySelector('button')!)+ expect(onClose).toHaveBeenCalledTimes(1)+ expect(onSubmit).not.toHaveBeenCalled()+ })++ it('FE-W5CNF-008: picking another category marks it active and submits it', async () => {+ const user = userEvent.setup()+ const { onSubmit } = renderModal({+ existingCategories: ['Food'],+ categoryColors: { Sights: '#6366f1' },+ })+ const sights = screen.getByRole('button', { name: 'Sights' })+ expect(sights.style.background).toBe('transparent')+ await user.click(sights)+ expect(sights.style.background).toBe('rgba(99, 102, 241, 0.094)')+ await user.type(screen.getByPlaceholderText('collab.notes.titlePlaceholder'), 'Museum')+ await user.click(screen.getByRole('button', { name: 'collab.notes.create' }))+ await waitFor(() => expect(onSubmit).toHaveBeenCalled())+ expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ category: 'Sights' }))+ })++ it('FE-W5CNF-009: pasting an image attaches it as a pending file', () => {+ renderModal()+ const file = new File(['x'], 'pasted.png', { type: 'image/png' })+ fireEvent.paste(document.querySelector('form')!, {+ clipboardData: { items: [{ type: 'image/png', getAsFile: () => file }] },+ })+ expect(screen.getByText('pasted.png')).toBeInTheDocument()+ })++ it('FE-W5CNF-010: pasting a PDF after a non-file item attaches the PDF', () => {+ renderModal()+ const file = new File(['%PDF'], 'itinerary.pdf', { type: 'application/pdf' })+ fireEvent.paste(document.querySelector('form')!, {+ clipboardData: {+ items: [+ { type: 'text/plain', getAsFile: () => null },+ { type: 'application/pdf', getAsFile: () => file },+ ],+ },+ })+ expect(screen.getByText('itinerary.pdf')).toBeInTheDocument()+ })++ it('FE-W5CNF-011: a paste whose item yields no file attaches nothing', () => {+ renderModal()+ fireEvent.paste(document.querySelector('form')!, {+ clipboardData: { items: [{ type: 'image/png', getAsFile: () => null }] },+ })+ expect(screen.queryByText(/\.png$/)).not.toBeInTheDocument()+ })++ it('FE-W5CNF-012: a paste without clipboard items is ignored', () => {+ renderModal()+ fireEvent.paste(document.querySelector('form')!, { clipboardData: {} })+ expect(screen.getByPlaceholderText('collab.notes.titlePlaceholder')).toBeInTheDocument()+ })++ it('FE-W5CNF-013: without upload rights the file section is hidden and paste is ignored', () => {+ seedStore(usePermissionsStore, { permissions: { file_upload: 'admin' } })+ renderModal()+ expect(screen.queryByText('collab.notes.attachFiles')).not.toBeInTheDocument()+ const file = new File(['x'], 'blocked.png', { type: 'image/png' })+ fireEvent.paste(document.querySelector('form')!, {+ clipboardData: { items: [{ type: 'image/png', getAsFile: () => file }] },+ })+ expect(screen.queryByText('blocked.png')).not.toBeInTheDocument()+ })++ it('FE-W5CNF-014: choosing files through the picker lists them and long names are truncated', () => {+ renderModal()+ const input = document.querySelector('input[type="file"]') as HTMLInputElement+ const longName = 'an-extremely-long-attachment-name.pdf'+ fireEvent.change(input, {+ target: {+ files: [+ new File(['a'], 'short.png', { type: 'image/png' }),+ new File(['b'], longName, { type: 'application/pdf' }),+ ],+ },+ })+ expect(screen.getByText('short.png')).toBeInTheDocument()+ expect(screen.getByText(`${longName.slice(0, 17)}...`)).toBeInTheDocument()+ })++ it('FE-W5CNF-015: an empty file selection changes nothing', () => {+ renderModal()+ const input = document.querySelector('input[type="file"]') as HTMLInputElement+ fireEvent.change(input, { target: { files: [] } })+ expect(screen.queryByText(/\.png$/)).not.toBeInTheDocument()+ })++ it('FE-W5CNF-016: a pending file can be removed again', async () => {+ const user = userEvent.setup()+ renderModal()+ const input = document.querySelector('input[type="file"]') as HTMLInputElement+ fireEvent.change(input, { target: { files: [new File(['a'], 'remove-me.png', { type: 'image/png' })] } })+ const chip = screen.getByText('remove-me.png').closest('div')!+ await user.click(chip.querySelector('button')!)+ expect(screen.queryByText('remove-me.png')).not.toBeInTheDocument()+ })++ it('FE-W5CNF-017: the add button opens the hidden file picker', async () => {+ const user = userEvent.setup()+ renderModal()+ const input = document.querySelector('input[type="file"]') as HTMLInputElement+ const clickSpy = vi.spyOn(input, 'click').mockImplementation(() => {})+ await user.click(screen.getByRole('button', { name: 'files.attach' }))+ expect(clickSpy).toHaveBeenCalled()+ clickSpy.mockRestore()+ })++ it('FE-W5CNF-018: the add button falls back to an English label', () => {+ renderModal({ t: (key: string) => (key === 'files.attach' ? '' : key) })+ expect(screen.getByRole('button', { name: 'Add' })).toBeInTheDocument()+ })++ it('FE-W5CNF-019: deleting an existing attachment calls back and drops the chip', async () => {+ const user = userEvent.setup()+ const onDeleteFile = vi.fn(async () => {})+ renderModal({+ note: buildNote({+ attachments: [+ buildAttachment({ id: 7, original_name: 'a-really-long-attachment-name.pdf', mime_type: 'application/pdf' }),+ ],+ }),+ onDeleteFile,+ })+ const chip = screen.getByText('a-really-long-att...').closest('div')!+ await user.click(chip.querySelector('button')!)+ await waitFor(() => expect(onDeleteFile).toHaveBeenCalledWith(42, 7))+ expect(screen.queryByText('a-really-long-att...')).not.toBeInTheDocument()+ })++ it('FE-W5CNF-020: an attachment without a delete handler stays in the list', async () => {+ const user = userEvent.setup()+ renderModal({ note: buildNote({ attachments: [buildAttachment({ id: 9 })] }) })+ const chip = screen.getByText('photo.png').closest('div')!+ await user.click(chip.querySelector('button')!)+ expect(screen.getByText('photo.png')).toBeInTheDocument()+ })++ it('FE-W5CNF-021: an attachment without an original name renders an empty label', () => {+ renderModal({+ note: buildNote({+ attachments: [buildAttachment({ id: 11, original_name: undefined as unknown as string, mime_type: 'text/plain' })],+ }),+ })+ const section = screen.getByText('collab.notes.attachFiles').parentElement!+ expect(section.querySelectorAll('img').length).toBe(0)+ })+})diff --git a/client/src/components/Collab/CollabPanel.test.tsx b/client/src/components/Collab/CollabPanel.test.tsxindex d13217b04..ef11e68f5 100644--- a/client/src/components/Collab/CollabPanel.test.tsx+++ b/client/src/components/Collab/CollabPanel.test.tsx@@ -143,3 +143,125 @@ describe('CollabPanel', () => {expect(screen.queryByTestId('collab-notes')).not.toBeInTheDocument()})})++// FE-W5CPN-001 to FE-W5CPN-013+// The desktop branch picks a different layout for every combination of enabled+// collab features, so each combination gets its own case.+const allOff = { chat: false, notes: false, polls: false, whatsnext: false }++describe('CollabPanel feature combinations', () => {+ beforeEach(() => {+ originalInnerWidth = window.innerWidth+ resetAllStores()+ seedStore(useAuthStore, { user: buildUser() })+ })++ afterEach(() => {+ Object.defineProperty(window, 'innerWidth', { value: originalInnerWidth, writable: true, configurable: true })+ })++ it('FE-W5CPN-001: renders nothing when every collab feature is disabled', () => {+ setViewport(1280)+ const { container } = render(<CollabPanel tripId={1} collabFeatures={allOff} />)+ expect(container).toBeEmptyDOMElement()+ expect(screen.queryByRole('button')).not.toBeInTheDocument()+ })++ it('FE-W5CPN-002: chat alone fills the whole desktop panel', () => {+ setViewport(1280)+ render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, chat: true }} />)+ expect(screen.getByTestId('collab-chat')).toBeInTheDocument()+ expect(screen.queryByTestId('collab-notes')).not.toBeInTheDocument()+ expect(screen.queryByTestId('collab-polls')).not.toBeInTheDocument()+ expect(screen.queryByTestId('whats-next')).not.toBeInTheDocument()+ })++ it('FE-W5CPN-003: chat plus notes puts the notes card next to the chat column', () => {+ setViewport(1280)+ render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, chat: true, notes: true }} />)+ expect(screen.getByTestId('collab-chat')).toBeInTheDocument()+ expect(screen.getByTestId('collab-notes')).toBeInTheDocument()+ expect(screen.queryByTestId('collab-polls')).not.toBeInTheDocument()+ })++ it('FE-W5CPN-004: chat plus polls renders the polls card as the only right panel', () => {+ setViewport(1280)+ render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, chat: true, polls: true }} />)+ expect(screen.getByTestId('collab-polls')).toBeInTheDocument()+ expect(screen.queryByTestId('collab-notes')).not.toBeInTheDocument()+ expect(screen.queryByTestId('whats-next')).not.toBeInTheDocument()+ })++ it("FE-W5CPN-005: chat plus what's next renders the widget as the only right panel", () => {+ setViewport(1280)+ render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, chat: true, whatsnext: true }} />)+ expect(screen.getByTestId('whats-next')).toBeInTheDocument()+ expect(screen.queryByTestId('collab-notes')).not.toBeInTheDocument()+ expect(screen.queryByTestId('collab-polls')).not.toBeInTheDocument()+ })++ it('FE-W5CPN-006: chat plus notes and polls stacks both right panels', () => {+ setViewport(1280)+ render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, chat: true, notes: true, polls: true }} />)+ expect(screen.getByTestId('collab-notes')).toBeInTheDocument()+ expect(screen.getByTestId('collab-polls')).toBeInTheDocument()+ expect(screen.queryByTestId('whats-next')).not.toBeInTheDocument()+ })++ it("FE-W5CPN-007: chat plus polls and what's next stacks those two", () => {+ setViewport(1280)+ render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, chat: true, polls: true, whatsnext: true }} />)+ expect(screen.getByTestId('collab-polls')).toBeInTheDocument()+ expect(screen.getByTestId('whats-next')).toBeInTheDocument()+ expect(screen.queryByTestId('collab-notes')).not.toBeInTheDocument()+ })++ it('FE-W5CPN-008: notes alone fills the panel when chat is off', () => {+ setViewport(1280)+ render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, notes: true }} />)+ expect(screen.getByTestId('collab-notes')).toBeInTheDocument()+ expect(screen.queryByTestId('collab-chat')).not.toBeInTheDocument()+ })++ it('FE-W5CPN-009: polls alone fills the panel when chat is off', () => {+ setViewport(1280)+ render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, polls: true }} />)+ expect(screen.getByTestId('collab-polls')).toBeInTheDocument()+ expect(screen.queryByTestId('collab-chat')).not.toBeInTheDocument()+ })++ it("FE-W5CPN-010: what's next alone fills the panel when chat is off", () => {+ setViewport(1280)+ render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, whatsnext: true }} />)+ expect(screen.getByTestId('whats-next')).toBeInTheDocument()+ expect(screen.queryByTestId('collab-chat')).not.toBeInTheDocument()+ })++ it('FE-W5CPN-011: notes and polls share the width side by side when chat is off', () => {+ setViewport(1280)+ render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, notes: true, polls: true }} />)+ expect(screen.getByTestId('collab-notes')).toBeInTheDocument()+ expect(screen.getByTestId('collab-polls')).toBeInTheDocument()+ expect(screen.queryByTestId('collab-chat')).not.toBeInTheDocument()+ })++ it("FE-W5CPN-012: polls and what's next share the width when chat is off", () => {+ setViewport(1280)+ render(<CollabPanel tripId={1} collabFeatures={{ ...allOff, polls: true, whatsnext: true }} />)+ expect(screen.getByTestId('collab-polls')).toBeInTheDocument()+ expect(screen.getByTestId('whats-next')).toBeInTheDocument()+ expect(screen.queryByTestId('collab-notes')).not.toBeInTheDocument()+ })++ it('FE-W5CPN-013: mobile falls back to the first tab when the active one gets disabled', () => {+ setViewport(375)+ const { rerender } = render(<CollabPanel tripId={1} />)+ fireEvent.click(screen.getByRole('button', { name: /polls/i }))+ expect(screen.getByTestId('collab-polls')).toBeInTheDocument()++ rerender(<CollabPanel tripId={1} collabFeatures={{ ...allOff, notes: true, whatsnext: true }} />)+ expect(screen.getByTestId('collab-notes')).toBeInTheDocument()+ expect(screen.queryByTestId('collab-polls')).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: /polls/i })).not.toBeInTheDocument()+ })+})diff --git a/client/src/components/Collab/CollabPolls.test.tsx b/client/src/components/Collab/CollabPolls.test.tsxindex 8a526ae82..5e181ce1c 100644--- a/client/src/components/Collab/CollabPolls.test.tsx+++ b/client/src/components/Collab/CollabPolls.test.tsx@@ -10,7 +10,7 @@ vi.mock('../../api/websocket', () => ({removeListener: vi.fn(),}));-import { render, screen, waitFor } from '../../../tests/helpers/render';+import { render, screen, waitFor, fireEvent, act } from '../../../tests/helpers/render';import userEvent from '@testing-library/user-event';import { http, HttpResponse } from 'msw';import { server } from '../../../tests/helpers/msw/server';@@ -273,3 +273,405 @@ describe('CollabPolls', () => {expect(optionInputs).toHaveLength(3);});});++// FE-W5CPL-001 to FE-W5CPL-026+// Covers the deadline maths, the voter chips, the error paths of every mutation+// and the WebSocket handler branches that the smoke tests above skip.++type AddToast = NonNullable<typeof window.__addToast>;++const MINUTE = 60_000;+const HOUR = 60 * MINUTE;+const DAY = 24 * HOUR;++/** A deadline `ms` in the future, with a small buffer so the clock can tick. */+const inFuture = (ms: number) => new Date(Date.now() + ms + 10_000).toISOString();++function servePolls(polls: unknown) {+ server.use(http.get('/api/trips/1/collab/polls', () => HttpResponse.json(polls)));+}++/** Grabs the WS handler CollabPolls registered on mount. */+function wsHandler(): (msg: Record<string, unknown>) => void {+ return (addListener as ReturnType<typeof vi.fn>).mock.calls[0][0];+}++describe('CollabPolls details', () => {+ let addToast: ReturnType<typeof vi.fn<AddToast>>;++ beforeEach(() => {+ addToast = vi.fn<AddToast>(() => 0);+ window.__addToast = addToast;+ });++ afterEach(() => {+ delete window.__addToast;+ });++ it('FE-W5CPL-001: a deadline more than a day away is shown in days and hours', async () => {+ servePolls({ polls: [buildPoll({ deadline: inFuture(2 * DAY + 3 * HOUR) })] });+ render(<CollabPolls {...defaultProps} />);+ expect(await screen.findByText('2d 3h')).toBeInTheDocument();+ });++ it('FE-W5CPL-002: a deadline within the day is shown in hours and minutes', async () => {+ servePolls({ polls: [buildPoll({ deadline: inFuture(5 * HOUR + 30 * MINUTE) })] });+ render(<CollabPolls {...defaultProps} />);+ expect(await screen.findByText('5h 30m')).toBeInTheDocument();+ });++ it('FE-W5CPL-003: a deadline within the hour is shown in minutes', async () => {+ servePolls({ polls: [buildPoll({ deadline: inFuture(45 * MINUTE) })] });+ render(<CollabPolls {...defaultProps} />);+ expect(await screen.findByText('45m')).toBeInTheDocument();+ });++ it('FE-W5CPL-004: a passed deadline closes the poll and drops the countdown', async () => {+ servePolls({ polls: [buildPoll({ deadline: '2020-01-01T00:00:00.000Z' })] });+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText('Best destination?');+ expect(screen.getByText(/closed/i)).toBeInTheDocument();+ expect(screen.getByText('Paris').closest('button')).toBeDisabled();+ });++ it('FE-W5CPL-005: a poll served as a bare array is rendered', async () => {+ servePolls([buildPoll({ question: 'Array shaped?' })]);+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText('Array shaped?');+ });++ it('FE-W5CPL-006: options without a voters array count as zero votes', async () => {+ servePolls({ polls: [{ ...buildPoll(), options: [{ id: 1, text: 'Solo' }] }] });+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText('Solo');+ expect(screen.getByText('0 votes')).toBeInTheDocument();+ });++ it('FE-W5CPL-007: a poll without an options array still renders its question', async () => {+ servePolls({ polls: [{ ...buildPoll(), options: undefined }] });+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText('Best destination?');+ expect(screen.queryByText('Paris')).not.toBeInTheDocument();+ });++ it('FE-W5CPL-008: plain string options are rendered as their own label', async () => {+ servePolls({ polls: [{ ...buildPoll(), options: ['Yes', 'No'] }] });+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText('Yes');+ expect(screen.getByText('No')).toBeInTheDocument();+ });++ it('FE-W5CPL-009: a multiple-choice poll shows the multi badge and a single vote label', async () => {+ servePolls({+ polls: [buildPoll({+ multiple_choice: true,+ options: [+ { id: 1, text: 'Paris', voters: [{ user_id: 9, username: 'bob', avatar_url: null }] },+ { id: 2, text: 'Rome', voters: [] },+ ],+ })],+ });+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText('Best destination?');+ expect(screen.getByText('Multiple choice')).toBeInTheDocument();+ expect(screen.getByText('1 vote')).toBeInTheDocument();+ });++ it('FE-W5CPL-010: once the user voted the results, avatars and tooltip appear', async () => {+ servePolls({+ polls: [buildPoll({+ options: [+ {+ id: 1, text: 'Paris',+ voters: [+ { user_id: 1, username: 'testuser', avatar_url: null },+ { user_id: 2, username: 'alice', avatar_url: '/uploads/avatars/alice.png' },+ ],+ },+ { id: 2, text: 'Rome', voters: [] },+ ],+ })],+ });+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText('Paris');+ expect(screen.getByText('100%')).toBeInTheDocument();+ expect(screen.getByText('0%')).toBeInTheDocument();+ expect(document.querySelector('img[src="/uploads/avatars/alice.png"]')).toBeInTheDocument();++ const chip = screen.getByText('T');+ fireEvent.mouseEnter(chip);+ expect(await screen.findByText('testuser')).toBeInTheDocument();+ fireEvent.mouseLeave(chip);+ await waitFor(() => expect(screen.queryByText('testuser')).not.toBeInTheDocument());+ });++ it('FE-W5CPL-011: a voter without a username falls back to a question mark', async () => {+ servePolls({+ polls: [buildPoll({+ is_closed: true,+ options: [+ { id: 1, text: 'Paris', voters: [{ user_id: 4, username: '', avatar_url: null }] },+ { id: 2, text: 'Rome', voters: [] },+ ],+ })],+ });+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText('Paris');+ expect(screen.getByText('?')).toBeInTheDocument();+ });++ it('FE-W5CPL-012: hovering an open option scales it, a closed one stays put', async () => {+ servePolls({ polls: [buildPoll({ id: 1 }), buildPoll({ id: 2, question: 'Done?', is_closed: true })] });+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText('Done?');+ const [openOption, closedOption] = screen.getAllByText('Paris').map(el => el.closest('button')!);+ fireEvent.mouseEnter(openOption);+ expect(openOption.style.transform).toBe('scale(1.01)');+ fireEvent.mouseLeave(openOption);+ expect(openOption.style.transform).toBe('scale(1)');++ fireEvent.mouseEnter(closedOption);+ expect(closedOption.style.transform).toBe('');+ });++ it('FE-W5CPL-013: the closed section heading only appears next to active polls', async () => {+ servePolls({+ polls: [+ buildPoll({ id: 1, question: 'Still open?' }),+ buildPoll({ id: 2, question: 'Already done?', is_closed: true }),+ ],+ });+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText('Still open?');+ expect(screen.getByText('Already done?')).toBeInTheDocument();+ // One "Closed" badge on the poll itself plus the section heading above it+ expect(screen.getAllByText('Closed')).toHaveLength(2);+ });++ it('FE-W5CPL-014: closing a poll marks it closed and moves it out of the active list', async () => {+ let closeCalled = false;+ servePolls({ polls: [buildPoll({ id: 5 })] });+ server.use(+ http.put('/api/trips/1/collab/polls/5/close', () => {+ closeCalled = true;+ return HttpResponse.json({ success: true });+ }),+ );+ const user = userEvent.setup();+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText('Best destination?');+ await user.click(screen.getByTitle(/close/i));+ await waitFor(() => expect(closeCalled).toBe(true));+ expect(await screen.findByText(/closed/i)).toBeInTheDocument();+ expect(screen.queryByTitle(/close/i)).not.toBeInTheDocument();+ });++ it('FE-W5CPL-015: a failing close shows an error and leaves the poll open', async () => {+ servePolls({ polls: [buildPoll({ id: 5 })] });+ server.use(+ http.put('/api/trips/1/collab/polls/5/close', () => new HttpResponse(null, { status: 500 })),+ );+ const user = userEvent.setup();+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText('Best destination?');+ await user.click(screen.getByTitle(/close/i));+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));+ expect(screen.getByTitle(/close/i)).toBeInTheDocument();+ });++ it('FE-W5CPL-016: a failing delete shows an error and keeps the poll', async () => {+ servePolls({ polls: [buildPoll({ id: 6 })] });+ server.use(+ http.delete('/api/trips/1/collab/polls/6', () => new HttpResponse(null, { status: 500 })),+ );+ const user = userEvent.setup();+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText('Best destination?');+ await user.click(screen.getByTitle(/delete/i));+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));+ expect(screen.getByText('Best destination?')).toBeInTheDocument();+ });++ it('FE-W5CPL-017: a failing vote shows an error and leaves the tally alone', async () => {+ servePolls({ polls: [buildPoll({ id: 7 })] });+ server.use(+ http.post('/api/trips/1/collab/polls/7/vote', () => new HttpResponse(null, { status: 500 })),+ );+ const user = userEvent.setup();+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText('Paris');+ await user.click(screen.getByText('Paris'));+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));+ expect(screen.queryByText('100%')).not.toBeInTheDocument();+ });++ it('FE-W5CPL-018: an unwrapped vote response only replaces the poll that was voted on', async () => {+ servePolls({ polls: [buildPoll({ id: 7 }), buildPoll({ id: 8, question: 'Untouched?' })] });+ server.use(+ http.post('/api/trips/1/collab/polls/7/vote', () =>+ HttpResponse.json(buildPoll({+ id: 7,+ question: 'Voted!',+ options: [+ { id: 1, text: 'Paris', voters: [{ user_id: 1, username: 'testuser', avatar_url: null }] },+ { id: 2, text: 'Rome', voters: [] },+ ],+ })),+ ),+ );+ const user = userEvent.setup();+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText('Untouched?');+ await user.click(screen.getAllByText('Paris')[0]);+ await screen.findByText('Voted!');+ expect(screen.getByText('Untouched?')).toBeInTheDocument();+ });++ it('FE-W5CPL-019: a failing create shows an error and keeps the modal open', async () => {+ server.use(+ http.post('/api/trips/1/collab/polls', () => new HttpResponse(null, { status: 500 })),+ );+ const user = userEvent.setup();+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText(/no polls yet|collab\.polls\.empty/i);+ await user.click(screen.getByRole('button', { name: /new/i }));+ await user.type(screen.getByPlaceholderText(/what should we do/i), 'Fails?');+ const optionInputs = screen.getAllByPlaceholderText(/option/i);+ await user.type(optionInputs[0], 'A');+ await user.type(optionInputs[1], 'B');+ await user.click(screen.getByRole('button', { name: /create|collab\.polls\.create/i }));+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));+ expect(screen.getByPlaceholderText(/what should we do/i)).toBeInTheDocument();+ });++ it('FE-W5CPL-020: creating a poll that is already in the list does not duplicate it', async () => {+ servePolls({ polls: [buildPoll({ id: 12, question: 'Same poll' })] });+ server.use(+ http.post('/api/trips/1/collab/polls', () =>+ HttpResponse.json(buildPoll({ id: 12, question: 'Same poll' })),+ ),+ );+ const user = userEvent.setup();+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText('Same poll');+ await user.click(screen.getByRole('button', { name: /new/i }));+ await user.type(screen.getByPlaceholderText(/what should we do/i), 'Same poll');+ const optionInputs = screen.getAllByPlaceholderText(/option/i);+ await user.type(optionInputs[0], 'A');+ await user.type(optionInputs[1], 'B');+ await user.click(screen.getByRole('button', { name: /create|collab\.polls\.create/i }));+ await waitFor(() =>+ expect(screen.queryByPlaceholderText(/what should we do/i)).not.toBeInTheDocument(),+ );+ expect(screen.getAllByText('Same poll')).toHaveLength(1);+ });++ it('FE-W5CPL-021: submitting the create form without enough options is a no-op', async () => {+ let postCalled = false;+ server.use(+ http.post('/api/trips/1/collab/polls', () => {+ postCalled = true;+ return HttpResponse.json({ poll: buildPoll() });+ }),+ );+ const user = userEvent.setup();+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText(/no polls yet|collab\.polls\.empty/i);+ await user.click(screen.getByRole('button', { name: /new/i }));+ await user.type(screen.getByPlaceholderText(/what should we do/i), 'Not enough');+ fireEvent.submit(screen.getByPlaceholderText(/what should we do/i).closest('form')!);+ await waitFor(() => expect(screen.getByPlaceholderText(/what should we do/i)).toBeInTheDocument());+ expect(postCalled).toBe(false);+ });++ it('FE-W5CPL-022: an extra option can be removed again', async () => {+ const user = userEvent.setup();+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText(/no polls yet|collab\.polls\.empty/i);+ await user.click(screen.getByRole('button', { name: /new/i }));+ await user.click(screen.getByText(/add option/i));+ expect(screen.getAllByPlaceholderText(/option/i)).toHaveLength(3);++ const thirdRow = screen.getAllByPlaceholderText(/option/i)[2].parentElement!;+ await user.click(thirdRow.querySelector('button')!);+ expect(screen.getAllByPlaceholderText(/option/i)).toHaveLength(2);+ });++ it('FE-W5CPL-023: the multi-choice toggle flips and is sent along on create', async () => {+ let body: Record<string, unknown> | null = null;+ server.use(+ http.post('/api/trips/1/collab/polls', async ({ request }) => {+ body = (await request.json()) as Record<string, unknown>;+ return HttpResponse.json({ poll: buildPoll({ id: 30, question: 'Multi?' }) });+ }),+ );+ const user = userEvent.setup();+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText(/no polls yet|collab\.polls\.empty/i);+ await user.click(screen.getByRole('button', { name: /new/i }));++ const toggle = screen.getByText(/multiple|multi/i).previousElementSibling as HTMLElement;+ expect(toggle.style.background).toBe('var(--border-primary)');+ await user.click(toggle);+ expect(toggle.style.background).toBe('rgb(0, 122, 255)');++ await user.type(screen.getByPlaceholderText(/what should we do/i), 'Multi?');+ const optionInputs = screen.getAllByPlaceholderText(/option/i);+ await user.type(optionInputs[0], 'A');+ await user.type(optionInputs[1], 'B');+ await user.click(screen.getByRole('button', { name: /create|collab\.polls\.create/i }));+ await screen.findByText('Multi?');+ expect(body).toMatchObject({ multiple_choice: true, options: ['A', 'B'] });+ });++ it('FE-W5CPL-024: WebSocket events without a type or a known id are ignored', async () => {+ servePolls({ polls: [buildPoll({ id: 40 })] });+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText('Best destination?');+ const handler = wsHandler();+ await act(async () => {+ handler({});+ handler({ type: 'collab:poll:deleted' });+ handler({ type: 'collab:poll:created', poll: { id: 40, question: 'Best destination?' } });+ });+ expect(screen.getAllByText('Best destination?')).toHaveLength(1);+ });++ it('FE-W5CPL-025: WebSocket vote and close events update only the matching poll', async () => {+ servePolls({ polls: [buildPoll({ id: 41 }), buildPoll({ id: 42, question: 'Other poll' })] });+ render(<CollabPolls {...defaultProps} />);+ await screen.findByText('Other poll');+ const handler = wsHandler();++ await act(async () => {+ handler({ type: 'collab:poll:voted', poll: buildPoll({ id: 41, question: 'Voted live' }) });+ });+ expect(await screen.findByText('Voted live')).toBeInTheDocument();+ expect(screen.getByText('Other poll')).toBeInTheDocument();++ await act(async () => {+ handler({ type: 'collab:poll:closed', poll: { id: 41 } });+ });+ await waitFor(() => expect(screen.getAllByText('Closed')).toHaveLength(2));++ await act(async () => {+ handler({ type: 'collab:poll:deleted', poll: { id: 42 } });+ });+ await waitFor(() => expect(screen.queryByText('Other poll')).not.toBeInTheDocument());+ });++ it('FE-W5CPL-026: a poll with a live deadline starts the countdown ticker', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ try {+ servePolls({ polls: [buildPoll({ deadline: inFuture(90 * MINUTE) })] });+ const { unmount } = render(<CollabPolls {...defaultProps} />);+ await screen.findByText('1h 30m');+ await act(async () => { await vi.advanceTimersByTimeAsync(31_000); });+ expect(screen.getByText('1h 29m')).toBeInTheDocument();+ unmount();+ expect(vi.getTimerCount()).toBe(0);+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/client/src/components/Collections/AddPlaceToCollectionModal.test.tsx b/client/src/components/Collections/AddPlaceToCollectionModal.test.tsxnew file mode 100644index 000000000..c9e698c3e--- /dev/null+++ b/client/src/components/Collections/AddPlaceToCollectionModal.test.tsx@@ -0,0 +1,355 @@+// FE-COMP-ADDPLACECOL-001 to FE-COMP-ADDPLACECOL-024+import React from 'react'+import type { Mock } from 'vitest'+import { http, HttpResponse } from 'msw'+import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render'+import { server } from '../../../tests/helpers/msw/server'+import type { Category } from '@trek/shared'+import { useTranslation } from '../../i18n/TranslationContext'+import AddPlaceToCollectionModal from './AddPlaceToCollectionModal'++type Props = React.ComponentProps<typeof AddPlaceToCollectionModal>+function Harness(props: Omit<Props, 't'>): React.ReactElement {+ const { t } = useTranslation()+ return <AddPlaceToCollectionModal {...props} t={t} />+}++const categories: Category[] = [+ { id: 3, name: 'Food', color: '#f97316', icon: 'utensils' },+ { id: 4, name: 'Museum', color: '', icon: 'landmark' },+]++const mapsResult = {+ name: 'Kissa Sakaiki',+ address: 'Shibuya, Tokyo',+ lat: 35.66,+ lng: 139.7,+ google_place_id: 'gp-1',+ google_ftid: 'ft-1',+ osm_id: 'osm-1',+ website: 'https://kissa.example',+ phone: '+81 3 0000 0000',+}++type AddToast = NonNullable<typeof window.__addToast>+let addToast: Mock<AddToast>+/** Bodies POSTed to the save endpoint, newest last. */+let savedBodies: Record<string, unknown>[]++function mockSearch(places: Record<string, unknown>[]): void {+ server.use(http.post('/api/maps/search', () => HttpResponse.json({ places, source: 'nominatim' })))+}++function mockSave(response: Record<string, unknown> = { place: { id: 99 } }): void {+ server.use(+ http.post('/api/addons/collections/places', async ({ request }) => {+ savedBodies.push((await request.json()) as Record<string, unknown>)+ return HttpResponse.json(response)+ }),+ )+}++function setup(over: Partial<Omit<Props, 't'>> = {}) {+ const props: Omit<Props, 't'> = {+ isOpen: true,+ collectionId: 7,+ collectionName: 'Tokyo 2026',+ categories,+ onClose: vi.fn(),+ onAdded: vi.fn(),+ ...over,+ }+ const view = render(<Harness {...props} />)+ return { ...view, props }+}++/** Fills the one field the save button waits on. */+function typeName(value: string): void {+ fireEvent.change(screen.getByPlaceholderText('Name'), { target: { value } })+}++describe('AddPlaceToCollectionModal', () => {+ beforeEach(() => {+ addToast = vi.fn<AddToast>(() => 0)+ window.__addToast = addToast+ savedBodies = []+ mockSave()+ })++ afterEach(() => {+ delete window.__addToast+ })++ it('FE-COMP-ADDPLACECOL-001: a closed modal renders nothing', () => {+ setup({ isOpen: false })+ expect(screen.queryByRole('heading', { name: 'Add a place' })).not.toBeInTheDocument()+ })++ it('FE-COMP-ADDPLACECOL-002: renders the search, form fields and status chips', () => {+ setup()+ expect(screen.getByRole('heading', { name: 'Add a place' })).toBeInTheDocument()+ expect(screen.getByPlaceholderText('Search for a place…')).toBeInTheDocument()+ expect(screen.getByPlaceholderText('Street, City, Country')).toBeInTheDocument()+ expect(screen.getByPlaceholderText('Latitude (e.g. 48.8566)')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /Idea/ })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /Want to go/ })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /Visited/ })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /Add$/ })).toBeDisabled()+ })++ it('FE-COMP-ADDPLACECOL-003: the search button is inert until something is typed', () => {+ setup()+ expect(screen.getByRole('button', { name: /Search/ })).toBeDisabled()+ fireEvent.change(screen.getByPlaceholderText('Search for a place…'), { target: { value: 'kissa' } })+ expect(screen.getByRole('button', { name: /Search/ })).not.toBeDisabled()+ })++ it('FE-COMP-ADDPLACECOL-004: Enter runs the search and lists the results', async () => {+ mockSearch([mapsResult, { name: 'No address place' }])+ setup()+ const input = screen.getByPlaceholderText('Search for a place…')+ fireEvent.change(input, { target: { value: 'kissa' } })+ fireEvent.keyDown(input, { key: 'Enter' })++ expect(await screen.findByText('Kissa Sakaiki')).toBeInTheDocument()+ expect(screen.getByText('Shibuya, Tokyo')).toBeInTheDocument()+ expect(screen.getByText('No address place')).toBeInTheDocument()+ })++ it('FE-COMP-ADDPLACECOL-005: picking a result fills name, address and coordinates', async () => {+ mockSearch([mapsResult])+ setup()+ fireEvent.change(screen.getByPlaceholderText('Search for a place…'), { target: { value: 'kissa' } })+ fireEvent.click(screen.getByRole('button', { name: /Search/ }))+ fireEvent.click(await screen.findByRole('button', { name: /Kissa Sakaiki/ }))++ expect(screen.getByPlaceholderText('Name')).toHaveValue('Kissa Sakaiki')+ expect(screen.getByPlaceholderText('Street, City, Country')).toHaveValue('Shibuya, Tokyo')+ expect(screen.getByPlaceholderText('Latitude (e.g. 48.8566)')).toHaveValue('35.66')+ expect(screen.getByPlaceholderText('Longitude (e.g. 2.3522)')).toHaveValue('139.7')+ // The dropdown collapses once a result is taken.+ expect(screen.queryByText('Shibuya, Tokyo')).not.toBeInTheDocument()+ })++ it('FE-COMP-ADDPLACECOL-006: a result without name or coordinates leaves those fields blank', async () => {+ mockSearch([{ address: 'Somewhere' }])+ setup()+ fireEvent.change(screen.getByPlaceholderText('Search for a place…'), { target: { value: 'x' } })+ fireEvent.click(screen.getByRole('button', { name: /Search/ }))+ fireEvent.click(await screen.findByText('Somewhere'))++ expect(screen.getByPlaceholderText('Name')).toHaveValue('')+ expect(screen.getByPlaceholderText('Latitude (e.g. 48.8566)')).toHaveValue('')+ // The query keeps what the user typed when the result carries no name.+ expect(screen.getByPlaceholderText('Search for a place…')).toHaveValue('x')+ })++ it('FE-COMP-ADDPLACECOL-007: the result dropdown can be dismissed', async () => {+ mockSearch([mapsResult])+ setup()+ fireEvent.change(screen.getByPlaceholderText('Search for a place…'), { target: { value: 'kissa' } })+ fireEvent.click(screen.getByRole('button', { name: /Search/ }))+ await screen.findByText('Kissa Sakaiki')++ fireEvent.click(screen.getByRole('button', { name: 'Close' }))+ expect(screen.queryByText('Kissa Sakaiki')).not.toBeInTheDocument()+ })++ it('FE-COMP-ADDPLACECOL-008: a failing search toasts the provider error', async () => {+ server.use(http.post('/api/maps/search', () => HttpResponse.json({ error: 'Places API disabled' }, { status: 500 })))+ setup()+ fireEvent.change(screen.getByPlaceholderText('Search for a place…'), { target: { value: 'kissa' } })+ fireEvent.click(screen.getByRole('button', { name: /Search/ }))+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Places API disabled', 'error', undefined))+ })++ it('FE-COMP-ADDPLACECOL-009: a search response without places yields no dropdown', async () => {+ server.use(http.post('/api/maps/search', () => HttpResponse.json({ source: 'nominatim' })))+ setup()+ fireEvent.change(screen.getByPlaceholderText('Search for a place…'), { target: { value: 'kissa' } })+ fireEvent.click(screen.getByRole('button', { name: /Search/ }))+ await waitFor(() => expect(screen.getByRole('button', { name: /Search/ })).not.toBeDisabled())+ expect(screen.queryByRole('button', { name: 'Close' })).not.toBeInTheDocument()+ })++ it('FE-COMP-ADDPLACECOL-010: saving posts the manually typed place with nulls for what is empty', async () => {+ const { props } = setup()+ typeName(' Manual spot ')+ fireEvent.click(screen.getByRole('button', { name: /Add$/ }))++ await waitFor(() => expect(savedBodies).toHaveLength(1))+ expect(savedBodies[0]).toMatchObject({+ collection_id: 7,+ name: 'Manual spot',+ address: null,+ lat: null,+ lng: null,+ google_place_id: null,+ osm_id: null,+ website: null,+ category_id: null,+ description: null,+ links: [],+ status: 'idea',+ force: true,+ })+ expect(addToast).toHaveBeenCalledWith('Added to Tokyo 2026', 'success', undefined)+ expect(props.onAdded).toHaveBeenCalledTimes(1)+ // The form clears so another place can be added straight away.+ await waitFor(() => expect(screen.getByPlaceholderText('Name')).toHaveValue(''))+ })++ it('FE-COMP-ADDPLACECOL-011: provenance from a picked result rides along with the save', async () => {+ mockSearch([mapsResult])+ setup()+ fireEvent.change(screen.getByPlaceholderText('Search for a place…'), { target: { value: 'kissa' } })+ fireEvent.click(screen.getByRole('button', { name: /Search/ }))+ fireEvent.click(await screen.findByRole('button', { name: /Kissa Sakaiki/ }))+ fireEvent.click(screen.getByRole('button', { name: /Add$/ }))++ await waitFor(() => expect(savedBodies).toHaveLength(1))+ expect(savedBodies[0]).toMatchObject({+ name: 'Kissa Sakaiki',+ address: 'Shibuya, Tokyo',+ lat: 35.66,+ lng: 139.7,+ google_place_id: 'gp-1',+ google_ftid: 'ft-1',+ osm_id: 'osm-1',+ website: 'https://kissa.example',+ phone: '+81 3 0000 0000',+ })+ })++ it('FE-COMP-ADDPLACECOL-012: a duplicate response warns instead of reporting a new place', async () => {+ mockSave({ duplicate: true })+ const { props } = setup()+ typeName('Manual spot')+ fireEvent.click(screen.getByRole('button', { name: /Add$/ }))++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('This place is already in the list', 'info', undefined))+ expect(props.onAdded).not.toHaveBeenCalled()+ })++ it('FE-COMP-ADDPLACECOL-013: a failing save surfaces the server error and keeps the form', async () => {+ server.use(http.post('/api/addons/collections/places', () => HttpResponse.json({ error: 'List is full' }, { status: 400 })))+ const { props } = setup()+ typeName('Manual spot')+ fireEvent.click(screen.getByRole('button', { name: /Add$/ }))++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('List is full', 'error', undefined))+ expect(props.onAdded).not.toHaveBeenCalled()+ expect(screen.getByPlaceholderText('Name')).toHaveValue('Manual spot')+ })++ it('FE-COMP-ADDPLACECOL-014: an address and coordinates typed by hand are kept, blanks stay null', async () => {+ setup()+ typeName('GPS only')+ fireEvent.change(screen.getByPlaceholderText('Street, City, Country'), { target: { value: ' 5 Rue Cler, Paris ' } })+ fireEvent.change(screen.getByPlaceholderText('Latitude (e.g. 48.8566)'), { target: { value: '48.8566' } })+ fireEvent.click(screen.getByRole('button', { name: /Add$/ }))++ await waitFor(() => expect(savedBodies).toHaveLength(1))+ expect(savedBodies[0]).toMatchObject({ address: '5 Rue Cler, Paris', lat: 48.8566, lng: null })+ })++ it('FE-COMP-ADDPLACECOL-015: pasting a coordinate pair splits it across both fields', () => {+ setup()+ const lat = screen.getByPlaceholderText('Latitude (e.g. 48.8566)')+ fireEvent.paste(lat, { clipboardData: { getData: () => ' 48.8566, 2.3522 ' } })+ expect(lat).toHaveValue('48.8566')+ expect(screen.getByPlaceholderText('Longitude (e.g. 2.3522)')).toHaveValue('2.3522')+ })++ it('FE-COMP-ADDPLACECOL-016: a paste that is not a coordinate pair is left to the input', () => {+ setup()+ const lat = screen.getByPlaceholderText('Latitude (e.g. 48.8566)')+ fireEvent.paste(lat, { clipboardData: { getData: () => 'Eiffel Tower' } })+ expect(lat).toHaveValue('')+ expect(screen.getByPlaceholderText('Longitude (e.g. 2.3522)')).toHaveValue('')+ })++ it('FE-COMP-ADDPLACECOL-017: the chosen status is saved', async () => {+ setup()+ typeName('Manual spot')+ fireEvent.click(screen.getByRole('button', { name: /Visited/ }))+ fireEvent.click(screen.getByRole('button', { name: /Add$/ }))+ await waitFor(() => expect(savedBodies).toHaveLength(1))+ expect(savedBodies[0]).toMatchObject({ status: 'visited' })+ })++ it('FE-COMP-ADDPLACECOL-018: a category can be picked and cleared again', async () => {+ setup()+ typeName('Manual spot')+ fireEvent.click(screen.getByRole('button', { name: /Food/ }))+ fireEvent.click(screen.getByRole('button', { name: /Museum/ }))+ fireEvent.click(screen.getByRole('button', { name: /Add$/ }))+ await waitFor(() => expect(savedBodies).toHaveLength(1))+ expect(savedBodies[0]).toMatchObject({ category_id: 4 })++ fireEvent.click(screen.getByRole('button', { name: 'No category' }))+ typeName('Second spot')+ fireEvent.click(screen.getByRole('button', { name: /Add$/ }))+ await waitFor(() => expect(savedBodies).toHaveLength(2))+ expect(savedBodies[1]).toMatchObject({ category_id: null })+ })++ it('FE-COMP-ADDPLACECOL-019: without categories the category row is not rendered', () => {+ setup({ categories: [] })+ expect(screen.queryByText('Category')).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'No category' })).not.toBeInTheDocument()+ })++ it('FE-COMP-ADDPLACECOL-020: links are normalised and blank rows dropped', async () => {+ setup()+ typeName('Manual spot')+ fireEvent.click(screen.getByRole('button', { name: /Add link/ }))+ fireEvent.click(screen.getByRole('button', { name: /Add link/ }))+ const urls = screen.getAllByPlaceholderText('https://…')+ fireEvent.change(screen.getAllByPlaceholderText('Label')[0], { target: { value: ' Menu ' } })+ fireEvent.change(urls[0], { target: { value: 'kissa.example/menu' } })++ fireEvent.click(screen.getByRole('button', { name: /Add$/ }))+ await waitFor(() => expect(savedBodies).toHaveLength(1))+ expect(savedBodies[0].links).toEqual([{ label: 'Menu', url: 'https://kissa.example/menu' }])+ })++ it('FE-COMP-ADDPLACECOL-021: a link row can be removed again', () => {+ setup()+ fireEvent.click(screen.getByRole('button', { name: /Add link/ }))+ expect(screen.getByPlaceholderText('https://…')).toBeInTheDocument()+ fireEvent.click(screen.getByRole('button', { name: 'Delete' }))+ expect(screen.queryByPlaceholderText('https://…')).not.toBeInTheDocument()+ })++ it('FE-COMP-ADDPLACECOL-022: a description renders a live markdown preview and is trimmed on save', async () => {+ setup()+ typeName('Manual spot')+ fireEvent.change(screen.getByPlaceholderText('Add a description…'), { target: { value: ' **Great** coffee ' } })+ expect(screen.getByText('Great')).toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: /Add$/ }))+ await waitFor(() => expect(savedBodies).toHaveLength(1))+ expect(savedBodies[0]).toMatchObject({ description: '**Great** coffee' })+ })++ it('FE-COMP-ADDPLACECOL-023: closing the modal resets the form for the next open', () => {+ const { rerender, props } = setup()+ typeName('Manual spot')+ fireEvent.change(screen.getByPlaceholderText('Add a description…'), { target: { value: 'notes' } })++ rerender(<Harness {...props} isOpen={false} />)+ rerender(<Harness {...props} isOpen />)++ expect(screen.getByPlaceholderText('Name')).toHaveValue('')+ expect(screen.getByPlaceholderText('Add a description…')).toHaveValue('')+ })++ it('FE-COMP-ADDPLACECOL-024: Cancel closes without saving', () => {+ const { props } = setup()+ typeName('Manual spot')+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))+ expect(props.onClose).toHaveBeenCalledTimes(1)+ expect(savedBodies).toHaveLength(0)+ })+})diff --git a/client/src/components/Collections/BulkAssignLabelModal.test.tsx b/client/src/components/Collections/BulkAssignLabelModal.test.tsxnew file mode 100644index 000000000..c18d77783--- /dev/null+++ b/client/src/components/Collections/BulkAssignLabelModal.test.tsx@@ -0,0 +1,127 @@+// FE-COMP-BULKLABEL-001 to FE-COMP-BULKLABEL-009+import React from 'react';+import { render, screen, waitFor } from '../../../tests/helpers/render';+import userEvent from '@testing-library/user-event';+import type { CollectionLabel } from '@trek/shared';+import { useTranslation } from '../../i18n/TranslationContext';+import BulkAssignLabelModal from './BulkAssignLabelModal';++type ModalProps = Omit<React.ComponentProps<typeof BulkAssignLabelModal>, 't'>;++function Harness(props: ModalProps): React.ReactElement {+ const { t } = useTranslation();+ return <BulkAssignLabelModal {...props} t={t} />;+}++const berlin: CollectionLabel = { id: 1, collection_id: 10, name: 'Berlin', color: '#0ea5e9' };+const food: CollectionLabel = { id: 2, collection_id: 10, name: 'Food', color: null };++function renderModal(overrides: Partial<ModalProps> = {}) {+ const props: ModalProps = {+ isOpen: true,+ labels: [berlin, food],+ count: 4,+ onAssign: vi.fn(async () => {}),+ onManage: vi.fn(),+ onClose: vi.fn(),+ ...overrides,+ };+ render(<Harness {...props} />);+ return props;+}++describe('BulkAssignLabelModal', () => {+ it('FE-COMP-BULKLABEL-001: titles the modal with the selection count and lists every label', () => {+ renderModal({ count: 4 });+ expect(screen.getByRole('heading', { name: 'Add labels to 4 places' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Berlin' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Food' })).toBeInTheDocument();+ });++ it('FE-COMP-BULKLABEL-002: with no labels it explains why and offers the manager instead', async () => {+ const user = userEvent.setup();+ const props = renderModal({ labels: [] });++ expect(screen.getByText('Create a label first to group places in this list.')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Assign label' })).not.toBeInTheDocument();++ await user.click(screen.getByRole('button', { name: /Manage labels/ }));+ expect(props.onManage).toHaveBeenCalledTimes(1);+ });++ it('FE-COMP-BULKLABEL-003: the assign button is disabled until at least one label is picked', async () => {+ const user = userEvent.setup();+ renderModal();+ const assign = screen.getByRole('button', { name: /^Assign label$/ });+ expect(assign).toBeDisabled();++ await user.click(screen.getByRole('button', { name: 'Berlin' }));+ expect(assign).toBeEnabled();+ });++ it('FE-COMP-BULKLABEL-004: picking a label marks the row selected, clicking again unpicks it', async () => {+ const user = userEvent.setup();+ renderModal();+ const berlinRow = screen.getByRole('button', { name: 'Berlin' });++ await user.click(berlinRow);+ expect(berlinRow).toHaveClass('border-accent');++ await user.click(berlinRow);+ expect(berlinRow).not.toHaveClass('border-accent');+ expect(screen.getByRole('button', { name: /^Assign label$/ })).toBeDisabled();+ });++ it('FE-COMP-BULKLABEL-005: assigning sends every picked id in click order and clears the selection', async () => {+ const user = userEvent.setup();+ const props = renderModal();++ await user.click(screen.getByRole('button', { name: 'Food' }));+ await user.click(screen.getByRole('button', { name: 'Berlin' }));+ await user.click(screen.getByRole('button', { name: /^Assign label$/ }));++ await waitFor(() => expect(props.onAssign).toHaveBeenCalledWith([2, 1]));+ // Selection resets so the modal is ready for the next batch.+ await waitFor(() => expect(screen.getByRole('button', { name: /^Assign label$/ })).toBeDisabled());+ expect(screen.getByRole('button', { name: 'Berlin' })).not.toHaveClass('border-accent');+ });++ it('FE-COMP-BULKLABEL-006: a second click while the assign is pending is ignored', async () => {+ const user = userEvent.setup();+ const onAssign = vi.fn(() => new Promise<void>(() => {}));+ renderModal({ onAssign });++ await user.click(screen.getByRole('button', { name: 'Berlin' }));+ const assign = screen.getByRole('button', { name: /^Assign label$/ });+ await user.click(assign);+ await user.click(assign);++ expect(onAssign).toHaveBeenCalledTimes(1);+ expect(assign.querySelector('.animate-spin')).not.toBeNull();+ expect(assign).toBeDisabled();+ });++ it('FE-COMP-BULKLABEL-007: Cancel closes without assigning anything', async () => {+ const user = userEvent.setup();+ const props = renderModal();++ await user.click(screen.getByRole('button', { name: 'Berlin' }));+ await user.click(screen.getByRole('button', { name: 'Cancel' }));++ expect(props.onClose).toHaveBeenCalledTimes(1);+ expect(props.onAssign).not.toHaveBeenCalled();+ });++ it('FE-COMP-BULKLABEL-008: the footer manage shortcut opens the label manager', async () => {+ const user = userEvent.setup();+ const props = renderModal();++ await user.click(screen.getByRole('button', { name: /Manage labels/ }));+ expect(props.onManage).toHaveBeenCalledTimes(1);+ });++ it('FE-COMP-BULKLABEL-009: renders nothing while closed', () => {+ renderModal({ isOpen: false });+ expect(screen.queryByRole('heading', { name: /Add labels to/ })).not.toBeInTheDocument();+ });+});diff --git a/client/src/components/Collections/CollectionHero.test.tsx b/client/src/components/Collections/CollectionHero.test.tsxnew file mode 100644index 000000000..a3a0be0ee--- /dev/null+++ b/client/src/components/Collections/CollectionHero.test.tsx@@ -0,0 +1,163 @@+// FE-COMP-COLHERO-001 to FE-COMP-COLHERO-011+import React from 'react';+import { render, screen, within } from '../../../tests/helpers/render';+import userEvent from '@testing-library/user-event';+import type { CollectionMember } from '@trek/shared';+import { useTranslation } from '../../i18n/TranslationContext';+import CollectionHero from './CollectionHero';++type HeroProps = Omit<React.ComponentProps<typeof CollectionHero>, 't'>;++function Harness(props: HeroProps): React.ReactElement {+ const { t } = useTranslation();+ return <CollectionHero {...props} t={t} />;+}++function member(over: Partial<CollectionMember> = {}): CollectionMember {+ return { user_id: 1, username: 'ada lovelace', status: 'accepted', ...over } as CollectionMember;+}++function renderHero(overrides: Partial<HeroProps> = {}) {+ const props: HeroProps = {+ eyebrow: 'Private list',+ title: 'Weekend in Rome',+ color: '#ef4444',+ members: [],+ canShare: true,+ isOwner: true,+ canEdit: true,+ onEdit: vi.fn(),+ shareMemberCount: 0,+ onShare: vi.fn(),+ ...overrides,+ };+ render(<Harness {...props} />);+ return props;+}++describe('CollectionHero', () => {+ it('FE-COMP-COLHERO-001: renders the eyebrow, the title and the colour wash', () => {+ renderHero();+ expect(screen.getByRole('heading', { name: 'Weekend in Rome' })).toBeInTheDocument();+ expect(screen.getByText('Private list')).toBeInTheDocument();+ // No cover image → the gradient background element stands in for it.+ expect(document.querySelector('.col-hero-bg')).not.toBeNull();+ expect(document.querySelector('.col-hero-img')).toBeNull();+ expect(document.querySelector<HTMLElement>('.col-hero')?.style.getPropertyValue('--hero-color')).toBe('#ef4444');+ });++ it('FE-COMP-COLHERO-002: a cover image replaces the gradient and adds the tint layer', () => {+ renderHero({ coverImage: '/uploads/covers/rome.jpg' });+ expect(document.querySelector<HTMLImageElement>('.col-hero-img')?.getAttribute('src')).toBe('/uploads/covers/rome.jpg');+ expect(document.querySelector('.col-hero-tint')).not.toBeNull();+ expect(document.querySelector('.col-hero-bg')).toBeNull();+ });++ it('FE-COMP-COLHERO-003: the description renders only when present', () => {+ const { unmount } = render(<Harness {...{+ eyebrow: 'x', title: 'y', color: '#000', members: [], canShare: false, isOwner: false,+ canEdit: false, onEdit: vi.fn(), shareMemberCount: 0, onShare: vi.fn(),+ }} />);+ expect(document.querySelector('.col-hero-desc')).toBeNull();+ unmount();++ renderHero({ description: 'Three days of pasta' });+ expect(screen.getByText('Three days of pasta')).toBeInTheDocument();+ });++ it('FE-COMP-COLHERO-004: a single member does not produce an avatar stack', () => {+ renderHero({ members: [member({ user_id: 1, is_owner: true })] });+ expect(document.querySelector('.members')).toBeNull();+ });++ it('FE-COMP-COLHERO-005: two or more accepted members render initials avatars', () => {+ renderHero({+ members: [+ member({ user_id: 1, username: 'ada lovelace', is_owner: true }),+ member({ user_id: 2, username: 'grace' }),+ member({ user_id: 3, username: ' ' }),+ ],+ });+ const stack = document.querySelector('.members');+ expect(stack).not.toBeNull();+ expect(within(stack as HTMLElement).getByText('AL')).toBeInTheDocument();+ expect(within(stack as HTMLElement).getByText('G')).toBeInTheDocument();+ // A blank username still gets a placeholder rather than an empty circle.+ expect(within(stack as HTMLElement).getByText('?')).toBeInTheDocument();+ });++ it('FE-COMP-COLHERO-006: pending members are excluded, owners are kept regardless of status', () => {+ renderHero({+ members: [+ member({ user_id: 1, username: 'ada', status: 'pending', is_owner: true }),+ member({ user_id: 2, username: 'grace' }),+ member({ user_id: 3, username: 'nobody', status: 'pending' }),+ ],+ });+ const stack = document.querySelector('.members') as HTMLElement;+ expect(within(stack).getByText('A')).toBeInTheDocument();+ expect(within(stack).getByText('G')).toBeInTheDocument();+ expect(within(stack).queryByText('N')).not.toBeInTheDocument();+ });++ it('FE-COMP-COLHERO-007: an uploaded avatar renders as an image, and beyond five members a +N chip appears', () => {+ const members = [1, 2, 3, 4, 5, 6, 7].map(i =>+ member({ user_id: i, username: `user${i}`, avatar: i === 1 ? 'me.png' : null }),+ );+ renderHero({ members });+ const stack = document.querySelector('.members') as HTMLElement;+ expect(within(stack).getByRole('img', { name: 'user1' })).toHaveAttribute('src', '/uploads/avatars/me.png');+ expect(within(stack).getByText('+2')).toBeInTheDocument();+ });++ it('FE-COMP-COLHERO-008: link chips show the label, or the bare host when unlabelled', async () => {+ const user = userEvent.setup();+ renderHero({+ links: [+ { url: 'https://www.romeguide.example/food', label: 'Food guide' },+ { url: 'https://maps.example/pin' },+ { url: 'not-a-url' },+ ],+ });+ const labelled = screen.getByRole('link', { name: /Food guide/ });+ expect(labelled).toHaveAttribute('href', 'https://www.romeguide.example/food');+ expect(labelled).toHaveAttribute('target', '_blank');+ // No label → hostname without the www. prefix.+ expect(screen.getByRole('link', { name: /maps\.example/ })).toBeInTheDocument();+ // Unparseable href → the raw string is shown rather than crashing.+ expect(screen.getByRole('link', { name: /not-a-url/ })).toBeInTheDocument();++ // The chip must not bubble a click up to the hero.+ const onEdit = vi.fn();+ await user.click(labelled);+ expect(onEdit).not.toHaveBeenCalled();+ });++ it('FE-COMP-COLHERO-009: the Edit button renders only when canEdit and calls onEdit', async () => {+ const user = userEvent.setup();+ const props = renderHero({ canEdit: true });+ await user.click(screen.getByRole('button', { name: 'Edit' }));+ expect(props.onEdit).toHaveBeenCalledTimes(1);++ renderHero({ canEdit: false, canShare: false });+ expect(screen.getAllByRole('button', { name: 'Edit' })).toHaveLength(1);+ });++ it('FE-COMP-COLHERO-010: the owner sees a Share button carrying the member count badge', async () => {+ const user = userEvent.setup();+ const props = renderHero({ isOwner: true, canShare: true, shareMemberCount: 3 });+ const share = screen.getByRole('button', { name: 'Share' });+ expect(share).toHaveClass('has-count');+ expect(within(share).getByText('3')).toBeInTheDocument();+ await user.click(share);+ expect(props.onShare).toHaveBeenCalledTimes(1);+ });++ it('FE-COMP-COLHERO-011: a non-owner sees a Shared button without a count badge', () => {+ renderHero({ isOwner: false, canShare: true, shareMemberCount: 3 });+ const share = screen.getByRole('button', { name: 'Shared' });+ expect(share).not.toHaveClass('has-count');+ expect(within(share).queryByText('3')).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Share' })).not.toBeInTheDocument();+ });+});diff --git a/client/src/components/Collections/CollectionPicker.test.tsx b/client/src/components/Collections/CollectionPicker.test.tsxnew file mode 100644index 000000000..8a1be5133--- /dev/null+++ b/client/src/components/Collections/CollectionPicker.test.tsx@@ -0,0 +1,208 @@+// FE-COMP-COLPICKER-001 to FE-COMP-COLPICKER-016+import React from 'react'+import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render'+import type { Collection, CollectionDetailResponse, CollectionPlace } from '@trek/shared'+import { collectionsApi } from '../../api/collections'+import { useAuthStore } from '../../store/authStore'+import { resetAllStores, seedStore } from '../../../tests/helpers/store'+import { buildUser } from '../../../tests/helpers/factories'+import { useTranslation } from '../../i18n/TranslationContext'+import CollectionPicker from './CollectionPicker'++type Props = React.ComponentProps<typeof CollectionPicker>+function Harness(props: Omit<Props, 't'>): React.ReactElement {+ const { t } = useTranslation()+ return <CollectionPicker {...props} t={t} />+}++const listA: Collection = { id: 1, owner_id: 1, name: 'Tokyo 2026', color: '#ec4899' }+const listB: Collection = { id: 2, owner_id: 1, name: 'Rome', color: null }++function place(over: Partial<CollectionPlace> & { id: number; collection_id: number; name: string }): CollectionPlace {+ return { status: 'idea', ...over }+}++// Zebra Cafe sits far from the bias box, Alpha Bar right inside it — so the+// alphabetical and the proximity order are deliberately opposites.+const zebra = place({ id: 10, collection_id: 1, name: 'Zebra Cafe', address: 'Shibuya 1', lat: 35.6, lng: 139.7 })+const alpha = place({ id: 11, collection_id: 2, name: 'Alpha Bar', address: 'Trastevere 9', lat: 41.9, lng: 12.5, category: { id: 3, name: 'Bar', color: '#f59e0b', icon: 'beer' } })+const noCoords = place({ id: 12, collection_id: 2, name: 'Mystery Spot', status: 'visited' })++function detail(collection: Collection, places: CollectionPlace[]): CollectionDetailResponse {+ return { collection, places }+}++function setup(over: Partial<Omit<Props, 't'>> = {}) {+ const props: Omit<Props, 't'> = { onSelect: vi.fn(), ...over }+ const view = render(<Harness {...props} />)+ return { ...view, props }+}++describe('CollectionPicker', () => {+ beforeEach(() => {+ resetAllStores()+ // Keeps PlaceAvatar from reaching for provider photos in jsdom.+ seedStore(useAuthStore, { user: buildUser(), placesPhotosEnabled: false })+ vi.spyOn(collectionsApi, 'list').mockResolvedValue({ collections: [listA, listB], incomingInvites: [] })+ vi.spyOn(collectionsApi, 'get').mockImplementation(async (id: number) =>+ id === 1 ? detail(listA, [zebra]) : detail(listB, [alpha, noCoords]),+ )+ })++ afterEach(() => {+ vi.restoreAllMocks()+ })++ it('FE-COMP-COLPICKER-001: shows a spinner until the lists have loaded', async () => {+ const { container } = setup()+ expect(container.querySelector('.animate-spin')).toBeTruthy()+ expect(await screen.findByText('Zebra Cafe')).toBeInTheDocument()+ expect(container.querySelector('.animate-spin')).toBeFalsy()+ })++ it('FE-COMP-COLPICKER-002: merges the places of every list and shows their addresses', async () => {+ setup()+ expect(await screen.findByText('Zebra Cafe')).toBeInTheDocument()+ expect(screen.getByText('Alpha Bar')).toBeInTheDocument()+ expect(screen.getByText('Mystery Spot')).toBeInTheDocument()+ expect(screen.getByText('Shibuya 1')).toBeInTheDocument()+ expect(screen.getByText('Saved places')).toBeInTheDocument()+ })++ it('FE-COMP-COLPICKER-003: sorts alphabetically without a bias box', async () => {+ setup()+ await screen.findByText('Zebra Cafe')+ const names = screen.getAllByRole('button', { name: /Alpha Bar|Mystery Spot|Zebra Cafe/ }).map(b => b.textContent)+ expect(names).toEqual(['Alpha BarTrastevere 9', 'Mystery Spot', 'Zebra CafeShibuya 1'])+ })++ it('FE-COMP-COLPICKER-004: a bias box sorts by proximity and pushes coordinate-less places last', async () => {+ setup({ bias: { low: { lat: 35.5, lng: 139.6 }, high: { lat: 35.7, lng: 139.8 } } })+ await screen.findByText('Zebra Cafe')+ const names = screen.getAllByRole('button', { name: /Alpha Bar|Mystery Spot|Zebra Cafe/ }).map(b => b.textContent)+ expect(names).toEqual(['Zebra CafeShibuya 1', 'Alpha BarTrastevere 9', 'Mystery Spot'])+ })++ it('FE-COMP-COLPICKER-005: picking a place hands the whole record to onSelect', async () => {+ const { props } = setup()+ fireEvent.click(await screen.findByRole('button', { name: /Zebra Cafe/ }))+ expect(props.onSelect).toHaveBeenCalledTimes(1)+ expect(props.onSelect).toHaveBeenCalledWith(zebra)+ })++ it('FE-COMP-COLPICKER-006: the search box matches on name', async () => {+ setup()+ await screen.findByText('Zebra Cafe')+ fireEvent.change(screen.getByPlaceholderText('Search your saved places'), { target: { value: 'zebra' } })+ expect(screen.getByText('Zebra Cafe')).toBeInTheDocument()+ expect(screen.queryByText('Alpha Bar')).not.toBeInTheDocument()+ })++ it('FE-COMP-COLPICKER-007: the search box also matches on address', async () => {+ setup()+ await screen.findByText('Zebra Cafe')+ fireEvent.change(screen.getByPlaceholderText('Search your saved places'), { target: { value: 'trastevere' } })+ expect(screen.getByText('Alpha Bar')).toBeInTheDocument()+ expect(screen.queryByText('Zebra Cafe')).not.toBeInTheDocument()+ })++ it('FE-COMP-COLPICKER-008: a search with no hits falls back to the empty copy', async () => {+ setup()+ await screen.findByText('Zebra Cafe')+ fireEvent.change(screen.getByPlaceholderText('Search your saved places'), { target: { value: 'nothing here' } })+ expect(screen.getByText('No saved places to add')).toBeInTheDocument()+ })++ it('FE-COMP-COLPICKER-009: the list dropdown counts each list and filters to it', async () => {+ setup()+ await screen.findByText('Zebra Cafe')+ fireEvent.click(screen.getByRole('button', { name: /All lists/ }))++ const menu = screen.getByRole('listbox')+ expect(within(menu).getByRole('option', { name: /All lists/ })).toHaveTextContent('3')+ expect(within(menu).getByRole('option', { name: /Rome/ })).toHaveTextContent('2')++ fireEvent.click(within(menu).getByRole('option', { name: /Tokyo 2026/ }))+ expect(screen.getByText('Zebra Cafe')).toBeInTheDocument()+ expect(screen.queryByText('Alpha Bar')).not.toBeInTheDocument()+ // The trigger adopts the picked option and the menu closes.+ expect(screen.getByRole('button', { name: /Tokyo 2026/ })).toBeInTheDocument()+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument()+ })++ it('FE-COMP-COLPICKER-010: the status dropdown filters by saved status', async () => {+ setup()+ await screen.findByText('Zebra Cafe')+ fireEvent.click(screen.getByRole('button', { name: /^All$/ }))+ fireEvent.click(within(screen.getByRole('listbox')).getByRole('option', { name: /Visited/ }))++ expect(screen.getByText('Mystery Spot')).toBeInTheDocument()+ expect(screen.queryByText('Zebra Cafe')).not.toBeInTheDocument()+ expect(screen.queryByText('Alpha Bar')).not.toBeInTheDocument()+ })++ it('FE-COMP-COLPICKER-011: the selected option is flagged for assistive tech', async () => {+ setup()+ await screen.findByText('Zebra Cafe')+ fireEvent.click(screen.getByRole('button', { name: /All lists/ }))+ const menu = screen.getByRole('listbox')+ expect(within(menu).getByRole('option', { name: /All lists/ })).toHaveAttribute('aria-selected', 'true')+ expect(within(menu).getByRole('option', { name: /Rome/ })).toHaveAttribute('aria-selected', 'false')+ })++ it('FE-COMP-COLPICKER-012: a click outside closes an open dropdown', async () => {+ setup()+ await screen.findByText('Zebra Cafe')+ const trigger = screen.getByRole('button', { name: /All lists/ })+ fireEvent.click(trigger)+ expect(trigger).toHaveAttribute('aria-expanded', 'true')++ fireEvent.mouseDown(document.body)+ await waitFor(() => expect(screen.queryByRole('listbox')).not.toBeInTheDocument())+ })++ it('FE-COMP-COLPICKER-013: a mousedown inside the dropdown keeps it open', async () => {+ setup()+ await screen.findByText('Zebra Cafe')+ fireEvent.click(screen.getByRole('button', { name: /All lists/ }))+ fireEvent.mouseDown(screen.getByRole('listbox'))+ expect(screen.getByRole('listbox')).toBeInTheDocument()+ })++ it('FE-COMP-COLPICKER-014: Escape closes an open dropdown', async () => {+ setup()+ await screen.findByText('Zebra Cafe')+ fireEvent.click(screen.getByRole('button', { name: /All lists/ }))+ fireEvent.keyDown(document, { key: 'Escape' })+ await waitFor(() => expect(screen.queryByRole('listbox')).not.toBeInTheDocument())+ // A different key leaves it alone.+ fireEvent.click(screen.getByRole('button', { name: /All lists/ }))+ fireEvent.keyDown(document, { key: 'a' })+ expect(screen.getByRole('listbox')).toBeInTheDocument()+ })++ it('FE-COMP-COLPICKER-015: a list whose detail request fails is skipped, the rest still load', async () => {+ vi.mocked(collectionsApi.get).mockImplementation(async (id: number) => {+ if (id === 1) throw new Error('403')+ return detail(listB, [alpha])+ })+ setup()+ expect(await screen.findByText('Alpha Bar')).toBeInTheDocument()+ expect(screen.queryByText('Zebra Cafe')).not.toBeInTheDocument()+ })++ it('FE-COMP-COLPICKER-016: a failing list request degrades to the empty state without filters', async () => {+ vi.mocked(collectionsApi.list).mockRejectedValue(new Error('offline'))+ setup()+ expect(await screen.findByText('No saved places to add')).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: /All lists/ })).not.toBeInTheDocument()+ })++ it('FE-COMP-COLPICKER-017: with no lists at all the filter row stays hidden', async () => {+ vi.mocked(collectionsApi.list).mockResolvedValue({ collections: [], incomingInvites: [] })+ setup()+ expect(await screen.findByText('No saved places to add')).toBeInTheDocument()+ expect(collectionsApi.get).not.toHaveBeenCalled()+ expect(screen.queryByRole('button', { name: /All lists/ })).not.toBeInTheDocument()+ })+})diff --git a/client/src/components/Collections/CollectionPlaceDetail.test.tsx b/client/src/components/Collections/CollectionPlaceDetail.test.tsxindex a4720ea8c..440097c64 100644--- a/client/src/components/Collections/CollectionPlaceDetail.test.tsx+++ b/client/src/components/Collections/CollectionPlaceDetail.test.tsx@@ -1,13 +1,14 @@-// FE-COMP-COLDETAIL-001 to FE-COMP-COLDETAIL-010+// FE-COMP-COLDETAIL-001 to FE-COMP-COLDETAIL-035import React from 'react';-import { render, screen } from '../../../tests/helpers/render';+import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render';import userEvent from '@testing-library/user-event';import { http, HttpResponse } from 'msw';import { server } from '../../../tests/helpers/msw/server';import { useAuthStore } from '../../store/authStore';import { resetAllStores, seedStore } from '../../../tests/helpers/store';import { buildUser } from '../../../tests/helpers/factories';-import type { CollectionPlace } from '@trek/shared';+import type { CollectionLabel, CollectionPlace } from '@trek/shared';+import type { Category } from '../../types';import { useTranslation } from '../../i18n/TranslationContext';import CollectionPlaceDetail from './CollectionPlaceDetail';@@ -33,6 +34,18 @@ const place: CollectionPlace = {category: { id: 1, name: 'Food', color: '#f00', icon: null },};+const CATEGORIES: Category[] = [+ { id: 1, name: 'Food', color: '#f00', icon: 'utensils' },+ { id: 2, name: 'Museums', color: '#00f', icon: 'landmark' },+];++const LABELS: CollectionLabel[] = [+ { id: 1, collection_id: 10, name: 'Berlin', color: '#0ea5e9' },+ { id: 2, collection_id: 10, name: 'Nightlife', color: null },+];++let addToast: ReturnType<typeof vi.fn>;+function renderDetail(overrides: Partial<Omit<DetailProps, 't'>> = {}) {const props = {place,@@ -55,6 +68,8 @@ function renderDetail(overrides: Partial<Omit<DetailProps, 't'>> = {}) {beforeEach(() => {resetAllStores();seedStore(useAuthStore, { user: buildUser(), placesPhotosEnabled: false });+ addToast = vi.fn();+ window.__addToast = addToast as unknown as typeof window.__addToast;// The detail sheet asks the maps provider for a cover photo on mount when a// place carries no image of its own — stub it so nothing hits the network.server.use(@@ -64,6 +79,10 @@ beforeEach(() => {);});+afterEach(() => {+ delete window.__addToast;+});+describe('CollectionPlaceDetail', () => {it('FE-COMP-COLDETAIL-001: renders the place name, address and description', async () => {renderDetail();@@ -142,8 +161,17 @@ describe('CollectionPlaceDetail', () => {// ── Custom cover image (#1136) ──────────────────────────────────────────────it('FE-COMP-COLDETAIL-011: shows the cover upload control when canEdit && onUploadImage', async () => {+ const user = userEvent.setup();renderDetail({ canEdit: true, onUploadImage: vi.fn() });- expect(await screen.findByRole('button', { name: 'Upload image' })).toBeInTheDocument();+ const camera = await screen.findByRole('button', { name: 'Upload image' });+ expect(camera).toBeInTheDocument();++ // The camera button proxies the hidden file input.+ const input = document.querySelector('input[type="file"]') as HTMLInputElement;+ const clicked = vi.fn();+ input.addEventListener('click', clicked);+ await user.click(camera);+ expect(clicked).toHaveBeenCalledTimes(1);});it('FE-COMP-COLDETAIL-012: hides the cover upload control when onUploadImage is not provided', async () => {@@ -161,4 +189,303 @@ describe('CollectionPlaceDetail', () => {await user.click(await screen.findByRole('button', { name: 'Remove image' }));expect(props.onSave).toHaveBeenCalledWith({ image_url: null });});++ it('FE-COMP-COLDETAIL-014: a failing cover removal surfaces the upload error', async () => {+ const user = userEvent.setup();+ const withImage: CollectionPlace = { ...place, image_url: '/uploads/places/mock.jpg' };+ const onSave = vi.fn(() => Promise.reject({ response: { data: { error: 'Disk full' } } }));+ renderDetail({ canEdit: true, onUploadImage: vi.fn(), place: withImage, onSave });++ await user.click(await screen.findByRole('button', { name: 'Remove image' }));+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Disk full', 'error', undefined));+ });++ it('FE-COMP-COLDETAIL-015: picking a cover file hands the normalized file to onUploadImage', async () => {+ const onUploadImage = vi.fn(async (_file: File) => {});+ renderDetail({ canEdit: true, onUploadImage });+ await screen.findByRole('button', { name: 'Upload image' });++ const input = document.querySelector('input[type="file"]') as HTMLInputElement;+ const file = new File(['x'], 'cover.png', { type: 'image/png' });+ fireEvent.change(input, { target: { files: [file] } });++ await waitFor(() => expect(onUploadImage).toHaveBeenCalledTimes(1));+ expect(onUploadImage.mock.calls[0][0]).toBe(file);+ // The picker resets so re-selecting the same file fires again.+ expect(input.value).toBe('');+ });++ it('FE-COMP-COLDETAIL-016: a cancelled file picker uploads nothing', async () => {+ const onUploadImage = vi.fn(async () => {});+ renderDetail({ canEdit: true, onUploadImage });+ await screen.findByRole('button', { name: 'Upload image' });++ const input = document.querySelector('input[type="file"]') as HTMLInputElement;+ fireEvent.change(input, { target: { files: [] } });+ expect(onUploadImage).not.toHaveBeenCalled();+ });++ it('FE-COMP-COLDETAIL-017: a failing upload surfaces the error and clears the busy state', async () => {+ const onUploadImage = vi.fn(() => Promise.reject(new Error('Upload rejected')));+ renderDetail({ canEdit: true, onUploadImage });+ await screen.findByRole('button', { name: 'Upload image' });++ const input = document.querySelector('input[type="file"]') as HTMLInputElement;+ fireEvent.change(input, { target: { files: [new File(['x'], 'cover.png', { type: 'image/png' })] } });++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Upload rejected', 'error', undefined));+ // The spinner is gone again, so the control accepts a retry.+ await waitFor(() => expect(document.querySelector('.animate-spin')).toBeNull());+ });++ it('FE-COMP-COLDETAIL-018: the cover renders the fetched provider photo when the place has none', async () => {+ server.use(+ http.get('/api/maps/place-photo/:id', () =>+ HttpResponse.json({ photoUrl: 'https://cdn.example/photo.jpg', attribution: null }),+ ),+ );+ renderDetail({ place: { ...place, google_place_id: 'gp-1' } });++ await waitFor(() =>+ expect(document.querySelector('.col-detail-cover img')).toHaveAttribute('src', 'https://cdn.example/photo.jpg'),+ );+ });++ it('FE-COMP-COLDETAIL-018b: a place with its own image never asks the provider for a photo', async () => {+ const photo = vi.fn();+ server.use(http.get('/api/maps/place-photo/:id', () => { photo(); return HttpResponse.json({ photoUrl: null }); }));+ renderDetail({ place: { ...place, image_url: '/uploads/places/mine.jpg', google_place_id: 'gp-1' } });++ await screen.findByRole('heading', { name: 'Test Cafe' });+ expect(document.querySelector('.col-detail-cover img')).toHaveAttribute('src', '/uploads/places/mine.jpg');+ expect(photo).not.toHaveBeenCalled();+ });++ it('FE-COMP-COLDETAIL-019: the category chip and the assigned label chips render in read mode', async () => {+ renderDetail({ labels: LABELS, place: { ...place, label_ids: [1] } });+ expect(await screen.findByText('Food')).toBeInTheDocument();+ expect(screen.getByText('Berlin')).toBeInTheDocument();+ // Only the assigned label shows — the list's other labels stay hidden.+ expect(screen.queryByText('Nightlife')).not.toBeInTheDocument();+ });++ it('FE-COMP-COLDETAIL-020: the description renders as markdown and links become chips', async () => {+ renderDetail({+ place: {+ ...place,+ description: '# Heading\n\nsome **bold** text',+ links: [{ url: 'https://www.example.com/menu', label: 'Menu' }, { url: 'https://tickets.example/x' }],+ },+ });+ expect(await screen.findByRole('heading', { name: 'Heading' })).toBeInTheDocument();+ expect(screen.getByText('bold').tagName).toBe('STRONG');+ expect(screen.getByRole('link', { name: /Menu/ })).toHaveAttribute('href', 'https://www.example.com/menu');+ // Unlabelled link falls back to the bare hostname.+ expect(screen.getByRole('link', { name: /tickets\.example/ })).toBeInTheDocument();+ });++ it('FE-COMP-COLDETAIL-021: the rating control renders only when onRate is supplied', async () => {+ const onRate = vi.fn(async () => {});+ renderDetail({ onRate, place: { ...place, rating_avg: 4 } });+ const stars = await screen.findByRole('radiogroup');+ await userEvent.setup().click(within(stars).getByRole('radio', { name: '5' }));+ expect(onRate).toHaveBeenCalledWith(5);+ });++ it('FE-COMP-COLDETAIL-022: edit mode exposes the category picker and switching category sticks', async () => {+ const user = userEvent.setup();+ renderDetail({ canEdit: true, categories: CATEGORIES, place: { ...place, category_id: 1 } });+ await user.click(await screen.findByRole('button', { name: 'Edit' }));++ expect(screen.getByText('Category')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /^Food$/ })).toHaveClass('on');++ await user.click(screen.getByRole('button', { name: /^Museums$/ }));+ expect(screen.getByRole('button', { name: /^Museums$/ })).toHaveClass('on');++ await user.click(screen.getByRole('button', { name: 'No category' }));+ expect(screen.getByRole('button', { name: 'No category' })).toHaveClass('on');+ });++ it('FE-COMP-COLDETAIL-023: saving from edit mode sends the whole patch and leaves edit mode', async () => {+ const user = userEvent.setup();+ const props = renderDetail({+ canEdit: true,+ categories: CATEGORIES,+ labels: LABELS,+ place: { ...place, lat: 52.5, lng: 13.4, label_ids: [1] },+ });+ await user.click(await screen.findByRole('button', { name: 'Edit' }));++ const nameInput = screen.getByLabelText('List name');+ await user.clear(nameInput);+ await user.type(nameInput, ' Renamed Cafe ');+ await user.click(screen.getByRole('button', { name: /^Museums$/ }));+ await user.click(screen.getByRole('button', { name: /Nightlife/ }));+ const desc = screen.getByPlaceholderText('Add a description…');+ await user.clear(desc);+ await user.type(desc, 'Great coffee');+ await user.click(screen.getByRole('button', { name: /Save/ }));++ await waitFor(() => expect(props.onSave).toHaveBeenCalled());+ expect(props.onSave).toHaveBeenCalledWith({+ name: 'Renamed Cafe',+ description: 'Great coffee',+ links: [{ label: undefined, url: 'https://x.com' }],+ category_id: 2,+ label_ids: [1, 2],+ lat: 52.5,+ lng: 13.4,+ });+ // Back in read mode.+ expect(await screen.findByRole('button', { name: 'Edit' })).toBeInTheDocument();+ });++ it('FE-COMP-COLDETAIL-024: an empty name and description fall back to the stored name and null', async () => {+ const user = userEvent.setup();+ const props = renderDetail({ canEdit: true, place: { ...place, description: 'Nice spot', links: [] } });+ await user.click(await screen.findByRole('button', { name: 'Edit' }));++ await user.clear(screen.getByLabelText('List name'));+ await user.clear(screen.getByPlaceholderText('Add a description…'));+ await user.click(screen.getByRole('button', { name: /Save/ }));++ await waitFor(() => expect(props.onSave).toHaveBeenCalled());+ expect(props.onSave).toHaveBeenCalledWith(expect.objectContaining({+ name: 'Test Cafe',+ description: null,+ lat: null,+ lng: null,+ }));+ });++ it('FE-COMP-COLDETAIL-025: a failed save toasts the server message and keeps the form open', async () => {+ const user = userEvent.setup();+ const onSave = vi.fn(() => Promise.reject({ response: { data: { error: 'Name taken' } } }));+ renderDetail({ canEdit: true, onSave });+ await user.click(await screen.findByRole('button', { name: 'Edit' }));+ await user.click(screen.getByRole('button', { name: /Save/ }));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Name taken', 'error', undefined));+ expect(screen.getByLabelText('List name')).toBeInTheDocument();+ });++ it('FE-COMP-COLDETAIL-026: Cancel discards the edits and returns to read mode', async () => {+ const user = userEvent.setup();+ const props = renderDetail({ canEdit: true });+ await user.click(await screen.findByRole('button', { name: 'Edit' }));++ await user.type(screen.getByLabelText('List name'), ' Extra');+ await user.click(screen.getByRole('button', { name: 'Cancel' }));++ expect(props.onSave).not.toHaveBeenCalled();+ expect(screen.getByRole('heading', { name: 'Test Cafe' })).toBeInTheDocument();+ });++ it('FE-COMP-COLDETAIL-027: links can be added, relabelled and removed in edit mode', async () => {+ const user = userEvent.setup();+ const props = renderDetail({ canEdit: true, place: { ...place, links: [] } });+ await user.click(await screen.findByRole('button', { name: 'Edit' }));++ await user.click(screen.getByRole('button', { name: /Add link/ }));+ await user.type(screen.getByPlaceholderText('Label'), 'Site');+ await user.type(screen.getByPlaceholderText('https://…'), 'example.com/menu');++ await user.click(screen.getByRole('button', { name: /Save/ }));+ await waitFor(() => expect(props.onSave).toHaveBeenCalled());+ // A bare host is normalized to an absolute https url before it is saved.+ expect(props.onSave).toHaveBeenCalledWith(expect.objectContaining({+ links: [{ label: 'Site', url: 'https://example.com/menu' }],+ }));+ });++ it('FE-COMP-COLDETAIL-028: an emptied link row is dropped from the saved patch', async () => {+ const user = userEvent.setup();+ const props = renderDetail({ canEdit: true, place: { ...place, links: [{ url: 'https://x.com' }] } });+ await user.click(await screen.findByRole('button', { name: 'Edit' }));++ // Two rows: the existing link plus a blank one that never gets a url.+ await user.click(screen.getByRole('button', { name: /Add link/ }));+ expect(screen.getAllByPlaceholderText('https://…')).toHaveLength(2);++ await user.click(screen.getAllByRole('button', { name: 'Delete' })[0]);+ await user.click(screen.getByRole('button', { name: /Save/ }));++ await waitFor(() => expect(props.onSave).toHaveBeenCalled());+ expect(props.onSave).toHaveBeenCalledWith(expect.objectContaining({ links: [] }));+ });++ it('FE-COMP-COLDETAIL-029: pasting a "lat, lng" pair into the latitude field fills both inputs', async () => {+ const user = userEvent.setup();+ const props = renderDetail({ canEdit: true });+ await user.click(await screen.findByRole('button', { name: 'Edit' }));++ const latInput = screen.getByPlaceholderText('Latitude (e.g. 48.8566)');+ fireEvent.paste(latInput, { clipboardData: { getData: () => ' 48.8566, 2.3522 ' } });++ expect(latInput).toHaveValue('48.8566');+ expect(screen.getByPlaceholderText('Longitude (e.g. 2.3522)')).toHaveValue('2.3522');++ await user.click(screen.getByRole('button', { name: /Save/ }));+ await waitFor(() => expect(props.onSave).toHaveBeenCalled());+ expect(props.onSave).toHaveBeenCalledWith(expect.objectContaining({ lat: 48.8566, lng: 2.3522 }));+ });++ it('FE-COMP-COLDETAIL-030: a paste that is not a coordinate pair is left to the input', async () => {+ const user = userEvent.setup();+ renderDetail({ canEdit: true });+ await user.click(await screen.findByRole('button', { name: 'Edit' }));++ const latInput = screen.getByPlaceholderText('Latitude (e.g. 48.8566)');+ fireEvent.paste(latInput, { clipboardData: { getData: () => 'somewhere nice' } });++ expect(latInput).toHaveValue('');+ expect(screen.getByPlaceholderText('Longitude (e.g. 2.3522)')).toHaveValue('');+ });++ it('FE-COMP-COLDETAIL-031: opening a different place resets the form back to read mode', async () => {+ const user = userEvent.setup();+ const props = renderDetail({ canEdit: true });+ await user.click(await screen.findByRole('button', { name: 'Edit' }));+ expect(screen.getByLabelText('List name')).toBeInTheDocument();++ const other: CollectionPlace = { ...place, id: 2, name: 'Second Bar', description: null, links: [] };+ render(<TranslatedDetail {...{ ...props, place: other }} />);++ // The freshly mounted sheet shows the new place in read mode.+ expect(await screen.findByRole('heading', { name: 'Second Bar' })).toBeInTheDocument();+ });++ it('FE-COMP-COLDETAIL-032: the labels field is omitted when the list defines none', async () => {+ const user = userEvent.setup();+ renderDetail({ canEdit: true, labels: [] });+ await user.click(await screen.findByRole('button', { name: 'Edit' }));++ expect(screen.getByText('Coordinates')).toBeInTheDocument();+ expect(screen.queryByText('Labels')).not.toBeInTheDocument();+ });++ it('FE-COMP-COLDETAIL-033: the anchor rect docks the sheet over the given column', async () => {+ renderDetail({ anchorRect: { left: 320, width: 420 } });+ await screen.findByRole('heading', { name: 'Test Cafe' });++ const sheet = document.querySelector('.col-detail') as HTMLElement;+ expect(sheet).toHaveClass('docked');+ expect(sheet.style.left).toBe('320px');+ expect(sheet.style.width).toBe('420px');+ });++ it('FE-COMP-COLDETAIL-034: the header close button hands back to the caller', async () => {+ const user = userEvent.setup();+ const props = renderDetail();+ await user.click(await screen.findByRole('button', { name: 'Close' }));+ expect(props.onClose).toHaveBeenCalledTimes(1);+ });++ it('FE-COMP-COLDETAIL-035: the remove action fires onRemove for an admin', async () => {+ const user = userEvent.setup();+ const props = renderDetail({ canDelete: true });+ await user.click(await screen.findByRole('button', { name: 'Remove from list' }));+ expect(props.onRemove).toHaveBeenCalledTimes(1);+ });});diff --git a/client/src/components/Collections/CopyToTripModal.test.tsx b/client/src/components/Collections/CopyToTripModal.test.tsxnew file mode 100644index 000000000..3cb737b33--- /dev/null+++ b/client/src/components/Collections/CopyToTripModal.test.tsx@@ -0,0 +1,220 @@+// FE-COMP-COPYTRIP-001 to FE-COMP-COPYTRIP-016+import React from 'react';+import { afterEach, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render';+import userEvent from '@testing-library/user-event';+import { tripsApi } from '../../api/client';+import { useTranslation } from '../../i18n/TranslationContext';+import CopyToTripModal from './CopyToTripModal';++type ModalProps = Omit<React.ComponentProps<typeof CopyToTripModal>, 't'>;+type CopyResult = { copied: number; skipped: { id: number; name: string }[] };++function Harness(props: ModalProps): React.ReactElement {+ const { t } = useTranslation();+ return <CopyToTripModal {...props} t={t} />;+}++const TRIPS = [+ { id: 1, title: 'Rome 2026', start_date: '2026-04-02', end_date: '2026-04-09', cover_image: '/uploads/covers/rome.jpg' },+ { id: 2, title: 'Tokyo', start_date: null, end_date: null, cover_image: null },+];++let addToast: ReturnType<typeof vi.fn>;++function renderModal(overrides: Partial<ModalProps> = {}) {+ const props: ModalProps = {+ isOpen: true,+ onClose: vi.fn(),+ placeIds: [7],+ onCopy: vi.fn(async () => ({ copied: 1, skipped: [] })),+ ...overrides,+ };+ render(<Harness {...props} />);+ return props;+}++beforeEach(() => {+ addToast = vi.fn();+ window.__addToast = addToast as unknown as typeof window.__addToast;+ vi.spyOn(tripsApi, 'list').mockResolvedValue({ trips: TRIPS });+});++afterEach(() => {+ vi.restoreAllMocks();+ delete window.__addToast;+});++describe('CopyToTripModal', () => {+ it('FE-COMP-COPYTRIP-001: lists the user trips with their date range once loaded', async () => {+ renderModal();+ expect(await screen.findByText('Rome 2026')).toBeInTheDocument();+ const rome = screen.getByRole('button', { name: /Rome 2026/ });+ expect(within(rome).getByText(/Apr 2 – .*Apr 9/)).toBeInTheDocument();+ // A trip without dates renders no date row at all.+ const tokyo = screen.getByRole('button', { name: /Tokyo/ });+ expect(tokyo.querySelector('.lucide-calendar-days')).toBeNull();+ });++ it('FE-COMP-COPYTRIP-015: a trips response landing after the modal closed is dropped', async () => {+ const closed = <Harness isOpen onClose={vi.fn()} placeIds={[7]} onCopy={vi.fn(async () => ({ copied: 0, skipped: [] }))} />;++ let resolve!: (v: { trips: typeof TRIPS }) => void;+ const spy = vi.spyOn(tripsApi, 'list').mockReturnValue(new Promise(r => { resolve = r; }));+ render(closed).unmount();+ resolve({ trips: TRIPS });+ await Promise.resolve();+ expect(screen.queryByText('Rome 2026')).not.toBeInTheDocument();++ // Same for a rejection — no "no trips" state is written into an unmounted tree.+ let reject!: (e: Error) => void;+ spy.mockReturnValue(new Promise((_, r) => { reject = r; }));+ render(closed).unmount();+ reject(new Error('offline'));+ await Promise.resolve();+ expect(screen.queryByText('No trips yet')).not.toBeInTheDocument();+ });++ it('FE-COMP-COPYTRIP-016: a trip without a title still renders and stays filterable', async () => {+ vi.spyOn(tripsApi, 'list').mockResolvedValue({ trips: [{ id: 8, title: null }, ...TRIPS] });+ renderModal();++ await screen.findByText('Rome 2026');+ fireEvent.change(screen.getByPlaceholderText('Search trips'), { target: { value: 'rome' } });+ expect(screen.getByText('Rome 2026')).toBeInTheDocument();+ expect(screen.getAllByRole('button', { name: /Rome 2026|Tokyo/ })).toHaveLength(1);+ });++ it('FE-COMP-COPYTRIP-014: a one-sided date range falls back to the single date it has', async () => {+ vi.spyOn(tripsApi, 'list').mockResolvedValue({+ trips: [+ { id: 3, title: 'Open ended', start_date: '2026-04-02', end_date: null },+ { id: 4, title: 'Return only', start_date: null, end_date: '2026-04-09' },+ ],+ });+ renderModal();+ await screen.findByText('Open ended');+ expect(within(screen.getByRole('button', { name: /Open ended/ })).getByText(/Apr 2/)).toBeInTheDocument();+ expect(within(screen.getByRole('button', { name: /Return only/ })).getByText(/Apr 9/)).toBeInTheDocument();+ });++ it('FE-COMP-COPYTRIP-002: a cover image replaces the pin placeholder', async () => {+ renderModal();+ await screen.findByText('Rome 2026');+ const rome = screen.getByRole('button', { name: /Rome 2026/ });+ expect(rome.querySelector('img')).toHaveAttribute('src', '/uploads/covers/rome.jpg');+ expect(screen.getByRole('button', { name: /Tokyo/ }).querySelector('.lucide-map-pin')).not.toBeNull();+ });++ it('FE-COMP-COPYTRIP-003: the title is singular for one place and counted for a bulk copy', async () => {+ const { unmount } = render(<Harness {...{ isOpen: true, onClose: vi.fn(), placeIds: [7], onCopy: vi.fn(async () => ({ copied: 1, skipped: [] })) }} />);+ expect(await screen.findByRole('heading', { name: 'Copy to trip' })).toBeInTheDocument();+ unmount();++ renderModal({ placeIds: [7, 8, 9] });+ expect(await screen.findByRole('heading', { name: 'Copy 3 to trip' })).toBeInTheDocument();+ });++ it('FE-COMP-COPYTRIP-004: shows the spinner until the trips arrive', async () => {+ let resolve!: (v: { trips: typeof TRIPS }) => void;+ vi.spyOn(tripsApi, 'list').mockReturnValue(new Promise(r => { resolve = r; }));+ renderModal();+ expect(document.querySelector('.animate-spin')).not.toBeNull();++ resolve({ trips: TRIPS });+ expect(await screen.findByText('Rome 2026')).toBeInTheDocument();+ });++ it('FE-COMP-COPYTRIP-005: an empty or failing trips response shows the no-trips copy', async () => {+ vi.spyOn(tripsApi, 'list').mockResolvedValue({});+ const { unmount } = render(<Harness {...{ isOpen: true, onClose: vi.fn(), placeIds: [7], onCopy: vi.fn(async () => ({ copied: 0, skipped: [] })) }} />);+ expect(await screen.findByText('No trips yet')).toBeInTheDocument();+ unmount();++ vi.spyOn(tripsApi, 'list').mockRejectedValue(new Error('offline'));+ renderModal();+ expect(await screen.findByText('No trips yet')).toBeInTheDocument();+ });++ it('FE-COMP-COPYTRIP-006: requests nothing and renders nothing while closed', () => {+ const spy = vi.spyOn(tripsApi, 'list').mockResolvedValue({ trips: TRIPS });+ renderModal({ isOpen: false });+ expect(spy).not.toHaveBeenCalled();+ expect(screen.queryByRole('heading', { name: /Copy/ })).not.toBeInTheDocument();+ });++ it('FE-COMP-COPYTRIP-007: the search box filters trips by title, case-insensitively', async () => {+ renderModal();+ const search = await screen.findByPlaceholderText('Search trips');++ fireEvent.change(search, { target: { value: 'rome' } });+ expect(screen.getByText('Rome 2026')).toBeInTheDocument();+ expect(screen.queryByText('Tokyo')).not.toBeInTheDocument();++ fireEvent.change(search, { target: { value: 'nope' } });+ expect(screen.getByText('No trips yet')).toBeInTheDocument();+ });++ it('FE-COMP-COPYTRIP-008: picking a trip copies, reports the count and closes', async () => {+ const onCopy = vi.fn(async (): Promise<CopyResult> => ({ copied: 2, skipped: [] }));+ const props = renderModal({ onCopy });++ fireEvent.click(await screen.findByText('Rome 2026'));++ await waitFor(() => expect(props.onClose).toHaveBeenCalled());+ expect(onCopy).toHaveBeenCalledWith(1);+ expect(addToast).toHaveBeenCalledWith('Copied 2 places', 'success', undefined);+ });++ it('FE-COMP-COPYTRIP-009: server-side duplicates are reported alongside the copied count', async () => {+ const onCopy = vi.fn(async (): Promise<CopyResult> => ({ copied: 1, skipped: [{ id: 9, name: 'Colosseum' }] }));+ renderModal({ onCopy });++ fireEvent.click(await screen.findByText('Rome 2026'));+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Skipped 1 duplicates', 'info', undefined));+ expect(addToast).toHaveBeenCalledWith('Copied 1 places', 'success', undefined);+ });++ it('FE-COMP-COPYTRIP-010: a no-op copy says so instead of staying silent', async () => {+ const onCopy = vi.fn(async (): Promise<CopyResult> => ({ copied: 0, skipped: [] }));+ renderModal({ onCopy });++ fireEvent.click(await screen.findByText('Rome 2026'));+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Nothing to copy', 'info', undefined));+ expect(addToast).toHaveBeenCalledTimes(1);+ });++ it('FE-COMP-COPYTRIP-011: a failed copy surfaces the server message and keeps the modal open', async () => {+ const onCopy = vi.fn((): Promise<CopyResult> => Promise.reject({ response: { data: { error: 'Trip is locked' } } }));+ const props = renderModal({ onCopy });++ fireEvent.click(await screen.findByText('Rome 2026'));+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Trip is locked', 'error', undefined));+ expect(props.onClose).not.toHaveBeenCalled();+ });++ it('FE-COMP-COPYTRIP-012: a second click while a copy is running is ignored', async () => {+ let resolve!: (v: CopyResult) => void;+ const onCopy = vi.fn(() => new Promise<CopyResult>(r => { resolve = r; }));+ const props = renderModal({ onCopy });++ fireEvent.click(await screen.findByText('Rome 2026'));+ fireEvent.click(screen.getByText('Tokyo'));+ expect(onCopy).toHaveBeenCalledTimes(1);+ expect(screen.getByRole('button', { name: /Rome 2026/ })).toBeDisabled();++ resolve({ copied: 1, skipped: [] });+ await waitFor(() => expect(props.onClose).toHaveBeenCalled());+ });++ it('FE-COMP-COPYTRIP-013: an empty selection never reaches the copy handler and Escape closes', async () => {+ const user = userEvent.setup();+ const props = renderModal({ placeIds: [] });++ fireEvent.click(await screen.findByText('Rome 2026'));+ expect(props.onCopy).not.toHaveBeenCalled();++ await user.keyboard('{Escape}');+ expect(props.onClose).toHaveBeenCalledTimes(1);+ });+});diff --git a/client/src/components/Collections/LabelManager.test.tsx b/client/src/components/Collections/LabelManager.test.tsxnew file mode 100644index 000000000..d2974d627--- /dev/null+++ b/client/src/components/Collections/LabelManager.test.tsx@@ -0,0 +1,172 @@+// FE-COMP-LABELMGR-001 to FE-COMP-LABELMGR-013+import React from 'react';+import { render, screen, waitFor, within } from '../../../tests/helpers/render';+import userEvent from '@testing-library/user-event';+import type { CollectionLabel } from '@trek/shared';+import { useTranslation } from '../../i18n/TranslationContext';+import LabelManager from './LabelManager';++type ManagerProps = Omit<React.ComponentProps<typeof LabelManager>, 't'>;++function Harness(props: ManagerProps): React.ReactElement {+ const { t } = useTranslation();+ return <LabelManager {...props} t={t} />;+}++const berlin: CollectionLabel = { id: 1, collection_id: 10, name: 'Berlin', color: '#0ea5e9' };+const food: CollectionLabel = { id: 2, collection_id: 10, name: 'Food', color: null };++function renderManager(overrides: Partial<ManagerProps> = {}) {+ const props: ManagerProps = {+ isOpen: true,+ labels: [berlin, food],+ onCreate: vi.fn(async () => {}),+ onUpdate: vi.fn(async () => {}),+ onDelete: vi.fn(async () => {}),+ onClose: vi.fn(),+ ...overrides,+ };+ render(<Harness {...props} />);+ return props;+}++/** The row whose rename input carries the given label name. */+function row(name: string): HTMLElement {+ return screen.getByDisplayValue(name).closest('div') as HTMLElement;+}++describe('LabelManager', () => {+ it('FE-COMP-LABELMGR-001: renders one editable row per label under the manage title', () => {+ renderManager();+ expect(screen.getByRole('heading', { name: 'Manage labels' })).toBeInTheDocument();+ expect(screen.getByDisplayValue('Berlin')).toBeInTheDocument();+ expect(screen.getByDisplayValue('Food')).toBeInTheDocument();+ });++ it('FE-COMP-LABELMGR-002: shows the empty copy and no rows when the list has no labels', () => {+ renderManager({ labels: [] });+ expect(screen.getByText('No labels yet')).toBeInTheDocument();+ expect(screen.queryByLabelText('Label name')).not.toBeInTheDocument();+ });++ it('FE-COMP-LABELMGR-003: renders nothing at all while closed', () => {+ renderManager({ isOpen: false });+ expect(screen.queryByRole('heading', { name: 'Manage labels' })).not.toBeInTheDocument();+ });++ it('FE-COMP-LABELMGR-004: the Add button stays disabled until a name is typed', async () => {+ const user = userEvent.setup();+ renderManager();+ const add = screen.getByRole('button', { name: /Add label/ });+ expect(add).toBeDisabled();++ await user.type(screen.getByPlaceholderText('e.g. Berlin'), 'Nightlife');+ expect(add).toBeEnabled();+ });++ it('FE-COMP-LABELMGR-005: adding a label passes the trimmed name plus the picked colour and clears the form', async () => {+ const user = userEvent.setup();+ const props = renderManager();++ await user.type(screen.getByPlaceholderText('e.g. Berlin'), ' Nightlife ');+ await user.click(screen.getByRole('button', { name: /Add label/ }));++ await waitFor(() => expect(props.onCreate).toHaveBeenCalledWith('Nightlife', '#6366f1'));+ expect(screen.getByPlaceholderText('e.g. Berlin')).toHaveValue('');+ });++ it('FE-COMP-LABELMGR-006: picking a swatch in the create form changes the colour sent to onCreate', async () => {+ const user = userEvent.setup();+ const props = renderManager({ labels: [] });++ // The only swatch row on screen belongs to the create form (no label rows).+ await user.click(screen.getByRole('button', { name: '#10b981' }));+ await user.type(screen.getByPlaceholderText('e.g. Berlin'), 'Nature');+ await user.click(screen.getByRole('button', { name: /Add label/ }));++ await waitFor(() => expect(props.onCreate).toHaveBeenCalledWith('Nature', '#10b981'));+ });++ it('FE-COMP-LABELMGR-007: Enter in the name field creates the label too', async () => {+ const user = userEvent.setup();+ const props = renderManager({ labels: [] });++ await user.type(screen.getByPlaceholderText('e.g. Berlin'), 'Museums{Enter}');+ await waitFor(() => expect(props.onCreate).toHaveBeenCalledWith('Museums', '#6366f1'));+ });++ it('FE-COMP-LABELMGR-008: a whitespace-only name never reaches onCreate', async () => {+ const user = userEvent.setup();+ const props = renderManager({ labels: [] });++ await user.type(screen.getByPlaceholderText('e.g. Berlin'), ' {Enter}');+ expect(props.onCreate).not.toHaveBeenCalled();+ });++ it('FE-COMP-LABELMGR-009: a second submit while the first create is still pending is ignored', async () => {+ const user = userEvent.setup();+ const onCreate = vi.fn(() => new Promise<void>(() => {}));+ renderManager({ labels: [], onCreate });++ const input = screen.getByPlaceholderText('e.g. Berlin');+ await user.type(input, 'Slow{Enter}');+ await user.type(input, '{Enter}');++ expect(onCreate).toHaveBeenCalledTimes(1);+ // The button shows the pending spinner while the promise is open.+ expect(screen.getByRole('button', { name: /Add label/ }).querySelector('.animate-spin')).not.toBeNull();+ });++ it('FE-COMP-LABELMGR-010: renaming a label commits the trimmed name on blur', async () => {+ const user = userEvent.setup();+ const props = renderManager();++ const input = screen.getByDisplayValue('Berlin');+ await user.clear(input);+ await user.type(input, 'Berlin Mitte');+ await user.tab();++ await waitFor(() => expect(props.onUpdate).toHaveBeenCalledWith(1, { name: 'Berlin Mitte' }));+ });++ it('FE-COMP-LABELMGR-011: Enter commits the rename, an unchanged or empty name reverts instead', async () => {+ const user = userEvent.setup();+ const props = renderManager();++ const input = screen.getByDisplayValue('Food');+ await user.type(input, ' Trucks{Enter}');+ await waitFor(() => expect(props.onUpdate).toHaveBeenCalledWith(2, { name: 'Food Trucks' }));+ expect(props.onUpdate).toHaveBeenCalledTimes(1);++ // Focus + blur without a change must not fire a second update.+ const berlinInput = screen.getByDisplayValue('Berlin');+ await user.click(berlinInput);+ await user.tab();+ expect(props.onUpdate).toHaveBeenCalledTimes(1);++ // Emptying the field restores the stored name rather than saving a blank one.+ await user.clear(berlinInput);+ await user.tab();+ expect(screen.getByDisplayValue('Berlin')).toBeInTheDocument();+ expect(props.onUpdate).toHaveBeenCalledTimes(1);+ });++ it('FE-COMP-LABELMGR-012: recolouring a row saves the new colour immediately', async () => {+ const user = userEvent.setup();+ const props = renderManager();++ await user.click(within(row('Berlin')).getByRole('button', { name: '#ef4444' }));+ await waitFor(() => expect(props.onUpdate).toHaveBeenCalledWith(1, { color: '#ef4444' }));+ });++ it('FE-COMP-LABELMGR-013: the row delete button passes the label id, the modal close hands back', async () => {+ const user = userEvent.setup();+ const props = renderManager();++ await user.click(within(row('Food')).getByRole('button', { name: 'Delete' }));+ expect(props.onDelete).toHaveBeenCalledWith(2);++ await user.keyboard('{Escape}');+ expect(props.onClose).toHaveBeenCalledTimes(1);+ });+});diff --git a/client/src/components/Collections/ListEditorModal.test.tsx b/client/src/components/Collections/ListEditorModal.test.tsxnew file mode 100644index 000000000..7b965a37e--- /dev/null+++ b/client/src/components/Collections/ListEditorModal.test.tsx@@ -0,0 +1,347 @@+// FE-COMP-LISTEDITOR-001 to FE-COMP-LISTEDITOR-025+import React from 'react'+import type { Mock } from 'vitest'+import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render'+import type { Collection } from '@trek/shared'+import { useCollectionStore } from '../../store/collectionStore'+import { tripsApi } from '../../api/client'+import { useTranslation } from '../../i18n/TranslationContext'+import ListEditorModal from './ListEditorModal'++// The modal takes `t` as a prop, so a harness forwards the real English+// translator from the provider the render helper mounts.+type Props = React.ComponentProps<typeof ListEditorModal>+function Harness(props: Omit<Props, 't'>): React.ReactElement {+ const { t } = useTranslation()+ return <ListEditorModal {...props} t={t} />+}++const existing: Collection = {+ id: 42,+ owner_id: 1,+ name: 'Tokyo 2026',+ color: '#ec4899',+ description: 'Ramen shortlist',+ links: [{ label: 'Guide', url: 'https://guide.example' }],+ cover_image: '/uploads/covers/tokyo.jpg',+ is_owner: true,+}++type CollectionStore = ReturnType<typeof useCollectionStore.getState>+type AddToast = NonNullable<typeof window.__addToast>++const initialCollectionState = useCollectionStore.getState()+let actions: {+ createCollection: Mock<CollectionStore['createCollection']>+ updateCollection: Mock<CollectionStore['updateCollection']>+ uploadCover: Mock<CollectionStore['uploadCover']>+}+let addToast: Mock<AddToast>++const realCreateObjectURL = URL.createObjectURL+const realRevokeObjectURL = URL.revokeObjectURL+function stubObjectUrl(value: unknown, revoke: unknown): void {+ Object.defineProperty(URL, 'createObjectURL', { writable: true, configurable: true, value })+ Object.defineProperty(URL, 'revokeObjectURL', { writable: true, configurable: true, value: revoke })+}++function setup(over: Partial<Omit<Props, 't'>> = {}) {+ const props: Omit<Props, 't'> = {+ target: 'new',+ onClose: vi.fn(),+ onCreated: vi.fn(),+ onRequestDelete: vi.fn(),+ ...over,+ }+ const view = render(<Harness {...props} />)+ return { ...view, props }+}++describe('ListEditorModal', () => {+ beforeEach(() => {+ useCollectionStore.setState(initialCollectionState, true)+ actions = {+ createCollection: vi.fn<CollectionStore['createCollection']>(async () => ({ id: 77, owner_id: 1, name: 'Fresh' })),+ updateCollection: vi.fn<CollectionStore['updateCollection']>(async () => undefined),+ uploadCover: vi.fn<CollectionStore['uploadCover']>(async () => undefined),+ }+ useCollectionStore.setState(actions)+ addToast = vi.fn<AddToast>(() => 0)+ window.__addToast = addToast+ // Node's URL.createObjectURL rejects a jsdom File, so the preview blob is stubbed.+ stubObjectUrl(vi.fn(() => 'blob:cover-preview'), vi.fn())+ vi.spyOn(tripsApi, 'searchCoverImages').mockResolvedValue({+ photos: [+ { id: 'p1', url: 'https://img/full1.jpg', thumb: 'https://img/thumb1.jpg', description: 'A street', photographer: 'Rin' },+ { id: 'p2', url: 'https://img/full2.jpg', thumb: 'https://img/thumb2.jpg', description: null, photographer: null },+ ],+ })+ })++ afterEach(() => {+ vi.restoreAllMocks()+ delete window.__addToast+ stubObjectUrl(realCreateObjectURL, realRevokeObjectURL)+ })++ it('FE-COMP-LISTEDITOR-001: renders nothing while the target is null', () => {+ setup({ target: null })+ expect(screen.queryByRole('heading', { name: /New list|Edit list/ })).not.toBeInTheDocument()+ })++ it('FE-COMP-LISTEDITOR-002: create mode shows the New list title and a Create action', () => {+ setup()+ expect(screen.getByRole('heading', { name: 'New list' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Create' })).toBeDisabled()+ expect(screen.queryByRole('button', { name: /Delete list/ })).not.toBeInTheDocument()+ })++ it('FE-COMP-LISTEDITOR-003: edit mode seeds name, description, links and the cover preview', () => {+ setup({ target: existing })+ expect(screen.getByRole('heading', { name: 'Edit list' })).toBeInTheDocument()+ expect(screen.getByDisplayValue('Tokyo 2026')).toBeInTheDocument()+ expect(screen.getByDisplayValue('Ramen shortlist')).toBeInTheDocument()+ expect(screen.getByDisplayValue('Guide')).toBeInTheDocument()+ expect(screen.getByDisplayValue('https://guide.example')).toBeInTheDocument()+ // A seeded cover flips the button label and paints the image.+ expect(screen.getByRole('button', { name: 'Change cover' })).toBeInTheDocument()+ expect(document.querySelector('img[src="/uploads/covers/tokyo.jpg"]')).toBeTruthy()+ })++ it('FE-COMP-LISTEDITOR-004: the owner gets a Delete list action that closes and hands off the id', () => {+ const { props } = setup({ target: existing })+ fireEvent.click(screen.getByRole('button', { name: /Delete list/ }))+ expect(props.onClose).toHaveBeenCalledTimes(1)+ expect(props.onRequestDelete).toHaveBeenCalledWith(42)+ })++ it('FE-COMP-LISTEDITOR-005: a non-owner editor sees no Delete list action', () => {+ setup({ target: { ...existing, is_owner: false } })+ expect(screen.queryByRole('button', { name: /Delete list/ })).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Save' })).toBeInTheDocument()+ })++ it('FE-COMP-LISTEDITOR-006: creating posts the trimmed payload and reports the new id', async () => {+ const { props } = setup()+ fireEvent.change(screen.getByPlaceholderText('e.g. Tokyo 2025'), { target: { value: ' Rome ' } })+ fireEvent.change(screen.getByPlaceholderText('Add a description…'), { target: { value: ' gelato ' } })+ fireEvent.click(screen.getByRole('button', { name: 'Create' }))++ await waitFor(() => expect(actions.createCollection).toHaveBeenCalledTimes(1))+ expect(actions.createCollection).toHaveBeenCalledWith({+ name: 'Rome',+ color: '#6366f1',+ description: 'gelato',+ links: [],+ })+ expect(props.onCreated).toHaveBeenCalledWith(77)+ expect(props.onClose).toHaveBeenCalledTimes(1)+ })++ it('FE-COMP-LISTEDITOR-007: an empty description is sent as null', async () => {+ setup()+ fireEvent.change(screen.getByPlaceholderText('e.g. Tokyo 2025'), { target: { value: 'Rome' } })+ fireEvent.click(screen.getByRole('button', { name: 'Create' }))+ await waitFor(() => expect(actions.createCollection).toHaveBeenCalled())+ expect(actions.createCollection.mock.calls[0][0].description).toBeNull()+ })++ it('FE-COMP-LISTEDITOR-008: editing patches the existing list and never calls onCreated', async () => {+ const { props } = setup({ target: existing })+ fireEvent.change(screen.getByDisplayValue('Tokyo 2026'), { target: { value: 'Tokyo 2027' } })+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => expect(actions.updateCollection).toHaveBeenCalledTimes(1))+ expect(actions.updateCollection).toHaveBeenCalledWith(42, expect.objectContaining({ name: 'Tokyo 2027', color: '#ec4899' }))+ expect(actions.createCollection).not.toHaveBeenCalled()+ expect(props.onCreated).not.toHaveBeenCalled()+ expect(props.onClose).toHaveBeenCalledTimes(1)+ })++ it('FE-COMP-LISTEDITOR-009: Enter in the name field saves', async () => {+ setup()+ const nameInput = screen.getByPlaceholderText('e.g. Tokyo 2025')+ fireEvent.change(nameInput, { target: { value: 'Lisbon' } })+ fireEvent.keyDown(nameInput, { key: 'Enter' })+ await waitFor(() => expect(actions.createCollection).toHaveBeenCalled())+ })++ it('FE-COMP-LISTEDITOR-010: Enter on a blank name does nothing', () => {+ setup()+ fireEvent.keyDown(screen.getByPlaceholderText('e.g. Tokyo 2025'), { key: 'Enter' })+ expect(actions.createCollection).not.toHaveBeenCalled()+ })++ it('FE-COMP-LISTEDITOR-011: picking a swatch changes the saved colour', async () => {+ setup()+ fireEvent.change(screen.getByPlaceholderText('e.g. Tokyo 2025'), { target: { value: 'Oslo' } })+ fireEvent.click(screen.getByRole('button', { name: '#22c55e' }))+ fireEvent.click(screen.getByRole('button', { name: 'Create' }))+ await waitFor(() => expect(actions.createCollection).toHaveBeenCalled())+ expect(actions.createCollection.mock.calls[0][0].color).toBe('#22c55e')+ })++ it('FE-COMP-LISTEDITOR-012: links are normalised, labelled and blank rows are dropped', async () => {+ setup()+ fireEvent.change(screen.getByPlaceholderText('e.g. Tokyo 2025'), { target: { value: 'Oslo' } })+ fireEvent.click(screen.getByRole('button', { name: /Add link/ }))+ fireEvent.click(screen.getByRole('button', { name: /Add link/ }))++ const urls = screen.getAllByPlaceholderText('https://…')+ const labels = screen.getAllByPlaceholderText('Label')+ fireEvent.change(labels[0], { target: { value: ' Menu ' } })+ fireEvent.change(urls[0], { target: { value: 'example.com/menu' } })+ // The second row stays blank and must not reach the payload.+ fireEvent.click(screen.getByRole('button', { name: 'Create' }))++ await waitFor(() => expect(actions.createCollection).toHaveBeenCalled())+ expect(actions.createCollection.mock.calls[0][0].links).toEqual([+ { label: 'Menu', url: 'https://example.com/menu' },+ ])+ })++ it('FE-COMP-LISTEDITOR-013: a link row can be removed again', () => {+ setup({ target: existing })+ expect(screen.getByDisplayValue('https://guide.example')).toBeInTheDocument()+ fireEvent.click(screen.getAllByRole('button', { name: 'Delete' })[0])+ expect(screen.queryByDisplayValue('https://guide.example')).not.toBeInTheDocument()+ })++ it('FE-COMP-LISTEDITOR-014: choosing a file shows a preview and uploads it after the create', async () => {+ const file = new File(['x'], 'cover.png', { type: 'image/png' })+ const { container } = setup()+ fireEvent.change(screen.getByPlaceholderText('e.g. Tokyo 2025'), { target: { value: 'Oslo' } })+ const fileInput = container.ownerDocument.querySelector('input[type="file"]') as HTMLInputElement+ fireEvent.change(fileInput, { target: { files: [file] } })++ expect(screen.getByRole('button', { name: 'Change cover' })).toBeInTheDocument()+ expect(document.querySelector('img[src="blob:cover-preview"]')).toBeTruthy()++ fireEvent.click(screen.getByRole('button', { name: 'Create' }))+ await waitFor(() => expect(actions.uploadCover).toHaveBeenCalledWith(77, file))+ })++ it('FE-COMP-LISTEDITOR-015: the cover tile opens the file picker, and an empty pick leaves the cover alone', () => {+ const { container } = setup()+ const fileInput = container.ownerDocument.querySelector('input[type="file"]') as HTMLInputElement+ const openPicker = vi.fn()+ fileInput.addEventListener('click', openPicker)++ fireEvent.click(screen.getByRole('button', { name: 'Add cover' }))+ expect(openPicker).toHaveBeenCalledTimes(1)++ fireEvent.change(fileInput, { target: { files: [] } })+ expect(screen.getByRole('button', { name: 'Add cover' })).toBeInTheDocument()+ })++ it('FE-COMP-LISTEDITOR-016: the Unsplash search renders results and the picked photo becomes cover_image', async () => {+ setup()+ fireEvent.change(screen.getByPlaceholderText('e.g. Tokyo 2025'), { target: { value: 'Oslo' } })+ fireEvent.change(screen.getByPlaceholderText('Search destination photos'), { target: { value: 'fjord' } })+ fireEvent.click(screen.getByRole('button', { name: /Search Unsplash/ }))++ expect(await screen.findByRole('button', { name: 'Rin' })).toBeInTheDocument()+ expect(tripsApi.searchCoverImages).toHaveBeenCalledWith('fjord')+ // A photo without a photographer falls back to the generic label.+ fireEvent.click(screen.getByRole('button', { name: 'Unsplash' }))+ expect(document.querySelector('img[src="https://img/full2.jpg"]')).toBeTruthy()++ fireEvent.click(screen.getByRole('button', { name: 'Create' }))+ await waitFor(() => expect(actions.createCollection).toHaveBeenCalled())+ expect(actions.createCollection.mock.calls[0][0].cover_image).toBe('https://img/full2.jpg')+ expect(actions.uploadCover).not.toHaveBeenCalled()+ })++ it('FE-COMP-LISTEDITOR-017: an empty query falls back to the list name, Enter triggers the search', async () => {+ setup()+ const query = screen.getByPlaceholderText('Search destination photos')+ fireEvent.change(screen.getByPlaceholderText('e.g. Tokyo 2025'), { target: { value: 'Bergen' } })+ fireEvent.keyDown(query, { key: 'Enter' })+ await waitFor(() => expect(tripsApi.searchCoverImages).toHaveBeenCalledWith('Bergen'))+ })++ it('FE-COMP-LISTEDITOR-018: with neither a query nor a name the search button stays disabled', () => {+ setup()+ expect(screen.getByRole('button', { name: /Search Unsplash/ })).toBeDisabled()+ })++ it('FE-COMP-LISTEDITOR-019: a failing cover search clears the result grid', async () => {+ vi.mocked(tripsApi.searchCoverImages).mockRejectedValueOnce(new Error('offline'))+ setup()+ fireEvent.change(screen.getByPlaceholderText('Search destination photos'), { target: { value: 'fjord' } })+ fireEvent.click(screen.getByRole('button', { name: /Search Unsplash/ }))+ await waitFor(() => expect(tripsApi.searchCoverImages).toHaveBeenCalled())+ expect(screen.queryByRole('button', { name: 'Rin' })).not.toBeInTheDocument()+ })++ it('FE-COMP-LISTEDITOR-020: an uploaded file wins over a previously picked Unsplash photo', async () => {+ const file = new File(['x'], 'cover.png', { type: 'image/png' })+ const { container } = setup()+ fireEvent.change(screen.getByPlaceholderText('e.g. Tokyo 2025'), { target: { value: 'Oslo' } })+ fireEvent.change(screen.getByPlaceholderText('Search destination photos'), { target: { value: 'fjord' } })+ fireEvent.click(screen.getByRole('button', { name: /Search Unsplash/ }))+ fireEvent.click(await screen.findByRole('button', { name: 'Rin' }))++ const fileInput = container.ownerDocument.querySelector('input[type="file"]') as HTMLInputElement+ fireEvent.change(fileInput, { target: { files: [file] } })+ fireEvent.click(screen.getByRole('button', { name: 'Create' }))++ await waitFor(() => expect(actions.createCollection).toHaveBeenCalled())+ expect(actions.createCollection.mock.calls[0][0].cover_image).toBeUndefined()+ await waitFor(() => expect(actions.uploadCover).toHaveBeenCalledWith(77, file))+ })++ it('FE-COMP-LISTEDITOR-021: a failed cover upload toasts the server message and the retry updates instead of re-creating', async () => {+ actions.uploadCover.mockRejectedValueOnce({ response: { data: { error: 'Cover too large' } } })+ const file = new File(['x'], 'cover.png', { type: 'image/png' })+ const { container, props } = setup()+ fireEvent.change(screen.getByPlaceholderText('e.g. Tokyo 2025'), { target: { value: 'Oslo' } })+ fireEvent.change(container.ownerDocument.querySelector('input[type="file"]') as HTMLInputElement, { target: { files: [file] } })++ fireEvent.click(screen.getByRole('button', { name: 'Create' }))+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Cover too large', 'error', undefined))+ expect(props.onClose).not.toHaveBeenCalled()++ // Retry: the id from the first (successful) create is reused.+ fireEvent.click(screen.getByRole('button', { name: 'Create' }))+ await waitFor(() => expect(actions.updateCollection).toHaveBeenCalledWith(77, expect.objectContaining({ name: 'Oslo' })))+ expect(actions.createCollection).toHaveBeenCalledTimes(1)+ })++ it('FE-COMP-LISTEDITOR-022: switching the target reseeds the form', () => {+ const { rerender, props } = setup({ target: existing })+ fireEvent.change(screen.getByDisplayValue('Tokyo 2026'), { target: { value: 'scratch' } })+ rerender(<Harness {...props} target="new" />)+ expect(screen.queryByDisplayValue('scratch')).not.toBeInTheDocument()+ expect(screen.getByRole('heading', { name: 'New list' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Add cover' })).toBeInTheDocument()+ })++ it('FE-COMP-LISTEDITOR-023: a create that fails outright keeps the modal open and reports the error', async () => {+ actions.createCollection.mockRejectedValueOnce(new Error('boom'))+ const { props } = setup()+ fireEvent.change(screen.getByPlaceholderText('e.g. Tokyo 2025'), { target: { value: 'Oslo' } })+ fireEvent.click(screen.getByRole('button', { name: 'Create' }))+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('boom', 'error', undefined))+ expect(props.onClose).not.toHaveBeenCalled()+ // The save button releases again so the user can retry.+ await waitFor(() => expect(screen.getByRole('button', { name: 'Create' })).not.toBeDisabled())+ })++ it('FE-COMP-LISTEDITOR-024: unmounting revokes the last preview blob', () => {+ const revoke = vi.fn()+ stubObjectUrl(vi.fn(() => 'blob:cover-preview'), revoke)+ const file = new File(['x'], 'cover.png', { type: 'image/png' })+ const { container, unmount } = setup()+ fireEvent.change(container.ownerDocument.querySelector('input[type="file"]') as HTMLInputElement, { target: { files: [file] } })+ unmount()+ expect(revoke).toHaveBeenCalledWith('blob:cover-preview')+ })++ it('FE-COMP-LISTEDITOR-025: Cancel closes without touching the store', () => {+ const { props } = setup({ target: existing })+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))+ expect(props.onClose).toHaveBeenCalledTimes(1)+ expect(actions.updateCollection).not.toHaveBeenCalled()+ })+})diff --git a/client/src/components/Collections/ListsRail.test.tsx b/client/src/components/Collections/ListsRail.test.tsxnew file mode 100644index 000000000..192317e67--- /dev/null+++ b/client/src/components/Collections/ListsRail.test.tsx@@ -0,0 +1,130 @@+// FE-COMP-LISTSRAIL-001 to FE-COMP-LISTSRAIL-010+import React from 'react';+import { render, screen, within } from '../../../tests/helpers/render';+import userEvent from '@testing-library/user-event';+import type { Collection } from '@trek/shared';+import { useTranslation } from '../../i18n/TranslationContext';+import { ALL_SAVED } from '../../store/collectionStore';+import type { IncomingCollectionInvite } from '../../store/collectionStore';+import ListsRail from './ListsRail';++// The rail takes `t` as a prop, so a harness forwards the real English translator+// from the provider the render helper mounts.+type RailProps = Omit<React.ComponentProps<typeof ListsRail>, 't'>;++function Harness(props: RailProps): React.ReactElement {+ const { t } = useTranslation();+ return <ListsRail {...props} t={t} />;+}++const rome: Collection = { id: 11, owner_id: 1, name: 'Weekend in Rome', color: '#ef4444', place_count: 3 };+const tokyo: Collection = { id: 22, owner_id: 1, name: 'Tokyo Food Tour', color: null };+const shared: Collection = { id: 33, owner_id: 9, name: 'Family trip', color: '#22c55e', place_count: 7, is_owner: false };++const invite: IncomingCollectionInvite = {+ collection_id: 44,+ name: 'Iceland ideas',+ from: { id: 5, username: 'kim' },+};++function renderRail(overrides: Partial<RailProps> = {}) {+ const props: RailProps = {+ ownedLists: [rome, tokyo],+ sharedLists: [],+ activeId: rome.id,+ incomingInvites: [],+ onSelect: vi.fn(),+ onNewList: vi.fn(),+ onAcceptInvite: vi.fn(),+ onDeclineInvite: vi.fn(),+ ...overrides,+ };+ render(<Harness {...props} />);+ return props;+}++describe('ListsRail', () => {+ it('FE-COMP-LISTSRAIL-001: renders the new-list action, the All saved row and every owned list', () => {+ renderRail();+ expect(screen.getByRole('button', { name: 'New list' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'All saved' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /Weekend in Rome/ })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /Tokyo Food Tour/ })).toBeInTheDocument();+ });++ it('FE-COMP-LISTSRAIL-002: shows the place count per list and falls back to 0 when absent', () => {+ renderRail();+ expect(within(screen.getByRole('button', { name: /Weekend in Rome/ })).getByText('3')).toBeInTheDocument();+ // tokyo carries no place_count — the rail renders 0 rather than an empty slot.+ expect(within(screen.getByRole('button', { name: /Tokyo Food Tour/ })).getByText('0')).toBeInTheDocument();+ });++ it('FE-COMP-LISTSRAIL-003: marks only the active list row with the "on" class', () => {+ renderRail({ activeId: tokyo.id });+ expect(screen.getByRole('button', { name: /Tokyo Food Tour/ })).toHaveClass('on');+ expect(screen.getByRole('button', { name: /Weekend in Rome/ })).not.toHaveClass('on');+ expect(screen.getByRole('button', { name: 'All saved' })).not.toHaveClass('on');+ });++ it('FE-COMP-LISTSRAIL-004: marks the All saved row active when activeId is the sentinel', () => {+ renderRail({ activeId: ALL_SAVED });+ expect(screen.getByRole('button', { name: 'All saved' })).toHaveClass('on');+ expect(screen.getByRole('button', { name: /Weekend in Rome/ })).not.toHaveClass('on');+ });++ it('FE-COMP-LISTSRAIL-005: clicking a list row selects it by id, All saved selects the sentinel', async () => {+ const user = userEvent.setup();+ const props = renderRail();++ await user.click(screen.getByRole('button', { name: /Tokyo Food Tour/ }));+ expect(props.onSelect).toHaveBeenCalledWith(22);++ await user.click(screen.getByRole('button', { name: 'All saved' }));+ expect(props.onSelect).toHaveBeenCalledWith(ALL_SAVED);+ });++ it('FE-COMP-LISTSRAIL-006: the new-list button calls onNewList', async () => {+ const user = userEvent.setup();+ const props = renderRail();+ await user.click(screen.getByRole('button', { name: 'New list' }));+ expect(props.onNewList).toHaveBeenCalledTimes(1);+ });++ it('FE-COMP-LISTSRAIL-007: renders a Shared section with its lists only when there are shared lists', () => {+ const { unmount } = render(<Harness {...{+ ownedLists: [rome], sharedLists: [], activeId: null, incomingInvites: [],+ onSelect: vi.fn(), onNewList: vi.fn(), onAcceptInvite: vi.fn(), onDeclineInvite: vi.fn(),+ }} />);+ expect(screen.queryByText('Shared')).not.toBeInTheDocument();+ unmount();++ renderRail({ sharedLists: [shared] });+ expect(screen.getByText('Shared')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /Family trip/ })).toBeInTheDocument();+ });++ it('FE-COMP-LISTSRAIL-008: renders the invites block with the sender name and a count badge', () => {+ renderRail({ incomingInvites: [invite] });+ expect(screen.getByText('Iceland ideas')).toBeInTheDocument();+ expect(screen.getByText('from kim')).toBeInTheDocument();+ expect(screen.getByText('Invites').querySelector('.badge')?.textContent).toBe('1');+ });++ it('FE-COMP-LISTSRAIL-009: accepting and declining an invite pass the collection id', async () => {+ const user = userEvent.setup();+ const props = renderRail({ incomingInvites: [invite] });++ await user.click(screen.getByRole('button', { name: 'Accept' }));+ expect(props.onAcceptInvite).toHaveBeenCalledWith(44);++ await user.click(screen.getByRole('button', { name: 'Decline' }));+ expect(props.onDeclineInvite).toHaveBeenCalledWith(44);+ });++ it('FE-COMP-LISTSRAIL-010: with no owned lists, no separator and no invite block render', () => {+ renderRail({ ownedLists: [], activeId: ALL_SAVED });+ expect(document.querySelector('.col-rail-sep')).toBeNull();+ expect(screen.queryByText('Invites')).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'All saved' })).toBeInTheDocument();+ });+});diff --git a/client/src/components/Collections/MSaveToCollectionSheet.test.tsx b/client/src/components/Collections/MSaveToCollectionSheet.test.tsxnew file mode 100644index 000000000..f45983261--- /dev/null+++ b/client/src/components/Collections/MSaveToCollectionSheet.test.tsx@@ -0,0 +1,266 @@+// FE-COMP-MSAVESHEET-001 to FE-COMP-MSAVESHEET-016+import React from 'react';+import { afterEach, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render';+import type { Collection, CollectionListResponse, CollectionMembership, CollectionSaveResult } from '@trek/shared';+import { collectionsApi } from '../../api/collections';+import { useSaveToCollectionStore } from '../../store/saveToCollectionStore';+import type { SaveToCollectionTarget } from '../../store/saveToCollectionStore';+import MSaveToCollectionSheet from './MSaveToCollectionSheet';++const mockNavigate = vi.fn();+vi.mock('react-router-dom', async () => {+ const actual = await vi.importActual('react-router-dom');+ return { ...actual, useNavigate: () => mockNavigate };+});++function list(over: Partial<Collection>): Collection {+ return { id: 1, owner_id: 7, name: 'List', color: null, place_count: 0, ...over } as Collection;+}++const FAVORITES = list({ id: 1, name: 'Favorites', color: '#ef4444', place_count: 4 });+const WISHLIST = list({ id: 2, name: 'Wishlist' });+const SHARED = list({ id: 3, name: 'Team ideas', is_owner: false });++const listResponse = (collections: Collection[]): CollectionListResponse => ({ collections, incomingInvites: [] });+const EMPTY_MEMBERSHIP: CollectionMembership = { saved: false, lists: [] };++const TARGET: SaveToCollectionTarget = {+ name: 'Colosseum',+ source_trip_id: 5,+ source_place_id: 42,+ lat: 41.89,+ lng: 12.49,+ google_place_id: 'gp-1',+ google_ftid: 'ft-1',+};++let addToast: ReturnType<typeof vi.fn>;++function openFor(target: SaveToCollectionTarget = TARGET) {+ useSaveToCollectionStore.setState({ target, version: 0 });+}++beforeEach(() => {+ addToast = vi.fn();+ window.__addToast = addToast as unknown as typeof window.__addToast;+ mockNavigate.mockClear();+ useSaveToCollectionStore.setState({ target: null, version: 0 });+ vi.spyOn(collectionsApi, 'list').mockResolvedValue(listResponse([FAVORITES, WISHLIST]));+ vi.spyOn(collectionsApi, 'membership').mockResolvedValue(EMPTY_MEMBERSHIP);+});++afterEach(() => {+ vi.restoreAllMocks();+ useSaveToCollectionStore.setState({ target: null, version: 0 });+ delete window.__addToast;+});++describe('MSaveToCollectionSheet', () => {+ it('FE-COMP-MSAVESHEET-001: stays closed and silent while no target is set', () => {+ render(<MSaveToCollectionSheet />);+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+ expect(collectionsApi.list).not.toHaveBeenCalled();+ });++ it('FE-COMP-MSAVESHEET-002: opens a labelled sheet showing the target name and the lists', async () => {+ openFor();+ render(<MSaveToCollectionSheet />);++ expect(await screen.findByText('Favorites')).toBeInTheDocument();+ expect(screen.getByRole('dialog', { name: 'Save to list' })).toBeInTheDocument();+ expect(screen.getByText('Colosseum')).toBeInTheDocument();+ expect(screen.getByText('4 places')).toBeInTheDocument();+ expect(screen.getByText('0 places')).toBeInTheDocument();+ });++ it('FE-COMP-MSAVESHEET-003: queries membership with the maps identity of the target', async () => {+ openFor();+ render(<MSaveToCollectionSheet />);+ await screen.findByText('Favorites');+ expect(collectionsApi.membership).toHaveBeenCalledWith({+ google_place_id: 'gp-1',+ google_ftid: 'ft-1',+ name: 'Colosseum',+ lat: 41.89,+ lng: 12.49,+ });+ });++ it('FE-COMP-MSAVESHEET-004: shows the spinner until the lists arrive', async () => {+ let resolve!: (v: CollectionListResponse) => void;+ vi.spyOn(collectionsApi, 'list').mockReturnValue(new Promise(r => { resolve = r; }));+ openFor();+ render(<MSaveToCollectionSheet />);+ expect(document.querySelector('.animate-spin')).not.toBeNull();++ resolve(listResponse([FAVORITES]));+ expect(await screen.findByText('Favorites')).toBeInTheDocument();+ });++ it('FE-COMP-MSAVESHEET-005: a failing list request shows the empty state and its create shortcut', async () => {+ vi.spyOn(collectionsApi, 'list').mockRejectedValue(new Error('offline'));+ openFor();+ render(<MSaveToCollectionSheet />);++ expect(await screen.findByText('Create a list first to save places.')).toBeInTheDocument();+ // With no lists the sheet drops its footer bar entirely.+ expect(screen.queryByRole('button', { name: 'View' })).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: /New list/ }));+ expect(mockNavigate).toHaveBeenCalledWith('/collections');+ expect(useSaveToCollectionStore.getState().target).toBeNull();+ });++ it('FE-COMP-MSAVESHEET-006: lists already holding the place are marked saved', async () => {+ vi.spyOn(collectionsApi, 'membership').mockResolvedValue({+ saved: true,+ lists: [{ collection_id: 1, name: 'Favorites', place_id: 900 }],+ });+ openFor();+ render(<MSaveToCollectionSheet />);++ const favorites = await screen.findByRole('button', { name: /Favorites/ });+ expect(favorites.querySelector('.lucide-bookmark-check')).not.toBeNull();+ expect(screen.getByRole('button', { name: /Wishlist/ }).querySelector('.lucide-bookmark-check')).toBeNull();+ });++ it('FE-COMP-MSAVESHEET-007: a failing membership lookup degrades to "saved nowhere"', async () => {+ vi.spyOn(collectionsApi, 'membership').mockRejectedValue(new Error('offline'));+ openFor();+ render(<MSaveToCollectionSheet />);++ const favorites = await screen.findByRole('button', { name: /Favorites/ });+ expect(favorites.querySelector('.lucide-bookmark-check')).toBeNull();+ });++ it('FE-COMP-MSAVESHEET-008: a shared list carries the SHARED badge', async () => {+ vi.spyOn(collectionsApi, 'list').mockResolvedValue(listResponse([FAVORITES, SHARED]));+ openFor();+ render(<MSaveToCollectionSheet />);++ const shared = await screen.findByRole('button', { name: /Team ideas/ });+ expect(within(shared).getByText('Shared')).toBeInTheDocument();+ });++ it('FE-COMP-MSAVESHEET-009: tapping an unsaved list saves the target and bumps the version', async () => {+ const save = vi.spyOn(collectionsApi, 'savePlace').mockResolvedValue({});+ openFor();+ render(<MSaveToCollectionSheet />);++ fireEvent.click(await screen.findByRole('button', { name: /Wishlist/ }));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Added to Wishlist', 'success', undefined));+ expect(save).toHaveBeenCalledWith(expect.objectContaining({+ collection_id: 2,+ source_trip_id: 5,+ source_place_id: 42,+ name: 'Colosseum',+ lat: 41.89,+ lng: 12.49,+ address: null,+ force: true,+ }));+ expect(useSaveToCollectionStore.getState().version).toBe(1);+ });++ it('FE-COMP-MSAVESHEET-010: tapping a saved list removes that place instead', async () => {+ vi.spyOn(collectionsApi, 'membership').mockResolvedValue({+ saved: true,+ lists: [{ collection_id: 1, name: 'Favorites', place_id: 900 }],+ });+ const del = vi.spyOn(collectionsApi, 'deletePlace').mockResolvedValue({});+ openFor();+ render(<MSaveToCollectionSheet />);++ fireEvent.click(await screen.findByRole('button', { name: /Favorites/ }));++ await waitFor(() => expect(del).toHaveBeenCalledWith(900));+ expect(addToast).toHaveBeenCalledWith('Removed from Favorites', 'success', undefined);+ });++ it('FE-COMP-MSAVESHEET-011: a failing save surfaces the server message and leaves the version alone', async () => {+ vi.spyOn(collectionsApi, 'savePlace').mockRejectedValue({ response: { data: { error: 'List is full' } } });+ openFor();+ render(<MSaveToCollectionSheet />);++ fireEvent.click(await screen.findByRole('button', { name: /Wishlist/ }));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('List is full', 'error', undefined));+ expect(useSaveToCollectionStore.getState().version).toBe(0);+ });++ it('FE-COMP-MSAVESHEET-012: every row locks while one save runs, so a second tap is dropped', async () => {+ let resolve!: (v: CollectionSaveResult) => void;+ const save = vi.spyOn(collectionsApi, 'savePlace').mockReturnValue(new Promise(r => { resolve = r; }));+ openFor();+ render(<MSaveToCollectionSheet />);++ const wishlist = await screen.findByRole('button', { name: /Wishlist/ });+ fireEvent.click(wishlist);+ const favorites = screen.getByRole('button', { name: /Favorites/ });+ expect(wishlist).toBeDisabled();+ expect(favorites).toBeDisabled();+ fireEvent.click(favorites);+ expect(save).toHaveBeenCalledTimes(1);++ resolve({});+ await waitFor(() => expect(useSaveToCollectionStore.getState().version).toBe(1));+ });++ it('FE-COMP-MSAVESHEET-015: a membership refresh that fails after a save falls back to "saved nowhere"', async () => {+ vi.spyOn(collectionsApi, 'membership')+ .mockResolvedValueOnce(EMPTY_MEMBERSHIP)+ .mockRejectedValue(new Error('offline'));+ vi.spyOn(collectionsApi, 'savePlace').mockResolvedValue({});+ openFor();+ render(<MSaveToCollectionSheet />);++ fireEvent.click(await screen.findByRole('button', { name: /Wishlist/ }));++ await waitFor(() => expect(useSaveToCollectionStore.getState().version).toBe(1));+ expect(screen.getByRole('button', { name: /Wishlist/ }).querySelector('.lucide-bookmark-check')).toBeNull();+ });++ it('FE-COMP-MSAVESHEET-016: a response landing after the sheet closed is dropped', async () => {+ let resolve!: (v: CollectionListResponse) => void;+ vi.spyOn(collectionsApi, 'list').mockReturnValue(new Promise(r => { resolve = r; }));+ openFor();+ const { unmount } = render(<MSaveToCollectionSheet />);+ unmount();++ resolve(listResponse([FAVORITES]));+ await Promise.resolve();+ expect(screen.queryByText('Favorites')).not.toBeInTheDocument();+ });++ it('FE-COMP-MSAVESHEET-013: the footer View navigates to the collections page', async () => {+ openFor();+ render(<MSaveToCollectionSheet />);+ await screen.findByText('Favorites');++ fireEvent.click(screen.getByRole('button', { name: 'View' }));+ expect(mockNavigate).toHaveBeenCalledWith('/collections');+ expect(useSaveToCollectionStore.getState().target).toBeNull();+ });++ it('FE-COMP-MSAVESHEET-014: both the header X and the footer Close dismiss without navigating', async () => {+ openFor();+ const { unmount } = render(<MSaveToCollectionSheet />);+ await screen.findByText('Favorites');++ // Header icon button first in the DOM, footer button last.+ const closes = screen.getAllByRole('button', { name: 'Close' });+ expect(closes).toHaveLength(2);+ fireEvent.click(closes[closes.length - 1]);+ expect(useSaveToCollectionStore.getState().target).toBeNull();+ unmount();++ openFor();+ render(<MSaveToCollectionSheet />);+ await screen.findByText('Favorites');+ fireEvent.click(screen.getAllByRole('button', { name: 'Close' })[0]);+ expect(useSaveToCollectionStore.getState().target).toBeNull();+ expect(mockNavigate).not.toHaveBeenCalled();+ });+});diff --git a/client/src/components/Collections/SaveToCollectionModal.test.tsx b/client/src/components/Collections/SaveToCollectionModal.test.tsxnew file mode 100644index 000000000..61e6637e5--- /dev/null+++ b/client/src/components/Collections/SaveToCollectionModal.test.tsx@@ -0,0 +1,282 @@+// FE-COMP-SAVETOCOL-001 to FE-COMP-SAVETOCOL-016+import React from 'react';+import { afterEach, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render';+import type { Collection, CollectionListResponse, CollectionMembership, CollectionSaveResult } from '@trek/shared';+import { collectionsApi } from '../../api/collections';+import { useSaveToCollectionStore } from '../../store/saveToCollectionStore';+import type { SaveToCollectionTarget } from '../../store/saveToCollectionStore';+import SaveToCollectionModal from './SaveToCollectionModal';++const mockNavigate = vi.fn();+vi.mock('react-router-dom', async () => {+ const actual = await vi.importActual('react-router-dom');+ return { ...actual, useNavigate: () => mockNavigate };+});++function list(over: Partial<Collection>): Collection {+ return { id: 1, owner_id: 7, name: 'List', color: null, place_count: 0, ...over } as Collection;+}++const FAVORITES = list({ id: 1, name: 'Favorites', color: '#ef4444', place_count: 4 });+const WISHLIST = list({ id: 2, name: 'Wishlist' });+const SHARED = list({ id: 3, name: 'Team ideas', is_owner: false });++const listResponse = (collections: Collection[]): CollectionListResponse => ({ collections, incomingInvites: [] });+const EMPTY_MEMBERSHIP: CollectionMembership = { saved: false, lists: [] };++const TARGET: SaveToCollectionTarget = {+ name: 'Colosseum',+ source_trip_id: 5,+ source_place_id: 42,+ description: 'Ancient arena',+ lat: 41.89,+ lng: 12.49,+ address: 'Rome',+ category_id: 3,+ price: 16,+ currency: 'EUR',+ notes: 'Book ahead',+ image_url: '/uploads/places/colosseum.jpg',+ google_place_id: 'gp-1',+ google_ftid: 'ft-1',+ osm_id: 'osm-1',+ website: 'https://colosseo.example',+ phone: '+39',+};++let addToast: ReturnType<typeof vi.fn>;++function openFor(target: SaveToCollectionTarget = TARGET) {+ useSaveToCollectionStore.setState({ target, version: 0 });+}++beforeEach(() => {+ addToast = vi.fn();+ window.__addToast = addToast as unknown as typeof window.__addToast;+ mockNavigate.mockClear();+ useSaveToCollectionStore.setState({ target: null, version: 0 });+ vi.spyOn(collectionsApi, 'list').mockResolvedValue(listResponse([FAVORITES, WISHLIST]));+ vi.spyOn(collectionsApi, 'membership').mockResolvedValue(EMPTY_MEMBERSHIP);+});++afterEach(() => {+ vi.restoreAllMocks();+ useSaveToCollectionStore.setState({ target: null, version: 0 });+ delete window.__addToast;+});++describe('SaveToCollectionModal', () => {+ it('FE-COMP-SAVETOCOL-001: renders nothing and calls no api while no target is set', () => {+ render(<SaveToCollectionModal />);+ expect(screen.queryByRole('heading', { name: 'Save to list' })).not.toBeInTheDocument();+ expect(collectionsApi.list).not.toHaveBeenCalled();+ });++ it('FE-COMP-SAVETOCOL-002: shows the target name plus every list once loaded', async () => {+ openFor();+ render(<SaveToCollectionModal />);+ expect(await screen.findByText('Favorites')).toBeInTheDocument();+ expect(screen.getByRole('heading', { name: 'Save to list' })).toBeInTheDocument();+ expect(screen.getByText('Colosseum')).toBeInTheDocument();+ expect(screen.getByText('Wishlist')).toBeInTheDocument();+ });++ it('FE-COMP-SAVETOCOL-003: queries membership with the maps identity of the target', async () => {+ openFor();+ render(<SaveToCollectionModal />);+ await screen.findByText('Favorites');+ expect(collectionsApi.membership).toHaveBeenCalledWith({+ google_place_id: 'gp-1',+ google_ftid: 'ft-1',+ name: 'Colosseum',+ lat: 41.89,+ lng: 12.49,+ });+ });++ it('FE-COMP-SAVETOCOL-004: shows the spinner until the lists arrive', async () => {+ let resolve!: (v: CollectionListResponse) => void;+ vi.spyOn(collectionsApi, 'list').mockReturnValue(new Promise(r => { resolve = r; }));+ openFor();+ render(<SaveToCollectionModal />);+ expect(document.querySelector('.animate-spin')).not.toBeNull();++ resolve(listResponse([FAVORITES]));+ expect(await screen.findByText('Favorites')).toBeInTheDocument();+ });++ it('FE-COMP-SAVETOCOL-005: a failing list request falls back to the empty state with a create shortcut', async () => {+ vi.spyOn(collectionsApi, 'list').mockRejectedValue(new Error('offline'));+ openFor();+ render(<SaveToCollectionModal />);++ expect(await screen.findByText('Create a list first to save places.')).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: /New list/ }));+ expect(mockNavigate).toHaveBeenCalledWith('/collections');+ expect(useSaveToCollectionStore.getState().target).toBeNull();+ });++ it('FE-COMP-SAVETOCOL-006: lists already holding the place are marked saved', async () => {+ vi.spyOn(collectionsApi, 'membership').mockResolvedValue({+ saved: true,+ lists: [{ collection_id: 1, name: 'Favorites', place_id: 900 }],+ });+ openFor();+ render(<SaveToCollectionModal />);++ const favorites = await screen.findByRole('button', { name: /Favorites/ });+ expect(favorites).toHaveClass('border-accent');+ expect(favorites.querySelector('.lucide-bookmark-check')).not.toBeNull();+ expect(screen.getByRole('button', { name: /Wishlist/ })).not.toHaveClass('border-accent');+ });++ it('FE-COMP-SAVETOCOL-007: a failing membership lookup degrades to "saved nowhere"', async () => {+ vi.spyOn(collectionsApi, 'membership').mockRejectedValue(new Error('offline'));+ openFor();+ render(<SaveToCollectionModal />);++ const favorites = await screen.findByRole('button', { name: /Favorites/ });+ expect(favorites).not.toHaveClass('border-accent');+ });++ it('FE-COMP-SAVETOCOL-008: a shared list carries the SHARED badge', async () => {+ vi.spyOn(collectionsApi, 'list').mockResolvedValue(listResponse([FAVORITES, SHARED]));+ openFor();+ render(<SaveToCollectionModal />);++ const shared = await screen.findByRole('button', { name: /Team ideas/ });+ expect(within(shared).getByText('Shared')).toBeInTheDocument();+ expect(within(screen.getByRole('button', { name: /Favorites/ })).queryByText('Shared')).not.toBeInTheDocument();+ });++ it('FE-COMP-SAVETOCOL-009: picking an unsaved list forwards the whole target payload and bumps the version', async () => {+ const save = vi.spyOn(collectionsApi, 'savePlace').mockResolvedValue({});+ openFor();+ render(<SaveToCollectionModal />);++ fireEvent.click(await screen.findByRole('button', { name: /Wishlist/ }));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Added to Wishlist', 'success', undefined));+ expect(save).toHaveBeenCalledWith(expect.objectContaining({+ collection_id: 2,+ source_trip_id: 5,+ source_place_id: 42,+ name: 'Colosseum',+ lat: 41.89,+ lng: 12.49,+ google_place_id: 'gp-1',+ osm_id: 'osm-1',+ website: 'https://colosseo.example',+ force: true,+ }));+ expect(useSaveToCollectionStore.getState().version).toBe(1);+ });++ it('FE-COMP-SAVETOCOL-010: a sparse target sends explicit nulls rather than undefined', async () => {+ const save = vi.spyOn(collectionsApi, 'savePlace').mockResolvedValue({});+ openFor({ name: 'Nameless bar' });+ render(<SaveToCollectionModal />);++ fireEvent.click(await screen.findByRole('button', { name: /Wishlist/ }));++ await waitFor(() => expect(save).toHaveBeenCalled());+ expect(save).toHaveBeenCalledWith(expect.objectContaining({+ collection_id: 2,+ name: 'Nameless bar',+ lat: null,+ lng: null,+ source_trip_id: null,+ phone: null,+ }));+ });++ it('FE-COMP-SAVETOCOL-011: picking a saved list removes that place instead', async () => {+ vi.spyOn(collectionsApi, 'membership').mockResolvedValue({+ saved: true,+ lists: [{ collection_id: 1, name: 'Favorites', place_id: 900 }],+ });+ const del = vi.spyOn(collectionsApi, 'deletePlace').mockResolvedValue({});+ const save = vi.spyOn(collectionsApi, 'savePlace');+ openFor();+ render(<SaveToCollectionModal />);++ fireEvent.click(await screen.findByRole('button', { name: /Favorites/ }));++ await waitFor(() => expect(del).toHaveBeenCalledWith(900));+ expect(save).not.toHaveBeenCalled();+ expect(addToast).toHaveBeenCalledWith('Removed from Favorites', 'success', undefined);+ });++ it('FE-COMP-SAVETOCOL-012: a failing save surfaces the server message and leaves the version alone', async () => {+ vi.spyOn(collectionsApi, 'savePlace').mockRejectedValue({ response: { data: { error: 'List is full' } } });+ openFor();+ render(<SaveToCollectionModal />);++ fireEvent.click(await screen.findByRole('button', { name: /Wishlist/ }));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('List is full', 'error', undefined));+ expect(useSaveToCollectionStore.getState().version).toBe(0);+ });++ it('FE-COMP-SAVETOCOL-013: a second click on the busy row is ignored while the save runs', async () => {+ let resolve!: (v: CollectionSaveResult) => void;+ const save = vi.spyOn(collectionsApi, 'savePlace').mockReturnValue(new Promise(r => { resolve = r; }));+ openFor();+ render(<SaveToCollectionModal />);++ const wishlist = await screen.findByRole('button', { name: /Wishlist/ });+ fireEvent.click(wishlist);+ expect(wishlist).toBeDisabled();+ fireEvent.click(screen.getByRole('button', { name: /Favorites/ }));+ expect(save).toHaveBeenCalledTimes(1);++ resolve({});+ await waitFor(() => expect(useSaveToCollectionStore.getState().version).toBe(1));+ });++ it('FE-COMP-SAVETOCOL-015: a membership refresh that fails after a save falls back to "saved nowhere"', async () => {+ vi.spyOn(collectionsApi, 'membership')+ .mockResolvedValueOnce(EMPTY_MEMBERSHIP)+ .mockRejectedValue(new Error('offline'));+ vi.spyOn(collectionsApi, 'savePlace').mockResolvedValue({});+ openFor();+ render(<SaveToCollectionModal />);++ fireEvent.click(await screen.findByRole('button', { name: /Wishlist/ }));++ await waitFor(() => expect(useSaveToCollectionStore.getState().version).toBe(1));+ expect(screen.getByRole('button', { name: /Wishlist/ })).not.toHaveClass('border-accent');+ });++ it('FE-COMP-SAVETOCOL-016: a response landing after the picker closed is dropped', async () => {+ let resolve!: (v: CollectionListResponse) => void;+ vi.spyOn(collectionsApi, 'list').mockReturnValue(new Promise(r => { resolve = r; }));+ openFor();+ const { unmount } = render(<SaveToCollectionModal />);+ unmount();++ resolve(listResponse([FAVORITES]));+ await Promise.resolve();+ expect(screen.queryByText('Favorites')).not.toBeInTheDocument();+ });++ it('FE-COMP-SAVETOCOL-014: the footer navigates to the collections page or just closes', async () => {+ openFor();+ const { unmount } = render(<SaveToCollectionModal />);+ await screen.findByText('Favorites');++ fireEvent.click(screen.getByRole('button', { name: 'View' }));+ expect(mockNavigate).toHaveBeenCalledWith('/collections');+ expect(useSaveToCollectionStore.getState().target).toBeNull();+ unmount();++ mockNavigate.mockClear();+ openFor();+ render(<SaveToCollectionModal />);+ await screen.findByText('Favorites');+ fireEvent.click(screen.getByRole('button', { name: 'Close' }));+ expect(mockNavigate).not.toHaveBeenCalled();+ expect(useSaveToCollectionStore.getState().target).toBeNull();+ });+});diff --git a/client/src/components/Collections/SaveTripPlacesToListModal.test.tsx b/client/src/components/Collections/SaveTripPlacesToListModal.test.tsxnew file mode 100644index 000000000..4f7f23f8b--- /dev/null+++ b/client/src/components/Collections/SaveTripPlacesToListModal.test.tsx@@ -0,0 +1,212 @@+// FE-COMP-SAVETRIPPL-001 to FE-COMP-SAVETRIPPL-015+import React from 'react';+import { afterEach, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render';+import userEvent from '@testing-library/user-event';+import type { Collection, CollectionListResponse } from '@trek/shared';+import { collectionsApi } from '../../api/collections';+import SaveTripPlacesToListModal from './SaveTripPlacesToListModal';++type ModalProps = React.ComponentProps<typeof SaveTripPlacesToListModal>;+type SaveManyResult = { copied: number; skipped: { id: number; name: string }[] };++function list(over: Partial<Collection>): Collection {+ return { id: 1, owner_id: 7, name: 'List', color: null, place_count: 0, ...over } as Collection;+}++const FAVORITES = list({ id: 1, name: 'Favorites', color: '#ef4444', place_count: 4 });+const WISHLIST = list({ id: 2, name: 'Wishlist' });++const listResponse = (collections: Collection[]): CollectionListResponse => ({ collections, incomingInvites: [] });++let addToast: ReturnType<typeof vi.fn>;++function renderModal(overrides: Partial<ModalProps> = {}) {+ const props: ModalProps = {+ isOpen: true,+ tripId: 5,+ placeIds: [11, 12],+ onClose: vi.fn(),+ onDone: vi.fn(),+ ...overrides,+ };+ render(<SaveTripPlacesToListModal {...props} />);+ return props;+}++beforeEach(() => {+ addToast = vi.fn();+ window.__addToast = addToast as unknown as typeof window.__addToast;+ vi.spyOn(collectionsApi, 'list').mockResolvedValue(listResponse([FAVORITES, WISHLIST]));+});++afterEach(() => {+ vi.restoreAllMocks();+ delete window.__addToast;+});++describe('SaveTripPlacesToListModal', () => {+ it('FE-COMP-SAVETRIPPL-001: titles the modal with the selection count and lists the writable lists', async () => {+ renderModal({ placeIds: [11, 12, 13] });+ expect(await screen.findByText('Favorites')).toBeInTheDocument();+ expect(screen.getByRole('heading', { name: 'Save 3 to a list' })).toBeInTheDocument();+ expect(screen.getByText('4 places')).toBeInTheDocument();+ expect(screen.getByText('0 places')).toBeInTheDocument();+ expect(screen.getByText('Duplicates are skipped automatically')).toBeInTheDocument();+ });++ it('FE-COMP-SAVETRIPPL-002: lists shared with the user are dropped — they cannot be written to', async () => {+ vi.spyOn(collectionsApi, 'list').mockResolvedValue(+ listResponse([FAVORITES, list({ id: 3, name: 'Team ideas', is_owner: false })]),+ );+ renderModal();+ expect(await screen.findByText('Favorites')).toBeInTheDocument();+ expect(screen.queryByText('Team ideas')).not.toBeInTheDocument();+ });++ it('FE-COMP-SAVETRIPPL-003: shows the spinner until the lists arrive', async () => {+ let resolve!: (v: CollectionListResponse) => void;+ vi.spyOn(collectionsApi, 'list').mockReturnValue(new Promise(r => { resolve = r; }));+ renderModal();+ expect(document.querySelector('.animate-spin')).not.toBeNull();+ expect(screen.queryByText('You have no lists yet')).not.toBeInTheDocument();++ resolve(listResponse([FAVORITES]));+ expect(await screen.findByText('Favorites')).toBeInTheDocument();+ });++ it('FE-COMP-SAVETRIPPL-004: an absent or failing collections response falls back to the empty copy', async () => {+ vi.spyOn(collectionsApi, 'list').mockResolvedValue({ incomingInvites: [] } as unknown as CollectionListResponse);+ const { unmount } = render(<SaveTripPlacesToListModal isOpen tripId={5} placeIds={[11]} onClose={vi.fn()} onDone={vi.fn()} />);+ expect(await screen.findByText('You have no lists yet')).toBeInTheDocument();+ unmount();++ vi.spyOn(collectionsApi, 'list').mockRejectedValue(new Error('offline'));+ renderModal();+ expect(await screen.findByText('You have no lists yet')).toBeInTheDocument();+ });++ it('FE-COMP-SAVETRIPPL-005: requests nothing and renders nothing while closed', () => {+ const spy = vi.spyOn(collectionsApi, 'list').mockResolvedValue(listResponse([FAVORITES]));+ renderModal({ isOpen: false });+ expect(spy).not.toHaveBeenCalled();+ expect(screen.queryByRole('heading', { name: /Save/ })).not.toBeInTheDocument();+ });++ it('FE-COMP-SAVETRIPPL-006: the search box appears above five lists and filters by name', async () => {+ const many = [1, 2, 3, 4, 5, 6].map(id => list({ id, name: `List ${id}` }));+ vi.spyOn(collectionsApi, 'list').mockResolvedValue(listResponse(many));+ renderModal();++ const search = await screen.findByPlaceholderText('Search trips');+ fireEvent.change(search, { target: { value: 'list 4' } });+ expect(screen.getByText('List 4')).toBeInTheDocument();+ expect(screen.queryByText('List 5')).not.toBeInTheDocument();++ fireEvent.change(search, { target: { value: 'nope' } });+ expect(screen.getByText('You have no lists yet')).toBeInTheDocument();+ });++ it('FE-COMP-SAVETRIPPL-007: five lists or fewer need no search box', async () => {+ renderModal();+ await screen.findByText('Favorites');+ expect(screen.queryByPlaceholderText('Search trips')).not.toBeInTheDocument();+ });++ it('FE-COMP-SAVETRIPPL-008: picking a list copies every selected place, reports it and closes', async () => {+ const save = vi.spyOn(collectionsApi, 'saveFromTripMany').mockResolvedValue({ copied: 2, skipped: [] });+ const props = renderModal();++ fireEvent.click(await screen.findByText('Favorites'));++ await waitFor(() => expect(props.onDone).toHaveBeenCalled());+ expect(save).toHaveBeenCalledWith(1, 5, [11, 12]);+ expect(addToast).toHaveBeenCalledWith('Saved 2 to Favorites', 'success', undefined);+ expect(props.onClose).toHaveBeenCalled();+ });++ it('FE-COMP-SAVETRIPPL-009: server-side duplicates are reported separately', async () => {+ vi.spyOn(collectionsApi, 'saveFromTripMany').mockResolvedValue({ copied: 1, skipped: [{ id: 12, name: 'Louvre' }] });+ renderModal();++ fireEvent.click(await screen.findByText('Favorites'));+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Skipped 1 duplicates', 'info', undefined));+ expect(addToast).toHaveBeenCalledWith('Saved 1 to Favorites', 'success', undefined);+ });++ it('FE-COMP-SAVETRIPPL-010: a no-op save says so instead of staying silent', async () => {+ vi.spyOn(collectionsApi, 'saveFromTripMany').mockResolvedValue({ copied: 0, skipped: [] });+ renderModal();++ fireEvent.click(await screen.findByText('Favorites'));+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Nothing to copy', 'info', undefined));+ expect(addToast).toHaveBeenCalledTimes(1);+ });++ it('FE-COMP-SAVETRIPPL-011: a failed save surfaces the server message and keeps the modal open', async () => {+ vi.spyOn(collectionsApi, 'saveFromTripMany').mockRejectedValue({ response: { data: { error: 'List is full' } } });+ const props = renderModal();++ fireEvent.click(await screen.findByText('Favorites'));+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('List is full', 'error', undefined));+ expect(props.onDone).not.toHaveBeenCalled();+ expect(props.onClose).not.toHaveBeenCalled();+ });++ it('FE-COMP-SAVETRIPPL-012: every row locks while a save runs, and an empty selection never reaches the server', async () => {+ let resolve!: (v: SaveManyResult) => void;+ const save = vi.spyOn(collectionsApi, 'saveFromTripMany').mockReturnValue(new Promise(r => { resolve = r; }));+ const props = renderModal();++ const favorites = await screen.findByRole('button', { name: /Favorites/ });+ fireEvent.click(favorites);+ const wishlist = screen.getByRole('button', { name: /Wishlist/ });+ expect(wishlist).toBeDisabled();+ expect(within(favorites).queryByText('4 places')).toBeInTheDocument();+ fireEvent.click(wishlist);+ expect(save).toHaveBeenCalledTimes(1);++ resolve({ copied: 1, skipped: [] });+ await waitFor(() => expect(props.onDone).toHaveBeenCalled());+ });++ it('FE-COMP-SAVETRIPPL-014: a list response landing after the modal closed is dropped', async () => {+ const closed = <SaveTripPlacesToListModal isOpen tripId={5} placeIds={[11]} onClose={vi.fn()} onDone={vi.fn()} />;++ let resolve!: (v: CollectionListResponse) => void;+ const spy = vi.spyOn(collectionsApi, 'list').mockReturnValue(new Promise(r => { resolve = r; }));+ render(closed).unmount();+ resolve(listResponse([FAVORITES]));+ await Promise.resolve();+ expect(screen.queryByText('Favorites')).not.toBeInTheDocument();++ let reject!: (e: Error) => void;+ spy.mockReturnValue(new Promise((_, r) => { reject = r; }));+ render(closed).unmount();+ reject(new Error('offline'));+ await Promise.resolve();+ expect(screen.queryByText('You have no lists yet')).not.toBeInTheDocument();+ });++ it('FE-COMP-SAVETRIPPL-015: a list the server sent without a count still renders a countable row', async () => {+ vi.spyOn(collectionsApi, 'list').mockResolvedValue(+ listResponse([{ id: 9, owner_id: 7, name: 'Untracked' } as Collection]),+ );+ renderModal();++ const untracked = await screen.findByRole('button', { name: /Untracked/ });+ expect(within(untracked).getByText('0 places')).toBeInTheDocument();+ });++ it('FE-COMP-SAVETRIPPL-013: an empty selection is a no-op, and Escape hands back to the caller', async () => {+ const user = userEvent.setup();+ const save = vi.spyOn(collectionsApi, 'saveFromTripMany');+ const props = renderModal({ placeIds: [] });++ fireEvent.click(await screen.findByText('Favorites'));+ expect(save).not.toHaveBeenCalled();++ await user.keyboard('{Escape}');+ expect(props.onClose).toHaveBeenCalledTimes(1);+ });+});diff --git a/client/src/components/Collections/ShareCollectionModal.test.tsx b/client/src/components/Collections/ShareCollectionModal.test.tsxnew file mode 100644index 000000000..15512ce8b--- /dev/null+++ b/client/src/components/Collections/ShareCollectionModal.test.tsx@@ -0,0 +1,294 @@+// FE-COMP-COLSHARE-001 to FE-COMP-COLSHARE-025+import React from 'react'+import type { Mock } from 'vitest'+import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render'+import type { CollectionMember } from '@trek/shared'+import { collectionsApi } from '../../api/collections'+import { useCollectionStore } from '../../store/collectionStore'+import { useAuthStore } from '../../store/authStore'+import { resetAllStores, seedStore } from '../../../tests/helpers/store'+import { buildUser } from '../../../tests/helpers/factories'+import { useTranslation } from '../../i18n/TranslationContext'+import ShareCollectionModal from './ShareCollectionModal'++type Props = React.ComponentProps<typeof ShareCollectionModal>+function Harness(props: Omit<Props, 't'>): React.ReactElement {+ const { t } = useTranslation()+ return <ShareCollectionModal {...props} t={t} />+}++const OWNER: CollectionMember = { user_id: 1, username: 'maurice', email: '[email protected]', status: 'accepted', is_owner: true }+const EDITOR: CollectionMember = { user_id: 2, username: 'julien', email: '[email protected]', status: 'accepted', role: 'editor', avatar: 'jul.png' }+const VIEWER: CollectionMember = { user_id: 4, username: 'ada', email: '[email protected]', status: 'accepted', role: 'viewer' }+const PENDING: CollectionMember = { user_id: 3, username: 'zoe', email: '[email protected]', status: 'pending' }++type CollectionStore = ReturnType<typeof useCollectionStore.getState>+type AddToast = NonNullable<typeof window.__addToast>++const initialCollectionState = useCollectionStore.getState()+let actions: {+ invite: Mock<CollectionStore['invite']>+ cancelInvite: Mock<CollectionStore['cancelInvite']>+ removeMember: Mock<CollectionStore['removeMember']>+ setMemberRole: Mock<CollectionStore['setMemberRole']>+ leave: Mock<CollectionStore['leave']>+}+let addToast: Mock<AddToast>++function setup(over: Partial<Omit<Props, 't'>> = {}) {+ const props: Omit<Props, 't'> = {+ isOpen: true,+ collectionId: 7,+ collectionName: 'Tokyo 2026',+ isOwner: true,+ members: [PENDING, EDITOR, OWNER],+ onClose: vi.fn(),+ onAfterLeave: vi.fn(),+ ...over,+ }+ const view = render(<Harness {...props} />)+ return { ...view, props }+}++/** The roster row for a member — the invite form carries the same role labels,+ * so role assertions have to be scoped to the row they belong to. */+function memberRow(username: string): HTMLElement {+ const nameCell = screen.getByText(username).parentElement as HTMLElement+ return nameCell.parentElement as HTMLElement+}++describe('ShareCollectionModal', () => {+ beforeEach(() => {+ resetAllStores()+ useCollectionStore.setState(initialCollectionState, true)+ actions = {+ invite: vi.fn<CollectionStore['invite']>(async () => undefined),+ cancelInvite: vi.fn<CollectionStore['cancelInvite']>(async () => undefined),+ removeMember: vi.fn<CollectionStore['removeMember']>(async () => undefined),+ setMemberRole: vi.fn<CollectionStore['setMemberRole']>(async () => undefined),+ leave: vi.fn<CollectionStore['leave']>(async () => undefined),+ }+ useCollectionStore.setState(actions)+ seedStore(useAuthStore, { user: buildUser({ id: 1, username: 'maurice' }) })+ addToast = vi.fn<AddToast>(() => 0)+ window.__addToast = addToast+ vi.spyOn(collectionsApi, 'availableUsers').mockResolvedValue({+ users: [{ id: 9, username: 'nina' }, { id: 10, username: 'omar' }],+ })+ })++ afterEach(() => {+ vi.restoreAllMocks()+ delete window.__addToast+ })++ it('FE-COMP-COLSHARE-001: a closed modal renders nothing and asks for no invitable users', () => {+ setup({ isOpen: false })+ expect(screen.queryByRole('heading', { name: /Share/ })).not.toBeInTheDocument()+ expect(collectionsApi.availableUsers).not.toHaveBeenCalled()+ })++ it('FE-COMP-COLSHARE-002: the title names the list and the roster is counted', () => {+ setup()+ expect(screen.getByRole('heading', { name: 'Share “Tokyo 2026”' })).toBeInTheDocument()+ expect(screen.getByText('Members')).toBeInTheDocument()+ expect(screen.getByText('3')).toBeInTheDocument()+ })++ it('FE-COMP-COLSHARE-003: sorts owner first, then accepted members, then pending invites', () => {+ setup({ members: [PENDING, VIEWER, EDITOR, OWNER] })+ const names = screen.getAllByText(/^(maurice|julien|ada|zoe)/).map(n => n.textContent)+ expect(names).toEqual(['maurice(you)', 'ada', 'julien', 'zoe'])+ })++ it('FE-COMP-COLSHARE-004: tags the owner, marks the signed-in user and hides a pending email', () => {+ setup()+ expect(screen.getByText('Owner')).toBeInTheDocument()+ expect(screen.getByText('(you)')).toBeInTheDocument()+ expect(screen.getByText('[email protected]')).toBeInTheDocument()+ expect(screen.getByText('pending invite')).toBeInTheDocument()+ expect(screen.queryByText('[email protected]')).not.toBeInTheDocument()+ })++ it('FE-COMP-COLSHARE-005: renders an uploaded avatar, otherwise the username initial', () => {+ setup()+ const avatars = document.querySelectorAll('img')+ expect(avatars).toHaveLength(1)+ expect(avatars[0]).toHaveAttribute('src', '/uploads/avatars/jul.png')+ expect(screen.getByText('M')).toBeInTheDocument()+ expect(screen.getByText('Z')).toBeInTheDocument()+ })++ it('FE-COMP-COLSHARE-006: a member without a username still gets a placeholder initial', () => {+ setup({ members: [OWNER, { ...EDITOR, username: '', avatar: undefined }] })+ expect(screen.getByText('?')).toBeInTheDocument()+ })++ it('FE-COMP-COLSHARE-007: the owner changes a member role through the role select', async () => {+ setup({ members: [OWNER, EDITOR] })+ // The select shows the member's current role; open it and pick another.+ fireEvent.click(within(memberRow('julien')).getByRole('button', { name: 'Editor' }))+ fireEvent.click(screen.getByRole('button', { name: 'Admin' }))+ await waitFor(() => expect(actions.setMemberRole).toHaveBeenCalledWith(7, 2, 'admin'))+ })++ it('FE-COMP-COLSHARE-008: a member with no explicit role defaults to editor in the select', () => {+ setup({ members: [OWNER, { ...EDITOR, role: undefined }] })+ expect(within(memberRow('julien')).getByRole('button', { name: 'Editor' })).toBeInTheDocument()+ })++ it('FE-COMP-COLSHARE-009: a failing role change surfaces the server message', async () => {+ actions.setMemberRole.mockRejectedValue({ response: { data: { error: 'Not allowed' } } })+ setup({ members: [OWNER, EDITOR] })+ fireEvent.click(within(memberRow('julien')).getByRole('button', { name: 'Editor' }))+ fireEvent.click(screen.getByRole('button', { name: 'Viewer' }))+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Not allowed', 'error', undefined))+ })++ it('FE-COMP-COLSHARE-010: the owner removes an accepted member and cancels a pending invite', async () => {+ setup()+ fireEvent.click(screen.getByRole('button', { name: 'Remove' }))+ await waitFor(() => expect(actions.removeMember).toHaveBeenCalledWith(7, 2))++ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))+ await waitFor(() => expect(actions.cancelInvite).toHaveBeenCalledWith(7, 3))+ })++ it('FE-COMP-COLSHARE-011: a second remove is ignored while the first is still running', async () => {+ let release!: () => void+ actions.removeMember.mockReturnValue(new Promise<void>(r => { release = r }))+ setup({ members: [OWNER, EDITOR, VIEWER] })+ const [first, second] = screen.getAllByRole('button', { name: 'Remove' })+ fireEvent.click(first)+ fireEvent.click(second)+ expect(actions.removeMember).toHaveBeenCalledTimes(1)+ expect(first).toBeDisabled()++ release()+ await waitFor(() => expect(first).not.toBeDisabled())+ })++ it('FE-COMP-COLSHARE-012: a failing cancel reports the fallback error', async () => {+ actions.cancelInvite.mockRejectedValue({})+ setup()+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined))+ })++ it('FE-COMP-COLSHARE-013: a failing remove reports the fallback error', async () => {+ actions.removeMember.mockRejectedValue({})+ setup()+ fireEvent.click(screen.getByRole('button', { name: 'Remove' }))+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined))+ })++ it('FE-COMP-COLSHARE-014: the owner picks a user and role, then sends the invite', async () => {+ setup({ members: [OWNER] })+ expect(await screen.findByRole('button', { name: /Send invite/ })).toBeDisabled()++ fireEvent.click(screen.getByRole('button', { name: 'Select a user' }))+ fireEvent.click(screen.getByRole('button', { name: 'omar' }))+ fireEvent.click(screen.getByRole('button', { name: 'Editor' }))+ fireEvent.click(screen.getByRole('button', { name: 'Admin' }))+ fireEvent.click(screen.getByRole('button', { name: /Send invite/ }))++ await waitFor(() => expect(actions.invite).toHaveBeenCalledWith(7, 10, 'admin'))+ expect(addToast).toHaveBeenCalledWith('Invite sent', 'success', undefined)+ // The picker falls back to its placeholder for the next invite.+ await waitFor(() => expect(screen.getByRole('button', { name: 'Select a user' })).toBeInTheDocument())+ })++ it('FE-COMP-COLSHARE-015: editor is the preselected invite role', async () => {+ setup({ members: [OWNER] })+ fireEvent.click(await screen.findByRole('button', { name: 'Select a user' }))+ fireEvent.click(screen.getByRole('button', { name: 'nina' }))+ fireEvent.click(screen.getByRole('button', { name: /Send invite/ }))+ await waitFor(() => expect(actions.invite).toHaveBeenCalledWith(7, 9, 'editor'))+ })++ it('FE-COMP-COLSHARE-016: a failing invite keeps the selection and reports the error', async () => {+ actions.invite.mockRejectedValue(new Error('boom'))+ setup({ members: [OWNER] })+ fireEvent.click(await screen.findByRole('button', { name: 'Select a user' }))+ fireEvent.click(screen.getByRole('button', { name: 'nina' }))+ fireEvent.click(screen.getByRole('button', { name: /Send invite/ }))+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Could not send invite', 'error', undefined))+ expect(screen.getByRole('button', { name: 'nina' })).toBeInTheDocument()+ })++ it('FE-COMP-COLSHARE-017: with nobody left to invite the owner is told so', async () => {+ vi.mocked(collectionsApi.availableUsers).mockResolvedValue({ users: [] })+ setup()+ expect(await screen.findByText('No users available to invite.')).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: /Send invite/ })).not.toBeInTheDocument()+ })++ it('FE-COMP-COLSHARE-018: a failing lookup degrades to the same empty state', async () => {+ vi.mocked(collectionsApi.availableUsers).mockRejectedValue(new Error('offline'))+ setup()+ expect(await screen.findByText('No users available to invite.')).toBeInTheDocument()+ })++ it('FE-COMP-COLSHARE-019: members see a read-only roster, no invite form and no row actions', async () => {+ setup({ isOwner: false, members: [OWNER, EDITOR, VIEWER] })+ expect(screen.getByText('Only the list owner can invite or remove people.')).toBeInTheDocument()+ expect(screen.getByText('Editor')).toBeInTheDocument()+ expect(screen.getByText('Viewer')).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Remove' })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: /Send invite/ })).not.toBeInTheDocument()+ await waitFor(() => expect(collectionsApi.availableUsers).not.toHaveBeenCalled())+ })++ it('FE-COMP-COLSHARE-020: a member without a role reads as editor in the read-only badge', () => {+ setup({ isOwner: false, members: [OWNER, { ...EDITOR, role: undefined }] })+ expect(screen.getByText('Editor')).toBeInTheDocument()+ })++ it('FE-COMP-COLSHARE-021: leaving asks for confirmation first and can be backed out of', () => {+ setup({ isOwner: false })+ fireEvent.click(screen.getByRole('button', { name: 'Leave list' }))+ expect(screen.getByText('Leave this shared list? You will lose access until you are invited again.')).toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))+ expect(actions.leave).not.toHaveBeenCalled()+ expect(screen.queryByText('Leave this shared list? You will lose access until you are invited again.')).not.toBeInTheDocument()+ })++ it('FE-COMP-COLSHARE-022: a confirmed leave calls the store and hands back to the page', async () => {+ const { props } = setup({ isOwner: false })+ fireEvent.click(screen.getByRole('button', { name: 'Leave list' }))+ fireEvent.click(screen.getAllByRole('button', { name: 'Leave list' })[0])+ await waitFor(() => expect(actions.leave).toHaveBeenCalledWith(7))+ expect(addToast).toHaveBeenCalledWith('You left the list', 'success', undefined)+ expect(props.onAfterLeave).toHaveBeenCalledTimes(1)+ })++ it('FE-COMP-COLSHARE-023: a failing leave reports the error and keeps the user in the list', async () => {+ actions.leave.mockRejectedValue({ response: { data: { error: 'Owners cannot leave' } } })+ const { props } = setup({ isOwner: false })+ fireEvent.click(screen.getByRole('button', { name: 'Leave list' }))+ fireEvent.click(screen.getAllByRole('button', { name: 'Leave list' })[0])+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Owners cannot leave', 'error', undefined))+ expect(props.onAfterLeave).not.toHaveBeenCalled()+ })++ it('FE-COMP-COLSHARE-024: closing resets the picker and the leave confirmation', async () => {+ const { rerender, props } = setup({ isOwner: false })+ fireEvent.click(screen.getByRole('button', { name: 'Leave list' }))+ expect(screen.getByText('Leave this shared list? You will lose access until you are invited again.')).toBeInTheDocument()++ rerender(<Harness {...props} isOwner={false} isOpen={false} />)+ rerender(<Harness {...props} isOwner={false} isOpen />)+ await waitFor(() =>+ expect(screen.queryByText('Leave this shared list? You will lose access until you are invited again.')).not.toBeInTheDocument(),+ )+ })++ it('FE-COMP-COLSHARE-025: the modal close button calls onClose', () => {+ const { props } = setup()+ // The Modal chrome's only unnamed control is its close button.+ const header = screen.getByRole('heading', { name: 'Share “Tokyo 2026”' }).parentElement as HTMLElement+ fireEvent.click(header.querySelector('button') as HTMLButtonElement)+ expect(props.onClose).toHaveBeenCalledTimes(1)+ })+})diff --git a/client/src/components/Dashboard/CollectionsWidget.test.tsx b/client/src/components/Dashboard/CollectionsWidget.test.tsxnew file mode 100644index 000000000..63a39969e--- /dev/null+++ b/client/src/components/Dashboard/CollectionsWidget.test.tsx@@ -0,0 +1,86 @@+import React from 'react';+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { http, HttpResponse } from 'msw';+import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render';+import { server } from '../../../tests/helpers/msw/server';+import CollectionsWidget from './CollectionsWidget';++// FE-COMP-COLWIDGET-001 onwards++function collections(list: unknown[]) {+ server.use(http.get('/api/addons/collections', () => HttpResponse.json({ collections: list })));+}++const list = (over: Record<string, unknown> = {}) => ({+ id: 1, name: 'Tokyo eats', color: '#ff0000', cover_image: null, place_count: 12, ...over,+});++beforeEach(() => {+ collections([]);+});++describe('CollectionsWidget', () => {+ it('FE-COMP-COLWIDGET-001: shows the empty hint once the fetch resolves', async () => {+ render(<CollectionsWidget onOpen={() => {}} />);++ expect(await screen.findByText('No saved places yet')).toBeInTheDocument();+ expect(screen.getByText('Collections')).toBeInTheDocument();+ });++ it('FE-COMP-COLWIDGET-002: renders at most six badges with their counts', async () => {+ collections([1, 2, 3, 4, 5, 6, 7].map(id => list({ id, name: `List ${id}`, place_count: id })));+ render(<CollectionsWidget onOpen={() => {}} />);++ expect(await screen.findByText('List 1')).toBeInTheDocument();+ expect(screen.getByText('List 6')).toBeInTheDocument();+ expect(screen.queryByText('List 7')).not.toBeInTheDocument();+ });++ it('FE-COMP-COLWIDGET-003: a list without a count renders a zero', async () => {+ collections([list({ place_count: null })]);+ render(<CollectionsWidget onOpen={() => {}} />);++ await screen.findByText('Tokyo eats');+ expect(screen.getByText('0')).toBeInTheDocument();+ });++ it('FE-COMP-COLWIDGET-004: a cover image replaces the gradient tile', async () => {+ collections([list({ cover_image: '/uploads/collections/1.jpg' })]);+ const { container } = render(<CollectionsWidget onOpen={() => {}} />);++ await screen.findByText('Tokyo eats');+ expect(container.querySelector('img.col-badge-media')).toHaveAttribute('src', '/uploads/collections/1.jpg');+ });++ it('FE-COMP-COLWIDGET-005: a list without a colour falls back to the entity gradient', async () => {+ collections([list({ color: null })]);+ const { container } = render(<CollectionsWidget onOpen={() => {}} />);++ await screen.findByText('Tokyo eats');+ const media = container.querySelector('div.col-badge-media') as HTMLElement;+ expect(media.style.backgroundImage).toContain('gradient');+ });++ it('FE-COMP-COLWIDGET-006: the header arrow runs the onOpen callback', async () => {+ const onOpen = vi.fn();+ render(<CollectionsWidget onOpen={onOpen} />);++ fireEvent.click(screen.getByRole('button', { name: 'Collections' }));++ expect(onOpen).toHaveBeenCalledTimes(1);+ });++ it('FE-COMP-COLWIDGET-007: a failing fetch degrades to the empty hint', async () => {+ server.use(http.get('/api/addons/collections', () => new HttpResponse(null, { status: 500 })));+ render(<CollectionsWidget onOpen={() => {}} />);++ expect(await screen.findByText('No saved places yet')).toBeInTheDocument();+ });++ it('FE-COMP-COLWIDGET-008: nothing renders while the fetch is still in flight', async () => {+ render(<CollectionsWidget onOpen={() => {}} />);++ expect(screen.queryByText('No saved places yet')).not.toBeInTheDocument();+ await waitFor(() => expect(screen.getByText('No saved places yet')).toBeInTheDocument());+ });+});diff --git a/client/src/components/Files/FileManager.helpers.extra.test.ts b/client/src/components/Files/FileManager.helpers.extra.test.tsnew file mode 100644index 000000000..dcb9b266e--- /dev/null+++ b/client/src/components/Files/FileManager.helpers.extra.test.ts@@ -0,0 +1,111 @@+// FE-W4FMH-001 to FE-W4FMH-012+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { File as FileIcon, FileText, FileImage, FileVideo, Plane, Train, Bus, Car, CarTaxiFront, Bike, Ship, Sailboat, Route } from 'lucide-react'++const downloadFile = vi.fn(async (_url: string, _name: string) => {})+vi.mock('../../utils/fileDownload', () => ({ downloadFile: (url: string, name: string) => downloadFile(url, name) }))++import {+ isImage, isVideo, isMedia, isMarkdown, getFileIcon, formatSize,+ triggerDownload, formatDateWithLocale, transportIcon,+} from './FileManager.helpers'++beforeEach(() => {+ downloadFile.mockReset()+ downloadFile.mockResolvedValue(undefined)+})++describe('mime helpers', () => {+ it('FE-W4FMH-001: detects images and videos', () => {+ expect(isImage('image/png')).toBe(true)+ expect(isImage('application/pdf')).toBe(false)+ expect(isImage(null)).toBe(false)+ expect(isVideo('video/mp4')).toBe(true)+ expect(isVideo(undefined)).toBe(false)+ })++ it('FE-W4FMH-002: treats both images and videos as lightbox media', () => {+ expect(isMedia('image/jpeg')).toBe(true)+ expect(isMedia('video/quicktime')).toBe(true)+ expect(isMedia('application/pdf')).toBe(false)+ expect(isMedia(null)).toBe(false)+ })++ it('FE-W4FMH-003: detects markdown by extension first', () => {+ expect(isMarkdown('application/octet-stream', 'NOTES.MD')).toBe(true)+ expect(isMarkdown('', 'readme.markdown')).toBe(true)+ expect(isMarkdown('text/markdown', 'blob')).toBe(true)+ expect(isMarkdown('text/x-markdown', null)).toBe(true)+ expect(isMarkdown('text/plain', 'notes.txt')).toBe(false)+ expect(isMarkdown(null, null)).toBe(false)+ })+})++describe('getFileIcon', () => {+ it('FE-W4FMH-004: picks the icon matching the mime family', () => {+ expect(getFileIcon('application/pdf')).toBe(FileText)+ expect(getFileIcon('video/mp4')).toBe(FileVideo)+ expect(getFileIcon('image/png')).toBe(FileImage)+ expect(getFileIcon('application/zip')).toBe(FileIcon)+ expect(getFileIcon(null)).toBe(FileIcon)+ })+})++describe('formatSize', () => {+ it('FE-W4FMH-005: renders bytes below a kilobyte', () => {+ expect(formatSize(512)).toBe('512 B')+ })++ it('FE-W4FMH-006: renders kilobytes and megabytes with one decimal', () => {+ expect(formatSize(2048)).toBe('2.0 KB')+ expect(formatSize(1024 * 1024 * 3.25)).toBe('3.3 MB')+ })++ it('FE-W4FMH-007: renders nothing for a missing or zero size', () => {+ expect(formatSize(0)).toBe('')+ expect(formatSize(null)).toBe('')+ expect(formatSize(undefined)).toBe('')+ })+})++describe('triggerDownload', () => {+ it('FE-W4FMH-008: forwards to the download helper', () => {+ triggerDownload('/uploads/files/a.pdf', 'a.pdf')++ expect(downloadFile).toHaveBeenCalledWith('/uploads/files/a.pdf', 'a.pdf')+ })++ it('FE-W4FMH-009: swallows a rejected download', async () => {+ downloadFile.mockRejectedValue(new Error('offline'))++ expect(() => triggerDownload('/x', 'x')).not.toThrow()+ await Promise.resolve()+ })+})++describe('formatDateWithLocale', () => {+ it('FE-W4FMH-010: formats an ISO date in the given locale', () => {+ expect(formatDateWithLocale('2026-06-15T10:00:00Z', 'en-GB')).toBe('15/06/2026')+ })++ it('FE-W4FMH-011: returns an empty string for a missing or unparseable date', () => {+ expect(formatDateWithLocale(null, 'en-GB')).toBe('')+ expect(formatDateWithLocale('', 'en-GB')).toBe('')+ expect(formatDateWithLocale('2026-06-15', 'en_US')).toBe('')+ })+})++describe('transportIcon', () => {+ it('FE-W4FMH-012: maps every transport type, defaulting to the plane', () => {+ expect(transportIcon('train')).toBe(Train)+ expect(transportIcon('bus')).toBe(Bus)+ expect(transportIcon('car')).toBe(Car)+ expect(transportIcon('taxi')).toBe(CarTaxiFront)+ expect(transportIcon('bicycle')).toBe(Bike)+ expect(transportIcon('cruise')).toBe(Ship)+ expect(transportIcon('ferry')).toBe(Sailboat)+ expect(transportIcon('transport_other')).toBe(Route)+ expect(transportIcon('flight')).toBe(Plane)+ expect(transportIcon('')).toBe(Plane)+ })+})diff --git a/client/src/components/Files/FileManagerAssignModal.test.tsx b/client/src/components/Files/FileManagerAssignModal.test.tsxnew file mode 100644index 000000000..afa92d9bf--- /dev/null+++ b/client/src/components/Files/FileManagerAssignModal.test.tsx@@ -0,0 +1,410 @@+// FE-W5ASG-001 to FE-W5ASG-022+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render'+import type { Day, Place, Reservation, TripFile } from '../../types'+import type { FileManagerState } from './useFileManager'++const getLinks = vi.fn(async (_tripId: number, _fileId: number): Promise<{ links?: unknown[] }> => ({ links: [] }))+const addLink = vi.fn(async (_tripId: number, _fileId: number, _data: unknown) => ({}))+const removeLink = vi.fn(async (_tripId: number, _fileId: number, _linkId: number) => ({}))++vi.mock('../../api/client', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../../api/client')>()+ return {+ ...actual,+ filesApi: {+ ...actual.filesApi,+ getLinks: (tripId: number, fileId: number) => getLinks(tripId, fileId),+ addLink: (tripId: number, fileId: number, data: unknown) => addLink(tripId, fileId, data),+ removeLink: (tripId: number, fileId: number, linkId: number) => removeLink(tripId, fileId, linkId),+ },+ }+})++import { AssignModal } from './FileManagerAssignModal'++const setAssignFileId = vi.fn()+const handleAssign = vi.fn(async (_fileId: number, _data: unknown) => {})+const refreshFiles = vi.fn(async () => {})++const file = (overrides: Partial<TripFile> = {}) =>+ ({ id: 7, original_name: 'ticket.pdf', description: '', url: '/uploads/files/ticket.pdf', ...overrides }) as unknown as TripFile++const place = (id: number, name: string) => ({ id, name }) as unknown as Place+const reservation = (id: number, title: string, type: string) => ({ id, title, type }) as unknown as Reservation+const day = (overrides: Partial<Day> = {}) => ({ id: 100, day_number: 1, ...overrides }) as unknown as Day++function state(overrides: Partial<FileManagerState> = {}): FileManagerState {+ return {+ files: [file()],+ assignFileId: 7,+ setAssignFileId,+ t: (key: string) => key,+ days: [],+ assignments: {},+ places: [],+ reservations: [],+ tripId: 3,+ handleAssign,+ refreshFiles,+ ...overrides,+ } as unknown as FileManagerState+}++beforeEach(() => {+ vi.clearAllMocks()+ getLinks.mockResolvedValue({ links: [] })+ addLink.mockResolvedValue({})+ removeLink.mockResolvedValue({})+})++describe('AssignModal shell', () => {+ it('FE-W5ASG-001: portals the modal and names the selected file', () => {+ const { container } = render(<AssignModal {...state()} />)++ expect(container).toBeEmptyDOMElement()+ expect(screen.getByText('files.assignTitle')).toBeInTheDocument()+ expect(screen.getByText('ticket.pdf')).toBeInTheDocument()+ })++ it('FE-W5ASG-002: the backdrop closes the modal but the card swallows the click', () => {+ render(<AssignModal {...state()} />)+ const card = screen.getByText('files.assignTitle').closest('div[style*="border-radius: 16px"]') as HTMLElement++ fireEvent.click(card)+ expect(setAssignFileId).not.toHaveBeenCalled()++ fireEvent.click(card.parentElement!)+ expect(setAssignFileId).toHaveBeenCalledWith(null)+ })++ it('FE-W5ASG-003: the header close button clears the selection', () => {+ render(<AssignModal {...state()} />)++ fireEvent.click(screen.getAllByRole('button')[0])++ expect(setAssignFileId).toHaveBeenCalledWith(null)+ })++ it('FE-W5ASG-034: the note label falls back to English when the key is missing', () => {+ render(<AssignModal {...state({ t: ((key: string) => (key === 'files.noteLabel' ? '' : key)) as FileManagerState['t'] })} />)++ expect(screen.getByText('Note')).toBeInTheDocument()+ })++ it('FE-W5ASG-004: an unknown file id leaves the header blank and the body empty', () => {+ render(<AssignModal {...state({ assignFileId: 999, places: [place(1, 'Louvre')] })} />)++ expect(screen.queryByText('ticket.pdf')).not.toBeInTheDocument()+ expect(screen.queryByText('files.assignPlace')).not.toBeInTheDocument()+ })+})++describe('AssignModal note field', () => {+ it('FE-W5ASG-005: a changed note is persisted on blur', () => {+ render(<AssignModal {...state()} />)+ const input = screen.getByPlaceholderText('files.notePlaceholder')++ fireEvent.blur(input, { target: { value: ' seat 14A ' } })++ expect(handleAssign).toHaveBeenCalledWith(7, { description: 'seat 14A' })+ })++ it('FE-W5ASG-006: an unchanged note is not persisted', () => {+ render(<AssignModal {...state({ files: [file({ description: 'seat 14A' })] })} />)+ const input = screen.getByPlaceholderText('files.notePlaceholder')++ fireEvent.blur(input, { target: { value: 'seat 14A' } })++ expect(handleAssign).not.toHaveBeenCalled()+ })++ it('FE-W5ASG-007: Enter blurs the note field, other keys do not', () => {+ render(<AssignModal {...state()} />)+ const input = screen.getByPlaceholderText('files.notePlaceholder') as HTMLInputElement+ const blur = vi.spyOn(input, 'blur')++ fireEvent.keyDown(input, { key: 'a' })+ expect(blur).not.toHaveBeenCalled()++ fireEvent.keyDown(input, { key: 'Enter' })+ expect(blur).toHaveBeenCalled()+ })+})++describe('AssignModal place list', () => {+ const places = [place(1, 'Louvre'), place(2, 'Eiffel Tower'), place(3, 'Sacré-Cœur')]++ it('FE-W5ASG-008: groups places under their day and shows the date badge', () => {+ render(<AssignModal {...state({+ places,+ days: [day({ id: 100, date: '2026-03-15', title: 'Museums' }), day({ id: 101, day_number: 2 })],+ assignments: { '100': [{ place: { id: 1 } }, { place_id: 2 }] as never },+ })} />)++ expect(screen.getByText('Museums')).toBeInTheDocument()+ expect(screen.getByText('2026-03-15')).toBeInTheDocument()+ // day 2 has no places and is dropped entirely+ expect(screen.queryByText('dayplan.dayN')).not.toBeInTheDocument()+ expect(screen.getByText('files.unassigned')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Sacré-Cœur' })).toBeInTheDocument()+ })++ it('FE-W5ASG-009: a titled day without a date badges the day number', () => {+ render(<AssignModal {...state({+ places,+ days: [day({ title: 'Museums' })],+ assignments: { '100': [{ place: { id: 1 } }] as never },+ })} />)++ expect(screen.getAllByText('dayplan.dayN')).toHaveLength(1)+ })++ it('FE-W5ASG-010: an untitled day without a date gets no badge', () => {+ render(<AssignModal {...state({+ places,+ days: [day()],+ assignments: { '100': [{ place: { id: 1 } }] as never },+ })} />)++ // only the group heading itself, no badge next to it+ expect(screen.getAllByText('dayplan.dayN')).toHaveLength(1)+ })++ it('FE-W5ASG-011: without day groups the unassigned heading is dropped', () => {+ render(<AssignModal {...state({ places })} />)++ expect(screen.getByText('files.assignPlace')).toBeInTheDocument()+ expect(screen.queryByText('files.unassigned')).not.toBeInTheDocument()+ })++ it('FE-W5ASG-012: the first place assignment goes through handleAssign', () => {+ render(<AssignModal {...state({ places })} />)++ fireEvent.click(screen.getByRole('button', { name: 'Louvre' }))++ expect(handleAssign).toHaveBeenCalledWith(7, { place_id: 1 })+ expect(addLink).not.toHaveBeenCalled()+ })++ it('FE-W5ASG-013: a second place becomes an extra link', async () => {+ render(<AssignModal {...state({ places, files: [file({ place_id: 1 })] })} />)++ fireEvent.click(screen.getByRole('button', { name: 'Eiffel Tower' }))++ await waitFor(() => expect(addLink).toHaveBeenCalledWith(3, 7, { place_id: 2 }))+ expect(refreshFiles).toHaveBeenCalled()+ })++ it('FE-W5ASG-014: a failing link request is swallowed', async () => {+ addLink.mockRejectedValueOnce(new Error('offline'))+ render(<AssignModal {...state({ places, files: [file({ place_id: 1 })] })} />)++ fireEvent.click(screen.getByRole('button', { name: 'Eiffel Tower' }))++ await waitFor(() => expect(addLink).toHaveBeenCalled())+ expect(refreshFiles).not.toHaveBeenCalled()+ })++ it('FE-W5ASG-015: clicking the primary place again unassigns it', () => {+ render(<AssignModal {...state({ places, files: [file({ place_id: 1 })] })} />)++ fireEvent.click(screen.getByRole('button', { name: 'Louvre' }))++ expect(handleAssign).toHaveBeenCalledWith(7, { place_id: null })+ })++ it('FE-W5ASG-016: clicking a linked place removes just that link', async () => {+ getLinks.mockResolvedValueOnce({ links: [{ id: 55, place_id: 2 }] })+ render(<AssignModal {...state({ places, files: [file({ place_id: 1, linked_place_ids: [2] })] })} />)++ fireEvent.click(screen.getByRole('button', { name: 'Eiffel Tower' }))++ await waitFor(() => expect(removeLink).toHaveBeenCalledWith(3, 7, 55))+ expect(refreshFiles).toHaveBeenCalled()+ })++ it('FE-W5ASG-017: a linked place with no matching link row still refreshes', async () => {+ getLinks.mockResolvedValueOnce({})+ render(<AssignModal {...state({ places, files: [file({ place_id: 1, linked_place_ids: [2] })] })} />)++ fireEvent.click(screen.getByRole('button', { name: 'Eiffel Tower' }))++ await waitFor(() => expect(refreshFiles).toHaveBeenCalled())+ expect(removeLink).not.toHaveBeenCalled()+ })++ it('FE-W5ASG-018: a failing links lookup is swallowed', async () => {+ getLinks.mockRejectedValueOnce(new Error('offline'))+ render(<AssignModal {...state({ places, files: [file({ place_id: 1, linked_place_ids: [2] })] })} />)++ fireEvent.click(screen.getByRole('button', { name: 'Eiffel Tower' }))++ await waitFor(() => expect(getLinks).toHaveBeenCalled())+ expect(refreshFiles).not.toHaveBeenCalled()+ })++ it('FE-W5ASG-019: rows keep the linked highlight on mouse-out, free rows do not', () => {+ render(<AssignModal {...state({ places, files: [file({ place_id: 1 })] })} />)+ const linked = screen.getByRole('button', { name: 'Louvre' })+ const free = screen.getByRole('button', { name: 'Eiffel Tower' })++ expect(linked.style.fontWeight).toBe('600')+ fireEvent.mouseEnter(linked)+ fireEvent.mouseLeave(linked)+ expect(linked.style.background).toBe('var(--bg-hover)')++ fireEvent.mouseEnter(free)+ expect(free.style.background).toBe('var(--bg-hover)')+ fireEvent.mouseLeave(free)+ expect(free.style.background).toBe('transparent')+ })+})++describe('AssignModal reservation list', () => {+ const bookings = [reservation(10, 'Hotel Lutetia', 'hotel')]+ const transports = [reservation(20, 'AF1234', 'flight'), reservation(21, 'TGV 8712', 'train')]++ it('FE-W5ASG-020: splits bookings from transports and gives each its own icon', () => {+ render(<AssignModal {...state({ reservations: [...bookings, ...transports] })} />)+ const iconOf = (name: string) =>+ screen.getByRole('button', { name }).querySelector('svg')?.getAttribute('class') ?? ''++ expect(screen.getByText('files.assignBooking')).toBeInTheDocument()+ expect(screen.getByText('files.assignTransport')).toBeInTheDocument()+ expect(iconOf('Hotel Lutetia')).toMatch(/ticket/)+ expect(iconOf('TGV 8712')).toMatch(/tram-front/)+ expect(iconOf('AF1234')).toMatch(/plane/)+ })++ it('FE-W5ASG-021: a transport-only trip shows no booking heading', () => {+ render(<AssignModal {...state({ reservations: transports })} />)++ expect(screen.queryByText('files.assignBooking')).not.toBeInTheDocument()+ expect(screen.getByText('files.assignTransport')).toBeInTheDocument()+ })++ it('FE-W5ASG-022: a booking-only trip shows no transport heading', () => {+ render(<AssignModal {...state({ reservations: bookings })} />)++ expect(screen.getByText('files.assignBooking')).toBeInTheDocument()+ expect(screen.queryByText('files.assignTransport')).not.toBeInTheDocument()+ })++ it('FE-W5ASG-023: the first reservation assignment goes through handleAssign', () => {+ render(<AssignModal {...state({ reservations: bookings })} />)++ fireEvent.click(screen.getByRole('button', { name: 'Hotel Lutetia' }))++ expect(handleAssign).toHaveBeenCalledWith(7, { reservation_id: 10 })+ })++ it('FE-W5ASG-024: a second reservation becomes an extra link', async () => {+ render(<AssignModal {...state({ reservations: [...bookings, ...transports], files: [file({ reservation_id: 10 })] })} />)++ fireEvent.click(screen.getByRole('button', { name: 'AF1234' }))++ await waitFor(() => expect(addLink).toHaveBeenCalledWith(3, 7, { reservation_id: 20 }))+ expect(refreshFiles).toHaveBeenCalled()+ })++ it('FE-W5ASG-025: a failing reservation link is swallowed', async () => {+ addLink.mockRejectedValueOnce(new Error('offline'))+ render(<AssignModal {...state({ reservations: [...bookings, ...transports], files: [file({ reservation_id: 10 })] })} />)++ fireEvent.click(screen.getByRole('button', { name: 'AF1234' }))++ await waitFor(() => expect(addLink).toHaveBeenCalled())+ expect(refreshFiles).not.toHaveBeenCalled()+ })++ it('FE-W5ASG-026: clicking the primary reservation again unassigns it', () => {+ render(<AssignModal {...state({ reservations: bookings, files: [file({ reservation_id: 10 })] })} />)++ fireEvent.click(screen.getByRole('button', { name: 'Hotel Lutetia' }))++ expect(handleAssign).toHaveBeenCalledWith(7, { reservation_id: null })+ })++ it('FE-W5ASG-027: clicking a linked reservation removes just that link', async () => {+ getLinks.mockResolvedValueOnce({ links: [{ id: 66, reservation_id: 20 }] })+ render(<AssignModal {...state({+ reservations: [...bookings, ...transports],+ files: [file({ reservation_id: 10, linked_reservation_ids: [20] })],+ })} />)++ fireEvent.click(screen.getByRole('button', { name: 'AF1234' }))++ await waitFor(() => expect(removeLink).toHaveBeenCalledWith(3, 7, 66))+ expect(refreshFiles).toHaveBeenCalled()+ })++ it('FE-W5ASG-028: a linked reservation with no matching link row still refreshes', async () => {+ getLinks.mockResolvedValueOnce({})+ render(<AssignModal {...state({+ reservations: [...bookings, ...transports],+ files: [file({ reservation_id: 10, linked_reservation_ids: [20] })],+ })} />)++ fireEvent.click(screen.getByRole('button', { name: 'AF1234' }))++ await waitFor(() => expect(refreshFiles).toHaveBeenCalled())+ expect(removeLink).not.toHaveBeenCalled()+ })++ it('FE-W5ASG-029: a failing reservation links lookup is swallowed', async () => {+ getLinks.mockRejectedValueOnce(new Error('offline'))+ render(<AssignModal {...state({+ reservations: [...bookings, ...transports],+ files: [file({ reservation_id: 10, linked_reservation_ids: [20] })],+ })} />)++ fireEvent.click(screen.getByRole('button', { name: 'AF1234' }))++ await waitFor(() => expect(getLinks).toHaveBeenCalled())+ expect(refreshFiles).not.toHaveBeenCalled()+ })++ it('FE-W5ASG-030: reservation rows keep the linked highlight on mouse-out', () => {+ render(<AssignModal {...state({ reservations: [...bookings, ...transports], files: [file({ reservation_id: 10 })] })} />)+ const linked = screen.getByRole('button', { name: 'Hotel Lutetia' })+ const free = screen.getByRole('button', { name: 'TGV 8712' })++ fireEvent.mouseEnter(linked)+ fireEvent.mouseLeave(linked)+ expect(linked.style.background).toBe('var(--bg-hover)')++ fireEvent.mouseEnter(free)+ expect(free.style.background).toBe('var(--bg-hover)')+ fireEvent.mouseLeave(free)+ expect(free.style.background).toBe('transparent')+ })+})++describe('AssignModal split layout', () => {+ it('FE-W5ASG-031: places and bookings sit side by side when both exist', () => {+ const { baseElement } = render(<AssignModal {...state({+ places: [place(1, 'Louvre')],+ reservations: [reservation(10, 'Hotel Lutetia', 'hotel')],+ })} />)++ expect(baseElement.querySelector('.md\\:flex')).not.toBeNull()+ expect(baseElement.querySelectorAll('.md\\:w-1\\/2')).toHaveLength(2)+ })++ it('FE-W5ASG-032: a places-only trip renders a single column', () => {+ const { baseElement } = render(<AssignModal {...state({ places: [place(1, 'Louvre')] })} />)++ expect(baseElement.querySelector('.md\\:flex')).toBeNull()+ expect(screen.getByText('files.assignPlace')).toBeInTheDocument()+ expect(screen.queryByText('files.assignBooking')).not.toBeInTheDocument()+ })++ it('FE-W5ASG-033: a bookings-only trip renders a single column', () => {+ const { baseElement } = render(<AssignModal {...state({ reservations: [reservation(10, 'Hotel Lutetia', 'hotel')] })} />)++ expect(baseElement.querySelector('.md\\:flex')).toBeNull()+ expect(screen.getByText('files.assignBooking')).toBeInTheDocument()+ expect(screen.queryByText('files.assignPlace')).not.toBeInTheDocument()+ })+})diff --git a/client/src/components/Files/FileManagerAvatarChip.test.tsx b/client/src/components/Files/FileManagerAvatarChip.test.tsxnew file mode 100644index 000000000..1319430dc--- /dev/null+++ b/client/src/components/Files/FileManagerAvatarChip.test.tsx@@ -0,0 +1,54 @@+// FE-W4AVC-001 to FE-W4AVC-006+import { describe, it, expect } from 'vitest'+import { render, screen, fireEvent } from '../../../tests/helpers/render'+import { AvatarChip } from './FileManagerAvatarChip'++describe('AvatarChip', () => {+ it('FE-W4AVC-001: falls back to the uppercased initial without an avatar', () => {+ const { container } = render(<AvatarChip name="ada" />)++ expect(container.firstElementChild).toHaveTextContent('A')+ expect(container.querySelector('img')).toBeNull()+ })++ it('FE-W4AVC-002: renders the avatar image when one is given', () => {+ const { container } = render(<AvatarChip name="ada" avatarUrl="/uploads/avatars/ada.png" />)++ expect(container.querySelector('img')).toHaveAttribute('src', '/uploads/avatars/ada.png')+ expect(container.firstElementChild).not.toHaveTextContent('A')+ })++ it('FE-W4AVC-003: sizes the chip and its glyph from the size prop', () => {+ const { container } = render(<AvatarChip name="ada" size={30} />)+ const chip = container.firstElementChild as HTMLElement++ expect(chip.style.width).toBe('30px')+ expect(chip.style.height).toBe('30px')+ expect(chip.style.fontSize).toBe('12px')+ })++ it('FE-W4AVC-004: defaults to a 20px chip', () => {+ const { container } = render(<AvatarChip name="ada" />)++ expect((container.firstElementChild as HTMLElement).style.width).toBe('20px')+ })++ it('FE-W4AVC-005: hovering portals a name tooltip and leaving removes it', () => {+ const { container } = render(<AvatarChip name="Ada Lovelace" />)+ const chip = container.firstElementChild as HTMLElement++ fireEvent.mouseEnter(chip)+ const tip = screen.getByText('Ada Lovelace')+ expect(tip).toBeInTheDocument()+ expect(container.contains(tip)).toBe(false)++ fireEvent.mouseLeave(chip)+ expect(screen.queryByText('Ada Lovelace')).toBeNull()+ })++ it('FE-W4AVC-006: renders nothing in the chip for an empty name', () => {+ const { container } = render(<AvatarChip name="" />)++ expect(container.firstElementChild).toBeEmptyDOMElement()+ })+})diff --git a/client/src/components/Files/FileManagerImageLightbox.test.tsx b/client/src/components/Files/FileManagerImageLightbox.test.tsxnew file mode 100644index 000000000..ce25174db--- /dev/null+++ b/client/src/components/Files/FileManagerImageLightbox.test.tsx@@ -0,0 +1,211 @@+// FE-W4LBX-001 to FE-W4LBX-017+import { describe, it, expect, vi, beforeEach } from 'vitest'+import type { TripFile } from '../../types'+import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render'++const getAuthUrl = vi.fn(async (url: string, _kind: string) => `${url}?token=abc`)+const openFile = vi.fn(async (_url: string, _name: string) => {})+const downloadFile = vi.fn(async (_url: string, _name: string) => {})++vi.mock('../../api/authUrl', () => ({ getAuthUrl: (url: string, kind: string) => getAuthUrl(url, kind) }))+vi.mock('../../utils/fileDownload', () => ({+ openFile: (url: string, name: string) => openFile(url, name),+ downloadFile: (url: string, name: string) => downloadFile(url, name),+}))+vi.mock('../Journey/VideoPlayer', () => ({+ default: ({ src }: { src: string }) => <div data-testid="video" data-src={src} />,+}))++import { ImageLightbox } from './FileManagerImageLightbox'++type LightboxFile = TripFile & { url: string }++function file(overrides: Partial<LightboxFile> = {}): LightboxFile {+ return { id: 1, original_name: 'beach.jpg', mime_type: 'image/jpeg', url: '/uploads/files/beach.jpg', ...overrides } as unknown as LightboxFile+}++const IMAGES = [+ file({ id: 1, original_name: 'a.jpg', url: '/f/a.jpg' }),+ file({ id: 2, original_name: 'b.jpg', url: '/f/b.jpg' }),+ file({ id: 3, original_name: 'c.jpg', url: '/f/c.jpg' }),+]++beforeEach(() => {+ getAuthUrl.mockReset()+ getAuthUrl.mockImplementation(async (url: string) => `${url}?token=abc`)+ openFile.mockReset()+ openFile.mockResolvedValue(undefined)+ downloadFile.mockReset()+ downloadFile.mockResolvedValue(undefined)+})++describe('ImageLightbox', () => {+ it('FE-W4LBX-001: renders nothing when the index points past the list', () => {+ const { container } = render(<ImageLightbox files={[]} initialIndex={0} onClose={() => {}} />)+ expect(container).toBeEmptyDOMElement()+ })++ it('FE-W4LBX-002: shows the file name and its position in the gallery', () => {+ render(<ImageLightbox files={IMAGES} initialIndex={1} onClose={() => {}} />)++ expect(screen.getByText('b.jpg', { exact: false })).toBeInTheDocument()+ expect(screen.getByText('2 / 3')).toBeInTheDocument()+ })++ it('FE-W4LBX-003: mints a signed download url for the shown image', async () => {+ const { container } = render(<ImageLightbox files={IMAGES} initialIndex={0} onClose={() => {}} />)++ await waitFor(() => expect(container.querySelector('img[alt="a.jpg"]')).not.toBeNull())+ expect(getAuthUrl).toHaveBeenCalledWith('/f/a.jpg', 'download')+ expect(container.querySelector('img[alt="a.jpg"]')).toHaveAttribute('src', '/f/a.jpg?token=abc')+ })++ it('FE-W4LBX-004: hides the previous arrow on the first and the next arrow on the last file', () => {+ const first = render(<ImageLightbox files={IMAGES} initialIndex={0} onClose={() => {}} />)+ // header (3) + next arrow + 3 thumbnails+ expect(first.container.querySelectorAll('.lucide-chevron-left')).toHaveLength(0)+ expect(first.container.querySelectorAll('.lucide-chevron-right')).toHaveLength(1)+ first.unmount()++ const last = render(<ImageLightbox files={IMAGES} initialIndex={2} onClose={() => {}} />)+ expect(last.container.querySelectorAll('.lucide-chevron-left')).toHaveLength(1)+ expect(last.container.querySelectorAll('.lucide-chevron-right')).toHaveLength(0)+ })++ it('FE-W4LBX-005: the arrows page through the gallery', () => {+ const { container } = render(<ImageLightbox files={IMAGES} initialIndex={0} onClose={() => {}} />)++ fireEvent.click(container.querySelector('.lucide-chevron-right')!.closest('button')!)+ expect(screen.getByText('2 / 3')).toBeInTheDocument()++ fireEvent.click(container.querySelector('.lucide-chevron-left')!.closest('button')!)+ expect(screen.getByText('1 / 3')).toBeInTheDocument()+ })++ it('FE-W4LBX-006: the arrow keys page and Escape closes', () => {+ const onClose = vi.fn()+ render(<ImageLightbox files={IMAGES} initialIndex={0} onClose={onClose} />)++ fireEvent.keyDown(window, { key: 'ArrowRight' })+ expect(screen.getByText('2 / 3')).toBeInTheDocument()++ fireEvent.keyDown(window, { key: 'ArrowLeft' })+ expect(screen.getByText('1 / 3')).toBeInTheDocument()++ fireEvent.keyDown(window, { key: 'Escape' })+ expect(onClose).toHaveBeenCalledOnce()+ })++ it('FE-W4LBX-007: paging never runs past either end', () => {+ render(<ImageLightbox files={IMAGES} initialIndex={0} onClose={() => {}} />)++ fireEvent.keyDown(window, { key: 'ArrowLeft' })+ expect(screen.getByText('1 / 3')).toBeInTheDocument()++ fireEvent.keyDown(window, { key: 'ArrowRight' })+ fireEvent.keyDown(window, { key: 'ArrowRight' })+ fireEvent.keyDown(window, { key: 'ArrowRight' })+ expect(screen.getByText('3 / 3')).toBeInTheDocument()+ })++ it('FE-W4LBX-008: a swipe pages in the swiped direction', () => {+ const { container } = render(<ImageLightbox files={IMAGES} initialIndex={1} onClose={() => {}} />)+ const root = container.firstElementChild as HTMLElement++ fireEvent.touchStart(root, { touches: [{ clientX: 200 }] })+ fireEvent.touchEnd(root, { changedTouches: [{ clientX: 100 }] })+ expect(screen.getByText('3 / 3')).toBeInTheDocument()++ fireEvent.touchStart(root, { touches: [{ clientX: 100 }] })+ fireEvent.touchEnd(root, { changedTouches: [{ clientX: 220 }] })+ expect(screen.getByText('2 / 3')).toBeInTheDocument()+ })++ it('FE-W4LBX-009: a short swipe is ignored', () => {+ const { container } = render(<ImageLightbox files={IMAGES} initialIndex={1} onClose={() => {}} />)+ const root = container.firstElementChild as HTMLElement++ fireEvent.touchStart(root, { touches: [{ clientX: 200 }] })+ fireEvent.touchEnd(root, { changedTouches: [{ clientX: 180 }] })++ expect(screen.getByText('2 / 3')).toBeInTheDocument()+ })++ it('FE-W4LBX-010: a touch end without a start is ignored', () => {+ const { container } = render(<ImageLightbox files={IMAGES} initialIndex={1} onClose={() => {}} />)++ fireEvent.touchEnd(container.firstElementChild!, { changedTouches: [{ clientX: 0 }] })++ expect(screen.getByText('2 / 3')).toBeInTheDocument()+ })++ it('FE-W4LBX-011: the header buttons open, download and close', () => {+ const onClose = vi.fn()+ render(<ImageLightbox files={IMAGES} initialIndex={0} onClose={onClose} />)++ fireEvent.click(screen.getByTitle(/open/i))+ expect(openFile).toHaveBeenCalledWith('/f/a.jpg', 'a.jpg')++ fireEvent.click(screen.getByTitle(/download/i))+ expect(downloadFile).toHaveBeenCalledWith('/f/a.jpg', 'a.jpg')++ fireEvent.click(screen.getAllByRole('button')[2])+ expect(onClose).toHaveBeenCalledOnce()+ })++ it('FE-W4LBX-012: clicking the backdrop closes but clicking the image does not', async () => {+ const onClose = vi.fn()+ const { container } = render(<ImageLightbox files={IMAGES} initialIndex={0} onClose={onClose} />)++ await waitFor(() => expect(container.querySelector('img[alt="a.jpg"]')).not.toBeNull())+ fireEvent.click(container.querySelector('img[alt="a.jpg"]')!)+ expect(onClose).not.toHaveBeenCalled()++ fireEvent.click(container.firstElementChild!)+ expect(onClose).toHaveBeenCalledOnce()+ })++ it('FE-W4LBX-013: the thumbnail strip jumps to the picked file', async () => {+ render(<ImageLightbox files={IMAGES} initialIndex={0} onClose={() => {}} />)+ // header: open + download + close, then the next arrow, then three thumbs.+ const thumbs = screen.getAllByRole('button').slice(-3)++ fireEvent.click(thumbs[2])++ expect(screen.getByText('3 / 3')).toBeInTheDocument()+ await waitFor(() => expect(getAuthUrl).toHaveBeenCalledWith('/f/c.jpg', 'download'))+ })++ it('FE-W4LBX-014: hides the strip for a single file', () => {+ render(<ImageLightbox files={[IMAGES[0]]} initialIndex={0} onClose={() => {}} />)++ expect(screen.getAllByRole('button')).toHaveLength(3)+ })++ it('FE-W4LBX-015: a video plays in the player and never mints a download token', () => {+ const video = file({ id: 9, original_name: 'clip.mp4', mime_type: 'video/mp4', url: '/f/clip.mp4' })+ const { container } = render(<ImageLightbox files={[video]} initialIndex={0} onClose={() => {}} />)++ expect(screen.getByTestId('video')).toHaveAttribute('data-src', '/f/clip.mp4')+ expect(getAuthUrl).not.toHaveBeenCalled()+ expect(container.querySelector('img')).toBeNull()+ })++ it('FE-W4LBX-016: a video thumbnail is a play glyph, not an image request', async () => {+ const files = [IMAGES[0], file({ id: 9, original_name: 'clip.mp4', mime_type: 'video/mp4', url: '/f/clip.mp4' })]+ const { container } = render(<ImageLightbox files={files} initialIndex={0} onClose={() => {}} />)++ await waitFor(() => expect(getAuthUrl).toHaveBeenCalledWith('/f/a.jpg', 'download'))+ expect(getAuthUrl).not.toHaveBeenCalledWith('/f/clip.mp4', 'download')+ expect(container.querySelector('.lucide-play')).not.toBeNull()+ })++ it('FE-W4LBX-017: clicking the video wrapper does not close the lightbox', () => {+ const onClose = vi.fn()+ render(<ImageLightbox files={[file({ mime_type: 'video/mp4' })]} initialIndex={0} onClose={onClose} />)++ fireEvent.click(screen.getByTestId('video').parentElement!)++ expect(onClose).not.toHaveBeenCalled()+ })+})diff --git a/client/src/components/Files/FileManagerPreviewModals.test.tsx b/client/src/components/Files/FileManagerPreviewModals.test.tsxnew file mode 100644index 000000000..7068e7a46--- /dev/null+++ b/client/src/components/Files/FileManagerPreviewModals.test.tsx@@ -0,0 +1,190 @@+// FE-W4FPM-001 to FE-W4FPM-014+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import type { TripFile } from '../../types'+import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render'+import type { FileManagerState } from './useFileManager'++const openFile = vi.fn(async (_url: string, _name: string) => {})+const downloadFile = vi.fn(async (_url: string, _name: string) => {})++vi.mock('../../utils/fileDownload', () => ({+ openFile: (url: string, name: string) => openFile(url, name),+ downloadFile: (url: string, name: string) => downloadFile(url, name),+}))++import { PdfPreviewModal } from './FileManagerPdfPreviewModal'+import { MarkdownPreviewModal } from './FileManagerMarkdownPreviewModal'++const toast = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() }+const setPreviewFile = vi.fn()++function state(overrides: Partial<FileManagerState> = {}): FileManagerState {+ return {+ previewFile: { id: 1, original_name: 'ticket.pdf', url: '/uploads/files/ticket.pdf' } as unknown as TripFile,+ previewFileUrl: '/uploads/files/ticket.pdf?token=abc',+ setPreviewFile,+ toast,+ t: (key: string) => key,+ ...overrides,+ } as unknown as FileManagerState+}++beforeEach(() => {+ openFile.mockReset()+ openFile.mockResolvedValue(undefined)+ downloadFile.mockReset()+ downloadFile.mockResolvedValue(undefined)+ setPreviewFile.mockClear()+ Object.values(toast).forEach(f => f.mockClear())+})++afterEach(() => {+ vi.unstubAllGlobals()+})++describe('PdfPreviewModal', () => {+ it('FE-W4FPM-001: portals the viewer with the signed url and the file name', () => {+ const { container, baseElement } = render(<PdfPreviewModal {...state()} />)++ expect(container).toBeEmptyDOMElement()+ expect(screen.getByText('ticket.pdf')).toBeInTheDocument()+ const object = baseElement.querySelector('object') as HTMLObjectElement+ expect(object).toHaveAttribute('data', '/uploads/files/ticket.pdf?token=abc#view=FitH')+ expect(object).toHaveAttribute('type', 'application/pdf')+ })++ it('FE-W4FPM-002: leaves the viewer source unset while no signed url exists yet', () => {+ const { baseElement } = render(<PdfPreviewModal {...state({ previewFileUrl: null })} />)++ expect(baseElement.querySelector('object')).not.toHaveAttribute('data')+ })++ it('FE-W4FPM-003: the open-in-tab button uses the unsigned url', () => {+ render(<PdfPreviewModal {...state()} />)++ fireEvent.click(screen.getByRole('button', { name: /openTab/ }))++ expect(openFile).toHaveBeenCalledWith('/uploads/files/ticket.pdf', 'ticket.pdf')+ })++ it('FE-W4FPM-004: a failed open toasts the error', async () => {+ openFile.mockRejectedValue(new Error('blocked'))+ render(<PdfPreviewModal {...state()} />)++ fireEvent.click(screen.getByRole('button', { name: /openTab/ }))++ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('files.openError'))+ })++ it('FE-W4FPM-005: the download button hands the file to the download helper', () => {+ render(<PdfPreviewModal {...state()} />)++ fireEvent.click(screen.getByRole('button', { name: 'files.download' }))++ expect(downloadFile).toHaveBeenCalledWith('/uploads/files/ticket.pdf', 'ticket.pdf')+ })++ it('FE-W4FPM-006: the close button and the backdrop clear the preview, the card does not', () => {+ const { baseElement } = render(<PdfPreviewModal {...state()} />)+ const backdrop = baseElement.querySelector('div[style*="rgba(0, 0, 0, 0.85)"]') as HTMLElement++ fireEvent.click(screen.getAllByRole('button')[2])+ expect(setPreviewFile).toHaveBeenCalledWith(null)++ setPreviewFile.mockClear()+ fireEvent.click(backdrop.firstElementChild!)+ expect(setPreviewFile).not.toHaveBeenCalled()++ fireEvent.click(backdrop)+ expect(setPreviewFile).toHaveBeenCalledWith(null)+ })++ it('FE-W4FPM-007: the no-plugin fallback also opens the file', () => {+ render(<PdfPreviewModal {...state()} />)++ fireEvent.click(screen.getByRole('button', { name: 'files.downloadPdf' }))++ expect(openFile).toHaveBeenCalledWith('/uploads/files/ticket.pdf', 'ticket.pdf')+ })++ it('FE-W4FPM-014: the toolbar buttons brighten on hover and dim again', () => {+ render(<PdfPreviewModal {...state()} />)++ for (const button of screen.getAllByRole('button').slice(0, 3)) {+ fireEvent.mouseEnter(button)+ expect(button.style.color).toBe('var(--text-primary)')+ fireEvent.mouseLeave(button)+ expect(button.style.color).toBe(button === screen.getAllByRole('button')[2] ? 'var(--text-faint)' : 'var(--text-muted)')+ }+ })+})++describe('MarkdownPreviewModal', () => {+ const mdState = (overrides: Partial<FileManagerState> = {}) => state({+ previewFile: { id: 2, original_name: 'notes.md', url: '/uploads/files/notes.md' } as unknown as TripFile,+ previewFileUrl: '/uploads/files/notes.md?token=abc',+ ...overrides,+ })++ it('FE-W4FPM-008: fetches the markdown with credentials and renders it', async () => {+ const fetchMock = vi.fn(async () => ({ ok: true, text: async () => '# Packing\n\nBring a **towel**.' }))+ vi.stubGlobal('fetch', fetchMock)++ render(<MarkdownPreviewModal {...mdState()} />)++ expect(fetchMock).toHaveBeenCalledWith('/uploads/files/notes.md?token=abc', { credentials: 'include' })+ expect(await screen.findByRole('heading', { name: 'Packing' })).toBeInTheDocument()+ expect(screen.getByText('towel')).toBeInTheDocument()+ })++ it('FE-W4FPM-009: shows the error copy when the fetch fails', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('offline') }))++ render(<MarkdownPreviewModal {...mdState()} />)++ expect(await screen.findByText('files.openError')).toBeInTheDocument()+ })++ it('FE-W4FPM-010: shows the error copy on a non-ok response', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, text: async () => '' })))++ render(<MarkdownPreviewModal {...mdState()} />)++ expect(await screen.findByText('files.openError')).toBeInTheDocument()+ })++ it('FE-W4FPM-011: skips the fetch until a signed url exists', () => {+ const fetchMock = vi.fn()+ vi.stubGlobal('fetch', fetchMock)++ render(<MarkdownPreviewModal {...mdState({ previewFileUrl: null })} />)++ expect(fetchMock).not.toHaveBeenCalled()+ expect(screen.getByText('notes.md')).toBeInTheDocument()+ })++ it('FE-W4FPM-012: the header buttons open, download and close', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, text: async () => 'hi' })))+ render(<MarkdownPreviewModal {...mdState()} />)++ fireEvent.click(screen.getByRole('button', { name: /openTab/ }))+ expect(openFile).toHaveBeenCalledWith('/uploads/files/notes.md', 'notes.md')++ fireEvent.click(screen.getByRole('button', { name: 'files.download' }))+ expect(downloadFile).toHaveBeenCalledWith('/uploads/files/notes.md', 'notes.md')++ fireEvent.click(screen.getAllByRole('button')[2])+ expect(setPreviewFile).toHaveBeenCalledWith(null)+ await waitFor(() => expect(screen.getByText('hi')).toBeInTheDocument())+ })++ it('FE-W4FPM-013: a failed open toasts the error', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, text: async () => '' })))+ openFile.mockRejectedValue(new Error('blocked'))+ render(<MarkdownPreviewModal {...mdState()} />)++ fireEvent.click(screen.getByRole('button', { name: /openTab/ }))++ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('files.openError'))+ })+})diff --git a/client/src/components/Journey/ContributorInviteDialog.test.tsx b/client/src/components/Journey/ContributorInviteDialog.test.tsxnew file mode 100644index 000000000..60e9d1ab6--- /dev/null+++ b/client/src/components/Journey/ContributorInviteDialog.test.tsx@@ -0,0 +1,175 @@+// FE-JRN-INVITE-001 to FE-JRN-INVITE-011++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { http, HttpResponse } from 'msw'+import userEvent from '@testing-library/user-event'+import { render, screen, waitFor, act } from '../../../tests/helpers/render'+import { server } from '../../../tests/helpers/msw/server'+import ContributorInviteDialog from './ContributorInviteDialog'++type ToastKind = 'success' | 'error' | 'warning' | 'info'++const toastSpy = vi.fn((_message: string, _type?: ToastKind, _duration?: number) => 0)++const users = [+ { id: 1, username: 'maurice', email: '[email protected]' },+ { id: 2, username: 'julien', email: '[email protected]' },+ { id: 3, username: 'anna', email: '[email protected]' },+]++function mountDialog(props: Partial<React.ComponentProps<typeof ContributorInviteDialog>> = {}) {+ const onClose = vi.fn()+ const onInvited = vi.fn()+ render(+ <ContributorInviteDialog+ journeyId={4}+ existingUserIds={[]}+ onClose={onClose}+ onInvited={onInvited}+ {...props}+ />,+ )+ return { onClose, onInvited }+}++beforeEach(() => {+ toastSpy.mockClear()+ window.__addToast = toastSpy+ server.use(http.get('/api/auth/users', () => HttpResponse.json({ users })))+})++afterEach(() => {+ delete window.__addToast+})++describe('ContributorInviteDialog', () => {+ it('FE-JRN-INVITE-001: lists every selectable user returned by the API', async () => {+ mountDialog()++ expect(await screen.findByText('maurice')).toBeInTheDocument()+ expect(screen.getByText('[email protected]')).toBeInTheDocument()+ expect(screen.getByText('anna')).toBeInTheDocument()+ })++ it('FE-JRN-INVITE-002: hides users that already contribute to the journey', async () => {+ mountDialog({ existingUserIds: [1, 3] })++ expect(await screen.findByText('julien')).toBeInTheDocument()+ expect(screen.queryByText('maurice')).not.toBeInTheDocument()+ expect(screen.queryByText('anna')).not.toBeInTheDocument()+ })++ it('FE-JRN-INVITE-003: filters the list by username', async () => {+ const user = userEvent.setup()+ mountDialog()+ await screen.findByText('maurice')++ await user.type(screen.getByPlaceholderText('Username or email...'), 'jul')++ expect(screen.getByText('julien')).toBeInTheDocument()+ expect(screen.queryByText('maurice')).not.toBeInTheDocument()+ })++ it('FE-JRN-INVITE-004: filters the list by email address', async () => {+ const user = userEvent.setup()+ mountDialog()+ await screen.findByText('maurice')++ await user.type(screen.getByPlaceholderText('Username or email...'), 'trek.dev')++ expect(screen.getByText('julien')).toBeInTheDocument()+ expect(screen.queryByText('anna')).not.toBeInTheDocument()+ })++ it('FE-JRN-INVITE-005: shows the empty hint when nothing matches the search', async () => {+ const user = userEvent.setup()+ mountDialog()+ await screen.findByText('maurice')++ await user.type(screen.getByPlaceholderText('Username or email...'), 'nobody')++ expect(screen.getByText('No users found')).toBeInTheDocument()+ })++ it('FE-JRN-INVITE-006: keeps the invite button disabled until a user is selected', async () => {+ const user = userEvent.setup()+ mountDialog()+ const row = await screen.findByText('julien')++ const inviteBtn = screen.getByRole('button', { name: 'Invite' })+ expect(inviteBtn).toBeDisabled()++ await user.click(row)+ expect(inviteBtn).toBeEnabled()+ })++ it('FE-JRN-INVITE-007: defaults the role to viewer and switches to editor on click', async () => {+ const user = userEvent.setup()+ mountDialog()+ await screen.findByText('maurice')++ const viewerBtn = screen.getByRole('button', { name: 'Viewer' })+ const editorBtn = screen.getByRole('button', { name: 'Editor' })+ expect(viewerBtn.className).toContain('bg-zinc-900')+ expect(editorBtn.className).not.toContain('bg-zinc-900')++ await user.click(editorBtn)+ expect(editorBtn.className).toContain('bg-zinc-900')+ expect(viewerBtn.className).not.toContain('bg-zinc-900')+ })++ it('FE-JRN-INVITE-008: posts the selected user and role, then reports success', async () => {+ const bodies: Record<string, unknown>[] = []+ server.use(http.post('/api/journeys/4/contributors', async ({ request }) => {+ bodies.push(await request.json() as Record<string, unknown>)+ return HttpResponse.json({ ok: true })+ }))+ const user = userEvent.setup()+ const { onInvited } = mountDialog()++ await user.click(await screen.findByText('julien'))+ await user.click(screen.getByRole('button', { name: 'Editor' }))+ await user.click(screen.getByRole('button', { name: 'Invite' }))++ await waitFor(() => expect(onInvited).toHaveBeenCalledTimes(1))+ expect(bodies[0]).toEqual({ user_id: 2, role: 'editor' })+ expect(toastSpy).toHaveBeenCalledWith('Contributor added', 'success', undefined)+ })++ it('FE-JRN-INVITE-009: reports a failed invite without notifying the parent', async () => {+ server.use(http.post('/api/journeys/4/contributors', () => new HttpResponse(null, { status: 403 })))+ const user = userEvent.setup()+ const { onInvited } = mountDialog()++ await user.click(await screen.findByText('anna'))+ await user.click(screen.getByRole('button', { name: 'Invite' }))++ await waitFor(() => {+ expect(toastSpy).toHaveBeenCalledWith('Failed to add contributor', 'error', undefined)+ })+ expect(onInvited).not.toHaveBeenCalled()+ expect(screen.getByRole('button', { name: 'Invite' })).toBeEnabled()+ })++ it('FE-JRN-INVITE-010: closes on both the header and the footer cancel button', async () => {+ const user = userEvent.setup()+ const { onClose } = mountDialog()+ await screen.findByText('maurice')++ await user.click(screen.getByRole('button', { name: 'Cancel' }))+ expect(onClose).toHaveBeenCalledTimes(1)++ // The header close button carries only an icon, so it is addressed by position.+ const headerClose = screen.getByRole('heading', { name: 'Invite Contributor' })+ .parentElement!.querySelector('button')!+ act(() => { headerClose.click() })+ expect(onClose).toHaveBeenCalledTimes(2)+ })++ it('FE-JRN-INVITE-011: renders the empty hint when the user list cannot be fetched', async () => {+ server.use(http.get('/api/auth/users', () => new HttpResponse(null, { status: 500 })))+ mountDialog()++ expect(await screen.findByText('No users found')).toBeInTheDocument()+ })+})diff --git a/client/src/components/Journey/JournalBody.test.tsx b/client/src/components/Journey/JournalBody.test.tsxindex 4a74878d1..0d9cc0270 100644--- a/client/src/components/Journey/JournalBody.test.tsx+++ b/client/src/components/Journey/JournalBody.test.tsx@@ -1,4 +1,4 @@-// FE-COMP-JOURNALBODY-001 to FE-COMP-JOURNALBODY-005+// FE-COMP-JOURNALBODY-001 to FE-COMP-JOURNALBODY-013import { describe, it, expect } from 'vitest';import { render, screen } from '../../../tests/helpers/render';@@ -36,4 +36,64 @@ describe('JournalBody', () => {const { container } = render(<JournalBody text="" />);expect(container.querySelector('.journal-body')).toBeInTheDocument();});++ it('FE-COMP-JOURNALBODY-006: renders block quotes with the journal accent border', () => {+ const { container } = render(<JournalBody text="> Remember the light" />);+ const quote = container.querySelector('blockquote');+ expect(quote).toBeInTheDocument();+ expect(quote!.textContent).toContain('Remember the light');+ expect(quote!.getAttribute('style')).toContain('var(--journal-accent)');+ });++ it('FE-COMP-JOURNALBODY-007: renders bullet and numbered lists', () => {+ const { container } = render(<JournalBody text={'- one\n- two\n\n1. first\n2. second'} />);+ expect(container.querySelectorAll('ul li')).toHaveLength(2);+ expect(container.querySelectorAll('ol li')).toHaveLength(2);+ expect(screen.getByText('second')).toBeInTheDocument();+ });++ it('FE-COMP-JOURNALBODY-008: renders emphasis and horizontal rules', () => {+ const { container } = render(<JournalBody text={'Some *stress* here\n\n---\n\nAfter'} />);+ expect(container.querySelector('em')!.textContent).toBe('stress');+ expect(container.querySelector('hr')).toBeInTheDocument();+ });++ it('FE-COMP-JOURNALBODY-009: renders inline code without a pre wrapper', () => {+ const { container } = render(<JournalBody text="Run `npm test` now" />);+ const code = container.querySelector('code');+ expect(code!.textContent).toBe('npm test');+ expect(container.querySelector('pre')).not.toBeInTheDocument();+ expect(code!.getAttribute('style')).toContain('rgba(0, 0, 0, 0.06)');+ });++ it('FE-COMP-JOURNALBODY-010: renders fenced code blocks inside a pre element', () => {+ const { container } = render(<JournalBody text={'```js\nconst a = 1\n```'} />);+ const pre = container.querySelector('pre');+ expect(pre).toBeInTheDocument();+ expect(pre!.querySelector('code')!.textContent).toContain('const a = 1');+ });++ it('FE-COMP-JOURNALBODY-011: renders h1 and h3 as plain paragraphs', () => {+ const { container } = render(<JournalBody text={'# Big\n\n### Small'} />);+ expect(container.querySelector('h1')).not.toBeInTheDocument();+ expect(container.querySelector('h3')).not.toBeInTheDocument();+ expect(screen.getByText('Big').tagName).toBe('P');+ expect(screen.getByText('Small').tagName).toBe('P');+ });++ it('FE-COMP-JOURNALBODY-012: keeps a setext underline as text instead of a heading', () => {+ // The pre-pass inserts a blank line so "====" stays its own block.+ const { container } = render(<JournalBody text={'Day One\n===='} />);+ expect(screen.getByText('Day One')).toBeInTheDocument();+ expect(screen.getByText('====')).toBeInTheDocument();+ expect(container.querySelectorAll('p')).toHaveLength(2);+ });++ it('FE-COMP-JOURNALBODY-013: darkens code backgrounds in dark mode', () => {+ const { container } = render(<JournalBody text={'`x`\n\n```js\ny\n```'} dark />);+ const [inline] = Array.from(container.querySelectorAll('code'));+ expect(inline.getAttribute('style')).toContain('rgba(255, 255, 255, 0.08)');+ // react-markdown supplies its own outer <pre>; the styled one is nested inside.+ expect(container.querySelectorAll('pre')[1].getAttribute('style')).toContain('rgba(255, 255, 255, 0.05)');+ });});diff --git a/client/src/components/Journey/JourneyDetailPageAddTripDialog.test.tsx b/client/src/components/Journey/JourneyDetailPageAddTripDialog.test.tsxnew file mode 100644index 000000000..721516a79--- /dev/null+++ b/client/src/components/Journey/JourneyDetailPageAddTripDialog.test.tsx@@ -0,0 +1,148 @@+// FE-JRN-ADDTRIP-001 to FE-JRN-ADDTRIP-009++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { http, HttpResponse, delay } from 'msw'+import userEvent from '@testing-library/user-event'+import { render, screen, waitFor, act } from '../../../tests/helpers/render'+import { server } from '../../../tests/helpers/msw/server'+import { AddTripDialog } from './JourneyDetailPageAddTripDialog'++type ToastKind = 'success' | 'error' | 'warning' | 'info'++const toastSpy = vi.fn((_message: string, _type?: ToastKind, _duration?: number) => 0)++const trips = [+ { id: 11, title: 'Italy Roadtrip', destination: 'Rome', start_date: '2026-03-14', end_date: '2026-03-20' },+ { id: 12, title: 'Winter Break', destination: 'Tromso' },+ { id: 13, title: 'City Hop' },+]++function mountDialog(props: Partial<React.ComponentProps<typeof AddTripDialog>> = {}) {+ const onClose = vi.fn()+ const onAdded = vi.fn()+ render(+ <AddTripDialog journeyId={4} existingTripIds={[]} onClose={onClose} onAdded={onAdded} {...props} />,+ )+ return { onClose, onAdded }+}++beforeEach(() => {+ toastSpy.mockClear()+ window.__addToast = toastSpy+ server.use(http.get('/api/journeys/available-trips', () => HttpResponse.json({ trips })))+})++afterEach(() => {+ delete window.__addToast+})++describe('AddTripDialog', () => {+ it('FE-JRN-ADDTRIP-001: lists the trips available for linking', async () => {+ mountDialog()++ expect(await screen.findByText('Italy Roadtrip')).toBeInTheDocument()+ expect(screen.getByText('Winter Break')).toBeInTheDocument()+ expect(screen.getByText('City Hop')).toBeInTheDocument()+ })++ it('FE-JRN-ADDTRIP-002: renders destination and start date as the trip subtitle', async () => {+ mountDialog()++ expect(await screen.findByText('Rome · 2026-03-14')).toBeInTheDocument()+ // Trips without a start date only show the destination.+ expect(screen.getByText('Tromso')).toBeInTheDocument()+ })++ it('FE-JRN-ADDTRIP-003: hides trips that are already linked', async () => {+ mountDialog({ existingTripIds: [11, 13] })++ expect(await screen.findByText('Winter Break')).toBeInTheDocument()+ expect(screen.queryByText('Italy Roadtrip')).not.toBeInTheDocument()+ expect(screen.queryByText('City Hop')).not.toBeInTheDocument()+ })++ it('FE-JRN-ADDTRIP-004: filters by title and by destination', async () => {+ const user = userEvent.setup()+ mountDialog()+ await screen.findByText('Italy Roadtrip')+ const search = screen.getByPlaceholderText('Trip name or destination...')++ await user.type(search, 'city')+ expect(screen.getByText('City Hop')).toBeInTheDocument()+ expect(screen.queryByText('Winter Break')).not.toBeInTheDocument()++ await user.clear(search)+ await user.type(search, 'tromso')+ expect(screen.getByText('Winter Break')).toBeInTheDocument()+ expect(screen.queryByText('City Hop')).not.toBeInTheDocument()+ })++ it('FE-JRN-ADDTRIP-005: shows the empty hint when no trip matches', async () => {+ const user = userEvent.setup()+ mountDialog()+ await screen.findByText('Italy Roadtrip')++ await user.type(screen.getByPlaceholderText('Trip name or destination...'), 'zzz')++ expect(screen.getByText('No trips available')).toBeInTheDocument()+ })++ it('FE-JRN-ADDTRIP-006: links the picked trip and notifies the parent', async () => {+ const bodies: Record<string, unknown>[] = []+ server.use(http.post('/api/journeys/4/trips', async ({ request }) => {+ bodies.push(await request.json() as Record<string, unknown>)+ return HttpResponse.json({ ok: true })+ }))+ const user = userEvent.setup()+ const { onAdded } = mountDialog()+ await screen.findByText('Italy Roadtrip')++ await user.click(screen.getAllByRole('button', { name: 'Link' })[0])++ await waitFor(() => expect(onAdded).toHaveBeenCalledTimes(1))+ expect(bodies[0]).toEqual({ trip_id: 11 })+ expect(toastSpy).toHaveBeenCalledWith('Trip linked', 'success', undefined)+ })++ it('FE-JRN-ADDTRIP-007: shows a busy state on the row while the link request runs', async () => {+ server.use(http.post('/api/journeys/4/trips', async () => {+ await delay(40)+ return HttpResponse.json({ ok: true })+ }))+ const user = userEvent.setup()+ const { onAdded } = mountDialog()+ await screen.findByText('Italy Roadtrip')++ await user.click(screen.getAllByRole('button', { name: 'Link' })[0])+ expect(screen.getByRole('button', { name: '...' })).toBeDisabled()++ await waitFor(() => expect(onAdded).toHaveBeenCalled())+ })++ it('FE-JRN-ADDTRIP-008: reports a failed link and re-enables the row', async () => {+ server.use(http.post('/api/journeys/4/trips', () => new HttpResponse(null, { status: 500 })))+ const user = userEvent.setup()+ const { onAdded } = mountDialog()+ await screen.findByText('Italy Roadtrip')++ await user.click(screen.getAllByRole('button', { name: 'Link' })[0])++ await waitFor(() => {+ expect(toastSpy).toHaveBeenCalledWith('Failed to link trip', 'error', undefined)+ })+ expect(onAdded).not.toHaveBeenCalled()+ expect(screen.getAllByRole('button', { name: 'Link' })[0]).toBeEnabled()+ })++ it('FE-JRN-ADDTRIP-009: closes via the header button and survives a failed trip fetch', async () => {+ server.use(http.get('/api/journeys/available-trips', () => new HttpResponse(null, { status: 500 })))+ const { onClose } = mountDialog()++ expect(await screen.findByText('No trips available')).toBeInTheDocument()++ const headerClose = screen.getByRole('heading', { name: 'Link Trip' })+ .parentElement!.querySelector('button')!+ act(() => { headerClose.click() })+ expect(onClose).toHaveBeenCalledTimes(1)+ })+})diff --git a/client/src/components/Journey/JourneyDetailPageEntryCard.test.tsx b/client/src/components/Journey/JourneyDetailPageEntryCard.test.tsxnew file mode 100644index 000000000..0094a2603--- /dev/null+++ b/client/src/components/Journey/JourneyDetailPageEntryCard.test.tsx@@ -0,0 +1,239 @@+// FE-JRN-CARD-001 to FE-JRN-CARD-017++import { describe, it, expect, beforeEach, vi } from 'vitest'+import { http, HttpResponse } from 'msw'+import userEvent from '@testing-library/user-event'+import { render, screen, waitFor } from '../../../tests/helpers/render'+import { server } from '../../../tests/helpers/msw/server'+import { usePluginStore } from '../../store/pluginStore'+import type { JourneyEntry, JourneyPhoto } from '../../store/journeyStore'+import { EntryCard, SkeletonCard, CheckinCard } from './JourneyDetailPageEntryCard'++function buildPhoto(id: number): JourneyPhoto {+ return { id, entry_id: 10, photo_id: id, caption: null, sort_order: 0, shared: 1, created_at: 0 }+}++function buildEntry(overrides: Partial<JourneyEntry> = {}): JourneyEntry {+ return {+ id: 10,+ journey_id: 1,+ author_id: 1,+ type: 'entry',+ entry_date: '2026-03-15',+ title: 'Arrived in Rome',+ story: null,+ location_name: 'Rome, Italy',+ entry_time: '10:00',+ visibility: 'private',+ sort_order: 0,+ photos: [],+ created_at: 0,+ updated_at: 0,+ ...overrides,+ }+}++function mountCard(entry: JourneyEntry, readOnly = false) {+ const onEdit = vi.fn()+ const onDelete = vi.fn()+ const onPhotoClick = vi.fn()+ const utils = render(+ <EntryCard entry={entry} readOnly={readOnly} onEdit={onEdit} onDelete={onDelete} onPhotoClick={onPhotoClick} />,+ )+ return { ...utils, onEdit, onDelete, onPhotoClick }+}++beforeEach(() => {+ usePluginStore.setState({ plugins: [], loaded: true })+})++describe('EntryCard', () => {+ it('FE-JRN-CARD-001: renders the header layout for an entry without photos', () => {+ mountCard(buildEntry())++ expect(screen.getByText('Arrived in Rome')).toBeInTheDocument()+ expect(screen.getByText('Rome, Italy')).toBeInTheDocument()+ expect(screen.getByText('10:00')).toBeInTheDocument()+ })++ it('FE-JRN-CARD-002: renders the photo hero with the title overlaid', () => {+ const { container } = mountCard(buildEntry({ photos: [buildPhoto(100)] }))++ const img = container.querySelector('img[src="/api/photos/100/thumbnail"]')+ expect(img).toBeInTheDocument()+ expect(screen.getByRole('heading', { name: 'Arrived in Rome' })).toBeInTheDocument()+ })++ it('FE-JRN-CARD-003: forwards a photo click with the photo list and index', async () => {+ const user = userEvent.setup()+ const photos = [buildPhoto(100), buildPhoto(101)]+ const { container, onPhotoClick } = mountCard(buildEntry({ photos }))++ await user.click(container.querySelector('img[src="/api/photos/101/thumbnail"]') as HTMLElement)++ expect(onPhotoClick).toHaveBeenCalledWith(photos, 1)+ })++ it('FE-JRN-CARD-004: opens the photo-card menu and triggers edit', async () => {+ const user = userEvent.setup()+ const { container, onEdit } = mountCard(buildEntry({ photos: [buildPhoto(100)] }))++ await user.click(container.querySelectorAll('button')[0])+ await user.click(screen.getByRole('button', { name: 'Edit' }))++ expect(onEdit).toHaveBeenCalledTimes(1)+ expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument()+ })++ it('FE-JRN-CARD-005: opens the header menu and triggers delete', async () => {+ const user = userEvent.setup()+ const { container, onDelete } = mountCard(buildEntry())++ await user.click(container.querySelectorAll('button')[0])+ await user.click(screen.getByRole('button', { name: 'Delete' }))++ expect(onDelete).toHaveBeenCalledTimes(1)+ })++ it('FE-JRN-CARD-006: closes the menu again when the backdrop is clicked', async () => {+ const user = userEvent.setup()+ const { container } = mountCard(buildEntry())++ await user.click(container.querySelectorAll('button')[0])+ const backdrop = document.querySelector('.fixed.inset-0.z-\\[99\\]') as HTMLElement+ expect(backdrop).toBeInTheDocument()++ await user.click(backdrop)+ expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument()+ })++ it('FE-JRN-CARD-007: hides the menu entirely in read-only mode', () => {+ const { container } = mountCard(buildEntry({ photos: [buildPhoto(100)] }), true)++ expect(container.querySelectorAll('button')).toHaveLength(0)+ })++ it('FE-JRN-CARD-008: renders mood, weather and tags in the meta row', () => {+ mountCard(buildEntry({ mood: 'amazing', weather: 'sunny', tags: ['culture', 'food'] }))++ expect(screen.getByText('Amazing')).toBeInTheDocument()+ expect(screen.getByText('Sunny')).toBeInTheDocument()+ expect(screen.getByText('culture')).toBeInTheDocument()+ expect(screen.getByText('food')).toBeInTheDocument()+ })++ it('FE-JRN-CARD-009: renders the pros/cons verdict and the story body', () => {+ mountCard(buildEntry({ story: 'A wonderful evening', pros_cons: { pros: ['Great food'], cons: ['Crowded'] } }))++ expect(screen.getByText('A wonderful evening')).toBeInTheDocument()+ expect(screen.getByText('Great food')).toBeInTheDocument()+ expect(screen.getByText('Crowded')).toBeInTheDocument()+ })++ it('FE-JRN-CARD-010: skips the plugin request while no plugins are active', async () => {+ let called = 0+ server.use(http.get('/api/journal-entry-rows/10', () => {+ called += 1+ return HttpResponse.json({ providers: [] })+ }))+ mountCard(buildEntry())++ await waitFor(() => expect(screen.getByText('Arrived in Rome')).toBeInTheDocument())+ expect(called).toBe(0)+ })++ it('FE-JRN-CARD-011: renders plugin rows as text and links, dropping empty providers', async () => {+ usePluginStore.setState({+ plugins: [{ id: 'koffi', name: 'Koffi', type: 'widget', icon: null }],+ loaded: true,+ })+ server.use(http.get('/api/journal-entry-rows/10', () => HttpResponse.json({+ providers: [+ { pluginId: 'koffi', items: [{ label: 'Coffee', value: 'Espresso' }, { label: 'Shop', value: 'Sant Eustachio', url: 'https://example.com' }] },+ { pluginId: 'empty', items: [] },+ ],+ })))+ mountCard(buildEntry())++ expect(await screen.findByText('Espresso')).toBeInTheDocument()+ const link = screen.getByRole('link', { name: 'Sant Eustachio' })+ expect(link).toHaveAttribute('href', 'https://example.com')+ expect(screen.queryByText('empty')).not.toBeInTheDocument()+ })++ it('FE-JRN-CARD-012: renders no plugin rows when the request fails', async () => {+ usePluginStore.setState({+ plugins: [{ id: 'koffi', name: 'Koffi', type: 'widget', icon: null }],+ loaded: true,+ })+ server.use(http.get('/api/journal-entry-rows/10', () => new HttpResponse(null, { status: 500 })))+ const { container } = mountCard(buildEntry())++ await waitFor(() => expect(screen.getByText('Arrived in Rome')).toBeInTheDocument())+ expect(container.querySelectorAll('a')).toHaveLength(0)+ })++ it('FE-JRN-CARD-013: falls back to the entry URL when a plugin row has no value', async () => {+ usePluginStore.setState({+ plugins: [{ id: 'koffi', name: 'Koffi', type: 'widget', icon: null }],+ loaded: true,+ })+ server.use(http.get('/api/journal-entry-rows/10', () => HttpResponse.json({+ providers: [{ pluginId: 'koffi', items: [{ label: 'Booking', url: 'https://book.example' }] }],+ })))+ mountCard(buildEntry())++ expect(await screen.findByRole('link', { name: 'https://book.example' })).toBeInTheDocument()+ })+})++describe('SkeletonCard', () => {+ it('FE-JRN-CARD-014: shows the placeholder title and the add CTA when clickable', async () => {+ const user = userEvent.setup()+ const onClick = vi.fn()+ render(<SkeletonCard entry={buildEntry({ title: null })} onClick={onClick} />)++ expect(screen.getByText('New Entry')).toBeInTheDocument()+ expect(screen.getByText('Rome, Italy · 10:00')).toBeInTheDocument()++ await user.click(screen.getByText('Add Entry'))+ expect(onClick).toHaveBeenCalledTimes(1)+ })++ it('FE-JRN-CARD-015: omits the add CTA when no click handler is given', () => {+ render(<SkeletonCard entry={buildEntry({ entry_time: null })} />)++ expect(screen.getByText('Arrived in Rome')).toBeInTheDocument()+ expect(screen.queryByText('Add Entry')).not.toBeInTheDocument()+ expect(screen.getByText('Rome, Italy')).toBeInTheDocument()+ })+})++describe('CheckinCard', () => {+ it('FE-JRN-CARD-016: renders title, location, story and time', async () => {+ const user = userEvent.setup()+ const onClick = vi.fn()+ render(+ <CheckinCard+ entry={buildEntry({ type: 'checkin', title: 'Quick stop', story: 'Espresso', entry_time: '15:30' })}+ onClick={onClick}+ />,+ )++ expect(screen.getByText('Quick stop')).toBeInTheDocument()+ expect(screen.getByText('· Rome, Italy')).toBeInTheDocument()+ expect(screen.getByText('Espresso')).toBeInTheDocument()++ await user.click(screen.getByText('15:30'))+ expect(onClick).toHaveBeenCalledTimes(1)+ })++ it('FE-JRN-CARD-017: renders a bare check-in without location, story or time', () => {+ const { container } = render(+ <CheckinCard entry={buildEntry({ type: 'checkin', title: 'Bare stop', location_name: null, entry_time: null })} />,+ )++ expect(screen.getByText('Bare stop')).toBeInTheDocument()+ expect(container.querySelector('.cursor-pointer')).not.toBeInTheDocument()+ })+})diff --git a/client/src/components/Journey/JourneyDetailPageEntryEditor.test.tsx b/client/src/components/Journey/JourneyDetailPageEntryEditor.test.tsxnew file mode 100644index 000000000..c5d0006a2--- /dev/null+++ b/client/src/components/Journey/JourneyDetailPageEntryEditor.test.tsx@@ -0,0 +1,798 @@+// FE-JRN-EDITOR-001 to FE-JRN-EDITOR-039++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { http, HttpResponse, delay } from 'msw'+import userEvent from '@testing-library/user-event'+import { render, screen, waitFor, fireEvent } from '../../../tests/helpers/render'+import { server } from '../../../tests/helpers/msw/server'+import type { GalleryPhoto, JourneyEntry, JourneyPhoto, JourneyTrip } from '../../store/journeyStore'+import type { ResilientResult, UploadProgress } from '../../utils/uploadQueue'+import { EntryEditor } from './JourneyDetailPageEntryEditor'++type ToastKind = 'success' | 'error' | 'warning' | 'info'++const toastSpy = vi.fn((_message: string, _type?: ToastKind, _duration?: number) => 0)++const trips: JourneyTrip[] = [+ { trip_id: 5, added_at: 0, title: 'Italy Trip', start_date: '2026-03-14', end_date: '2026-03-20', place_count: 3 },+]++function buildEntry(overrides: Partial<JourneyEntry> = {}): JourneyEntry {+ return {+ id: 0,+ journey_id: 1,+ author_id: 1,+ type: 'entry',+ entry_date: '2026-03-15',+ entry_time: '',+ visibility: 'private',+ sort_order: 0,+ photos: [],+ created_at: 0,+ updated_at: 0,+ ...overrides,+ }+}++function buildPhoto(id: number): JourneyPhoto {+ return { id, entry_id: 10, photo_id: id, caption: null, sort_order: 0, shared: 1, created_at: 0 }+}++function buildGalleryPhoto(id: number): GalleryPhoto {+ return { id, journey_id: 1, photo_id: id, caption: null, shared: 1, sort_order: 0, created_at: 0 }+}++function mountEditor(+ entry: JourneyEntry,+ opts: { galleryPhotos?: GalleryPhoto[]; withProviderHook?: boolean } = {},+) {+ const onClose = vi.fn()+ const onDone = vi.fn()+ const onSave = vi.fn(async (_data: Record<string, unknown>, _existingEntryId?: number) => 55)+ const onUploadPhotos = vi.fn(+ async (_entryId: number, files: File[], cbs?: { onProgress?: (p: UploadProgress) => void }) => {+ cbs?.onProgress?.({ done: files.length, total: files.length, failed: 0, percent: 100 })+ return { succeeded: [] as JourneyPhoto[], failed: [] as File[] }+ },+ )+ const onAddProviderPhotos = vi.fn(async () => {})+ const utils = render(+ <EntryEditor+ entry={entry}+ journeyId={1}+ tripDates={new Set(['2026-03-15'])}+ galleryPhotos={opts.galleryPhotos ?? []}+ trips={trips}+ userId={42}+ onClose={onClose}+ onSave={onSave}+ onUploadPhotos={onUploadPhotos}+ onAddProviderPhotos={opts.withProviderHook === false ? undefined : onAddProviderPhotos}+ onDone={onDone}+ />,+ )+ return { ...utils, onClose, onDone, onSave, onUploadPhotos, onAddProviderPhotos }+}++function useConnectedImmich() {+ server.use(+ http.get('/api/addons', () => HttpResponse.json({+ addons: [{ id: 'immich', name: 'Immich', type: 'photo_provider', icon: 'camera', enabled: true }],+ })),+ http.get('/api/integrations/memories/immich/status', () => HttpResponse.json({ connected: true })),+ http.post('/api/integrations/memories/immich/search', () => HttpResponse.json({+ assets: [{ id: 'asset-1', takenAt: '2026-03-15T09:00:00.000Z', mediaType: 'image' }],+ hasMore: false,+ })),+ )+}++const originalCreateObjectURL = URL.createObjectURL++beforeEach(() => {+ toastSpy.mockClear()+ window.__addToast = toastSpy+ Object.defineProperty(URL, 'createObjectURL', {+ configurable: true, writable: true, value: vi.fn(() => 'blob:preview'),+ })+})++afterEach(() => {+ delete window.__addToast+ Object.defineProperty(URL, 'createObjectURL', {+ configurable: true, writable: true, value: originalCreateObjectURL,+ })+})++describe('EntryEditor', () => {+ it('FE-JRN-EDITOR-001: opens as a new entry with empty fields', () => {+ mountEditor(buildEntry())++ expect(screen.getByRole('heading', { name: 'New Entry' })).toBeInTheDocument()+ expect(screen.getByPlaceholderText('Give this moment a name...')).toHaveValue('')+ expect(screen.getByPlaceholderText('Write your story...')).toHaveValue('')+ expect(screen.getByPlaceholderText('Search location...')).toHaveValue('')+ })++ it('FE-JRN-EDITOR-002: seeds every field from an existing entry', () => {+ mountEditor(buildEntry({+ id: 10, title: 'Arrived in Rome', story: 'Amazing city', location_name: 'Rome',+ location_lat: 41.9, location_lng: 12.5, mood: 'amazing', weather: 'sunny',+ pros_cons: { pros: ['Great food'], cons: ['Crowded'] },+ }))++ expect(screen.getByRole('heading', { name: 'Edit Entry' })).toBeInTheDocument()+ expect(screen.getByDisplayValue('Arrived in Rome')).toBeInTheDocument()+ expect(screen.getByDisplayValue('Amazing city')).toBeInTheDocument()+ expect(screen.getByDisplayValue('Rome')).toBeInTheDocument()+ expect(screen.getByDisplayValue('Great food')).toBeInTheDocument()+ expect(screen.getByDisplayValue('Crowded')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Amazing' }).className).not.toContain('border-zinc-200')+ })++ it('FE-JRN-EDITOR-003: saves the edited fields and finishes', async () => {+ const user = userEvent.setup()+ const { onSave, onDone } = mountEditor(buildEntry({ id: 10, title: 'Old' }))++ await user.clear(screen.getByDisplayValue('Old'))+ await user.type(screen.getByPlaceholderText('Give this moment a name...'), 'Rome')+ await user.type(screen.getByPlaceholderText('Write your story...'), 'Great day')+ await user.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => expect(onDone).toHaveBeenCalledTimes(1))+ expect(onSave).toHaveBeenCalledWith(+ expect.objectContaining({+ title: 'Rome',+ story: 'Great day',+ entry_date: '2026-03-15',+ entry_time: null,+ location_name: null,+ mood: null,+ weather: null,+ pros_cons: { pros: [], cons: [] },+ type: undefined,+ }),+ 10,+ )+ })++ it('FE-JRN-EDITOR-004: promotes a skeleton to a real entry once it has a story', async () => {+ const user = userEvent.setup()+ const { onSave } = mountEditor(buildEntry({ id: 21, type: 'skeleton', title: 'Venice' }))++ await user.type(screen.getByPlaceholderText('Write your story...'), 'Gondolas')+ await user.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => expect(onSave).toHaveBeenCalled())+ expect(onSave.mock.calls[0][0]).toMatchObject({ type: 'entry' })+ })++ it('FE-JRN-EDITOR-005: uploads files queued before the save', async () => {+ const user = userEvent.setup()+ const { container, onUploadPhotos, onDone } = mountEditor(buildEntry())++ const file = new File(['a'], 'a.jpg', { type: 'image/jpeg' })+ fireEvent.change(container.querySelector('input[type="file"]') as HTMLInputElement, { target: { files: [file] } })+ await waitFor(() => expect(container.querySelector('img[src="blob:preview"]')).toBeInTheDocument())++ await user.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => expect(onDone).toHaveBeenCalledTimes(1))+ expect(onUploadPhotos).toHaveBeenCalledWith(55, [file], expect.anything())+ })++ it('FE-JRN-EDITOR-006: keeps the files that failed to upload and warns', async () => {+ const user = userEvent.setup()+ const { container, onUploadPhotos } = mountEditor(buildEntry())+ const file = new File(['a'], 'a.jpg', { type: 'image/jpeg' })+ onUploadPhotos.mockResolvedValueOnce({ succeeded: [], failed: [file] })++ fireEvent.change(container.querySelector('input[type="file"]') as HTMLInputElement, { target: { files: [file] } })+ await waitFor(() => expect(container.querySelector('img[src="blob:preview"]')).toBeInTheDocument())+ await user.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => {+ expect(toastSpy).toHaveBeenCalledWith('1 of 1 photos failed — save again to retry', 'error', undefined)+ })+ expect(container.querySelector('img[src="blob:preview"]')).toBeInTheDocument()+ })++ it('FE-JRN-EDITOR-007: reports a rejected upload', async () => {+ const user = userEvent.setup()+ const { container, onUploadPhotos, onDone } = mountEditor(buildEntry())+ onUploadPhotos.mockRejectedValueOnce(new Error('disk full'))++ fireEvent.change(container.querySelector('input[type="file"]') as HTMLInputElement, {+ target: { files: [new File(['a'], 'a.jpg', { type: 'image/jpeg' })] },+ })+ await waitFor(() => expect(container.querySelector('img[src="blob:preview"]')).toBeInTheDocument())+ await user.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('disk full', 'error', undefined))+ expect(onDone).toHaveBeenCalledTimes(1)+ })++ it('FE-JRN-EDITOR-008: drops a queued file again from the preview strip', async () => {+ const user = userEvent.setup()+ const { container } = mountEditor(buildEntry())++ fireEvent.change(container.querySelector('input[type="file"]') as HTMLInputElement, {+ target: { files: [new File(['a'], 'a.jpg', { type: 'image/jpeg' })] },+ })+ await waitFor(() => expect(container.querySelector('img[src="blob:preview"]')).toBeInTheDocument())++ const preview = container.querySelector('img[src="blob:preview"]') as HTMLElement+ await user.click(preview.parentElement!.querySelector('button') as HTMLElement)+ expect(container.querySelector('img[src="blob:preview"]')).not.toBeInTheDocument()+ })++ it('FE-JRN-EDITOR-009: links gallery photos picked before the entry exists', async () => {+ const linked: string[] = []+ server.use(http.post('/api/journeys/entries/55/link-photo', async ({ request }) => {+ linked.push(JSON.stringify(await request.json()))+ return HttpResponse.json({ id: 200 })+ }))+ const user = userEvent.setup()+ const { onDone } = mountEditor(buildEntry(), { galleryPhotos: [buildGalleryPhoto(200)] })++ await user.click(screen.getByRole('button', { name: 'From Gallery' }))+ await user.click(screen.getAllByAltText('')[0])+ await user.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => expect(onDone).toHaveBeenCalledTimes(1))+ expect(linked).toEqual([JSON.stringify({ journey_photo_id: 200 })])+ })++ it('FE-JRN-EDITOR-010: links a gallery photo straight away on an existing entry', async () => {+ let linked = false+ server.use(http.post('/api/journeys/entries/10/link-photo', () => {+ linked = true+ return HttpResponse.json({ id: 200, entry_id: 10, photo_id: 200, sort_order: 0, shared: 1, created_at: 0 })+ }))+ const user = userEvent.setup()+ const { container } = mountEditor(buildEntry({ id: 10 }), { galleryPhotos: [buildGalleryPhoto(200)] })++ await user.click(screen.getByRole('button', { name: 'From Gallery' }))+ await user.click(screen.getAllByAltText('')[0])++ await waitFor(() => expect(linked).toBe(true))+ // The linked photo joins the strip, so the picker reports nothing left.+ expect(container.querySelectorAll('img[src="/api/photos/200/thumbnail"]').length).toBeGreaterThan(0)+ expect(await screen.findByText('All photos already added')).toBeInTheDocument()+ })++ it('FE-JRN-EDITOR-011: unlinks a removed photo from an existing entry', async () => {+ let unlinked = false+ server.use(http.delete('/api/journeys/entries/10/photos/100', () => {+ unlinked = true+ return HttpResponse.json({ ok: true })+ }))+ const user = userEvent.setup()+ const { container } = mountEditor(buildEntry({ id: 10, photos: [buildPhoto(100)] }))++ const tile = container.querySelector('img[src="/api/photos/100/thumbnail"]')!.parentElement as HTMLElement+ await user.click(tile.querySelector('button') as HTMLElement)++ await waitFor(() => expect(unlinked).toBe(true))+ expect(container.querySelector('img[src="/api/photos/100/thumbnail"]')).not.toBeInTheDocument()+ })++ it('FE-JRN-EDITOR-012: promoting a photo to first persists the new sort order', async () => {+ const patched: Array<{ id: string; body: unknown }> = []+ server.use(http.patch('/api/journeys/photos/:id', async ({ params, request }) => {+ patched.push({ id: String(params.id), body: await request.json() })+ return HttpResponse.json({ ok: true })+ }))+ const user = userEvent.setup()+ const { container } = mountEditor(buildEntry({ id: 10, photos: [buildPhoto(100), buildPhoto(101)] }))++ expect(screen.getByText('1st')).toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: 'Make 1st' }))++ await waitFor(() => expect(patched).toHaveLength(2))+ expect(patched).toEqual([+ { id: '101', body: { sort_order: 0 } },+ { id: '100', body: { sort_order: 1 } },+ ])+ const imgs = Array.from(container.querySelectorAll('img')).map(i => i.getAttribute('src'))+ expect(imgs[0]).toBe('/api/photos/101/thumbnail')+ })++ it('FE-JRN-EDITOR-013: asks before discarding a dirty editor', async () => {+ const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false)+ const user = userEvent.setup()+ const { onClose } = mountEditor(buildEntry({ id: 10, title: 'Rome' }))++ await user.type(screen.getByDisplayValue('Rome'), '!')+ await user.click(screen.getByRole('button', { name: 'Cancel' }))++ expect(confirmSpy).toHaveBeenCalledWith('You have unsaved changes. Discard them?')+ expect(onClose).not.toHaveBeenCalled()++ confirmSpy.mockReturnValue(true)+ await user.click(screen.getByRole('button', { name: 'Cancel' }))+ expect(onClose).toHaveBeenCalledTimes(1)+ confirmSpy.mockRestore()+ })++ it('FE-JRN-EDITOR-014: closes an untouched editor without asking', async () => {+ const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true)+ const user = userEvent.setup()+ const { onClose } = mountEditor(buildEntry({ id: 10 }))++ await user.click(screen.getByRole('button', { name: 'Cancel' }))++ expect(confirmSpy).not.toHaveBeenCalled()+ expect(onClose).toHaveBeenCalledTimes(1)+ confirmSpy.mockRestore()+ })++ it('FE-JRN-EDITOR-015: adds and removes pro and con rows', async () => {+ const user = userEvent.setup()+ const { onSave } = mountEditor(buildEntry({ id: 10 }))++ const [addPro, addCon] = screen.getAllByRole('button', { name: 'Add another' })+ await user.click(addPro)+ await user.click(addCon)++ const proInputs = screen.getAllByPlaceholderText('Something great...')+ expect(proInputs).toHaveLength(2)+ await user.type(proInputs[0], 'Food')+ await user.type(screen.getAllByPlaceholderText('Not so great...')[1], 'Queues')++ // Each extra row gets its own delete control once more than one exists.+ const removeSecondPro = proInputs[1].parentElement!.querySelector('button') as HTMLElement+ await user.click(removeSecondPro)+ expect(screen.getAllByPlaceholderText('Something great...')).toHaveLength(1)++ await user.click(screen.getByRole('button', { name: 'Save' }))+ await waitFor(() => expect(onSave).toHaveBeenCalled())+ expect(onSave.mock.calls[0][0]).toMatchObject({ pros_cons: { pros: ['Food'], cons: ['Queues'] } })+ })++ it('FE-JRN-EDITOR-016: toggles mood and weather chips on and off', async () => {+ const user = userEvent.setup()+ const { onSave } = mountEditor(buildEntry({ id: 10 }))++ await user.click(screen.getByRole('button', { name: 'Neutral' }))+ await user.click(screen.getByRole('button', { name: 'Rainy' }))+ expect(screen.getByRole('button', { name: 'Rainy' }).className).toContain('bg-zinc-900')++ await user.click(screen.getByRole('button', { name: 'Rainy' }))+ expect(screen.getByRole('button', { name: 'Rainy' }).className).not.toContain('bg-zinc-900')++ await user.click(screen.getByRole('button', { name: 'Save' }))+ await waitFor(() => expect(onSave).toHaveBeenCalled())+ expect(onSave.mock.calls[0][0]).toMatchObject({ mood: 'neutral', weather: null })+ })++ it('FE-JRN-EDITOR-017: picks a searched location and stores its coordinates', async () => {+ server.use(http.post('/api/maps/search', () => HttpResponse.json({+ places: [{ name: 'Roma Termini', address: 'Piazza dei Cinquecento', lat: 41.9, lng: 12.5 }],+ })))+ const user = userEvent.setup()+ const { onSave } = mountEditor(buildEntry({ id: 10 }))++ fireEvent.change(screen.getByPlaceholderText('Search location...'), { target: { value: 'Roma' } })++ const result = await screen.findByText('Roma Termini', {}, { timeout: 3000 })+ expect(screen.getByText('Piazza dei Cinquecento')).toBeInTheDocument()+ await user.click(result)++ expect(screen.getByDisplayValue('Roma Termini')).toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: 'Save' }))+ await waitFor(() => expect(onSave).toHaveBeenCalled())+ expect(onSave.mock.calls[0][0]).toMatchObject({ location_name: 'Roma Termini', location_lat: 41.9, location_lng: 12.5 })+ })++ it('FE-JRN-EDITOR-018: shows no suggestions when the location search fails', async () => {+ let calls = 0+ server.use(http.post('/api/maps/search', () => {+ calls += 1+ return new HttpResponse(null, { status: 500 })+ }))+ mountEditor(buildEntry({ id: 10 }))+ const input = screen.getByPlaceholderText('Search location...')++ // A one-character query never reaches the network at all.+ fireEvent.change(input, { target: { value: 'R' } })+ fireEvent.change(input, { target: { value: 'Roma' } })++ await waitFor(() => expect(calls).toBe(1), { timeout: 3000 })+ await waitFor(() => expect(screen.queryByText('Searching...')).not.toBeInTheDocument())+ expect(screen.getByDisplayValue('Roma')).toBeInTheDocument()+ })++ it('FE-JRN-EDITOR-022: dismisses the suggestion list and brings it back on focus', async () => {+ server.use(http.post('/api/maps/search', () => HttpResponse.json({+ places: [{ name: 'Roma Termini', address: 'Piazza dei Cinquecento', lat: 41.9, lng: 12.5 }],+ })))+ const user = userEvent.setup()+ mountEditor(buildEntry({ id: 10 }))+ const input = screen.getByPlaceholderText('Search location...')++ fireEvent.change(input, { target: { value: 'Roma' } })+ await screen.findByText('Roma Termini', {}, { timeout: 3000 })++ await user.click(document.querySelector('.fixed.inset-0.z-\\[99\\]') as HTMLElement)+ expect(screen.queryByText('Roma Termini')).not.toBeInTheDocument()++ fireEvent.focus(input)+ expect(screen.getByText('Roma Termini')).toBeInTheDocument()+ })++ it('FE-JRN-EDITOR-019: reports that no external provider is connected', async () => {+ server.use(http.get('/api/addons', () => HttpResponse.json({ addons: [] })))+ const user = userEvent.setup()+ mountEditor(buildEntry({ id: 10 }))++ await user.click(screen.getByRole('button', { name: 'External photos' }))++ expect(await screen.findByText('No connected photo providers are available.')).toBeInTheDocument()+ })++ it('FE-JRN-EDITOR-020: queues photos picked from a connected provider and clears them again', async () => {+ useConnectedImmich()+ const user = userEvent.setup()+ mountEditor(buildEntry({ id: 10, location_lat: 41.9, location_lng: 12.5, location_name: 'Rome' }))++ await user.click(screen.getByRole('button', { name: 'External photos' }))+ expect(await screen.findByTestId('journey-external-provider-immich')).toBeInTheDocument()+ expect(screen.getByText('Nearby photos first · Rome')).toBeInTheDocument()+ expect(screen.getByText('Photos for Mar 15, 2026')).toBeInTheDocument()++ await user.click(await screen.findByAltText(''))+ await user.click(screen.getByRole('button', { name: 'Add (1)' }))++ const clearBtn = await screen.findByRole('button', { name: /1 queued · Clear/ })+ await user.click(clearBtn)+ expect(screen.queryByRole('button', { name: /queued/ })).not.toBeInTheDocument()+ })++ it('FE-JRN-EDITOR-021: sends queued provider photos on save and keeps the failed ones', async () => {+ useConnectedImmich()+ const user = userEvent.setup()+ const { onAddProviderPhotos, onDone } = mountEditor(buildEntry({ id: 10 }))++ await user.click(screen.getByRole('button', { name: 'External photos' }))+ expect(await screen.findByText('All photos from this day')).toBeInTheDocument()+ await user.click(await screen.findByAltText(''))+ await user.click(screen.getByRole('button', { name: 'Add (1)' }))+ await screen.findByRole('button', { name: /1 queued · Clear/ })++ onAddProviderPhotos.mockRejectedValueOnce(new Error('provider down'))+ await user.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => {+ expect(toastSpy).toHaveBeenCalledWith('1 photo groups failed — save again to retry', 'error', undefined)+ })+ expect(onDone).not.toHaveBeenCalled()++ await user.click(screen.getByRole('button', { name: 'Save' }))+ await waitFor(() => expect(onDone).toHaveBeenCalledTimes(1))+ expect(onAddProviderPhotos).toHaveBeenLastCalledWith(55, expect.objectContaining({+ provider: 'immich',+ assetIds: ['asset-1'],+ }))+ })++ it('FE-JRN-EDITOR-023: the upload button closes the gallery picker and an empty pick is ignored', async () => {+ const user = userEvent.setup()+ const { container } = mountEditor(buildEntry(), { galleryPhotos: [buildGalleryPhoto(200)] })++ await user.click(screen.getByRole('button', { name: 'From Gallery' }))+ expect(screen.getAllByAltText('')).toHaveLength(1)++ await user.click(screen.getByRole('button', { name: 'Upload photos' }))+ expect(screen.queryByAltText('')).not.toBeInTheDocument()++ fireEvent.change(container.querySelector('input[type="file"]') as HTMLInputElement, { target: { files: [] } })+ expect(container.querySelector('img[src="blob:preview"]')).not.toBeInTheDocument()+ })++ it('FE-JRN-EDITOR-024: falls back to today and an empty strip when the entry carries neither', () => {+ const { container } = mountEditor(buildEntry({+ entry_date: '', photos: undefined as unknown as JourneyPhoto[],+ }))++ const today = new Date().toISOString().split('T')[0]+ const label = new Date(today + 'T00:00:00').toLocaleDateString(undefined, {+ month: 'short', day: 'numeric', year: 'numeric',+ })+ expect(screen.getByText(label)).toBeInTheDocument()+ expect(container.querySelector('.w-20.h-20')).not.toBeInTheDocument()+ })++ it('FE-JRN-EDITOR-025: skips the photo upload when the save does not yield an entry id', async () => {+ const user = userEvent.setup()+ const { container, onSave, onUploadPhotos, onDone } = mountEditor(buildEntry())+ onSave.mockResolvedValueOnce(0)++ fireEvent.change(container.querySelector('input[type="file"]') as HTMLInputElement, {+ target: { files: [new File(['a'], 'a.jpg', { type: 'image/jpeg' })] },+ })+ await waitFor(() => expect(container.querySelector('img[src="blob:preview"]')).toBeInTheDocument())+ await user.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => expect(onDone).toHaveBeenCalledTimes(1))+ expect(onUploadPhotos).not.toHaveBeenCalled()+ })++ it('FE-JRN-EDITOR-026: leaves a skeleton without any content a skeleton', async () => {+ const user = userEvent.setup()+ const { onSave } = mountEditor(buildEntry({ id: 21, type: 'skeleton', title: 'Venice' }))++ await user.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => expect(onSave).toHaveBeenCalled())+ expect(onSave.mock.calls[0][0]).toMatchObject({ type: undefined })+ })++ it('FE-JRN-EDITOR-027: removes a con row again', async () => {+ const user = userEvent.setup()+ const { onSave } = mountEditor(buildEntry({+ id: 10, pros_cons: { pros: ['Food'], cons: ['Queues', 'Heat'] },+ }))++ const row = screen.getByDisplayValue('Heat').parentElement as HTMLElement+ await user.click(row.querySelector('button') as HTMLElement)+ expect(screen.queryByDisplayValue('Heat')).not.toBeInTheDocument()++ await user.click(screen.getByRole('button', { name: 'Save' }))+ await waitFor(() => expect(onSave).toHaveBeenCalled())+ expect(onSave.mock.calls[0][0]).toMatchObject({ pros_cons: { pros: ['Food'], cons: ['Queues'] } })+ })++ it('FE-JRN-EDITOR-028: a broken thumbnail retries once against the original size', async () => {+ const user = userEvent.setup()+ const { container } = mountEditor(+ buildEntry({ id: 10, photos: [buildPhoto(100)] }),+ { galleryPhotos: [buildGalleryPhoto(200)] },+ )++ await user.click(screen.getByRole('button', { name: 'From Gallery' }))+ const galleryImg = container.querySelector('img[src="/api/photos/200/thumbnail"]') as HTMLImageElement+ fireEvent.error(galleryImg)+ expect(galleryImg.getAttribute('src')).toBe('/api/photos/200/original')+ // A second failure must not loop back onto the thumbnail.+ fireEvent.error(galleryImg)+ expect(galleryImg.getAttribute('src')).toBe('/api/photos/200/original')++ const stripImg = container.querySelector('img[src="/api/photos/100/thumbnail"]') as HTMLImageElement+ fireEvent.error(stripImg)+ expect(stripImg.getAttribute('src')).toBe('/api/photos/100/original')+ })++ it('FE-JRN-EDITOR-029: reorders photos locally even when persisting the order fails', async () => {+ let attempts = 0+ server.use(http.patch('/api/journeys/photos/:id', () => {+ attempts += 1+ return new HttpResponse(null, { status: 500 })+ }))+ const user = userEvent.setup()+ const { container } = mountEditor(buildEntry({ id: 10, photos: [buildPhoto(100), buildPhoto(101)] }))++ await user.click(screen.getByRole('button', { name: 'Make 1st' }))++ await waitFor(() => expect(attempts).toBe(2))+ const order = Array.from(container.querySelectorAll('.w-20.h-20 img')).map(i => i.getAttribute('src'))+ expect(order).toEqual(['/api/photos/101/thumbnail', '/api/photos/100/thumbnail'])+ })++ it('FE-JRN-EDITOR-030: dropping an unsaved gallery pick cancels its link', async () => {+ const linked: string[] = []+ server.use(http.post('/api/journeys/entries/55/link-photo', async ({ request }) => {+ linked.push(JSON.stringify(await request.json()))+ return HttpResponse.json({ id: 200 })+ }))+ const user = userEvent.setup()+ const { container, onDone } = mountEditor(buildEntry(), { galleryPhotos: [buildGalleryPhoto(200)] })++ await user.click(screen.getByRole('button', { name: 'From Gallery' }))+ await user.click(screen.getAllByAltText('')[0])+ await screen.findByText('All photos already added')++ const tile = container.querySelector('.w-20.h-20') as HTMLElement+ await user.click(tile.querySelector('button') as HTMLElement)+ await user.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => expect(onDone).toHaveBeenCalledTimes(1))+ expect(linked).toEqual([])+ })++ it('FE-JRN-EDITOR-031: keeps a gallery photo in the picker when linking it fails', async () => {+ let attempts = 0+ server.use(http.post('/api/journeys/entries/10/link-photo', () => {+ attempts += 1+ return new HttpResponse(null, { status: 500 })+ }))+ const user = userEvent.setup()+ mountEditor(buildEntry({ id: 10 }), { galleryPhotos: [buildGalleryPhoto(200)] })++ await user.click(screen.getByRole('button', { name: 'From Gallery' }))+ await user.click(screen.getAllByAltText('')[0])++ await waitFor(() => expect(attempts).toBe(1))+ expect(screen.queryByText('All photos already added')).not.toBeInTheDocument()+ expect(screen.getAllByAltText('')).toHaveLength(1)+ })++ it('FE-JRN-EDITOR-032: only offers enabled and connected photo providers', async () => {+ server.use(+ http.get('/api/addons', () => HttpResponse.json({+ addons: [+ { id: 'immich', name: 'Immich', type: 'photo_provider', icon: 'camera', enabled: true },+ { id: 'photoprism', name: 'PhotoPrism', type: 'photo_provider', icon: 'camera', enabled: true },+ { id: 'nas', name: 'NAS', type: 'photo_provider', icon: 'camera', enabled: false },+ { id: 'offline', name: 'Offline', type: 'photo_provider', icon: 'camera', enabled: true },+ { id: 'broken', name: 'Broken', type: 'photo_provider', icon: 'camera', enabled: true },+ { id: 'budget', name: 'Budget', type: 'feature', icon: 'wallet', enabled: true },+ ],+ })),+ http.get('/api/integrations/memories/immich/status', () => HttpResponse.json({ connected: true })),+ http.get('/api/integrations/memories/photoprism/status', () => HttpResponse.json({ connected: true })),+ http.get('/api/integrations/memories/offline/status', () => HttpResponse.json({ connected: false })),+ http.get('/api/integrations/memories/broken/status', () => HttpResponse.error()),+ http.post('/api/integrations/memories/immich/search', () => HttpResponse.json({+ assets: [{ id: 'asset-1', takenAt: '2026-03-15T09:00:00.000Z', mediaType: 'image' }],+ hasMore: false,+ })),+ http.post('/api/integrations/memories/photoprism/search', () => HttpResponse.json({ assets: [], hasMore: false })),+ )+ const user = userEvent.setup()+ mountEditor(buildEntry({ id: 10 }))++ await user.click(screen.getByRole('button', { name: 'External photos' }))++ expect(await screen.findByTestId('journey-external-provider-immich')).toBeInTheDocument()+ expect(screen.getByTestId('journey-external-provider-photoprism')).toBeInTheDocument()+ expect(screen.queryByTestId('journey-external-provider-nas')).not.toBeInTheDocument()+ expect(screen.queryByTestId('journey-external-provider-offline')).not.toBeInTheDocument()+ expect(screen.queryByTestId('journey-external-provider-broken')).not.toBeInTheDocument()++ // Queue a photo from the first provider, then switch tabs.+ await user.click(await screen.findByAltText(''))+ await user.click(screen.getByRole('button', { name: 'Add (1)' }))+ await screen.findByRole('button', { name: /1 queued · Clear/ })++ await user.click(screen.getByTestId('journey-external-provider-photoprism'))+ expect(screen.getByTestId('journey-external-provider-photoprism').className).toContain('bg-zinc-900')++ // The picker's own cancel drops back to the first available provider.+ await user.click(screen.getAllByRole('button', { name: 'Cancel' })[0])+ expect(screen.getByTestId('journey-external-provider-photoprism').className).not.toContain('bg-zinc-900')+ expect(screen.getByRole('button', { name: /1 queued · Clear/ })).toBeInTheDocument()+ })++ it('FE-JRN-EDITOR-033: merges a second pick into the already queued group', async () => {+ server.use(+ http.get('/api/addons', () => HttpResponse.json({+ addons: [{ id: 'immich', name: 'Immich', type: 'photo_provider', icon: 'camera', enabled: true }],+ })),+ http.get('/api/integrations/memories/immich/status', () => HttpResponse.json({ connected: true })),+ http.post('/api/integrations/memories/immich/search', () => HttpResponse.json({+ assets: [+ { id: 'asset-1', takenAt: '2026-03-15T09:00:00.000Z', mediaType: 'image' },+ { id: 'asset-2', takenAt: '2026-03-15T10:00:00.000Z', mediaType: 'video' },+ ],+ hasMore: false,+ })),+ )+ const user = userEvent.setup()+ const { onAddProviderPhotos, onDone } = mountEditor(buildEntry({ id: 10 }))++ await user.click(screen.getByRole('button', { name: 'External photos' }))+ const tiles = await screen.findAllByAltText('')+ const assetIdOf = (img: HTMLElement) => img.getAttribute('src')!.split('/assets/0/')[1].split('/')[0]+ const firstId = assetIdOf(tiles[0])++ await user.click(tiles[0])+ await user.click(screen.getByRole('button', { name: 'Add (1)' }))+ await screen.findByRole('button', { name: /1 queued · Clear/ })++ // The first asset stays selected but is now greyed out, so the second Add+ // re-sends it and the merge has to skip the duplicate.+ const remaining = screen.getAllByAltText('').find(img => !img.parentElement!.className.includes('opacity-40'))!+ const secondId = assetIdOf(remaining)+ await user.click(remaining)+ await user.click(screen.getByRole('button', { name: 'Add (2)' }))+ expect(await screen.findByRole('button', { name: /2 queued · Clear/ })).toBeInTheDocument()++ await user.click(screen.getByRole('button', { name: 'Save' }))+ await waitFor(() => expect(onDone).toHaveBeenCalledTimes(1))+ expect(onAddProviderPhotos).toHaveBeenCalledTimes(1)+ expect(onAddProviderPhotos).toHaveBeenCalledWith(55, expect.objectContaining({+ provider: 'immich',+ assetIds: [firstId, secondId],+ }))+ })++ it('FE-JRN-EDITOR-034: greys out provider assets already linked to the entry', async () => {+ useConnectedImmich()+ const user = userEvent.setup()+ mountEditor(buildEntry({+ id: 10,+ photos: [{ ...buildPhoto(100), provider: 'immich', asset_id: 'asset-1' }],+ }))++ await user.click(screen.getByRole('button', { name: 'External photos' }))+ await screen.findByTestId('journey-external-provider-immich')++ await waitFor(() => expect(document.querySelector('.opacity-40')).toBeInTheDocument())+ expect(screen.queryByRole('button', { name: /Select all/ })).not.toBeInTheDocument()+ })++ it('FE-JRN-EDITOR-035: falls back to the day-wide provider search without a place name', async () => {+ useConnectedImmich()+ const user = userEvent.setup()+ mountEditor(buildEntry({ id: 10, location_lat: 41.9, location_lng: 12.5 }))++ await user.click(screen.getByRole('button', { name: 'External photos' }))++ expect(await screen.findByText('All photos from this day')).toBeInTheDocument()+ })++ it('FE-JRN-EDITOR-036: shows the upload progress while photos are in flight', async () => {+ const user = userEvent.setup()+ const { container, onUploadPhotos, onDone } = mountEditor(buildEntry())+ let release: (r: ResilientResult<JourneyPhoto>) => void = () => {}+ onUploadPhotos.mockImplementationOnce((_entryId, files, cbs) =>+ new Promise<ResilientResult<JourneyPhoto>>(resolve => {+ cbs?.onProgress?.({ done: 1, total: files.length, failed: 0, percent: 50 })+ release = resolve+ }))++ fireEvent.change(container.querySelector('input[type="file"]') as HTMLInputElement, {+ target: { files: [new File(['a'], 'a.jpg', { type: 'image/jpeg' })] },+ })+ await waitFor(() => expect(container.querySelector('img[src="blob:preview"]')).toBeInTheDocument())+ await user.click(screen.getByRole('button', { name: 'Save' }))++ expect(await screen.findByText('Uploading 1/1…')).toBeInTheDocument()+ release({ succeeded: [], failed: [] })+ await waitFor(() => expect(onDone).toHaveBeenCalledTimes(1))+ })++ it('FE-JRN-EDITOR-037: a fresh keystroke cancels the pending search and an empty payload yields nothing', async () => {+ let calls = 0+ server.use(http.post('/api/maps/search', () => {+ calls += 1+ return HttpResponse.json({})+ }))+ mountEditor(buildEntry({ id: 10 }))+ const input = screen.getByPlaceholderText('Search location...')++ fireEvent.focus(input)+ fireEvent.change(input, { target: { value: 'Ro' } })+ fireEvent.change(input, { target: { value: 'Rom' } })++ await waitFor(() => expect(calls).toBe(1), { timeout: 3000 })+ await waitFor(() => expect(screen.queryByText('Searching...')).not.toBeInTheDocument())+ expect(screen.getByDisplayValue('Rom')).toBeInTheDocument()+ })++ it('FE-JRN-EDITOR-038: shows a searching hint while the location lookup runs', async () => {+ server.use(http.post('/api/maps/search', async () => {+ await delay(200)+ return HttpResponse.json({ places: [{ name: 'Roma Termini', lat: 41.9, lng: 12.5 }] })+ }))+ mountEditor(buildEntry({ id: 10 }))++ fireEvent.change(screen.getByPlaceholderText('Search location...'), { target: { value: 'Roma' } })++ expect(await screen.findByText('Searching...', {}, { timeout: 3000 })).toBeInTheDocument()+ expect(await screen.findByText('Roma Termini', {}, { timeout: 3000 })).toBeInTheDocument()+ })++ it('FE-JRN-EDITOR-039: highlights the picked mood with its own palette', async () => {+ const user = userEvent.setup()+ mountEditor(buildEntry({ id: 10 }))++ const amazing = screen.getByRole('button', { name: 'Amazing' })+ expect(amazing.getAttribute('style')).toBeNull()++ await user.click(amazing)+ expect(amazing.className).not.toContain('border-zinc-200')+ expect(amazing.getAttribute('style')).toBeTruthy()+ })+})diff --git a/client/src/components/Journey/JourneyDetailPageGalleryView.test.tsx b/client/src/components/Journey/JourneyDetailPageGalleryView.test.tsxnew file mode 100644index 000000000..42b35bc94--- /dev/null+++ b/client/src/components/Journey/JourneyDetailPageGalleryView.test.tsx@@ -0,0 +1,306 @@+// FE-JRN-GALLERY-001 to FE-JRN-GALLERY-016++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { http, HttpResponse } from 'msw'+import userEvent from '@testing-library/user-event'+import { render, screen, waitFor, fireEvent } from '../../../tests/helpers/render'+import { server } from '../../../tests/helpers/msw/server'+import { useJourneyStore, type GalleryPhoto, type JourneyEntry, type JourneyTrip } from '../../store/journeyStore'+import type { UploadProgress } from '../../utils/uploadQueue'+import { GalleryView } from './JourneyDetailPageGalleryView'++type ToastKind = 'success' | 'error' | 'warning' | 'info'++const toastSpy = vi.fn((_message: string, _type?: ToastKind, _duration?: number) => 0)++const uploadGalleryPhotos = vi.fn(+ async (_journeyId: number, files: File[], cbs?: { onProgress?: (p: UploadProgress) => void }) => {+ cbs?.onProgress?.({ done: files.length, total: files.length, failed: 0, percent: 100 })+ return { succeeded: [], failed: [] as File[] }+ },+)++const JOURNEY_ID = 9++function buildGalleryPhoto(overrides: Partial<GalleryPhoto> = {}): GalleryPhoto {+ return {+ id: 100,+ journey_id: JOURNEY_ID,+ photo_id: 100,+ caption: null,+ shared: 1,+ sort_order: 0,+ created_at: 0,+ provider: 'local',+ ...overrides,+ }+}++const trips: JourneyTrip[] = [+ { trip_id: 5, added_at: 0, title: 'Italy Trip', start_date: '2026-03-14', end_date: '2026-03-20', place_count: 3 },+]++const entries: JourneyEntry[] = [+ {+ id: 10, journey_id: JOURNEY_ID, author_id: 1, type: 'entry', entry_date: '2026-03-15',+ title: 'Arrived in Rome', visibility: 'private', sort_order: 0, photos: [], created_at: 0, updated_at: 0,+ },+]++function mountGallery(gallery: GalleryPhoto[], onRegisterUpload?: (fn: () => void) => void) {+ const onPhotoClick = vi.fn()+ const onRefresh = vi.fn()+ const utils = render(+ <GalleryView+ entries={entries}+ gallery={gallery}+ journeyId={JOURNEY_ID}+ userId={1}+ trips={trips}+ onPhotoClick={onPhotoClick}+ onRefresh={onRefresh}+ onRegisterUpload={onRegisterUpload}+ />,+ )+ return { ...utils, onPhotoClick, onRefresh }+}++function useConnectedImmich() {+ server.use(+ http.get('/api/addons', () => HttpResponse.json({+ addons: [+ { id: 'immich', name: 'Immich', type: 'photo_provider', icon: 'camera', enabled: true },+ { id: 'synologyphotos', name: 'Synology Photos', type: 'photo_provider', icon: 'camera', enabled: false },+ { id: 'vacay', name: 'Vacay', type: 'feature', icon: 'calendar', enabled: true },+ ],+ })),+ http.get('/api/integrations/memories/immich/status', () => HttpResponse.json({ connected: true })),+ http.post('/api/integrations/memories/immich/search', () => HttpResponse.json({+ assets: [{ id: 'asset-1', takenAt: '2026-03-15T10:00:00.000Z', mediaType: 'image' }],+ hasMore: false,+ })),+ )+}++beforeEach(() => {+ toastSpy.mockClear()+ uploadGalleryPhotos.mockClear()+ window.__addToast = toastSpy+ useJourneyStore.setState({ current: null, uploadGalleryPhotos })+})++afterEach(() => {+ delete window.__addToast+})++describe('GalleryView', () => {+ it('FE-JRN-GALLERY-001: shows the mascot empty state when the journey has no photos', async () => {+ const { container } = mountGallery([])++ expect(screen.getByText('No photos yet')).toBeInTheDocument()+ expect(container.querySelector('.trek--journey')).toBeInTheDocument()+ expect(screen.getByText('0 photos')).toBeInTheDocument()+ })++ it('FE-JRN-GALLERY-002: renders one tile per photo with the thumbnail URL', () => {+ const { container } = mountGallery([buildGalleryPhoto(), buildGalleryPhoto({ id: 101, photo_id: 101 })])++ expect(container.querySelector('img[src="/api/photos/100/thumbnail"]')).toBeInTheDocument()+ expect(container.querySelector('img[src="/api/photos/101/thumbnail"]')).toBeInTheDocument()+ expect(screen.getByText('2 photos')).toBeInTheDocument()+ })++ it('FE-JRN-GALLERY-003: forwards the clicked photo index to the parent', async () => {+ const user = userEvent.setup()+ const gallery = [buildGalleryPhoto(), buildGalleryPhoto({ id: 101, photo_id: 101 })]+ const { container, onPhotoClick } = mountGallery(gallery)++ await user.click(container.querySelector('img[src="/api/photos/101/thumbnail"]')!.parentElement as HTMLElement)++ expect(onPhotoClick).toHaveBeenCalledWith(gallery, 1)+ })++ it('FE-JRN-GALLERY-004: renders a neutral tile for a video without a poster', () => {+ const { container } = mountGallery([buildGalleryPhoto({ media_type: 'video', thumbnail_path: null })])++ expect(container.querySelector('img')).not.toBeInTheDocument()+ // Videos still get the play overlay.+ expect(container.querySelector('.lucide-play')).toBeInTheDocument()+ })++ it('FE-JRN-GALLERY-005: renders the poster for a video that has one', () => {+ const { container } = mountGallery([buildGalleryPhoto({ media_type: 'video', thumbnail_path: 'thumbs/a.jpg' })])++ expect(container.querySelector('img[src="/api/photos/100/thumbnail"]')).toBeInTheDocument()+ expect(container.querySelector('.lucide-play')).toBeInTheDocument()+ })++ it('FE-JRN-GALLERY-006: labels provider-backed photos and shows their caption', () => {+ mountGallery([+ buildGalleryPhoto({ id: 101, photo_id: 101, provider: 'immich', caption: 'Colosseum' }),+ buildGalleryPhoto({ id: 102, photo_id: 102, provider: 'synologyphotos' }),+ buildGalleryPhoto({ id: 103, photo_id: 103, provider: 'nextcloud' }),+ buildGalleryPhoto({ id: 104, photo_id: 104, provider: 'local' }),+ ])++ expect(screen.getByText('Immich')).toBeInTheDocument()+ expect(screen.getByText('Synology Photos')).toBeInTheDocument()+ expect(screen.getByText('nextcloud')).toBeInTheDocument()+ expect(screen.getByText('Colosseum')).toBeInTheDocument()+ })++ it('FE-JRN-GALLERY-007: removes a deleted photo from the store optimistically', async () => {+ let deleted = false+ server.use(http.delete('/api/journeys/9/gallery/100', () => {+ deleted = true+ return HttpResponse.json({ ok: true })+ }))+ const photo = buildGalleryPhoto()+ useJourneyStore.setState({+ current: {+ id: JOURNEY_ID, user_id: 1, title: 'Italy', status: 'active', created_at: 0, updated_at: 0,+ entries: [{ ...entries[0], photos: [{ id: 100, entry_id: 10, photo_id: 100, sort_order: 0, shared: 1, created_at: 0 }] }],+ gallery: [photo], trips, contributors: [], stats: { entries: 1, photos: 1, places: 0 },+ },+ })+ const user = userEvent.setup()+ const { container, onRefresh } = mountGallery([photo])++ await user.click(container.querySelectorAll('button')[0])++ await waitFor(() => expect(deleted).toBe(true))+ const current = useJourneyStore.getState().current!+ expect(current.gallery).toHaveLength(0)+ expect(current.entries[0].photos).toHaveLength(0)+ expect(onRefresh).not.toHaveBeenCalled()+ })++ it('FE-JRN-GALLERY-008: reports a failed delete and asks the parent to refetch', async () => {+ server.use(http.delete('/api/journeys/9/gallery/100', () => new HttpResponse(null, { status: 500 })))+ const photo = buildGalleryPhoto()+ useJourneyStore.setState({+ current: {+ id: JOURNEY_ID, user_id: 1, title: 'Italy', status: 'active', created_at: 0, updated_at: 0,+ entries: [], gallery: [photo], trips, contributors: [], stats: { entries: 0, photos: 1, places: 0 },+ },+ })+ const user = userEvent.setup()+ const { container, onRefresh } = mountGallery([photo])++ await user.click(container.querySelectorAll('button')[0])++ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Error', 'error', undefined))+ expect(onRefresh).toHaveBeenCalledTimes(1)+ })++ it('FE-JRN-GALLERY-009: ignores a delete while no journey is loaded', async () => {+ let deleted = false+ server.use(http.delete('/api/journeys/9/gallery/100', () => {+ deleted = true+ return HttpResponse.json({ ok: true })+ }))+ const user = userEvent.setup()+ const { container } = mountGallery([buildGalleryPhoto()])++ await user.click(container.querySelectorAll('button')[0])++ expect(deleted).toBe(false)+ })++ it('FE-JRN-GALLERY-010: only offers providers that are enabled and connected', async () => {+ useConnectedImmich()+ mountGallery([])++ expect(await screen.findByRole('button', { name: 'Immich' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Synology Photos' })).not.toBeInTheDocument()+ })++ it('FE-JRN-GALLERY-011: offers no providers when the status probe fails', async () => {+ server.use(+ http.get('/api/addons', () => HttpResponse.json({+ addons: [{ id: 'immich', name: 'Immich', type: 'photo_provider', icon: 'camera', enabled: true }],+ })),+ http.get('/api/integrations/memories/immich/status', () => new HttpResponse(null, { status: 401 })),+ )+ mountGallery([])++ await waitFor(() => expect(screen.getByText('No photos yet')).toBeInTheDocument())+ expect(screen.queryByRole('button', { name: 'Immich' })).not.toBeInTheDocument()+ })++ it('FE-JRN-GALLERY-012: adds picked provider photos to the gallery', async () => {+ useConnectedImmich()+ const bodies: Record<string, unknown>[] = []+ server.use(http.post('/api/journeys/9/gallery/provider-photos', async ({ request }) => {+ bodies.push(await request.json() as Record<string, unknown>)+ return HttpResponse.json({ added: 1 })+ }))+ const user = userEvent.setup()+ const { onRefresh } = mountGallery([])++ await user.click(await screen.findByRole('button', { name: 'Immich' }))+ await user.click(await screen.findByAltText(''))+ await user.click(screen.getByRole('button', { name: 'Add (1)' }))++ await waitFor(() => expect(onRefresh).toHaveBeenCalledTimes(1))+ expect(bodies[0]).toEqual({ provider: 'immich', asset_ids: ['asset-1'], media_types: ['image'] })+ expect(toastSpy).toHaveBeenCalledWith('1 photos added', 'success', undefined)+ expect(screen.queryByRole('heading', { name: 'Immich' })).not.toBeInTheDocument()+ })++ it('FE-JRN-GALLERY-013: reports when adding provider photos fails', async () => {+ useConnectedImmich()+ server.use(http.post('/api/journeys/9/gallery/provider-photos', () => new HttpResponse(null, { status: 500 })))+ const user = userEvent.setup()+ const { onRefresh } = mountGallery([])++ await user.click(await screen.findByRole('button', { name: 'Immich' }))+ await user.click(await screen.findByAltText(''))+ await user.click(screen.getByRole('button', { name: 'Add (1)' }))++ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Error', 'error', undefined))+ expect(onRefresh).not.toHaveBeenCalled()+ })++ it('FE-JRN-GALLERY-014: uploads picked files and refreshes on success', async () => {+ let registered: (() => void) | null = null+ const { container, onRefresh } = mountGallery([], fn => { registered = fn })++ expect(registered).toBeTypeOf('function')+ const input = container.querySelector('input[type="file"]') as HTMLInputElement+ fireEvent.change(input, { target: { files: [new File(['a'], 'a.jpg', { type: 'image/jpeg' })] } })++ await waitFor(() => expect(onRefresh).toHaveBeenCalledTimes(1))+ expect(uploadGalleryPhotos).toHaveBeenCalledTimes(1)+ expect(toastSpy).toHaveBeenCalledWith('1 photos uploaded', 'success', undefined)+ expect(input.value).toBe('')+ })++ it('FE-JRN-GALLERY-015: reports partially failed uploads but still refreshes', async () => {+ const failedFile = new File(['b'], 'b.jpg', { type: 'image/jpeg' })+ uploadGalleryPhotos.mockResolvedValueOnce({ succeeded: [], failed: [failedFile] })+ const { container, onRefresh } = mountGallery([])++ const input = container.querySelector('input[type="file"]') as HTMLInputElement+ fireEvent.change(input, { target: { files: [failedFile] } })++ await waitFor(() => {+ expect(toastSpy).toHaveBeenCalledWith('1 of 1 photos failed — save again to retry', 'error', undefined)+ })+ expect(onRefresh).toHaveBeenCalledTimes(1)+ })++ it('FE-JRN-GALLERY-016: reports a rejected upload and ignores an empty selection', async () => {+ uploadGalleryPhotos.mockRejectedValueOnce({ code: 'ERR_NETWORK' })+ const { container, onRefresh } = mountGallery([])+ const input = container.querySelector('input[type="file"]') as HTMLInputElement++ fireEvent.change(input, { target: { files: [] } })+ expect(uploadGalleryPhotos).not.toHaveBeenCalled()++ fireEvent.change(input, { target: { files: [new File(['c'], 'c.jpg', { type: 'image/jpeg' })] } })++ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Some photos failed to upload', 'error', undefined))+ expect(onRefresh).not.toHaveBeenCalled()+ })+})diff --git a/client/src/components/Journey/JourneyDetailPageMapView.test.tsx b/client/src/components/Journey/JourneyDetailPageMapView.test.tsxnew file mode 100644index 000000000..85a848e37--- /dev/null+++ b/client/src/components/Journey/JourneyDetailPageMapView.test.tsx@@ -0,0 +1,175 @@+// FE-COMP-JMAPVIEW-001 to FE-COMP-JMAPVIEW-011++const lastMapProps = vi.hoisted(() => ({ current: {} as Record<string, unknown> }))++// The map renderer picks Leaflet or GL from the settings store and is covered+// by its own suites — here it is reduced to a props recorder.+vi.mock('./JourneyMapAuto', async () => {+ const React = await import('react')+ return {+ default: React.forwardRef(function MockJourneyMapAuto(+ props: Record<string, unknown>,+ _ref: React.ForwardedRef<unknown>,+ ) {+ lastMapProps.current = props+ return React.createElement('div', { 'data-testid': 'journey-map' })+ }),+ }+})++import { createRef } from 'react'+import { render, screen, fireEvent, within } from '../../../tests/helpers/render'+import { resetAllStores } from '../../../tests/helpers/store'+import { MapView } from './JourneyDetailPageMapView'+import type { JourneyMapAutoHandle } from './JourneyMapAuto'+import type { JourneyEntry } from '../../store/journeyStore'++function buildEntry(overrides: Record<string, unknown>): JourneyEntry {+ return {+ id: 1,+ journey_id: 1,+ author_id: 1,+ type: 'entry',+ title: 'Louvre',+ story: null,+ entry_date: '2025-06-01',+ entry_time: null,+ location_name: 'Paris, France',+ location_lat: 48.86,+ location_lng: 2.35,+ mood: null,+ weather: null,+ tags: [],+ pros_cons: null,+ visibility: 'private',+ sort_order: 0,+ photos: [],+ created_at: 0,+ updated_at: 0,+ ...overrides,+ } as unknown as JourneyEntry+}++const mapEntries = [+ buildEntry({ id: 1, title: 'Louvre', entry_date: '2025-06-01', entry_time: '09:00' }),+ buildEntry({ id: 2, title: 'Sacré-Cœur', entry_date: '2025-06-01', location_name: 'Montmartre, Paris, France' }),+ buildEntry({ id: 3, title: 'Museumsinsel', entry_date: '2025-06-02', location_name: 'Berlin, Germany', location_lat: 52.52, location_lng: 13.4 }),+]++const allEntries = [+ ...mapEntries,+ buildEntry({ id: 4, type: 'checkin', title: 'Checked in', entry_date: '2025-06-02' }),+]++function renderMapView(props: Partial<{+ entries: JourneyEntry[]+ mapEntries: JourneyEntry[]+ activeLocationId: string | null+ onLocationClick: (id: string) => void+}> = {}) {+ const onLocationClick = props.onLocationClick ?? vi.fn()+ const result = render(+ <MapView+ entries={props.entries ?? allEntries}+ mapEntries={props.mapEntries ?? mapEntries}+ sortedDates={['2025-06-01', '2025-06-02']}+ activeLocationId={props.activeLocationId ?? null}+ fullMapRef={createRef<JourneyMapAutoHandle>()}+ onLocationClick={onLocationClick}+ />,+ )+ return { ...result, onLocationClick }+}++beforeEach(() => {+ resetAllStores()+ vi.clearAllMocks()+})++describe('JourneyDetailPage MapView', () => {+ it('FE-COMP-JMAPVIEW-001: hands the located entries to the map as plain marker items', () => {+ renderMapView()+ expect(screen.getByTestId('journey-map')).toBeInTheDocument()+ expect(lastMapProps.current).toMatchObject({ height: 560, activeMarkerId: null })+ expect(lastMapProps.current.entries).toEqual([+ { id: '1', lat: 48.86, lng: 2.35, title: 'Louvre', mood: null, entry_date: '2025-06-01' },+ { id: '2', lat: 48.86, lng: 2.35, title: 'Sacré-Cœur', mood: null, entry_date: '2025-06-01' },+ { id: '3', lat: 52.52, lng: 13.4, title: 'Museumsinsel', mood: null, entry_date: '2025-06-02' },+ ])+ })++ it('FE-COMP-JMAPVIEW-002: the stats row counts places, days and stories', () => {+ renderMapView()+ const places = screen.getByText('Places').previousElementSibling+ const days = screen.getByText('Days').previousElementSibling+ const stories = screen.getByText('Stories').previousElementSibling+ expect(places).toHaveTextContent('3')+ expect(days).toHaveTextContent('2')+ // the check-in is not a story+ expect(stories).toHaveTextContent('3')+ })++ it('FE-COMP-JMAPVIEW-003: a journey with no located entries hides the stats row', () => {+ renderMapView({ mapEntries: [] })+ expect(screen.queryByText('Places')).not.toBeInTheDocument()+ expect(screen.queryByText('Day 1')).not.toBeInTheDocument()+ })++ it('FE-COMP-JMAPVIEW-004: entries are grouped under numbered day headers', () => {+ renderMapView()+ expect(screen.getByText('Day 1')).toBeInTheDocument()+ expect(screen.getByText('Day 2')).toBeInTheDocument()+ expect(screen.getByText('June 1')).toBeInTheDocument()+ expect(screen.getByText('June 2')).toBeInTheDocument()+ })++ it('FE-COMP-JMAPVIEW-005: each row is numbered by its position across the whole journey', () => {+ renderMapView()+ const berlin = screen.getByText('Museumsinsel').closest('div[class*="cursor-pointer"]')!+ expect(within(berlin as HTMLElement).getByText('3')).toBeInTheDocument()+ })++ it('FE-COMP-JMAPVIEW-006: the location line shortens the place and appends the time', () => {+ renderMapView()+ expect(screen.getByText('Paris, France · 09:00')).toBeInTheDocument()+ expect(screen.getByText('Montmartre, Paris, France')).toBeInTheDocument()+ })++ it('FE-COMP-JMAPVIEW-007: an entry without a title falls back to its location name', () => {+ renderMapView({+ mapEntries: [buildEntry({ id: 9, title: null, location_name: 'Reykjavík' })],+ })+ expect(screen.getAllByText('Reykjavík').length).toBeGreaterThan(0)+ })++ it('FE-COMP-JMAPVIEW-008: clicking a row reports the entry id', () => {+ const onLocationClick = vi.fn()+ renderMapView({ onLocationClick })++ fireEvent.click(screen.getByText('Sacré-Cœur'))++ expect(onLocationClick).toHaveBeenCalledWith('2')+ })++ it('FE-COMP-JMAPVIEW-009: the map reports marker clicks through the same handler', () => {+ const onLocationClick = vi.fn()+ renderMapView({ onLocationClick })+ expect(lastMapProps.current.onMarkerClick).toBe(onLocationClick)+ })++ it('FE-COMP-JMAPVIEW-010: the active row is outlined and forwarded to the map', () => {+ renderMapView({ activeLocationId: '2' })+ expect(lastMapProps.current.activeMarkerId).toBe('2')++ const row = screen.getByText('Sacré-Cœur').closest('div[class*="cursor-pointer"]') as HTMLElement+ expect(row.className).toContain('border-zinc-900')+ const inactive = screen.getByText('Louvre').closest('div[class*="cursor-pointer"]') as HTMLElement+ expect(inactive.className).toContain('border-zinc-200')+ })++ it('FE-COMP-JMAPVIEW-011: connectors sit between same-day rows, never after the last one', () => {+ const { container } = renderMapView()+ // day 1 has two rows (one connector), day 2 has a single row (none)+ expect(container.querySelectorAll('.w-0\\.5')).toHaveLength(1)+ })+})diff --git a/client/src/components/Journey/JourneyDetailPageProviderPicker.test.tsx b/client/src/components/Journey/JourneyDetailPageProviderPicker.test.tsxnew file mode 100644index 000000000..ed202c6e4--- /dev/null+++ b/client/src/components/Journey/JourneyDetailPageProviderPicker.test.tsx@@ -0,0 +1,340 @@+// FE-JRN-PICKER-001 to FE-JRN-PICKER-020++import { describe, it, expect, beforeEach, vi } from 'vitest'+import { http, HttpResponse, delay } from 'msw'+import userEvent from '@testing-library/user-event'+import { render, screen, waitFor, within, fireEvent } from '../../../tests/helpers/render'+import { server } from '../../../tests/helpers/msw/server'+import type { JourneyEntry, JourneyTrip } from '../../store/journeyStore'+import { ProviderPicker } from './JourneyDetailPageProviderPicker'++const trips: JourneyTrip[] = [+ { trip_id: 5, added_at: 0, title: 'Italy Trip', start_date: '2026-03-14', end_date: '2026-03-20', place_count: 3 },+ { trip_id: 6, added_at: 0, title: 'Side Trip', start_date: '2026-03-16', end_date: '2026-03-18', place_count: 1 },+]++function buildEntry(overrides: Partial<JourneyEntry> = {}): JourneyEntry {+ return {+ id: 10, journey_id: 1, author_id: 1, type: 'entry', entry_date: '2026-03-15',+ title: 'Arrived in Rome', visibility: 'private', sort_order: 0, photos: [], created_at: 0, updated_at: 0,+ ...overrides,+ }+}++const entries = [+ buildEntry(),+ buildEntry({ id: 11, title: 'Gallery' }),+ buildEntry({ id: 12, title: null, location_name: 'Florence' }),+ buildEntry({ id: 13, type: 'skeleton', title: 'Skipped' }),+]++const asset = (id: string, extra: Record<string, unknown> = {}) => ({+ id, takenAt: '2026-03-15T10:00:00.000Z', mediaType: 'image', ...extra,+})++function searchReturns(assets: Record<string, unknown>[], hasMore = false) {+ server.use(http.post('/api/integrations/memories/immich/search', () => HttpResponse.json({ assets, hasMore })))+}++function mountPicker(props: Partial<React.ComponentProps<typeof ProviderPicker>> = {}) {+ const onClose = vi.fn()+ const onAdd = vi.fn(async () => {})+ const utils = render(+ <ProviderPicker+ provider="immich"+ userId={42}+ entries={entries}+ trips={trips}+ existingAssetIds={new Set<string>()}+ onClose={onClose}+ onAdd={onAdd}+ {...props}+ />,+ )+ return { ...utils, onClose, onAdd }+}++beforeEach(() => {+ searchReturns([asset('a1')])+})++describe('ProviderPicker', () => {+ it('FE-JRN-PICKER-001: opens on the trip period and groups the photos by date', async () => {+ mountPicker()++ expect(await screen.findByText('March 15, 2026')).toBeInTheDocument()+ expect(screen.getByRole('heading', { name: 'Immich' })).toBeInTheDocument()+ // The trip range spans the union of all linked trips.+ expect(screen.getByText('Mar 14')).toBeInTheDocument()+ expect(screen.getByText('Mar 20, 2026')).toBeInTheDocument()+ expect(screen.getByText('(7 days)')).toBeInTheDocument()+ })++ it('FE-JRN-PICKER-002: names the other provider in the header', () => {+ mountPicker({ provider: 'synologyphotos' })++ expect(screen.getByRole('heading', { name: 'Synology Photos' })).toBeInTheDocument()+ })++ it('FE-JRN-PICKER-003: explains that no trip is linked when the range is empty', async () => {+ mountPicker({ trips: [] })++ await waitFor(() => expect(screen.getAllByText('No trips linked').length).toBe(2))+ })++ it('FE-JRN-PICKER-004: adds a day tab and preselects it when an initial date is given', async () => {+ mountPicker({ initialDate: '2026-03-15', contextLocation: { lat: 41.9, lng: 12.5, name: 'Rome' } })++ expect(await screen.findByText('Sunday, March 15, 2026')).toBeInTheDocument()+ expect(screen.getByText('· near Rome')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'This day' }).className).toContain('bg-zinc-900')+ })++ it('FE-JRN-PICKER-005: the all-photos tab searches without a date range', async () => {+ const ranges: Record<string, unknown>[] = []+ server.use(http.post('/api/integrations/memories/immich/search', async ({ request }) => {+ ranges.push(await request.json() as Record<string, unknown>)+ return HttpResponse.json({ assets: [asset('a1')], hasMore: false })+ }))+ const user = userEvent.setup()+ mountPicker()+ await screen.findByText('March 15, 2026')++ await user.click(screen.getByRole('button', { name: /All Photos/ }))++ await waitFor(() => expect(ranges).toHaveLength(2))+ expect(ranges[1]).toEqual({ from: '', to: '', page: 1, size: 50 })+ })++ it('FE-JRN-PICKER-006: the album tab loads albums and reports when there are none', async () => {+ server.use(http.get('/api/integrations/memories/immich/albums', () => HttpResponse.json({ albums: [] })))+ const user = userEvent.setup()+ mountPicker()+ await screen.findByText('March 15, 2026')++ await user.click(screen.getByRole('button', { name: 'Albums' }))++ expect(await screen.findByText('No albums found')).toBeInTheDocument()+ })++ it('FE-JRN-PICKER-007: picking an album loads its photos with the album passphrase', async () => {+ const requested: string[] = []+ server.use(+ http.get('/api/integrations/memories/immich/albums', () => HttpResponse.json({+ albums: [{ id: 'alb1', albumName: 'Rome', assetCount: 2, passphrase: 'pw 1' }],+ })),+ http.get('/api/integrations/memories/immich/albums/alb1/photos', ({ request }) => {+ requested.push(new URL(request.url).searchParams.get('passphrase') ?? '')+ return HttpResponse.json({ assets: [asset('alb-a1')] })+ }),+ )+ const user = userEvent.setup()+ mountPicker()+ await screen.findByText('March 15, 2026')++ await user.click(screen.getByRole('button', { name: 'Albums' }))+ await user.click(await screen.findByRole('button', { name: 'Rome (2)' }))++ await waitFor(() => expect(requested).toEqual(['pw 1']))+ const thumb = await screen.findByAltText('')+ expect(thumb.getAttribute('src')).toContain('passphrase=pw%201')+ })++ it('FE-JRN-PICKER-008: selects and deselects every selectable asset at once', async () => {+ searchReturns([asset('a1'), asset('a2'), asset('a3')])+ const user = userEvent.setup()+ mountPicker({ existingAssetIds: new Set(['a3']) })++ const selectAll = await screen.findByRole('button', { name: /Select all \(2\)/ })+ await user.click(selectAll)++ expect(screen.getByRole('button', { name: 'Add (2)' })).toBeEnabled()+ await user.click(screen.getByRole('button', { name: /Deselect all \(2\)/ }))+ expect(screen.getByRole('button', { name: 'Add' })).toBeDisabled()+ })++ it('FE-JRN-PICKER-009: hides the select-all bar when every asset was already added', async () => {+ searchReturns([asset('a1')])+ mountPicker({ existingAssetIds: new Set(['a1']) })++ await screen.findByText('March 15, 2026')+ expect(screen.queryByRole('button', { name: /Select all/ })).not.toBeInTheDocument()+ })++ it('FE-JRN-PICKER-010: toggles a single asset on and off', async () => {+ searchReturns([asset('a1'), asset('a2')])+ const user = userEvent.setup()+ mountPicker()++ const tiles = await screen.findAllByAltText('')+ await user.click(tiles[0])+ expect(screen.getByRole('button', { name: 'Add (1)' })).toBeInTheDocument()++ await user.click(tiles[0])+ expect(screen.getByRole('button', { name: 'Add' })).toBeDisabled()+ })++ it('FE-JRN-PICKER-011: ignores clicks on assets that are already in the journey', async () => {+ searchReturns([asset('a1'), asset('a2')])+ const user = userEvent.setup()+ mountPicker({ existingAssetIds: new Set(['a1']) })++ const tiles = await screen.findAllByAltText('')+ await user.click(tiles[0])++ expect(screen.getByRole('button', { name: 'Add' })).toBeDisabled()+ })++ it('FE-JRN-PICKER-012: submits the selection grouped by passphrase with media types', async () => {+ searchReturns([asset('a1'), asset('a2', { mediaType: 'video' })])+ const user = userEvent.setup()+ const { onAdd } = mountPicker()++ const tiles = await screen.findAllByAltText('')+ await user.click(tiles[0])+ await user.click(tiles[1])+ await user.click(screen.getByRole('button', { name: 'Add (2)' }))++ expect(onAdd).toHaveBeenCalledWith(+ [{ assetIds: ['a1', 'a2'], mediaTypes: ['image', 'video'], passphrase: undefined }],+ null,+ )+ })++ it('FE-JRN-PICKER-013: retargets the upload to a journal entry via the add-to menu', async () => {+ const user = userEvent.setup()+ const { onAdd } = mountPicker()++ const tiles = await screen.findAllByAltText('')+ await user.click(tiles[0])+ await user.click(screen.getByRole('button', { name: /New Gallery/ }))++ // Skeletons and the reserved gallery entries never appear as targets.+ expect(screen.queryByRole('button', { name: 'Skipped' })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Gallery' })).not.toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: 'Arrived in Rome' }))++ await user.click(screen.getByRole('button', { name: 'Add (1)' }))+ expect(onAdd).toHaveBeenCalledWith([{ assetIds: ['a1'], mediaTypes: ['image'], passphrase: undefined }], 10)+ })++ it('FE-JRN-PICKER-014: falls back to the location name for untitled entries and back to the gallery', async () => {+ const user = userEvent.setup()+ const { onAdd } = mountPicker({ initialEntryId: 10 })++ const tiles = await screen.findAllByAltText('')+ await user.click(tiles[0])+ await user.click(screen.getByRole('button', { name: /Arrived in Rome/ }))+ expect(screen.getByRole('button', { name: 'Florence' })).toBeInTheDocument()++ await user.click(screen.getByRole('button', { name: /^New Gallery$/ }))+ await user.click(screen.getByRole('button', { name: 'Add (1)' }))+ expect(onAdd).toHaveBeenCalledWith([{ assetIds: ['a1'], mediaTypes: ['image'], passphrase: undefined }], null)+ })++ it('FE-JRN-PICKER-015: retries a broken thumbnail against the original size', async () => {+ const user = userEvent.setup()+ mountPicker()++ const tile = await screen.findByAltText('')+ expect(tile.getAttribute('src')).toContain('/api/integrations/memories/immich/assets/0/a1/42/thumbnail')+ fireEvent.error(tile)+ expect(tile.getAttribute('src')).toContain('/api/integrations/memories/immich/assets/0/a1/42/original')++ // A second failure must not loop back to the thumbnail.+ fireEvent.error(tile)+ expect(tile.getAttribute('src')).toContain('/original')++ await user.click(screen.getByRole('button', { name: 'Cancel' }))+ })++ it('FE-JRN-PICKER-016: shows a spinner while searching and the empty hint when the search fails', async () => {+ server.use(http.post('/api/integrations/memories/immich/search', async () => {+ await delay(30)+ return new HttpResponse(null, { status: 502 })+ }))+ const { container } = mountPicker()++ expect(container.querySelector('.animate-spin')).toBeInTheDocument()++ expect(await screen.findByText('No photos yet')).toBeInTheDocument()+ })++ it('FE-JRN-PICKER-017: loads the next page when the scroll trigger becomes visible', async () => {+ const pages: number[] = []+ server.use(http.post('/api/integrations/memories/immich/search', async ({ request }) => {+ const body = await request.json() as { page: number }+ pages.push(body.page)+ return HttpResponse.json({ assets: [asset(`p${body.page}`)], hasMore: body.page < 2 })+ }))+ const observers: IntersectionObserverCallback[] = []+ class ImmediateObserver {+ constructor(private cb: IntersectionObserverCallback) { observers.push(cb) }+ observe() { this.cb([{ isIntersecting: true } as IntersectionObserverEntry], this as unknown as IntersectionObserver) }+ unobserve() {}+ disconnect() {}+ }+ const original = globalThis.IntersectionObserver+ globalThis.IntersectionObserver = ImmediateObserver as unknown as typeof IntersectionObserver+ try {+ mountPicker()+ await waitFor(() => expect(pages).toEqual([1, 2]))+ expect(observers.length).toBeGreaterThan(0)+ expect(await screen.findAllByAltText('')).toHaveLength(2)+ } finally {+ globalThis.IntersectionObserver = original+ }+ })++ it('FE-JRN-PICKER-018: the embedded variant drops the header, the add-to bar and the date captions', async () => {+ mountPicker({ embedded: true, initialDate: '2026-03-15' })++ expect(await screen.findByTestId('journey-provider-picker-embedded')).toBeInTheDocument()+ expect(screen.queryByRole('heading', { name: 'Immich' })).not.toBeInTheDocument()+ expect(screen.queryByText('Add to')).not.toBeInTheDocument()+ expect(screen.queryByText('March 15, 2026')).not.toBeInTheDocument()+ })++ it('FE-JRN-PICKER-019: searches the picked custom range and ignores an incomplete one', async () => {+ const ranges: Record<string, unknown>[] = []+ server.use(http.post('/api/integrations/memories/immich/search', async ({ request }) => {+ ranges.push(await request.json() as Record<string, unknown>)+ return HttpResponse.json({ assets: [asset('a1')], hasMore: false })+ }))+ const user = userEvent.setup()+ const { container } = mountPicker()+ await screen.findByText('March 15, 2026')+ ranges.length = 0++ await user.click(screen.getByRole('button', { name: 'Date Range' }))+ // No dates picked yet, so searching is a no-op.+ await user.click(screen.getByRole('button', { name: 'Search' }))+ expect(ranges).toHaveLength(0)++ const [fromPicker, toPicker] = Array.from(container.querySelectorAll('.flex-1 > .relative')) as HTMLElement[]+ await user.click(within(fromPicker).getByRole('button'))+ await user.click(within(fromPicker).getByRole('button', { name: '3' }))+ await user.click(within(toPicker).getByRole('button'))+ await user.click(within(toPicker).getByRole('button', { name: '9' }))+ await user.click(screen.getByRole('button', { name: 'Search' }))++ await waitFor(() => expect(ranges).toHaveLength(1))+ const range = ranges[0] as { from: string; to: string }+ expect(range.from.endsWith('-03')).toBe(true)+ expect(range.to.endsWith('-09')).toBe(true)+ })++ it('FE-JRN-PICKER-020: closes through the header button and the backdrop', async () => {+ const user = userEvent.setup()+ const { container, onClose } = mountPicker()+ await screen.findByText('March 15, 2026')++ const headerClose = screen.getByRole('heading', { name: 'Immich' })+ .parentElement!.querySelectorAll('button')[0]+ await user.click(headerClose)+ expect(onClose).toHaveBeenCalledTimes(1)++ await user.click(container.firstElementChild as HTMLElement)+ expect(onClose).toHaveBeenCalledTimes(2)+ })+})diff --git a/client/src/components/Journey/JourneyDetailPageScrollTrigger.test.tsx b/client/src/components/Journey/JourneyDetailPageScrollTrigger.test.tsxnew file mode 100644index 000000000..e74216da8--- /dev/null+++ b/client/src/components/Journey/JourneyDetailPageScrollTrigger.test.tsx@@ -0,0 +1,90 @@+// FE-COMP-JSCROLLTRIG-001 to FE-COMP-JSCROLLTRIG-006++import { render } from '../../../tests/helpers/render'+import { resetAllStores } from '../../../tests/helpers/store'+import { ScrollTrigger } from './JourneyDetailPageScrollTrigger'++// The global stub in tests/setup.ts never fires — swap in one that hands the+// callback back so the sentinel can be driven into view on demand.+interface ObserverStub {+ callback: IntersectionObserverCallback+ options?: IntersectionObserverInit+ observed: Element[]+ disconnect: () => void+}++let observers: ObserverStub[] = []++function intersect(observer: ObserverStub, isIntersecting: boolean) {+ observer.callback(+ [{ isIntersecting, target: observer.observed[0] } as unknown as IntersectionObserverEntry],+ observer as unknown as IntersectionObserver,+ )+}++beforeEach(() => {+ resetAllStores()+ observers = []+ vi.stubGlobal('IntersectionObserver', class {+ constructor(callback: IntersectionObserverCallback, options?: IntersectionObserverInit) {+ const stub: ObserverStub = { callback, options, observed: [], disconnect: vi.fn(() => {}) }+ observers.push(stub)+ this.observe = (el: Element) => { stub.observed.push(el) }+ this.disconnect = stub.disconnect+ }+ observe: (el: Element) => void+ disconnect: () => void+ unobserve = vi.fn()+ takeRecords = vi.fn(() => [])+ })+})++afterEach(() => {+ vi.unstubAllGlobals()+})++describe('ScrollTrigger', () => {+ it('FE-COMP-JSCROLLTRIG-001: renders a spinner sentinel and observes it', () => {+ const { container } = render(<ScrollTrigger onVisible={vi.fn()} loading={false} />)+ expect(container.querySelector('.animate-spin')).not.toBeNull()+ expect(observers).toHaveLength(1)+ expect(observers[0].observed[0]).toBe(container.firstChild)+ })++ it('FE-COMP-JSCROLLTRIG-002: pre-loads while the sentinel is still 200px away', () => {+ render(<ScrollTrigger onVisible={vi.fn()} loading={false} />)+ expect(observers[0].options).toMatchObject({ rootMargin: '200px' })+ })++ it('FE-COMP-JSCROLLTRIG-003: scrolling the sentinel into view asks for the next page', () => {+ const onVisible = vi.fn()+ render(<ScrollTrigger onVisible={onVisible} loading={false} />)+ intersect(observers[0], true)+ expect(onVisible).toHaveBeenCalledTimes(1)+ })++ it('FE-COMP-JSCROLLTRIG-004: leaving the viewport does not ask for a page', () => {+ const onVisible = vi.fn()+ render(<ScrollTrigger onVisible={onVisible} loading={false} />)+ intersect(observers[0], false)+ expect(onVisible).not.toHaveBeenCalled()+ })++ it('FE-COMP-JSCROLLTRIG-005: a page already in flight is not requested twice', () => {+ const onVisible = vi.fn()+ const { rerender } = render(<ScrollTrigger onVisible={onVisible} loading />)+ intersect(observers[0], true)+ expect(onVisible).not.toHaveBeenCalled()++ // once the fetch settles the sentinel is re-observed and fires again+ rerender(<ScrollTrigger onVisible={onVisible} loading={false} />)+ intersect(observers[observers.length - 1], true)+ expect(onVisible).toHaveBeenCalledTimes(1)+ })++ it('FE-COMP-JSCROLLTRIG-006: unmounting disconnects the observer', () => {+ const { unmount } = render(<ScrollTrigger onVisible={vi.fn()} loading={false} />)+ unmount()+ expect(observers[0].disconnect).toHaveBeenCalled()+ })+})diff --git a/client/src/components/Journey/JourneyDetailPageSettingsDialog.test.tsx b/client/src/components/Journey/JourneyDetailPageSettingsDialog.test.tsxnew file mode 100644index 000000000..b25be7f96--- /dev/null+++ b/client/src/components/Journey/JourneyDetailPageSettingsDialog.test.tsx@@ -0,0 +1,363 @@+// FE-JRN-SETTINGS-001 to FE-JRN-SETTINGS-019++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { http, HttpResponse } from 'msw'+import userEvent from '@testing-library/user-event'+import { render, screen, waitFor, within, fireEvent, act } from '../../../tests/helpers/render'+import { server } from '../../../tests/helpers/msw/server'+import { useJourneyStore, type JourneyDetail } from '../../store/journeyStore'+import { JourneySettingsDialog } from './JourneyDetailPageSettingsDialog'++type ToastKind = 'success' | 'error' | 'warning' | 'info'++const mockNavigate = vi.fn()+vi.mock('react-router-dom', async () => {+ const actual = await vi.importActual<typeof import('react-router-dom')>('react-router-dom')+ return { ...actual, useNavigate: () => mockNavigate }+})++const toastSpy = vi.fn((_message: string, _type?: ToastKind, _duration?: number) => 0)+const updateJourney = vi.fn(async (_id: number, _data: Record<string, unknown>) => {})+const deleteJourney = vi.fn(async (_id: number) => {})++function buildJourney(overrides: Partial<JourneyDetail> = {}): JourneyDetail {+ return {+ id: 3,+ user_id: 1,+ title: 'Italy 2026',+ subtitle: 'Rome & Florence',+ status: 'active',+ cover_image: null,+ cover_gradient: null,+ created_at: 0,+ updated_at: 0,+ entries: [],+ gallery: [],+ trips: [{ trip_id: 5, added_at: 0, title: 'Italy Trip', place_count: 8 }],+ contributors: [+ { journey_id: 3, user_id: 1, role: 'owner', added_at: 0, username: 'maurice', avatar: null },+ { journey_id: 3, user_id: 2, role: 'editor', added_at: 0, username: 'julien', avatar: null },+ ],+ stats: { entries: 0, photos: 0, places: 0 },+ ...overrides,+ }+}++function mountDialog(journey: JourneyDetail = buildJourney()) {+ const onClose = vi.fn()+ const onSaved = vi.fn()+ const onOpenInvite = vi.fn()+ const onRefresh = vi.fn()+ const utils = render(+ <JourneySettingsDialog+ journey={journey}+ onClose={onClose}+ onSaved={onSaved}+ onOpenInvite={onOpenInvite}+ onRefresh={onRefresh}+ />,+ )+ return { ...utils, onClose, onSaved, onOpenInvite, onRefresh }+}++/** The confirm dialogs are portalled and only differ by their heading. */+function confirmIn(headingText: string) {+ const modal = screen.getByRole('heading', { name: headingText }).closest('.trek-modal-enter') as HTMLElement+ return within(modal)+}++beforeEach(() => {+ toastSpy.mockClear()+ updateJourney.mockClear()+ updateJourney.mockResolvedValue(undefined)+ deleteJourney.mockClear()+ deleteJourney.mockResolvedValue(undefined)+ mockNavigate.mockClear()+ window.__addToast = toastSpy+ useJourneyStore.setState({ updateJourney, deleteJourney })+ server.use(+ http.get('/api/journeys/3/share-link', () => HttpResponse.json({ link: null })),+ http.get('/api/journeys/available-trips', () => HttpResponse.json({ trips: [] })),+ )+})++afterEach(() => {+ delete window.__addToast+})++describe('JourneySettingsDialog', () => {+ it('FE-JRN-SETTINGS-001: seeds the form from the journey and lists trips and contributors', async () => {+ mountDialog()++ expect(screen.getByDisplayValue('Italy 2026')).toBeInTheDocument()+ expect(screen.getByDisplayValue('Rome & Florence')).toBeInTheDocument()+ expect(screen.getByText('Italy Trip')).toBeInTheDocument()+ expect(screen.getByText('8 places')).toBeInTheDocument()+ expect(screen.getByText('julien')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Add cover image' })).toBeInTheDocument()+ await screen.findByRole('button', { name: /create share link/i })+ })++ it('FE-JRN-SETTINGS-002: saves the edited title and subtitle', async () => {+ const user = userEvent.setup()+ const { onSaved } = mountDialog()++ const titleInput = screen.getByDisplayValue('Italy 2026')+ await user.clear(titleInput)+ await user.type(titleInput, 'Italy 2027')+ await user.type(screen.getByPlaceholderText('e.g. Thailand, Vietnam & Cambodia'), '!')++ await user.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1))+ expect(updateJourney).toHaveBeenCalledWith(3, { title: 'Italy 2027', subtitle: 'Rome & Florence!' })+ })++ it('FE-JRN-SETTINGS-003: clears the subtitle to null when it is emptied', async () => {+ const user = userEvent.setup()+ mountDialog()++ await user.clear(screen.getByDisplayValue('Rome & Florence'))+ await user.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => expect(updateJourney).toHaveBeenCalledWith(3, { title: 'Italy 2026', subtitle: null }))+ })++ it('FE-JRN-SETTINGS-004: reports a failed save', async () => {+ updateJourney.mockRejectedValueOnce(new Error('nope'))+ const user = userEvent.setup()+ const { onSaved } = mountDialog()++ await user.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined))+ expect(onSaved).not.toHaveBeenCalled()+ })++ it('FE-JRN-SETTINGS-005: disables saving while the title is blank', async () => {+ const user = userEvent.setup()+ mountDialog()++ await user.clear(screen.getByDisplayValue('Italy 2026'))++ expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()+ })++ it('FE-JRN-SETTINGS-006: uploads a picked cover image', async () => {+ let uploaded = false+ server.use(http.post('/api/journeys/3/cover', () => {+ uploaded = true+ return HttpResponse.json({ ok: true })+ }))+ const { container, onSaved } = mountDialog()++ const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement+ fireEvent.change(fileInput, { target: { files: [new File(['x'], 'cover.png', { type: 'image/png' })] } })++ await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1))+ expect(uploaded).toBe(true)+ expect(toastSpy).toHaveBeenCalledWith('Cover updated', 'success', undefined)+ })++ it('FE-JRN-SETTINGS-007: reports a failed cover upload', async () => {+ server.use(http.post('/api/journeys/3/cover', () => new HttpResponse(null, { status: 413 })))+ const { container, onSaved } = mountDialog()++ const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement+ fireEvent.change(fileInput, { target: { files: [new File(['x'], 'cover.png', { type: 'image/png' })] } })++ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Upload failed', 'error', undefined))+ expect(onSaved).not.toHaveBeenCalled()+ })++ it('FE-JRN-SETTINGS-008: ignores a cover change event without a file', async () => {+ const { container, onSaved } = mountDialog()++ const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement+ fireEvent.change(fileInput, { target: { files: [] } })++ expect(onSaved).not.toHaveBeenCalled()+ expect(toastSpy).not.toHaveBeenCalled()+ })++ it('FE-JRN-SETTINGS-009: shows the existing cover as a preview', () => {+ mountDialog(buildJourney({ cover_image: 'covers/italy.jpg' }))++ expect(screen.getByRole('button', { name: 'Change cover' })).toBeInTheDocument()+ const preview = document.querySelector('img[src="/uploads/covers/italy.jpg"]')+ expect(preview).toBeInTheDocument()+ })++ it('FE-JRN-SETTINGS-010: archives an active journey', async () => {+ const user = userEvent.setup()+ const { onSaved } = mountDialog()++ await user.click(screen.getByRole('button', { name: 'Archive Journey' }))++ await waitFor(() => expect(updateJourney).toHaveBeenCalledWith(3, { status: 'archived' }))+ expect(toastSpy).toHaveBeenCalledWith('Journey archived', 'success', undefined)+ expect(onSaved).toHaveBeenCalledTimes(1)+ })++ it('FE-JRN-SETTINGS-011: restores an archived journey', async () => {+ const user = userEvent.setup()+ mountDialog(buildJourney({ status: 'archived' }))++ await user.click(screen.getByRole('button', { name: 'Restore Journey' }))++ await waitFor(() => expect(updateJourney).toHaveBeenCalledWith(3, { status: 'active' }))+ expect(toastSpy).toHaveBeenCalledWith('Journey reopened', 'success', undefined)+ })++ it('FE-JRN-SETTINGS-012: reports a failed archive toggle', async () => {+ updateJourney.mockRejectedValueOnce(new Error('nope'))+ const user = userEvent.setup()+ mountDialog()++ await user.click(screen.getByRole('button', { name: 'Archive Journey' }))++ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined))+ expect(screen.getByRole('button', { name: 'Archive Journey' })).toBeEnabled()+ })++ it('FE-JRN-SETTINGS-013: deletes the journey and navigates back to the list', async () => {+ const user = userEvent.setup()+ mountDialog()++ await user.click(screen.getByRole('button', { name: 'Delete' }))+ await user.click(confirmIn('Delete Journey').getByRole('button', { name: 'Delete' }))++ await waitFor(() => expect(deleteJourney).toHaveBeenCalledWith(3))+ expect(mockNavigate).toHaveBeenCalledWith('/journey')+ })++ it('FE-JRN-SETTINGS-014: reports a failed delete and stays on the page', async () => {+ deleteJourney.mockRejectedValueOnce(new Error('nope'))+ const user = userEvent.setup()+ mountDialog()++ await user.click(screen.getByRole('button', { name: 'Delete' }))+ await user.click(confirmIn('Delete Journey').getByRole('button', { name: 'Delete' }))++ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to delete', 'error', undefined))+ expect(mockNavigate).not.toHaveBeenCalled()+ })++ it('FE-JRN-SETTINGS-015: unlinks a trip after confirmation', async () => {+ let unlinked = false+ server.use(http.delete('/api/journeys/3/trips/5', () => {+ unlinked = true+ return HttpResponse.json({ ok: true })+ }))+ const user = userEvent.setup()+ const { onSaved } = mountDialog()++ await user.click(screen.getByTitle('Unlink trip'))+ expect(screen.getByText(/Unlink "Italy Trip"\?/)).toBeInTheDocument()+ await user.click(confirmIn('Unlink Trip').getByRole('button', { name: 'Unlink' }))++ await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1))+ expect(unlinked).toBe(true)+ expect(toastSpy).toHaveBeenCalledWith('Trip unlinked', 'success', undefined)+ })++ it('FE-JRN-SETTINGS-016: reports a failed unlink', async () => {+ server.use(http.delete('/api/journeys/3/trips/5', () => new HttpResponse(null, { status: 500 })))+ const user = userEvent.setup()+ const { onSaved } = mountDialog()++ await user.click(screen.getByTitle('Unlink trip'))+ await user.click(confirmIn('Unlink Trip').getByRole('button', { name: 'Unlink' }))++ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to unlink trip', 'error', undefined))+ expect(onSaved).not.toHaveBeenCalled()+ })++ it('FE-JRN-SETTINGS-017: removes a contributor only after the browser confirm', async () => {+ let removed = 0+ server.use(http.delete('/api/journeys/3/contributors/2', () => {+ removed += 1+ return HttpResponse.json({ ok: true })+ }))+ const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false)+ const user = userEvent.setup()+ const { onRefresh } = mountDialog()++ // Only the non-owner contributor gets a remove control.+ const removeBtn = screen.getByRole('button', { name: 'Remove contributor' })+ await user.click(removeBtn)+ expect(confirmSpy).toHaveBeenCalledWith('Remove julien from this journey?')+ expect(removed).toBe(0)++ confirmSpy.mockReturnValue(true)+ await user.click(removeBtn)+ await waitFor(() => expect(onRefresh).toHaveBeenCalledTimes(1))+ expect(removed).toBe(1)+ expect(toastSpy).toHaveBeenCalledWith('Contributor removed', 'success', undefined)+ confirmSpy.mockRestore()+ })++ it('FE-JRN-SETTINGS-018: reports a failed contributor removal', async () => {+ server.use(http.delete('/api/journeys/3/contributors/2', () => new HttpResponse(null, { status: 500 })))+ const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true)+ const user = userEvent.setup()+ const { onRefresh } = mountDialog()++ await user.click(screen.getByRole('button', { name: 'Remove contributor' }))++ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to remove contributor', 'error', undefined))+ expect(onRefresh).not.toHaveBeenCalled()+ confirmSpy.mockRestore()+ })++ it('FE-JRN-SETTINGS-019: opens the invite and the add-trip flow', async () => {+ const user = userEvent.setup()+ const { onOpenInvite } = mountDialog(buildJourney({ trips: [] }))++ expect(screen.getByText('No trips linked')).toBeInTheDocument()++ await user.click(screen.getByRole('button', { name: 'Invite Contributor' }))+ expect(onOpenInvite).toHaveBeenCalledTimes(1)++ await user.click(screen.getByRole('button', { name: 'Add Trip' }))+ expect(await screen.findByRole('heading', { name: 'Link Trip' })).toBeInTheDocument()+ })++ it('FE-JRN-SETTINGS-020: closes straight away when nothing was edited', async () => {+ const user = userEvent.setup()+ const { onClose } = mountDialog()++ await user.click(screen.getByRole('button', { name: 'Cancel' }))++ expect(onClose).toHaveBeenCalledTimes(1)+ expect(screen.queryByRole('heading', { name: 'Discard Changes' })).not.toBeInTheDocument()+ })++ it('FE-JRN-SETTINGS-021: asks before discarding unsaved edits', async () => {+ const user = userEvent.setup()+ const { onClose } = mountDialog()++ await user.type(screen.getByDisplayValue('Italy 2026'), '!')+ await user.click(screen.getByRole('button', { name: 'Cancel' }))+ expect(onClose).not.toHaveBeenCalled()++ await user.click(confirmIn('Discard Changes').getByRole('button', { name: 'Discard' }))+ expect(onClose).toHaveBeenCalledTimes(1)+ })++ it('FE-JRN-SETTINGS-022: keeps the dialog open when the discard prompt is dismissed', async () => {+ const user = userEvent.setup()+ const { onClose } = mountDialog()++ // The header close button carries only an icon, so it is addressed by position.+ const headerClose = screen.getByRole('heading', { name: 'Journey Settings' })+ .parentElement!.querySelectorAll('button')[0]+ await user.type(screen.getByDisplayValue('Rome & Florence'), '!')+ act(() => { headerClose.click() })++ await user.click(confirmIn('Discard Changes').getByRole('button', { name: 'Cancel' }))++ expect(onClose).not.toHaveBeenCalled()+ expect(screen.getByRole('heading', { name: 'Journey Settings' })).toBeInTheDocument()+ })+})diff --git a/client/src/components/Journey/JourneyMap.test.tsx b/client/src/components/Journey/JourneyMap.test.tsxindex 4eff50a8e..7ece6edaf 100644--- a/client/src/components/Journey/JourneyMap.test.tsx+++ b/client/src/components/Journey/JourneyMap.test.tsx@@ -1,4 +1,4 @@-// FE-COMP-JOURNEYMAP-001 to FE-COMP-JOURNEYMAP-006+// FE-COMP-JOURNEYMAP-001 to FE-COMP-JOURNEYMAP-027vi.mock('../../api/websocket', () => ({connect: vi.fn(),@@ -49,7 +49,7 @@ vi.mock('leaflet', () => {});import React from 'react';-import { render } from '../../../tests/helpers/render';+import { render, act, fireEvent } from '../../../tests/helpers/render';import { resetAllStores, seedStore } from '../../../tests/helpers/store';import { useSettingsStore } from '../../store/settingsStore';import { buildSettings } from '../../../tests/helpers/factories';@@ -71,6 +71,12 @@ const mixedEntries = [...entriesWithoutCoords,];+// The leaflet mock hands out one shared map/marker instance, so every render+// resolves to the same spy object.+const mockedMap = () => vi.mocked(L.map).mock.results[0].value;+const mockedMarker = (i = 0) => vi.mocked(L.marker).mock.results[i].value;+const divIconHtml = (i: number) => String(vi.mocked(L.divIcon).mock.calls[i][0].html);+beforeEach(() => {resetAllStores();seedStore(useSettingsStore, { settings: buildSettings() });@@ -227,4 +233,260 @@ describe('JourneyMap', () => {expect(buttons[0].textContent).toBe('+');expect(buttons[1].textContent).toBe('−');});++ it('FE-COMP-JOURNEYMAP-013: skips entries without coordinates but keeps the rest', () => {+ render(+ <JourneyMap checkins={[]} entries={mixedEntries} />+ );+ // Only the two entries with real lat/lng become markers+ expect(L.marker).toHaveBeenCalledTimes(2);+ });++ it('FE-COMP-JOURNEYMAP-014: highlightMarker scales the pin up and lifts its z-index', () => {+ const ref = React.createRef<JourneyMapHandle>();+ render(<JourneyMap ref={ref} checkins={[]} entries={entriesWithCoords} />);+ const iconsBefore = vi.mocked(L.divIcon).mock.calls.length;++ act(() => { ref.current!.highlightMarker('e1'); });++ expect(divIconHtml(iconsBefore)).toContain('scale(1.2)');+ expect(mockedMarker().setZIndexOffset).toHaveBeenCalledWith(1000);+ });++ it('FE-COMP-JOURNEYMAP-015: highlighting a second marker resets the previous one', () => {+ const ref = React.createRef<JourneyMapHandle>();+ render(<JourneyMap ref={ref} checkins={[]} entries={entriesWithCoords} />);+ act(() => { ref.current!.highlightMarker('e1'); });+ const iconsBefore = vi.mocked(L.divIcon).mock.calls.length;++ act(() => { ref.current!.highlightMarker('e2'); });++ // First the old pin is redrawn unhighlighted, then the new one highlighted+ expect(divIconHtml(iconsBefore)).toContain('scale(1)');+ expect(divIconHtml(iconsBefore + 1)).toContain('scale(1.2)');+ expect(mockedMarker().setZIndexOffset).toHaveBeenCalledWith(0);+ });++ it('FE-COMP-JOURNEYMAP-016: highlightMarker ignores ids that have no marker', () => {+ const ref = React.createRef<JourneyMapHandle>();+ render(<JourneyMap ref={ref} checkins={[]} entries={entriesWithCoords} />);+ const iconsBefore = vi.mocked(L.divIcon).mock.calls.length;++ act(() => { ref.current!.highlightMarker('does-not-exist'); });++ expect(vi.mocked(L.divIcon).mock.calls.length).toBe(iconsBefore);+ });++ it('FE-COMP-JOURNEYMAP-017: focusMarker flies to the pin, never below zoom 12', () => {+ const ref = React.createRef<JourneyMapHandle>();+ render(<JourneyMap ref={ref} checkins={[]} entries={entriesWithCoords} />);++ act(() => { ref.current!.focusMarker('e2'); });++ // getZoom() is stubbed at 10, so the floor of 12 wins+ expect(mockedMap().flyTo).toHaveBeenCalledWith({ lat: 0, lng: 0 }, 12, { duration: 0.5 });+ });++ it('FE-COMP-JOURNEYMAP-018: focusMarker swallows leaflet errors when the map has no view yet', () => {+ const ref = React.createRef<JourneyMapHandle>();+ render(<JourneyMap ref={ref} checkins={[]} entries={entriesWithCoords} />);+ vi.mocked(mockedMap().getZoom).mockImplementationOnce(() => { throw new Error('Set map center and zoom first'); });++ expect(() => act(() => { ref.current!.focusMarker('e1'); })).not.toThrow();+ expect(mockedMap().flyTo).not.toHaveBeenCalled();+ });++ it('FE-COMP-JOURNEYMAP-019: invalidateSize forwards to the leaflet map', () => {+ const ref = React.createRef<JourneyMapHandle>();+ render(<JourneyMap ref={ref} checkins={[]} entries={entriesWithCoords} />);+ const before = vi.mocked(mockedMap().invalidateSize).mock.calls.length;++ act(() => { ref.current!.invalidateSize(); });++ expect(vi.mocked(mockedMap().invalidateSize).mock.calls.length).toBe(before + 1);+ });++ it('FE-COMP-JOURNEYMAP-020: a trail draws its own dashed polyline', () => {+ render(+ <JourneyMap+ checkins={[]}+ entries={entriesWithCoords}+ trail={[{ lat: 48.85, lng: 2.35 }, { lat: 50.0, lng: 8.0 }, { lat: 52.52, lng: 13.4 }]}+ />+ );+ // trail polyline first, route polyline second+ const trailCall = vi.mocked(L.polyline).mock.calls[0];+ expect(trailCall[0]).toEqual([[48.85, 2.35], [50.0, 8.0], [52.52, 13.4]]);+ expect(trailCall[1]).toMatchObject({ dashArray: '6 4', color: '#6366f1' });+ });++ it('FE-COMP-JOURNEYMAP-021: a single-point trail is not drawn', () => {+ render(+ <JourneyMap checkins={[]} entries={entriesWithoutCoords} trail={[{ lat: 1, lng: 2 }]} />+ );+ expect(L.polyline).not.toHaveBeenCalled();+ });++ it('FE-COMP-JOURNEYMAP-022: fullScreen enables wheel zoom and drops the route polyline', () => {+ render(+ <JourneyMap checkins={[]} entries={entriesWithCoords} fullScreen />+ );+ expect(vi.mocked(L.map).mock.calls[0][1]).toMatchObject({ scrollWheelZoom: true });+ // The connecting route line is a sidebar-only decoration+ expect(L.polyline).not.toHaveBeenCalled();+ });++ it('FE-COMP-JOURNEYMAP-023: clicking a marker reports the entry id', () => {+ const onMarkerClick = vi.fn();+ render(+ <JourneyMap checkins={[]} entries={entriesWithCoords} onMarkerClick={onMarkerClick} />+ );+ const handler = vi.mocked(mockedMarker().on).mock.calls.find(c => c[0] === 'click')?.[1] as () => void;+ act(() => { handler(); });+ expect(onMarkerClick).toHaveBeenCalledWith('e1');+ });++ it('FE-COMP-JOURNEYMAP-024: without any coordinates the map falls back to the world view', () => {+ const origRAF = globalThis.requestAnimationFrame;+ globalThis.requestAnimationFrame = (cb: FrameRequestCallback) => { cb(0); return 0; };+ try {+ render(<JourneyMap checkins={[]} entries={entriesWithoutCoords} />);+ expect(mockedMap().setView).toHaveBeenCalledWith([30, 0], 2);+ expect(mockedMap().fitBounds).not.toHaveBeenCalled();+ } finally {+ globalThis.requestAnimationFrame = origRAF;+ }+ });++ it('FE-COMP-JOURNEYMAP-025: paddingBottom widens the bottom fit padding', () => {+ const origRAF = globalThis.requestAnimationFrame;+ globalThis.requestAnimationFrame = (cb: FrameRequestCallback) => { cb(0); return 0; };+ try {+ render(<JourneyMap checkins={[]} entries={entriesWithCoords} paddingBottom={200} />);+ expect(mockedMap().fitBounds).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ paddingBottomRight: [50, 200] }),+ );+ } finally {+ globalThis.requestAnimationFrame = origRAF;+ }+ });++ it('FE-COMP-JOURNEYMAP-026: dark mode picks the dark basemap', () => {+ render(<JourneyMap checkins={[]} entries={entriesWithCoords} dark />);+ expect(vi.mocked(L.tileLayer).mock.calls[0][0]).toContain('dark_all');+ });++ it('FE-COMP-JOURNEYMAP-027: a configured tile url overrides the default basemap', () => {+ seedStore(useSettingsStore, { settings: buildSettings({ map_tile_url: 'https://tiles.test/{z}/{x}/{y}.png' }) });+ render(<JourneyMap checkins={[]} entries={entriesWithCoords} />);+ expect(vi.mocked(L.tileLayer).mock.calls[0][0]).toBe('https://tiles.test/{z}/{x}/{y}.png');+ });++ it('FE-COMP-JOURNEYMAP-028: the activeMarkerId prop flies to that marker after the settle delay', () => {+ vi.useFakeTimers();+ try {+ render(<JourneyMap checkins={[]} entries={entriesWithCoords} activeMarkerId="e2" />);+ expect(mockedMap().flyTo).not.toHaveBeenCalled();+ act(() => { vi.advanceTimersByTime(60); });+ expect(mockedMap().flyTo).toHaveBeenCalledWith({ lat: 0, lng: 0 }, 12, { duration: 0.5 });+ } finally {+ vi.useRealTimers();+ }+ });++ it('FE-COMP-JOURNEYMAP-029: activeMarkerId falls back to setView while the map has no view yet', () => {+ vi.useFakeTimers();+ try {+ render(<JourneyMap checkins={[]} entries={entriesWithCoords} activeMarkerId="e1" />);+ vi.mocked(mockedMap().getZoom).mockImplementationOnce(() => { throw new Error('Set map center and zoom first'); });+ act(() => { vi.advanceTimersByTime(60); });+ expect(mockedMap().setView).toHaveBeenCalledWith({ lat: 0, lng: 0 }, 12);+ expect(mockedMap().flyTo).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });++ it('FE-COMP-JOURNEYMAP-030: an activeMarkerId with no marker does not move the camera', () => {+ vi.useFakeTimers();+ try {+ render(<JourneyMap checkins={[]} entries={entriesWithCoords} activeMarkerId="ghost" />);+ act(() => { vi.advanceTimersByTime(60); });+ expect(mockedMap().flyTo).not.toHaveBeenCalled();+ expect(mockedMap().setView).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });++ it('FE-COMP-JOURNEYMAP-031: the deferred resize fires 200ms after mount', () => {+ vi.useFakeTimers();+ try {+ render(<JourneyMap checkins={[]} entries={entriesWithCoords} />);+ const before = vi.mocked(mockedMap().invalidateSize).mock.calls.length;+ act(() => { vi.advanceTimersByTime(250); });+ expect(vi.mocked(mockedMap().invalidateSize).mock.calls.length).toBeGreaterThan(before);+ } finally {+ vi.useRealTimers();+ }+ });++ it('FE-COMP-JOURNEYMAP-032: the zoom buttons drive the leaflet map', () => {+ const { container } = render(<JourneyMap checkins={[]} entries={entriesWithCoords} />);+ const buttons = container.querySelectorAll('button');+ fireEvent.click(buttons[0]);+ fireEvent.click(buttons[1]);+ expect(mockedMap().zoomIn).toHaveBeenCalledTimes(1);+ expect(mockedMap().zoomOut).toHaveBeenCalledTimes(1);+ });++ it('FE-COMP-JOURNEYMAP-033: height 9999 stretches the wrapper to the full container', () => {+ const { container } = render(<JourneyMap checkins={[]} entries={entriesWithCoords} height={9999} />);+ expect((container.firstChild as HTMLElement).style.height).toBe('100%');+ });++ it('FE-COMP-JOURNEYMAP-034: per-day colours and labels reach the pin svg', () => {+ render(+ <JourneyMap+ checkins={[]}+ entries={[{ id: 'e9', lat: 40.4, lng: -3.7, title: 'Madrid', mood: null, entry_date: '2025-06-04', dayColor: '#ff0055', dayLabel: 4 }]}+ />+ );+ const html = divIconHtml(0);+ expect(html).toContain('#ff0055');+ expect(html).toContain('>4<');+ });++ it('FE-COMP-JOURNEYMAP-035: entries are ordered by date, not by array position', () => {+ render(+ <JourneyMap+ checkins={[]}+ entries={[+ { id: 'late', lat: 52.52, lng: 13.405, title: 'Berlin', mood: null, entry_date: '2025-06-09' },+ { id: 'early', lat: 48.8566, lng: 2.3522, title: 'Paris', mood: null, entry_date: '2025-06-01' },+ ]}+ />+ );+ const tooltipTitles = vi.mocked(mockedMarker().bindTooltip).mock.calls.map(c => c[0]);+ expect(tooltipTitles).toEqual(['Paris', 'Berlin']);+ });++ it('FE-COMP-JOURNEYMAP-036: an untitled entry still gets a tooltip label', () => {+ render(+ <JourneyMap+ checkins={[]}+ entries={[{ id: 'e0', lat: 1, lng: 2, title: null, mood: null, entry_date: '2025-06-01' }]}+ />+ );+ expect(mockedMarker().bindTooltip).toHaveBeenCalledWith('Entry', expect.objectContaining({ direction: 'top' }));+ });++ it('FE-COMP-JOURNEYMAP-037: unmounting tears the leaflet map down', () => {+ const { unmount } = render(<JourneyMap checkins={[]} entries={entriesWithCoords} />);+ const map = mockedMap();+ const before = vi.mocked(map.remove).mock.calls.length;+ unmount();+ expect(vi.mocked(map.remove).mock.calls.length).toBe(before + 1);+ });});diff --git a/client/src/components/Journey/JourneyMapGL.test.tsx b/client/src/components/Journey/JourneyMapGL.test.tsxnew file mode 100644index 000000000..ff6ef4252--- /dev/null+++ b/client/src/components/Journey/JourneyMapGL.test.tsx@@ -0,0 +1,592 @@+// FE-COMP-JMAPGL-001 to FE-COMP-JMAPGL-026++type Spy = ReturnType<typeof vi.fn>++interface MarkerStub {+ element: HTMLElement+ lngLat: [number, number]+ setLngLat: Spy+ addTo: Spy+ remove: Spy+ getElement: Spy+ getLngLat: Spy+}++interface PopupStub {+ options: Record<string, unknown>+ element: HTMLElement+ setLngLat: Spy+ setHTML: Spy+ setOffset: Spy+ getElement: Spy+ addTo: Spy+ remove: Spy+}++interface BoundsStub {+ points: [number, number][]+ extend: Spy+ getCenter: Spy+}++const gl = vi.hoisted(() => {+ const map = {+ on: vi.fn(),+ remove: vi.fn(),+ resize: vi.fn(),+ flyTo: vi.fn(),+ fitBounds: vi.fn(),+ getZoom: vi.fn(() => 10),+ addSource: vi.fn(),+ addLayer: vi.fn(),+ getSource: vi.fn((): unknown => null),+ setTerrain: vi.fn(),+ setConfigProperty: vi.fn(),+ }+ const markers: MarkerStub[] = []+ const popups: PopupStub[] = []+ const boundsList: BoundsStub[] = []++ function createMarker(options: { element?: HTMLElement }): MarkerStub {+ const marker: MarkerStub = {+ element: options?.element ?? document.createElement('div'),+ lngLat: [0, 0],+ setLngLat: vi.fn((ll: [number, number]) => { marker.lngLat = ll; return marker }),+ addTo: vi.fn(() => marker),+ remove: vi.fn(),+ getElement: vi.fn(() => marker.element),+ getLngLat: vi.fn(() => marker.lngLat),+ }+ markers.push(marker)+ return marker+ }++ function createPopup(options: Record<string, unknown>): PopupStub {+ const popup: PopupStub = {+ options: options ?? {},+ element: document.createElement('div'),+ setLngLat: vi.fn(() => popup),+ setHTML: vi.fn(() => popup),+ setOffset: vi.fn(() => popup),+ getElement: vi.fn(() => popup.element),+ addTo: vi.fn(() => popup),+ remove: vi.fn(),+ }+ popups.push(popup)+ return popup+ }++ function createBounds(): BoundsStub {+ const bounds: BoundsStub = {+ points: [],+ extend: vi.fn((p: [number, number]) => { bounds.points.push(p); return bounds }),+ getCenter: vi.fn(() => ({ lng: 5, lat: 45 })),+ }+ boundsList.push(bounds)+ return bounds+ }++ return { map, markers, popups, boundsList, createMarker, createPopup, createBounds }+})++const glModule = vi.hoisted(() => () => ({+ default: {+ accessToken: '',+ Map: vi.fn(function () { return gl.map }),+ Marker: vi.fn(function (options: { element?: HTMLElement }) { return gl.createMarker(options) }),+ Popup: vi.fn(function (options: Record<string, unknown>) { return gl.createPopup(options) }),+ LngLatBounds: vi.fn(function () { return gl.createBounds() }),+ },+}))++vi.mock('mapbox-gl', glModule)+vi.mock('maplibre-gl', glModule)+vi.mock('mapbox-gl/dist/mapbox-gl.css', () => ({}))+vi.mock('maplibre-gl/dist/maplibre-gl.css', () => ({}))++vi.mock('../Map/mapboxSetup', () => ({+ isStandardFamily: vi.fn(() => false),+ supportsCustom3d: vi.fn(() => false),+ wantsTerrain: vi.fn(() => false),+ addCustom3dBuildings: vi.fn(),+ addTerrainAndSky: vi.fn(),+}))++import React from 'react'+import mapboxgl from 'mapbox-gl'+import maplibregl from 'maplibre-gl'+import { render, screen, act } from '../../../tests/helpers/render'+import { resetAllStores, seedStore } from '../../../tests/helpers/store'+import { useSettingsStore } from '../../store/settingsStore'+import { isStandardFamily, supportsCustom3d, wantsTerrain, addCustom3dBuildings, addTerrainAndSky } from '../Map/mapboxSetup'+import JourneyMapGL from './JourneyMapGL'+import type { JourneyMapGLHandle } from './JourneyMapGL'++const entries = [+ { id: 'e1', lat: 48.8566, lng: 2.3522, title: 'Louvre', location_name: 'Paris, France', entry_date: '2025-06-01', dayColor: '#ff0055', dayLabel: 2 },+ { id: 'e2', lat: 52.52, lng: 13.405, title: 'Museumsinsel', location_name: 'Berlin, Germany', entry_date: '2025-06-02' },+]++const singleEntry = [entries[0]]++function withToken(extra: Record<string, unknown> = {}) {+ seedStore(useSettingsStore, {+ settings: { ...useSettingsStore.getState().settings, mapbox_access_token: 'pk.test_token', ...extra },+ })+}++function mapOptions(): Record<string, unknown> {+ const call = vi.mocked(mapboxgl.Map).mock.calls[0]+ return call[0] as unknown as Record<string, unknown>+}++function popupHtml(index = 0): string {+ return String(gl.popups[index].setHTML.mock.calls[0][0])+}++beforeEach(() => {+ resetAllStores()+ vi.clearAllMocks()+ gl.markers.length = 0+ gl.popups.length = 0+ gl.boundsList.length = 0+ gl.map.on.mockImplementation((event: string, handler: () => void) => {+ if (event === 'load') handler()+ return gl.map+ })+ gl.map.getZoom.mockReturnValue(10)+ gl.map.getSource.mockReturnValue(null)+ vi.mocked(isStandardFamily).mockReturnValue(false)+ vi.mocked(supportsCustom3d).mockReturnValue(false)+ vi.mocked(wantsTerrain).mockReturnValue(false)+ document.getElementById('trek-journey-popup-style')?.remove()+})++describe('JourneyMapGL', () => {+ it('FE-COMP-JMAPGL-001: mapbox without a token shows the settings hint instead of a map', () => {+ render(<JourneyMapGL checkins={[]} entries={entries} />)+ expect(screen.getByText(/No Mapbox access token configured/)).toBeInTheDocument()+ expect(screen.getByText('Settings → Map → Mapbox GL')).toBeInTheDocument()+ expect(mapboxgl.Map).not.toHaveBeenCalled()+ })++ it('FE-COMP-JMAPGL-002: a configured token builds the map and is handed to the sdk', () => {+ withToken()+ render(<JourneyMapGL checkins={[]} entries={entries} />)+ expect(mapboxgl.accessToken).toBe('pk.test_token')+ expect(mapboxgl.Map).toHaveBeenCalledTimes(1)+ expect(mapOptions()).toMatchObject({ style: 'mapbox://styles/mapbox/standard', attributionControl: true })+ })++ it('FE-COMP-JMAPGL-003: maplibre needs no token and opts out of the around-center rotate', () => {+ render(<JourneyMapGL checkins={[]} entries={entries} glProvider="maplibre-gl" />)+ expect(maplibregl.Map).toHaveBeenCalledTimes(1)+ const options = vi.mocked(maplibregl.Map).mock.calls[0][0] as unknown as Record<string, unknown>+ expect(options.aroundCenter).toBe(false)+ // projection is a mapbox-only option+ expect(options).not.toHaveProperty('projection')+ })++ it('FE-COMP-JMAPGL-004: quality mode turns on the globe projection and antialiasing', () => {+ withToken({ mapbox_quality_mode: true })+ render(<JourneyMapGL checkins={[]} entries={entries} />)+ expect(mapOptions()).toMatchObject({ projection: 'globe', antialias: true })+ })++ it('FE-COMP-JMAPGL-005: entries become bottom-anchored pins carrying their day colour and label', () => {+ withToken()+ render(<JourneyMapGL checkins={[]} entries={entries} />)++ expect(gl.markers).toHaveLength(2)+ expect(vi.mocked(mapboxgl.Marker).mock.calls[0][0]).toMatchObject({ anchor: 'bottom' })+ expect(gl.markers[0].setLngLat).toHaveBeenCalledWith([2.3522, 48.8566])+ const svg = gl.markers[0].element.innerHTML+ expect(svg).toContain('#ff0055')+ expect(svg).toContain('>2<')+ // the second entry has no explicit day meta and falls back to the neutral defaults+ expect(gl.markers[1].element.innerHTML).toContain('#52525B')+ expect(gl.markers[1].element.innerHTML).toContain('>1<')+ })++ it('FE-COMP-JMAPGL-006: entries without coordinates never reach the map', () => {+ withToken()+ render(+ <JourneyMapGL+ checkins={[]}+ entries={[{ id: 'nope', lat: 0, lng: 0, title: 'Null Island', entry_date: '2025-06-01' }]}+ />,+ )+ expect(gl.markers).toHaveLength(0)+ expect(gl.map.fitBounds).not.toHaveBeenCalled()+ })++ it('FE-COMP-JMAPGL-007: two or more entries add the dashed route source and layer', () => {+ withToken()+ render(<JourneyMapGL checkins={[]} entries={entries} />)++ expect(gl.map.addSource).toHaveBeenCalledWith('journey-route', expect.objectContaining({ type: 'geojson' }))+ const source = vi.mocked(gl.map.addSource).mock.calls[0][1] as { data: { geometry: { coordinates: number[][] } } }+ expect(source.data.geometry.coordinates).toEqual([[2.3522, 48.8566], [13.405, 52.52]])+ expect(gl.map.addLayer).toHaveBeenCalledWith(expect.objectContaining({+ id: 'journey-route-line',+ source: 'journey-route',+ }))+ })++ it('FE-COMP-JMAPGL-008: an existing route source is updated instead of re-added', () => {+ withToken()+ const setData = vi.fn()+ gl.map.getSource.mockReturnValue({ setData })++ render(<JourneyMapGL checkins={[]} entries={entries} />)++ expect(gl.map.addSource).not.toHaveBeenCalled()+ expect(setData).toHaveBeenCalledWith(expect.objectContaining({ type: 'Feature' }))+ })++ it('FE-COMP-JMAPGL-009: a single entry draws no route line', () => {+ withToken()+ render(<JourneyMapGL checkins={[]} entries={singleEntry} />)+ expect(gl.map.addSource).not.toHaveBeenCalled()+ expect(gl.map.addLayer).not.toHaveBeenCalled()+ })++ it('FE-COMP-JMAPGL-010: the camera fits entries and trail with the requested bottom padding', () => {+ withToken()+ render(+ <JourneyMapGL+ checkins={[]}+ entries={entries}+ trail={[{ lat: 50, lng: 8 }]}+ paddingBottom={200}+ fullScreen+ />,+ )++ expect(gl.boundsList[0].points).toEqual([[2.3522, 48.8566], [13.405, 52.52], [8, 50]])+ expect(gl.map.fitBounds).toHaveBeenCalledWith(gl.boundsList[0], expect.objectContaining({+ padding: { top: 50, bottom: 200, left: 50, right: 50 },+ maxZoom: 16,+ pitch: 45,+ duration: 0,+ }))+ // fullScreen + 3D also tilts the opening camera+ expect(mapOptions()).toMatchObject({ pitch: 45, center: { lng: 5, lat: 45 }, zoom: 2 })+ })++ it('FE-COMP-JMAPGL-011: with nothing to show the map opens on the world view', () => {+ withToken()+ render(<JourneyMapGL checkins={[]} entries={[]} />)+ expect(mapOptions()).toMatchObject({ center: [0, 30], zoom: 1 })+ expect(gl.map.fitBounds).not.toHaveBeenCalled()+ })++ it('FE-COMP-JMAPGL-012: clicking a pin reports the entry id and stops the map from handling it', () => {+ withToken()+ const onMarkerClick = vi.fn()+ render(<JourneyMapGL checkins={[]} entries={entries} onMarkerClick={onMarkerClick} />)++ const ev = new MouseEvent('click', { bubbles: true, cancelable: true })+ const stopPropagation = vi.spyOn(ev, 'stopPropagation')+ act(() => { gl.markers[1].element.dispatchEvent(ev) })++ expect(onMarkerClick).toHaveBeenCalledWith('e2')+ expect(stopPropagation).toHaveBeenCalled()+ })++ it('FE-COMP-JMAPGL-013: highlightMarker enlarges the pin and opens a two-line popup', () => {+ withToken()+ const ref = React.createRef<JourneyMapGLHandle>()+ render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} />)++ act(() => { ref.current!.highlightMarker('e1') })++ const inner = gl.markers[0].element.querySelector('.trek-journey-marker-inner') as HTMLElement+ expect(inner.style.transform).toBe('scale(1.2)')+ expect(gl.markers[0].element.style.zIndex).toBe('1000')++ expect(gl.popups).toHaveLength(1)+ expect(gl.popups[0].setLngLat).toHaveBeenCalledWith([2.3522, 48.8566])+ expect(gl.popups[0].addTo).toHaveBeenCalledWith(gl.map)+ const html = popupHtml()+ expect(html).toContain('>Louvre<')+ expect(html).toContain('trek-journey-popup-place')+ expect(html).toContain('trek-journey-popup-sep')+ })++ it('FE-COMP-JMAPGL-014: the popup falls back to the location name when the entry has no title', () => {+ withToken()+ const ref = React.createRef<JourneyMapGLHandle>()+ render(+ <JourneyMapGL+ ref={ref}+ checkins={[]}+ entries={[{ id: 'e1', lat: 1, lng: 2, title: null, location_name: 'Reykjavík', entry_date: '2025-06-01' }]}+ />,+ )++ act(() => { ref.current!.highlightMarker('e1') })++ const html = popupHtml()+ expect(html).toContain('>Reykjavík<')+ // the location moved to the title line, so there is no place chip left below+ expect(html).not.toContain('trek-journey-popup-place')+ expect(html).not.toContain('trek-journey-popup-sep')+ })++ it('FE-COMP-JMAPGL-015: an entry with neither title nor place still gets a heading', () => {+ withToken()+ const ref = React.createRef<JourneyMapGLHandle>()+ render(+ <JourneyMapGL+ ref={ref}+ checkins={[]}+ entries={[{ id: 'e1', lat: 1, lng: 2, entry_date: '' }]}+ />,+ )++ act(() => { ref.current!.highlightMarker('e1') })++ const html = popupHtml()+ expect(html).toContain('>Entry<')+ // empty entry_date yields no subline at all+ expect(html).not.toContain('trek-journey-popup-sub')+ })++ it('FE-COMP-JMAPGL-016: an unparseable entry date is passed through verbatim', () => {+ withToken()+ const ref = React.createRef<JourneyMapGLHandle>()+ render(+ <JourneyMapGL+ ref={ref}+ checkins={[]}+ entries={[{ id: 'e1', lat: 1, lng: 2, title: 'Somewhere', entry_date: 'sometime' }]}+ />,+ )++ act(() => { ref.current!.highlightMarker('e1') })+ expect(popupHtml()).toContain('>sometime<')+ })++ it('FE-COMP-JMAPGL-017: popup text is html-escaped', () => {+ withToken()+ const ref = React.createRef<JourneyMapGLHandle>()+ render(+ <JourneyMapGL+ ref={ref}+ checkins={[]}+ entries={[{ id: 'e1', lat: 1, lng: 2, title: '<img src=x onerror="alert(1)">', location_name: "Tom & Jerry's", entry_date: '2025-06-01' }]}+ />,+ )++ act(() => { ref.current!.highlightMarker('e1') })++ const html = popupHtml()+ expect(html).not.toContain('<img')+ expect(html).toContain('<img src=x onerror="alert(1)">')+ expect(html).toContain('Tom & Jerry's')+ })++ it('FE-COMP-JMAPGL-018: highlighting a second pin reuses the popup and resets the first pin', () => {+ withToken()+ const ref = React.createRef<JourneyMapGLHandle>()+ render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} dark />)++ act(() => { ref.current!.highlightMarker('e1') })+ act(() => { ref.current!.highlightMarker('e2') })++ // only one popup instance is ever constructed+ expect(gl.popups).toHaveLength(1)+ expect(gl.popups[0].setLngLat).toHaveBeenCalledWith([13.405, 52.52])+ expect(gl.popups[0].setOffset).toHaveBeenCalledWith([0, -46])+ expect(gl.popups[0].element.classList.contains('trek-dark')).toBe(true)++ const firstInner = gl.markers[0].element.querySelector('.trek-journey-marker-inner') as HTMLElement+ expect(firstInner.style.transform).toBe('scale(1)')+ expect(gl.markers[0].element.style.zIndex).toBe('0')+ })++ it('FE-COMP-JMAPGL-019: dark mode tags the popup class on creation', () => {+ withToken()+ const ref = React.createRef<JourneyMapGLHandle>()+ render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} dark />)+ act(() => { ref.current!.highlightMarker('e1') })+ expect(gl.popups[0].options.className).toBe('trek-journey-popup trek-dark')+ })++ it('FE-COMP-JMAPGL-020: highlightMarker(null) closes the popup', () => {+ withToken()+ const ref = React.createRef<JourneyMapGLHandle>()+ render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} />)+ act(() => { ref.current!.highlightMarker('e1') })+ act(() => { ref.current!.highlightMarker(null) })+ expect(gl.popups[0].remove).toHaveBeenCalled()+ })++ it('FE-COMP-JMAPGL-021: highlighting an unknown id changes nothing', () => {+ withToken()+ const ref = React.createRef<JourneyMapGLHandle>()+ render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} />)+ act(() => { ref.current!.highlightMarker('ghost') })+ expect(gl.popups).toHaveLength(0)+ expect(gl.markers[0].element.style.zIndex).toBe('')+ })++ it('FE-COMP-JMAPGL-022: the popup stylesheet is injected exactly once', () => {+ withToken()+ const ref = React.createRef<JourneyMapGLHandle>()+ render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} />)+ act(() => { ref.current!.highlightMarker('e1') })+ act(() => { ref.current!.highlightMarker('e2') })+ expect(document.querySelectorAll('#trek-journey-popup-style')).toHaveLength(1)+ })++ it('FE-COMP-JMAPGL-023: focusMarker flies in with the 3D pitch and a zoom floor of 14', () => {+ withToken()+ const ref = React.createRef<JourneyMapGLHandle>()+ render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} />)++ act(() => { ref.current!.focusMarker('e2') })++ expect(gl.map.flyTo).toHaveBeenCalledWith({+ center: [13.405, 52.52],+ zoom: 14,+ pitch: 45,+ duration: 600,+ })+ })++ it('FE-COMP-JMAPGL-024: with 3D disabled the camera stays flat', () => {+ withToken({ mapbox_3d_enabled: false })+ const ref = React.createRef<JourneyMapGLHandle>()+ render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} />)++ act(() => { ref.current!.focusMarker('e1') })++ expect(gl.map.flyTo).toHaveBeenCalledWith(expect.objectContaining({ pitch: 0 }))+ expect(addCustom3dBuildings).not.toHaveBeenCalled()+ })++ it('FE-COMP-JMAPGL-025: focusMarker swallows sdk errors while the map is not ready', () => {+ withToken()+ const ref = React.createRef<JourneyMapGLHandle>()+ render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} />)+ gl.map.getZoom.mockImplementationOnce(() => { throw new Error('not ready') })++ expect(() => act(() => { ref.current!.focusMarker('e1') })).not.toThrow()+ expect(gl.map.flyTo).not.toHaveBeenCalled()+ })++ it('FE-COMP-JMAPGL-026: focusMarker on an unknown id is a no-op', () => {+ withToken()+ const ref = React.createRef<JourneyMapGLHandle>()+ render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} />)+ act(() => { ref.current!.focusMarker('ghost') })+ expect(gl.map.flyTo).not.toHaveBeenCalled()+ })++ it('FE-COMP-JMAPGL-027: invalidateSize resizes the gl canvas', () => {+ withToken()+ const ref = React.createRef<JourneyMapGLHandle>()+ render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} />)+ act(() => { ref.current!.invalidateSize() })+ expect(gl.map.resize).toHaveBeenCalled()+ })++ it('FE-COMP-JMAPGL-028: the activeMarkerId prop highlights and flies after the settle delay', () => {+ vi.useFakeTimers()+ try {+ withToken()+ render(<JourneyMapGL checkins={[]} entries={entries} activeMarkerId="e2" />)+ expect(gl.map.flyTo).not.toHaveBeenCalled()++ act(() => { vi.advanceTimersByTime(60) })++ expect(gl.popups).toHaveLength(1)+ expect(gl.map.flyTo).toHaveBeenCalledWith(expect.objectContaining({+ center: [13.405, 52.52],+ zoom: 12,+ duration: 500,+ }))+ } finally {+ vi.useRealTimers()+ }+ })++ it('FE-COMP-JMAPGL-029: an activeMarkerId with no pin leaves the camera alone', () => {+ vi.useFakeTimers()+ try {+ withToken()+ render(<JourneyMapGL checkins={[]} entries={entries} activeMarkerId="ghost" />)+ act(() => { vi.advanceTimersByTime(60) })+ expect(gl.map.flyTo).not.toHaveBeenCalled()+ } finally {+ vi.useRealTimers()+ }+ })++ it('FE-COMP-JMAPGL-030: 3D styles get terrain, sky and custom buildings on load', () => {+ withToken({ mapbox_style: 'mapbox://styles/mapbox/outdoors-v12' })+ vi.mocked(wantsTerrain).mockReturnValue(true)+ vi.mocked(supportsCustom3d).mockReturnValue(true)++ render(<JourneyMapGL checkins={[]} entries={entries} dark />)++ expect(addTerrainAndSky).toHaveBeenCalledWith(gl.map)+ expect(addCustom3dBuildings).toHaveBeenCalledWith(gl.map, true)+ // only the Standard style needs its built-in DEM flattened+ expect(gl.map.setTerrain).not.toHaveBeenCalled()+ })++ it('FE-COMP-JMAPGL-031: the Standard basemap is flattened and pinned to the ui language', () => {+ withToken({ language: 'gr' })+ vi.mocked(isStandardFamily).mockReturnValue(true)++ render(<JourneyMapGL checkins={[]} entries={entries} />)++ expect(gl.map.setTerrain).toHaveBeenCalledWith(null)+ expect(gl.map.setConfigProperty).toHaveBeenCalledWith('basemap', 'language', 'el')+ expect(addTerrainAndSky).not.toHaveBeenCalled()+ })++ it('FE-COMP-JMAPGL-032: sdk failures while configuring the basemap do not break the load', () => {+ withToken()+ vi.mocked(isStandardFamily).mockReturnValue(true)+ gl.map.setTerrain.mockImplementationOnce(() => { throw new Error('no terrain') })+ gl.map.setConfigProperty.mockImplementationOnce(() => { throw new Error('unsupported') })++ expect(() => render(<JourneyMapGL checkins={[]} entries={entries} />)).not.toThrow()+ expect(gl.markers).toHaveLength(2)+ })++ it('FE-COMP-JMAPGL-033: an empty bounds fit is swallowed', () => {+ withToken()+ gl.map.fitBounds.mockImplementationOnce(() => { throw new Error('empty bounds') })+ expect(() => render(<JourneyMapGL checkins={[]} entries={entries} />)).not.toThrow()+ })++ it('FE-COMP-JMAPGL-034: unmounting removes the pins, the popup and the map', () => {+ withToken()+ const ref = React.createRef<JourneyMapGLHandle>()+ const { unmount } = render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} />)+ act(() => { ref.current!.highlightMarker('e1') })++ unmount()++ expect(gl.markers[0].remove).toHaveBeenCalled()+ expect(gl.markers[1].remove).toHaveBeenCalled()+ expect(gl.popups[0].remove).toHaveBeenCalled()+ expect(gl.map.remove).toHaveBeenCalled()+ })++ it('FE-COMP-JMAPGL-035: height 9999 stretches the wrapper to its container', () => {+ withToken()+ const { container } = render(<JourneyMapGL checkins={[]} entries={entries} height={9999} />)+ expect((container.firstChild as HTMLElement).style.height).toBe('100%')+ })++ it('FE-COMP-JMAPGL-036: the token placeholder honours the height prop', () => {+ const { container } = render(<JourneyMapGL checkins={[]} entries={entries} height={9999} />)+ expect((container.firstChild as HTMLElement).style.height).toBe('100%')+ })+})diff --git a/client/src/components/Journey/JourneyShareSection.test.tsx b/client/src/components/Journey/JourneyShareSection.test.tsxnew file mode 100644index 000000000..d08f0f19c--- /dev/null+++ b/client/src/components/Journey/JourneyShareSection.test.tsx@@ -0,0 +1,182 @@+// FE-JRN-SHARE-001 to FE-JRN-SHARE-011++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { http, HttpResponse, delay } from 'msw'+import { render, screen, waitFor, act } from '../../../tests/helpers/render'+import { server } from '../../../tests/helpers/msw/server'+import JourneyShareSection from './JourneyShareSection'++type ToastKind = 'success' | 'error' | 'warning' | 'info'++const toastSpy = vi.fn((_message: string, _type?: ToastKind, _duration?: number) => 0)+const writeText = vi.fn(async (_text: string) => {})++const JOURNEY_ID = 7++function existingLink(overrides: Record<string, unknown> = {}) {+ return { token: 'tok-abc', share_timeline: true, share_gallery: false, share_map: true, ...overrides }+}++beforeEach(() => {+ toastSpy.mockClear()+ writeText.mockClear()+ window.__addToast = toastSpy+ Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true, writable: true })+})++afterEach(() => {+ delete window.__addToast+})++describe('JourneyShareSection', () => {+ it('FE-JRN-SHARE-001: offers to create a link when the journey has none', async () => {+ server.use(http.get('/api/journeys/7/share-link', () => HttpResponse.json({ link: null })))+ render(<JourneyShareSection journeyId={JOURNEY_ID} />)++ expect(await screen.findByRole('button', { name: /create share link/i })).toBeInTheDocument()+ expect(screen.getByText('Public Share')).toBeInTheDocument()+ })++ it('FE-JRN-SHARE-002: renders nothing while the share link is still loading', async () => {+ server.use(http.get('/api/journeys/7/share-link', async () => {+ await delay(30)+ return HttpResponse.json({ link: null })+ }))++ const { container } = render(<JourneyShareSection journeyId={JOURNEY_ID} />)+ expect(container).toBeEmptyDOMElement()++ await screen.findByRole('button', { name: /create share link/i })+ })++ it('FE-JRN-SHARE-003: creates a link and shows the public URL', async () => {+ server.use(+ http.get('/api/journeys/7/share-link', () => HttpResponse.json({ link: null })),+ http.post('/api/journeys/7/share-link', () => HttpResponse.json({ token: 'fresh-token' })),+ )+ render(<JourneyShareSection journeyId={JOURNEY_ID} />)++ const createBtn = await screen.findByRole('button', { name: /create share link/i })+ act(() => { createBtn.click() })++ expect(await screen.findByText(`${window.location.origin}/public/journey/fresh-token`)).toBeInTheDocument()+ expect(toastSpy).toHaveBeenCalledWith('Share link created', 'success', undefined)+ })++ it('FE-JRN-SHARE-004: warns when creating the link fails', async () => {+ server.use(+ http.get('/api/journeys/7/share-link', () => HttpResponse.json({ link: null })),+ http.post('/api/journeys/7/share-link', () => new HttpResponse(null, { status: 500 })),+ )+ render(<JourneyShareSection journeyId={JOURNEY_ID} />)++ const createBtn = await screen.findByRole('button', { name: /create share link/i })+ act(() => { createBtn.click() })++ await waitFor(() => {+ expect(toastSpy).toHaveBeenCalledWith('Failed to create link', 'error', undefined)+ })+ expect(screen.getByRole('button', { name: /create share link/i })).toBeInTheDocument()+ })++ it('FE-JRN-SHARE-005: renders the permission toggles in the state the link reports', async () => {+ server.use(http.get('/api/journeys/7/share-link', () => HttpResponse.json({ link: existingLink() })))+ render(<JourneyShareSection journeyId={JOURNEY_ID} />)++ const timeline = await screen.findByRole('button', { name: 'Timeline' })+ expect(timeline.className).toContain('bg-zinc-900')+ expect(screen.getByRole('button', { name: 'Map' }).className).toContain('bg-zinc-900')+ expect(screen.getByRole('button', { name: 'Gallery' }).className).not.toContain('bg-zinc-900')+ expect(screen.getByText(`${window.location.origin}/public/journey/tok-abc`)).toBeInTheDocument()+ })++ it('FE-JRN-SHARE-006: copies the URL and resets the button label after two seconds', async () => {+ server.use(http.get('/api/journeys/7/share-link', () => HttpResponse.json({ link: existingLink() })))+ vi.useFakeTimers({ shouldAdvanceTime: true })+ try {+ render(<JourneyShareSection journeyId={JOURNEY_ID} />)+ const copyBtn = await screen.findByRole('button', { name: 'Copy' })+ act(() => { copyBtn.click() })++ expect(writeText).toHaveBeenCalledWith(`${window.location.origin}/public/journey/tok-abc`)+ expect(screen.getByRole('button', { name: 'Copied!' })).toBeInTheDocument()++ act(() => { vi.advanceTimersByTime(2100) })+ expect(screen.getByRole('button', { name: 'Copy' })).toBeInTheDocument()+ } finally {+ vi.useRealTimers()+ }+ })++ it('FE-JRN-SHARE-007: toggling a permission posts the updated flag set', async () => {+ const bodies: Record<string, unknown>[] = []+ server.use(+ http.get('/api/journeys/7/share-link', () => HttpResponse.json({ link: existingLink() })),+ http.post('/api/journeys/7/share-link', async ({ request }) => {+ bodies.push(await request.json() as Record<string, unknown>)+ return HttpResponse.json({ token: 'tok-abc' })+ }),+ )+ render(<JourneyShareSection journeyId={JOURNEY_ID} />)++ const gallery = await screen.findByRole('button', { name: 'Gallery' })+ act(() => { gallery.click() })++ await waitFor(() => expect(bodies).toHaveLength(1))+ expect(bodies[0]).toEqual({ share_timeline: true, share_gallery: true, share_map: true })+ expect(screen.getByRole('button', { name: 'Gallery' }).className).toContain('bg-zinc-900')+ })++ it('FE-JRN-SHARE-008: reverts the toggle when the update request fails', async () => {+ server.use(+ http.get('/api/journeys/7/share-link', () => HttpResponse.json({ link: existingLink() })),+ http.post('/api/journeys/7/share-link', () => new HttpResponse(null, { status: 500 })),+ )+ render(<JourneyShareSection journeyId={JOURNEY_ID} />)++ const timeline = await screen.findByRole('button', { name: 'Timeline' })+ act(() => { timeline.click() })++ await waitFor(() => {+ expect(toastSpy).toHaveBeenCalledWith('Failed to update', 'error', undefined)+ })+ expect(screen.getByRole('button', { name: 'Timeline' }).className).toContain('bg-zinc-900')+ })++ it('FE-JRN-SHARE-009: deleting the link returns to the create state', async () => {+ server.use(+ http.get('/api/journeys/7/share-link', () => HttpResponse.json({ link: existingLink() })),+ http.delete('/api/journeys/7/share-link', () => HttpResponse.json({ ok: true })),+ )+ render(<JourneyShareSection journeyId={JOURNEY_ID} />)++ const deleteBtn = await screen.findByRole('button', { name: 'Delete link' })+ act(() => { deleteBtn.click() })++ expect(await screen.findByRole('button', { name: /create share link/i })).toBeInTheDocument()+ expect(toastSpy).toHaveBeenCalledWith('Share link deleted', 'success', undefined)+ })++ it('FE-JRN-SHARE-010: warns and keeps the link when deleting fails', async () => {+ server.use(+ http.get('/api/journeys/7/share-link', () => HttpResponse.json({ link: existingLink() })),+ http.delete('/api/journeys/7/share-link', () => new HttpResponse(null, { status: 500 })),+ )+ render(<JourneyShareSection journeyId={JOURNEY_ID} />)++ const deleteBtn = await screen.findByRole('button', { name: 'Delete link' })+ act(() => { deleteBtn.click() })++ await waitFor(() => {+ expect(toastSpy).toHaveBeenCalledWith('Failed to delete', 'error', undefined)+ })+ expect(screen.getByRole('button', { name: 'Delete link' })).toBeInTheDocument()+ })++ it('FE-JRN-SHARE-011: falls back to the create state when the link cannot be loaded', async () => {+ server.use(http.get('/api/journeys/7/share-link', () => new HttpResponse(null, { status: 500 })))+ render(<JourneyShareSection journeyId={JOURNEY_ID} />)++ expect(await screen.findByRole('button', { name: /create share link/i })).toBeInTheDocument()+ })+})diff --git a/client/src/components/Journey/MobileEntryCard.test.tsx b/client/src/components/Journey/MobileEntryCard.test.tsxnew file mode 100644index 000000000..bedf35b7c--- /dev/null+++ b/client/src/components/Journey/MobileEntryCard.test.tsx@@ -0,0 +1,178 @@+// FE-COMP-JENTRYCARD-001 to FE-COMP-JENTRYCARD-014++import { render, screen, fireEvent } from '../../../tests/helpers/render'+import { resetAllStores } from '../../../tests/helpers/store'+import MobileEntryCard from './MobileEntryCard'++type CardEntry = Parameters<typeof MobileEntryCard>[0]['entry']++function buildEntry(overrides: Partial<Record<string, unknown>> = {}): CardEntry {+ return {+ id: 1,+ type: 'entry',+ title: 'Sunrise over the fjord',+ location_name: 'Geiranger, Møre og Romsdal, Norway',+ location_lat: 62.1,+ location_lng: 7.2,+ entry_date: '2025-06-01',+ entry_time: '07:30:00',+ mood: null,+ weather: null,+ photos: [],+ story: null,+ ...overrides,+ } as unknown as CardEntry+}++function renderCard(entry: CardEntry, props: Partial<{ isActive: boolean; onClick: () => void; publicPhotoUrl: (id: number) => string; dayLabel: number; dayColor: string }> = {}) {+ const onClick = props.onClick ?? vi.fn()+ const result = render(+ <MobileEntryCard+ entry={entry}+ dayLabel={props.dayLabel ?? 3}+ dayColor={props.dayColor ?? '#ff0055'}+ isActive={props.isActive ?? false}+ onClick={onClick}+ publicPhotoUrl={props.publicPhotoUrl}+ />,+ )+ return { ...result, onClick }+}++beforeEach(() => {+ resetAllStores()+})++describe('MobileEntryCard', () => {+ it('FE-COMP-JENTRYCARD-001: shows the day badge, date and time', () => {+ renderCard(buildEntry())+ const badge = screen.getByText('3')+ expect(badge).toHaveStyle({ background: '#ff0055' })+ expect(screen.getByText('Jun 1')).toBeInTheDocument()+ // seconds are trimmed off the stored time+ expect(screen.getByText('· 07:30')).toBeInTheDocument()+ })++ it('FE-COMP-JENTRYCARD-002: an entry without a time shows only the date', () => {+ renderCard(buildEntry({ entry_time: null }))+ expect(screen.queryByText(/·/)).not.toBeInTheDocument()+ })++ it('FE-COMP-JENTRYCARD-003: renders the first photo thumbnail from the api', () => {+ const { container } = renderCard(buildEntry({ photos: [{ photo_id: 42 }, { photo_id: 43 }] }))+ expect(container.querySelector('img')).toHaveAttribute('src', '/api/photos/42/thumbnail')+ })++ it('FE-COMP-JENTRYCARD-004: a public journey builds its own photo url', () => {+ const publicPhotoUrl = (id: number) => `/public/p/${id}.jpg`+ const { container } = renderCard(buildEntry({ photos: [{ photo_id: 7 }] }), { publicPhotoUrl })+ expect(container.querySelector('img')).toHaveAttribute('src', '/public/p/7.jpg')+ })++ it('FE-COMP-JENTRYCARD-004b: a shared-journey photo carrying only an id still resolves', () => {+ const publicPhotoUrl = (id: number) => `/public/p/${id}.jpg`+ const { container } = renderCard(buildEntry({ photos: [{ id: 11 }] }), { publicPhotoUrl })+ expect(container.querySelector('img')).toHaveAttribute('src', '/public/p/11.jpg')+ })++ it('FE-COMP-JENTRYCARD-005: several photos add a counter badge', () => {+ const { container } = renderCard(+ buildEntry({ photos: [{ photo_id: 1 }, { photo_id: 2 }, { photo_id: 3 }] }),+ { dayLabel: 9 },+ )+ expect(container.querySelector('svg.lucide-camera')).not.toBeNull()+ expect(screen.getByText('3')).toBeInTheDocument()+ })++ it('FE-COMP-JENTRYCARD-006: a single photo has no counter badge', () => {+ const { container } = renderCard(buildEntry({ photos: [{ photo_id: 1 }] }))+ expect(container.querySelector('svg.lucide-camera')).toBeNull()+ })++ it('FE-COMP-JENTRYCARD-007: without photos it falls back to a pin placeholder', () => {+ const { container } = renderCard(buildEntry())+ expect(container.querySelector('img')).toBeNull()+ expect(container.querySelectorAll('svg.lucide-map-pin').length).toBeGreaterThan(0)+ })++ it('FE-COMP-JENTRYCARD-008: mood and weather render their own icons', () => {+ const { container } = renderCard(buildEntry({ mood: 'amazing', weather: 'rainy' }))+ expect(container.querySelector('svg.lucide-laugh')).not.toBeNull()+ expect(container.querySelector('svg.lucide-cloud-rain')).not.toBeNull()+ })++ it('FE-COMP-JENTRYCARD-008b: every known mood gets its own chip colour', () => {+ const cases: [string, string, string][] = [+ ['good', 'lucide-smile', 'bg-amber-100'],+ ['neutral', 'lucide-meh', 'bg-zinc-100'],+ ['rough', 'lucide-frown', 'bg-violet-100'],+ ]+ for (const [mood, icon, bg] of cases) {+ const { container, unmount } = renderCard(buildEntry({ mood }))+ const chip = container.querySelector(`svg.${icon}`)!.parentElement!+ expect(chip.className).toContain(bg)+ unmount()+ }+ })++ it('FE-COMP-JENTRYCARD-009: an unknown mood renders no mood icon', () => {+ const { container } = renderCard(buildEntry({ mood: 'ecstatic' }))+ expect(container.querySelector('svg.lucide-laugh')).toBeNull()+ expect(container.querySelector('svg.lucide-smile')).toBeNull()+ })++ it('FE-COMP-JENTRYCARD-010: untitled entries fall back to a type-specific label', () => {+ const { unmount } = renderCard(buildEntry({ title: null, type: 'checkin' }))+ expect(screen.getByText('Check-in')).toBeInTheDocument()+ unmount()++ const skeleton = renderCard(buildEntry({ title: null, type: 'skeleton' }))+ expect(screen.getByText('Add your story…')).toBeInTheDocument()+ skeleton.unmount()++ renderCard(buildEntry({ title: '', type: 'entry' }))+ expect(screen.getByText('Untitled')).toBeInTheDocument()+ })++ it('FE-COMP-JENTRYCARD-011: the story preview only appears on the active card, stripped of markdown', () => {+ const story = '## Day one\n\nWe **walked** to the pier'+ const inactive = renderCard(buildEntry({ story }))+ expect(screen.queryByText(/We walked to the pier/)).not.toBeInTheDocument()+ inactive.unmount()++ renderCard(buildEntry({ story }), { isActive: true })+ expect(screen.getByText('Day one We walked to the pier')).toBeInTheDocument()+ })++ it('FE-COMP-JENTRYCARD-012: the location badge shortens a long location name', () => {+ renderCard(buildEntry())+ // formatLocationName collapses the 3+ part name+ expect(screen.getByText('Geiranger, Møre og Romsdal, Norway')).toBeInTheDocument()+ })++ it('FE-COMP-JENTRYCARD-013: a located entry without a name still says it is on the map', () => {+ renderCard(buildEntry({ location_name: null }))+ expect(screen.getByText('On the map')).toBeInTheDocument()+ })++ it('FE-COMP-JENTRYCARD-014: an entry without coordinates is marked as unlocated', () => {+ renderCard(buildEntry({ location_lat: null, location_lng: null }))+ expect(screen.getByText('No location')).toBeInTheDocument()+ })++ it('FE-COMP-JENTRYCARD-015: tapping the card calls back', () => {+ const onClick = vi.fn()+ renderCard(buildEntry(), { onClick })+ fireEvent.click(screen.getByRole('button'))+ expect(onClick).toHaveBeenCalledTimes(1)+ })++ it('FE-COMP-JENTRYCARD-016: the active card grows', () => {+ const inactive = renderCard(buildEntry())+ expect(screen.getByRole('button').className).toContain('w-[240px]')+ inactive.unmount()++ renderCard(buildEntry(), { isActive: true })+ expect(screen.getByRole('button').className).toContain('w-[320px]')+ })+})diff --git a/client/src/components/Journey/MobileEntryView.test.tsx b/client/src/components/Journey/MobileEntryView.test.tsxnew file mode 100644index 000000000..5873f47f3--- /dev/null+++ b/client/src/components/Journey/MobileEntryView.test.tsx@@ -0,0 +1,215 @@+// FE-COMP-JENTRYVIEW-001 to FE-COMP-JENTRYVIEW-017++import { render, screen, fireEvent } from '../../../tests/helpers/render'+import { resetAllStores } from '../../../tests/helpers/store'+import MobileEntryView from './MobileEntryView'+import type { JourneyEntry, JourneyPhoto } from '../../store/journeyStore'++function buildPhoto(photoId: number): JourneyPhoto {+ return {+ id: photoId * 10,+ entry_id: 1,+ photo_id: photoId,+ caption: null,+ sort_order: photoId,+ shared: 0,+ created_at: 0,+ }+}++function buildEntry(overrides: Record<string, unknown> = {}): JourneyEntry {+ return {+ id: 1,+ journey_id: 1,+ author_id: 1,+ type: 'entry',+ title: 'Sunrise over the fjord',+ story: null,+ entry_date: '2025-06-01',+ entry_time: '07:30:00',+ location_name: 'Geiranger, Norway',+ location_lat: 62.1,+ location_lng: 7.2,+ mood: null,+ weather: null,+ tags: [],+ pros_cons: null,+ visibility: 'private',+ sort_order: 0,+ photos: [],+ created_at: 0,+ updated_at: 0,+ ...overrides,+ } as unknown as JourneyEntry+}++interface ViewProps {+ readOnly: boolean+ publicPhotoUrl: (photoId: number) => string+ onClose: () => void+ onEdit: () => void+ onDelete: () => void+ onPhotoClick: (photos: JourneyPhoto[], index: number) => void+}++function renderView(entry: JourneyEntry, props: Partial<ViewProps> = {}) {+ const handlers = {+ onClose: props.onClose ?? vi.fn(),+ onEdit: props.onEdit ?? vi.fn(),+ onDelete: props.onDelete ?? vi.fn(),+ onPhotoClick: props.onPhotoClick ?? vi.fn(),+ }+ const result = render(+ <MobileEntryView+ entry={entry}+ readOnly={props.readOnly}+ publicPhotoUrl={props.publicPhotoUrl}+ {...handlers}+ />,+ )+ return { ...result, ...handlers }+}++beforeEach(() => {+ resetAllStores()+})++describe('MobileEntryView', () => {+ it('FE-COMP-JENTRYVIEW-001: renders the header with the long date, time and location', () => {+ renderView(buildEntry())+ expect(screen.getByText('Sunday, June 1')).toBeInTheDocument()+ expect(screen.getByText('07:30')).toBeInTheDocument()+ expect(screen.getByText('Geiranger, Norway')).toBeInTheDocument()+ expect(screen.getByRole('heading', { name: 'Sunrise over the fjord' })).toBeInTheDocument()+ })++ it('FE-COMP-JENTRYVIEW-002: an entry without time, location or title renders none of them', () => {+ const { container } = renderView(buildEntry({ entry_time: null, location_name: null, title: null }))+ expect(container.querySelector('h1')).toBeNull()+ expect(container.querySelector('svg.lucide-clock')).toBeNull()+ expect(container.querySelector('svg.lucide-map-pin')).toBeNull()+ })++ it('FE-COMP-JENTRYVIEW-003: the close button calls back', () => {+ const { onClose, container } = renderView(buildEntry())+ fireEvent.click(container.querySelector('svg.lucide-x')!.closest('button')!)+ expect(onClose).toHaveBeenCalledTimes(1)+ })++ it('FE-COMP-JENTRYVIEW-004: edit closes the sheet first, then opens the editor', () => {+ const order: string[] = []+ const onClose = vi.fn(() => { order.push('close') })+ const onEdit = vi.fn(() => { order.push('edit') })+ renderView(buildEntry(), { onClose, onEdit })++ fireEvent.click(screen.getByRole('button', { name: /Edit/ }))++ expect(order).toEqual(['close', 'edit'])+ })++ it('FE-COMP-JENTRYVIEW-005: delete closes the sheet first, then asks to delete', () => {+ const order: string[] = []+ const onClose = vi.fn(() => { order.push('close') })+ const onDelete = vi.fn(() => { order.push('delete') })+ const { container } = renderView(buildEntry(), { onClose, onDelete })++ fireEvent.click(container.querySelector('svg.lucide-trash2')!.closest('button')!)++ expect(order).toEqual(['close', 'delete'])+ })++ it('FE-COMP-JENTRYVIEW-006: read-only journeys hide the edit and delete actions', () => {+ const { container } = renderView(buildEntry(), { readOnly: true })+ expect(screen.queryByRole('button', { name: /Edit/ })).not.toBeInTheDocument()+ expect(container.querySelector('svg.lucide-trash2')).toBeNull()+ // the close button stays+ expect(container.querySelector('svg.lucide-x')).not.toBeNull()+ })++ it('FE-COMP-JENTRYVIEW-007: a single photo renders as the hero without a strip or counter', () => {+ const { container } = renderView(buildEntry({ photos: [buildPhoto(4)] }))+ const images = container.querySelectorAll('img')+ expect(images).toHaveLength(1)+ expect(images[0]).toHaveAttribute('src', '/api/photos/4/original')+ expect(container.querySelector('svg.lucide-camera')).toBeNull()+ })++ it('FE-COMP-JENTRYVIEW-008: several photos add a counter and a thumbnail strip', () => {+ const { container } = renderView(buildEntry({ photos: [buildPhoto(4), buildPhoto(5), buildPhoto(6)] }))+ expect(screen.getByText('3 photos')).toBeInTheDocument()+ const images = container.querySelectorAll('img')+ // hero + one thumbnail per photo+ expect(images).toHaveLength(4)+ expect(images[1]).toHaveAttribute('src', '/api/photos/4/thumbnail')+ })++ it('FE-COMP-JENTRYVIEW-009: tapping the hero and a thumbnail opens the lightbox at that index', () => {+ const onPhotoClick = vi.fn()+ const photos = [buildPhoto(4), buildPhoto(5)]+ const { container } = renderView(buildEntry({ photos }), { onPhotoClick })+ const images = container.querySelectorAll('img')++ fireEvent.click(images[0])+ expect(onPhotoClick).toHaveBeenLastCalledWith(photos, 0)++ fireEvent.click(images[2])+ expect(onPhotoClick).toHaveBeenLastCalledWith(photos, 1)+ })++ it('FE-COMP-JENTRYVIEW-010: a public journey builds its own photo urls', () => {+ const { container } = renderView(+ buildEntry({ photos: [buildPhoto(4), buildPhoto(5)] }),+ { publicPhotoUrl: (id: number) => `/public/p/${id}.jpg` },+ )+ const images = container.querySelectorAll('img')+ expect(images[0]).toHaveAttribute('src', '/public/p/4.jpg')+ expect(images[1]).toHaveAttribute('src', '/public/p/4.jpg')+ })++ it('FE-COMP-JENTRYVIEW-011: mood and weather render as labelled chips', () => {+ const { container } = renderView(buildEntry({ mood: 'rough', weather: 'stormy' }))+ expect(screen.getByText('Rough')).toBeInTheDocument()+ expect(screen.getByText('Stormy')).toBeInTheDocument()+ expect(container.querySelector('svg.lucide-frown')).not.toBeNull()+ expect(container.querySelector('svg.lucide-cloud-lightning')).not.toBeNull()+ })++ it('FE-COMP-JENTRYVIEW-012: unknown mood and weather values render no chips', () => {+ renderView(buildEntry({ mood: 'ecstatic', weather: 'hail' }))+ expect(screen.queryByText('Rough')).not.toBeInTheDocument()+ expect(screen.queryByText('Stormy')).not.toBeInTheDocument()+ })++ it('FE-COMP-JENTRYVIEW-013: the story is rendered as markdown body copy', () => {+ renderView(buildEntry({ story: 'We **walked** to the pier' }))+ expect(screen.getByText('walked').tagName).toBe('STRONG')+ })++ it('FE-COMP-JENTRYVIEW-014: tags render as chips', () => {+ renderView(buildEntry({ tags: ['hiking', 'fjord'] }))+ expect(screen.getByText('hiking')).toBeInTheDocument()+ expect(screen.getByText('fjord')).toBeInTheDocument()+ })++ it('FE-COMP-JENTRYVIEW-015: pros and cons render both lists with a divider', () => {+ const { container } = renderView(buildEntry({ pros_cons: { pros: ['great light'], cons: ['very cold'] } }))+ expect(screen.getByText('Pros')).toBeInTheDocument()+ expect(screen.getByText('Cons')).toBeInTheDocument()+ expect(screen.getByText('great light')).toBeInTheDocument()+ expect(screen.getByText('very cold')).toBeInTheDocument()+ expect(container.querySelector('svg.lucide-thumbs-up')).not.toBeNull()+ expect(container.querySelector('svg.lucide-thumbs-down')).not.toBeNull()+ })++ it('FE-COMP-JENTRYVIEW-016: a cons-only entry skips the pros block', () => {+ renderView(buildEntry({ pros_cons: { pros: [], cons: ['very cold'] } }))+ expect(screen.queryByText('Pros')).not.toBeInTheDocument()+ expect(screen.getByText('Cons')).toBeInTheDocument()+ })++ it('FE-COMP-JENTRYVIEW-017: an empty pros/cons block is not rendered at all', () => {+ renderView(buildEntry({ pros_cons: { pros: [], cons: [] } }))+ expect(screen.queryByText('Pros')).not.toBeInTheDocument()+ expect(screen.queryByText('Cons')).not.toBeInTheDocument()+ })+})diff --git a/client/src/components/Journey/MobileMapTimeline.test.tsx b/client/src/components/Journey/MobileMapTimeline.test.tsxnew file mode 100644index 000000000..eaaa18faf--- /dev/null+++ b/client/src/components/Journey/MobileMapTimeline.test.tsx@@ -0,0 +1,318 @@+// FE-COMP-JMAPTL-001 to FE-COMP-JMAPTL-016++const mapHandle = vi.hoisted(() => ({+ highlightMarker: vi.fn(),+ focusMarker: vi.fn(),+ invalidateSize: vi.fn(),+}))++const lastMapProps = vi.hoisted(() => ({ current: {} as Record<string, unknown> }))++// The Leaflet map is exercised in JourneyMap.test.tsx — here it only needs to+// hand back its imperative handle and expose the props it was given.+vi.mock('./JourneyMap', async () => {+ const React = await import('react')+ return {+ default: React.forwardRef(function MockJourneyMap(+ props: Record<string, unknown>,+ ref: React.ForwardedRef<typeof mapHandle>,+ ) {+ lastMapProps.current = props+ React.useImperativeHandle(ref, () => mapHandle, [])+ return React.createElement('div', { 'data-testid': 'journey-map' })+ }),+ }+})++import { render, screen, fireEvent, act } from '../../../tests/helpers/render'+import { resetAllStores } from '../../../tests/helpers/store'+import MobileMapTimeline from './MobileMapTimeline'+import { DAY_COLORS } from './dayColors'++interface TimelineEntry {+ id: number+ type: string+ title: string+ entry_date: string+ entry_time: string | null+ location_name: string | null+ location_lat: number | null+ location_lng: number | null+ mood: string | null+ weather: string | null+ photos: { photo_id: number }[]+ story: string | null+}++function buildEntry(id: number, date: string, title: string): TimelineEntry {+ return {+ id,+ type: 'entry',+ title,+ entry_date: date,+ entry_time: null,+ location_name: 'Somewhere',+ location_lat: 48 + id,+ location_lng: 2 + id,+ mood: null,+ weather: null,+ photos: [],+ story: null,+ }+}++const entries = [+ buildEntry(1, '2025-06-01', 'Louvre'),+ buildEntry(2, '2025-06-02', 'Museumsinsel'),+ buildEntry(3, '2025-06-02', 'Reichstag'),+]++const mapEntries = entries.map(e => ({+ id: String(e.id),+ lat: e.location_lat!,+ lng: e.location_lng!,+ title: e.title,+ mood: null,+ entry_date: e.entry_date,+}))++function fakeRect(left: number, width: number): DOMRect {+ return {+ left, width, right: left + width, top: 0, bottom: 0, height: 0, x: left, y: 0,+ toJSON: () => ({}),+ } as DOMRect+}++function carouselOf(container: HTMLElement) {+ const carousel = container.querySelector('.overflow-x-auto') as HTMLElement+ const cards = [...carousel.children] as HTMLElement[]+ return { carousel, cards }+}++function renderTimeline(props: Partial<{+ entries: TimelineEntry[]+ onEntryClick: (entry: TimelineEntry) => void+ onAddEntry: () => void+ readOnly: boolean+ carouselBottom: string+}> = {}) {+ const onEntryClick = props.onEntryClick ?? vi.fn()+ const result = render(+ <MobileMapTimeline+ entries={props.entries ?? entries}+ mapEntries={mapEntries}+ onEntryClick={onEntryClick}+ onAddEntry={props.onAddEntry}+ readOnly={props.readOnly}+ carouselBottom={props.carouselBottom}+ />,+ )+ return { ...result, onEntryClick }+}++beforeEach(() => {+ resetAllStores()+ vi.clearAllMocks()+})++describe('MobileMapTimeline', () => {+ it('FE-COMP-JMAPTL-001: renders one card per entry on top of a full-screen map', () => {+ renderTimeline()+ expect(screen.getByTestId('journey-map')).toBeInTheDocument()+ expect(lastMapProps.current).toMatchObject({ height: 9999, fullScreen: true, paddingBottom: 200 })+ expect(screen.getByText('Louvre')).toBeInTheDocument()+ expect(screen.getByText('Museumsinsel')).toBeInTheDocument()+ expect(screen.getByText('Reichstag')).toBeInTheDocument()+ })++ it('FE-COMP-JMAPTL-002: entries on the same day share a colour and count up', () => {+ const { container } = renderTimeline()+ const { cards } = carouselOf(container)+ const badge = (card: HTMLElement) => card.querySelector('span[style]') as HTMLElement++ expect(badge(cards[0]).textContent).toBe('1')+ expect(badge(cards[0])).toHaveStyle({ background: DAY_COLORS[0] })+ // second day, first and second entry of that day+ expect(badge(cards[1]).textContent).toBe('1')+ expect(badge(cards[2]).textContent).toBe('2')+ expect(badge(cards[1])).toHaveStyle({ background: DAY_COLORS[1] })+ expect(badge(cards[2])).toHaveStyle({ background: DAY_COLORS[1] })+ })++ it('FE-COMP-JMAPTL-003: the first entry starts out active and drives the map highlight', () => {+ renderTimeline()+ expect(lastMapProps.current.activeMarkerId).toBe('1')+ })++ it('FE-COMP-JMAPTL-004: tapping an inactive card only activates it', () => {+ const onEntryClick = vi.fn()+ renderTimeline({ onEntryClick })++ fireEvent.click(screen.getByText('Reichstag'))++ expect(onEntryClick).not.toHaveBeenCalled()+ expect(lastMapProps.current.activeMarkerId).toBe('3')+ expect(Element.prototype.scrollIntoView).toHaveBeenCalledWith(+ expect.objectContaining({ inline: 'center', behavior: 'smooth' }),+ )+ })++ it('FE-COMP-JMAPTL-005: tapping the already active card opens the entry', () => {+ const onEntryClick = vi.fn()+ renderTimeline({ onEntryClick })++ fireEvent.click(screen.getByText('Louvre'))++ expect(onEntryClick).toHaveBeenCalledWith(entries[0])+ })++ it('FE-COMP-JMAPTL-006: clicking a map marker centres the matching card', () => {+ renderTimeline()+ const onMarkerClick = lastMapProps.current.onMarkerClick as (id: string) => void++ act(() => { onMarkerClick('2') })++ expect(lastMapProps.current.activeMarkerId).toBe('2')+ expect(Element.prototype.scrollIntoView).toHaveBeenCalled()+ })++ it('FE-COMP-JMAPTL-007: a marker click for an unknown entry is ignored', () => {+ renderTimeline()+ const onMarkerClick = lastMapProps.current.onMarkerClick as (id: string) => void++ act(() => { onMarkerClick('999') })++ expect(lastMapProps.current.activeMarkerId).toBe('1')+ expect(Element.prototype.scrollIntoView).not.toHaveBeenCalled()+ })++ it('FE-COMP-JMAPTL-008: the map is focused on the first entry once leaflet has settled', () => {+ vi.useFakeTimers()+ try {+ renderTimeline()+ expect(mapHandle.focusMarker).not.toHaveBeenCalled()+ act(() => { vi.advanceTimersByTime(500) })+ expect(mapHandle.focusMarker).toHaveBeenCalledWith('1')+ } finally {+ vi.useRealTimers()+ }+ })++ it('FE-COMP-JMAPTL-009: an entry that has no marker clears the highlight instead', () => {+ vi.useFakeTimers()+ try {+ renderTimeline({ entries: [buildEntry(77, '2025-06-01', 'Unmapped')] })+ act(() => { vi.advanceTimersByTime(500) })+ expect(mapHandle.focusMarker).not.toHaveBeenCalled()+ expect(mapHandle.highlightMarker).toHaveBeenCalledWith(null)+ } finally {+ vi.useRealTimers()+ }+ })++ it('FE-COMP-JMAPTL-010: a settled carousel scroll activates the card nearest the centre', () => {+ vi.useFakeTimers()+ try {+ const { container } = renderTimeline()+ const { carousel, cards } = carouselOf(container)+ Object.defineProperty(carousel, 'clientWidth', { value: 300, configurable: true })+ carousel.getBoundingClientRect = () => fakeRect(0, 300)+ cards[0].getBoundingClientRect = () => fakeRect(-400, 240)+ cards[1].getBoundingClientRect = () => fakeRect(30, 240)+ cards[2].getBoundingClientRect = () => fakeRect(320, 240)++ fireEvent.scroll(carousel)+ // nothing happens mid-swipe, only once scrolling settles+ expect(mapHandle.focusMarker).not.toHaveBeenCalled()+ act(() => { vi.advanceTimersByTime(200) })++ expect(mapHandle.focusMarker).toHaveBeenCalledWith('2')+ expect(lastMapProps.current.activeMarkerId).toBe('2')+ } finally {+ vi.useRealTimers()+ }+ })++ it('FE-COMP-JMAPTL-011: repeated scrolls restart the settle timer', () => {+ vi.useFakeTimers()+ try {+ const { container } = renderTimeline()+ const { carousel, cards } = carouselOf(container)+ Object.defineProperty(carousel, 'clientWidth', { value: 300, configurable: true })+ carousel.getBoundingClientRect = () => fakeRect(0, 300)+ cards.forEach((c, i) => { c.getBoundingClientRect = () => fakeRect(i === 2 ? 30 : -400, 240) })++ fireEvent.scroll(carousel)+ act(() => { vi.advanceTimersByTime(100) })+ fireEvent.scroll(carousel)+ act(() => { vi.advanceTimersByTime(100) })+ expect(lastMapProps.current.activeMarkerId).toBe('1')++ act(() => { vi.advanceTimersByTime(100) })+ expect(lastMapProps.current.activeMarkerId).toBe('3')+ } finally {+ vi.useRealTimers()+ }+ })++ it('FE-COMP-JMAPTL-012: settling on the card that was already active does not refocus the map', () => {+ vi.useFakeTimers()+ try {+ const { container } = renderTimeline()+ act(() => { vi.advanceTimersByTime(500) })+ mapHandle.focusMarker.mockClear()++ const { carousel, cards } = carouselOf(container)+ Object.defineProperty(carousel, 'clientWidth', { value: 300, configurable: true })+ carousel.getBoundingClientRect = () => fakeRect(0, 300)+ cards.forEach((c, i) => { c.getBoundingClientRect = () => fakeRect(i === 0 ? 30 : 900, 240) })++ fireEvent.scroll(carousel)+ act(() => { vi.advanceTimersByTime(200) })++ expect(mapHandle.focusMarker).not.toHaveBeenCalled()+ } finally {+ vi.useRealTimers()+ }+ })++ it('FE-COMP-JMAPTL-013: the add button reports back and can be hidden', () => {+ const onAddEntry = vi.fn()+ const withFab = renderTimeline({ onAddEntry })+ fireEvent.click(screen.getByRole('button', { name: '' }))+ expect(onAddEntry).toHaveBeenCalledTimes(1)+ withFab.unmount()++ renderTimeline({ onAddEntry, readOnly: true })+ expect(screen.queryByRole('button', { name: '' })).not.toBeInTheDocument()+ })++ it('FE-COMP-JMAPTL-014: carouselBottom positions the strip above the tab bar', () => {+ const { container } = renderTimeline({ carouselBottom: '120px' })+ const strip = container.querySelector('.z-40') as HTMLElement+ expect(strip.style.bottom).toBe('120px')+ })++ it('FE-COMP-JMAPTL-015: an empty journey shows only the map and the add button', () => {+ const onAddEntry = vi.fn()+ const { container } = renderTimeline({ entries: [], onAddEntry })++ expect(screen.getByTestId('journey-map')).toBeInTheDocument()+ expect(container.querySelector('.overflow-x-auto')).toBeNull()+ // no card is active, so the map gets no highlight to chase+ expect(lastMapProps.current.activeMarkerId).toBeUndefined()++ fireEvent.click(screen.getByRole('button', { name: '' }))+ expect(onAddEntry).toHaveBeenCalledTimes(1)+ })++ it('FE-COMP-JMAPTL-016: an empty read-only journey has no add button', () => {+ renderTimeline({ entries: [], onAddEntry: vi.fn(), readOnly: true })+ expect(screen.queryByRole('button', { name: '' })).not.toBeInTheDocument()+ })++ it('FE-COMP-JMAPTL-017: without an add handler no button is rendered at all', () => {+ renderTimeline({ entries: [] })+ expect(screen.queryByRole('button', { name: '' })).not.toBeInTheDocument()+ })+})diff --git a/client/src/components/Journey/PhotoLightbox.test.tsx b/client/src/components/Journey/PhotoLightbox.test.tsxindex 4d5d8d62f..a2dceb702 100644--- a/client/src/components/Journey/PhotoLightbox.test.tsx+++ b/client/src/components/Journey/PhotoLightbox.test.tsx@@ -1,4 +1,9 @@-// FE-COMP-LIGHTBOX-001 to FE-COMP-LIGHTBOX-008+// FE-COMP-LIGHTBOX-001 to FE-COMP-LIGHTBOX-017++// Plyr needs a real media pipeline, so the player is stubbed here.+vi.mock('./VideoPlayer', () => ({+ default: ({ src }: { src: string }) => <video data-testid="video-player" src={src} />,+}));vi.mock('../../api/websocket', () => ({connect: vi.fn(),@@ -95,4 +100,100 @@ describe('PhotoLightbox', () => {buttons[0].click();expect(onClose).toHaveBeenCalled();});++ it('FE-COMP-LIGHTBOX-009: opens at the requested start index', () => {+ const { container } = render(<PhotoLightbox photos={samplePhotos} startIndex={2} onClose={vi.fn()} />);+ expect(screen.getByText('3 / 3')).toBeInTheDocument();+ // The third photo has no caption, so its img is presentational.+ expect(container.querySelector('img')).toHaveAttribute('src', '/photos/3.jpg');+ });++ it('FE-COMP-LIGHTBOX-010: only offers the arrows that lead somewhere', () => {+ render(<PhotoLightbox photos={samplePhotos} onClose={vi.fn()} />);+ // First photo: close + next.+ expect(screen.getAllByRole('button')).toHaveLength(2);++ fireEvent.keyDown(window, { key: 'ArrowRight' });+ expect(screen.getAllByRole('button')).toHaveLength(3);++ fireEvent.keyDown(window, { key: 'ArrowRight' });+ // Last photo: close + prev.+ expect(screen.getAllByRole('button')).toHaveLength(2);++ fireEvent.keyDown(window, { key: 'ArrowRight' });+ expect(screen.getByText('3 / 3')).toBeInTheDocument();+ });++ it('FE-COMP-LIGHTBOX-011: navigates with the on-screen arrows', () => {+ render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);+ const [, prev, next] = screen.getAllByRole('button');++ fireEvent.click(next);+ expect(screen.getByText('3 / 3')).toBeInTheDocument();++ fireEvent.click(screen.getAllByRole('button')[1]);+ expect(screen.getByText('2 / 3')).toBeInTheDocument();+ expect(prev).toBeInTheDocument();+ });++ it('FE-COMP-LIGHTBOX-012: stays on the first photo when arrowing left', () => {+ render(<PhotoLightbox photos={samplePhotos} onClose={vi.fn()} />);+ fireEvent.keyDown(window, { key: 'ArrowLeft' });+ expect(screen.getByText('1 / 3')).toBeInTheDocument();+ });++ it('FE-COMP-LIGHTBOX-013: renders the caption of the current photo only', () => {+ render(<PhotoLightbox photos={samplePhotos} onClose={vi.fn()} />);+ expect(screen.getByText('Sunset at the beach')).toBeInTheDocument();+ expect(screen.queryByText('Mountain trail')).not.toBeInTheDocument();++ fireEvent.keyDown(window, { key: 'ArrowRight' });+ expect(screen.getByText('Mountain trail')).toBeInTheDocument();+ });++ it('FE-COMP-LIGHTBOX-014: renders a video item through the player instead of an image', () => {+ render(+ <PhotoLightbox+ photos={[{ id: 'v1', src: '/videos/1.mp4', caption: null, mediaType: 'video' }]}+ onClose={vi.fn()}+ />,+ );+ expect(screen.getByTestId('video-player')).toHaveAttribute('src', '/videos/1.mp4');+ expect(screen.queryByRole('img')).not.toBeInTheDocument();+ });++ it('FE-COMP-LIGHTBOX-015: swipes horizontally to move between photos', () => {+ const { container } = render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);+ const surface = container.firstElementChild as HTMLElement;++ fireEvent.touchStart(surface, { touches: [{ clientX: 200, clientY: 200 }] });+ fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 100, clientY: 210 }] });+ expect(screen.getByText('3 / 3')).toBeInTheDocument();++ fireEvent.touchStart(surface, { touches: [{ clientX: 100, clientY: 200 }] });+ fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 200, clientY: 210 }] });+ expect(screen.getByText('2 / 3')).toBeInTheDocument();+ });++ it('FE-COMP-LIGHTBOX-016: swipes down to close', () => {+ const onClose = vi.fn();+ const { container } = render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);+ const surface = container.firstElementChild as HTMLElement;++ fireEvent.touchStart(surface, { touches: [{ clientX: 200, clientY: 100 }] });+ fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 210, clientY: 300 }] });++ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it('FE-COMP-LIGHTBOX-017: ignores a touch end without a matching touch start', () => {+ const onClose = vi.fn();+ const { container } = render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);+ const surface = container.firstElementChild as HTMLElement;++ fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 210, clientY: 300 }] });++ expect(onClose).not.toHaveBeenCalled();+ expect(screen.getByText('1 / 3')).toBeInTheDocument();+ });});diff --git a/client/src/components/Layout/Navbar.test.tsx b/client/src/components/Layout/Navbar.test.tsxindex 4c098eb28..322299ce4 100644--- a/client/src/components/Layout/Navbar.test.tsx+++ b/client/src/components/Layout/Navbar.test.tsx@@ -1,5 +1,5 @@// FE-COMP-NAVBAR-001 to FE-COMP-NAVBAR-028-import { render, screen, waitFor } from '../../../tests/helpers/render';+import { act, fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';import userEvent from '@testing-library/user-event';import { http, HttpResponse } from 'msw';import { server } from '../../../tests/helpers/msw/server';@@ -323,3 +323,239 @@ describe('Navbar', () => {expect(container.querySelector('.lucide-blocks')).not.toBeNull();});});++// FE-W5NAV-001 to FE-W5NAV-012 — scroll/dark styling, the addon-name fallback,+// the prerelease badge, the theme-transition timer and the hover styling that+// the behavioural tests above leave untouched.+describe('Navbar styling and menu details', () => {+ const nav = () => document.querySelector('nav') as HTMLElement;++ beforeEach(() => {+ document.documentElement.classList.remove('trek-theme-transitioning');+ Object.defineProperty(window, 'scrollY', { value: 0, configurable: true });+ });++ it('FE-W5NAV-001: the bar goes translucent once the page is scrolled', () => {+ render(<Navbar />);+ expect(nav().style.backdropFilter).toBe('blur(20px)');++ Object.defineProperty(window, 'scrollY', { value: 40, configurable: true });+ fireEvent.scroll(window);++ expect(nav().style.backdropFilter).toBe('blur(28px) saturate(180%)');+ expect(nav().style.background).toBe('rgba(255, 255, 255, 0.72)');+ });++ it('FE-W5NAV-002: dark mode swaps the bar and logo assets', () => {+ seedStore(useSettingsStore, { settings: buildSettings({ dark_mode: 'dark' }) });+ render(<Navbar />);++ expect(nav().style.background).toBe('rgba(9, 9, 11, 0.95)');+ expect(document.querySelector('img[src="/logo-light.svg"]')).not.toBeNull();++ Object.defineProperty(window, 'scrollY', { value: 40, configurable: true });+ fireEvent.scroll(window);+ expect(nav().style.background).toBe('rgba(9, 9, 11, 0.78)');+ });++ it('FE-W5NAV-003: a scrolled body counts as scrolled too', () => {+ render(<Navbar />);+ Object.defineProperty(document.body, 'scrollTop', { value: 30, configurable: true });+ fireEvent.scroll(document.body);++ expect(nav().style.backdropFilter).toBe('blur(28px) saturate(180%)');+ Object.defineProperty(document.body, 'scrollTop', { value: 0, configurable: true });+ });++ it('FE-W5NAV-004: no addons are loaded while nobody is signed in', () => {+ const loadAddons = vi.fn(async () => {});+ seedStore(useAuthStore, { user: null, isAuthenticated: false });+ seedStore(useAddonStore, { loadAddons });+ render(<Navbar />);++ expect(loadAddons).not.toHaveBeenCalled();+ expect(screen.queryByText('testuser')).not.toBeInTheDocument();+ });++ it('FE-W5NAV-005: a catalogued addon uses its translated name, an unknown one its own', () => {+ seedStore(useAddonStore, {+ addons: [+ { id: 'budget', name: 'Budget', icon: 'Briefcase', type: 'global', enabled: true },+ { id: 'trip-doctor', name: 'Trip Doctor', icon: 'NoSuchIcon', type: 'global', enabled: true },+ { id: 'weather', name: 'Weather', icon: 'Globe', type: 'integration', enabled: true },+ { id: 'atlas', name: 'Atlas', icon: 'Globe', type: 'global', enabled: false },+ ],+ });+ render(<Navbar />);++ expect(screen.getByRole('link', { name: /^Costs$/ })).toHaveAttribute('href', '/budget');+ expect(screen.getByRole('link', { name: /^Trip Doctor$/ })).toBeInTheDocument();+ expect(screen.queryByRole('link', { name: /^Weather$/ })).not.toBeInTheDocument();+ expect(screen.queryByRole('link', { name: /^Atlas$/ })).not.toBeInTheDocument();+ });++ it('FE-W5NAV-006: the active tab keeps its colour on hover, inactive tabs brighten', () => {+ seedStore(useAddonStore, {+ addons: [{ id: 'vacay', name: 'Vacay', icon: 'CalendarDays', type: 'global', enabled: true }],+ });+ render(<Navbar />, { initialEntries: ['/dashboard'] });++ const active = screen.getByRole('link', { name: /my trips/i });+ const inactive = screen.getByRole('link', { name: /vacay/i });+ expect(active.style.background).toBe('var(--bg-card)');+ expect(inactive.style.background).toBe('transparent');++ fireEvent.mouseEnter(active);+ fireEvent.mouseLeave(active);+ expect(active.style.color).toBe('var(--text-primary)');++ fireEvent.mouseEnter(inactive);+ expect(inactive.style.color).toBe('var(--text-primary)');+ fireEvent.mouseLeave(inactive);+ expect(inactive.style.color).toBe('var(--text-muted)');+ });++ it('FE-W5NAV-007: trip pages swap the tab pill for the centre notice slot', () => {+ seedStore(useAddonStore, {+ addons: [{ id: 'vacay', name: 'Vacay', icon: 'CalendarDays', type: 'global', enabled: true }],+ });+ render(<Navbar tripTitle="Japan 2027" />);++ expect(document.getElementById('trek-nav-center-slot')).not.toBeNull();+ expect(document.querySelector('.trek-nav-pill')).toBeNull();+ });++ it('FE-W5NAV-008: the prerelease badge only shows with a version and the flag set', () => {+ seedStore(useAuthStore, {+ user: buildUser({ username: 'testuser' }),+ isAuthenticated: true,+ isPrerelease: true,+ appVersion: '3.5.0-rc1',+ });+ const { unmount } = render(<Navbar />);+ expect(screen.getByText('3.5.0-rc1')).toBeInTheDocument();+ unmount();++ seedStore(useAuthStore, { isPrerelease: true, appVersion: null });+ render(<Navbar />);+ expect(screen.queryByText('3.5.0-rc1')).not.toBeInTheDocument();+ });++ it('FE-W5NAV-009: the back, share and theme buttons reset their hover background', () => {+ render(<Navbar showBack onBack={vi.fn()} onShare={vi.fn()} />);++ const back = screen.getByRole('button', { name: /back/i });+ fireEvent.mouseEnter(back);+ expect(back.style.background).toBe('var(--bg-hover)');+ fireEvent.mouseLeave(back);+ expect(back.style.background).toBe('transparent');++ const share = screen.getByRole('button', { name: /share/i });+ fireEvent.mouseEnter(share);+ expect(share.style.background).toBe('var(--bg-hover)');+ fireEvent.mouseLeave(share);+ expect(share.style.background).toBe('var(--bg-card)');++ const theme = document.querySelector('button[title]') as HTMLElement;+ fireEvent.mouseEnter(theme);+ expect(theme.style.background).toBe('var(--bg-hover)');+ fireEvent.mouseLeave(theme);+ expect(theme.style.background).toBe('transparent');+ });++ it('FE-W5NAV-010: toggling the theme twice restarts the transition class timer', () => {+ const updateSetting = vi.fn(async () => {});+ seedStore(useSettingsStore, { settings: buildSettings({ dark_mode: false }), updateSetting });+ render(<Navbar />);+ const theme = document.querySelector('button[title]') as HTMLElement;++ vi.useFakeTimers();+ try {+ fireEvent.click(theme);+ expect(document.documentElement.classList.contains('trek-theme-transitioning')).toBe(true);++ act(() => { vi.advanceTimersByTime(200); });+ fireEvent.click(theme); // restarts the pending timer+ act(() => { vi.advanceTimersByTime(200); });+ expect(document.documentElement.classList.contains('trek-theme-transitioning')).toBe(true);++ act(() => { vi.advanceTimersByTime(200); });+ expect(document.documentElement.classList.contains('trek-theme-transitioning')).toBe(false);+ } finally {+ vi.useRealTimers();+ }+ });++ it('FE-W5NAV-011: unmounting with a pending transition cancels its timer', () => {+ const updateSetting = vi.fn(async () => {});+ seedStore(useSettingsStore, { settings: buildSettings({ dark_mode: false }), updateSetting });+ const { unmount } = render(<Navbar />);+ const theme = document.querySelector('button[title]') as HTMLElement;++ vi.useFakeTimers();+ try {+ fireEvent.click(theme);+ const clear = vi.spyOn(window, 'clearTimeout');+ unmount();+ expect(clear).toHaveBeenCalled();+ clear.mockRestore();+ } finally {+ vi.useRealTimers();+ document.documentElement.classList.remove('trek-theme-transitioning');+ }+ });++ it('FE-W5NAV-012: every entry in the open user menu resets its hover background', async () => {+ const user = userEvent.setup();+ seedStore(useAuthStore, {+ user: buildUser({ username: 'adminuser', role: 'admin' }),+ isAuthenticated: true,+ appVersion: '3.5.0',+ });+ seedStore(useSettingsStore, { settings: buildSettings({ dark_mode: 'dark' }) });+ render(<Navbar />);+ await user.click(screen.getByText('adminuser'));++ for (const name of [/^Settings$/, /^Help$/, /^Admin$/]) {+ const link = screen.getByRole('link', { name });+ fireEvent.mouseEnter(link);+ expect(link.style.background).toBe('var(--bg-hover)');+ fireEvent.mouseLeave(link);+ expect(link.style.background).toBe('transparent');+ }++ const discord = screen.getByTitle('Discord');+ fireEvent.mouseEnter(discord);+ expect(discord.style.background).toBe('rgba(88, 101, 242, 0.125)');+ fireEvent.mouseLeave(discord);+ expect(discord.style.background).toBe('var(--bg-tertiary)');++ expect(document.querySelector('img[src="/text-light.svg"]')).not.toBeNull();+ });++ it('FE-W5NAV-013: following any menu entry closes the menu', async () => {+ const user = userEvent.setup();+ seedStore(useAuthStore, {+ user: buildUser({ username: 'adminuser', role: 'admin' }),+ isAuthenticated: true,+ });+ render(<Navbar />);++ for (const name of [/^Settings$/, /^Help$/, /^Admin$/]) {+ await user.click(screen.getByText('adminuser'));+ await user.click(screen.getByRole('link', { name }));+ expect(screen.queryByRole('link', { name: /^Settings$/ })).not.toBeInTheDocument();+ }+ });++ it('FE-W5NAV-014: a rejected theme update is swallowed', async () => {+ const updateSetting = vi.fn(() => Promise.reject(new Error('offline')));+ seedStore(useSettingsStore, { settings: buildSettings({ dark_mode: false }), updateSetting });+ render(<Navbar />);++ fireEvent.click(document.querySelector('button[title]') as HTMLElement);++ await waitFor(() => expect(updateSetting).toHaveBeenCalledWith('dark_mode', 'dark'));+ document.documentElement.classList.remove('trek-theme-transitioning');+ });+});diff --git a/client/src/components/Layout/PageShell.test.tsx b/client/src/components/Layout/PageShell.test.tsxnew file mode 100644index 000000000..baec0373a--- /dev/null+++ b/client/src/components/Layout/PageShell.test.tsx@@ -0,0 +1,60 @@+// FE-W4SHELL-001 to FE-W4SHELL-006+import { describe, it, expect, vi } from 'vitest'+import { render, screen } from '../../../tests/helpers/render'++vi.mock('./Navbar', () => ({+ default: ({ tripTitle }: { tripTitle?: string }) => <nav data-testid="navbar">{tripTitle ?? 'nav'}</nav>,+}))++import PageShell from './PageShell'++describe('PageShell', () => {+ it('FE-W4SHELL-001: renders the navbar above the children', () => {+ render(<PageShell><p>content</p></PageShell>)++ expect(screen.getByTestId('navbar')).toBeInTheDocument()+ expect(screen.getByText('content')).toBeInTheDocument()+ })++ it('FE-W4SHELL-002: offsets the content by the global nav height', () => {+ render(<PageShell><p>content</p></PageShell>)++ expect(screen.getByText('content').parentElement).toHaveStyle({ paddingTop: 'var(--nav-h)' })+ })++ it('FE-W4SHELL-003: accepts a custom nav offset and content style', () => {+ render(+ <PageShell navOffset="80px" contentStyle={{ maxWidth: 900 }} contentClassName="mx-auto">+ <p>content</p>+ </PageShell>,+ )+ const wrapper = screen.getByText('content').parentElement as HTMLElement++ expect(wrapper.style.paddingTop).toBe('80px')+ expect(wrapper.style.maxWidth).toBe('900px')+ expect(wrapper.className).toBe('mx-auto')+ })++ it('FE-W4SHELL-004: keeps min-h-screen and appends the caller className', () => {+ const { container } = render(<PageShell className="bg-surface"><p>c</p></PageShell>)++ expect((container.firstElementChild as HTMLElement).className).toBe('min-h-screen bg-surface')+ })++ it('FE-W4SHELL-005: leaves the root class untouched without a className', () => {+ const { container } = render(<PageShell><p>c</p></PageShell>)+ const root = container.firstElementChild as HTMLElement++ expect(root.className).toBe('min-h-screen')+ expect(root.getAttribute('style')).toBeNull()+ })++ it('FE-W4SHELL-006: themes the root via an inline background and forwards navbar props', () => {+ const { container } = render(+ <PageShell background="var(--bg-secondary)" navbar={{ tripTitle: 'Iceland' }}><p>c</p></PageShell>,+ )++ expect((container.firstElementChild as HTMLElement).style.background).toBe('var(--bg-secondary)')+ expect(screen.getByTestId('navbar')).toHaveTextContent('Iceland')+ })+})diff --git a/client/src/components/Layout/PageSidebar.test.tsx b/client/src/components/Layout/PageSidebar.test.tsxnew file mode 100644index 000000000..e67f341a2--- /dev/null+++ b/client/src/components/Layout/PageSidebar.test.tsx@@ -0,0 +1,132 @@+// FE-W4PSB-001 to FE-W4PSB-012+import type { ComponentProps } from 'react'+import { describe, it, expect, vi } from 'vitest'+import { Bell, Palette, Shield } from 'lucide-react'+import { render, screen, fireEvent, within } from '../../../tests/helpers/render'+import PageSidebar, { type PageSidebarTab } from './PageSidebar'++const TABS: PageSidebarTab[] = [+ { id: 'appearance', label: 'Appearance', icon: Palette, group: 'General' },+ { id: 'notifications', label: 'Notifications', icon: Bell, group: 'General' },+ { id: 'security', label: 'Security', icon: Shield, group: 'Account' },+]++function setup(overrides: Partial<ComponentProps<typeof PageSidebar>> = {}) {+ const onTabChange = vi.fn()+ const utils = render(+ <PageSidebar sidebarLabel="SETTINGS" tabs={TABS} activeTab="appearance" onTabChange={onTabChange} {...overrides}>+ <p>panel body</p>+ </PageSidebar>,+ )+ return { onTabChange, ...utils }+}++describe('PageSidebar', () => {+ it('FE-W4PSB-001: renders the label, every tab and the panel children', () => {+ setup()++ expect(screen.getAllByText('SETTINGS').length).toBeGreaterThan(0)+ expect(screen.getByRole('button', { name: /^Appearance$/ })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /^Security$/ })).toBeInTheDocument()+ expect(screen.getByText('panel body')).toBeInTheDocument()+ })++ it('FE-W4PSB-002: prints one heading per contiguous group', () => {+ setup()++ expect(screen.getByText('General')).toBeInTheDocument()+ expect(screen.getByText('Account')).toBeInTheDocument()+ })++ it('FE-W4PSB-003: highlights the active tab', () => {+ setup()++ expect(screen.getByRole('button', { name: /^Appearance$/ }).className).toContain('font-semibold')+ expect(screen.getByRole('button', { name: /^Security$/ }).className).toContain('font-medium')+ })++ it('FE-W4PSB-004: mirrors the active tab label in the mobile top bar', () => {+ setup({ activeTab: 'security' })++ expect(screen.getByText('Security', { selector: 'div' })).toBeInTheDocument()+ })++ it('FE-W4PSB-005: falls back to an empty mobile label for an unknown tab', () => {+ const { container } = setup({ activeTab: 'nope' })+ const bar = container.querySelector('.lg\\:hidden') as HTMLElement++ expect(within(bar).getByLabelText('Open navigation')).toBeInTheDocument()+ expect(bar.textContent).toBe('')+ })++ it('FE-W4PSB-006: reports the clicked tab id', () => {+ const { onTabChange } = setup()++ fireEvent.click(screen.getByRole('button', { name: /^Notifications$/ }))++ expect(onTabChange).toHaveBeenCalledWith('notifications')+ })++ it('FE-W4PSB-007: the hamburger opens the drawer and its close button shuts it', () => {+ setup()++ fireEvent.click(screen.getByLabelText('Open navigation'))+ expect(screen.getByLabelText('Close navigation')).toBeInTheDocument()+ // The drawer duplicates the tab list.+ expect(screen.getAllByRole('button', { name: /^Appearance$/ })).toHaveLength(2)++ fireEvent.click(screen.getByLabelText('Close navigation'))+ expect(screen.queryByLabelText('Close navigation')).toBeNull()+ })++ it('FE-W4PSB-008: picking a tab in the drawer reports it and closes the drawer', () => {+ const { onTabChange } = setup()+ fireEvent.click(screen.getByLabelText('Open navigation'))++ const drawerTabs = screen.getAllByRole('button', { name: /^Security$/ })+ fireEvent.click(drawerTabs[drawerTabs.length - 1])++ expect(onTabChange).toHaveBeenCalledWith('security')+ expect(screen.queryByLabelText('Close navigation')).toBeNull()+ })++ it('FE-W4PSB-009: Escape closes the drawer', () => {+ setup()+ fireEvent.click(screen.getByLabelText('Open navigation'))++ fireEvent.keyDown(window, { key: 'Escape' })+ expect(screen.queryByLabelText('Close navigation')).toBeNull()++ // A stray key while closed must not crash.+ fireEvent.keyDown(window, { key: 'Enter' })+ expect(screen.queryByLabelText('Close navigation')).toBeNull()+ })++ it('FE-W4PSB-010: clicking the scrim closes the drawer', () => {+ const { container } = setup()+ fireEvent.click(screen.getByLabelText('Open navigation'))++ fireEvent.click(container.querySelector('.fixed.inset-0')!)++ expect(screen.queryByLabelText('Close navigation')).toBeNull()+ })++ it('FE-W4PSB-011: renders an optional footer in both sidebar copies', () => {+ setup({ footer: 'v3.4 · self-hosted' })+ expect(screen.getAllByText('v3.4 · self-hosted')).toHaveLength(1)++ fireEvent.click(screen.getByLabelText('Open navigation'))+ expect(screen.getAllByText('v3.4 · self-hosted')).toHaveLength(2)+ })++ it('FE-W4PSB-012: renders ungrouped tabs without a heading', () => {+ render(+ <PageSidebar sidebarLabel="ADMIN" tabs={[{ id: 'users', label: 'Users', icon: Shield }]} activeTab="users" onTabChange={() => {}}>+ <p>body</p>+ </PageSidebar>,+ )++ expect(screen.getByRole('button', { name: /^Users$/ })).toBeInTheDocument()+ expect(screen.queryByText('General')).toBeNull()+ })+})diff --git a/client/src/components/Layout/navItems.hook.test.tsx b/client/src/components/Layout/navItems.hook.test.tsxnew file mode 100644index 000000000..82aea2a4c--- /dev/null+++ b/client/src/components/Layout/navItems.hook.test.tsx@@ -0,0 +1,79 @@+// FE-W4NAVH-001 to FE-W4NAVH-005+import { describe, it, expect, beforeEach } from 'vitest'+import { CalendarDays, Globe, LayoutGrid } from 'lucide-react'+import { renderHook } from '@testing-library/react'+import { TranslationProvider } from '../../i18n/TranslationContext'+import { useAddonStore } from '../../store/addonStore'+import { usePluginStore } from '../../store/pluginStore'+import { useNavItems } from './navItems'++function wrapper({ children }: { children: React.ReactNode }) {+ return <TranslationProvider>{children}</TranslationProvider>+}++const render = () => renderHook(() => useNavItems(), { wrapper })++beforeEach(() => {+ useAddonStore.setState({ addons: [] })+ usePluginStore.setState({ plugins: [] })+})++describe('useNavItems', () => {+ it('FE-W4NAVH-001: always starts with the pinned Dashboard entry', () => {+ const { result } = render()++ expect(result.current).toHaveLength(1)+ expect(result.current[0]).toMatchObject({ id: 'dashboard', to: '/dashboard', icon: LayoutGrid, pinned: true })+ })++ it('FE-W4NAVH-002: appends enabled global addons with their signature icons', () => {+ useAddonStore.setState({+ addons: [+ { id: 'vacay', name: 'Vacay', icon: 'Calendar', type: 'global', enabled: true },+ { id: 'atlas', name: 'Atlas', icon: 'Map', type: 'global', enabled: true },+ ] as never,+ })++ const { result } = render()++ expect(result.current.map(i => i.id)).toEqual(['dashboard', 'vacay', 'atlas'])+ expect(result.current[1].icon).toBe(CalendarDays)+ expect(result.current[2].icon).toBe(Globe)+ })++ it('FE-W4NAVH-003: ignores disabled and non-global addons', () => {+ useAddonStore.setState({+ addons: [+ { id: 'vacay', name: 'Vacay', icon: 'Calendar', type: 'global', enabled: false },+ { id: 'budget', name: 'Budget', icon: 'Wallet', type: 'trip', enabled: true },+ ] as never,+ })++ const { result } = render()++ expect(result.current.map(i => i.id)).toEqual(['dashboard'])+ })++ it('FE-W4NAVH-004: appends page plugins under a plugin: id and skips other plugin types', () => {+ usePluginStore.setState({+ plugins: [+ { id: 'notes', name: 'Notes', icon: 'Stethoscope', type: 'page' },+ { id: 'fx', name: 'Currency', icon: null, type: 'widget' },+ ] as never,+ })++ const { result } = render()++ expect(result.current.map(i => i.id)).toEqual(['dashboard', 'plugin:notes'])+ expect(result.current[1]).toMatchObject({ to: '/plugins/notes', label: 'Notes' })+ })++ it('FE-W4NAVH-005: keeps the item list stable while the stores do not change', () => {+ const { result, rerender } = render()+ const first = result.current++ rerender()++ expect(result.current).toBe(first)+ })+})diff --git a/client/src/components/Map/MapCompassPill.test.tsx b/client/src/components/Map/MapCompassPill.test.tsxnew file mode 100644index 000000000..23128f0da--- /dev/null+++ b/client/src/components/Map/MapCompassPill.test.tsx@@ -0,0 +1,88 @@+// FE-COMP-MAPCOMPASS-001 to FE-COMP-MAPCOMPASS-006+import React from 'react'+import { describe, it, expect, vi } from 'vitest'+import { render, screen, fireEvent, act } from '../../../tests/helpers/render'+import { MapCompassPill, type CompassMap } from './MapCompassPill'++function fakeCompassMap(initialBearing = 0) {+ const listeners: Array<() => void> = []+ let bearing = initialBearing+ const map = {+ getBearing: vi.fn(() => bearing),+ on: vi.fn((_type: 'rotate', fn: () => void) => { listeners.push(fn) }),+ off: vi.fn((_type: 'rotate', fn: () => void) => {+ const i = listeners.indexOf(fn)+ if (i >= 0) listeners.splice(i, 1)+ }),+ easeTo: vi.fn(),+ }+ return {+ map: map as unknown as CompassMap,+ spies: map,+ listenerCount: () => listeners.length,+ rotateTo: (next: number) => {+ bearing = next+ act(() => { listeners.forEach(fn => fn()) })+ },+ }+}++const needle = () => screen.getByRole('button', { name: 'Reset north' }).querySelector('svg') as SVGElement++describe('MapCompassPill', () => {+ it('FE-COMP-MAPCOMPASS-001: points the needle against the current map bearing', () => {+ const { map } = fakeCompassMap(45)+ render(<MapCompassPill map={map} />)+ // The map rotated 45° clockwise, so the needle turns 45° back to keep pointing north.+ expect(needle().style.transform).toBe('rotate(-45deg)')+ })++ it('FE-COMP-MAPCOMPASS-002: follows the map while it rotates', () => {+ const compass = fakeCompassMap(0)+ render(<MapCompassPill map={compass.map} />)+ expect(needle().style.transform).toBe('rotate(0deg)')++ compass.rotateTo(120)+ expect(needle().style.transform).toBe('rotate(-120deg)')+ })++ it('FE-COMP-MAPCOMPASS-003: snaps the camera back to north and flat on click', () => {+ const compass = fakeCompassMap(75)+ render(<MapCompassPill map={compass.map} />)++ fireEvent.click(screen.getByRole('button', { name: 'Reset north' }))+ expect(compass.spies.easeTo).toHaveBeenCalledWith({ bearing: 0, pitch: 0, duration: 300 })+ })++ it('FE-COMP-MAPCOMPASS-004: unsubscribes from the rotate event on unmount', () => {+ const compass = fakeCompassMap(0)+ const { unmount } = render(<MapCompassPill map={compass.map} />)+ expect(compass.listenerCount()).toBe(1)++ unmount()+ expect(compass.spies.off).toHaveBeenCalledWith('rotate', expect.any(Function))+ expect(compass.listenerCount()).toBe(0)+ })++ it('FE-COMP-MAPCOMPASS-005: resubscribes when the map instance is swapped (style rebuild)', () => {+ const first = fakeCompassMap(10)+ const second = fakeCompassMap(200)+ const { rerender } = render(<MapCompassPill map={first.map} />)++ rerender(<MapCompassPill map={second.map} />)+ expect(first.listenerCount()).toBe(0)+ expect(second.listenerCount()).toBe(1)+ expect(needle().style.transform).toBe('rotate(-200deg)')+ })++ it('FE-COMP-MAPCOMPASS-006: highlights the button on hover and clears it again', () => {+ const { map } = fakeCompassMap(0)+ render(<MapCompassPill map={map} />)+ const button = screen.getByRole('button', { name: 'Reset north' })++ fireEvent.mouseEnter(button)+ expect(button.style.background).toBe('var(--bg-hover)')+ fireEvent.mouseLeave(button)+ expect(button.style.background).toBe('transparent')+ })+})diff --git a/client/src/components/Map/MapPluginLayers.test.tsx b/client/src/components/Map/MapPluginLayers.test.tsxnew file mode 100644index 000000000..d1daab229--- /dev/null+++ b/client/src/components/Map/MapPluginLayers.test.tsx@@ -0,0 +1,211 @@+// FE-COMP-MAPPLUGINLAYERS-001 to FE-COMP-MAPPLUGINLAYERS-009+import React from 'react'+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { http, HttpResponse } from 'msw'+import { render, screen, waitFor } from '../../../tests/helpers/render'+import { server } from '../../../tests/helpers/msw/server'+import type { PluginMapLayer, PluginMapLayerFeature } from '../../api/client'++interface PathProps {+ positions?: [number, number][]+ center?: [number, number]+ radius?: number+ pathOptions?: Record<string, unknown>+ children?: React.ReactNode+}++// react-leaflet primitives are replaced by markers that surface exactly what the+// component controls: geometry, the path options and the pane it draws into.+const mapHolder = vi.hoisted(() => ({ current: {} as Record<string, unknown> }))++vi.mock('react-leaflet', () => ({+ Polyline: ({ positions, pathOptions, children }: PathProps) => (+ <div data-testid="polyline" data-points={JSON.stringify(positions)} data-path-options={JSON.stringify(pathOptions)}>{children}</div>+ ),+ Polygon: ({ positions, pathOptions, children }: PathProps) => (+ <div data-testid="polygon" data-points={JSON.stringify(positions)} data-path-options={JSON.stringify(pathOptions)}>{children}</div>+ ),+ Circle: ({ center, radius, pathOptions, children }: PathProps) => (+ <div data-testid="circle" data-center={JSON.stringify(center)} data-radius={radius} data-path-options={JSON.stringify(pathOptions)}>{children}</div>+ ),+ Tooltip: ({ children }: { children?: React.ReactNode }) => <span data-testid="tooltip">{children}</span>,+ useMap: () => mapHolder.current,+}))++import { PluginMapLayers } from './MapPluginLayers'++function paneMap(preexisting = false) {+ const panes = new Map<string, HTMLElement>()+ if (preexisting) panes.set('trek-plugin-layers', document.createElement('div'))+ return {+ panes,+ getPane: vi.fn((name: string) => panes.get(name)),+ createPane: vi.fn((name: string) => {+ const el = document.createElement('div')+ panes.set(name, el)+ return el+ }),+ }+}++function feature(overrides: Partial<PluginMapLayerFeature> = {}): PluginMapLayerFeature {+ return {+ type: 'polyline',+ points: [[48.85, 2.35], [48.86, 2.36]],+ tone: 'default',+ width: 3,+ dash: 'solid',+ opacity: 0.8,+ fill: false,+ ...overrides,+ }+}++function layer(features: PluginMapLayerFeature[], overrides: Partial<PluginMapLayer> = {}): PluginMapLayer {+ return { pluginId: 'ev-router', id: 'corridor', features, ...overrides }+}++function serveLayers(layers: PluginMapLayer[]) {+ server.use(http.get('/api/map-layers/:tripId', () => HttpResponse.json({ layers })))+}++const optionsOf = (el: HTMLElement) => JSON.parse(el.getAttribute('data-path-options') || '{}') as Record<string, unknown>++beforeEach(() => {+ mapHolder.current = paneMap() as unknown as Record<string, unknown>+})++afterEach(() => {+ vi.clearAllMocks()+})++describe('PluginMapLayers', () => {+ it('FE-COMP-MAPPLUGINLAYERS-001: renders nothing without a trip', async () => {+ let requests = 0+ server.use(http.get('/api/map-layers/:tripId', () => { requests += 1; return HttpResponse.json({ layers: [] }) }))++ render(<PluginMapLayers />)+ await waitFor(() => expect(screen.queryByTestId('polyline')).toBeNull())+ expect(requests).toBe(0)+ })++ it('FE-COMP-MAPPLUGINLAYERS-002: creates the below-overlay pane and draws into it', async () => {+ const map = paneMap()+ mapHolder.current = map as unknown as Record<string, unknown>+ serveLayers([layer([feature()])])++ render(<PluginMapLayers tripId={4} />)+ const line = await screen.findByTestId('polyline')++ expect(map.createPane).toHaveBeenCalledWith('trek-plugin-layers')+ // Core geometry (overlayPane, 400) has to stay on top of plugin shapes.+ expect(map.panes.get('trek-plugin-layers')?.style.zIndex).toBe('399')+ expect(optionsOf(line).pane).toBe('trek-plugin-layers')+ })++ it('FE-COMP-MAPPLUGINLAYERS-003: reuses an existing pane instead of creating a second one', async () => {+ const map = paneMap(true)+ mapHolder.current = map as unknown as Record<string, unknown>+ serveLayers([layer([feature()])])++ render(<PluginMapLayers tripId={4} />)+ await screen.findByTestId('polyline')++ expect(map.createPane).not.toHaveBeenCalled()+ })++ it('FE-COMP-MAPPLUGINLAYERS-004: still draws on a map without the pane API, just without a pane', async () => {+ mapHolder.current = {}+ serveLayers([layer([feature()])])++ render(<PluginMapLayers tripId={4} />)+ const line = await screen.findByTestId('polyline')+ expect(optionsOf(line)).not.toHaveProperty('pane')+ })++ it('FE-COMP-MAPPLUGINLAYERS-005: draws polylines, polygons and metric circles', async () => {+ serveLayers([layer([+ feature({ type: 'polyline' }),+ feature({ type: 'polygon', points: [[48, 2], [48, 3], [49, 3]] }),+ feature({ type: 'circle', points: undefined, center: [48.8, 2.3], radiusM: 750 }),+ ])])++ render(<PluginMapLayers tripId={4} />)+ await screen.findByTestId('polyline')++ expect(JSON.parse(screen.getByTestId('polygon').getAttribute('data-points') || '')).toEqual([[48, 2], [48, 3], [49, 3]])+ const circle = screen.getByTestId('circle')+ expect(JSON.parse(circle.getAttribute('data-center') || '')).toEqual([48.8, 2.3])+ expect(circle.getAttribute('data-radius')).toBe('750')+ })++ it('FE-COMP-MAPPLUGINLAYERS-006: maps tone, width, dash and fill onto the leaflet path options', async () => {+ serveLayers([layer([+ feature({ tone: 'danger', width: 6, dash: 'dash', opacity: 0.5 }),+ feature({ type: 'polygon', tone: 'success', dash: 'dot', opacity: 0.9, fill: true }),+ ])])++ render(<PluginMapLayers tripId={4} />)+ const line = await screen.findByTestId('polyline')++ expect(optionsOf(line)).toMatchObject({+ color: '#ef4444',+ weight: 6,+ opacity: 0.5,+ dashArray: '8, 8',+ fill: false,+ fillOpacity: 0,+ })+ // A filled shape is capped at 0.25 so it never hides the basemap underneath.+ expect(optionsOf(screen.getByTestId('polygon'))).toMatchObject({+ color: '#10b981',+ dashArray: '1, 7',+ fill: true,+ fillOpacity: 0.25,+ })+ })++ it('FE-COMP-MAPPLUGINLAYERS-007: only a labelled feature gets a tooltip and stays clickable', async () => {+ serveLayers([layer([+ feature({ label: 'Charging corridor' }),+ feature({ type: 'polygon' }),+ ])])++ render(<PluginMapLayers tripId={4} />)+ const line = await screen.findByTestId('polyline')++ expect(screen.getByTestId('tooltip')).toHaveTextContent('Charging corridor')+ expect(optionsOf(line).interactive).toBe(true)+ // Unlabelled shapes must never steal a map click.+ expect(optionsOf(screen.getByTestId('polygon')).interactive).toBe(false)+ expect(screen.getAllByTestId('tooltip')).toHaveLength(1)+ })++ it('FE-COMP-MAPPLUGINLAYERS-008: skips features whose geometry is incomplete', async () => {+ serveLayers([layer([+ feature({ type: 'polyline', points: undefined }),+ feature({ type: 'polygon', points: undefined }),+ feature({ type: 'circle', points: undefined, center: [48, 2] }),+ feature({ type: 'circle', points: undefined, radiusM: 500 }),+ feature({ label: 'kept' }),+ ])])++ render(<PluginMapLayers tripId={4} />)+ await screen.findByTestId('polyline')++ expect(screen.getAllByTestId('polyline')).toHaveLength(1)+ expect(screen.queryByTestId('polygon')).toBeNull()+ expect(screen.queryByTestId('circle')).toBeNull()+ })++ it('FE-COMP-MAPPLUGINLAYERS-009: a failing request leaves the map without plugin overlays', async () => {+ serveLayers([layer([feature()])])+ const { rerender } = render(<PluginMapLayers tripId={4} />)+ await screen.findByTestId('polyline')++ server.use(http.get('/api/map-layers/:tripId', () => HttpResponse.json({ error: 'boom' }, { status: 500 })))+ rerender(<PluginMapLayers tripId={9} />)++ await waitFor(() => expect(screen.queryByTestId('polyline')).toBeNull())+ })+})diff --git a/client/src/components/Map/MapView.test.tsx b/client/src/components/Map/MapView.test.tsxindex b1bc860ea..89f9e068e 100644--- a/client/src/components/Map/MapView.test.tsx+++ b/client/src/components/Map/MapView.test.tsx@@ -1,10 +1,12 @@import React from 'react'import { describe, it, expect, vi, afterEach } from 'vitest'import { render, screen } from '../../../tests/helpers/render'-import { fireEvent, waitFor } from '@testing-library/react'+import { act, fireEvent, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { resetAllStores } from '../../../tests/helpers/store'import { buildPlace, buildReservation } from '../../../tests/helpers/factories'+import { useAuthStore } from '../../store/authStore'+import { CATEGORY_ICON_MAP } from '../shared/categoryIcons'import * as photoService from '../../services/photoService'const mapMock = vi.hoisted(() => ({@@ -16,19 +18,50 @@ const mapMock = vi.hoisted(() => ({off: vi.fn(),panBy: vi.fn(),latLngToContainerPoint: vi.fn(() => ({ x: 0, y: 0, distanceTo: () => 1000 })),+ // Panes: jsdom has none, so keep them in a map the pane tests can read back.+ panes: new Map<string, HTMLElement>(),+ getPane: vi.fn(function (this: void, name: string) { return mapMock.panes.get(name) }),+ createPane: vi.fn(function (this: void, name: string) {+ const el = document.createElement('div')+ mapMock.panes.set(name, el)+ return el+ }),+ getBounds: vi.fn(() => ({ getSouth: () => 47, getWest: () => 1, getNorth: () => 49, getEast: () => 3 })),+ whenReady: vi.fn((cb: () => void) => { cb() }),}))+// Live-location fixture; tests flip this before rendering.+const geoMock = vi.hoisted(() => ({+ position: null as { lat: number; lng: number; accuracy: number; heading: number | null } | null,+ mode: 'off' as 'off' | 'show' | 'follow',+ error: null as string | null,+ cycleMode: vi.fn(),+ setMode: vi.fn(),+}))++vi.mock('../../hooks/useGeolocation', () => ({+ useGeolocation: () => geoMock,+}))++// onThumbReady callbacks are captured so a test can play back a photo landing+// after the map already rendered.+const thumbCallbacks = vi.hoisted(() => new Map<string, (thumb: string) => void>())+vi.mock('react-leaflet', () => ({// center/zoom are surfaced so tests can assert the camera the map is built with.MapContainer: ({ children, center, zoom }: any) => (<div data-testid="map-container" data-center={JSON.stringify(center)} data-zoom={zoom}>{children}</div>),TileLayer: () => <div data-testid="tile-layer" />,- Marker: ({ children, eventHandlers, position }: any) => (+ Marker: ({ children, eventHandlers, position, icon, zIndexOffset }: any) => (<divdata-testid="marker"data-lat={position[0]}data-lng={position[1]}+ data-zindex={zIndexOffset}+ // The divIcon mock hands its options straight back, so the generated+ // marker HTML is assertable without a real Leaflet.+ data-icon-html={icon?.html ?? ''}onClick={() => eventHandlers?.click?.()}><button@@ -37,6 +70,14 @@ vi.mock('react-leaflet', () => ({// hover-simulation must not trigger the marker's click handler.onClick={(e: any) => { e.stopPropagation(); eventHandlers?.mouseover?.({ originalEvent: { clientX: 100, clientY: 100 } }) }}/>+ <button+ data-testid="marker-move-trigger"+ onClick={(e: any) => { e.stopPropagation(); eventHandlers?.mousemove?.({ originalEvent: { clientX: 150, clientY: 160 } }) }}+ />+ <button+ data-testid="marker-out-trigger"+ onClick={(e: any) => { e.stopPropagation(); eventHandlers?.mouseout?.() }}+ />{children}</div>),@@ -64,27 +105,42 @@ vi.mock('react-leaflet', () => ({}))vi.mock('react-leaflet-cluster', () => ({- default: ({ children }: any) => <div data-testid="cluster-group">{children}</div>,+ // The real cluster group calls iconCreateFunction itself; the probe button+ // lets a test invoke it with a chosen child count.+ default: ({ children, iconCreateFunction }: any) => (+ <div data-testid="cluster-group">+ <button+ data-testid="cluster-icon-probe"+ onClick={(e: any) => {+ const count = Number(e.currentTarget.getAttribute('data-count') || 0)+ const icon = iconCreateFunction?.({ getChildCount: () => count })+ e.currentTarget.setAttribute('data-icon-html', icon?.html ?? '')+ }}+ />+ {children}+ </div>+ ),}))-vi.mock('leaflet', () => ({- default: {- divIcon: vi.fn(() => ({})),+vi.mock('leaflet', () => {+ const divIcon = vi.fn((options: any) => ({ ...options }))+ const leaflet = {+ divIcon,Icon: { Default: { prototype: {}, mergeOptions: vi.fn() } },latLngBounds: vi.fn(() => ({ isValid: () => true })),point: vi.fn((x: number, y: number) => [x, y]),- },- divIcon: vi.fn(() => ({})),- Icon: { Default: { prototype: {}, mergeOptions: vi.fn() } },- latLngBounds: vi.fn(() => ({ isValid: () => true })),- point: vi.fn((x: number, y: number) => [x, y]),-}))+ }+ return { default: leaflet, ...leaflet }+})vi.mock('../../services/photoService', () => ({getCached: vi.fn(() => null),isLoading: vi.fn(() => false),fetchPhoto: vi.fn(),- onThumbReady: vi.fn(() => () => {}),+ onThumbReady: vi.fn((key: string, cb: (thumb: string) => void) => {+ thumbCallbacks.set(key, cb)+ return () => { thumbCallbacks.delete(key) }+ }),getAllThumbs: vi.fn(() => ({})),}))@@ -102,9 +158,17 @@ function buildMapPlace(overrides: Record<string, any> = {}) {} as any}+const ORIGINAL_WIDTH = window.innerWidth+afterEach(() => {vi.clearAllMocks()resetAllStores()+ mapMock.panes.clear()+ thumbCallbacks.clear()+ geoMock.position = null+ geoMock.mode = 'off'+ geoMock.error = null+ Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: ORIGINAL_WIDTH })})describe('MapView', () => {@@ -456,4 +520,491 @@ describe('MapView', () => {render(<MapView reservations={[reservation]} visibleConnectionIds={[42]} />)expect(screen.getAllByTestId('polyline').length).toBeGreaterThan(0)})++ it('FE-COMP-MAPVIEW-073: a category icon that throws leaves the marker circle intact', () => {+ // Icon components come from a lookup table a plugin can extend; one that+ // throws must not take the whole map down, only its own glyph.+ const key = '__ExplodingIcon'+ CATEGORY_ICON_MAP[key] = (() => { throw new Error('icon blew up') }) as unknown as typeof CATEGORY_ICON_MAP['MapPin']+ try {+ render(<MapView places={[buildMapPlace({ id: 5, lat: 48, lng: 2, category_icon: key })]} />)+ const html = screen.getByTestId('marker').getAttribute('data-icon-html') || ''+ expect(html).toContain('border-radius:50%')+ expect(html).not.toContain('<svg')+ } finally {+ delete CATEGORY_ICON_MAP[key]+ }+ })+})++// ── FE-COMP-MAPVIEW-030 onwards ───────────────────────────────────────────────++const leafletMock = async () => ((await import('leaflet')).default) as unknown as {+ divIcon: ReturnType<typeof vi.fn>+ latLngBounds: ReturnType<typeof vi.fn>+}++const iconHtmlOf = (el: HTMLElement) => el.getAttribute('data-icon-html') || ''+const markersWithZ = (z: string) => screen.queryAllByTestId('marker').filter(m => m.getAttribute('data-zindex') === z)+const handlerFor = (event: string) => mapMock.on.mock.calls.find(c => c[0] === event)?.[1] as (() => void) | undefined++function buildPoi(overrides: Record<string, any> = {}) {+ return {+ osm_id: 'node/1',+ name: 'Café Central',+ lat: 48.21,+ lng: 16.36,+ category: 'cafe',+ poi_type: 'cafe',+ address: null,+ website: null,+ phone: null,+ opening_hours: null,+ cuisine: null,+ source: 'openstreetmap',+ ...overrides,+ }+}++describe('MapView clusters and badges', () => {+ it('FE-COMP-MAPVIEW-030: the cluster icon grows with the number of markers it hides', () => {+ render(<MapView places={[buildMapPlace({ id: 1, lat: 48, lng: 2 })]} />)+ const probe = screen.getByTestId('cluster-icon-probe')++ const iconFor = (count: number) => {+ probe.setAttribute('data-count', String(count))+ fireEvent.click(probe)+ return probe.getAttribute('data-icon-html') || ''+ }++ expect(iconFor(4)).toContain('width:36px')+ expect(iconFor(4)).toContain('<span>4</span>')+ expect(iconFor(20)).toContain('width:42px')+ expect(iconFor(120)).toContain('width:48px')+ })++ it('FE-COMP-MAPVIEW-031: a place on one day gets a single order badge', () => {+ render(<MapView places={[buildMapPlace({ id: 3, lat: 48, lng: 2 })]} dayOrderMap={{ 3: [2] }} />)+ const html = iconHtmlOf(screen.getAllByTestId('marker')[0])+ expect(html).toContain('>2</span>')+ expect(html).toContain('height:18px')+ })++ it('FE-COMP-MAPVIEW-032: a place visited on several days gets a wider combined badge', () => {+ render(<MapView places={[buildMapPlace({ id: 4, lat: 48, lng: 2 })]} dayOrderMap={{ 4: [1, 3] }} />)+ const html = iconHtmlOf(screen.getAllByTestId('marker')[0])+ expect(html).toContain('>1 · 3</span>')+ expect(html).toContain('height:16px')+ })+})++describe('MapView explore POIs', () => {+ it('FE-COMP-MAPVIEW-033: renders a pin per POI in its category colour with a name tooltip', () => {+ render(<MapView pois={[buildPoi()]} />)+ const poiMarker = markersWithZ('500')[0]+ expect(poiMarker).toBeTruthy()+ expect(iconHtmlOf(poiMarker)).toContain('#B45309') // cafe+ expect(poiMarker.textContent).toContain('Café Central')+ })++ it('FE-COMP-MAPVIEW-034: clicking a POI hands the whole POI back to the caller', () => {+ const onPoiClick = vi.fn()+ const poi = buildPoi({ osm_id: 'node/7' })+ render(<MapView pois={[poi]} onPoiClick={onPoiClick} />)+ fireEvent.click(markersWithZ('500')[0])+ expect(onPoiClick).toHaveBeenCalledWith(poi)+ })++ it('FE-COMP-MAPVIEW-035: an unknown POI category falls back to grey and draws no glyph', () => {+ render(<MapView pois={[buildPoi({ osm_id: 'node/8', category: 'not-a-category' })]} />)+ const html = iconHtmlOf(markersWithZ('500')[0])+ expect(html).toContain('#6b7280')+ expect(html).not.toContain('<svg')+ })++ it('FE-COMP-MAPVIEW-036: POIs of one category share a single cached icon', async () => {+ const L = await leafletMock()+ render(<MapView pois={[+ buildPoi({ osm_id: 'node/10', category: 'museum' }),+ buildPoi({ osm_id: 'node/11', category: 'museum', lat: 48.3 }),+ ]} />)+ const poiIcons = L.divIcon.mock.calls.filter(c => JSON.stringify((c[0] as { iconSize: number[] }).iconSize) === '[26,26]')+ expect(markersWithZ('500')).toHaveLength(2)+ expect(poiIcons).toHaveLength(1)+ })+})++describe('MapView plugin route vias', () => {+ const via = (overrides: Record<string, any> = {}) => ({ lat: 48.5, lng: 2.5, tone: 'default', ...overrides })++ it('FE-COMP-MAPVIEW-037: draws a tone dot for each via point', () => {+ render(<MapView routeVias={[via({ tone: 'success' }), via({ tone: 'danger', lat: 48.7 })]} />)+ const vias = markersWithZ('800')+ expect(vias).toHaveLength(2)+ expect(iconHtmlOf(vias[0])).toContain('#10b981')+ expect(iconHtmlOf(vias[1])).toContain('#ef4444')+ })++ it('FE-COMP-MAPVIEW-038: an unknown tone falls back to the default indigo', () => {+ render(<MapView routeVias={[via({ tone: 'chartreuse' })]} />)+ expect(iconHtmlOf(markersWithZ('800')[0])).toContain('#4F46E5')+ })++ it('FE-COMP-MAPVIEW-039: vias of the same tone share one cached icon', async () => {+ const L = await leafletMock()+ render(<MapView routeVias={[via({ tone: 'warn' }), via({ tone: 'warn', lat: 48.9 })]} />)+ const viaIcons = L.divIcon.mock.calls.filter(c => JSON.stringify((c[0] as { iconSize: number[] }).iconSize) === '[13,13]')+ expect(markersWithZ('800')).toHaveLength(2)+ expect(viaIcons).toHaveLength(1)+ })++ it('FE-COMP-MAPVIEW-040: a via tooltip joins its label and its dwell time', () => {+ render(<MapView routeVias={[via({ label: 'Supercharger', dwellSeconds: 5400 })]} />)+ expect(markersWithZ('800')[0].textContent).toContain('Supercharger · 1 h 30 min')+ })++ it('FE-COMP-MAPVIEW-041: a dwell under an hour is shown in minutes alone', () => {+ render(<MapView routeVias={[via({ dwellSeconds: 1500 })]} />)+ expect(markersWithZ('800')[0].textContent).toContain('25 min')+ })++ it('FE-COMP-MAPVIEW-042: a bare via carries no tooltip at all', () => {+ render(<MapView routeVias={[via()]} />)+ expect(markersWithZ('800')[0].textContent).toBe('')+ })++ it('FE-COMP-MAPVIEW-074: a via with a label but no dwell shows the label alone', () => {+ render(<MapView routeVias={[via({ label: 'Rest area' })]} />)+ expect(markersWithZ('800')[0].textContent).toBe('Rest area')+ })+})++describe('MapView map event wiring', () => {+ it('FE-COMP-MAPVIEW-043: reports the viewport bbox once the map is ready and again on every move', () => {+ const onViewportChange = vi.fn()+ render(<MapView onViewportChange={onViewportChange} />)+ expect(onViewportChange).toHaveBeenCalledWith({ south: 47, west: 1, north: 49, east: 3 })++ const moveend = handlerFor('moveend')+ const zoomend = handlerFor('zoomend')+ expect(moveend).toBeTypeOf('function')+ moveend!()+ zoomend!()+ expect(onViewportChange).toHaveBeenCalledTimes(3)+ })++ it('FE-COMP-MAPVIEW-044: no viewport callback means no listeners at all', () => {+ render(<MapView />)+ expect(mapMock.on.mock.calls.some(c => c[0] === 'moveend')).toBe(false)+ })++ it('FE-COMP-MAPVIEW-045: unmounting detaches the viewport listeners', () => {+ const { unmount } = render(<MapView onViewportChange={vi.fn()} />)+ unmount()+ expect(mapMock.off).toHaveBeenCalledWith('moveend', expect.any(Function))+ expect(mapMock.off).toHaveBeenCalledWith('zoomend', expect.any(Function))+ })++ it('FE-COMP-MAPVIEW-046: a map-click handler is attached and detached again', () => {+ const onMapClick = vi.fn()+ const { unmount } = render(<MapView onMapClick={onMapClick} />)+ expect(mapMock.on).toHaveBeenCalledWith('click', onMapClick)+ unmount()+ expect(mapMock.off).toHaveBeenCalledWith('click', onMapClick)+ })++ it('FE-COMP-MAPVIEW-047: without a click handler nothing is bound', () => {+ render(<MapView onMapClick={null} />)+ expect(mapMock.on.mock.calls.some(c => c[0] === 'click')).toBe(false)+ })++ it('FE-COMP-MAPVIEW-048: a context-menu handler is attached and detached again', () => {+ const onMapContextMenu = vi.fn()+ const { unmount } = render(<MapView onMapContextMenu={onMapContextMenu} />)+ expect(mapMock.on).toHaveBeenCalledWith('contextmenu', onMapContextMenu)+ unmount()+ expect(mapMock.off).toHaveBeenCalledWith('contextmenu', onMapContextMenu)+ })++ it('FE-COMP-MAPVIEW-049: changing the center prop moves the camera there', () => {+ const places = [buildMapPlace({ id: 1, lat: 48, lng: 2 })]+ const { rerender } = render(<MapView places={places} center={[48, 2]} zoom={9} />)+ mapMock.setView.mockClear()++ rerender(<MapView places={places} center={[35.01, 135.76]} zoom={11} />)+ expect(mapMock.setView).toHaveBeenCalledWith([35.01, 135.76], 11)++ // The same center again must not re-issue the camera move.+ mapMock.setView.mockClear()+ rerender(<MapView places={places} center={[35.01, 135.76]} zoom={11} />)+ expect(mapMock.setView).not.toHaveBeenCalled()+ })+})++describe('MapView track casing pane (#776)', () => {+ it('FE-COMP-MAPVIEW-050: creates the casing pane under the overlay pane and draws casings into it', () => {+ render(<MapView places={[buildMapPlace({+ id: 1, lat: 48, lng: 2, route_geometry: '[[48.0,2.0],[49.0,3.0]]', route_color: '#059669',+ })]} />)++ expect(mapMock.createPane).toHaveBeenCalledWith('trek-track-casing')+ expect(mapMock.panes.get('trek-track-casing')!.style.zIndex).toBe('398')++ const casing = screen.getAllByTestId('polyline')+ .find(el => JSON.parse(el.getAttribute('data-path-options') || '{}').weight === 6.5)+ expect(casing!.getAttribute('data-pane')).toBe('trek-track-casing')+ })++ it('FE-COMP-MAPVIEW-072: a renderer without pane support still draws every track', () => {+ const paneless = mapMock as unknown as Record<string, unknown>+ const { getPane, createPane } = paneless+ delete paneless.getPane+ delete paneless.createPane+ try {+ render(<MapView places={[buildMapPlace({+ id: 1, lat: 48, lng: 2, route_geometry: '[[48.0,2.0],[49.0,3.0]]',+ })]} />)+ // Casing, line and hit area are all mounted — just in insertion order.+ expect(screen.getAllByTestId('polyline')).toHaveLength(3)+ const casing = screen.getAllByTestId('polyline')+ .find(el => JSON.parse(el.getAttribute('data-path-options') || '{}').weight === 6.5)+ expect(casing!.getAttribute('data-pane')).toBe('')+ } finally {+ paneless.getPane = getPane+ paneless.createPane = createPane+ }+ })+})++describe('MapView selection panning (#921)', () => {+ it('FE-COMP-MAPVIEW-051: pans to the padding-corrected point when the map can project', () => {+ const projectable = mapMock as unknown as Record<string, unknown>+ const add = vi.fn(() => ({ x: 5, y: 6 }))+ projectable.project = vi.fn(() => ({ add }))+ projectable.unproject = vi.fn(() => [49, 4])+ try {+ const places = [buildMapPlace({ id: 8, lat: 48, lng: 2 })]+ const { rerender } = render(<MapView places={places} selectedPlaceId={null} />)+ rerender(<MapView places={places} selectedPlaceId={8} />)++ expect(projectable.project).toHaveBeenCalledWith([48, 2])+ // The offset is half the difference between the two padding corners.+ expect(add).toHaveBeenCalledWith([0, 0])+ expect(mapMock.panTo).toHaveBeenCalledWith([49, 4], { animate: true })+ } finally {+ delete projectable.project+ delete projectable.unproject+ }+ })++ it('FE-COMP-MAPVIEW-052: falls back to a plain pan when the map cannot project', () => {+ const places = [buildMapPlace({ id: 9, lat: 48, lng: 2 })]+ const { rerender } = render(<MapView places={places} selectedPlaceId={null} />)+ rerender(<MapView places={places} selectedPlaceId={9} />)+ expect(mapMock.panTo).toHaveBeenCalledWith([48, 2], { animate: true })+ })++ it('FE-COMP-MAPVIEW-053: a selected place without coordinates is not panned to', () => {+ const places = [buildMapPlace({ id: 10, lat: null, lng: null })]+ const { rerender } = render(<MapView places={places} selectedPlaceId={null} />)+ rerender(<MapView places={places} selectedPlaceId={10} />)+ expect(mapMock.panTo).not.toHaveBeenCalled()+ })+})++describe('MapView hover card', () => {+ const place = () => buildMapPlace({ id: 12, name: 'Eiffel Tower', lat: 48.85, lng: 2.29 })++ it('FE-COMP-MAPVIEW-054: mousemove keeps the card following the cursor', () => {+ render(<MapView places={[place()]} />)+ fireEvent.click(screen.getByTestId('marker-move-trigger'))+ const card = screen.getByTestId('tooltip')+ expect(card.textContent).toContain('Eiffel Tower')+ expect(card.style.left).toBe('164px') // 150 + 14+ expect(card.style.top).toBe('150px') // 160 - 10+ })++ it('FE-COMP-MAPVIEW-055: mouseout clears the card', () => {+ render(<MapView places={[place()]} />)+ fireEvent.click(screen.getByTestId('marker-hover-trigger'))+ expect(screen.getByTestId('tooltip')).toBeTruthy()++ fireEvent.click(screen.getByTestId('marker-out-trigger'))+ expect(screen.queryByTestId('tooltip')).toBeNull()+ })++ it('FE-COMP-MAPVIEW-056: scrolling the page drops the card so it cannot get orphaned', () => {+ render(<MapView places={[place()]} />)+ fireEvent.click(screen.getByTestId('marker-hover-trigger'))+ expect(screen.getByTestId('tooltip')).toBeTruthy()++ fireEvent.scroll(window)+ expect(screen.queryByTestId('tooltip')).toBeNull()+ })++ it('FE-COMP-MAPVIEW-057: hoverDisabled suppresses the card entirely', () => {+ render(<MapView places={[place()]} hoverDisabled />)+ fireEvent.click(screen.getByTestId('marker-hover-trigger'))+ fireEvent.click(screen.getByTestId('marker-move-trigger'))+ expect(screen.queryByTestId('tooltip')).toBeNull()+ })+})++describe('MapView live location', () => {+ const fix = (over: Record<string, any> = {}) => ({ lat: 48.2, lng: 16.37, accuracy: 25, heading: null, ...over })++ it('FE-COMP-MAPVIEW-058: no fix means no dot, circle or heading cone', () => {+ render(<MapView />)+ expect(screen.queryByTestId('circle-marker')).toBeNull()+ expect(screen.queryByTestId('circle')).toBeNull()+ })++ it('FE-COMP-MAPVIEW-059: a fix draws the blue dot and its accuracy circle', () => {+ geoMock.position = fix()+ geoMock.mode = 'show'+ render(<MapView />)+ expect(screen.getByTestId('circle-marker')).toBeTruthy()+ expect(screen.getByTestId('circle')).toBeTruthy()+ })++ it('FE-COMP-MAPVIEW-060: a city-level fix draws the dot but no accuracy circle', () => {+ geoMock.position = fix({ accuracy: 900 })+ geoMock.mode = 'show'+ render(<MapView />)+ expect(screen.getByTestId('circle-marker')).toBeTruthy()+ expect(screen.queryByTestId('circle')).toBeNull()+ })++ it('FE-COMP-MAPVIEW-061: a compass heading adds a rotated cone marker', () => {+ geoMock.position = fix({ heading: 135 })+ geoMock.mode = 'show'+ render(<MapView />)+ const cone = screen.getAllByTestId('marker').find(m => iconHtmlOf(m).includes('rotate(135deg)'))+ expect(cone).toBeTruthy()+ })++ it('FE-COMP-MAPVIEW-062: show mode recentres once and then leaves the camera alone', () => {+ geoMock.position = fix()+ geoMock.mode = 'show'+ const { rerender } = render(<MapView />)+ expect(mapMock.setView).toHaveBeenCalledWith([48.2, 16.37], 15)++ mapMock.setView.mockClear()+ geoMock.position = fix({ lat: 48.25 })+ // A prop change forces the re-render the new fix would otherwise not cause.+ rerender(<MapView hoverDisabled />)+ expect(mapMock.setView).not.toHaveBeenCalled()+ })++ it('FE-COMP-MAPVIEW-063: follow mode recentres on every fix at navigation zoom', () => {+ geoMock.position = fix()+ geoMock.mode = 'follow'+ render(<MapView />)+ expect(mapMock.setView).toHaveBeenCalledWith([48.2, 16.37], 16, { animate: true, duration: 0.35 })+ })++ it('FE-COMP-MAPVIEW-064: a mobile viewport gets the location button, desktop does not', () => {+ render(<MapView />)+ expect(screen.queryByRole('button', { name: 'Show my location' })).toBeNull()++ Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 420 })+ geoMock.mode = 'show'+ render(<MapView />)+ fireEvent.click(screen.getByRole('button', { name: 'Follow my location' }))+ expect(geoMock.cycleMode).toHaveBeenCalled()+ })+})++describe('MapView bounds fitting', () => {+ it('FE-COMP-MAPVIEW-065: a day-detail fit nudges the map down once the animation ran (#1348)', async () => {+ const places = [+ buildMapPlace({ id: 1, lat: 48, lng: 2 }),+ buildMapPlace({ id: 2, lat: 48.2, lng: 2.2 }),+ ]+ const { rerender } = render(<MapView places={places} dayPlaces={places} fitKey={1} hasDayDetail />)+ rerender(<MapView places={places} dayPlaces={places} fitKey={2} hasDayDetail />)++ expect(mapMock.fitBounds).toHaveBeenCalled()+ await waitFor(() => expect(mapMock.panBy).toHaveBeenCalledWith([0, 150], { animate: true }), { timeout: 2000 })+ })++ it('FE-COMP-MAPVIEW-066: a fitKey that never changed is not re-fitted', async () => {+ const L = await leafletMock()+ L.latLngBounds.mockClear()+ render(<MapView places={[buildMapPlace({ id: 1, lat: 48, lng: 2 })]} fitKey={-1} />)+ expect(L.latLngBounds).not.toHaveBeenCalled()+ })++ it('FE-COMP-MAPVIEW-067: an invalid bounds object is ignored instead of throwing', async () => {+ const L = await leafletMock()+ L.latLngBounds.mockImplementationOnce(() => ({ isValid: () => false }))+ const places = [buildMapPlace({ id: 1, lat: 48, lng: 2 })]+ const { rerender } = render(<MapView places={places} fitKey={1} />)+ mapMock.fitBounds.mockClear()+ rerender(<MapView places={places} fitKey={2} />)+ expect(mapMock.fitBounds).not.toHaveBeenCalled()+ })+})++describe('MapView photo thumbnails', () => {+ const THUMB = 'data:image/jpeg;base64,THUMBDATA'++ it('FE-COMP-MAPVIEW-068: a photo that arrives after mount is folded into the marker icon', async () => {+ render(<MapView places={[buildMapPlace({ id: 21, lat: 48, lng: 2, google_place_id: 'gp-21' })]} />)+ const deliver = thumbCallbacks.get('gp-21')+ expect(deliver).toBeTypeOf('function')++ // Two deliveries in one frame collapse into a single re-render.+ act(() => { deliver!(THUMB); deliver!(THUMB) })+ await waitFor(() => expect(iconHtmlOf(screen.getAllByTestId('marker')[0])).toContain(THUMB))+ })++ it('FE-COMP-MAPVIEW-069: re-delivering the same thumb does not change the icon', async () => {+ render(<MapView places={[buildMapPlace({ id: 22, lat: 48, lng: 2, google_place_id: 'gp-22' })]} />)+ const deliver = thumbCallbacks.get('gp-22')!+ act(() => { deliver(THUMB) })+ await waitFor(() => expect(iconHtmlOf(screen.getAllByTestId('marker')[0])).toContain(THUMB))++ const before = iconHtmlOf(screen.getAllByTestId('marker')[0])+ act(() => { deliver(THUMB) })+ await waitFor(() => expect(iconHtmlOf(screen.getAllByTestId('marker')[0])).toBe(before))+ })++ it('FE-COMP-MAPVIEW-075: an unchanged batch keeps the previous photo state object', () => {+ // Same case as above, but with the batching frame under the test's control so+ // the "nothing changed" path in the state updater really runs before teardown.+ const frames: FrameRequestCallback[] = []+ const flush = () => { frames.splice(0).forEach(cb => cb(0)) }+ vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => frames.push(cb))+ vi.stubGlobal('cancelAnimationFrame', () => { frames.length = 0 })+ try {+ render(<MapView places={[buildMapPlace({ id: 24, lat: 48, lng: 2, google_place_id: 'gp-24' })]} />)+ const deliver = thumbCallbacks.get('gp-24')!++ act(() => { deliver(THUMB) })+ act(flush)+ const withThumb = iconHtmlOf(screen.getAllByTestId('marker')[0])+ expect(withThumb).toContain(THUMB)++ act(() => { deliver(THUMB) })+ act(flush)+ expect(iconHtmlOf(screen.getAllByTestId('marker')[0])).toBe(withThumb)+ } finally {+ vi.unstubAllGlobals()+ }+ })++ it('FE-COMP-MAPVIEW-070: a place with a custom uploaded image is never auto-fetched', () => {+ render(<MapView places={[buildMapPlace({ id: 23, lat: 48, lng: 2, image_url: '/uploads/places/mine.jpg' })]} />)+ expect(thumbCallbacks.size).toBe(0)+ expect(vi.mocked(photoService.fetchPhoto)).not.toHaveBeenCalled()+ expect(iconHtmlOf(screen.getAllByTestId('marker')[0])).toContain('/uploads/places/mine.jpg')+ })++ it('FE-COMP-MAPVIEW-071: photos are not fetched at all when the feature is off', () => {+ useAuthStore.setState({ placesPhotosEnabled: false })+ render(<MapView places={[buildMapPlace({ id: 24, lat: 48, lng: 2, google_place_id: 'gp-24' })]} />)+ expect(thumbCallbacks.size).toBe(0)+ expect(vi.mocked(photoService.fetchPhoto)).not.toHaveBeenCalled()+ })})diff --git a/client/src/components/Map/MapViewGL.test.tsx b/client/src/components/Map/MapViewGL.test.tsxindex 5d675ff6d..f5afff66a 100644--- a/client/src/components/Map/MapViewGL.test.tsx+++ b/client/src/components/Map/MapViewGL.test.tsx@@ -1,12 +1,19 @@import React from 'react'import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'+import { http, HttpResponse } from 'msw'import { render } from '../../../tests/helpers/render'-import { act } from '@testing-library/react'+import { act, waitFor } from '@testing-library/react'import { resetAllStores } from '../../../tests/helpers/store'import { buildPlace } from '../../../tests/helpers/factories'+import { server } from '../../../tests/helpers/msw/server'import { useSettingsStore } from '../../store/settingsStore'+import { useAuthStore } from '../../store/authStore'import maplibregl from 'maplibre-gl'import { DEFAULT_MAP_ZOOM } from '../../constants/mapDefaults'+import type { GeoPosition, TrackingMode } from '../../hooks/useGeolocation'+import type { PluginMapLayer, PluginMapLayerFeature, PluginMapMarker } from '../../api/client'+import type { Poi } from './poiCategories'+import type { RouteVia } from '../../types'// Stable fake map so fitBounds call counts survive re-renders. The canvas// container is a single element so listeners registered by the component are@@ -37,6 +44,11 @@ const glMap = vi.hoisted(() => ({unproject: vi.fn(() => ({ lng: 2.3522, lat: 48.8566 })),getBounds: vi.fn(() => ({ getSouth: () => 0, getWest: () => 0, getNorth: () => 1, getEast: () => 1 })),easeTo: vi.fn(),+ getCanvas: vi.fn(() => document.createElement('canvas')),+ getBearing: vi.fn(() => 0),+ setTerrain: vi.fn(),+ setConfigProperty: vi.fn(),+ queryTerrainElevation: vi.fn((): number | null => null),}))const glBounds = vi.hoisted(() => {@@ -56,31 +68,77 @@ const glBounds = vi.hoisted(() => {}})+// Markers and popups are created through the mocked GL constructors, so the+// tests can reach the very instances the component built (their DOM element,+// the coordinates they were placed at, the popup content they were given).+interface FakeMarker {+ element: HTMLElement+ lngLat: number[] | null+ setLngLat: (ll: number[]) => FakeMarker+ getLngLat: () => { lng: number; lat: number }+ addTo: (map: unknown) => FakeMarker+ remove: () => void+ getElement: () => HTMLElement+}++interface FakePopup {+ setLngLat: (ll: unknown) => FakePopup+ setHTML: (html: string) => FakePopup+ setText: (text: string) => FakePopup+ setDOMContent: (node: HTMLElement) => FakePopup+ addTo: (map: unknown) => FakePopup+ remove: () => void+}++const glMarkers = vi.hoisted(() => {+ const created: FakeMarker[] = []+ return {+ get created() { return created },+ clear: () => { created.length = 0 },+ make: (opts?: { element?: HTMLElement }): FakeMarker => {+ const element = opts?.element ?? document.createElement('div')+ const marker: FakeMarker = {+ element,+ lngLat: null,+ setLngLat: vi.fn((ll: number[]) => { marker.lngLat = ll; return marker }),+ getLngLat: vi.fn(() => ({ lng: Number(marker.lngLat?.[0] ?? 0), lat: Number(marker.lngLat?.[1] ?? 0) })),+ addTo: vi.fn((_map: unknown) => marker),+ remove: vi.fn(),+ getElement: vi.fn(() => element),+ }+ created.push(marker)+ return marker+ },+ }+})++const glPopup = vi.hoisted((): FakePopup => {+ const popup: FakePopup = {+ setLngLat: vi.fn((_ll: unknown) => popup),+ setHTML: vi.fn((_html: string) => popup),+ setText: vi.fn((_text: string) => popup),+ setDOMContent: vi.fn((_node: HTMLElement) => popup),+ addTo: vi.fn((_map: unknown) => popup),+ remove: vi.fn(),+ }+ return popup+})+vi.mock('mapbox-gl', () => ({default: {accessToken: '',Map: vi.fn(function () {return glMap}),- Marker: vi.fn(function () {- return {- setLngLat: vi.fn().mockReturnThis(),- addTo: vi.fn().mockReturnThis(),- remove: vi.fn(),- getElement: vi.fn(() => document.createElement('div')),- }+ Marker: vi.fn(function (opts?: { element?: HTMLElement }) {+ return glMarkers.make(opts)}),LngLatBounds: vi.fn(function () {return glBounds.create()}),NavigationControl: vi.fn(),Popup: vi.fn(function () {- return {- setLngLat: vi.fn().mockReturnThis(),- setHTML: vi.fn().mockReturnThis(),- addTo: vi.fn().mockReturnThis(),- remove: vi.fn(),- }+ return glPopup}),},}))@@ -91,25 +149,15 @@ vi.mock('maplibre-gl', () => ({Map: vi.fn(function () {return glMap}),- Marker: vi.fn(function () {- return {- setLngLat: vi.fn().mockReturnThis(),- addTo: vi.fn().mockReturnThis(),- remove: vi.fn(),- getElement: vi.fn(() => document.createElement('div')),- }+ Marker: vi.fn(function (opts?: { element?: HTMLElement }) {+ return glMarkers.make(opts)}),LngLatBounds: vi.fn(function () {return glBounds.create()}),NavigationControl: vi.fn(),Popup: vi.fn(function () {- return {- setLngLat: vi.fn().mockReturnThis(),- setHTML: vi.fn().mockReturnThis(),- addTo: vi.fn().mockReturnThis(),- remove: vi.fn(),- }+ return glPopup}),},}))@@ -123,24 +171,33 @@ vi.mock('./mapboxSetup', () => ({addTerrainAndSky: vi.fn(),}))+const locationMarker = vi.hoisted(() => ({ update: vi.fn(), destroy: vi.fn() }))+vi.mock('./locationMarkerMapbox', () => ({- attachLocationMarker: vi.fn(() => ({ update: vi.fn() })),+ attachLocationMarker: vi.fn(() => locationMarker),+}))++const reservationOverlay = vi.hoisted(() => ({+ update: vi.fn((_reservations: unknown, _opts: unknown, _routes: unknown) => {}),+ destroy: vi.fn(),}))vi.mock('./reservationsMapbox', () => ({ReservationMapboxOverlay: vi.fn(function () {- return { update: vi.fn(), destroy: vi.fn() }+ return reservationOverlay}),}))+const geoStub = vi.hoisted(() => ({+ position: null as GeoPosition | null,+ mode: 'off' as TrackingMode,+ error: null as string | null,+ cycleMode: vi.fn(async () => {}),+ setMode: vi.fn((_m: TrackingMode | ((prev: TrackingMode) => TrackingMode)) => {}),+}))+vi.mock('../../hooks/useGeolocation', () => ({- useGeolocation: vi.fn(() => ({- position: null,- mode: 'off',- error: null,- cycleMode: vi.fn(),- setMode: vi.fn(),- })),+ useGeolocation: vi.fn(() => geoStub),}))vi.mock('../../services/photoService', () => ({@@ -152,6 +209,9 @@ vi.mock('../../services/photoService', () => ({}))import { MapViewGL } from './MapViewGL'+import * as mapboxSetup from './mapboxSetup'+import * as photoService from '../../services/photoService'+import { ReservationMapboxOverlay } from './reservationsMapbox'function buildMapPlace(overrides: Record<string, any> = {}) {return {@@ -172,6 +232,22 @@ beforeEach(() => {glMap.getLayer.mockReturnValue(null)glMap.queryRenderedFeatures.mockReturnValue([])glMap.querySourceFeatures.mockReturnValue([])+ glMap.getCanvas.mockImplementation(() => document.createElement('canvas'))+ glMap.getBearing.mockReturnValue(0)+ glMap.queryTerrainElevation.mockReturnValue(null)+ glMarkers.clear()+ // clearAllMocks() wipes call history but keeps implementations, so anything a+ // test overrides with mockReturnValue has to be put back here.+ vi.mocked(mapboxSetup.isStandardFamily).mockReturnValue(false)+ vi.mocked(mapboxSetup.supportsCustom3d).mockReturnValue(false)+ vi.mocked(mapboxSetup.wantsTerrain).mockReturnValue(false)+ vi.mocked(photoService.getCached).mockReturnValue(undefined)+ vi.mocked(photoService.isLoading).mockReturnValue(false)+ vi.mocked(photoService.onThumbReady).mockReturnValue(() => {})+ vi.mocked(photoService.getAllThumbs).mockReturnValue({})+ geoStub.position = null+ geoStub.mode = 'off'+ geoStub.error = nulluseSettingsStore.setState({settings: {...useSettingsStore.getState().settings,@@ -710,4 +786,945 @@ describe('MapViewGL', () => {await act(async () => {})expect(features()[0]?.properties).toMatchObject({ color: '#00ff00', cased: false })})++ // ── Shared helpers for the effects below ──────────────────────────────────+ // Nothing beyond the bare map is wired up until the style reports 'load', so+ // most of the overlay work only runs once that handler has fired.+ function loadOnAttach() {+ glMap.on.mockImplementation((event: string, handlerOrLayer: unknown) => {+ if (event === 'load' && typeof handlerOrLayer === 'function') (handlerOrLayer as () => void)()+ return glMap+ })+ }++ // Layer-scoped listeners are registered as (event, layerId, handler);+ // map-level ones as (event, handler).+ const layerHandler = (event: string, layerId: string) =>+ glMap.on.mock.calls.find(c => c[0] === event && c[1] === layerId)?.[2] as (e?: unknown) => void+ const mapHandler = (event: string) =>+ glMap.on.mock.calls.find(c => c[0] === event && typeof c[1] === 'function')?.[1] as (e?: unknown) => void++ interface GeoFeature {+ properties: Record<string, unknown>+ geometry: { type: string; coordinates: number[] | number[][] | number[][][] }+ }+ const geoSource = () => ({ setData: vi.fn((_data: unknown) => {}) })+ function lastData(src: ReturnType<typeof geoSource>): { features: GeoFeature[] } {+ const calls = vi.mocked(src.setData).mock.calls+ return calls[calls.length - 1][0] as { features: GeoFeature[] }+ }++ // jsdom drives requestAnimationFrame off a timer, so the marker reconcile and+ // the batched photo updates only land after a short tick.+ const flushFrames = () => act(async () => { await new Promise(resolve => setTimeout(resolve, 40)) })++ it('FE-COMP-MAPVIEWGL-023: draws a photo marker for an uploaded image and a category pin otherwise', async () => {+ loadOnAttach()+ const places = [+ buildMapPlace({ id: 11, lat: 48.11, lng: 2.11, image_url: '/uploads/places/eiffel.jpg' }),+ buildMapPlace({ id: 12, lat: 48.12, lng: 2.12, category_color: '#ff0000', category_icon: 'Utensils' }),+ ]++ render(<MapViewGL places={places} fitKey={1} dayOrderMap={{ 11: [2], 12: [1, 3] }} />)+ await act(async () => {})++ const photoMarker = glMarkers.created[0].element+ expect(photoMarker.querySelector('img')?.getAttribute('src')).toBe('/uploads/places/eiffel.jpg')+ expect(photoMarker.textContent).toContain('2')++ const pinMarker = glMarkers.created[1].element+ expect(pinMarker.querySelector('img')).toBeNull()+ expect(pinMarker.querySelector('svg')).toBeTruthy()+ expect(pinMarker.innerHTML).toContain('#ff0000')+ // A place that appears on several days lists all of them in one badge.+ expect(pinMarker.textContent).toContain('1 · 3')+ expect(glMarkers.created[1].lngLat).toEqual([2.12, 48.12])+ })++ it('FE-COMP-MAPVIEWGL-024: the hover card shows name, category and address and follows the cursor', async () => {+ loadOnAttach()+ const places = [buildMapPlace({+ id: 21, lat: 48.86, lng: 2.33, name: 'Louvre', address: 'Rue de Rivoli',+ category_name: 'Museum', category_color: '#6366f1', category_icon: 'Landmark',+ })]++ const { getByTestId, queryByTestId } = render(<MapViewGL places={places} fitKey={1} />)+ await act(async () => {})+ const el = glMarkers.created[0].element++ act(() => { el.dispatchEvent(new MouseEvent('mouseenter', { clientX: 40, clientY: 60 })) })+ const card = getByTestId('tooltip')+ expect(card.textContent).toContain('Louvre')+ expect(card.textContent).toContain('Museum')+ expect(card.textContent).toContain('Rue de Rivoli')+ expect(card.style.left).toBe('54px')++ act(() => { el.dispatchEvent(new MouseEvent('mousemove', { clientX: 100, clientY: 120 })) })+ expect(getByTestId('tooltip').style.left).toBe('114px')++ // The card is position:fixed, so a page scroll would leave it stranded.+ act(() => { window.dispatchEvent(new Event('scroll')) })+ expect(queryByTestId('tooltip')).toBeNull()+ })++ it('FE-COMP-MAPVIEWGL-025: mouseleave clears the card and hoverDisabled suppresses it entirely', async () => {+ loadOnAttach()+ const places = [buildMapPlace({ id: 22, lat: 48.86, lng: 2.33 })]++ const { queryByTestId } = render(<MapViewGL places={places} fitKey={1} />)+ await act(async () => {})+ const el = glMarkers.created[0].element+ act(() => { el.dispatchEvent(new MouseEvent('mouseenter', { clientX: 10, clientY: 10 })) })+ expect(queryByTestId('tooltip')).toBeTruthy()+ act(() => { el.dispatchEvent(new MouseEvent('mouseleave')) })+ expect(queryByTestId('tooltip')).toBeNull()++ glMarkers.clear()+ const disabled = render(<MapViewGL places={places} fitKey={1} hoverDisabled />)+ await act(async () => {})+ const disabledEl = glMarkers.created[0].element+ act(() => {+ disabledEl.dispatchEvent(new MouseEvent('mouseenter', { clientX: 10, clientY: 10 }))+ disabledEl.dispatchEvent(new MouseEvent('mousemove', { clientX: 20, clientY: 20 }))+ disabledEl.dispatchEvent(new MouseEvent('mouseleave'))+ })+ expect(disabled.queryByTestId('tooltip')).toBeNull()+ })++ it('FE-COMP-MAPVIEWGL-026: a place that disappears takes its marker and hover card with it', async () => {+ loadOnAttach()+ const kept = buildMapPlace({ id: 31, lat: 48.31, lng: 2.31 })+ const dropped = buildMapPlace({ id: 32, lat: 48.32, lng: 2.32 })++ const { rerender, queryByTestId } = render(<MapViewGL places={[kept, dropped]} fitKey={1} />)+ await act(async () => {})+ const droppedEl = glMarkers.created[1].element+ act(() => { droppedEl.dispatchEvent(new MouseEvent('mouseenter', { clientX: 10, clientY: 10 })) })+ expect(queryByTestId('tooltip')).toBeTruthy()++ rerender(<MapViewGL places={[kept]} fitKey={1} />)+ await act(async () => {})+ // Removing the marker under the cursor never fires mouseleave, so the card+ // has to be dropped by the reconcile itself.+ expect(queryByTestId('tooltip')).toBeNull()+ })++ it('FE-COMP-MAPVIEWGL-027: clicking a GPX track selects its place unless a marker or cluster is on top', async () => {+ loadOnAttach()+ const onMarkerClick = vi.fn()+ render(+ <MapViewGL+ places={[buildMapPlace({ id: 41, lat: 48, lng: 2, route_geometry: '[[48,2],[49,3]]' })]}+ fitKey={1}+ onMarkerClick={onMarkerClick}+ />,+ )+ await act(async () => {})+ const selectTrack = layerHandler('click', 'trip-gpx-hit')+ expect(selectTrack).toBeTypeOf('function')++ const trackEvent = (target: HTMLElement) => ({+ point: { x: 10, y: 10 },+ originalEvent: { target },+ features: [{ properties: { place_id: 41 } }],+ })+ act(() => { selectTrack(trackEvent(document.createElement('div'))) })+ expect(onMarkerClick).toHaveBeenCalledWith(41)++ const markerEl = document.createElement('div')+ markerEl.className = 'mapboxgl-marker'+ act(() => { selectTrack(trackEvent(markerEl)) })+ expect(onMarkerClick).toHaveBeenCalledTimes(1)++ // A cluster bubble sitting over the line owns the click (zoom-to-expand).+ glMap.getLayer.mockReturnValue({ id: 'trip-place-clusters-circle' })+ glMap.queryRenderedFeatures.mockReturnValue([{ properties: { cluster_id: 3 } }])+ act(() => { selectTrack(trackEvent(document.createElement('div'))) })+ expect(onMarkerClick).toHaveBeenCalledTimes(1)+ })++ it('FE-COMP-MAPVIEWGL-028: hovering a track turns the cursor into a pointer', async () => {+ loadOnAttach()+ const canvas = document.createElement('canvas')+ glMap.getCanvas.mockReturnValue(canvas)+ render(<MapViewGL places={[buildMapPlace({ id: 42, lat: 48, lng: 2 })]} fitKey={1} />)+ await act(async () => {})++ act(() => { layerHandler('mouseenter', 'trip-gpx-hit')() })+ expect(canvas.style.cursor).toBe('pointer')+ act(() => { layerHandler('mouseleave', 'trip-gpx-hit')() })+ expect(canvas.style.cursor).toBe('')++ act(() => { layerHandler('mouseenter', 'trip-place-clusters-circle')() })+ expect(canvas.style.cursor).toBe('pointer')+ act(() => { layerHandler('mouseleave', 'trip-place-clusters-circle')() })+ expect(canvas.style.cursor).toBe('')+ })++ it('FE-COMP-MAPVIEWGL-029: clicking a cluster bubble eases in to its expansion zoom', async () => {+ loadOnAttach()+ render(<MapViewGL places={[buildMapPlace({ id: 43, lat: 48, lng: 2 })]} fitKey={1} />)+ await act(async () => {})+ const zoomToCluster = layerHandler('click', 'trip-place-clusters-circle')+ expect(zoomToCluster).toBeTypeOf('function')++ const clusterFeature = { properties: { cluster_id: 7 }, geometry: { coordinates: [2, 48] } }+ glMap.queryRenderedFeatures.mockReturnValue([clusterFeature])+ const clusterSource: { getClusterExpansionZoom: (id: number, cb: (err: Error | null, zoom: number) => void) => number | Promise<number> | undefined } = {+ getClusterExpansionZoom: vi.fn((_id: number, cb: (err: Error | null, zoom: number) => void) => { cb(null, 12); return undefined }),+ }+ glMap.getSource.mockImplementation((id: string) => (id === 'trip-place-clusters' ? clusterSource : null))++ act(() => { zoomToCluster({ point: { x: 5, y: 5 } }) })+ expect(glMap.easeTo).toHaveBeenCalledWith({ center: [2, 48], zoom: 12, duration: 350 })++ // maplibre resolves the zoom as a promise instead of a callback.+ glMap.easeTo.mockClear()+ clusterSource.getClusterExpansionZoom = vi.fn(() => Promise.resolve(9))+ await act(async () => { zoomToCluster({ point: { x: 5, y: 5 } }) })+ expect(glMap.easeTo).toHaveBeenCalledWith({ center: [2, 48], zoom: 9, duration: 350 })++ // Older SDKs return the zoom straight from the call.+ glMap.easeTo.mockClear()+ glMap.queryRenderedFeatures.mockReturnValue([clusterFeature])+ clusterSource.getClusterExpansionZoom = vi.fn(() => 14)+ act(() => { zoomToCluster({ point: { x: 5, y: 5 } }) })+ expect(glMap.easeTo).toHaveBeenCalledWith({ center: [2, 48], zoom: 14, duration: 350 })++ // A failed expansion lookup leaves the camera where it is.+ glMap.easeTo.mockClear()+ clusterSource.getClusterExpansionZoom = vi.fn((_id: number, cb: (err: Error | null, zoom: number) => void) => {+ cb(new Error('cluster gone'), 0)+ return undefined+ })+ act(() => { zoomToCluster({ point: { x: 5, y: 5 } }) })+ expect(glMap.easeTo).not.toHaveBeenCalled()++ // A click that hits no cluster is a no-op.+ glMap.queryRenderedFeatures.mockReturnValue([])+ act(() => { zoomToCluster({ point: { x: 5, y: 5 } }) })+ expect(glMap.easeTo).not.toHaveBeenCalled()+ })++ it('FE-COMP-MAPVIEWGL-030: a labelled plugin layer feature answers a click with a plain-text popup', async () => {+ loadOnAttach()+ render(<MapViewGL places={[]} fitKey={1} />)+ await act(async () => {})+ const showLabel = layerHandler('click', 'trek-plugin-layers-fill')+ expect(showLabel).toBeTypeOf('function')++ act(() => { showLabel({ lngLat: { lng: 2, lat: 48 }, features: [{ properties: { label: 'Charging corridor' } }] }) })+ expect(glPopup.setText).toHaveBeenCalledWith('Charging corridor')++ // Unlabelled features stay inert.+ vi.mocked(glPopup.setText).mockClear()+ act(() => { showLabel({ lngLat: { lng: 2, lat: 48 }, features: [{ properties: { label: '' } }] }) })+ expect(glPopup.setText).not.toHaveBeenCalled()+ })++ it('FE-COMP-MAPVIEWGL-031: a map click on a marker, a cluster or a track never drops a new place', async () => {+ loadOnAttach()+ const onMapClick = vi.fn()+ render(<MapViewGL places={[]} fitKey={1} onMapClick={onMapClick} />)+ await act(async () => {})+ const click = mapHandler('click')++ const markerEl = document.createElement('div')+ markerEl.className = 'maplibregl-marker'+ act(() => { click({ point: { x: 1, y: 1 }, lngLat: { lat: 1, lng: 2 }, originalEvent: { target: markerEl } }) })+ expect(onMapClick).not.toHaveBeenCalled()++ glMap.getLayer.mockImplementation((id: string) => (id === 'trip-place-clusters-circle' ? { id } : null))+ glMap.queryRenderedFeatures.mockReturnValue([{ properties: { cluster_id: 1 } }])+ act(() => { click({ point: { x: 1, y: 1 }, lngLat: { lat: 1, lng: 2 }, originalEvent: { target: glCanvasContainer } }) })+ expect(onMapClick).not.toHaveBeenCalled()++ glMap.getLayer.mockImplementation((id: string) => (id === 'trip-gpx-hit' ? { id } : null))+ glMap.queryRenderedFeatures.mockImplementation((_point: unknown, opts: { layers: string[] }) => (+ opts.layers.includes('trip-gpx-hit') ? [{ properties: { place_id: 9 } }] : []+ ))+ act(() => { click({ point: { x: 1, y: 1 }, lngLat: { lat: 1, lng: 2 }, originalEvent: { target: glCanvasContainer } }) })+ expect(onMapClick).not.toHaveBeenCalled()++ glMap.getLayer.mockReturnValue(null)+ act(() => { click({ point: { x: 1, y: 1 }, lngLat: { lat: 1, lng: 2 }, originalEvent: { target: glCanvasContainer } }) })+ expect(onMapClick).toHaveBeenCalledWith({ latlng: { lat: 1, lng: 2 } })+ })++ it('FE-COMP-MAPVIEWGL-032: the tap that ends a long-press is swallowed exactly once (#1398)', async () => {+ vi.useFakeTimers()+ try {+ const onContext = vi.fn()+ const onMapClick = vi.fn()+ render(<MapViewGL places={[]} fitKey={1} onMapContextMenu={onContext} onMapClick={onMapClick} />)+ await act(async () => {})+ const click = mapHandler('click')++ act(() => {+ glCanvasContainer.dispatchEvent(touchEvent('touchstart', [{ clientX: 30, clientY: 40 }]))+ vi.advanceTimersByTime(650)+ })+ expect(onContext).toHaveBeenCalledTimes(1)++ act(() => { click({ point: { x: 1, y: 1 }, lngLat: { lat: 1, lng: 2 }, originalEvent: { target: glCanvasContainer } }) })+ expect(onMapClick).not.toHaveBeenCalled()+ // The flag is consumed, so the next click is a real one again.+ act(() => { click({ point: { x: 1, y: 1 }, lngLat: { lat: 1, lng: 2 }, originalEvent: { target: glCanvasContainer } }) })+ expect(onMapClick).toHaveBeenCalledTimes(1)+ } finally {+ vi.useRealTimers()+ }+ })++ it('FE-COMP-MAPVIEWGL-033: a left-click is not an Add-Place gesture and only middle auxclick is suppressed', async () => {+ const onContext = vi.fn()+ render(<MapViewGL places={[]} fitKey={1} onMapContextMenu={onContext} />)+ await act(async () => {})++ act(() => { glCanvasContainer.dispatchEvent(new MouseEvent('mousedown', { button: 0, bubbles: true })) })+ expect(onContext).not.toHaveBeenCalled()++ const middle = new MouseEvent('auxclick', { button: 1, bubbles: true, cancelable: true })+ act(() => { glCanvasContainer.dispatchEvent(middle) })+ expect(middle.defaultPrevented).toBe(true)++ const right = new MouseEvent('auxclick', { button: 2, bubbles: true, cancelable: true })+ act(() => { glCanvasContainer.dispatchEvent(right) })+ expect(right.defaultPrevented).toBe(false)+ })++ it('FE-COMP-MAPVIEWGL-034: a long-press that starts on a marker never opens Add-Place', async () => {+ vi.useFakeTimers()+ const markerEl = document.createElement('div')+ markerEl.className = 'mapboxgl-marker'+ glCanvasContainer.appendChild(markerEl)+ try {+ const onContext = vi.fn()+ render(<MapViewGL places={[]} fitKey={1} onMapContextMenu={onContext} />)+ await act(async () => {})+ act(() => {+ markerEl.dispatchEvent(touchEvent('touchstart', [{ clientX: 30, clientY: 40 }]))+ vi.advanceTimersByTime(650)+ })+ expect(onContext).not.toHaveBeenCalled()+ } finally {+ vi.useRealTimers()+ markerEl.remove()+ }+ })++ it('FE-COMP-MAPVIEWGL-035: panning the map by hand drops follow mode but leaves the other modes alone', async () => {+ render(<MapViewGL places={[]} fitKey={1} />)+ await act(async () => {})++ act(() => { mapHandler('dragstart')() })+ expect(geoStub.setMode).toHaveBeenCalledTimes(1)+ const updater = geoStub.setMode.mock.calls[0][0] as (prev: TrackingMode) => TrackingMode+ expect(updater('follow')).toBe('show')+ expect(updater('show')).toBe('show')+ expect(updater('off')).toBe('off')+ })++ it('FE-COMP-MAPVIEWGL-036: with 3D on it injects terrain plus buildings and pins markers to the DEM', async () => {+ loadOnAttach()+ vi.mocked(mapboxSetup.wantsTerrain).mockReturnValue(true)+ vi.mocked(mapboxSetup.supportsCustom3d).mockReturnValue(true)+ useSettingsStore.setState({+ settings: {+ ...useSettingsStore.getState().settings,+ mapbox_style: 'mapbox://styles/mapbox/satellite-v9',+ mapbox_3d_enabled: true,+ },+ } as any)+ glMap.queryTerrainElevation.mockReturnValue(120)++ render(<MapViewGL places={[buildMapPlace({ id: 51, lat: 48.5, lng: 2.5 })]} fitKey={1} />)+ await act(async () => {})++ expect(mapboxSetup.addTerrainAndSky).toHaveBeenCalledWith(glMap)+ expect(mapboxSetup.addCustom3dBuildings).toHaveBeenCalledWith(glMap, false)++ const marker = glMarkers.created[glMarkers.created.length - 1]+ act(() => { mapHandler('render')() })+ expect(vi.mocked(marker.setLngLat)).toHaveBeenLastCalledWith([2.5, 48.5, 120])++ // ~12 Hz throttle: a second frame straight away must not re-project.+ const callsAfterFirstFrame = vi.mocked(marker.setLngLat).mock.calls.length+ act(() => { mapHandler('render')() })+ expect(vi.mocked(marker.setLngLat).mock.calls.length).toBe(callsAfterFirstFrame)+ })++ it('FE-COMP-MAPVIEWGL-037: markers stay put while the terrain DEM is still streaming in', async () => {+ loadOnAttach()+ useSettingsStore.setState({+ settings: { ...useSettingsStore.getState().settings, mapbox_3d_enabled: true },+ } as any)+ glMap.queryTerrainElevation.mockImplementation(() => { throw new Error('terrain not ready') })++ render(<MapViewGL places={[buildMapPlace({ id: 52, lat: 48.5, lng: 2.5 })]} fitKey={1} />)+ await act(async () => {})+ const marker = glMarkers.created[glMarkers.created.length - 1]+ const before = vi.mocked(marker.setLngLat).mock.calls.length++ act(() => { mapHandler('render')() })+ expect(vi.mocked(marker.setLngLat).mock.calls.length).toBe(before)+ })++ it('FE-COMP-MAPVIEWGL-038: the Standard style is flattened and pinned to the UI label language (#1299)', async () => {+ loadOnAttach()+ vi.mocked(mapboxSetup.isStandardFamily).mockReturnValue(true)+ useSettingsStore.setState({+ settings: {+ ...useSettingsStore.getState().settings,+ mapbox_style: 'mapbox://styles/mapbox/standard',+ mapbox_3d_enabled: true,+ language: 'zh',+ },+ } as any)++ render(<MapViewGL places={[buildMapPlace({ id: 53, lat: 48, lng: 2 })]} fitKey={1} />)+ await act(async () => {})++ // Standard's own DEM would lift the buildings off the sea-level markers.+ expect(glMap.setTerrain).toHaveBeenCalledWith(null)+ expect(glMap.setConfigProperty).toHaveBeenCalledWith('basemap', 'language', 'zh-Hans')+ // It ships its own 3D, so nothing extra is injected.+ expect(mapboxSetup.addTerrainAndSky).not.toHaveBeenCalled()+ expect(mapboxSetup.addCustom3dBuildings).not.toHaveBeenCalled()+ })++ it('FE-COMP-MAPVIEWGL-039: a fix attaches the blue dot and follow mode eases the camera onto it', async () => {+ const position: GeoPosition = { lat: 48.86, lng: 2.35, accuracy: 12, heading: 90, speed: null, timestamp: 1 }+ geoStub.position = position+ geoStub.mode = 'follow'++ render(<MapViewGL places={[]} fitKey={1} />)+ await act(async () => {})++ expect(locationMarker.update).toHaveBeenCalledWith(position)+ expect(glMap.easeTo).toHaveBeenCalledWith({ center: [2.35, 48.86], bearing: 90, zoom: 16, duration: 350 })+ })++ it('FE-COMP-MAPVIEWGL-040: the dot waits for the style, follows tracking changes and is destroyed on unmount', async () => {+ glMap.loaded.mockReturnValue(false)+ geoStub.position = { lat: 48.86, lng: 2.35, accuracy: 12, heading: null, speed: null, timestamp: 1 }+ geoStub.mode = 'show'++ const { rerender, unmount } = render(<MapViewGL places={[]} fitKey={1} />)+ await act(async () => {})+ expect(locationMarker.update).not.toHaveBeenCalled()++ const apply = glMap.once.mock.calls.find(c => c[0] === 'load')?.[1] as () => void+ act(() => { apply() })+ expect(locationMarker.update).toHaveBeenCalledTimes(1)+ // 'show' means the dot stays but the camera does not chase it.+ expect(glMap.easeTo).not.toHaveBeenCalled()++ geoStub.mode = 'off'+ rerender(<MapViewGL places={[]} fitKey={1} />)+ await act(async () => {})+ expect(locationMarker.update).toHaveBeenLastCalledWith(null)++ unmount()+ expect(locationMarker.destroy).toHaveBeenCalled()+ })++ it('FE-COMP-MAPVIEWGL-041: the reservation overlay reports endpoint clicks back to the caller', async () => {+ loadOnAttach()+ const onReservationClick = vi.fn()+ render(+ <MapViewGL places={[]} fitKey={1} reservations={[]} showReservationStats onReservationClick={onReservationClick} />,+ )+ await act(async () => {})++ const options = reservationOverlay.update.mock.calls[0][1] as {+ showConnections: boolean+ showStats: boolean+ onEndpointClick: (id: number) => void+ }+ expect(options.showConnections).toBe(true)+ expect(options.showStats).toBe(true)+ options.onEndpointClick(77)+ expect(onReservationClick).toHaveBeenCalledWith(77)+ })++ it('FE-COMP-MAPVIEWGL-042: explore POIs get their own pin, hover popup and click callback', async () => {+ loadOnAttach()+ const basePoi: Poi = {+ osm_id: 'n1', name: 'Café de Flore', lat: 48.854, lng: 2.332, category: 'cafe',+ poi_type: 'cafe', address: null, website: null, phone: null, opening_hours: null,+ cuisine: null, source: 'openstreetmap',+ }+ const unknownPoi: Poi = { ...basePoi, osm_id: 'n2', name: 'Spaceport', category: 'spaceport' }+ const onPoiClick = vi.fn()++ render(<MapViewGL places={[]} fitKey={1} pois={[basePoi, unknownPoi]} onPoiClick={onPoiClick} />)+ await act(async () => {})++ expect(glMarkers.created).toHaveLength(2)+ const el = glMarkers.created[0].element+ expect(el.innerHTML).toContain('#B45309')++ act(() => { el.dispatchEvent(new MouseEvent('mouseenter')) })+ expect(glPopup.setLngLat).toHaveBeenCalledWith([2.332, 48.854])+ expect(glPopup.setHTML).toHaveBeenCalledWith(expect.stringContaining('Café de Flore'))+ expect(glPopup.addTo).toHaveBeenCalledWith(glMap)++ vi.mocked(glPopup.remove).mockClear()+ act(() => { el.dispatchEvent(new MouseEvent('mouseleave')) })+ expect(glPopup.remove).toHaveBeenCalled()++ act(() => { el.dispatchEvent(new MouseEvent('click')) })+ expect(onPoiClick).toHaveBeenCalledWith(basePoi)++ // An unknown category falls back to the neutral grey pin without an icon.+ expect(glMarkers.created[1].element.innerHTML).toContain('#6b7280')+ })++ it('FE-COMP-MAPVIEWGL-043: plugin markers render as tone dots with a text-only popup', async () => {+ loadOnAttach()+ const markers: PluginMapMarker[] = [+ { pluginId: 'ev', id: 'm1', lat: 48.5, lng: 2.5, tone: 'success', label: 'Fastned', popupText: '150 kW', url: 'https://example.com/c' },+ { pluginId: 'ev', id: 'm2', lat: 48.6, lng: 2.6, tone: 'default' },+ ]+ server.use(+ http.get('/api/map-markers/:tripId', () => HttpResponse.json({ markers })),+ http.get('/api/map-layers/:tripId', () => HttpResponse.json({ layers: [] })),+ )++ render(<MapViewGL places={[]} fitKey={1} tripId={4} />)+ await waitFor(() => expect(glMarkers.created).toHaveLength(2))++ expect(glMarkers.created[0].element.innerHTML).toContain('#10b981')+ act(() => { glMarkers.created[0].element.dispatchEvent(new MouseEvent('click')) })+ const box = vi.mocked(glPopup.setDOMContent).mock.calls[0][0]+ expect(box.textContent).toContain('Fastned')+ expect(box.textContent).toContain('150 kW')+ expect(box.querySelector('a')?.getAttribute('href')).toBe('https://example.com/c')++ // A bare marker carries no popup at all.+ vi.mocked(glPopup.setDOMContent).mockClear()+ act(() => { glMarkers.created[1].element.dispatchEvent(new MouseEvent('click')) })+ expect(glPopup.setDOMContent).not.toHaveBeenCalled()+ })++ it('FE-COMP-MAPVIEWGL-044: plugin layer features become one geojson source with closed rings', async () => {+ loadOnAttach()+ const features: PluginMapLayerFeature[] = [+ { type: 'polyline', points: [[48, 2], [49, 3]], tone: 'warn', width: 4, dash: 'dash', opacity: 0.6, fill: false },+ { type: 'polygon', points: [[48, 2], [48, 3], [49, 3]], tone: 'danger', width: 2, dash: 'solid', opacity: 0.8, fill: true },+ { type: 'circle', center: [48, 2], radiusM: 1000, tone: 'nonsense' as PluginMapLayerFeature['tone'], width: 2, dash: 'dot', opacity: 0.4, fill: false },+ { type: 'polyline', tone: 'default', width: 2, dash: 'solid', opacity: 1, fill: false },+ ]+ const layers: PluginMapLayer[] = [{ pluginId: 'ev', id: 'corridor', features }]+ server.use(+ http.get('/api/map-markers/:tripId', () => HttpResponse.json({ markers: [] })),+ http.get('/api/map-layers/:tripId', () => HttpResponse.json({ layers })),+ )+ const pluginSource = geoSource()++ render(<MapViewGL places={[]} fitKey={1} tripId={4} />)+ glMap.getSource.mockImplementation((id: string) => (id === 'trek-plugin-layers' ? pluginSource : null))+ await waitFor(() => expect(lastData(pluginSource).features).toHaveLength(3))++ const [line, polygon, circle] = lastData(pluginSource).features+ expect(line.geometry).toEqual({ type: 'LineString', coordinates: [[2, 48], [3, 49]] })+ expect(line.properties).toMatchObject({ id: 'ev:corridor:0', color: '#f59e0b', dash: 'dash', fillOpacity: 0 })++ const ring = polygon.geometry.coordinates[0] as unknown as number[][]+ expect(ring[0]).toEqual(ring[ring.length - 1])+ // A filled shape never drowns the basemap.+ expect(polygon.properties.fillOpacity).toBe(0.25)++ // A metric circle is approximated as a polygon, since GL circles size in pixels.+ const circleRing = circle.geometry.coordinates[0] as unknown as number[][]+ expect(circleRing).toHaveLength(65)+ expect(circleRing[0][0]).toBeCloseTo(2 + 1000 / (111320 * Math.cos(48 * Math.PI / 180)), 4)+ // Unknown tones fall back to the default indigo.+ expect(circle.properties.color).toBe('#4F46E5')+ })++ it('FE-COMP-MAPVIEWGL-045: failing plugin contributions leave the core map untouched', async () => {+ loadOnAttach()+ server.use(+ http.get('/api/map-markers/:tripId', () => HttpResponse.json({ error: 'down' }, { status: 500 })),+ http.get('/api/map-layers/:tripId', () => HttpResponse.json({ error: 'down' }, { status: 500 })),+ )+ const pluginSource = geoSource()++ const { rerender } = render(<MapViewGL places={[]} fitKey={1} tripId={4} />)+ glMap.getSource.mockImplementation((id: string) => (id === 'trek-plugin-layers' ? pluginSource : null))+ await act(async () => {})+ expect(glMarkers.created).toHaveLength(0)++ // Dropping the trip clears whatever was there.+ rerender(<MapViewGL places={[]} fitKey={1} />)+ await act(async () => {})+ expect(lastData(pluginSource).features).toHaveLength(0)+ })++ it('FE-COMP-MAPVIEWGL-046: plugin route via points show their label and dwell time on tap', async () => {+ loadOnAttach()+ const routeVias: RouteVia[] = [+ { lat: 48.5, lng: 2.5, tone: 'success', label: 'Fastned', dwellSeconds: 4500 },+ { lat: 48.6, lng: 2.6, tone: 'warn', dwellSeconds: 900 },+ { lat: 48.7, lng: 2.7, tone: 'default' },+ ]++ render(<MapViewGL places={[]} fitKey={1} routeVias={routeVias} />)+ await act(async () => {})+ expect(glMarkers.created).toHaveLength(3)++ act(() => { glMarkers.created[0].element.dispatchEvent(new MouseEvent('click')) })+ expect(glPopup.setText).toHaveBeenCalledWith('Fastned · 1 h 15 min')++ act(() => { glMarkers.created[1].element.dispatchEvent(new MouseEvent('click')) })+ expect(glPopup.setText).toHaveBeenLastCalledWith('15 min')++ // Neither label nor dwell time: nothing to show, so the dot stays inert.+ act(() => { glMarkers.created[2].element.dispatchEvent(new MouseEvent('click')) })+ expect(glPopup.setText).toHaveBeenCalledTimes(2)+ })++ it('FE-COMP-MAPVIEWGL-047: only the unclustered leaves of the cluster source get a rich marker (#1385)', async () => {+ loadOnAttach()+ const clusterSource = geoSource()+ glMap.getSource.mockImplementation((id: string) => (id === 'trip-place-clusters' ? clusterSource : null))+ glMap.querySourceFeatures.mockReturnValue([+ { properties: { placeId: 61 } },+ { properties: { placeId: '62' } }, // vector-tile encoders hand ids back as strings+ { properties: { placeId: 62 } }, // …and can repeat them+ { properties: { placeId: 999 } }, // no longer in the trip+ { properties: { placeId: 'nope' } },+ { properties: {} },+ ])+ const places = [+ buildMapPlace({ id: 61, lat: 48.1, lng: 2.1 }),+ buildMapPlace({ id: 62, lat: 48.2, lng: 2.2 }),+ buildMapPlace({ id: 63, lat: 48.3, lng: 2.3 }),+ ]++ render(<MapViewGL places={places} fitKey={1} />)+ await flushFrames()++ const source = lastData(clusterSource)+ expect(source.features).toHaveLength(3)+ expect(source.features[0].properties.placeId).toBe(61)+ expect(source.features[0].geometry.coordinates).toEqual([2.1, 48.1])++ const drawn = glMarkers.created.map(m => m.lngLat)+ expect(drawn).toContainEqual([2.1, 48.1])+ expect(drawn).toContainEqual([2.2, 48.2])+ // 63 is inside a cluster bubble, so no HTML marker is drawn for it.+ expect(drawn).not.toContainEqual([2.3, 48.3])+ })++ it('FE-COMP-MAPVIEWGL-048: the day route becomes one LineString per drawn segment', async () => {+ const routeSource = geoSource()+ glMap.getSource.mockImplementation((id: string) => (id === 'trip-route' ? routeSource : null))++ render(<MapViewGL places={[]} fitKey={1} route={[[[48, 2], [49, 3]], [[50, 4]]]} />)+ await act(async () => {})++ const { features } = lastData(routeSource)+ // A one-point segment is not a line.+ expect(features).toHaveLength(1)+ expect(features[0].geometry.coordinates).toEqual([[2, 48], [3, 49]])+ })++ it('FE-COMP-MAPVIEWGL-049: unusable GPX geometry is skipped instead of breaking the layer', async () => {+ const gpxSource = geoSource()+ glMap.getSource.mockImplementation((id: string) => (id === 'trip-gpx' ? gpxSource : null))+ const places = [+ buildMapPlace({ id: 71, lat: 48, lng: 2, route_geometry: null }),+ buildMapPlace({ id: 72, lat: 48, lng: 2, route_geometry: '[[48,2]]' }),+ buildMapPlace({ id: 73, lat: 48, lng: 2, route_geometry: 'not json at all' }),+ buildMapPlace({ id: 74, lat: 48, lng: 2, route_geometry: '[[48,2],[49,3]]' }),+ ]++ render(<MapViewGL places={places} fitKey={1} />)+ await act(async () => {})++ const { features } = lastData(gpxSource)+ expect(features).toHaveLength(1)+ expect(features[0].properties.place_id).toBe(74)+ })++ it('FE-COMP-MAPVIEWGL-050: without a Mapbox token it shows the settings hint and touches no camera', async () => {+ const mapboxgl = (await import('mapbox-gl')).default+ useSettingsStore.setState({+ settings: { ...useSettingsStore.getState().settings, mapbox_access_token: '' },+ } as any)+ const places = [buildMapPlace({ id: 81, lat: 48, lng: 2 })]++ const { container, rerender } = render(<MapViewGL places={places} fitKey={1} center={[1, 2]} />)+ await act(async () => {})+ expect(container.textContent).toContain('No Mapbox access token configured')+ expect(container.textContent).toContain('Settings → Map → Mapbox GL')+ expect(mapboxgl.Map).not.toHaveBeenCalled()++ rerender(<MapViewGL places={places} fitKey={2} center={[10, 20]} />)+ await act(async () => {})+ expect(glMap.fitBounds).not.toHaveBeenCalled()+ expect(glMap.jumpTo).not.toHaveBeenCalled()+ })++ it('FE-COMP-MAPVIEWGL-051: a later centre prop change jumps the camera in [lng, lat] order', async () => {+ const { rerender } = render(<MapViewGL places={[]} fitKey={1} center={[48, 2]} zoom={9} />)+ await act(async () => {})+ expect(glMap.jumpTo).not.toHaveBeenCalled()++ rerender(<MapViewGL places={[]} fitKey={1} center={[35.68, 139.69]} zoom={9} />)+ await act(async () => {})+ expect(glMap.jumpTo).toHaveBeenCalledWith({ center: [139.69, 35.68], zoom: 9 })+ })++ it('FE-COMP-MAPVIEWGL-052: a fit that throws before the style is ready is retried on load', async () => {+ const places = [+ buildMapPlace({ id: 82, lat: 48.1, lng: 2.1 }),+ buildMapPlace({ id: 83, lat: 48.2, lng: 2.2 }),+ ]+ const { rerender } = render(<MapViewGL places={places} fitKey={1} />)+ await act(async () => {})++ glMap.fitBounds.mockImplementationOnce(() => { throw new Error('style not ready') })+ rerender(<MapViewGL places={places} fitKey={2} />)+ await act(async () => {})+ expect(glMap.fitBounds).toHaveBeenCalledTimes(1)++ const retry = glMap.once.mock.calls.find(c => c[0] === 'load')?.[1] as () => void+ expect(retry).toBeTypeOf('function')+ act(() => { retry() })+ expect(glMap.fitBounds).toHaveBeenCalledTimes(2)+ })++ it('FE-COMP-MAPVIEWGL-053: on a phone it shows the location FAB, uses mobile padding and hides the hover card', async () => {+ loadOnAttach()+ const original = window.innerWidth+ Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 420 })+ try {+ const places = [+ buildMapPlace({ id: 84, lat: 48.1, lng: 2.1 }),+ buildMapPlace({ id: 85, lat: 48.2, lng: 2.2 }),+ ]+ const { rerender, getByRole, queryByTestId } = render(<MapViewGL places={places} fitKey={1} hasDayDetail />)+ await act(async () => {})+ expect(getByRole('button', { name: 'Show my location' })).toBeTruthy()++ act(() => { glMarkers.created[0].element.dispatchEvent(new MouseEvent('mouseenter', { clientX: 5, clientY: 5 })) })+ expect(queryByTestId('tooltip')).toBeNull()++ rerender(<MapViewGL places={places} fitKey={2} hasDayDetail />)+ await act(async () => {})+ const fitOptions = glMap.fitBounds.mock.calls[0][1] as { padding: Record<string, number> }+ expect(fitOptions.padding).toEqual({ top: 40, right: 20, bottom: 40, left: 20 })+ } finally {+ Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: original })+ }+ })++ it('FE-COMP-MAPVIEWGL-054: desktop padding leaves room for the side panels and the inspector', async () => {+ const places = [+ buildMapPlace({ id: 86, lat: 48.1, lng: 2.1 }),+ buildMapPlace({ id: 87, lat: 48.2, lng: 2.2 }),+ ]+ const { rerender } = render(<MapViewGL places={places} fitKey={1} leftWidth={300} rightWidth={360} hasInspector />)+ await act(async () => {})++ rerender(<MapViewGL places={places} fitKey={2} leftWidth={300} rightWidth={360} hasInspector />)+ await act(async () => {})+ const fitOptions = glMap.fitBounds.mock.calls[0][1] as { padding: Record<string, number>; maxZoom: number }+ expect(fitOptions.padding).toEqual({ top: 60, right: 400, bottom: 320, left: 340 })+ expect(fitOptions.maxZoom).toBe(15)+ })++ it('FE-COMP-MAPVIEWGL-055: cached thumbs paint the marker while a custom upload is never re-fetched (#1136)', async () => {+ loadOnAttach()+ const thumbListeners: Record<string, (thumb: string) => void> = {}+ vi.mocked(photoService.getCached).mockImplementation((key: string) => (+ key === 'gp-1'+ ? ({ thumbDataUrl: 'data:image/png;base64,AAA' } as unknown as ReturnType<typeof photoService.getCached>)+ : undefined+ ))+ vi.mocked(photoService.onThumbReady).mockImplementation((key: string, fn: (thumb: string) => void) => {+ thumbListeners[key] = fn+ return () => {}+ })+ const places = [+ buildMapPlace({ id: 91, lat: 48.1, lng: 2.1, google_place_id: 'gp-1' }),+ buildMapPlace({ id: 92, lat: 48.2, lng: 2.2, osm_id: 'osm-2', name: 'Bar' }),+ buildMapPlace({ id: 93, lat: 48.3, lng: 2.3, image_url: '/uploads/places/own.jpg' }),+ ]++ render(<MapViewGL places={places} fitKey={1} />)+ await flushFrames()++ // Only the place without a cached photo and without a custom image is fetched.+ expect(photoService.fetchPhoto).toHaveBeenCalledTimes(1)+ expect(photoService.fetchPhoto).toHaveBeenCalledWith('osm-2', 'osm-2', 48.2, 2.2, 'Bar')++ const srcs = () => glMarkers.created.map(m => m.element.querySelector('img')?.getAttribute('src'))+ expect(srcs()).toContain('data:image/png;base64,AAA')+ expect(srcs()).toContain('/uploads/places/own.jpg')++ await act(async () => {+ thumbListeners['osm-2']?.('data:image/png;base64,BBB')+ await new Promise(resolve => setTimeout(resolve, 40))+ })+ expect(srcs()).toContain('data:image/png;base64,BBB')+ })++ it('FE-COMP-MAPVIEWGL-056: an in-flight photo is not requested twice and the proxy url is used as the id', async () => {+ vi.mocked(photoService.isLoading).mockImplementation((key: string) => key === 'osm-loading')+ const places = [+ buildMapPlace({ id: 94, lat: 48.4, lng: 2.4, osm_id: 'osm-loading' }),+ buildMapPlace({ id: 95, lat: 48.5, lng: 2.5, osm_id: 'osm-5', image_url: '/api/maps/place-photo/abc', name: 'Museum' }),+ ]++ render(<MapViewGL places={places} fitKey={1} />)+ await act(async () => {})++ expect(photoService.fetchPhoto).toHaveBeenCalledTimes(1)+ expect(photoService.fetchPhoto).toHaveBeenCalledWith('osm-5', '/api/maps/place-photo/abc', 48.5, 2.5, 'Museum')+ })++ it('FE-COMP-MAPVIEWGL-057: no photos are fetched when place photos are switched off', async () => {+ useAuthStore.setState({ placesPhotosEnabled: false })++ render(<MapViewGL places={[buildMapPlace({ id: 96, lat: 48, lng: 2, osm_id: 'osm-6' })]} fitKey={1} />)+ await act(async () => {})++ expect(photoService.fetchPhoto).not.toHaveBeenCalled()+ expect(photoService.onThumbReady).not.toHaveBeenCalled()+ })++ it('FE-COMP-MAPVIEWGL-058: unmounting unsubscribes the thumb listeners and drops the map', async () => {+ const dispose = vi.fn()+ const thumbListeners: Record<string, (thumb: string) => void> = {}+ vi.mocked(photoService.onThumbReady).mockImplementation((key: string, fn: (thumb: string) => void) => {+ thumbListeners[key] = fn+ return dispose+ })+ glMap.remove.mockImplementation(() => { throw new Error('context already lost') })++ const { unmount } = render(<MapViewGL places={[buildMapPlace({ id: 97, lat: 48, lng: 2, osm_id: 'osm-7' })]} fitKey={1} />)+ await act(async () => {})+ // A thumb arriving just before unmount leaves a frame scheduled.+ act(() => { thumbListeners['osm-7']?.('data:image/png;base64,CCC') })++ expect(() => unmount()).not.toThrow()+ expect(dispose).toHaveBeenCalled()+ expect(glMap.remove).toHaveBeenCalled()+ })++ it('FE-COMP-MAPVIEWGL-059: pan and zoom report the visible bbox for the POI explore pill', async () => {+ const onViewportChange = vi.fn()+ render(<MapViewGL places={[]} fitKey={1} onViewportChange={onViewportChange} />)+ await act(async () => {})++ act(() => { mapHandler('moveend')() })+ expect(onViewportChange).toHaveBeenCalledWith({ south: 0, west: 0, north: 1, east: 1 })+ })++ it('FE-COMP-MAPVIEWGL-060: a new POI or via set replaces the previous overlay markers', async () => {+ loadOnAttach()+ const poi: Poi = {+ osm_id: 'n1', name: 'Café', lat: 48.85, lng: 2.33, category: 'cafe', poi_type: 'cafe',+ address: null, website: null, phone: null, opening_hours: null, cuisine: null, source: 'openstreetmap',+ }+ const via: RouteVia = { lat: 48.5, lng: 2.5, tone: 'default' }++ const { rerender } = render(<MapViewGL places={[]} fitKey={1} pois={[poi]} routeVias={[via]} />)+ await act(async () => {})+ const first = [...glMarkers.created]+ expect(first).toHaveLength(2)++ rerender(+ <MapViewGL+ places={[]}+ fitKey={1}+ pois={[{ ...poi, osm_id: 'n2', lat: 48.9 }]}+ routeVias={[{ ...via, lat: 48.6 }]}+ />,+ )+ await act(async () => {})+ first.forEach(marker => expect(vi.mocked(marker.remove)).toHaveBeenCalled())+ expect(glMarkers.created.length).toBeGreaterThan(first.length)+ })++ it('FE-COMP-MAPVIEWGL-061: plugin markers are torn down when the trip loses them', async () => {+ loadOnAttach()+ server.use(+ http.get('/api/map-markers/:tripId', ({ params }) => HttpResponse.json({+ markers: params.tripId === '4'+ ? [{ pluginId: 'ev', id: 'm1', lat: 48.5, lng: 2.5, tone: 'default' } as PluginMapMarker]+ : [],+ })),+ http.get('/api/map-layers/:tripId', () => HttpResponse.json({ layers: [] })),+ )++ const { rerender } = render(<MapViewGL places={[]} fitKey={1} tripId={4} />)+ await waitFor(() => expect(glMarkers.created).toHaveLength(1))+ const stale = glMarkers.created[0]++ rerender(<MapViewGL places={[]} fitKey={1} tripId={5} />)+ await waitFor(() => expect(vi.mocked(stale.remove)).toHaveBeenCalled())+ })++ it('FE-COMP-MAPVIEWGL-062: selecting a day-only place flies there; one without coordinates does not', async () => {+ const dayPlace = buildMapPlace({ id: 101, lat: 35.68, lng: 139.69 })+ const broken = buildMapPlace({ id: 102, lat: null, lng: null })++ const { rerender } = render(+ <MapViewGL places={[broken]} dayPlaces={[dayPlace]} fitKey={1} selectedPlaceId={null} />,+ )+ await act(async () => {})++ rerender(<MapViewGL places={[broken]} dayPlaces={[dayPlace]} fitKey={1} selectedPlaceId={101} />)+ await act(async () => {})+ expect(glMap.flyTo).toHaveBeenCalledWith(expect.objectContaining({ center: [139.69, 35.68], zoom: 14 }))++ glMap.flyTo.mockClear()+ rerender(<MapViewGL places={[broken]} dayPlaces={[dayPlace]} fitKey={1} selectedPlaceId={102} />)+ await act(async () => {})+ expect(glMap.flyTo).not.toHaveBeenCalled()+ })++ it('FE-COMP-MAPVIEWGL-063: tracking without a fix yet does not attach the blue dot', async () => {+ geoStub.mode = 'show'+ geoStub.position = null++ render(<MapViewGL places={[]} fitKey={1} />)+ await act(async () => {})++ expect(locationMarker.update).not.toHaveBeenCalled()+ })++ it('FE-COMP-MAPVIEWGL-064: the overlay gets the endpoint callback already at construction time', async () => {+ loadOnAttach()+ const onReservationClick = vi.fn()+ render(<MapViewGL places={[]} fitKey={1} reservations={[]} onReservationClick={onReservationClick} />)+ await act(async () => {})++ const ctorOptions = vi.mocked(ReservationMapboxOverlay).mock.calls[0][1] as unknown as {+ showEndpointLabels: boolean+ onEndpointClick: (id: number) => void+ }+ expect(ctorOptions.showEndpointLabels).toBe(false)+ ctorOptions.onEndpointClick(42)+ expect(onReservationClick).toHaveBeenCalledWith(42)+ })++ it('FE-COMP-MAPVIEWGL-065: unmounting mid-reconcile cancels the scheduled frame and detaches the listeners', async () => {+ loadOnAttach()+ const clusterSource = geoSource()+ glMap.getSource.mockImplementation((id: string) => (id === 'trip-place-clusters' ? clusterSource : null))++ const { unmount } = render(<MapViewGL places={[buildMapPlace({ id: 111, lat: 48, lng: 2 })]} fitKey={1} />)+ unmount()+ await flushFrames()++ expect(glMap.off).toHaveBeenCalledWith('moveend', expect.any(Function))+ expect(glMap.off).toHaveBeenCalledWith('zoomend', expect.any(Function))+ })})diff --git a/client/src/components/Map/ReservationOverlay.test.tsx b/client/src/components/Map/ReservationOverlay.test.tsxnew file mode 100644index 000000000..a0dd6c068--- /dev/null+++ b/client/src/components/Map/ReservationOverlay.test.tsx@@ -0,0 +1,558 @@+// FE-COMP-RESOVERLAY-001 to FE-COMP-RESOVERLAY-024+import React from 'react'+import { describe, it, expect, vi, afterEach } from 'vitest'+import { render, screen } from '../../../tests/helpers/render'+import { act, fireEvent } from '@testing-library/react'+import { resetAllStores, seedStore } from '../../../tests/helpers/store'+import { useSettingsStore } from '../../store/settingsStore'+import type { Reservation, ReservationEndpoint } from '../../types'++// The Leaflet map jsdom cannot provide: panes are a plain map, and the+// projection is a linear lat/lng → pixel scale so the tests can put endpoints a+// chosen number of pixels apart and drive the declutter thresholds exactly.+const leaflet = vi.hoisted(() => {+ const panes = new Map<string, HTMLElement>()+ const view = { zoom: 10, scale: 1000 }+ const point = (x: number, y: number) => ({+ x, y,+ distanceTo(other: { x: number; y: number }) { return Math.hypot(x - other.x, y - other.y) },+ })+ const events: Record<string, () => void> = {}+ const map = {+ getZoom: () => view.zoom,+ getPane: (name: string) => panes.get(name),+ createPane: (name: string) => {+ const el = document.createElement('div')+ panes.set(name, el)+ return el+ },+ latLngToContainerPoint: ([lat, lng]: [number, number]) => point(lng * view.scale, lat * view.scale),+ }+ return { panes, view, events, map }+})++vi.mock('react-leaflet', () => ({+ Marker: ({ children, position, icon, eventHandlers, pane, zIndexOffset }: any) => (+ <div+ data-testid="endpoint-marker"+ data-lat={position[0]}+ data-lng={position[1]}+ data-pane={pane ?? ''}+ data-zindex={zIndexOffset}+ data-icon-html={icon?.options?.html ?? ''}+ onClick={() => eventHandlers?.click?.()}+ >+ {children}+ </div>+ ),+ Polyline: ({ positions, pathOptions }: any) => (+ <div+ data-testid="polyline"+ data-points={JSON.stringify(positions)}+ data-path-options={JSON.stringify(pathOptions ?? null)}+ />+ ),+ Tooltip: ({ children }: any) => <div data-testid="marker-tooltip">{children}</div>,+ useMap: () => leaflet.map,+ useMapEvents: (handlers: Record<string, () => void>) => {+ Object.assign(leaflet.events, handlers)+ return leaflet.map+ },+}))++vi.mock('leaflet', () => {+ const divIcon = vi.fn((options: Record<string, unknown>) => ({ options }))+ const marker = vi.fn(() => ({+ addTo: vi.fn(), remove: vi.fn(), setLatLng: vi.fn(), getElement: () => null,+ }))+ const point = vi.fn((x: number, y: number) => ({ x, y }))+ return { default: { divIcon, marker, point }, divIcon, marker, point }+})++import ReservationOverlay from './ReservationOverlay'++function endpoint(over: Partial<ReservationEndpoint> = {}): ReservationEndpoint {+ return {+ role: 'from', sequence: 0, name: 'A', code: null,+ lat: 48, lng: 16, timezone: null, local_time: null, local_date: null,+ ...over,+ } as unknown as ReservationEndpoint+}++// Endpoints 3500 px apart at the default scale — past every type's declutter and+// label threshold, so a booking is fully drawn unless a test says otherwise.+function booking(over: Partial<Reservation> = {}): Reservation {+ return {+ id: 1, type: 'flight', status: 'confirmed', title: null,+ endpoints: [+ endpoint({ role: 'from', sequence: 0, name: 'Vienna', code: 'VIE', lat: 48, lng: 16 }),+ endpoint({ role: 'to', sequence: 1, name: 'London', code: 'LHR', lat: 51.5, lng: 16 }),+ ],+ ...over,+ } as unknown as Reservation+}++const GEOMETRY = '__upzA_gayB_af@_pR_ry@~oR'++function transitBooking(legs: Record<string, unknown>[]): Reservation {+ return booking({+ id: 2,+ type: 'transit',+ endpoints: [+ endpoint({ role: 'from', sequence: 0, name: 'Stop A', lat: 48, lng: 16 }),+ endpoint({ role: 'to', sequence: 1, name: 'Stop B', lat: 48.02, lng: 16 }),+ ],+ metadata: { transit: { legs } },+ } as unknown as Partial<Reservation>)+}++function renderOverlay(props: Partial<React.ComponentProps<typeof ReservationOverlay>> = {}) {+ return render(+ <ReservationOverlay+ reservations={[booking()]}+ showConnections+ showStats={false}+ {...props}+ />,+ )+}++const markers = () => screen.queryAllByTestId('endpoint-marker')+const lines = () => screen.queryAllByTestId('polyline')+const styleOf = (el: HTMLElement) => JSON.parse(el.getAttribute('data-path-options') || 'null')+const labelOf = (el: HTMLElement) => {+ const html = el.getAttribute('data-icon-html') || ''+ return html.replace(/<[^>]*>/g, '').trim()+}++afterEach(() => {+ vi.clearAllMocks()+ leaflet.panes.clear()+ leaflet.view.scale = 1000+ resetAllStores()+})++describe('ReservationOverlay', () => {+ it('FE-COMP-RESOVERLAY-001: creates the endpoint pane above the overlay pane', () => {+ renderOverlay()+ const pane = leaflet.panes.get('reservation-endpoints')+ expect(pane).toBeDefined()+ expect(pane!.style.zIndex).toBe('650')+ expect(pane!.style.pointerEvents).toBe('auto')+ })++ it('FE-COMP-RESOVERLAY-002: renders nothing at all while connections are hidden', () => {+ renderOverlay({ showConnections: false })+ expect(lines()).toHaveLength(0)+ expect(markers()).toHaveLength(0)+ })++ it('FE-COMP-RESOVERLAY-003: draws a marker per waypoint in the endpoint pane', () => {+ renderOverlay()+ expect(markers()).toHaveLength(2)+ expect(markers()[0].getAttribute('data-pane')).toBe('reservation-endpoints')+ expect(markers()[0].getAttribute('data-zindex')).toBe('1000')+ expect(markers().map(m => m.getAttribute('data-lat'))).toEqual(['48', '51.5'])+ })++ it('FE-COMP-RESOVERLAY-004: a flight is drawn as a geodesic arc, not a two-point line', () => {+ renderOverlay()+ const points = JSON.parse(lines()[0].getAttribute('data-points') || '[]')+ expect(points.length).toBeGreaterThan(2)+ expect(points[0]).toEqual([48, 16])+ expect(points[points.length - 1]).toEqual([51.5, 16])+ })++ it('FE-COMP-RESOVERLAY-005: a train is drawn as the plain two-point line', () => {+ renderOverlay({ reservations: [booking({ type: 'train' })] })+ expect(JSON.parse(lines()[0].getAttribute('data-points') || '[]')).toEqual([[48, 16], [51.5, 16]])+ })++ it('FE-COMP-RESOVERLAY-006: a pending booking is dashed and dimmer than a confirmed one', () => {+ const { unmount } = renderOverlay({ reservations: [booking({ status: 'pending' })] })+ expect(styleOf(lines()[0])).toMatchObject({ opacity: 0.55, dashArray: '6, 6' })+ unmount()++ renderOverlay({ reservations: [booking({ id: 9 })] })+ const confirmed = styleOf(lines()[0])+ expect(confirmed.opacity).toBe(0.75)+ expect(confirmed.dashArray).toBeUndefined()+ })++ it('FE-COMP-RESOVERLAY-007: skips reservations that are not a transport type', () => {+ renderOverlay({ reservations: [booking({ type: 'hotel' as Reservation['type'] })] })+ expect(lines()).toHaveLength(0)+ expect(markers()).toHaveLength(0)+ })++ it('FE-COMP-RESOVERLAY-008: skips a booking with fewer than two waypoints', () => {+ renderOverlay({ reservations: [booking({ endpoints: [endpoint({ role: 'from', sequence: 0 })] })] })+ expect(lines()).toHaveLength(0)+ })++ it('FE-COMP-RESOVERLAY-009: orders waypoints by sequence and draws one leg per pair', () => {+ renderOverlay({+ reservations: [booking({+ type: 'train',+ endpoints: [+ endpoint({ role: 'to', sequence: 2, name: 'C', lat: 51.5, lng: 16 }),+ endpoint({ role: 'from', sequence: 0, name: 'A', lat: 48, lng: 16 }),+ endpoint({ role: 'stop', sequence: 1, name: 'B', lat: 50, lng: 16 }),+ ],+ })],+ })+ expect(lines()).toHaveLength(2)+ expect(JSON.parse(lines()[0].getAttribute('data-points') || '[]')).toEqual([[48, 16], [50, 16]])+ expect(JSON.parse(lines()[1].getAttribute('data-points') || '[]')).toEqual([[50, 16], [51.5, 16]])+ expect(markers()).toHaveLength(3)+ })++ it('FE-COMP-RESOVERLAY-010: hides a hop whose endpoints sit almost on top of each other', () => {+ renderOverlay({+ reservations: [booking({+ type: 'train',+ endpoints: [+ endpoint({ role: 'from', sequence: 0, lat: 48, lng: 16 }),+ endpoint({ role: 'to', sequence: 1, lat: 48.05, lng: 16 }), // 50 px, under the 200 px floor+ ],+ })],+ })+ expect(lines()).toHaveLength(0)+ expect(markers()).toHaveLength(0)+ })++ it('FE-COMP-RESOVERLAY-011: the same hop reappears once the map is zoomed in', () => {+ renderOverlay({+ reservations: [booking({+ type: 'train',+ endpoints: [+ endpoint({ role: 'from', sequence: 0, lat: 48, lng: 16 }),+ endpoint({ role: 'to', sequence: 1, lat: 48.05, lng: 16 }),+ ],+ })],+ })+ expect(lines()).toHaveLength(0)++ leaflet.view.scale = 20000 // 1000 px apart now+ leaflet.view.zoom = 14+ act(() => { leaflet.events.zoomend() })+ expect(lines()).toHaveLength(1)+ })++ it('FE-COMP-RESOVERLAY-012: each transport type gets its own declutter floor', () => {+ // 100 px apart: a flight survives (50 px floor), a cruise does not (150 px).+ const short = (type: string, id: number) => booking({+ id, type: type as Reservation['type'],+ endpoints: [+ endpoint({ role: 'from', sequence: 0, lat: 48, lng: 16 }),+ endpoint({ role: 'to', sequence: 1, lat: 48.1, lng: 16 }),+ ],+ })+ const { unmount } = renderOverlay({ reservations: [short('flight', 1)] })+ expect(lines().length).toBeGreaterThan(0)+ unmount()++ renderOverlay({ reservations: [short('cruise', 2)] })+ expect(lines()).toHaveLength(0)+ })++ it('FE-COMP-RESOVERLAY-013: clicking an endpoint reports its reservation id', () => {+ const onEndpointClick = vi.fn()+ renderOverlay({ reservations: [booking({ id: 42 })], onEndpointClick })+ fireEvent.click(markers()[1])+ expect(onEndpointClick).toHaveBeenCalledWith(42)+ })++ it('FE-COMP-RESOVERLAY-014: an endpoint without a click handler stays inert', () => {+ renderOverlay({ onEndpointClick: undefined })+ expect(() => fireEvent.click(markers()[0])).not.toThrow()+ })++ it('FE-COMP-RESOVERLAY-015: the tooltip shows the stop name and the booking title', () => {+ renderOverlay({ reservations: [booking({ title: 'OS 456' })] })+ const tooltips = screen.getAllByTestId('marker-tooltip')+ expect(tooltips[0].textContent).toContain('Vienna')+ expect(tooltips[0].textContent).toContain('OS 456')+ })++ it('FE-COMP-RESOVERLAY-016: endpoint badges carry no label until the setting is on', () => {+ renderOverlay()+ expect(labelOf(markers()[0])).toBe('')+ })++ it('FE-COMP-RESOVERLAY-017: with the setting on the badge shows the endpoint code', () => {+ seedStore(useSettingsStore, { settings: { map_booking_labels: true } })+ renderOverlay()+ expect(markers().map(labelOf)).toEqual(['VIE', 'LHR'])+ })++ it('FE-COMP-RESOVERLAY-018: a code-less stop falls back to its name without the parenthetical', () => {+ seedStore(useSettingsStore, { settings: { map_booking_labels: true } })+ renderOverlay({+ reservations: [booking({+ type: 'train',+ endpoints: [+ endpoint({ role: 'from', sequence: 0, name: 'Wien Hbf (Bahnsteig 3)', lat: 48, lng: 16 }),+ endpoint({ role: 'to', sequence: 1, name: 'München Hbf', lat: 51.5, lng: 16 }),+ ],+ })],+ })+ expect(markers().map(labelOf)).toEqual(['Wien Hbf', 'München Hbf'])+ })++ it('FE-COMP-RESOVERLAY-019: a short train hop draws its line but keeps its labels off', () => {+ seedStore(useSettingsStore, { settings: { map_booking_labels: true } })+ renderOverlay({+ reservations: [booking({+ type: 'train',+ endpoints: [+ endpoint({ role: 'from', sequence: 0, name: 'Wien', code: 'VIE', lat: 48, lng: 16 }),+ endpoint({ role: 'to', sequence: 1, name: 'Graz', code: 'GRZ', lat: 48.3, lng: 16 }),+ ],+ })],+ })+ // 300 px: over the 200 px line floor, under the 400 px label floor.+ expect(lines()).toHaveLength(1)+ expect(markers().map(labelOf)).toEqual(['', ''])+ })+})++describe('ReservationOverlay declutter floors and road routes', () => {+ // Same endpoints every time, only the north-south gap changes: at the mocked+ // scale one degree of latitude is 1000 px, so `dLat` *is* the pixel distance / 1000.+ const hop = (type: string, id: number, dLat: number) => booking({+ id, type: type as Reservation['type'],+ endpoints: [+ endpoint({ role: 'from', sequence: 0, name: 'Start', code: 'AAA', lat: 48, lng: 16 }),+ endpoint({ role: 'to', sequence: 1, name: 'End', code: 'BBB', lat: 48 + dLat, lng: 16 }),+ ],+ })++ it('FE-COMP-RESOVERLAY-030: a renderer without pane support still draws the overlay', () => {+ const realGetPane = leaflet.map.getPane+ leaflet.map.getPane = undefined+ try {+ renderOverlay()+ expect(leaflet.panes.size).toBe(0)+ expect(markers()).toHaveLength(2)+ expect(lines().length).toBeGreaterThan(0)+ } finally {+ leaflet.map.getPane = realGetPane+ }+ })++ it('FE-COMP-RESOVERLAY-031: a car hop has its own 80 px line floor', () => {+ const { unmount } = renderOverlay({ reservations: [hop('car', 1, 0.1)] })+ expect(lines()).toHaveLength(1)+ unmount()++ renderOverlay({ reservations: [hop('car', 2, 0.05)] })+ expect(lines()).toHaveLength(0)+ })++ it('FE-COMP-RESOVERLAY-032: a car keeps its endpoint labels off below 150 px', () => {+ seedStore(useSettingsStore, { settings: { map_booking_labels: true } })+ const { unmount } = renderOverlay({ reservations: [hop('car', 1, 0.1)] })+ expect(markers().map(labelOf)).toEqual(['', ''])+ unmount()++ renderOverlay({ reservations: [hop('car', 2, 0.2)] })+ expect(markers().map(labelOf)).toEqual(['AAA', 'BBB'])+ })++ it('FE-COMP-RESOVERLAY-033: a cruise draws from 150 px but only labels from 300 px', () => {+ seedStore(useSettingsStore, { settings: { map_booking_labels: true } })+ const { unmount } = renderOverlay({ reservations: [hop('cruise', 1, 0.2)] })+ expect(lines().length).toBeGreaterThan(0)+ expect(markers().map(labelOf)).toEqual(['', ''])+ unmount()++ renderOverlay({ reservations: [hop('cruise', 2, 0.4)] })+ expect(markers().map(labelOf)).toEqual(['AAA', 'BBB'])+ })++ it('FE-COMP-RESOVERLAY-034: a supplied road route replaces the straight arc', () => {+ const road: [number, number][] = [[48, 16], [49, 16.4], [51.5, 16]]+ renderOverlay({+ reservations: [hop('car', 7, 3.5)],+ roadRoutes: new Map([[7, road]]),+ })+ expect(lines()).toHaveLength(1)+ expect(JSON.parse(lines()[0].getAttribute('data-points') || '[]')).toEqual(road)+ })++ it('FE-COMP-RESOVERLAY-035: a one-point road route falls back to the straight arc', () => {+ renderOverlay({+ reservations: [hop('car', 7, 3.5)],+ roadRoutes: new Map([[7, [[48, 16]] as [number, number][]]]),+ })+ expect(JSON.parse(lines()[0].getAttribute('data-points') || '[]')).toEqual([[48, 16], [51.5, 16]])+ })++ it('FE-COMP-RESOVERLAY-036: a booking without an endpoints array is skipped', () => {+ renderOverlay({ reservations: [booking({ endpoints: undefined })] })+ expect(lines()).toHaveLength(0)+ expect(markers()).toHaveLength(0)+ })++ it('FE-COMP-RESOVERLAY-037: waypoints without a sequence keep their array order', () => {+ renderOverlay({+ reservations: [booking({+ type: 'train',+ endpoints: [+ endpoint({ role: 'from', sequence: undefined, name: 'A', lat: 48, lng: 16 }),+ endpoint({ role: 'stop', sequence: undefined, name: 'B', lat: 50, lng: 16 }),+ endpoint({ role: 'to', sequence: undefined, name: 'C', lat: 51.5, lng: 16 }),+ ],+ })],+ })+ expect(lines()).toHaveLength(2)+ expect(JSON.parse(lines()[0].getAttribute('data-points') || '[]')).toEqual([[48, 16], [50, 16]])+ expect(JSON.parse(lines()[1].getAttribute('data-points') || '[]')).toEqual([[50, 16], [51.5, 16]])+ })++ it('FE-COMP-RESOVERLAY-038: a leg whose stops share coordinates degrades to a straight segment', () => {+ renderOverlay({+ reservations: [booking({+ endpoints: [+ endpoint({ role: 'from', sequence: 0, name: 'Vienna', code: 'VIE', lat: 48, lng: 16 }),+ endpoint({ role: 'stop', sequence: 1, name: 'Vienna Gate', code: 'VIE', lat: 48, lng: 16 }),+ endpoint({ role: 'to', sequence: 2, name: 'London', code: 'LHR', lat: 51.5, lng: 16 }),+ ],+ })],+ })+ expect(lines()).toHaveLength(2)+ expect(JSON.parse(lines()[0].getAttribute('data-points') || '[]')).toHaveLength(2)+ expect(JSON.parse(lines()[1].getAttribute('data-points') || '[]').length).toBeGreaterThan(2)+ })++ it('FE-COMP-RESOVERLAY-039: a code-less stop between two coded ends falls back to its name', () => {+ seedStore(useSettingsStore, { settings: { map_booking_labels: true } })+ renderOverlay({+ reservations: [booking({+ type: 'train',+ endpoints: [+ endpoint({ role: 'from', sequence: 0, name: 'Wien', code: 'VIE', lat: 48, lng: 16 }),+ endpoint({ role: 'stop', sequence: 1, name: 'Zuerich HB (Gleis 5)', code: null, lat: 50, lng: 16 }),+ endpoint({ role: 'to', sequence: 2, name: 'London', code: 'LHR', lat: 51.5, lng: 16 }),+ ],+ })],+ })+ expect(markers().map(labelOf)).toEqual(['VIE', 'Zuerich HB', 'LHR'])+ })+})++describe('ReservationOverlay transit journeys (#1570)', () => {+ it('FE-COMP-RESOVERLAY-020: draws the stored rail alignment with a white casing under it', () => {+ renderOverlay({ reservations: [transitBooking([{ geometry: GEOMETRY, mode: 'BUS', line_color: '#7c3aed' }])] })+ expect(lines()).toHaveLength(2)+ expect(styleOf(lines()[0])).toMatchObject({ color: '#ffffff', weight: 6 })+ expect(styleOf(lines()[1])).toMatchObject({ color: '#7c3aed', weight: 3.5 })+ expect(JSON.parse(lines()[1].getAttribute('data-points') || '[]')).toEqual([[48, 2], [48.02, 2.01], [48.05, 2]])+ })++ it('FE-COMP-RESOVERLAY-021: a walking leg is dotted and gets no casing', () => {+ renderOverlay({ reservations: [transitBooking([{ geometry: GEOMETRY, mode: 'WALK' }])] })+ expect(lines()).toHaveLength(1)+ expect(styleOf(lines()[0])).toMatchObject({ color: '#64748b', dashArray: '1, 7' })+ })++ it('FE-COMP-RESOVERLAY-022: a leg without a line colour falls back to the transit blue', () => {+ renderOverlay({ reservations: [transitBooking([{ geometry: GEOMETRY, mode: 'BUS' }])] })+ expect(styleOf(lines()[1])).toMatchObject({ color: '#3b82f6' })+ })++ it('FE-COMP-RESOVERLAY-023: real geometry survives the endpoint declutter even zoomed right out', () => {+ // The two stations project ~20 px apart — far under the 200 px floor.+ renderOverlay({ reservations: [transitBooking([{ geometry: GEOMETRY, mode: 'BUS' }])] })+ expect(lines().length).toBeGreaterThan(0)+ expect(markers()).toHaveLength(2)+ })++ it('FE-COMP-RESOVERLAY-024: a transit journey without stored geometry is decluttered like any hop', () => {+ renderOverlay({ reservations: [transitBooking([{ mode: 'BUS' }])] })+ expect(lines()).toHaveLength(0)+ })+})++// computeDuration only feeds the stats badge, which this overlay no longer+// renders — but it still runs on every update, and a non-finite date once threw+// inside Intl.formatToParts and blanked the whole trip (#1620).+describe('ReservationOverlay duration math', () => {+ const timed = (from: Partial<ReservationEndpoint>, to: Partial<ReservationEndpoint>, res: Partial<Reservation> = {}) =>+ booking({+ endpoints: [+ endpoint({ role: 'from', sequence: 0, name: 'Vienna', code: 'VIE', lat: 48, lng: 16, ...from }),+ endpoint({ role: 'to', sequence: 1, name: 'London', code: 'LHR', lat: 51.5, lng: 16, ...to }),+ ],+ ...res,+ })++ it('FE-COMP-RESOVERLAY-025: renders a well-formed cross-timezone flight', () => {+ renderOverlay({ reservations: [timed(+ { timezone: 'Europe/Vienna', local_date: '2024-01-15', local_time: '09:20' },+ { timezone: 'Europe/London', local_date: '2024-01-15', local_time: '11:05' },+ )] })+ expect(lines().length).toBeGreaterThan(0)+ })++ it('FE-COMP-RESOVERLAY-026: renders a flight whose local arrival reads before its departure', () => {+ renderOverlay({ reservations: [timed(+ { timezone: 'Europe/Vienna', local_date: '2024-01-15', local_time: '22:30' },+ { timezone: 'America/New_York', local_date: '2024-01-15', local_time: '02:10' },+ )] })+ expect(lines().length).toBeGreaterThan(0)+ })++ it('FE-COMP-RESOVERLAY-027: renders a flight whose imported time is missing its minutes', () => {+ expect(() => renderOverlay({ reservations: [timed(+ { timezone: 'Europe/Vienna', local_date: '2024-01-15', local_time: '22' },+ { timezone: 'Europe/London', local_date: '2024-01-16', local_time: '08' },+ )] })).not.toThrow()+ expect(lines().length).toBeGreaterThan(0)+ })++ it('FE-COMP-RESOVERLAY-028: a time-only endpoint borrows the date from the other side', () => {+ renderOverlay({ reservations: [timed(+ { local_date: '2024-01-15', local_time: '09:20' }, {},+ { reservation_end_time: '17:30' } as Partial<Reservation>,+ )] })+ expect(lines().length).toBeGreaterThan(0)+ })++ it('FE-COMP-RESOVERLAY-029: two date-less times and an implausible gap both render', () => {+ const { unmount } = renderOverlay({ reservations: [timed({}, {}, {+ reservation_time: '09:20', reservation_end_time: '17:30',+ } as Partial<Reservation>)] })+ expect(lines().length).toBeGreaterThan(0)+ unmount()++ renderOverlay({ reservations: [timed({}, {}, {+ id: 5, reservation_time: '2024-01-15T09:20', reservation_end_time: '2024-01-19T17:30',+ } as Partial<Reservation>)] })+ expect(lines().length).toBeGreaterThan(0)+ })++ it('FE-COMP-RESOVERLAY-040: a date-less departure borrows the date from the arrival', () => {+ renderOverlay({ reservations: [timed(+ {}, { local_date: '2024-01-16', local_time: '08:00' },+ { reservation_time: '22:30' } as Partial<Reservation>,+ )] })+ expect(lines().length).toBeGreaterThan(0)+ })++ it('FE-COMP-RESOVERLAY-041: a hop shorter than an hour renders', () => {+ renderOverlay({ reservations: [timed({}, {}, {+ reservation_time: '2024-01-15T09:20', reservation_end_time: '2024-01-15T09:50',+ } as Partial<Reservation>)] })+ expect(lines().length).toBeGreaterThan(0)+ })++ it('FE-COMP-RESOVERLAY-042: a stored timestamp that carries no clock time renders', () => {+ renderOverlay({ reservations: [timed(+ { timezone: 'Europe/Vienna' }, { timezone: 'Europe/London' },+ { reservation_time: '2024-01-15T', reservation_end_time: '2024-01-15T18:00' } as Partial<Reservation>,+ )] })+ expect(lines().length).toBeGreaterThan(0)+ })+})diff --git a/client/src/components/Map/RouteCalculator.test.ts b/client/src/components/Map/RouteCalculator.test.tsindex 6e847c7da..62bc45597 100644--- a/client/src/components/Map/RouteCalculator.test.ts+++ b/client/src/components/Map/RouteCalculator.test.ts@@ -1,15 +1,25 @@-import { describe, it, expect } from 'vitest'+import { describe, it, expect, vi, afterEach } from 'vitest'import { http, HttpResponse } from 'msw'import { server } from '../../../tests/helpers/msw/server'+import { pluginsApi, type PluginRouteResult } from '../../api/client'+import { useSettingsStore } from '../../store/settingsStore'import {calculateRoute,+ calculateRouteWithLegs,calculateSegments,optimizeRoute,generateGoogleMapsUrl,+ parsePluginProfile,withHotelBookends,} from './RouteCalculator'const OSRM_BASE = 'https://router.project-osrm.org/route/v1'+// calculateRouteWithLegs talks to the FOSSGIS per-profile hosts, not the car-only demo.+const FOSSGIS = {+ driving: 'https://routing.openstreetmap.de/routed-car/route/v1/driving',+ walking: 'https://routing.openstreetmap.de/routed-foot/route/v1/foot',+ cycling: 'https://routing.openstreetmap.de/routed-bike/route/v1/bike',+}const buildOsrmRouteResponse = (distance = 5000, duration = 360) => ({code: 'Ok',@@ -285,3 +295,280 @@ describe('withHotelBookends', () => {])})})++// ── parsePluginProfile ─────────────────────────────────────────────────────────++describe('parsePluginProfile', () => {+ it('FE-COMP-ROUTECALCULATOR-026: splits plugin:<id>/<profile> into its two halves', () => {+ expect(parsePluginProfile('plugin:ev-router/fastest')).toEqual({ pluginId: 'ev-router', profileId: 'fastest' })+ })++ it('FE-COMP-ROUTECALCULATOR-027: a profile id may itself contain slashes', () => {+ expect(parsePluginProfile('plugin:ev-router/eco/winter')).toEqual({ pluginId: 'ev-router', profileId: 'eco/winter' })+ })++ it('FE-COMP-ROUTECALCULATOR-028: a built-in profile is not a plugin profile', () => {+ expect(parsePluginProfile('driving')).toBeNull()+ expect(parsePluginProfile('walking')).toBeNull()+ })++ it('FE-COMP-ROUTECALCULATOR-029: rejects a malformed plugin key', () => {+ expect(parsePluginProfile('plugin:ev-router')).toBeNull() // no separator+ expect(parsePluginProfile('plugin:/fastest')).toBeNull() // empty plugin id+ expect(parsePluginProfile('plugin:ev-router/')).toBeNull() // empty profile id+ })+})++// ── calculateRoute: remaining profiles ─────────────────────────────────────────++describe('calculateRoute profiles', () => {+ it('FE-COMP-ROUTECALCULATOR-030: cycling overrides the OSRM duration with a 15 km/h estimate', async () => {+ server.use(+ http.get(`${OSRM_BASE}/cycling/:coords`, () =>+ HttpResponse.json(buildOsrmRouteResponse(9000, 4242))+ )+ )+ const result = await calculateRoute([wp1, wp2], 'cycling')+ expect(result.duration).toBeCloseTo(9000 / (15000 / 3600))+ // The raw OSRM duration is still reported as the driving estimate.+ expect(result.drivingText).toBe('1 h 10 min')+ })+})++// ── calculateSegments error paths ──────────────────────────────────────────────++describe('calculateSegments failures', () => {+ it('FE-COMP-ROUTECALCULATOR-031: throws when OSRM answers with an HTTP error', async () => {+ server.use(http.get(`${OSRM_BASE}/driving/:coords`, () => HttpResponse.json({}, { status: 502 })))+ await expect(calculateSegments([wp1, wp2])).rejects.toThrow('Route could not be calculated')+ })++ it('FE-COMP-ROUTECALCULATOR-032: throws when OSRM reports no usable route', async () => {+ server.use(http.get(`${OSRM_BASE}/driving/:coords`, () => HttpResponse.json({ code: 'NoRoute', routes: [] })))+ await expect(calculateSegments([wp1, wp2])).rejects.toThrow('No route found')+ })+})++// ── calculateRouteWithLegs ─────────────────────────────────────────────────────++// The module caches by the exact waypoint list, so every test that must reach the+// network needs coordinates no earlier test has used.+let coordSeed = 0+function freshWaypoints(count = 2) {+ coordSeed += 1+ return Array.from({ length: count }, (_, i) => ({ lat: 10 + coordSeed + i / 100, lng: 20 + coordSeed + i / 100 }))+}++const buildLegsResponse = (legCount = 1) => ({+ code: 'Ok',+ routes: [{+ geometry: { coordinates: [[2.35, 48.85], [2.36, 48.86], [2.37, 48.87]] },+ distance: 4200,+ duration: 600,+ legs: Array.from({ length: legCount }, () => ({ distance: 4200 / legCount, duration: 600 / legCount })),+ }],+})++function pluginRouteResult(over: Partial<PluginRouteResult> = {}): PluginRouteResult {+ return {+ pluginId: 'ev-router',+ profile: 'fastest',+ coordinates: [[48.85, 2.35], [48.9, 2.4]],+ distance: 120000,+ duration: 5400,+ legs: [{ distance: 120000, duration: 5400 }],+ viaPoints: [],+ ...over,+ }+}++afterEach(() => {+ vi.restoreAllMocks()+ useSettingsStore.setState({ settings: { ...useSettingsStore.getState().settings, distance_unit: 'metric' } })+})++describe('calculateRouteWithLegs', () => {+ it('FE-COMP-ROUTECALCULATOR-033: returns an empty route for fewer than 2 waypoints without calling OSRM', async () => {+ const result = await calculateRouteWithLegs([wp1])+ expect(result).toEqual({ coordinates: [], distance: 0, duration: 0, legs: [] })+ })++ it('FE-COMP-ROUTECALCULATOR-034: returns road geometry as [lat,lng] plus per-leg metadata', async () => {+ server.use(http.get(`${FOSSGIS.driving}/:coords`, () => HttpResponse.json(buildLegsResponse())))+ const [a, b] = freshWaypoints()+ const result = await calculateRouteWithLegs([a, b])++ // OSRM ships [lng,lat]; Leaflet wants [lat,lng].+ expect(result.coordinates).toEqual([[48.85, 2.35], [48.86, 2.36], [48.87, 2.37]])+ expect(result.distance).toBe(4200)+ expect(result.legs).toHaveLength(1)+ expect(result.legs[0].from).toEqual([a.lat, a.lng])+ expect(result.legs[0].to).toEqual([b.lat, b.lng])+ expect(result.legs[0].mid).toEqual([(a.lat + b.lat) / 2, (a.lng + b.lng) / 2])+ expect(result.legs[0].distanceText).toBe('4.2 km')+ expect(result.legs[0].drivingText).toBe('10 min')+ expect(result.legs[0].walkingText).toBe('50 min')+ })++ it('FE-COMP-ROUTECALCULATOR-035: a repeated call is served from the cache instead of the network', async () => {+ let hits = 0+ server.use(http.get(`${FOSSGIS.driving}/:coords`, () => { hits++; return HttpResponse.json(buildLegsResponse()) }))+ const wps = freshWaypoints()+ const first = await calculateRouteWithLegs(wps)+ const second = await calculateRouteWithLegs(wps)++ expect(hits).toBe(1)+ expect(second).toBe(first)+ })++ it('FE-COMP-ROUTECALCULATOR-036: switching the distance unit re-fetches instead of reusing stale text (#1300)', async () => {+ server.use(http.get(`${FOSSGIS.driving}/:coords`, () => HttpResponse.json(buildLegsResponse())))+ const wps = freshWaypoints()+ const metric = await calculateRouteWithLegs(wps)+ expect(metric.legs[0].distanceText).toBe('4.2 km')++ useSettingsStore.setState({ settings: { ...useSettingsStore.getState().settings, distance_unit: 'imperial' } })+ const imperial = await calculateRouteWithLegs(wps)+ expect(imperial).not.toBe(metric)+ expect(imperial.legs[0].distanceText).toContain('mi')+ })++ it('FE-COMP-ROUTECALCULATOR-037: walking and cycling go to their own FOSSGIS profile hosts', async () => {+ server.use(+ http.get(`${FOSSGIS.walking}/:coords`, () => HttpResponse.json(buildLegsResponse())),+ http.get(`${FOSSGIS.cycling}/:coords`, () => HttpResponse.json(buildLegsResponse())),+ )+ await expect(calculateRouteWithLegs(freshWaypoints(), { profile: 'walking' })).resolves.toMatchObject({ distance: 4200 })+ await expect(calculateRouteWithLegs(freshWaypoints(), { profile: 'cycling' })).resolves.toMatchObject({ distance: 4200 })+ })++ it('FE-COMP-ROUTECALCULATOR-038: an unknown profile falls back to the car host', async () => {+ let hits = 0+ server.use(http.get(`${FOSSGIS.driving}/:coords`, () => { hits++; return HttpResponse.json(buildLegsResponse()) }))+ await calculateRouteWithLegs(freshWaypoints(), { profile: 'hovercraft' })+ expect(hits).toBe(1)+ })++ it('FE-COMP-ROUTECALCULATOR-039: builds one leg per waypoint pair', async () => {+ server.use(http.get(`${FOSSGIS.driving}/:coords`, () => HttpResponse.json(buildLegsResponse(2))))+ const wps = freshWaypoints(3)+ const result = await calculateRouteWithLegs(wps)+ expect(result.legs).toHaveLength(2)+ expect(result.legs[1].from).toEqual([wps[1].lat, wps[1].lng])+ expect(result.legs[1].to).toEqual([wps[2].lat, wps[2].lng])+ })++ it('FE-COMP-ROUTECALCULATOR-040: throws on an OSRM HTTP error so the caller can fall back to a straight line', async () => {+ server.use(http.get(`${FOSSGIS.driving}/:coords`, () => HttpResponse.json({}, { status: 503 })))+ await expect(calculateRouteWithLegs(freshWaypoints())).rejects.toThrow('Route could not be calculated')+ })++ it('FE-COMP-ROUTECALCULATOR-041: throws when OSRM reports no route', async () => {+ server.use(http.get(`${FOSSGIS.driving}/:coords`, () => HttpResponse.json({ code: 'NoRoute', routes: [] })))+ await expect(calculateRouteWithLegs(freshWaypoints())).rejects.toThrow('No route found')+ })++ it('FE-COMP-ROUTECALCULATOR-042: a route without legs still returns its geometry', async () => {+ server.use(http.get(`${FOSSGIS.driving}/:coords`, () => HttpResponse.json({+ code: 'Ok',+ routes: [{ geometry: { coordinates: [[2.35, 48.85]] }, distance: 10, duration: 5 }],+ })))+ const result = await calculateRouteWithLegs(freshWaypoints())+ expect(result.legs).toEqual([])+ expect(result.coordinates).toEqual([[48.85, 2.35]])+ })+})++describe('calculateRouteWithLegs plugin profiles', () => {+ it('FE-COMP-ROUTECALCULATOR-043: refuses a plugin route without a trip context', async () => {+ const spy = vi.spyOn(pluginsApi, 'pluginRoute')+ await expect(+ calculateRouteWithLegs(freshWaypoints(), { profile: 'plugin:ev-router/fastest' })+ ).rejects.toThrow('Plugin routing needs a trip context')+ expect(spy).not.toHaveBeenCalled()+ })++ it('FE-COMP-ROUTECALCULATOR-044: forwards the trip/day context and the bare coordinates to the plugin', async () => {+ const spy = vi.spyOn(pluginsApi, 'pluginRoute').mockResolvedValue({ route: pluginRouteResult() })+ const wps = freshWaypoints()+ await calculateRouteWithLegs(wps, { profile: 'plugin:ev-router/fastest', tripId: 7, dayId: 3 })++ expect(spy).toHaveBeenCalledWith(+ 'ev-router',+ 'fastest',+ { tripId: 7, dayId: 3, waypoints: wps.map(p => ({ lat: p.lat, lng: p.lng })) },+ { signal: undefined },+ )+ })++ it('FE-COMP-ROUTECALCULATOR-045: maps the plugin answer onto the normal route shape', async () => {+ vi.spyOn(pluginsApi, 'pluginRoute').mockResolvedValue({+ route: pluginRouteResult({+ legs: [{ distance: 120000, duration: 5400, note: '25 min charge' }],+ viaPoints: [{ lat: 48.7, lng: 2.3, label: 'Supercharger', tone: 'success', dwellSeconds: 1500 }],+ }),+ })+ const wps = freshWaypoints()+ const result = await calculateRouteWithLegs(wps, { profile: 'plugin:ev-router/fastest', tripId: 7 })++ expect(result.coordinates).toEqual([[48.85, 2.35], [48.9, 2.4]])+ expect(result.legs[0].noteText).toBe('25 min charge')+ expect(result.legs[0].drivingText).toBe('1 h 30 min')+ expect(result.legs[0].distanceText).toBe('120 km')+ expect(result.legs[0].from).toEqual([wps[0].lat, wps[0].lng])+ expect(result.vias).toHaveLength(1)+ expect(result.vias?.[0].label).toBe('Supercharger')+ })++ it('FE-COMP-ROUTECALCULATOR-046: a leg without a note carries no noteText, and no vias means no vias key', async () => {+ vi.spyOn(pluginsApi, 'pluginRoute').mockResolvedValue({ route: pluginRouteResult() })+ const result = await calculateRouteWithLegs(freshWaypoints(), { profile: 'plugin:ev-router/fastest', tripId: 7 })+ expect(result.legs[0].noteText).toBeUndefined()+ expect('vias' in result).toBe(false)+ })++ it('FE-COMP-ROUTECALCULATOR-047: a refusing plugin throws like an OSRM outage', async () => {+ vi.spyOn(pluginsApi, 'pluginRoute').mockResolvedValue({ route: null })+ await expect(+ calculateRouteWithLegs(freshWaypoints(), { profile: 'plugin:ev-router/fastest', tripId: 7 })+ ).rejects.toThrow('No route found')+ })++ it('FE-COMP-ROUTECALCULATOR-048: the same coordinates on a different day are routed again, not served from cache', async () => {+ const spy = vi.spyOn(pluginsApi, 'pluginRoute').mockResolvedValue({ route: pluginRouteResult() })+ const wps = freshWaypoints()+ const opts = { profile: 'plugin:ev-router/fastest', tripId: 7 }+ await calculateRouteWithLegs(wps, { ...opts, dayId: 1 })+ await calculateRouteWithLegs(wps, { ...opts, dayId: 1 })+ expect(spy).toHaveBeenCalledTimes(1)++ // A plugin may hand back different charging stops for another day, so the+ // cache key is scoped to trip + day.+ await calculateRouteWithLegs(wps, { ...opts, dayId: 2 })+ expect(spy).toHaveBeenCalledTimes(2)+ })+})++// Runs last on purpose: it fills the module-level route cache to its cap, which+// would evict the entries the tests above rely on.+describe('calculateRouteWithLegs cache eviction', () => {+ it('FE-COMP-ROUTECALCULATOR-049: the route cache is capped and drops its oldest entry', async () => {+ const spy = vi.spyOn(pluginsApi, 'pluginRoute').mockResolvedValue({ route: pluginRouteResult() })+ const opts = { profile: 'plugin:ev-router/fastest', tripId: 99 }+ const oldest = freshWaypoints()+ await calculateRouteWithLegs(oldest, opts)++ // ROUTE_CACHE_MAX is 200 — push past it so the first entry falls out again.+ for (let i = 0; i < 201; i++) await calculateRouteWithLegs(freshWaypoints(), opts)++ spy.mockClear()+ await calculateRouteWithLegs(oldest, opts)+ expect(spy).toHaveBeenCalledTimes(1)++ // The OSRM path writes into (and trims) the very same cache.+ let hits = 0+ server.use(http.get(`${FOSSGIS.driving}/:coords`, () => { hits++; return HttpResponse.json(buildLegsResponse()) }))+ await calculateRouteWithLegs(freshWaypoints())+ expect(hits).toBe(1)+ })+})diff --git a/client/src/components/Map/locationMarkerMapbox.test.ts b/client/src/components/Map/locationMarkerMapbox.test.tsnew file mode 100644index 000000000..7e11699aa--- /dev/null+++ b/client/src/components/Map/locationMarkerMapbox.test.ts@@ -0,0 +1,239 @@+// FE-COMP-LOCMARKERGL-001 to FE-COMP-LOCMARKERGL-016+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { attachLocationMarker } from './locationMarkerMapbox'+import type { GeoPosition } from '../../hooks/useGeolocation'++const SOURCE_ID = 'trek-location-accuracy'++type FeatureCollection = {+ type: 'FeatureCollection'+ features: { geometry: { type: string; coordinates: number[][][] } }[]+}++// Minimal mapbox-gl stand-in: sources/layers live in plain maps so the tests can+// assert what the handle added and removed, and `loaded` is switchable to drive+// the "map not ready yet" branch.+function fakeMap({ loaded = true }: { loaded?: boolean } = {}) {+ const sources = new Map<string, { setData: ReturnType<typeof vi.fn> }>()+ const layers = new Map<string, unknown>()+ const once = vi.fn()+ return {+ _sources: sources,+ _layers: layers,+ once,+ loaded: () => loaded,+ getSource: (id: string) => sources.get(id),+ addSource: vi.fn((id: string) => { sources.set(id, { setData: vi.fn() }) }),+ addLayer: vi.fn((layer: { id: string }) => { layers.set(layer.id, layer) }),+ getLayer: (id: string) => layers.get(id),+ removeLayer: vi.fn((id: string) => { layers.delete(id) }),+ removeSource: vi.fn((id: string) => { sources.delete(id) }),+ // Fires the handler the marker registered for the given event.+ fire: (event: string) => {+ const call = once.mock.calls.find(c => c[0] === event)+ ;(call?.[1] as (() => void) | undefined)?.()+ },+ }+}++type FakeMarker = {+ setLngLat: ReturnType<typeof vi.fn>+ addTo: ReturnType<typeof vi.fn>+ remove: ReturnType<typeof vi.fn>+ getElement: () => HTMLElement+ _el: HTMLElement+}++let markers: FakeMarker[] = []++// A marker that mirrors mapbox's DOM contract: addTo appends the element (so+// `getElement().parentElement` becomes truthy), remove detaches it again.+const FakeMarkerCtor = vi.fn(function (options?: { element?: HTMLElement }) {+ const el = options?.element ?? document.createElement('div')+ const marker: FakeMarker = {+ _el: el,+ setLngLat: vi.fn(() => marker),+ addTo: vi.fn(() => { document.body.appendChild(el); return marker }),+ remove: vi.fn(() => { el.remove() }),+ getElement: () => el,+ }+ markers.push(marker)+ return marker+}) as unknown as new (options?: { element?: HTMLElement; anchor?: string }) => unknown++function position(over: Partial<GeoPosition> = {}): GeoPosition {+ return { lat: 48.2, lng: 16.37, accuracy: 20, heading: null, speed: null, timestamp: 1 , ...over } as GeoPosition+}++function lastData(map: ReturnType<typeof fakeMap>): FeatureCollection | undefined {+ const src = map._sources.get(SOURCE_ID)+ const calls = src?.setData.mock.calls ?? []+ return calls[calls.length - 1]?.[0] as FeatureCollection | undefined+}++function attach(map: ReturnType<typeof fakeMap>) {+ return attachLocationMarker(map as never, FakeMarkerCtor as never)+}++beforeEach(() => {+ markers = []+ vi.clearAllMocks()+ document.getElementById('trek-location-style')?.remove()+ document.body.innerHTML = ''+})++describe('attachLocationMarker', () => {+ it('FE-COMP-LOCMARKERGL-001: injects the pulse keyframes exactly once per document', () => {+ attach(fakeMap())+ attach(fakeMap())+ const styles = document.querySelectorAll('#trek-location-style')+ expect(styles).toHaveLength(1)+ expect(styles[0].textContent).toContain('@keyframes trek-location-pulse')+ })++ it('FE-COMP-LOCMARKERGL-002: builds a marker element with a pulse, a heading cone and a dot', () => {+ attach(fakeMap())+ const root = markers[0]._el+ expect(root.children).toHaveLength(3)+ // The cone starts hidden — there is no heading until the first fix.+ expect((root.children[1] as HTMLElement).style.display).toBe('none')+ })++ it('FE-COMP-LOCMARKERGL-003: adds the accuracy source and fill layer when the map is already loaded', () => {+ const map = fakeMap({ loaded: true })+ attach(map)+ expect(map.addSource).toHaveBeenCalledWith(SOURCE_ID, expect.objectContaining({ type: 'geojson' }))+ expect(map.addLayer).toHaveBeenCalledWith(expect.objectContaining({ id: SOURCE_ID, type: 'fill' }))+ })++ it('FE-COMP-LOCMARKERGL-004: defers the layer to the load event when the map is not ready', () => {+ const map = fakeMap({ loaded: false })+ attach(map)+ expect(map.addSource).not.toHaveBeenCalled()+ expect(map.once).toHaveBeenCalledWith('load', expect.any(Function))++ map.fire('load')+ expect(map.addSource).toHaveBeenCalledTimes(1)+ })++ it('FE-COMP-LOCMARKERGL-005: does not re-add the layer when the source already exists', () => {+ const map = fakeMap({ loaded: true })+ attach(map)+ map.addSource.mockClear()+ map.addLayer.mockClear()+ // A second marker on the same map (e.g. a remount) must reuse the source.+ attach(map)+ expect(map.addSource).not.toHaveBeenCalled()+ expect(map.addLayer).not.toHaveBeenCalled()+ })++ it('FE-COMP-LOCMARKERGL-006: swallows an addSource failure instead of breaking the map', () => {+ const map = fakeMap({ loaded: true })+ map.addSource.mockImplementation(() => { throw new Error('style not loaded') })+ expect(() => attach(map)).not.toThrow()+ expect(map.addLayer).not.toHaveBeenCalled()+ })++ it('FE-COMP-LOCMARKERGL-007: the first update positions the marker and adds it to the map', () => {+ const map = fakeMap()+ attach(map).update(position({ lat: 10, lng: 20 }))+ expect(markers[0].setLngLat).toHaveBeenCalledWith([20, 10])+ expect(markers[0].addTo).toHaveBeenCalledWith(map)+ })++ it('FE-COMP-LOCMARKERGL-008: a follow-up update moves the marker without re-adding it', () => {+ const handle = attach(fakeMap())+ handle.update(position())+ handle.update(position({ lat: 11, lng: 21 }))+ expect(markers[0].addTo).toHaveBeenCalledTimes(1)+ expect(markers[0].setLngLat).toHaveBeenLastCalledWith([21, 11])+ })++ it('FE-COMP-LOCMARKERGL-009: a heading shows the cone and rotates it', () => {+ const handle = attach(fakeMap())+ handle.update(position({ heading: 135 }))+ const cone = markers[0]._el.children[1] as HTMLElement+ expect(cone.style.display).toBe('block')+ expect(cone.style.transform).toContain('rotate(135deg)')+ })++ it('FE-COMP-LOCMARKERGL-010: a null or NaN heading hides the cone again', () => {+ const handle = attach(fakeMap())+ const cone = markers[0]._el.children[1] as HTMLElement+ handle.update(position({ heading: 90 }))+ expect(cone.style.display).toBe('block')++ handle.update(position({ heading: null }))+ expect(cone.style.display).toBe('none')++ handle.update(position({ heading: 90 }))+ handle.update(position({ heading: NaN }))+ expect(cone.style.display).toBe('none')+ })++ it('FE-COMP-LOCMARKERGL-011: an accuracy radius becomes a 48-segment geodesic ring', () => {+ const map = fakeMap()+ attach(map).update(position({ lat: 48, lng: 16, accuracy: 100 }))+ const data = lastData(map)!+ expect(data.features).toHaveLength(1)+ const ring = data.features[0].geometry.coordinates[0]+ // 48 segments produces 49 points, with the ring closed back on itself.+ expect(ring).toHaveLength(49)+ expect(ring[0][0]).toBeCloseTo(ring[48][0], 9)+ expect(ring[0][1]).toBeCloseTo(ring[48][1], 9)+ // 100 m at this latitude is well under a hundredth of a degree from the fix.+ ring.forEach(([lng, lat]) => {+ expect(Math.abs(lat - 48)).toBeLessThan(0.01)+ expect(Math.abs(lng - 16)).toBeLessThan(0.01)+ })+ })++ it('FE-COMP-LOCMARKERGL-012: a sub-metre or missing accuracy clears the ring', () => {+ const map = fakeMap()+ const handle = attach(map)+ handle.update(position({ accuracy: 0.5 }))+ expect(lastData(map)!.features).toHaveLength(0)++ handle.update(position({ accuracy: 0 }))+ expect(lastData(map)!.features).toHaveLength(0)+ })++ it('FE-COMP-LOCMARKERGL-013: update(null) removes the marker and empties the accuracy ring', () => {+ const map = fakeMap()+ const handle = attach(map)+ handle.update(position({ accuracy: 80 }))+ expect(lastData(map)!.features).toHaveLength(1)++ handle.update(null)+ expect(markers[0].remove).toHaveBeenCalled()+ expect(lastData(map)!.features).toHaveLength(0)+ })++ it('FE-COMP-LOCMARKERGL-014: an update before the source exists does not throw', () => {+ const map = fakeMap({ loaded: false })+ const handle = attach(map)+ expect(() => handle.update(position({ accuracy: 50 }))).not.toThrow()+ expect(() => handle.update(null)).not.toThrow()+ expect(markers[0].setLngLat).toHaveBeenCalled()+ })++ it('FE-COMP-LOCMARKERGL-015: destroy removes the marker, the layer and the source', () => {+ const map = fakeMap()+ const handle = attach(map)+ handle.update(position())+ handle.destroy()+ expect(markers[0].remove).toHaveBeenCalled()+ expect(map.removeLayer).toHaveBeenCalledWith(SOURCE_ID)+ expect(map.removeSource).toHaveBeenCalledWith(SOURCE_ID)+ })++ it('FE-COMP-LOCMARKERGL-016: destroy survives a torn-down map and a throwing marker', () => {+ const map = fakeMap()+ const handle = attach(map)+ markers[0].remove.mockImplementation(() => { throw new Error('marker gone') })+ map.removeLayer.mockImplementation(() => { throw new Error('style gone') })+ expect(() => handle.destroy()).not.toThrow()+ // The source removal is in the same try block, so it never ran.+ expect(map.removeSource).not.toHaveBeenCalled()+ })+})diff --git a/client/src/components/Map/mapboxSetup.test.ts b/client/src/components/Map/mapboxSetup.test.tsnew file mode 100644index 000000000..e3698ab10--- /dev/null+++ b/client/src/components/Map/mapboxSetup.test.ts@@ -0,0 +1,181 @@+// FE-COMP-MAPBOXSETUP-001 to FE-COMP-MAPBOXSETUP-014+import { describe, it, expect, vi } from 'vitest'+import type mapboxgl from 'mapbox-gl'+import {+ isStandardFamily,+ wantsTerrain,+ supportsCustom3d,+ addCustom3dBuildings,+ addTerrainAndSky,+} from './mapboxSetup'++interface FakeMapOptions {+ layers?: string[]+ sources?: string[]+ styleLayers?: Array<{ id: string; type: string }>+ noStyle?: boolean+ addSourceThrows?: boolean+ addLayerThrows?: boolean+ setTerrainThrows?: boolean+}++function fakeMap(opts: FakeMapOptions = {}) {+ const layers = new Set(opts.layers ?? [])+ const sources = new Set(opts.sources ?? [])+ return {+ getLayer: vi.fn((id: string) => (layers.has(id) ? { id } : undefined)),+ getSource: vi.fn((id: string) => (sources.has(id) ? { id } : undefined)),+ addSource: vi.fn((id: string) => {+ if (opts.addSourceThrows) throw new Error('source rejected')+ sources.add(id)+ }),+ addLayer: vi.fn((spec: { id: string }) => {+ if (opts.addLayerThrows) throw new Error('source-layer unavailable')+ layers.add(spec.id)+ }),+ getStyle: vi.fn(() => (opts.noStyle ? undefined : { layers: opts.styleLayers ?? [] })),+ setTerrain: vi.fn(() => {+ if (opts.setTerrainThrows) throw new Error('style has no terrain')+ }),+ }+}++type FakeMap = ReturnType<typeof fakeMap>+const asMap = (m: FakeMap) => m as unknown as mapboxgl.Map++describe('mapboxSetup', () => {+ it('FE-COMP-MAPBOXSETUP-001: recognises the two Standard styles as the standard family', () => {+ expect(isStandardFamily('mapbox://styles/mapbox/standard')).toBe(true)+ expect(isStandardFamily('mapbox://styles/mapbox/standard-satellite')).toBe(true)+ expect(isStandardFamily('mapbox://styles/mapbox/streets-v12')).toBe(false)+ expect(isStandardFamily('https://tiles.openfreemap.org/styles/liberty')).toBe(false)+ })++ it('FE-COMP-MAPBOXSETUP-002: wants terrain only for satellite and outdoors styles', () => {+ expect(wantsTerrain('mapbox://styles/mapbox/satellite-v9')).toBe(true)+ expect(wantsTerrain('mapbox://styles/mapbox/satellite-streets-v12')).toBe(true)+ expect(wantsTerrain('mapbox://styles/mapbox/outdoors-v12')).toBe(true)+ // Flat vector styles must stay flat — DEM would drift the route lines off the markers.+ expect(wantsTerrain('mapbox://styles/mapbox/streets-v12')).toBe(false)+ expect(wantsTerrain('mapbox://styles/mapbox/standard')).toBe(false)+ })++ it('FE-COMP-MAPBOXSETUP-003: custom 3D is offered for everything outside the standard family', () => {+ expect(supportsCustom3d('mapbox://styles/mapbox/streets-v12')).toBe(true)+ expect(supportsCustom3d('mapbox://styles/mapbox/satellite-v9')).toBe(true)+ expect(supportsCustom3d('mapbox://styles/mapbox/standard')).toBe(false)+ expect(supportsCustom3d('mapbox://styles/mapbox/standard-satellite')).toBe(false)+ })++ it('FE-COMP-MAPBOXSETUP-004: addCustom3dBuildings bails out when the layer already exists', () => {+ const map = fakeMap({ layers: ['trek-3d-buildings'] })+ addCustom3dBuildings(asMap(map), false)+ expect(map.addLayer).not.toHaveBeenCalled()+ expect(map.addSource).not.toHaveBeenCalled()+ })++ it('FE-COMP-MAPBOXSETUP-005: uses the style composite source and inserts below the first symbol layer', () => {+ const map = fakeMap({+ sources: ['composite'],+ styleLayers: [+ { id: 'water', type: 'fill' },+ { id: 'place-labels', type: 'symbol' },+ { id: 'road-labels', type: 'symbol' },+ ],+ })+ addCustom3dBuildings(asMap(map), false)++ expect(map.addSource).not.toHaveBeenCalled()+ const [spec, beforeId] = map.addLayer.mock.calls[0] as unknown as [Record<string, unknown>, string]+ expect(spec.id).toBe('trek-3d-buildings')+ expect(spec.source).toBe('composite')+ expect(spec.type).toBe('fill-extrusion')+ // Extrusions must sit under the first label layer so text stays readable.+ expect(beforeId).toBe('place-labels')+ })++ it('FE-COMP-MAPBOXSETUP-006: attaches the streets tileset when the style has no composite source', () => {+ const map = fakeMap({ styleLayers: [] })+ addCustom3dBuildings(asMap(map), false)++ expect(map.addSource).toHaveBeenCalledWith('mapbox-streets-v8', {+ type: 'vector',+ url: 'mapbox://mapbox.mapbox-streets-v8',+ })+ const [spec, beforeId] = map.addLayer.mock.calls[0] as unknown as [Record<string, unknown>, string | undefined]+ expect(spec.source).toBe('mapbox-streets-v8')+ // No symbol layer in the style: nothing to insert before.+ expect(beforeId).toBeUndefined()+ })++ it('FE-COMP-MAPBOXSETUP-007: reuses an already attached streets tileset', () => {+ const map = fakeMap({ sources: ['mapbox-streets-v8'] })+ addCustom3dBuildings(asMap(map), false)++ expect(map.addSource).not.toHaveBeenCalled()+ const [spec] = map.addLayer.mock.calls[0] as unknown as [Record<string, unknown>]+ expect(spec.source).toBe('mapbox-streets-v8')+ })++ it('FE-COMP-MAPBOXSETUP-008: gives up quietly when the fallback source cannot be added', () => {+ const map = fakeMap({ addSourceThrows: true })+ expect(() => addCustom3dBuildings(asMap(map), false)).not.toThrow()+ expect(map.addLayer).not.toHaveBeenCalled()+ })++ it('FE-COMP-MAPBOXSETUP-009: swallows a rejected extrusion layer', () => {+ const map = fakeMap({ sources: ['composite'], addLayerThrows: true })+ expect(() => addCustom3dBuildings(asMap(map), false)).not.toThrow()+ expect(map.addLayer).toHaveBeenCalledTimes(1)+ })++ it('FE-COMP-MAPBOXSETUP-010: picks the dark building colour in dark mode', () => {+ const light = fakeMap({ sources: ['composite'] })+ addCustom3dBuildings(asMap(light), false)+ const dark = fakeMap({ sources: ['composite'] })+ addCustom3dBuildings(asMap(dark), true)++ const paintOf = (m: FakeMap) => (m.addLayer.mock.calls[0][0] as unknown as { paint: Record<string, unknown> }).paint+ expect(paintOf(light)['fill-extrusion-color']).toBe('#cfd2d6')+ expect(paintOf(dark)['fill-extrusion-color']).toBe('#3b3b3f')+ })++ it('FE-COMP-MAPBOXSETUP-011: survives a style that reports no layers at all', () => {+ const map = fakeMap({ sources: ['composite'], noStyle: true })+ addCustom3dBuildings(asMap(map), false)+ const [, beforeId] = map.addLayer.mock.calls[0] as unknown as [unknown, string | undefined]+ expect(beforeId).toBeUndefined()+ })++ it('FE-COMP-MAPBOXSETUP-012: addTerrainAndSky adds the DEM source, the terrain and the sky layer', () => {+ const map = fakeMap()+ addTerrainAndSky(asMap(map))++ expect(map.addSource).toHaveBeenCalledWith('mapbox-dem', {+ type: 'raster-dem',+ url: 'mapbox://mapbox.mapbox-terrain-dem-v1',+ tileSize: 512,+ maxzoom: 14,+ })+ expect(map.setTerrain).toHaveBeenCalledWith({ source: 'mapbox-dem', exaggeration: 1.2 })+ const [spec] = map.addLayer.mock.calls[0] as unknown as [Record<string, unknown>]+ expect(spec.id).toBe('sky')+ expect(spec.type).toBe('sky')+ })++ it('FE-COMP-MAPBOXSETUP-013: does not re-add DEM or sky when they are already there', () => {+ const map = fakeMap({ sources: ['mapbox-dem'], layers: ['sky'] })+ addTerrainAndSky(asMap(map))++ expect(map.addSource).not.toHaveBeenCalled()+ expect(map.addLayer).not.toHaveBeenCalled()+ // Terrain itself is re-applied — it is what the style rebuild dropped.+ expect(map.setTerrain).toHaveBeenCalledTimes(1)+ })++ it('FE-COMP-MAPBOXSETUP-014: swallows a style that does not support terrain', () => {+ const map = fakeMap({ setTerrainThrows: true })+ expect(() => addTerrainAndSky(asMap(map))).not.toThrow()+ expect(map.addLayer).not.toHaveBeenCalled()+ })+})diff --git a/client/src/components/Map/placePopup.test.ts b/client/src/components/Map/placePopup.test.tsnew file mode 100644index 000000000..9eea982b2--- /dev/null+++ b/client/src/components/Map/placePopup.test.ts@@ -0,0 +1,132 @@+// FE-COMP-PLACEPOPUP-001 to FE-COMP-PLACEPOPUP-014+import { describe, it, expect } from 'vitest'+import { buildPlacePopupHtml, buildPoiPopupHtml } from './placePopup'+import { buildPlace } from '../../../tests/helpers/factories'+import type { Poi } from './poiCategories'+import type { Place } from '../../types'++type PopupPlace = Place & {+ category_color?: string | null+ category_icon?: string | null+ category_name?: string | null+}++function popupPlace(overrides: Partial<PopupPlace> = {}): PopupPlace {+ return {+ ...buildPlace(),+ category_color: null,+ category_icon: null,+ category_name: null,+ ...overrides,+ } as PopupPlace+}++function poi(overrides: Partial<Poi> = {}): Poi {+ return {+ osm_id: 'node/1',+ name: 'Café Central',+ lat: 48.21,+ lng: 16.36,+ category: 'cafe',+ poi_type: 'cafe',+ address: null,+ website: null,+ phone: null,+ opening_hours: null,+ cuisine: null,+ source: 'openstreetmap',+ ...overrides,+ }+}++describe('buildPlacePopupHtml', () => {+ it('FE-COMP-PLACEPOPUP-001: renders the name and nothing else for a bare place', () => {+ const html = buildPlacePopupHtml(popupPlace({ name: 'Louvre', address: null }), null)+ expect(html).toContain('Louvre')+ expect(html).not.toContain('<img')+ expect(html).not.toContain('<svg')+ })++ it('FE-COMP-PLACEPOPUP-002: escapes HTML metacharacters in the name', () => {+ const html = buildPlacePopupHtml(popupPlace({ name: 'Bar & "Grill" <b>x</b>' }), null)+ expect(html).toContain('Bar & "Grill" <b>x</b>')+ expect(html).not.toContain('<b>x</b>')+ })++ it('FE-COMP-PLACEPOPUP-003: embeds a data: thumbnail as an img', () => {+ const html = buildPlacePopupHtml(popupPlace(), 'data:image/jpeg;base64,AAAA')+ expect(html).toContain('<img src="data:image/jpeg;base64,AAAA"')+ })++ it('FE-COMP-PLACEPOPUP-004: embeds a photo-proxy URL as an img', () => {+ const html = buildPlacePopupHtml(popupPlace(), '/api/maps/place-photo/abc123')+ expect(html).toContain('<img src="/api/maps/place-photo/abc123"')+ })++ it('FE-COMP-PLACEPOPUP-005: ignores a foreign photo URL — it is a fetch seed, not a src', () => {+ const html = buildPlacePopupHtml(popupPlace(), 'https://lh3.googleusercontent.com/p/AF1')+ expect(html).not.toContain('<img')+ })++ it('FE-COMP-PLACEPOPUP-006: renders the category row with an inline icon svg', () => {+ const html = buildPlacePopupHtml(+ popupPlace({ category_name: 'Museum', category_icon: 'Landmark', category_color: '#6366F1' }),+ null,+ )+ expect(html).toContain('Museum')+ expect(html).toContain('<svg')+ expect(html).toContain('#6366F1')+ })++ it('FE-COMP-PLACEPOPUP-007: an unknown icon name falls back to the MapPin glyph', () => {+ const known = buildPlacePopupHtml(popupPlace({ category_name: 'X', category_icon: 'MapPin' }), null)+ const unknown = buildPlacePopupHtml(popupPlace({ category_name: 'X', category_icon: 'NoSuchIcon' }), null)+ const svgOf = (s: string) => s.slice(s.indexOf('<svg'), s.indexOf('</svg>'))+ expect(svgOf(unknown)).toBe(svgOf(known))+ })++ it('FE-COMP-PLACEPOPUP-008: a category without an icon draws no category row', () => {+ const html = buildPlacePopupHtml(popupPlace({ category_name: 'Museum', category_icon: null }), null)+ expect(html).not.toContain('Museum')+ expect(html).not.toContain('<svg')+ })++ it('FE-COMP-PLACEPOPUP-009: an icon without a category name draws no category row', () => {+ const html = buildPlacePopupHtml(popupPlace({ category_name: null, category_icon: 'Landmark' }), null)+ expect(html).not.toContain('<svg')+ })++ it('FE-COMP-PLACEPOPUP-010: renders and escapes the address', () => {+ const html = buildPlacePopupHtml(popupPlace({ address: 'Rue <A> & B' }), null)+ expect(html).toContain('Rue <A> & B')+ })++ it('FE-COMP-PLACEPOPUP-011: a category icon with no colour falls back to grey', () => {+ const html = buildPlacePopupHtml(+ popupPlace({ category_name: 'Museum', category_icon: 'Landmark', category_color: null }),+ null,+ )+ expect(html).toContain('#6b7280')+ })+})++describe('buildPoiPopupHtml', () => {+ it('FE-COMP-PLACEPOPUP-012: renders the POI name with its category-coloured icon', () => {+ const html = buildPoiPopupHtml(poi({ name: 'Café Central', category: 'cafe' }))+ expect(html).toContain('Café Central')+ expect(html).toContain('<svg')+ // cafe → #B45309 in POI_CATEGORIES+ expect(html).toContain('#B45309')+ })++ it('FE-COMP-PLACEPOPUP-013: an unknown category renders no icon and the grey fallback', () => {+ const html = buildPoiPopupHtml(poi({ category: 'not-a-category', name: 'Somewhere' }))+ expect(html).not.toContain('<svg')+ expect(html).toContain('Somewhere')+ })++ it('FE-COMP-PLACEPOPUP-014: escapes the POI address and omits it when absent', () => {+ expect(buildPoiPopupHtml(poi({ address: null }))).not.toContain('margin-top:3px')+ expect(buildPoiPopupHtml(poi({ address: 'Herrengasse 14 & 16' }))).toContain('Herrengasse 14 & 16')+ })+})diff --git a/client/src/components/Map/reservationsMapbox.test.ts b/client/src/components/Map/reservationsMapbox.test.tsindex ab39319d6..ce02a60bb 100644--- a/client/src/components/Map/reservationsMapbox.test.ts+++ b/client/src/components/Map/reservationsMapbox.test.ts@@ -1,6 +1,11 @@-import { describe, it, expect, vi } from 'vitest'-import { ReservationMapboxOverlay } from './reservationsMapbox'-import type { Reservation } from '../../types'+import { describe, it, expect, vi, beforeEach } from 'vitest'+import {+ ReservationMapboxOverlay,+ RESERVATION_SOURCE_ID,+ RESERVATION_LINE_LAYER_ID,+ type ReservationOverlayOptions,+} from './reservationsMapbox'+import type { Reservation, ReservationEndpoint } from '../../types'// A minimal mapbox-gl stand-in: a persistent source that records the last// setData, and project() spreading points far enough apart to pass the@@ -134,3 +139,577 @@ describe('ReservationMapboxOverlay transit routes (#1570)', () => {expect(data.features).toHaveLength(0)})})++// ── FE-COMP-RESGL-001 to FE-COMP-RESGL-023 ────────────────────────────────────+// The fake above always hands back a source, which makes the constructor skip+// setupLayer. This one starts empty like a real freshly-styled map, records its+// event handlers so the tests can fire them, and lets a test swap the projection+// mid-flight to simulate a zoom.++type Handler = () => void+type Projection = (c: [number, number]) => { x: number; y: number }++const spread: Projection = ([lng, lat]) => ({ x: lng * 1000, y: lat * 1000 })+const collapsed: Projection = () => ({ x: 0, y: 0 })++function freshMap(projection: Projection = spread) {+ const sources = new Map<string, { setData: ReturnType<typeof vi.fn> }>()+ const layers = new Map<string, unknown>()+ const handlers: Record<string, Handler[]> = {}+ return {+ projection,+ _sources: sources,+ _layers: layers,+ getSource: (id: string) => sources.get(id),+ addSource: vi.fn((id: string) => { sources.set(id, { setData: vi.fn() }) }),+ addLayer: vi.fn((layer: { id: string }) => { layers.set(layer.id, layer) }),+ getLayer: (id: string) => layers.get(id),+ removeLayer: vi.fn((id: string) => { layers.delete(id) }),+ removeSource: vi.fn((id: string) => { sources.delete(id) }),+ on: vi.fn(function (this: void, event: string, fn: Handler) { (handlers[event] ||= []).push(fn) }),+ off: vi.fn((event: string, fn: Handler) => { handlers[event] = (handlers[event] || []).filter(h => h !== fn) }),+ getZoom: () => 12,+ project(this: { projection: Projection }, c: [number, number]) { return this.projection(c) },+ fire: (event: string) => { (handlers[event] || []).forEach(h => h()) },+ listeners: (event: string) => (handlers[event] || []).length,+ }+}++type MarkerRecord = { el: HTMLElement; remove: ReturnType<typeof vi.fn>; lngLat: [number, number] | null }+let glMarkers: MarkerRecord[] = []++// Unlike FakeMarker above this keeps the element it was handed, so the tests can+// read the rendered badge and dispatch real clicks on it.+const TrackingMarker = vi.fn(function (options?: { element?: HTMLElement }) {+ const record: MarkerRecord = {+ el: options?.element ?? document.createElement('div'),+ remove: vi.fn(),+ lngLat: null,+ }+ glMarkers.push(record)+ const marker = {+ setLngLat: (lngLat: [number, number]) => { record.lngLat = lngLat; return marker },+ addTo: () => marker,+ remove: record.remove,+ getElement: () => record.el,+ }+ return marker+}) as unknown as new (options?: { element?: HTMLElement; anchor?: string }) => unknown++function endpoint(over: Partial<ReservationEndpoint> = {}): ReservationEndpoint {+ return {+ role: 'from', sequence: 0, name: 'A', code: null,+ lat: 48, lng: 2, timezone: null, local_time: null, local_date: null,+ ...over,+ } as unknown as ReservationEndpoint+}++function booking(over: Partial<Reservation> = {}): Reservation {+ return {+ id: 100, type: 'flight', status: 'confirmed',+ endpoints: [+ endpoint({ role: 'from', sequence: 0, name: 'Vienna', code: 'VIE', lat: 48, lng: 16 }),+ endpoint({ role: 'to', sequence: 1, name: 'London', code: 'LHR', lat: 51.5, lng: -0.5 }),+ ],+ ...over,+ } as unknown as Reservation+}++const labelled = { showConnections: true, showStats: false, showEndpointLabels: true }++function features(map: ReturnType<typeof freshMap>) {+ const src = map._sources.get(RESERVATION_SOURCE_ID)+ const calls = src?.setData.mock.calls ?? []+ const data = calls[calls.length - 1]?.[0] as {+ features: { properties: Record<string, unknown>; geometry: { coordinates: [number, number][] } }[]+ } | undefined+ return data?.features ?? []+}++function attach(map: ReturnType<typeof freshMap>, options: ReservationOverlayOptions = opts) {+ return new ReservationMapboxOverlay(map as never, options, TrackingMarker as never)+}++beforeEach(() => {+ glMarkers = []+ vi.clearAllMocks()+})++describe('ReservationMapboxOverlay lifecycle', () => {+ it('FE-COMP-RESGL-001: sets up the geojson source and both line layers on a fresh map', () => {+ const map = freshMap()+ attach(map)+ expect(map.addSource).toHaveBeenCalledWith(RESERVATION_SOURCE_ID, expect.objectContaining({ type: 'geojson' }))+ expect(map._layers.has(RESERVATION_LINE_LAYER_ID)).toBe(true)+ expect(map._layers.has(`${RESERVATION_LINE_LAYER_ID}-transit-casing`)).toBe(true)+ })++ it('FE-COMP-RESGL-002: a second overlay on the same map reuses the existing source', () => {+ const map = freshMap()+ attach(map)+ map.addSource.mockClear()+ map.addLayer.mockClear()+ attach(map)+ expect(map.addSource).not.toHaveBeenCalled()+ expect(map.addLayer).not.toHaveBeenCalled()+ })++ it('FE-COMP-RESGL-003: destroy unhooks every listener and removes the markers, layer and source', () => {+ const map = freshMap()+ const overlay = attach(map, { ...opts, onEndpointClick: vi.fn() })+ overlay.update([booking()], opts)+ expect(glMarkers).toHaveLength(2)++ overlay.destroy()+ expect(glMarkers.every(m => m.remove.mock.calls.length > 0)).toBe(true)+ expect(map.listeners('zoomend')).toBe(0)+ expect(map.listeners('moveend')).toBe(0)+ expect(map.listeners('render')).toBe(0)+ expect(map.removeLayer).toHaveBeenCalledWith(RESERVATION_LINE_LAYER_ID)+ expect(map.removeSource).toHaveBeenCalledWith(RESERVATION_SOURCE_ID)+ })++ it('FE-COMP-RESGL-004: destroy survives a map whose style is already gone', () => {+ const map = freshMap()+ const overlay = attach(map)+ map.removeLayer.mockImplementation(() => { throw new Error('style gone') })+ expect(() => overlay.destroy()).not.toThrow()+ })++ it('FE-COMP-RESGL-005: a camera move redraws — a hop that was decluttered appears once zoomed in', () => {+ const map = freshMap(collapsed)+ const overlay = attach(map)+ overlay.update([booking({ type: 'train' })], opts)+ expect(features(map)).toHaveLength(0)++ map.projection = spread+ map.fire('zoomend')+ expect(features(map)).toHaveLength(1)+ })++ it('FE-COMP-RESGL-006: the redraw and rotation handlers are inert once the overlay is destroyed', () => {+ const map = freshMap()+ const overlay = attach(map)+ const handlerFor = (event: string) =>+ map.on.mock.calls.find(c => c[0] === event)?.[1] as Handler+ const rerender = handlerFor('moveend')+ const rotate = handlerFor('render')++ overlay.update([booking()], opts)+ const drawsBefore = map._sources.get(RESERVATION_SOURCE_ID)!.setData.mock.calls.length+ overlay.destroy()++ rerender()+ rotate()+ expect(map._sources.get(RESERVATION_SOURCE_ID)).toBeUndefined()+ expect(drawsBefore).toBeGreaterThan(0)+ })++ it('FE-COMP-RESGL-007: an update after the style dropped the source draws nothing', () => {+ const map = freshMap()+ const overlay = attach(map)+ map._sources.clear()+ overlay.update([booking()], opts)+ expect(glMarkers).toHaveLength(0)+ })++ it('FE-COMP-RESGL-008: a projection failure keeps the booking rather than hiding it', () => {+ const map = freshMap(() => { throw new Error('not projectable') })+ const overlay = attach(map)+ overlay.update([booking()], labelled)+ expect(features(map)).toHaveLength(1)+ // The label threshold cannot be measured either, so no labels are drawn.+ expect(glMarkers[0].el.textContent).toBe('')+ })+})++describe('ReservationMapboxOverlay item filtering', () => {+ it('FE-COMP-RESGL-009: ignores reservations that are not transport', () => {+ const map = freshMap()+ attach(map).update([booking({ type: 'hotel' as Reservation['type'] })], opts)+ expect(features(map)).toHaveLength(0)+ expect(glMarkers).toHaveLength(0)+ })++ it('FE-COMP-RESGL-010: ignores a booking with fewer than two waypoints', () => {+ const map = freshMap()+ attach(map).update([booking({ endpoints: [endpoint({ role: 'from', sequence: 0 })] })], opts)+ expect(features(map)).toHaveLength(0)+ })++ it('FE-COMP-RESGL-011: ignores endpoints that are neither from, to nor stop', () => {+ const map = freshMap()+ const res = booking({+ endpoints: [+ endpoint({ role: 'from', sequence: 0, lat: 48, lng: 16 }),+ endpoint({ role: 'via' as ReservationEndpoint['role'], sequence: 1, lat: 49, lng: 17 }),+ ],+ })+ attach(map).update([res], opts)+ expect(features(map)).toHaveLength(0)+ })++ it('FE-COMP-RESGL-012: orders waypoints by sequence and draws one arc per leg', () => {+ const map = freshMap()+ const res = booking({+ type: 'train',+ endpoints: [+ endpoint({ role: 'to', sequence: 2, name: 'C', lat: 51, lng: 16 }),+ endpoint({ role: 'from', sequence: 0, name: 'A', lat: 48, lng: 16 }),+ endpoint({ role: 'stop', sequence: 1, name: 'B', lat: 49.5, lng: 16 }),+ ],+ })+ attach(map).update([res], opts)+ const drawn = features(map)+ expect(drawn).toHaveLength(2)+ // GeoJSON is [lng, lat]; legs run A→B and B→C.+ expect(drawn[0].geometry.coordinates).toEqual([[16, 48], [16, 49.5]])+ expect(drawn[1].geometry.coordinates).toEqual([[16, 49.5], [16, 51]])+ })++ it('FE-COMP-RESGL-013: a booking without a status is drawn as pending', () => {+ const map = freshMap()+ attach(map).update([booking({ status: undefined })], opts)+ expect(features(map)[0].properties.status).toBe('pending')+ })+})++describe('ReservationMapboxOverlay endpoint markers', () => {+ it('FE-COMP-RESGL-014: places one marker per waypoint, titled with the stop name', () => {+ const map = freshMap()+ attach(map).update([booking()], opts)+ expect(glMarkers).toHaveLength(2)+ expect(glMarkers.map(m => m.lngLat)).toEqual([[16, 48], [-0.5, 51.5]])+ expect(glMarkers.map(m => m.el.title)).toEqual(['Vienna', 'London'])+ })++ it('FE-COMP-RESGL-015: no label is rendered while endpoint labels are off', () => {+ const map = freshMap()+ attach(map).update([booking()], opts)+ expect(glMarkers[0].el.textContent).toBe('')+ })++ it('FE-COMP-RESGL-016: labels show the endpoint code when there is one', () => {+ const map = freshMap()+ attach(map).update([booking()], labelled)+ expect(glMarkers.map(m => m.el.textContent)).toEqual(['VIE', 'LHR'])+ })++ it('FE-COMP-RESGL-017: a code-less stop falls back to its name with the parenthetical stripped', () => {+ const map = freshMap()+ const res = booking({+ type: 'train',+ endpoints: [+ endpoint({ role: 'from', sequence: 0, name: 'Wien Hbf (Bahnsteig 3)', lat: 48, lng: 16 }),+ endpoint({ role: 'to', sequence: 1, name: 'München Hbf', lat: 49, lng: 16 }),+ ],+ })+ attach(map).update([res], labelled)+ expect(glMarkers.map(m => m.el.textContent)).toEqual(['Wien Hbf', 'München Hbf'])+ })++ it('FE-COMP-RESGL-018: a short hop draws its line but not its labels', () => {+ const map = freshMap()+ // 300 px apart: past the 200 px line threshold, under the 400 px label one.+ const res = booking({+ type: 'train',+ endpoints: [+ endpoint({ role: 'from', sequence: 0, name: 'Wien', code: 'VIE', lat: 48, lng: 16 }),+ endpoint({ role: 'to', sequence: 1, name: 'Graz', code: 'GRZ', lat: 48.3, lng: 16 }),+ ],+ })+ attach(map).update([res], labelled)+ expect(features(map)).toHaveLength(1)+ expect(glMarkers.map(m => m.el.textContent)).toEqual(['', ''])+ })++ it('FE-COMP-RESGL-019: a redraw replaces the previous markers instead of stacking them', () => {+ const map = freshMap()+ const overlay = attach(map)+ overlay.update([booking()], opts)+ const first = [...glMarkers]++ overlay.update([booking()], opts)+ expect(first.every(m => m.remove.mock.calls.length > 0)).toBe(true)+ expect(glMarkers).toHaveLength(4)+ })++ it('FE-COMP-RESGL-020: hiding connections drops the markers and the lines', () => {+ const map = freshMap()+ const overlay = attach(map)+ overlay.update([booking()], opts)+ const shown = [...glMarkers]++ overlay.update([booking()], { ...opts, showConnections: false })+ expect(shown.every(m => m.remove.mock.calls.length > 0)).toBe(true)+ expect(features(map)).toHaveLength(0)+ expect(glMarkers).toHaveLength(2) // the removed ones; none were added+ })++ it('FE-COMP-RESGL-021: clicking an endpoint reports its reservation and does not reach the map', () => {+ const onEndpointClick = vi.fn()+ const clickable = { ...opts, onEndpointClick }+ const map = freshMap()+ attach(map, clickable).update([booking({ id: 77 })], clickable)++ const wrapper = document.createElement('div')+ const onMapClick = vi.fn()+ wrapper.addEventListener('click', onMapClick)+ wrapper.appendChild(glMarkers[0].el)+ glMarkers[0].el.dispatchEvent(new MouseEvent('click', { bubbles: true }))++ expect(onEndpointClick).toHaveBeenCalledWith(77)+ expect(onMapClick).not.toHaveBeenCalled()+ })++ it('FE-COMP-RESGL-022: without a click handler the marker stays inert', () => {+ const map = freshMap()+ attach(map, { ...opts, onEndpointClick: undefined }).update([booking()], opts)+ expect(() => glMarkers[0].el.dispatchEvent(new MouseEvent('click', { bubbles: true }))).not.toThrow()+ })+})++// computeDuration feeds the stats badge, which the GL overlay no longer draws —+// but it still runs on every update, and a throw in there blanked whole trips+// once (#1620). These pin down that every time shape stays survivable and the+// connection keeps being drawn.+describe('ReservationMapboxOverlay duration math', () => {+ function timed(from: Partial<ReservationEndpoint>, to: Partial<ReservationEndpoint>, res: Partial<Reservation> = {}) {+ return booking({+ endpoints: [+ endpoint({ role: 'from', sequence: 0, name: 'Vienna', code: 'VIE', lat: 48, lng: 16, ...from }),+ endpoint({ role: 'to', sequence: 1, name: 'London', code: 'LHR', lat: 51.5, lng: -0.5, ...to }),+ ],+ ...res,+ })+ }++ it('FE-COMP-RESGL-023: a well-formed cross-timezone flight renders', () => {+ const map = freshMap()+ attach(map).update([timed(+ { timezone: 'Europe/Vienna', local_date: '2024-01-15', local_time: '09:20' },+ { timezone: 'Europe/London', local_date: '2024-01-15', local_time: '11:05' },+ )], opts)+ expect(features(map)).toHaveLength(1)+ })++ it('FE-COMP-RESGL-024: an overnight flight whose arrival reads earlier than departure renders', () => {+ const map = freshMap()+ attach(map).update([timed(+ { timezone: 'Europe/Vienna', local_date: '2024-01-15', local_time: '22:30' },+ { timezone: 'America/New_York', local_date: '2024-01-15', local_time: '02:10' },+ )], opts)+ expect(features(map)).toHaveLength(1)+ })++ it('FE-COMP-RESGL-025: a time-only endpoint borrows the date from the other side', () => {+ const map = freshMap()+ attach(map).update([timed(+ { local_date: '2024-01-15', local_time: '09:20' },+ {},+ { reservation_end_time: '17:30' } as Partial<Reservation>,+ )], opts)+ expect(features(map)).toHaveLength(1)++ const other = freshMap()+ attach(other).update([timed(+ {},+ { local_date: '2024-01-15', local_time: '17:30' },+ { reservation_time: '09:20' } as Partial<Reservation>,+ )], opts)+ expect(features(other)).toHaveLength(1)+ })++ it('FE-COMP-RESGL-026: two date-less times render without a duration', () => {+ const map = freshMap()+ attach(map).update([timed({}, {}, {+ reservation_time: '09:20', reservation_end_time: '17:30',+ } as Partial<Reservation>)], opts)+ expect(features(map)).toHaveLength(1)+ })++ it('FE-COMP-RESGL-027: a booking without time zones uses the plain reservation times', () => {+ const map = freshMap()+ attach(map).update([timed({}, {}, {+ reservation_time: '2024-01-15T09:20', reservation_end_time: '2024-01-15T17:30',+ } as Partial<Reservation>)], opts)+ expect(features(map)).toHaveLength(1)+ })++ it('FE-COMP-RESGL-028: an implausibly long gap is rendered without a duration', () => {+ const map = freshMap()+ attach(map).update([timed({}, {}, {+ reservation_time: '2024-01-15T09:20', reservation_end_time: '2024-01-19T17:30',+ } as Partial<Reservation>)], opts)+ expect(features(map)).toHaveLength(1)+ })++ it('FE-COMP-RESGL-029: a booking with no times at all still draws its connection', () => {+ const map = freshMap()+ attach(map).update([timed({}, {})], opts)+ expect(features(map)).toHaveLength(1)+ })++ it('FE-COMP-RESGL-030: a hop shorter than an hour renders', () => {+ const map = freshMap()+ attach(map).update([timed({}, {}, {+ reservation_time: '2024-01-15T09:20', reservation_end_time: '2024-01-15T09:50',+ } as Partial<Reservation>)], opts)+ expect(features(map)).toHaveLength(1)+ })++ it('FE-COMP-RESGL-031: a stored timestamp that carries no clock time renders', () => {+ const map = freshMap()+ attach(map).update([timed(+ { timezone: 'Europe/Vienna' },+ { timezone: 'Europe/London' },+ { reservation_time: '2024-01-15T', reservation_end_time: '2024-01-15T18:00' } as Partial<Reservation>,+ )], opts)+ expect(features(map)).toHaveLength(1)+ })+})++describe('ReservationMapboxOverlay declutter floors', () => {+ // At the fake projection one degree of latitude is 1000 px, so `dLat` is the+ // on-screen gap between the two endpoints divided by 1000.+ const hop = (id: number, type: string, dLat: number) => booking({+ id, type: type as Reservation['type'],+ endpoints: [+ endpoint({ role: 'from', sequence: 0, name: 'Genoa', code: 'GOA', lat: 48, lng: 16 }),+ endpoint({ role: 'to', sequence: 1, name: 'Palma', code: 'PMI', lat: 48 + dLat, lng: 16 }),+ ],+ })++ it('FE-COMP-RESGL-032: a cruise needs 150 px before it is drawn', () => {+ const near = freshMap()+ attach(near, labelled).update([hop(1, 'cruise', 0.1)], labelled)+ expect(features(near)).toHaveLength(0)++ const far = freshMap()+ attach(far, labelled).update([hop(2, 'cruise', 0.2)], labelled)+ expect(features(far)).toHaveLength(1)+ })++ it('FE-COMP-RESGL-033: a cruise keeps its endpoint labels off below 300 px', () => {+ const map = freshMap()+ attach(map, labelled).update([hop(1, 'cruise', 0.2)], labelled)+ expect(glMarkers.map(m => m.el.textContent)).toEqual(['', ''])++ glMarkers = []+ const wide = freshMap()+ attach(wide, labelled).update([hop(2, 'cruise', 0.4)], labelled)+ expect(glMarkers.map(m => m.el.textContent)).toEqual(['GOA', 'PMI'])+ })+})++describe('ReservationMapboxOverlay waypoint edge cases', () => {+ it('FE-COMP-RESGL-034: a booking without an endpoints array is skipped', () => {+ const map = freshMap()+ attach(map).update([booking({ endpoints: undefined })], opts)+ expect(features(map)).toHaveLength(0)+ expect(glMarkers).toHaveLength(0)+ })++ it('FE-COMP-RESGL-035: waypoints without a sequence keep their array order', () => {+ const map = freshMap()+ attach(map).update([booking({+ type: 'train',+ endpoints: [+ endpoint({ role: 'from', sequence: undefined, name: 'A', lat: 48, lng: 16 }),+ endpoint({ role: 'stop', sequence: undefined, name: 'B', lat: 49.5, lng: 16 }),+ endpoint({ role: 'to', sequence: undefined, name: 'C', lat: 51, lng: 16 }),+ ],+ })], opts)+ const drawn = features(map)+ expect(drawn).toHaveLength(2)+ expect(drawn[0].geometry.coordinates).toEqual([[16, 48], [16, 49.5]])+ expect(drawn[1].geometry.coordinates).toEqual([[16, 49.5], [16, 51]])+ })++ it('FE-COMP-RESGL-036: a leg whose stops share coordinates degrades to a straight segment', () => {+ const map = freshMap()+ attach(map).update([booking({+ endpoints: [+ endpoint({ role: 'from', sequence: 0, name: 'Vienna', code: 'VIE', lat: 48, lng: 16 }),+ endpoint({ role: 'stop', sequence: 1, name: 'Vienna Gate', code: 'VIE', lat: 48, lng: 16 }),+ endpoint({ role: 'to', sequence: 2, name: 'London', code: 'LHR', lat: 51.5, lng: 16 }),+ ],+ })], opts)+ const drawn = features(map)+ expect(drawn).toHaveLength(2)+ expect(drawn[0].geometry.coordinates).toHaveLength(2)+ expect(drawn[1].geometry.coordinates.length).toBeGreaterThan(2)+ })++ it('FE-COMP-RESGL-037: a code-less stop between two coded ends falls back to its name', () => {+ const map = freshMap()+ attach(map, labelled).update([booking({+ type: 'train',+ endpoints: [+ endpoint({ role: 'from', sequence: 0, name: 'Wien', code: 'VIE', lat: 48, lng: 16 }),+ endpoint({ role: 'stop', sequence: 1, name: 'Zuerich HB (Gleis 5)', code: null, lat: 50, lng: 16 }),+ endpoint({ role: 'to', sequence: 2, name: 'London', code: 'LHR', lat: 51.5, lng: 16 }),+ ],+ })], labelled)+ expect(glMarkers.map(m => m.el.textContent)).toEqual(['VIE', 'Zuerich HB', 'LHR'])+ })++ it('FE-COMP-RESGL-038: an endpoint without a name gets an empty marker title', () => {+ const map = freshMap()+ attach(map).update([booking({+ endpoints: [+ endpoint({ role: 'from', sequence: 0, name: '', lat: 48, lng: 16 }),+ endpoint({ role: 'to', sequence: 1, name: 'London', lat: 51.5, lng: 16 }),+ ],+ })], opts)+ expect(glMarkers.map(m => m.el.title)).toEqual(['', 'London'])+ })+})++describe('ReservationMapboxOverlay transit styling', () => {+ const GEOMETRY = '__upzA_gayB_af@_pR_ry@~oR'++ const transit = (legs: Record<string, unknown>[], over: Partial<Reservation> = {}) => booking({+ id: 200,+ type: 'transit' as Reservation['type'],+ endpoints: [+ endpoint({ role: 'from', sequence: 0, name: 'Stop A', lat: 48, lng: 2 }),+ endpoint({ role: 'to', sequence: 1, name: 'Stop B', lat: 48.05, lng: 2 }),+ ],+ metadata: { transit: { legs } },+ ...over,+ } as unknown as Partial<Reservation>)++ it('FE-COMP-RESGL-039: a walking leg is grey and flagged as a walk', () => {+ const map = freshMap()+ attach(map).update([transit([{ geometry: GEOMETRY, mode: 'WALK' }])], opts)+ expect(features(map)[0].properties).toMatchObject({ transitPath: true, walk: true, color: '#64748b' })+ })++ it('FE-COMP-RESGL-040: a leg without a line colour falls back to the transit violet', () => {+ const map = freshMap()+ attach(map).update([transit([{ geometry: GEOMETRY, mode: 'BUS' }])], opts)+ expect(features(map)[0].properties).toMatchObject({ walk: false, color: '#7c3aed' })+ })++ it('FE-COMP-RESGL-041: a transit journey without a status is drawn as pending', () => {+ const map = freshMap()+ attach(map).update([transit([{ geometry: GEOMETRY, mode: 'BUS' }], { status: undefined })], opts)+ expect(features(map)[0].properties.status).toBe('pending')+ })+})++describe('ReservationMapboxOverlay frame handler', () => {+ it('FE-COMP-RESGL-042: a paint frame rotates only — it does not redraw the overlay', () => {+ const map = freshMap()+ const overlay = attach(map)+ overlay.update([booking()], opts)+ const drawsBefore = map._sources.get(RESERVATION_SOURCE_ID)!.setData.mock.calls.length++ map.fire('render')++ expect(map._sources.get(RESERVATION_SOURCE_ID)!.setData.mock.calls).toHaveLength(drawsBefore)+ expect(glMarkers).toHaveLength(2)+ expect(glMarkers.every(m => m.remove.mock.calls.length === 0)).toBe(true)+ })+})diff --git a/client/src/components/Map/usePoiExplore.test.tsx b/client/src/components/Map/usePoiExplore.test.tsxnew file mode 100644index 000000000..741ed9169--- /dev/null+++ b/client/src/components/Map/usePoiExplore.test.tsx@@ -0,0 +1,243 @@+// FE-COMP-POIEXPLORE-001 to FE-COMP-POIEXPLORE-016+import React from 'react'+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { act, renderHook, waitFor } from '@testing-library/react'+import { TranslationProvider } from '../../i18n'+import { mapsApi } from '../../api/client'+import { usePoiExplore, type Bbox } from './usePoiExplore'+import type { Poi } from './poiCategories'++type PoiResponse = Awaited<ReturnType<typeof mapsApi.pois>>++const BBOX: Bbox = { south: 48.1, west: 16.3, north: 48.3, east: 16.4 }++function poi(over: Partial<Poi> = {}): Poi {+ return {+ osm_id: 'node/1',+ name: 'Café Central',+ lat: 48.21,+ lng: 16.36,+ category: 'cafe',+ poi_type: 'cafe',+ address: null,+ website: null,+ phone: null,+ opening_hours: null,+ cuisine: null,+ source: 'openstreetmap',+ ...over,+ }+}++function response(pois: Poi[]): PoiResponse {+ return { pois, source: 'openstreetmap', truncated: false }+}++// Hand-controlled promise so a test can hold a request "in flight" and decide+// exactly when — and in which order — it settles.+function deferred<T>() {+ let resolve!: (value: T) => void+ let reject!: (reason?: unknown) => void+ const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej })+ return { promise, resolve, reject }+}++const wrapper = ({ children }: { children: React.ReactNode }) => (+ <TranslationProvider>{children}</TranslationProvider>+)++function setup() {+ return renderHook(() => usePoiExplore(), { wrapper })+}++const spyOnPois = () => vi.spyOn(mapsApi, 'pois')+let pois: ReturnType<typeof spyOnPois>++beforeEach(() => {+ pois = spyOnPois().mockResolvedValue(response([poi()]))+})++afterEach(() => {+ vi.restoreAllMocks()+})++describe('usePoiExplore', () => {+ it('FE-COMP-POIEXPLORE-001: starts with nothing selected, loaded or failed', () => {+ const { result } = setup()+ expect(result.current.active.size).toBe(0)+ expect(result.current.pois).toEqual([])+ expect(result.current.loadingKeys.size).toBe(0)+ expect(result.current.errorKeys.size).toBe(0)+ expect(result.current.moved).toBe(false)+ })++ it('FE-COMP-POIEXPLORE-002: panning with nothing active does not offer "search this area"', () => {+ const { result } = setup()+ act(() => { result.current.onViewportChange(BBOX) })+ expect(result.current.moved).toBe(false)+ })++ it('FE-COMP-POIEXPLORE-003: toggling before the map reported a viewport selects but does not fetch', () => {+ const { result } = setup()+ act(() => { result.current.toggle('cafe') })+ expect(result.current.active.has('cafe')).toBe(true)+ expect(pois).not.toHaveBeenCalled()+ })++ it('FE-COMP-POIEXPLORE-004: toggling fetches the category for the current viewport', async () => {+ const { result } = setup()+ act(() => { result.current.onViewportChange(BBOX) })+ act(() => { result.current.toggle('cafe') })++ await waitFor(() => expect(result.current.pois).toHaveLength(1))+ expect(pois).toHaveBeenCalledWith('cafe', BBOX, 'en-US', expect.any(AbortSignal))+ expect(result.current.pois[0].osm_id).toBe('node/1')+ })++ it('FE-COMP-POIEXPLORE-005: the spinner is on while the request is in flight and off when it lands', async () => {+ const d = deferred<PoiResponse>()+ pois.mockReturnValue(d.promise)+ const { result } = setup()+ act(() => { result.current.onViewportChange(BBOX) })+ act(() => { result.current.toggle('cafe') })++ expect(result.current.loadingKeys.has('cafe')).toBe(true)++ await act(async () => { d.resolve(response([poi()])) })+ await waitFor(() => expect(result.current.loadingKeys.has('cafe')).toBe(false))+ })++ it('FE-COMP-POIEXPLORE-006: toggling the active category turns it off and drops its markers', async () => {+ const { result } = setup()+ act(() => { result.current.onViewportChange(BBOX) })+ act(() => { result.current.toggle('cafe') })+ await waitFor(() => expect(result.current.pois).toHaveLength(1))++ act(() => { result.current.toggle('cafe') })+ expect(result.current.active.size).toBe(0)+ expect(result.current.pois).toEqual([])+ expect(pois).toHaveBeenCalledTimes(1)+ })++ it('FE-COMP-POIEXPLORE-007: the pill is single-select — a second category replaces the first', async () => {+ const { result } = setup()+ act(() => { result.current.onViewportChange(BBOX) })+ act(() => { result.current.toggle('cafe') })+ await waitFor(() => expect(result.current.pois).toHaveLength(1))++ pois.mockResolvedValue(response([poi({ osm_id: 'node/2', category: 'bar', name: 'Loos Bar' })]))+ act(() => { result.current.toggle('bar') })+ // The previous category's markers vanish immediately, before the new results land.+ expect(result.current.active).toEqual(new Set(['bar']))+ expect(result.current.pois).toEqual([])++ await waitFor(() => expect(result.current.pois).toHaveLength(1))+ expect(result.current.pois[0].osm_id).toBe('node/2')+ })++ it('FE-COMP-POIEXPLORE-008: panning with a category active marks the results stale', async () => {+ const { result } = setup()+ act(() => { result.current.onViewportChange(BBOX) })+ act(() => { result.current.toggle('cafe') })+ await waitFor(() => expect(result.current.pois).toHaveLength(1))+ expect(result.current.moved).toBe(false)++ act(() => { result.current.onViewportChange({ ...BBOX, south: 48.0 }) })+ expect(result.current.moved).toBe(true)+ })++ it('FE-COMP-POIEXPLORE-009: searchArea refetches the active category for the new viewport', async () => {+ const { result } = setup()+ act(() => { result.current.onViewportChange(BBOX) })+ act(() => { result.current.toggle('cafe') })+ await waitFor(() => expect(result.current.pois).toHaveLength(1))++ const moved: Bbox = { south: 40, west: 10, north: 41, east: 11 }+ act(() => { result.current.onViewportChange(moved) })+ act(() => { result.current.searchArea() })++ expect(result.current.moved).toBe(false)+ await waitFor(() => expect(pois).toHaveBeenCalledTimes(2))+ expect(pois).toHaveBeenLastCalledWith('cafe', moved, 'en-US', expect.any(AbortSignal))+ })++ it('FE-COMP-POIEXPLORE-010: searchArea without a viewport is a no-op', () => {+ const { result } = setup()+ act(() => { result.current.searchArea() })+ expect(pois).not.toHaveBeenCalled()+ expect(result.current.moved).toBe(false)+ })++ it('FE-COMP-POIEXPLORE-011: searchArea with nothing active fetches nothing', () => {+ const { result } = setup()+ act(() => { result.current.onViewportChange(BBOX) })+ act(() => { result.current.searchArea() })+ expect(pois).not.toHaveBeenCalled()+ })++ it('FE-COMP-POIEXPLORE-012: a failed fetch surfaces a retryable error instead of a silent empty', async () => {+ pois.mockRejectedValue(new Error('all Overpass mirrors down'))+ const { result } = setup()+ act(() => { result.current.onViewportChange(BBOX) })+ act(() => { result.current.toggle('cafe') })++ await waitFor(() => expect(result.current.errorKeys.has('cafe')).toBe(true))+ expect(result.current.pois).toEqual([])+ expect(result.current.loadingKeys.has('cafe')).toBe(false)+ })++ it('FE-COMP-POIEXPLORE-013: a retry that succeeds clears the error flag', async () => {+ pois.mockRejectedValueOnce(new Error('timeout'))+ const { result } = setup()+ act(() => { result.current.onViewportChange(BBOX) })+ act(() => { result.current.toggle('cafe') })+ await waitFor(() => expect(result.current.errorKeys.has('cafe')).toBe(true))++ act(() => { result.current.searchArea() })+ await waitFor(() => expect(result.current.pois).toHaveLength(1))+ expect(result.current.errorKeys.has('cafe')).toBe(false)+ })++ it('FE-COMP-POIEXPLORE-014: switching category clears a previous error flag', async () => {+ pois.mockRejectedValueOnce(new Error('timeout'))+ const { result } = setup()+ act(() => { result.current.onViewportChange(BBOX) })+ act(() => { result.current.toggle('cafe') })+ await waitFor(() => expect(result.current.errorKeys.has('cafe')).toBe(true))++ act(() => { result.current.toggle('bar') })+ expect(result.current.errorKeys.size).toBe(0)+ await waitFor(() => expect(result.current.pois).toHaveLength(1))+ })++ it('FE-COMP-POIEXPLORE-015: results that land after the category was switched off are dropped', async () => {+ const d = deferred<PoiResponse>()+ pois.mockReturnValue(d.promise)+ const { result } = setup()+ act(() => { result.current.onViewportChange(BBOX) })+ act(() => { result.current.toggle('cafe') })+ act(() => { result.current.toggle('cafe') })+ expect(result.current.active.size).toBe(0)++ await act(async () => { d.resolve(response([poi()])) })+ expect(result.current.pois).toEqual([])+ })++ it('FE-COMP-POIEXPLORE-016: a superseded request is not reported as a failure', async () => {+ const first = deferred<PoiResponse>()+ pois.mockReturnValueOnce(first.promise)+ const { result } = setup()+ act(() => { result.current.onViewportChange(BBOX) })+ act(() => { result.current.toggle('cafe') })++ pois.mockResolvedValue(response([poi({ osm_id: 'node/9', category: 'bar' })]))+ act(() => { result.current.toggle('bar') })++ // The abandoned cafe request rejects with axios' cancellation error.+ await act(async () => { first.reject(Object.assign(new Error('canceled'), { name: 'CanceledError' })) })++ await waitFor(() => expect(result.current.pois).toHaveLength(1))+ expect(result.current.errorKeys.size).toBe(0)+ expect(result.current.pois[0].osm_id).toBe('node/9')+ })+})diff --git a/client/src/components/Packing/ApplyTemplateButton.test.tsx b/client/src/components/Packing/ApplyTemplateButton.test.tsxnew file mode 100644index 000000000..b9d19a316--- /dev/null+++ b/client/src/components/Packing/ApplyTemplateButton.test.tsx@@ -0,0 +1,141 @@+// FE-W4ATB-001 to FE-W4ATB-010+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render'+import { useTripStore } from '../../store/tripStore'++const listTemplates = vi.fn(async (_tripId: number | string) => ({ templates: [] as unknown[] }))+const applyTemplate = vi.fn(async (_tripId: number | string, _id: number, _vis: string) => ({ items: [] as unknown[], count: 0 }))+const toast = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() }++vi.mock('../../api/client', () => ({+ packingApi: {+ listTemplates: (tripId: number | string) => listTemplates(tripId),+ applyTemplate: (tripId: number | string, id: number, vis: string) => applyTemplate(tripId, id, vis),+ },+}))+vi.mock('../shared/Toast', () => ({ useToast: () => toast }))++import ApplyTemplateButton from './ApplyTemplateButton'++const TEMPLATES = [+ { id: 1, name: 'Beach trip', item_count: 12 },+ { id: 2, name: 'City break', item_count: 7 },+]++function renderButton(visibility: 'common' | 'personal' = 'common') {+ return render(<ApplyTemplateButton tripId={4} visibility={visibility} style={{ gap: 6 }} />)+}++beforeEach(() => {+ listTemplates.mockReset()+ listTemplates.mockResolvedValue({ templates: TEMPLATES })+ applyTemplate.mockReset()+ applyTemplate.mockResolvedValue({ items: [], count: 0 })+ Object.values(toast).forEach(f => f.mockClear())+ useTripStore.setState({ packingItems: [] })+})++describe('ApplyTemplateButton', () => {+ it('FE-W4ATB-001: renders nothing while no template exists', async () => {+ listTemplates.mockResolvedValue({ templates: [] })+ const { container } = renderButton()++ await waitFor(() => expect(listTemplates).toHaveBeenCalledWith(4))+ expect(container).toBeEmptyDOMElement()+ })++ it('FE-W4ATB-002: stays hidden when the template list fails to load', async () => {+ listTemplates.mockRejectedValue(new Error('offline'))+ const { container } = renderButton()++ await waitFor(() => expect(listTemplates).toHaveBeenCalled())+ expect(container).toBeEmptyDOMElement()+ })++ it('FE-W4ATB-003: tolerates a response without a templates array', async () => {+ listTemplates.mockResolvedValue({} as { templates: unknown[] })+ const { container } = renderButton()++ await waitFor(() => expect(listTemplates).toHaveBeenCalled())+ expect(container).toBeEmptyDOMElement()+ })++ it('FE-W4ATB-004: shows the trigger once templates arrive', async () => {+ renderButton()++ expect(await screen.findByRole('button')).toHaveTextContent(/apply template/i)+ })++ it('FE-W4ATB-005: the trigger toggles the template menu', async () => {+ renderButton()+ const trigger = await screen.findByRole('button')++ fireEvent.click(trigger)+ expect(screen.getByText('Beach trip')).toBeInTheDocument()+ expect(screen.getByText(/^12 /)).toBeInTheDocument()++ fireEvent.click(trigger)+ expect(screen.queryByText('Beach trip')).toBeNull()+ })++ it('FE-W4ATB-006: a mousedown outside closes the menu', async () => {+ renderButton()+ fireEvent.click(await screen.findByRole('button'))+ expect(screen.getByText('City break')).toBeInTheDocument()++ fireEvent.mouseDown(document.body)+ expect(screen.queryByText('City break')).toBeNull()+ })++ it('FE-W4ATB-007: a mousedown inside keeps the menu open', async () => {+ renderButton()+ fireEvent.click(await screen.findByRole('button'))++ fireEvent.mouseDown(screen.getByText('Beach trip'))++ expect(screen.getByText('Beach trip')).toBeInTheDocument()+ })++ it('FE-W4ATB-008: applying a template appends its items to the trip store', async () => {+ applyTemplate.mockResolvedValue({ items: [{ id: 90 }, { id: 91 }], count: 2 })+ useTripStore.setState({ packingItems: [{ id: 1 }] as never })+ renderButton('personal')++ fireEvent.click(await screen.findByRole('button'))+ fireEvent.click(screen.getByText('Beach trip'))++ await waitFor(() => expect(toast.success).toHaveBeenCalledWith(expect.stringContaining('2')))+ expect(applyTemplate).toHaveBeenCalledWith(4, 1, 'personal')+ expect(useTripStore.getState().packingItems.map(i => i.id)).toEqual([1, 90, 91])+ expect(screen.queryByText('Beach trip')).toBeNull()+ })++ it('FE-W4ATB-009: tolerates a response without an items array', async () => {+ applyTemplate.mockResolvedValue({ count: 0 } as { items: unknown[]; count: number })+ renderButton()++ fireEvent.click(await screen.findByRole('button'))+ fireEvent.click(screen.getByText('City break'))++ await waitFor(() => expect(toast.success).toHaveBeenCalled())+ expect(useTripStore.getState().packingItems).toEqual([])+ })++ it('FE-W4ATB-010: a failing apply toasts an error and keeps the menu open', async () => {+ applyTemplate.mockRejectedValue(new Error('500'))+ renderButton()++ fireEvent.click(await screen.findByRole('button'))+ fireEvent.click(screen.getByText('Beach trip'))++ await waitFor(() => expect(toast.error).toHaveBeenCalled())+ expect(toast.success).not.toHaveBeenCalled()+ expect(screen.getByText('Beach trip')).toBeInTheDocument()+ })++ it('FE-W4ATB-011: honours a caller className on the trigger', async () => {+ render(<ApplyTemplateButton tripId={4} visibility="common" style={{}} className="btn-ghost" />)++ expect(await screen.findByRole('button')).toHaveClass('btn-ghost')+ })+})diff --git a/client/src/components/Packing/PackingListPanelCategoryGroup.test.tsx b/client/src/components/Packing/PackingListPanelCategoryGroup.test.tsxnew file mode 100644index 000000000..e42d79915--- /dev/null+++ b/client/src/components/Packing/PackingListPanelCategoryGroup.test.tsx@@ -0,0 +1,602 @@+// FE-W5CAT-001 to FE-W5CAT-034+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import type { ComponentProps } from 'react'+import { http, HttpResponse } from 'msw'+import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render'+import { server } from '../../../tests/helpers/msw/server'+import { resetAllStores, seedStore } from '../../../tests/helpers/store'+import { buildUser, buildTrip, buildPackingItem } from '../../../tests/helpers/factories'+import { useAuthStore } from '../../store/authStore'+import { useTripStore } from '../../store/tripStore'+import { KategorieGruppe } from './PackingListPanelCategoryGroup'+import type { TripMember } from './usePackingListPanel'++type Props = ComponentProps<typeof KategorieGruppe>++const toastSpy = vi.fn((_message: string, _type?: string, _duration?: number) => 0)++const MEMBERS = [+ { id: 1, username: 'owner' },+ { id: 2, username: 'alice', is_guest: true },+] as unknown as TripMember[]++/** A dataTransfer stand-in — jsdom drag events carry none of their own. */+const dt = () => ({ effectAllowed: '', dropEffect: '', setData: vi.fn(), getData: vi.fn(() => '') })++function setup(overrides: Partial<Props> = {}) {+ const items = overrides.items ?? [buildPackingItem({ id: 1, name: 'Tent', category: 'Gear' })]+ const props: Props = {+ kategorie: 'Gear',+ items,+ tripId: 1,+ allCategories: ['Gear', 'Docs'],+ onRename: vi.fn(async () => {}),+ onDeleteAll: vi.fn(async () => {}),+ onDeleteItem: vi.fn(async () => {}),+ onAddItem: vi.fn(async () => {}),+ assignees: [],+ tripMembers: [],+ onSetAssignees: vi.fn(async () => {}),+ onCreateBag: vi.fn(async () => undefined),+ allItems: items,+ onReorder: vi.fn((_ids: number[]) => {}),+ ...overrides,+ }+ const utils = render(<KategorieGruppe {...props} />)+ return { ...utils, props }+}++/** The category header owns the first MoreHorizontal; item rows render their own. */+function openCategoryMenu(container: HTMLElement) {+ const btn = container.querySelectorAll('svg.lucide-more-horizontal')[0].closest('button')!+ fireEvent.click(btn)+ return btn+}++function rows(container: HTMLElement) {+ return Array.from(container.querySelectorAll<HTMLElement>('.packing-item-row'))+}++function grip(row: HTMLElement) {+ return row.querySelector<HTMLElement>('div[draggable="true"]')!+}++beforeEach(() => {+ resetAllStores()+ toastSpy.mockClear()+ window.__addToast = toastSpy+ server.use(+ http.get('/api/view-contributions/:view/:tripId', () => HttpResponse.json({ contributions: [] })),+ )+ seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true })+ seedStore(useTripStore, { trip: buildTrip({ id: 1 }) })+})++afterEach(() => {+ delete window.__addToast+ vi.restoreAllMocks()+})++describe('KategorieGruppe — header', () => {+ it('FE-W5CAT-001: shows the category name and its packed count', () => {+ setup({+ items: [+ buildPackingItem({ id: 1, name: 'Tent', checked: 1 }),+ buildPackingItem({ id: 2, name: 'Rope', checked: 0 }),+ ],+ })++ expect(screen.getByText('Gear')).toBeInTheDocument()+ expect(screen.getByText('1/2')).toBeInTheDocument()+ })++ it('FE-W5CAT-002: a fully packed category marks its badge green', () => {+ setup({ items: [buildPackingItem({ id: 1, name: 'Tent', checked: 1 })] })++ expect(screen.getByText('1/1')).toHaveStyle({ color: '#16a34a' })+ })++ it('FE-W5CAT-003: the chevron collapses and re-expands the item list', () => {+ const { container } = setup()+ const toggle = container.querySelector('svg.lucide-chevron-down')!.closest('button')!++ fireEvent.click(toggle)+ expect(screen.queryByText('Tent')).not.toBeInTheDocument()++ fireEvent.click(container.querySelector('svg.lucide-chevron-right')!.closest('button')!)+ expect(screen.getByText('Tent')).toBeInTheDocument()+ })+})++describe('KategorieGruppe — rename', () => {+ it('FE-W5CAT-004: renaming through the menu reports the new name', async () => {+ const onRename = vi.fn(async () => {})+ const { container } = setup({ onRename })+ openCategoryMenu(container)+ fireEvent.click(screen.getByText('Rename'))++ const input = screen.getByDisplayValue('Gear')+ fireEvent.change(input, { target: { value: 'Camping' } })+ fireEvent.keyDown(input, { key: 'Enter' })++ await waitFor(() => expect(onRename).toHaveBeenCalledWith('Gear', 'Camping'))+ })++ it('FE-W5CAT-005: an unchanged name closes the editor without a request', async () => {+ const onRename = vi.fn(async () => {})+ const { container } = setup({ onRename })+ openCategoryMenu(container)+ fireEvent.click(screen.getByText('Rename'))++ fireEvent.blur(screen.getByDisplayValue('Gear'))++ await waitFor(() => expect(screen.queryByDisplayValue('Gear')).toBeNull())+ expect(onRename).not.toHaveBeenCalled()+ })++ it('FE-W5CAT-006: an emptied name is discarded', async () => {+ const onRename = vi.fn(async () => {})+ const { container } = setup({ onRename })+ openCategoryMenu(container)+ fireEvent.click(screen.getByText('Rename'))++ const input = screen.getByDisplayValue('Gear')+ fireEvent.change(input, { target: { value: ' ' } })+ fireEvent.blur(input)++ // The editor closes and the original name is restored as plain text.+ await waitFor(() => expect(screen.queryByDisplayValue('Gear')).toBeNull())+ expect(screen.getByText('Gear')).toBeInTheDocument()+ expect(onRename).not.toHaveBeenCalled()+ })++ it('FE-W5CAT-007: Escape restores the original name', () => {+ const { container } = setup()+ openCategoryMenu(container)+ fireEvent.click(screen.getByText('Rename'))++ const input = screen.getByDisplayValue('Gear')+ fireEvent.change(input, { target: { value: 'Camping' } })+ fireEvent.keyDown(input, { key: 'Escape' })++ expect(screen.queryByDisplayValue('Camping')).toBeNull()+ expect(screen.getByText('Gear')).toBeInTheDocument()+ })++ it('FE-W5CAT-008: a failing rename surfaces a rename error', async () => {+ const onRename = vi.fn(async () => { throw new Error('nope') })+ const { container } = setup({ onRename })+ openCategoryMenu(container)+ fireEvent.click(screen.getByText('Rename'))++ const input = screen.getByDisplayValue('Gear')+ fireEvent.change(input, { target: { value: 'Camping' } })+ fireEvent.keyDown(input, { key: 'Enter' })++ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to rename', 'error', undefined))+ })++ it('FE-W5CAT-009: a read-only category offers no rename entry', () => {+ const { container } = setup({ canEdit: false })+ openCategoryMenu(container)++ expect(screen.queryByText('Rename')).toBeNull()+ expect(screen.queryByText('Delete List')).toBeNull()+ expect(screen.getByText('Check All')).toBeInTheDocument()+ })+})++describe('KategorieGruppe — bulk actions', () => {+ it('FE-W5CAT-010: Check All only touches the unchecked items', async () => {+ const puts: number[] = []+ server.use(+ http.put('/api/trips/1/packing/:itemId', ({ params }) => {+ puts.push(Number(params.itemId))+ return HttpResponse.json({ item: buildPackingItem({ id: Number(params.itemId) }) })+ }),+ )+ const { container } = setup({+ items: [+ buildPackingItem({ id: 1, name: 'Tent', checked: 1 }),+ buildPackingItem({ id: 2, name: 'Rope', checked: 0 }),+ ],+ })+ openCategoryMenu(container)++ fireEvent.click(screen.getByText('Check All'))++ await waitFor(() => expect(puts).toEqual([2]))+ })++ it('FE-W5CAT-011: Uncheck All only touches the checked items', async () => {+ const puts: number[] = []+ server.use(+ http.put('/api/trips/1/packing/:itemId', ({ params }) => {+ puts.push(Number(params.itemId))+ return HttpResponse.json({ item: buildPackingItem({ id: Number(params.itemId) }) })+ }),+ )+ const { container } = setup({+ items: [+ buildPackingItem({ id: 1, name: 'Tent', checked: 1 }),+ buildPackingItem({ id: 2, name: 'Rope', checked: 0 }),+ ],+ })+ openCategoryMenu(container)++ fireEvent.click(screen.getByText('Uncheck All'))++ await waitFor(() => expect(puts).toEqual([1]))+ })++ it('FE-W5CAT-012: a throwing toggle during Check All surfaces a save error', async () => {+ useTripStore.setState({ togglePackingItem: async () => { throw new Error('offline') } })+ const { container } = setup({ items: [buildPackingItem({ id: 1, name: 'Tent', checked: 0 })] })+ openCategoryMenu(container)++ fireEvent.click(screen.getByText('Check All'))++ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined))+ })++ it('FE-W5CAT-013: a throwing toggle during Uncheck All surfaces a save error', async () => {+ useTripStore.setState({ togglePackingItem: async () => { throw new Error('offline') } })+ const { container } = setup({ items: [buildPackingItem({ id: 1, name: 'Tent', checked: 1 })] })+ openCategoryMenu(container)++ fireEvent.click(screen.getByText('Uncheck All'))++ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined))+ })++ it('FE-W5CAT-014: Delete List hands the whole category to the panel and closes the menu', async () => {+ const onDeleteAll = vi.fn(async () => {})+ const items = [buildPackingItem({ id: 1, name: 'Tent' })]+ const { container } = setup({ items, onDeleteAll })+ openCategoryMenu(container)++ fireEvent.click(screen.getByText('Delete List'))++ await waitFor(() => expect(onDeleteAll).toHaveBeenCalledWith(items))+ expect(screen.queryByText('Delete List')).toBeNull()+ })++ it('FE-W5CAT-015: the scrim closes the category menu', () => {+ const { container, baseElement } = setup()+ openCategoryMenu(container)++ fireEvent.click(baseElement.querySelector('div[style*="z-index: 99"]')!)++ expect(screen.queryByText('Check All')).toBeNull()+ })++ it('FE-W5CAT-015a: the menu trigger highlights on hover', () => {+ const { container } = setup()+ const trigger = container.querySelectorAll('svg.lucide-more-horizontal')[0].closest('button')!++ fireEvent.mouseEnter(trigger)+ expect(trigger.style.color).toBe('var(--text-secondary)')+ fireEvent.mouseLeave(trigger)+ expect(trigger.style.color).toBe('var(--text-faint)')+ })++ it('FE-W5CAT-016: a menu entry highlights on hover and resets on leave', () => {+ const { container } = setup()+ openCategoryMenu(container)+ const checkAll = screen.getByText('Check All').closest('button')!+ const deleteAll = screen.getByText('Delete List').closest('button')!++ fireEvent.mouseEnter(checkAll)+ expect(checkAll.style.background).toBe('var(--bg-tertiary)')+ fireEvent.mouseLeave(checkAll)+ expect(checkAll.style.background).toBe('none')++ fireEvent.mouseEnter(deleteAll)+ expect(deleteAll.style.background).toBe('rgb(254, 242, 242)')+ })+})++describe('KategorieGruppe — assignees', () => {+ it('FE-W5CAT-017: the dropdown lists every member and flags guests', () => {+ const { container } = setup({ tripMembers: MEMBERS })+ fireEvent.click(container.querySelector('svg.lucide-user-plus')!.closest('button')!)++ expect(screen.getByText('owner')).toBeInTheDocument()+ expect(screen.getByText('alice')).toBeInTheDocument()+ expect(screen.getByText('Guest')).toBeInTheDocument()+ })++ it('FE-W5CAT-018: an empty trip shows the no-members hint', () => {+ const { container } = setup({ tripMembers: [] })+ fireEvent.click(container.querySelector('svg.lucide-user-plus')!.closest('button')!)++ expect(screen.getByText('No trip members')).toBeInTheDocument()+ })++ it('FE-W5CAT-019: picking an unassigned member adds them', () => {+ const onSetAssignees = vi.fn(async () => {})+ const { container } = setup({ tripMembers: MEMBERS, onSetAssignees })+ fireEvent.click(container.querySelector('svg.lucide-user-plus')!.closest('button')!)++ fireEvent.click(screen.getByText('alice').closest('button')!)++ expect(onSetAssignees).toHaveBeenCalledWith('Gear', [2])+ })++ it('FE-W5CAT-019a: adding a member keeps the ones already assigned', () => {+ const onSetAssignees = vi.fn(async () => {})+ const { container } = setup({+ tripMembers: MEMBERS,+ assignees: [{ user_id: 1, username: 'owner' }],+ onSetAssignees,+ })+ fireEvent.click(container.querySelector('svg.lucide-user-plus')!.closest('button')!)++ fireEvent.click(screen.getByRole('button', { name: /alice/ }))++ expect(onSetAssignees).toHaveBeenCalledWith('Gear', [1, 2])+ })++ it('FE-W5CAT-020: picking an assigned member removes them again', () => {+ const onSetAssignees = vi.fn(async () => {})+ const { container } = setup({+ tripMembers: MEMBERS,+ assignees: [{ user_id: 2, username: 'alice' }, { user_id: 1, username: 'owner' }],+ onSetAssignees,+ })+ fireEvent.click(container.querySelector('svg.lucide-user-plus')!.closest('button')!)++ fireEvent.click(within(screen.getByRole('button', { name: /alice/ })).getByText('alice').closest('button')!)++ expect(onSetAssignees).toHaveBeenCalledWith('Gear', [1])+ })++ it('FE-W5CAT-021: only the unassigned rows react to hover', () => {+ const { container } = setup({+ tripMembers: MEMBERS,+ assignees: [{ user_id: 1, username: 'owner' }],+ })+ fireEvent.click(container.querySelector('svg.lucide-user-plus')!.closest('button')!)+ const assigned = screen.getByRole('button', { name: /owner/ })+ const free = screen.getByRole('button', { name: /alice/ })++ fireEvent.mouseEnter(free)+ expect(free.style.background).toBe('var(--bg-tertiary)')+ fireEvent.mouseLeave(free)+ expect(free.style.background).toBe('transparent')++ fireEvent.mouseEnter(assigned)+ fireEvent.mouseLeave(assigned)+ expect(assigned.style.background).toBe('var(--bg-hover)')+ })++ it('FE-W5CAT-022: the add-assignee button highlights on hover', () => {+ const { container } = setup({ tripMembers: MEMBERS })+ const btn = container.querySelector('svg.lucide-user-plus')!.closest('button')!++ fireEvent.mouseEnter(btn)+ expect(btn.style.color).toBe('var(--text-muted)')+ fireEvent.mouseLeave(btn)+ expect(btn.style.color).toBe('var(--text-faint)')+ })++ it('FE-W5CAT-023: a mousedown outside closes the assignee dropdown', () => {+ const { container } = setup({ tripMembers: MEMBERS })+ fireEvent.click(container.querySelector('svg.lucide-user-plus')!.closest('button')!)+ expect(screen.getByText('alice')).toBeInTheDocument()++ fireEvent.mouseDown(document.body)++ expect(screen.queryByText('alice')).toBeNull()+ })++ it('FE-W5CAT-023a: a mousedown inside the assignee dropdown keeps it open', () => {+ const { container } = setup({ tripMembers: MEMBERS })+ fireEvent.click(container.querySelector('svg.lucide-user-plus')!.closest('button')!)++ fireEvent.mouseDown(screen.getByText('alice'))++ expect(screen.getByText('alice')).toBeInTheDocument()+ })++ it('FE-W5CAT-024: clicking an assignee chip drops that member', () => {+ const onSetAssignees = vi.fn(async () => {})+ const { container } = setup({+ assignees: [{ user_id: 2, username: 'alice' }, { user_id: 1, username: 'owner' }],+ onSetAssignees,+ })++ fireEvent.click(container.querySelector('.assignee-chip')!.parentElement!)++ expect(onSetAssignees).toHaveBeenCalledWith('Gear', [1])+ })++ it('FE-W5CAT-025: a read-only category ignores chip clicks and hides the add button', () => {+ const onSetAssignees = vi.fn(async () => {})+ const { container } = setup({+ canEdit: false,+ assignees: [{ user_id: 2, username: 'alice' }],+ onSetAssignees,+ })++ fireEvent.click(container.querySelector('.assignee-chip')!.parentElement!)++ expect(onSetAssignees).not.toHaveBeenCalled()+ expect(container.querySelector('svg.lucide-user-plus')).toBeNull()+ })+})++describe('KategorieGruppe — inline add item', () => {+ it('FE-W5CAT-026: Enter adds the typed item and clears the field', () => {+ const onAddItem = vi.fn(async () => {})+ setup({ onAddItem })+ fireEvent.click(screen.getByText('Add item'))++ const input = screen.getByPlaceholderText('Item name...')+ fireEvent.change(input, { target: { value: 'Rope' } })+ fireEvent.keyDown(input, { key: 'Enter' })++ expect(onAddItem).toHaveBeenCalledWith('Gear', 'Rope')+ expect(input).toHaveValue('')+ })++ it('FE-W5CAT-027: Enter on an empty field adds nothing', () => {+ const onAddItem = vi.fn(async () => {})+ setup({ onAddItem })+ fireEvent.click(screen.getByText('Add item'))++ fireEvent.keyDown(screen.getByPlaceholderText('Item name...'), { key: 'Enter' })++ expect(onAddItem).not.toHaveBeenCalled()+ })++ it('FE-W5CAT-028: the confirm button adds the item, and stays inert while empty', () => {+ const onAddItem = vi.fn(async () => {})+ const { container } = setup({ onAddItem })+ fireEvent.click(screen.getByText('Add item'))+ const confirm = container.querySelector('svg.lucide-plus')!.closest('button')!++ fireEvent.click(confirm)+ expect(onAddItem).not.toHaveBeenCalled()++ fireEvent.change(screen.getByPlaceholderText('Item name...'), { target: { value: 'Rope' } })+ fireEvent.click(confirm)+ expect(onAddItem).toHaveBeenCalledWith('Gear', 'Rope')+ })++ it('FE-W5CAT-029: Escape closes the inline form', () => {+ setup()+ fireEvent.click(screen.getByText('Add item'))++ fireEvent.keyDown(screen.getByPlaceholderText('Item name...'), { key: 'Escape' })++ expect(screen.queryByPlaceholderText('Item name...')).toBeNull()+ })++ it('FE-W5CAT-030: the X button closes the inline form', () => {+ const { container } = setup()+ fireEvent.click(screen.getByText('Add item'))+ fireEvent.change(screen.getByPlaceholderText('Item name...'), { target: { value: 'Rope' } })++ fireEvent.click(container.querySelector('svg.lucide-x')!.closest('button')!)++ expect(screen.queryByPlaceholderText('Item name...')).toBeNull()+ })++ it('FE-W5CAT-031: the add-item trigger highlights on hover', () => {+ setup()+ const trigger = screen.getByText('Add item').closest('button')!++ fireEvent.mouseEnter(trigger)+ expect(trigger.style.color).toBe('var(--text-secondary)')+ fireEvent.mouseLeave(trigger)+ expect(trigger.style.color).toBe('var(--text-faint)')+ })++ it('FE-W5CAT-032: a read-only category hides the add-item affordance', () => {+ setup({ canEdit: false })++ expect(screen.queryByText('Add item')).toBeNull()+ })+})++describe('KategorieGruppe — drag to reorder', () => {+ const items = [+ buildPackingItem({ id: 1, name: 'Tent' }),+ buildPackingItem({ id: 2, name: 'Rope' }),+ buildPackingItem({ id: 3, name: 'Stove' }),+ ]+ // The order is global: another category's item sits between ours.+ const allItems = [items[0], buildPackingItem({ id: 9, name: 'Passport', category: 'Docs' }), items[1], items[2]]++ it('FE-W5CAT-033: dropping an item onto a later sibling reorders only this category', () => {+ const onReorder = vi.fn((_ids: number[]) => {})+ const { container } = setup({ items, allItems, onReorder })+ const row = rows(container)++ fireEvent.dragStart(grip(row[0]), { dataTransfer: dt() })+ fireEvent.dragOver(row[2], { dataTransfer: dt() })+ fireEvent.drop(row[2], { dataTransfer: dt() })++ expect(onReorder).toHaveBeenCalledWith([2, 9, 3, 1])+ })++ it('FE-W5CAT-034: a drop without a drag source is ignored', () => {+ const onReorder = vi.fn((_ids: number[]) => {})+ const { container } = setup({ items, allItems, onReorder })++ fireEvent.drop(rows(container)[1], { dataTransfer: dt() })++ expect(onReorder).not.toHaveBeenCalled()+ })++ it('FE-W5CAT-035: dropping an item onto itself is ignored', () => {+ const onReorder = vi.fn((_ids: number[]) => {})+ const { container } = setup({ items, allItems, onReorder })+ const row = rows(container)++ fireEvent.dragStart(grip(row[1]), { dataTransfer: dt() })+ fireEvent.drop(row[1], { dataTransfer: dt() })++ expect(onReorder).not.toHaveBeenCalled()+ })++ it('FE-W5CAT-036: a drop whose source has left the category is ignored', () => {+ const onReorder = vi.fn((_ids: number[]) => {})+ const { container, rerender, props } = setup({ items, allItems, onReorder })++ fireEvent.dragStart(grip(rows(container)[0]), { dataTransfer: dt() })+ // The dragged row disappears mid-drag (another client removed it).+ const shorter = [items[1], items[2]]+ rerender(<KategorieGruppe {...props} items={shorter} allItems={shorter} />)+ fireEvent.drop(rows(container)[0], { dataTransfer: dt() })++ expect(onReorder).not.toHaveBeenCalled()+ })++ it('FE-W5CAT-037: dragging marks the source faint and the hovered target with an edge', () => {+ const { container } = setup({ items, allItems })+ const row = rows(container)++ fireEvent.dragStart(grip(row[0]), { dataTransfer: dt() })+ fireEvent.dragOver(row[1], { dataTransfer: dt() })++ expect(row[0].style.opacity).toBe('0.4')+ expect(row[1].style.boxShadow).toBe('inset 3px 0 0 0 var(--accent)')+ })++ it('FE-W5CAT-038: ending a drag clears both markers', () => {+ const { container } = setup({ items, allItems })+ const row = rows(container)++ fireEvent.dragStart(grip(row[0]), { dataTransfer: dt() })+ fireEvent.dragOver(row[1], { dataTransfer: dt() })+ fireEvent.dragEnd(grip(row[0]))++ expect(row[0].style.opacity).toBe('1')+ expect(row[1].style.boxShadow).toBe('none')+ })++ it('FE-W5CAT-039: a read-only category renders no drag handles', () => {+ const { container } = setup({ items, allItems, canEdit: false })++ expect(container.querySelector('div[draggable="true"]')).toBeNull()+ })+})++describe('KategorieGruppe — plugin contributions', () => {+ it('FE-W5CAT-040: a plugin column is rendered below its item row', async () => {+ server.use(+ http.get('/api/view-contributions/:view/:tripId', () =>+ HttpResponse.json({+ contributions: [+ { kind: 'column', pluginId: 'weather', entityId: 1, id: 'c1', label: 'Forecast', value: 'Sunny', tone: 'default' },+ ],+ })),+ )+ setup({ items: [buildPackingItem({ id: 1, name: 'Tent' })] })++ expect(await screen.findByText('Sunny')).toBeInTheDocument()+ expect(screen.getByText('Forecast')).toBeInTheDocument()+ })+})diff --git a/client/src/components/Packing/PackingListPanelItemRow.test.tsx b/client/src/components/Packing/PackingListPanelItemRow.test.tsxnew file mode 100644index 000000000..7c695e601--- /dev/null+++ b/client/src/components/Packing/PackingListPanelItemRow.test.tsx@@ -0,0 +1,867 @@+// FE-W5ROW-001 to FE-W5ROW-055+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import type { ComponentProps } from 'react'+import { http, HttpResponse } from 'msw'+import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render'+import { server } from '../../../tests/helpers/msw/server'+import { resetAllStores, seedStore } from '../../../tests/helpers/store'+import { buildUser, buildTrip, buildPackingItem } from '../../../tests/helpers/factories'+import { useAuthStore } from '../../store/authStore'+import { useTripStore } from '../../store/tripStore'+import { ArtikelZeile } from './PackingListPanelItemRow'+import type { PackingBag, PackingItem } from '../../types'+import type { TripMember } from './usePackingListPanel'++type Props = ComponentProps<typeof ArtikelZeile>++const toastSpy = vi.fn((_message: string, _type?: string, _duration?: number) => 0)++const BAGS = [+ { id: 7, name: 'Carry-on', color: '#10b981' },+ { id: 8, name: 'Trolley', color: '#ec4899' },+] as unknown as PackingBag[]++const MEMBERS = [+ { id: 1, username: 'owner' },+ { id: 2, username: 'alice' },+] as unknown as TripMember[]++const dt = () => ({ effectAllowed: '', dropEffect: '', setData: vi.fn(), getData: vi.fn(() => '') })++function setup(overrides: Partial<Props> = {}) {+ const props: Props = {+ item: buildPackingItem({ id: 1, name: 'Tent', category: 'Gear' }),+ tripId: 1,+ categories: ['Gear', 'Docs'],+ onCategoryChange: () => {},+ onCreateBag: vi.fn(async () => undefined),+ ...overrides,+ }+ const utils = render(<ArtikelZeile {...props} />)+ return { ...utils, props }+}++/** The row's own overflow menu trigger (rendered but display:none on desktop). */+function overflowTrigger(container: HTMLElement) {+ return container.querySelector<HTMLButtonElement>('.packing-row-overflow button')!+}++/**+ * The overflow menu lives inside a display:none wrapper (it only shows on narrow+ * viewports), so every query against it has to opt into hidden elements.+ */+function menu(container: HTMLElement) {+ return within(container.querySelector<HTMLElement>('.trek-menu-enter')!)+}++function menuButton(container: HTMLElement, name: string) {+ return menu(container).getByRole('button', { name, hidden: true })+}++function fieldOf(container: HTMLElement, label: string) {+ return within(menu(container).getByText(label).parentElement!).getByRole('textbox', { hidden: true })+}++function bagButton(container: HTMLElement) {+ // The bag picker trigger is the round button right after the weight field.+ return container.querySelectorAll<HTMLButtonElement>('button[style*="border-radius: 50%"]')[0]+}++beforeEach(() => {+ resetAllStores()+ toastSpy.mockClear()+ window.__addToast = toastSpy+ seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true })+ seedStore(useTripStore, { trip: buildTrip({ id: 1 }) })+})++afterEach(() => {+ delete window.__addToast+ vi.restoreAllMocks()+})++describe('ArtikelZeile — basics', () => {+ it('FE-W5ROW-001: renders the name and checks the item off', async () => {+ let body: Record<string, unknown> | null = null+ server.use(+ http.put('/api/trips/1/packing/1', async ({ request }) => {+ body = (await request.json()) as Record<string, unknown>+ return HttpResponse.json({ item: buildPackingItem({ id: 1, checked: 1 }) })+ }),+ )+ const { container } = setup()++ expect(screen.getByText('Tent')).toBeInTheDocument()+ fireEvent.click(container.querySelector('svg.lucide-square')!.closest('button')!)++ await waitFor(() => expect(body).toMatchObject({ checked: true }))+ })++ it('FE-W5ROW-002: a checked item is struck through and not editable by click', () => {+ setup({ item: buildPackingItem({ id: 1, name: 'Tent', checked: 1 }) })+ const label = screen.getByText('Tent')++ expect(label).toHaveStyle({ textDecoration: 'line-through' })+ fireEvent.click(label)++ expect(screen.queryByDisplayValue('Tent')).toBeNull()+ })++ it('FE-W5ROW-003: the placeholder row edits from an empty field', () => {+ setup({ item: buildPackingItem({ id: 1, name: '...', category: 'Gear' }) })++ fireEvent.click(screen.getByText('...'))++ const input = screen.getByPlaceholderText('...')+ expect(input).toHaveValue('')+ })++ it('FE-W5ROW-004: a read-only row hides the quantity field and the action buttons', () => {+ const { container } = setup({ canEdit: false })++ expect(screen.queryByTitle('Rename')).toBeNull()+ expect(screen.queryByTitle('Delete')).toBeNull()+ expect(container.querySelector('.packing-row-overflow')).toBeNull()+ fireEvent.click(screen.getByText('Tent'))+ expect(screen.queryByDisplayValue('Tent')).toBeNull()+ })++ it('FE-W5ROW-005: hovering the row lifts its background and dismisses open pickers', () => {+ const { container } = setup()+ const row = container.querySelector<HTMLElement>('.packing-item-row')!++ fireEvent.mouseEnter(row)+ expect(row.style.background).toBe('var(--bg-secondary)')++ fireEvent.click(screen.getByTitle('Move to List'))+ expect(screen.getByRole('button', { name: 'Docs' })).toBeInTheDocument()++ fireEvent.mouseLeave(row)+ expect(row.style.background).toBe('transparent')+ expect(screen.queryByRole('button', { name: 'Docs' })).toBeNull()+ })+})++describe('ArtikelZeile — renaming', () => {+ it('FE-W5ROW-006: Enter commits the new name', async () => {+ let body: Record<string, unknown> | null = null+ server.use(+ http.put('/api/trips/1/packing/1', async ({ request }) => {+ body = (await request.json()) as Record<string, unknown>+ return HttpResponse.json({ item: buildPackingItem({ id: 1, name: 'Tarp' }) })+ }),+ )+ setup()+ fireEvent.click(screen.getByTitle('Rename'))++ const input = screen.getByDisplayValue('Tent')+ fireEvent.change(input, { target: { value: ' Tarp ' } })+ fireEvent.keyDown(input, { key: 'Enter' })++ await waitFor(() => expect(body).toMatchObject({ name: 'Tarp' }))+ })++ it('FE-W5ROW-007: blurring an emptied field restores the old name', async () => {+ let called = false+ server.use(http.put('/api/trips/1/packing/1', () => { called = true; return HttpResponse.json({ item: buildPackingItem() }) }))+ setup()+ fireEvent.click(screen.getByTitle('Rename'))++ const input = screen.getByDisplayValue('Tent')+ fireEvent.change(input, { target: { value: ' ' } })+ fireEvent.blur(input)++ await waitFor(() => expect(screen.queryByDisplayValue('Tent')).toBeNull())+ expect(screen.getByText('Tent')).toBeInTheDocument()+ expect(called).toBe(false)+ })++ it('FE-W5ROW-008: Escape discards the edit', () => {+ setup()+ fireEvent.click(screen.getByText('Tent'))++ const input = screen.getByDisplayValue('Tent')+ fireEvent.change(input, { target: { value: 'Tarp' } })+ fireEvent.keyDown(input, { key: 'Escape' })++ expect(screen.queryByDisplayValue('Tarp')).toBeNull()+ expect(screen.getByText('Tent')).toBeInTheDocument()+ })++ it('FE-W5ROW-009: a failing rename surfaces a save error', async () => {+ server.use(http.put('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 })))+ setup()+ fireEvent.click(screen.getByTitle('Rename'))++ fireEvent.change(screen.getByDisplayValue('Tent'), { target: { value: 'Tarp' } })+ fireEvent.keyDown(screen.getByDisplayValue('Tarp'), { key: 'Enter' })++ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined))+ })+})++describe('ArtikelZeile — deleting', () => {+ it('FE-W5ROW-010: the panel handler takes over when provided', async () => {+ const onDelete = vi.fn(async () => {})+ const { props } = setup({ onDelete })++ fireEvent.click(screen.getByTitle('Delete'))++ await waitFor(() => expect(onDelete).toHaveBeenCalledWith(props.item))+ })++ it('FE-W5ROW-011: a standalone row deletes through the store', async () => {+ let deleted = false+ server.use(http.delete('/api/trips/1/packing/1', () => { deleted = true; return HttpResponse.json({ success: true }) }))+ setup()++ fireEvent.click(screen.getByTitle('Delete'))++ await waitFor(() => expect(deleted).toBe(true))+ })++ it('FE-W5ROW-012: a failing standalone delete surfaces a delete error', async () => {+ server.use(http.delete('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 })))+ setup()++ fireEvent.click(screen.getByTitle('Delete'))++ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to delete', 'error', undefined))+ })++ it('FE-W5ROW-013: the rename and delete buttons highlight on hover', () => {+ setup()+ const rename = screen.getByTitle('Rename')+ const remove = screen.getByTitle('Delete')++ fireEvent.mouseEnter(rename)+ expect(rename.style.color).toBe('var(--text-secondary)')+ fireEvent.mouseLeave(rename)+ expect(rename.style.color).toBe('var(--text-faint)')++ fireEvent.mouseEnter(remove)+ expect(remove.style.color).toBe('rgb(239, 68, 68)')+ fireEvent.mouseLeave(remove)+ expect(remove.style.color).toBe('var(--text-faint)')+ })+})++describe('ArtikelZeile — category picker', () => {+ it('FE-W5ROW-014: picking another list moves the item', async () => {+ let body: Record<string, unknown> | null = null+ server.use(+ http.put('/api/trips/1/packing/1', async ({ request }) => {+ body = (await request.json()) as Record<string, unknown>+ return HttpResponse.json({ item: buildPackingItem({ id: 1, category: 'Docs' }) })+ }),+ )+ setup()+ fireEvent.click(screen.getByTitle('Move to List'))++ fireEvent.click(screen.getByRole('button', { name: 'Docs' }))++ await waitFor(() => expect(body).toMatchObject({ category: 'Docs' }))+ expect(screen.queryByRole('button', { name: 'Docs' })).toBeNull()+ })++ it('FE-W5ROW-015: picking the current list closes the picker without a request', async () => {+ let called = false+ server.use(http.put('/api/trips/1/packing/1', () => { called = true; return HttpResponse.json({ item: buildPackingItem() }) }))+ setup()+ fireEvent.click(screen.getByTitle('Move to List'))++ fireEvent.click(screen.getByRole('button', { name: 'Gear' }))++ await waitFor(() => expect(screen.queryByRole('button', { name: 'Docs' })).toBeNull())+ expect(called).toBe(false)+ })++ it('FE-W5ROW-016: a failing move surfaces a generic error', async () => {+ server.use(http.put('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 })))+ setup()+ fireEvent.click(screen.getByTitle('Move to List'))++ fireEvent.click(screen.getByRole('button', { name: 'Docs' }))++ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Error', 'error', undefined))+ })++ it('FE-W5ROW-017: an uncategorized item marks the default list as current', () => {+ setup({+ item: buildPackingItem({ id: 1, name: 'Soap', category: null }),+ categories: ['Other', 'Gear'],+ })+ fireEvent.click(screen.getByTitle('Move to List'))++ expect(screen.getByRole('button', { name: 'Other' })).toHaveStyle({ background: 'var(--bg-tertiary)' })+ expect(screen.getByRole('button', { name: 'Gear' })).not.toHaveStyle({ background: 'var(--bg-tertiary)' })+ })+})++describe('ArtikelZeile — sharing badges', () => {+ it('FE-W5ROW-018: an item somebody else brings shows their name', () => {+ setup({+ item: buildPackingItem({ id: 1, name: 'Stove', is_private: 1, owner_id: 2, owner_username: 'Bob' } as Partial<PackingItem>),+ currentUserId: 1,+ })++ expect(screen.getByText('by Bob')).toBeInTheDocument()+ })++ it('FE-W5ROW-019: a nameless bringer degrades to an empty name', () => {+ setup({+ item: buildPackingItem({ id: 1, name: 'Stove', is_private: 1, owner_id: 2, owner_username: null } as Partial<PackingItem>),+ currentUserId: 1,+ })++ expect(screen.getByTitle('by')).toBeInTheDocument()+ })++ it('FE-W5ROW-020: an item shared by me counts its recipients', () => {+ setup({+ item: buildPackingItem({+ id: 1, name: 'Stove', is_private: 1, owner_id: 1,+ recipients: [{ user_id: 2, username: 'alice' }, { user_id: 3, username: 'bob' }],+ } as unknown as Partial<PackingItem>),+ currentUserId: 1,+ })++ expect(screen.getByText('shared with 2')).toBeInTheDocument()+ expect(screen.getByTitle('alice, bob')).toBeInTheDocument()+ })++ it('FE-W5ROW-021: a common item names its bringer and counts co-bringers', () => {+ setup({+ item: buildPackingItem({+ id: 1, name: 'Stove', is_private: 0, owner_username: 'Bob',+ contributors: [{ user_id: 3, username: 'cleo' }],+ } as unknown as Partial<PackingItem>),+ currentUserId: 1,+ })++ expect(screen.getByTitle('brought by Bob')).toHaveTextContent('Bob +1')+ })++ it('FE-W5ROW-022: a bringer without co-bringers shows no counter', () => {+ setup({+ item: buildPackingItem({ id: 1, name: 'Stove', is_private: 0, owner_username: 'Bob' } as Partial<PackingItem>),+ currentUserId: 1,+ })++ expect(screen.getByTitle('brought by Bob')).toHaveTextContent(/^Bob$/)+ })++ it('FE-W5ROW-023: the placeholder row carries no badges and no share control', () => {+ setup({+ item: buildPackingItem({ id: 1, name: '...', is_private: 0, owner_username: 'Bob' } as Partial<PackingItem>),+ currentUserId: 1,+ onSetSharing: () => {},+ onClone: () => {},+ onJoin: () => {},+ onLeave: () => {},+ })++ expect(screen.queryByTitle('brought by Bob')).toBeNull()+ expect(screen.queryByTitle('Sharing')).toBeNull()+ })++ it('FE-W5ROW-024: the share control is wired up for an editable item', () => {+ const onSetSharing = vi.fn()+ setup({+ currentUserId: 1,+ tripMembers: MEMBERS,+ onSetSharing,+ onClone: () => {},+ onJoin: () => {},+ onLeave: () => {},+ })++ fireEvent.click(screen.getByTitle('Sharing'))+ fireEvent.click(screen.getByText(/^Personal$/))++ expect(onSetSharing).toHaveBeenCalledWith(1, 'personal', [])+ })+})++describe('ArtikelZeile — drag handle', () => {+ const drag = () => ({+ isDragging: false,+ isOver: false,+ onStart: vi.fn((_id: number) => {}),+ onOver: vi.fn((_id: number) => {}),+ onEnd: vi.fn(() => {}),+ onDrop: vi.fn((_id: number) => {}),+ })++ it('FE-W5ROW-025: starting and ending a drag reports the item id', () => {+ const d = drag()+ const { container } = setup({ drag: d })+ const handle = container.querySelector<HTMLElement>('div[draggable="true"]')!++ fireEvent.dragStart(handle, { dataTransfer: dt() })+ expect(d.onStart).toHaveBeenCalledWith(1)++ fireEvent.dragEnd(handle)+ expect(d.onEnd).toHaveBeenCalled()+ })++ it('FE-W5ROW-026: dragging over the row marks it as the drop target', () => {+ const d = drag()+ const { container } = setup({ drag: d })+ const row = container.querySelector<HTMLElement>('.packing-item-row')!++ fireEvent.dragOver(row, { dataTransfer: dt() })++ expect(d.onOver).toHaveBeenCalledWith(1)+ })++ it('FE-W5ROW-027: leaving the row clears the drop target, but moving inside it does not', () => {+ const d = drag()+ const { container } = setup({ drag: d })+ const row = container.querySelector<HTMLElement>('.packing-item-row')!+ const leave = (relatedTarget: Node) =>+ fireEvent(row, new MouseEvent('dragleave', { bubbles: true, relatedTarget }))++ leave(document.body)+ expect(d.onOver).toHaveBeenCalledWith(-1)++ d.onOver.mockClear()+ leave(screen.getByText('Tent'))+ expect(d.onOver).not.toHaveBeenCalled()+ })++ it('FE-W5ROW-028: dropping on the row reports the target id', () => {+ const d = drag()+ const { container } = setup({ drag: d })++ fireEvent.drop(container.querySelector<HTMLElement>('.packing-item-row')!, { dataTransfer: dt() })++ expect(d.onDrop).toHaveBeenCalledWith(1)+ })++ it('FE-W5ROW-029: the dragged row fades and the hovered row shows an edge', () => {+ const { container } = setup({ drag: { ...drag(), isDragging: true, isOver: true } })+ const row = container.querySelector<HTMLElement>('.packing-item-row')!++ expect(row.style.opacity).toBe('0.4')+ expect(row.style.boxShadow).toBe('inset 3px 0 0 0 var(--accent)')+ })++ it('FE-W5ROW-030: hovering the row brings the grip to full opacity', () => {+ const { container } = setup({ drag: drag() })+ const row = container.querySelector<HTMLElement>('.packing-item-row')!+ const handle = container.querySelector<HTMLElement>('div[draggable="true"]')!++ expect(handle.style.opacity).toBe('0.35')+ fireEvent.mouseEnter(row)+ expect(handle.style.opacity).toBe('1')+ })++ it('FE-W5ROW-031: a placeholder row is not draggable', () => {+ const { container } = setup({ item: buildPackingItem({ id: 1, name: '...' }), drag: drag() })++ expect(container.querySelector('div[draggable="true"]')).toBeNull()+ })+})++describe('ArtikelZeile — weight and bag', () => {+ it('FE-W5ROW-032: entering a weight saves it in grams', async () => {+ let body: Record<string, unknown> | null = null+ server.use(+ http.put('/api/trips/1/packing/1', async ({ request }) => {+ body = (await request.json()) as Record<string, unknown>+ return HttpResponse.json({ item: buildPackingItem({ id: 1 }) })+ }),+ )+ const { container } = setup({ bagTrackingEnabled: true, bags: BAGS })++ fireEvent.change(container.querySelector('input[placeholder="—"]')!, { target: { value: '450' } })++ await waitFor(() => expect(body).toMatchObject({ weight_grams: 450 }))+ })++ it('FE-W5ROW-033: clearing the weight stores null', async () => {+ let body: Record<string, unknown> | null = null+ server.use(+ http.put('/api/trips/1/packing/1', async ({ request }) => {+ body = (await request.json()) as Record<string, unknown>+ return HttpResponse.json({ item: buildPackingItem({ id: 1 }) })+ }),+ )+ const { container } = setup({+ item: buildPackingItem({ id: 1, name: 'Tent', weight_grams: 300 } as Partial<PackingItem>),+ bagTrackingEnabled: true,+ })++ fireEvent.change(container.querySelector('input[placeholder="—"]')!, { target: { value: '' } })++ await waitFor(() => expect(body).toMatchObject({ weight_grams: null }))+ })++ it('FE-W5ROW-034: a failing weight save surfaces a save error', async () => {+ server.use(http.put('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 })))+ const { container } = setup({ bagTrackingEnabled: true })++ fireEvent.change(container.querySelector('input[placeholder="—"]')!, { target: { value: '450' } })++ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined))+ })++ it('FE-W5ROW-035: a read-only row ignores weight edits and never opens the bag picker', async () => {+ let called = false+ server.use(http.put('/api/trips/1/packing/1', () => { called = true; return HttpResponse.json({ item: buildPackingItem() }) }))+ const { container } = setup({ bagTrackingEnabled: true, bags: BAGS, canEdit: false })++ const weight = container.querySelector<HTMLInputElement>('input[placeholder="—"]')!+ expect(weight.readOnly).toBe(true)+ fireEvent.change(weight, { target: { value: '450' } })+ fireEvent.click(bagButton(container))++ await waitFor(() => expect(screen.queryByRole('button', { name: /Carry-on/ })).toBeNull())+ expect(called).toBe(false)+ })++ it('FE-W5ROW-036: picking a bag assigns it', async () => {+ let body: Record<string, unknown> | null = null+ server.use(+ http.put('/api/trips/1/packing/1', async ({ request }) => {+ body = (await request.json()) as Record<string, unknown>+ return HttpResponse.json({ item: buildPackingItem({ id: 1 }) })+ }),+ )+ const { container } = setup({ bagTrackingEnabled: true, bags: BAGS })+ fireEvent.click(bagButton(container))++ fireEvent.click(screen.getByRole('button', { name: 'Trolley' }))++ await waitFor(() => expect(body).toMatchObject({ bag_id: 8 }))+ })++ it('FE-W5ROW-037: a failing bag assign surfaces a save error', async () => {+ server.use(http.put('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 })))+ const { container } = setup({ bagTrackingEnabled: true, bags: BAGS })+ fireEvent.click(bagButton(container))++ fireEvent.click(screen.getByRole('button', { name: 'Trolley' }))++ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined))+ })++ it('FE-W5ROW-038: only an assigned item offers the Unassigned entry, which clears the bag', async () => {+ let body: Record<string, unknown> | null = null+ server.use(+ http.put('/api/trips/1/packing/1', async ({ request }) => {+ body = (await request.json()) as Record<string, unknown>+ return HttpResponse.json({ item: buildPackingItem({ id: 1 }) })+ }),+ )+ const unassigned = setup({ bagTrackingEnabled: true, bags: BAGS })+ fireEvent.click(bagButton(unassigned.container))+ expect(screen.queryByRole('button', { name: 'Unassigned' })).toBeNull()+ unassigned.unmount()++ const { container } = setup({+ item: buildPackingItem({ id: 1, name: 'Tent', bag_id: 7 } as Partial<PackingItem>),+ bagTrackingEnabled: true,+ bags: BAGS,+ })+ fireEvent.click(bagButton(container))+ fireEvent.click(screen.getByRole('button', { name: 'Unassigned' }))++ await waitFor(() => expect(body).toMatchObject({ bag_id: null }))+ })++ it('FE-W5ROW-039: a failing clear surfaces a save error', async () => {+ server.use(http.put('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 })))+ const { container } = setup({+ item: buildPackingItem({ id: 1, name: 'Tent', bag_id: 7 } as Partial<PackingItem>),+ bagTrackingEnabled: true,+ bags: BAGS,+ })+ fireEvent.click(bagButton(container))++ fireEvent.click(screen.getByRole('button', { name: 'Unassigned' }))++ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined))+ })++ it('FE-W5ROW-040: only the unselected bag entries react to hover', () => {+ const { container } = setup({+ item: buildPackingItem({ id: 1, name: 'Tent', bag_id: 7 } as Partial<PackingItem>),+ bagTrackingEnabled: true,+ bags: BAGS,+ })+ fireEvent.click(bagButton(container))+ const selected = screen.getByRole('button', { name: 'Carry-on' })+ const other = screen.getByRole('button', { name: 'Trolley' })++ fireEvent.mouseEnter(other)+ expect(other.style.background).toBe('var(--bg-tertiary)')+ fireEvent.mouseLeave(other)+ expect(other.style.background).toBe('none')++ fireEvent.mouseEnter(selected)+ fireEvent.mouseLeave(selected)+ expect(selected.style.background).toBe('var(--bg-tertiary)')+ })++ it('FE-W5ROW-041: creating a bag inline assigns it right away', async () => {+ const created = { id: 12, name: 'Duffel', color: '#f97316' } as unknown as PackingBag+ const onCreateBag = vi.fn(async () => created)+ let body: Record<string, unknown> | null = null+ server.use(+ http.put('/api/trips/1/packing/1', async ({ request }) => {+ body = (await request.json()) as Record<string, unknown>+ return HttpResponse.json({ item: buildPackingItem({ id: 1 }) })+ }),+ )+ const { container } = setup({ bagTrackingEnabled: true, bags: BAGS, onCreateBag })+ fireEvent.click(bagButton(container))+ fireEvent.click(screen.getByText('Add bag'))++ const input = screen.getByPlaceholderText('Bag name...')+ fireEvent.change(input, { target: { value: ' Duffel ' } })+ fireEvent.keyDown(input, { key: 'Enter' })++ await waitFor(() => expect(onCreateBag).toHaveBeenCalledWith('Duffel'))+ await waitFor(() => expect(body).toMatchObject({ bag_id: 12 }))+ })++ it('FE-W5ROW-042: Enter on a blank inline name creates nothing', () => {+ const onCreateBag = vi.fn(async () => undefined)+ const { container } = setup({ bagTrackingEnabled: true, bags: BAGS, onCreateBag })+ fireEvent.click(bagButton(container))+ fireEvent.click(screen.getByText('Add bag'))++ fireEvent.keyDown(screen.getByPlaceholderText('Bag name...'), { key: 'Enter' })++ expect(onCreateBag).not.toHaveBeenCalled()+ })++ it('FE-W5ROW-043: Escape cancels the inline bag form', () => {+ const { container } = setup({ bagTrackingEnabled: true, bags: BAGS })+ fireEvent.click(bagButton(container))+ fireEvent.click(screen.getByText('Add bag'))++ fireEvent.keyDown(screen.getByPlaceholderText('Bag name...'), { key: 'Escape' })++ expect(screen.queryByPlaceholderText('Bag name...')).toBeNull()+ expect(screen.getByText('Add bag')).toBeInTheDocument()+ })++ it('FE-W5ROW-044: the inline confirm button creates the bag, and is inert while blank', async () => {+ const created = { id: 13, name: 'Crate', color: '#f97316' } as unknown as PackingBag+ const onCreateBag = vi.fn(async () => created)+ server.use(http.put('/api/trips/1/packing/1', () => HttpResponse.json({ item: buildPackingItem({ id: 1 }) })))+ const { container } = setup({ bagTrackingEnabled: true, bags: BAGS, onCreateBag })+ fireEvent.click(bagButton(container))+ fireEvent.click(screen.getByText('Add bag'))+ const confirm = screen.getByPlaceholderText('Bag name...').nextElementSibling as HTMLButtonElement++ fireEvent.click(confirm)+ expect(onCreateBag).not.toHaveBeenCalled()++ fireEvent.change(screen.getByPlaceholderText('Bag name...'), { target: { value: 'Crate' } })+ fireEvent.click(confirm)++ await waitFor(() => expect(onCreateBag).toHaveBeenCalledWith('Crate'))+ })++ it('FE-W5ROW-045: a rejected bag creation leaves the item unassigned', async () => {+ const onCreateBag = vi.fn(async () => undefined)+ let called = false+ server.use(http.put('/api/trips/1/packing/1', () => { called = true; return HttpResponse.json({ item: buildPackingItem() }) }))+ const { container } = setup({ bagTrackingEnabled: true, bags: [], onCreateBag })+ fireEvent.click(bagButton(container))+ fireEvent.click(screen.getByText('Add bag'))++ const input = screen.getByPlaceholderText('Bag name...')+ fireEvent.change(input, { target: { value: 'Duffel' } })+ fireEvent.keyDown(input, { key: 'Enter' })++ await waitFor(() => expect(onCreateBag).toHaveBeenCalled())+ await waitFor(() => expect(screen.queryByPlaceholderText('Bag name...')).toBeNull())+ expect(called).toBe(false)+ })++ it('FE-W5ROW-046: the Add bag entry highlights on hover', () => {+ const { container } = setup({ bagTrackingEnabled: true, bags: BAGS })+ fireEvent.click(bagButton(container))+ const add = screen.getByText('Add bag').closest('button')!++ fireEvent.mouseEnter(add)+ expect(add.style.color).toBe('var(--text-secondary)')+ fireEvent.mouseLeave(add)+ expect(add.style.color).toBe('var(--text-faint)')+ })+})++describe('ArtikelZeile — overflow menu', () => {+ it('FE-W5ROW-047: the menu renames and closes', () => {+ const { container } = setup()+ fireEvent.click(overflowTrigger(container))++ fireEvent.click(screen.getByText('Rename'))++ expect(screen.getByDisplayValue('Tent')).toBeInTheDocument()+ expect(screen.queryByText('Delete')).toBeNull()+ })++ it('FE-W5ROW-048: the menu deletes through the panel handler', async () => {+ const onDelete = vi.fn(async () => {})+ const { container, props } = setup({ onDelete })+ fireEvent.click(overflowTrigger(container))++ fireEvent.click(screen.getByText('Delete'))++ await waitFor(() => expect(onDelete).toHaveBeenCalledWith(props.item))+ })++ it('FE-W5ROW-049: the scrim closes the menu', () => {+ const { container, baseElement } = setup()+ fireEvent.click(overflowTrigger(container))+ expect(screen.getByText('Qty')).toBeInTheDocument()++ fireEvent.click(baseElement.querySelector('div[style*="z-index: 1098"]')!)++ expect(screen.queryByText('Qty')).toBeNull()+ })++ it('FE-W5ROW-050: the menu commits a new quantity', async () => {+ let body: Record<string, unknown> | null = null+ server.use(+ http.put('/api/trips/1/packing/1', async ({ request }) => {+ body = (await request.json()) as Record<string, unknown>+ return HttpResponse.json({ item: buildPackingItem({ id: 1, quantity: 4 }) })+ }),+ )+ const { container } = setup({ item: buildPackingItem({ id: 1, name: 'Tent', quantity: null } as Partial<PackingItem>) })+ fireEvent.click(overflowTrigger(container))++ const qty = fieldOf(container, 'Qty')+ fireEvent.change(qty, { target: { value: '4' } })+ fireEvent.blur(qty)++ await waitFor(() => expect(body).toMatchObject({ quantity: 4 }))+ })++ it('FE-W5ROW-051: the menu saves a weight and reassigns the bag', async () => {+ const bodies: Record<string, unknown>[] = []+ server.use(+ http.put('/api/trips/1/packing/1', async ({ request }) => {+ bodies.push((await request.json()) as Record<string, unknown>)+ return HttpResponse.json({ item: buildPackingItem({ id: 1 }) })+ }),+ )+ const { container } = setup({+ item: buildPackingItem({ id: 1, name: 'Tent', bag_id: 7 } as Partial<PackingItem>),+ bagTrackingEnabled: true,+ bags: BAGS,+ })+ fireEvent.click(overflowTrigger(container))++ const weight = fieldOf(container, 'Total weight')+ fireEvent.change(weight, { target: { value: '900' } })+ await waitFor(() => expect(bodies[0]).toMatchObject({ weight_grams: 900 }))++ // The first entry mirrors the current bag and clears it when tapped.+ fireEvent.click(menu(container).getAllByRole('button', { name: 'Carry-on', hidden: true })[0])+ await waitFor(() => expect(bodies[1]).toMatchObject({ bag_id: null }))++ fireEvent.click(menuButton(container, 'Trolley'))+ await waitFor(() => expect(bodies[2]).toMatchObject({ bag_id: 8 }))+ })++ it('FE-W5ROW-052: a failing menu weight or bag change surfaces a save error', async () => {+ server.use(http.put('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 })))+ const { container } = setup({ bagTrackingEnabled: true, bags: BAGS })+ fireEvent.click(overflowTrigger(container))++ fireEvent.change(fieldOf(container, 'Total weight'), { target: { value: '900' } })++ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined))++ toastSpy.mockClear()+ fireEvent.click(menuButton(container, 'Trolley'))+ await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined))+ })++ it('FE-W5ROW-053: an unassigned item shows the Unassigned row without firing a request', async () => {+ let called = false+ server.use(http.put('/api/trips/1/packing/1', () => { called = true; return HttpResponse.json({ item: buildPackingItem() }) }))+ const { container } = setup({ bagTrackingEnabled: true, bags: BAGS })+ fireEvent.click(overflowTrigger(container))++ fireEvent.click(menuButton(container, 'Unassigned'))++ await waitFor(() => expect(menu(container).getByText('Total weight')).toBeInTheDocument())+ expect(called).toBe(false)+ })++ it('FE-W5ROW-054: the menu list submenu moves the item and can be collapsed again', async () => {+ let body: Record<string, unknown> | null = null+ server.use(+ http.put('/api/trips/1/packing/1', async ({ request }) => {+ body = (await request.json()) as Record<string, unknown>+ return HttpResponse.json({ item: buildPackingItem({ id: 1, category: 'Docs' }) })+ }),+ )+ const { container } = setup()+ fireEvent.click(overflowTrigger(container))++ fireEvent.click(menuButton(container, 'Move to List'))+ expect(menuButton(container, 'Docs')).toBeInTheDocument()++ fireEvent.click(menuButton(container, 'Move to List'))+ expect(menu(container).queryByRole('button', { name: 'Docs', hidden: true })).toBeNull()++ fireEvent.click(menuButton(container, 'Move to List'))+ fireEvent.click(menuButton(container, 'Docs'))++ await waitFor(() => expect(body).toMatchObject({ category: 'Docs' }))+ })++ it('FE-W5ROW-055: the menu carries its own share control', () => {+ const onSetSharing = vi.fn()+ const { container } = setup({+ currentUserId: 1,+ tripMembers: MEMBERS,+ onSetSharing,+ onClone: () => {},+ onJoin: () => {},+ onLeave: () => {},+ })+ fireEvent.click(overflowTrigger(container))++ expect(screen.getByText('Sharing')).toBeInTheDocument()+ const triggers = screen.getAllByTitle('Sharing')+ fireEvent.click(triggers[triggers.length - 1])+ fireEvent.click(screen.getByText(/^Personal$/))++ expect(onSetSharing).toHaveBeenCalledWith(1, 'personal', [])+ })++ it('FE-W5ROW-056: menu entries highlight on hover, the active one stays put', () => {+ const { container } = setup({+ item: buildPackingItem({ id: 1, name: 'Tent', category: 'Gear', bag_id: 8 } as Partial<PackingItem>),+ bagTrackingEnabled: true,+ bags: BAGS,+ })+ fireEvent.click(overflowTrigger(container))+ const active = screen.getByRole('button', { name: 'Trolley' })+ const plain = screen.getByRole('button', { name: 'Carry-on' })+ const danger = screen.getByText('Delete').closest('button')!++ fireEvent.mouseEnter(plain)+ expect(plain.style.background).toBe('var(--bg-tertiary)')+ fireEvent.mouseLeave(plain)+ expect(plain.style.background).toBe('none')++ fireEvent.mouseEnter(active)+ fireEvent.mouseLeave(active)+ expect(active.style.background).toBe('var(--bg-tertiary)')++ fireEvent.mouseEnter(danger)+ expect(danger.style.background).toBe('rgb(254, 242, 242)')+ })+})diff --git a/client/src/components/Packing/PackingShareControl.test.tsx b/client/src/components/Packing/PackingShareControl.test.tsxnew file mode 100644index 000000000..38e152024--- /dev/null+++ b/client/src/components/Packing/PackingShareControl.test.tsx@@ -0,0 +1,284 @@+// FE-W4PSC-001 to FE-W4PSC-015, FE-W5PSC-001 to FE-W5PSC-009+import { describe, it, expect, vi } from 'vitest'+import type { PackingItem } from '../../types'+import { render, screen, fireEvent } from '../../../tests/helpers/render'+import PackingShareControl from './PackingShareControl'+import type { TripMember } from './usePackingListPanel'++const MEMBERS = [+ { id: 1, username: 'ada' },+ { id: 2, username: 'bob' },+ { id: 3, username: 'cleo' },+] as unknown as TripMember[]++function item(overrides: Partial<PackingItem> = {}): PackingItem {+ return { id: 5, name: 'Tent', is_private: 0, owner_id: 1, recipients: [], contributors: [], ...overrides } as unknown as PackingItem+}++function setup(it_: PackingItem, currentUserId = 1) {+ const onSetSharing = vi.fn()+ const onClone = vi.fn()+ const onJoin = vi.fn()+ const onLeave = vi.fn()+ const utils = render(+ <PackingShareControl+ item={it_} tripMembers={MEMBERS} currentUserId={currentUserId}+ onSetSharing={onSetSharing} onClone={onClone} onJoin={onJoin} onLeave={onLeave}+ />,+ )+ return { onSetSharing, onClone, onJoin, onLeave, ...utils }+}++describe('PackingShareControl — owner', () => {+ it('FE-W4PSC-001: shows the share trigger for the owner of a common item', () => {+ setup(item())++ expect(screen.getByRole('button', { name: /sharing/i })).toBeInTheDocument()+ })++ it('FE-W4PSC-002: opening the menu lists both tiers plus every other member', () => {+ setup(item())++ fireEvent.click(screen.getByRole('button', { name: /sharing/i }))++ expect(screen.getByText(/^Shared$/)).toBeInTheDocument()+ expect(screen.getByText(/^Personal$/)).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /bob/ })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /cleo/ })).toBeInTheDocument()+ // Neither the owner nor the current user is offered as a recipient.+ expect(screen.queryByRole('button', { name: /ada/ })).toBeNull()+ })++ it('FE-W4PSC-003: picking Personal reports the tier and closes the menu', () => {+ const { onSetSharing } = setup(item())+ fireEvent.click(screen.getByRole('button', { name: /sharing/i }))++ fireEvent.click(screen.getByText(/^Personal$/))++ expect(onSetSharing).toHaveBeenCalledWith(5, 'personal', [])+ expect(screen.queryByText(/^Personal$/)).toBeNull()+ })++ it('FE-W4PSC-004: picking the common tier reports it', () => {+ const { onSetSharing } = setup(item({ is_private: 1 } as Partial<PackingItem>))+ fireEvent.click(screen.getByRole('button', { name: /sharing/i }))++ fireEvent.click(screen.getByText(/^Shared$/))++ expect(onSetSharing).toHaveBeenCalledWith(5, 'common', [])+ })++ it('FE-W4PSC-005: toggling a member on shares the item with them', () => {+ const { onSetSharing } = setup(item({ is_private: 1 } as Partial<PackingItem>))+ fireEvent.click(screen.getByRole('button', { name: /sharing/i }))++ fireEvent.click(screen.getByRole('button', { name: /bob/ }))++ expect(onSetSharing).toHaveBeenCalledWith(5, 'shared', [2])+ })++ it('FE-W4PSC-006: toggling an existing recipient off removes them', () => {+ const { onSetSharing } = setup(item({ is_private: 1, recipients: [{ user_id: 2 }, { user_id: 3 }] } as unknown as Partial<PackingItem>))+ fireEvent.click(screen.getByRole('button', { name: /sharing/i }))++ fireEvent.click(screen.getByRole('button', { name: /bob/ }))++ expect(onSetSharing).toHaveBeenCalledWith(5, 'shared', [3])+ })++ it('FE-W4PSC-007: an item with recipients reads as the shared tier', () => {+ setup(item({ is_private: 1, recipients: [{ user_id: 2 }] } as unknown as Partial<PackingItem>))+ fireEvent.click(screen.getByRole('button', { name: /sharing/i }))++ // The chosen recipient carries the check mark.+ expect(screen.getByRole('button', { name: /bob/ }).querySelector('svg')).not.toBeNull()+ })++ it('FE-W4PSC-008: shows a hint when there is nobody else to share with', () => {+ render(+ <PackingShareControl+ item={item()} tripMembers={[MEMBERS[0]]} currentUserId={1}+ onSetSharing={() => {}} onClone={() => {}} onJoin={() => {}} onLeave={() => {}}+ />,+ )+ fireEvent.click(screen.getByRole('button', { name: /sharing/i }))++ expect(screen.getByText(/no one/i)).toBeInTheDocument()+ })++ it('FE-W4PSC-009: the scrim closes the menu', () => {+ const { baseElement } = setup(item())+ fireEvent.click(screen.getByRole('button', { name: /sharing/i }))++ // The scrim is the portaled full-screen layer that sits just under the menu.+ fireEvent.click(baseElement.querySelector('div[style*="z-index: 1099"]')!)++ expect(screen.queryByText(/^Personal$/)).toBeNull()+ })++ it('FE-W4PSC-010: the trigger toggles the menu closed again', () => {+ setup(item())+ const trigger = screen.getByRole('button', { name: /sharing/i })++ fireEvent.click(trigger)+ expect(screen.getByText(/^Personal$/)).toBeInTheDocument()++ fireEvent.click(trigger)+ expect(screen.queryByText(/^Personal$/)).toBeNull()+ })++ it('FE-W4PSC-011: an unowned item is treated as the current user own', () => {+ setup(item({ owner_id: null } as unknown as Partial<PackingItem>), 9)++ expect(screen.getByRole('button', { name: /sharing/i })).toBeInTheDocument()+ })+})++describe('PackingShareControl — other members', () => {+ it('FE-W4PSC-012: a non-owner can pledge to co-bring a common item', () => {+ const { onJoin } = setup(item(), 2)++ const buttons = screen.getAllByRole('button')+ expect(buttons).toHaveLength(2)+ fireEvent.click(buttons[0])++ expect(onJoin).toHaveBeenCalledWith(5)+ })++ it('FE-W4PSC-013: a pledged contributor can withdraw again', () => {+ const { onLeave } = setup(item({ contributors: [{ user_id: 2 }] } as unknown as Partial<PackingItem>), 2)++ fireEvent.click(screen.getAllByRole('button')[0])++ expect(onLeave).toHaveBeenCalledWith(5, 2)+ })++ it('FE-W4PSC-014: a non-owner can clone a common item to their own list', () => {+ const { onClone } = setup(item(), 2)++ fireEvent.click(screen.getAllByRole('button')[1])++ expect(onClone).toHaveBeenCalledWith(5)+ })++ it('FE-W4PSC-015: a recipient of a shared item gets no controls', () => {+ const { container } = setup(item({ is_private: 1, recipients: [{ user_id: 2 }] } as unknown as Partial<PackingItem>), 2)++ expect(container).toBeEmptyDOMElement()+ })+})++describe('PackingShareControl — hover affordances', () => {+ it('FE-W5PSC-001: the trigger of a common item highlights on hover and resets on leave', () => {+ setup(item())+ const trigger = screen.getByRole('button', { name: /sharing/i })++ fireEvent.mouseEnter(trigger)+ expect(trigger.style.color).toBe('var(--text-secondary)')++ fireEvent.mouseLeave(trigger)+ expect(trigger.style.color).toBe('var(--text-faint)')+ })++ it('FE-W5PSC-002: a non-common item keeps its accent colour while hovered', () => {+ setup(item({ is_private: 1 } as Partial<PackingItem>))+ const trigger = screen.getByRole('button', { name: /sharing/i })++ fireEvent.mouseEnter(trigger)+ expect(trigger.style.color).toBe('var(--accent)')++ fireEvent.mouseLeave(trigger)+ expect(trigger.style.color).toBe('var(--accent)')+ })++ it('FE-W5PSC-003: the inactive tier row takes a hover background and drops it again', () => {+ setup(item())+ fireEvent.click(screen.getByRole('button', { name: /sharing/i }))+ // The item is Common, so the Personal row is the inactive one.+ const personalRow = screen.getByText(/^Personal$/).closest('button')!++ fireEvent.mouseEnter(personalRow)+ expect(personalRow.style.background).toBe('var(--bg-tertiary)')++ fireEvent.mouseLeave(personalRow)+ expect(personalRow.style.background).toBe('none')+ })++ it('FE-W5PSC-004: the active tier row ignores hover', () => {+ setup(item())+ fireEvent.click(screen.getByRole('button', { name: /sharing/i }))+ const commonRow = screen.getByText(/^Shared$/).closest('button')!+ const before = commonRow.style.background++ fireEvent.mouseEnter(commonRow)+ fireEvent.mouseLeave(commonRow)++ expect(commonRow.style.background).toBe(before)+ })++ it('FE-W5PSC-005: a recipient row highlights on hover', () => {+ setup(item({ is_private: 1 } as Partial<PackingItem>))+ fireEvent.click(screen.getByRole('button', { name: /sharing/i }))+ const bob = screen.getByRole('button', { name: /bob/ })++ fireEvent.mouseEnter(bob)+ expect(bob.style.background).toBe('var(--bg-tertiary)')++ fireEvent.mouseLeave(bob)+ expect(bob.style.background).toBe('none')+ })++ it('FE-W5PSC-006: the co-bring button of a non-contributor highlights on hover', () => {+ setup(item(), 2)+ const pledge = screen.getAllByRole('button')[0]++ fireEvent.mouseEnter(pledge)+ expect(pledge.style.color).toBe('var(--text-secondary)')++ fireEvent.mouseLeave(pledge)+ expect(pledge.style.color).toBe('var(--text-faint)')+ })++ it('FE-W5PSC-007: an already pledged contributor keeps the accent colour while hovered', () => {+ setup(item({ contributors: [{ user_id: 2 }] } as unknown as Partial<PackingItem>), 2)+ const pledge = screen.getAllByRole('button')[0]++ fireEvent.mouseEnter(pledge)+ fireEvent.mouseLeave(pledge)++ expect(pledge.style.color).toBe('var(--accent)')+ })+})++describe('PackingShareControl — optional fields', () => {+ it('FE-W5PSC-008: an item without recipients or contributors reads as the common tier', () => {+ const bare = { id: 7, name: 'Stove', is_private: 0, owner_id: 1 } as unknown as PackingItem+ const onSetSharing = vi.fn()+ render(+ <PackingShareControl+ item={bare} tripMembers={MEMBERS} currentUserId={1}+ onSetSharing={onSetSharing} onClone={() => {}} onJoin={() => {}} onLeave={() => {}}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: /sharing/i }))+ fireEvent.click(screen.getByRole('button', { name: /bob/ }))++ expect(onSetSharing).toHaveBeenCalledWith(7, 'shared', [2])+ })++ it('FE-W5PSC-009: a non-owner without a contributor list can still pledge', () => {+ const bare = { id: 8, name: 'Stove', is_private: 0, owner_id: 1 } as unknown as PackingItem+ const onJoin = vi.fn()+ render(+ <PackingShareControl+ item={bare} tripMembers={MEMBERS} currentUserId={3}+ onSetSharing={() => {}} onClone={() => {}} onJoin={onJoin} onLeave={() => {}}+ />,+ )++ fireEvent.click(screen.getAllByRole('button')[0])++ expect(onJoin).toHaveBeenCalledWith(8)+ })+})diff --git a/client/src/components/Packing/usePackingListPanel.test.tsx b/client/src/components/Packing/usePackingListPanel.test.tsxnew file mode 100644index 000000000..5c4811f49--- /dev/null+++ b/client/src/components/Packing/usePackingListPanel.test.tsx@@ -0,0 +1,875 @@+// FE-W5HOOK-001 to FE-W5HOOK-047+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import type { ChangeEvent, ReactNode } from 'react'+import { http, HttpResponse } from 'msw'+import { renderHook, act, waitFor } from '@testing-library/react'+import { TranslationProvider } from '../../i18n/TranslationContext'+import { server } from '../../../tests/helpers/msw/server'+import { resetAllStores, seedStore } from '../../../tests/helpers/store'+import { buildUser, buildAdmin, buildTrip, buildPackingItem } from '../../../tests/helpers/factories'+import { useAuthStore } from '../../store/authStore'+import { useTripStore } from '../../store/tripStore'+import { useAddonStore } from '../../store/addonStore'+import { usePermissionsStore } from '../../store/permissionsStore'+import { usePackingList, type PackingListPanelProps } from './usePackingListPanel'+import type { PackingItem } from '../../types'++const wrapper = ({ children }: { children: ReactNode }) => <TranslationProvider>{children}</TranslationProvider>++const toastSpy = vi.fn((_message: string, _type?: string, _duration?: number) => 0)++function renderPanel(props: Partial<PackingListPanelProps> = {}) {+ return renderHook((p: PackingListPanelProps) => usePackingList(p), {+ wrapper,+ initialProps: { tripId: 1, items: [], ...props },+ })+}++/** Waits for the mount effects (members, assignees, templates) to settle. */+async function settled() {+ await act(async () => { await Promise.resolve() })+}++beforeEach(() => {+ resetAllStores()+ toastSpy.mockClear()+ window.__addToast = toastSpy+ server.use(+ http.get('/api/trips/:id/members', () =>+ HttpResponse.json({ owner: { id: 1, username: 'owner', avatar_url: null }, members: [] })),+ http.get('/api/trips/:id/packing/category-assignees', () => HttpResponse.json({ assignees: {} })),+ http.get('/api/addons', () => HttpResponse.json({ bagTracking: false, addons: [] })),+ http.get('/api/trips/:id/packing/templates', () => HttpResponse.json({ templates: [] })),+ http.get('/api/trips/:id/packing/bags', () => HttpResponse.json({ bags: [] })),+ )+ seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true })+ seedStore(useTripStore, { trip: buildTrip({ id: 1, user_id: 1 }) })+})++afterEach(() => {+ delete window.__addToast+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+})++describe('usePackingList — members & assignees', () => {+ it('FE-W5HOOK-001: merges the owner and the members into one member list', async () => {+ server.use(+ http.get('/api/trips/:id/members', () =>+ HttpResponse.json({+ owner: { id: 1, username: 'owner', avatar_url: 'a.png' },+ members: [{ id: 2, username: 'alice', avatar_url: null, is_guest: 1 }],+ })),+ )+ const { result } = renderPanel()++ await waitFor(() => expect(result.current.tripMembers).toHaveLength(2))+ expect(result.current.tripMembers[0]).toEqual({ id: 1, username: 'owner', avatar: 'a.png', is_guest: false })+ expect(result.current.tripMembers[1]).toEqual({ id: 2, username: 'alice', avatar: null, is_guest: true })+ })++ it('FE-W5HOOK-002: a response without owner or members yields no members', async () => {+ server.use(http.get('/api/trips/:id/members', () => HttpResponse.json({})))+ const { result } = renderPanel()++ await settled()+ expect(result.current.tripMembers).toEqual([])+ })++ it('FE-W5HOOK-003: a failing members request leaves the list empty', async () => {+ server.use(http.get('/api/trips/:id/members', () => new HttpResponse(null, { status: 500 })))+ const { result } = renderPanel()++ await settled()+ expect(result.current.tripMembers).toEqual([])+ })++ it('FE-W5HOOK-004: an assignee response without a map falls back to an empty record', async () => {+ server.use(http.get('/api/trips/:id/packing/category-assignees', () => HttpResponse.json({})))+ const { result } = renderPanel()++ await settled()+ expect(result.current.categoryAssignees).toEqual({})+ })++ it('FE-W5HOOK-005: setting assignees stores the returned list for that category', async () => {+ server.use(+ http.get('/api/trips/:id/packing/category-assignees', () => HttpResponse.json({ assignees: { Docs: [] } })),+ http.put('/api/trips/1/packing/category-assignees/Gear', () =>+ HttpResponse.json({ assignees: [{ user_id: 2, username: 'alice' }] })),+ )+ const { result } = renderPanel()+ await waitFor(() => expect(result.current.categoryAssignees.Docs).toEqual([]))++ await act(async () => { await result.current.handleSetAssignees('Gear', [2]) })++ expect(result.current.categoryAssignees.Gear).toEqual([{ user_id: 2, username: 'alice' }])+ // The existing categories survive the merge.+ expect(result.current.categoryAssignees.Docs).toEqual([])+ })++ it('FE-W5HOOK-006: an assignee response without a list stores an empty array', async () => {+ server.use(+ http.get('/api/trips/:id/packing/category-assignees', () => HttpResponse.json({ assignees: { Docs: [] } })),+ http.put('/api/trips/1/packing/category-assignees/Gear', () => HttpResponse.json({})),+ )+ const { result } = renderPanel()+ await waitFor(() => expect(result.current.categoryAssignees.Docs).toEqual([]))++ await act(async () => { await result.current.handleSetAssignees('Gear', [2]) })++ expect(result.current.categoryAssignees.Gear).toEqual([])+ })++ it('FE-W5HOOK-007: a failing assignee update surfaces a save error', async () => {+ server.use(http.put('/api/trips/1/packing/category-assignees/Gear', () => new HttpResponse(null, { status: 500 })))+ const { result } = renderPanel()++ await act(async () => { await result.current.handleSetAssignees('Gear', [2]) })++ expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined)+ })+})++describe('usePackingList — grouping, filtering and progress', () => {+ const items = [+ buildPackingItem({ id: 1, name: 'Tent', category: 'Gear', checked: 1 }),+ buildPackingItem({ id: 2, name: 'Rope', category: 'Gear', checked: 0 }),+ buildPackingItem({ id: 3, name: 'Soap', category: null, checked: 0 }),+ buildPackingItem({ id: 4, name: 'Diary', category: 'Gear', is_private: 1 } as Partial<PackingItem>),+ ]++ it('FE-W5HOOK-008: the common view hides private items and buckets by category', async () => {+ const { result } = renderPanel({ items })+ await settled()++ expect(result.current.allCategories).toEqual(['Gear', 'Other'])+ expect(result.current.gruppiert.Gear.map(i => i.name)).toEqual(['Tent', 'Rope'])+ expect(result.current.gruppiert.Other.map(i => i.name)).toEqual(['Soap'])+ })++ it('FE-W5HOOK-009: the personal view shows only private items', async () => {+ const { result } = renderPanel({ items })+ await settled()++ act(() => result.current.setView('personal'))++ expect(result.current.view).toBe('personal')+ expect(result.current.gruppiert.Gear.map(i => i.name)).toEqual(['Diary'])+ })++ it('FE-W5HOOK-010: the "offen" filter keeps only unchecked items', async () => {+ const { result } = renderPanel({ items })+ await settled()++ act(() => result.current.setFilter('offen'))++ expect(result.current.gruppiert.Gear.map(i => i.name)).toEqual(['Rope'])+ })++ it('FE-W5HOOK-011: the "erledigt" filter keeps only checked items', async () => {+ const { result } = renderPanel({ items })+ await settled()++ act(() => result.current.setFilter('erledigt'))++ expect(result.current.gruppiert.Gear.map(i => i.name)).toEqual(['Tent'])+ expect(result.current.gruppiert.Other).toBeUndefined()+ })++ it('FE-W5HOOK-012: progress is the checked share of the active view', async () => {+ const { result } = renderPanel({ items })+ await settled()++ expect(result.current.abgehakt).toBe(1)+ expect(result.current.fortschritt).toBe(33)+ })++ it('FE-W5HOOK-013: an empty view reports zero progress instead of NaN', async () => {+ const { result } = renderPanel()+ await settled()++ expect(result.current.fortschritt).toBe(0)+ })++ it('FE-W5HOOK-014: a controlled view prop drives the split and reports changes upwards', async () => {+ const onViewChange = vi.fn()+ const { result } = renderPanel({ items, view: 'personal', onViewChange })+ await settled()++ expect(result.current.gruppiert.Gear.map(i => i.name)).toEqual(['Diary'])++ act(() => result.current.setView('common'))++ expect(onViewChange).toHaveBeenCalledWith('common')+ // Controlled: the hook does not flip its own state.+ expect(result.current.view).toBe('personal')+ })+})++describe('usePackingList — item and category CRUD', () => {+ it('FE-W5HOOK-015: adding to a category reuses its placeholder row', async () => {+ const placeholder = buildPackingItem({ id: 9, name: '...', category: 'Gear' })+ seedStore(useTripStore, { packingItems: [placeholder] })+ let put: Record<string, unknown> | null = null+ let posted = false+ server.use(+ http.put('/api/trips/1/packing/9', async ({ request }) => {+ put = (await request.json()) as Record<string, unknown>+ return HttpResponse.json({ item: placeholder })+ }),+ http.post('/api/trips/1/packing', () => { posted = true; return HttpResponse.json({ item: placeholder }) }),+ )+ const { result } = renderPanel({ items: [placeholder] })++ await act(async () => { await result.current.handleAddItemToCategory('Gear', 'Tent') })++ expect(put).toMatchObject({ name: 'Tent' })+ expect(posted).toBe(false)+ })++ it('FE-W5HOOK-016: a new item in the personal view is created as personal', async () => {+ let body: Record<string, unknown> | null = null+ server.use(+ http.post('/api/trips/1/packing', async ({ request }) => {+ body = (await request.json()) as Record<string, unknown>+ return HttpResponse.json({ item: buildPackingItem({ id: 3 }) })+ }),+ )+ const { result } = renderPanel({ view: 'personal', onViewChange: () => {} })++ await act(async () => { await result.current.handleAddItemToCategory('Gear', 'Tent') })++ expect(body).toMatchObject({ name: 'Tent', category: 'Gear', visibility: 'personal' })+ })++ it('FE-W5HOOK-017: a failing add surfaces an add error', async () => {+ server.use(http.post('/api/trips/1/packing', () => new HttpResponse(null, { status: 500 })))+ const { result } = renderPanel()++ await act(async () => { await result.current.handleAddItemToCategory('Gear', 'Tent') })++ expect(toastSpy).toHaveBeenCalledWith('Failed to add', 'error', undefined)+ })++ it('FE-W5HOOK-018: deleting the last item of a category unchecks it and converts it to a placeholder', async () => {+ const item = buildPackingItem({ id: 11, name: 'Tent', category: 'Gear', checked: 1 })+ const bodies: Record<string, unknown>[] = []+ let deleted = false+ server.use(+ http.put('/api/trips/1/packing/11', async ({ request }) => {+ bodies.push((await request.json()) as Record<string, unknown>)+ return HttpResponse.json({ item })+ }),+ http.delete('/api/trips/1/packing/11', () => { deleted = true; return HttpResponse.json({ success: true }) }),+ )+ const { result } = renderPanel({ items: [item] })++ await act(async () => { await result.current.handleDeleteItem(item) })++ expect(bodies[0]).toMatchObject({ checked: false })+ expect(bodies[1]).toMatchObject({ name: '...', weight_grams: null, bag_id: null, quantity: 1 })+ expect(deleted).toBe(false)+ })++ it('FE-W5HOOK-018a: the last item of a category is converted without an extra uncheck call', async () => {+ const item = buildPackingItem({ id: 14, name: 'Tent', category: 'Gear', checked: 0 })+ const bodies: Record<string, unknown>[] = []+ server.use(+ http.put('/api/trips/1/packing/14', async ({ request }) => {+ bodies.push((await request.json()) as Record<string, unknown>)+ return HttpResponse.json({ item })+ }),+ )+ const { result } = renderPanel({ items: [item] })++ await act(async () => { await result.current.handleDeleteItem(item) })++ expect(bodies).toHaveLength(1)+ expect(bodies[0]).toMatchObject({ name: '...' })+ })++ it('FE-W5HOOK-018b: an item with siblings in its category is deleted outright', async () => {+ const item = buildPackingItem({ id: 15, name: 'Tent', category: 'Gear' })+ const sibling = buildPackingItem({ id: 16, name: 'Rope', category: 'Gear' })+ let deleted = false+ let converted = false+ server.use(+ http.delete('/api/trips/1/packing/15', () => { deleted = true; return HttpResponse.json({ success: true }) }),+ http.put('/api/trips/1/packing/15', () => { converted = true; return HttpResponse.json({ item }) }),+ )+ const { result } = renderPanel({ items: [item, sibling] })++ await act(async () => { await result.current.handleDeleteItem(item) })++ expect(deleted).toBe(true)+ expect(converted).toBe(false)+ })++ it('FE-W5HOOK-019: an uncategorized item is deleted outright', async () => {+ const item = buildPackingItem({ id: 12, name: 'Soap', category: null })+ let deleted = false+ server.use(http.delete('/api/trips/1/packing/12', () => { deleted = true; return HttpResponse.json({ success: true }) }))+ const { result } = renderPanel({ items: [item] })++ await act(async () => { await result.current.handleDeleteItem(item) })++ expect(deleted).toBe(true)+ })++ it('FE-W5HOOK-020: a failing delete surfaces a delete error', async () => {+ const item = buildPackingItem({ id: 13, name: 'Soap', category: null })+ server.use(http.delete('/api/trips/1/packing/13', () => new HttpResponse(null, { status: 500 })))+ const { result } = renderPanel({ items: [item] })++ await act(async () => { await result.current.handleDeleteItem(item) })++ expect(toastSpy).toHaveBeenCalledWith('Failed to delete', 'error', undefined)+ })++ it('FE-W5HOOK-021: adding a category without a name does nothing', async () => {+ let posted = false+ server.use(http.post('/api/trips/1/packing', () => { posted = true; return HttpResponse.json({ item: buildPackingItem() }) }))+ const { result } = renderPanel()++ act(() => result.current.setNewCatName(' '))+ await act(async () => { await result.current.handleAddNewCategory() })++ expect(posted).toBe(false)+ })++ it('FE-W5HOOK-022: a duplicate category name gets a zero-width suffix so it stays distinct', async () => {+ let body: Record<string, unknown> | null = null+ server.use(+ http.post('/api/trips/1/packing', async ({ request }) => {+ body = (await request.json()) as Record<string, unknown>+ return HttpResponse.json({ item: buildPackingItem() })+ }),+ )+ const { result } = renderPanel({ items: [buildPackingItem({ id: 20, category: 'Gear' })] })+ await settled()++ act(() => result.current.setNewCatName('Gear'))+ await act(async () => { await result.current.handleAddNewCategory() })++ expect(body).toMatchObject({ name: '...', category: 'Gear', visibility: 'common' })+ expect(result.current.newCatName).toBe('')+ expect(result.current.addingCategory).toBe(false)+ })++ it('FE-W5HOOK-022a: a category added from the personal view is created as personal', async () => {+ let body: Record<string, unknown> | null = null+ server.use(+ http.post('/api/trips/1/packing', async ({ request }) => {+ body = (await request.json()) as Record<string, unknown>+ return HttpResponse.json({ item: buildPackingItem() })+ }),+ )+ const { result } = renderPanel({ view: 'personal', onViewChange: () => {} })++ act(() => result.current.setNewCatName('Gear'))+ await act(async () => { await result.current.handleAddNewCategory() })++ expect(body).toMatchObject({ category: 'Gear', visibility: 'personal' })+ })++ it('FE-W5HOOK-023: a failing category add surfaces an add error', async () => {+ server.use(http.post('/api/trips/1/packing', () => new HttpResponse(null, { status: 500 })))+ const { result } = renderPanel()++ act(() => result.current.setNewCatName('Gear'))+ await act(async () => { await result.current.handleAddNewCategory() })++ expect(toastSpy).toHaveBeenCalledWith('Failed to add', 'error', undefined)+ })++ it('FE-W5HOOK-024: renaming the default category moves every uncategorized item', async () => {+ const items = [+ buildPackingItem({ id: 31, category: null }),+ buildPackingItem({ id: 32, category: 'Gear' }),+ ]+ const touched: number[] = []+ server.use(+ http.put('/api/trips/1/packing/:itemId', ({ params }) => {+ touched.push(Number(params.itemId))+ return HttpResponse.json({ item: items[0] })+ }),+ )+ const { result } = renderPanel({ items })++ await act(async () => { await result.current.handleRenameCategory('Other', 'Misc') })++ expect(touched).toEqual([31])+ })++ it('FE-W5HOOK-025: a partly failing category delete surfaces a delete error', async () => {+ const items = [buildPackingItem({ id: 41 }), buildPackingItem({ id: 42 })]+ server.use(+ http.delete('/api/trips/1/packing/41', () => HttpResponse.json({ success: true })),+ http.delete('/api/trips/1/packing/42', () => new HttpResponse(null, { status: 500 })),+ )+ const { result } = renderPanel({ items })++ await act(async () => { await result.current.handleDeleteCategory(items) })++ expect(toastSpy).toHaveBeenCalledWith('Failed to delete', 'error', undefined)+ })++ it('FE-W5HOOK-025a: a clean category delete stays quiet', async () => {+ const items = [buildPackingItem({ id: 43 }), buildPackingItem({ id: 44 })]+ const deleted: number[] = []+ server.use(+ http.delete('/api/trips/1/packing/:itemId', ({ params }) => {+ deleted.push(Number(params.itemId))+ return HttpResponse.json({ success: true })+ }),+ )+ const { result } = renderPanel({ items })++ await act(async () => { await result.current.handleDeleteCategory(items) })++ expect(deleted).toEqual([43, 44])+ expect(toastSpy).not.toHaveBeenCalled()+ })++ it('FE-W5HOOK-026: declining the clear-checked confirmation deletes nothing', async () => {+ vi.spyOn(window, 'confirm').mockReturnValue(false)+ let deleted = false+ server.use(http.delete('/api/trips/1/packing/:itemId', () => { deleted = true; return HttpResponse.json({ success: true }) }))+ const { result } = renderPanel({ items: [buildPackingItem({ id: 51, checked: 1 })] })++ await act(async () => { await result.current.handleClearChecked() })++ expect(deleted).toBe(false)+ })++ it('FE-W5HOOK-027: a failing clear-checked delete surfaces a delete error', async () => {+ vi.spyOn(window, 'confirm').mockReturnValue(true)+ server.use(http.delete('/api/trips/1/packing/52', () => new HttpResponse(null, { status: 500 })))+ const { result } = renderPanel({ items: [buildPackingItem({ id: 52, checked: 1 })] })++ await act(async () => { await result.current.handleClearChecked() })++ expect(toastSpy).toHaveBeenCalledWith('Failed to delete', 'error', undefined)+ })+})++describe('usePackingList — bags', () => {+ beforeEach(() => {+ seedStore(useAddonStore, { bagTracking: true, loaded: true })+ })++ it('FE-W5HOOK-028: a bag list response without bags falls back to an empty list', async () => {+ server.use(http.get('/api/trips/:id/packing/bags', () => HttpResponse.json({})))+ const { result } = renderPanel()++ await settled()+ expect(result.current.bagTrackingEnabled).toBe(true)+ expect(result.current.bags).toEqual([])+ })++ it('FE-W5HOOK-029: creating a bag without a name does nothing', async () => {+ let posted = false+ server.use(http.post('/api/trips/1/packing/bags', () => { posted = true; return HttpResponse.json({ bag: {} }) }))+ const { result } = renderPanel()++ act(() => result.current.setNewBagName(' '))+ await act(async () => { await result.current.handleCreateBag() })++ expect(posted).toBe(false)+ })++ it('FE-W5HOOK-030: creating a bag appends it and clears the form', async () => {+ server.use(+ http.post('/api/trips/1/packing/bags', () =>+ HttpResponse.json({ bag: { id: 3, name: 'Duffel', color: '#6366f1' } })),+ )+ const { result } = renderPanel()+ await settled()++ act(() => { result.current.setNewBagName('Duffel'); result.current.setShowAddBag(true) })+ await act(async () => { await result.current.handleCreateBag() })++ expect(result.current.bags).toEqual([{ id: 3, name: 'Duffel', color: '#6366f1' }])+ expect(result.current.newBagName).toBe('')+ expect(result.current.showAddBag).toBe(false)+ })++ it('FE-W5HOOK-031: a failing bag create surfaces a save error', async () => {+ server.use(http.post('/api/trips/1/packing/bags', () => new HttpResponse(null, { status: 500 })))+ const { result } = renderPanel()++ act(() => result.current.setNewBagName('Duffel'))+ await act(async () => { await result.current.handleCreateBag() })++ expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined)+ })++ it('FE-W5HOOK-032: creating a bag by name returns the new bag', async () => {+ server.use(+ http.post('/api/trips/1/packing/bags', () =>+ HttpResponse.json({ bag: { id: 4, name: 'Crate', color: '#6366f1' } })),+ )+ const { result } = renderPanel()+ await settled()++ let created: unknown+ await act(async () => { created = await result.current.handleCreateBagByName('Crate') })++ expect(created).toEqual({ id: 4, name: 'Crate', color: '#6366f1' })+ expect(result.current.bags).toHaveLength(1)+ })++ it('FE-W5HOOK-033: a failing create-by-name returns undefined and warns', async () => {+ server.use(http.post('/api/trips/1/packing/bags', () => new HttpResponse(null, { status: 500 })))+ const { result } = renderPanel()++ let created: unknown = 'unset'+ await act(async () => { created = await result.current.handleCreateBagByName('Crate') })++ expect(created).toBeUndefined()+ expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined)+ })++ it('FE-W5HOOK-034: deleting a bag drops it from the list', async () => {+ server.use(+ http.get('/api/trips/:id/packing/bags', () =>+ HttpResponse.json({ bags: [{ id: 5, name: 'A' }, { id: 6, name: 'B' }] })),+ http.delete('/api/trips/1/packing/bags/5', () => HttpResponse.json({ success: true })),+ )+ const { result } = renderPanel()+ await waitFor(() => expect(result.current.bags).toHaveLength(2))++ await act(async () => { await result.current.handleDeleteBag(5) })++ expect(result.current.bags.map(b => b.id)).toEqual([6])+ })++ it('FE-W5HOOK-035: a failing bag delete surfaces a delete error', async () => {+ server.use(http.delete('/api/trips/1/packing/bags/5', () => new HttpResponse(null, { status: 500 })))+ const { result } = renderPanel()++ await act(async () => { await result.current.handleDeleteBag(5) })++ expect(toastSpy).toHaveBeenCalledWith('Failed to delete', 'error', undefined)+ })++ it('FE-W5HOOK-036: updating a bag merges the response into that bag only', async () => {+ server.use(+ http.get('/api/trips/:id/packing/bags', () =>+ HttpResponse.json({ bags: [{ id: 5, name: 'A' }, { id: 6, name: 'B' }] })),+ http.put('/api/trips/1/packing/bags/6', () => HttpResponse.json({ bag: { name: 'Renamed' } })),+ )+ const { result } = renderPanel()+ await waitFor(() => expect(result.current.bags).toHaveLength(2))++ await act(async () => { await result.current.handleUpdateBag(6, { name: 'Renamed' }) })++ expect(result.current.bags.map(b => b.name)).toEqual(['A', 'Renamed'])+ })++ it('FE-W5HOOK-037: a failing bag update surfaces a generic error', async () => {+ server.use(http.put('/api/trips/1/packing/bags/6', () => new HttpResponse(null, { status: 500 })))+ const { result } = renderPanel()++ await act(async () => { await result.current.handleUpdateBag(6, { name: 'X' }) })++ expect(toastSpy).toHaveBeenCalledWith('Error', 'error', undefined)+ })++ it('FE-W5HOOK-038: setting bag members replaces that bag members', async () => {+ server.use(+ http.get('/api/trips/:id/packing/bags', () =>+ HttpResponse.json({ bags: [{ id: 5, name: 'A', members: [] }, { id: 6, name: 'B', members: [] }] })),+ http.put('/api/trips/1/packing/bags/5/members', () =>+ HttpResponse.json({ members: [{ user_id: 2, username: 'alice' }] })),+ )+ const { result } = renderPanel()+ await waitFor(() => expect(result.current.bags).toHaveLength(2))++ await act(async () => { await result.current.handleSetBagMembers(5, [2]) })++ expect(result.current.bags[0].members).toEqual([{ user_id: 2, username: 'alice' }])+ expect(result.current.bags[1].members).toEqual([])+ })++ it('FE-W5HOOK-039: a failing member update surfaces a generic error', async () => {+ server.use(http.put('/api/trips/1/packing/bags/5/members', () => new HttpResponse(null, { status: 500 })))+ const { result } = renderPanel()++ await act(async () => { await result.current.handleSetBagMembers(5, [2]) })++ expect(toastSpy).toHaveBeenCalledWith('Error', 'error', undefined)+ })+})++describe('usePackingList — templates, import and signals', () => {+ it('FE-W5HOOK-040: a template list response without templates falls back to an empty list', async () => {+ server.use(http.get('/api/trips/:id/packing/templates', () => HttpResponse.json({})))+ const { result } = renderPanel()++ await settled()+ expect(result.current.availableTemplates).toEqual([])+ })++ it('FE-W5HOOK-041: applying a template appends its items and reports the count', async () => {+ const fresh = buildPackingItem({ id: 61, name: 'Towel' })+ server.use(http.post('/api/trips/1/packing/apply-template/2', () => HttpResponse.json({ items: [fresh], count: 1 })))+ const { result } = renderPanel()++ act(() => result.current.setShowTemplateDropdown(true))+ await act(async () => { await result.current.handleApplyTemplate(2) })++ expect(useTripStore.getState().packingItems).toContainEqual(fresh)+ expect(toastSpy).toHaveBeenCalledWith('1 items added from template', 'success', undefined)+ expect(result.current.showTemplateDropdown).toBe(false)+ expect(result.current.applyingTemplate).toBe(false)+ })++ it('FE-W5HOOK-041a: a template response without items leaves the store untouched', async () => {+ server.use(http.post('/api/trips/1/packing/apply-template/2', () => HttpResponse.json({ count: 0 })))+ const { result } = renderPanel()++ await act(async () => { await result.current.handleApplyTemplate(2) })++ expect(useTripStore.getState().packingItems).toEqual([])+ expect(toastSpy).toHaveBeenCalledWith('0 items added from template', 'success', undefined)+ })++ it('FE-W5HOOK-042: a failing template apply surfaces a template error', async () => {+ server.use(http.post('/api/trips/1/packing/apply-template/2', () => new HttpResponse(null, { status: 500 })))+ const { result } = renderPanel()++ await act(async () => { await result.current.handleApplyTemplate(2) })++ expect(toastSpy).toHaveBeenCalledWith('Failed to apply template', 'error', undefined)+ expect(result.current.applyingTemplate).toBe(false)+ })++ it('FE-W5HOOK-043: saving a template without a name does nothing', async () => {+ let posted = false+ server.use(http.post('/api/trips/1/packing/save-as-template', () => { posted = true; return HttpResponse.json({}) }))+ const { result } = renderPanel()++ await act(async () => { await result.current.handleSaveAsTemplate() })++ expect(posted).toBe(false)+ })++ it('FE-W5HOOK-044: saving a template reloads the list and clears the form', async () => {+ server.use(+ http.post('/api/trips/1/packing/save-as-template', () => HttpResponse.json({ success: true })),+ // The reload response omits `templates` — the hook must fall back to [].+ http.get('/api/trips/:id/packing/templates', () => HttpResponse.json({})),+ )+ const { result } = renderPanel()++ act(() => { result.current.setSaveTemplateName('Beach'); result.current.setShowSaveTemplate(true) })+ await act(async () => { await result.current.handleSaveAsTemplate() })++ expect(toastSpy).toHaveBeenCalledWith('Packing list saved as template', 'success', undefined)+ expect(result.current.showSaveTemplate).toBe(false)+ expect(result.current.saveTemplateName).toBe('')+ await waitFor(() => expect(result.current.availableTemplates).toEqual([]))+ })++ it('FE-W5HOOK-045: a failing template save surfaces a generic error', async () => {+ server.use(http.post('/api/trips/1/packing/save-as-template', () => new HttpResponse(null, { status: 500 })))+ const { result } = renderPanel()++ act(() => result.current.setSaveTemplateName('Beach'))+ await act(async () => { await result.current.handleSaveAsTemplate() })++ expect(toastSpy).toHaveBeenCalledWith('Error', 'error', undefined)+ })++ it('FE-W5HOOK-046: importing nothing reports an empty import', async () => {+ const { result } = renderPanel()++ await act(async () => { await result.current.handleBulkImport() })++ expect(toastSpy).toHaveBeenCalledWith('No items to import', 'error', undefined)+ })++ it('FE-W5HOOK-047: a successful import appends the items and closes the modal', async () => {+ const imported = buildPackingItem({ id: 71, name: 'Rope' })+ server.use(http.post('/api/trips/1/packing/import', () => HttpResponse.json({ items: [imported], count: 1 })))+ const { result } = renderPanel()++ act(() => { result.current.setImportText('Gear, Rope'); result.current.setShowImportModal(true) })+ await act(async () => { await result.current.handleBulkImport() })++ expect(useTripStore.getState().packingItems).toContainEqual(imported)+ expect(toastSpy).toHaveBeenCalledWith('1 items imported', 'success', undefined)+ expect(result.current.importText).toBe('')+ expect(result.current.showImportModal).toBe(false)+ })++ it('FE-W5HOOK-047a: an import response without items still reports success', async () => {+ server.use(http.post('/api/trips/1/packing/import', () => HttpResponse.json({ count: 0 })))+ const { result } = renderPanel()++ act(() => result.current.setImportText('Gear, Rope'))+ await act(async () => { await result.current.handleBulkImport() })++ expect(useTripStore.getState().packingItems).toEqual([])+ expect(toastSpy).toHaveBeenCalledWith('0 items imported', 'success', undefined)+ })++ it('FE-W5HOOK-048: a failing import surfaces an import error', async () => {+ server.use(http.post('/api/trips/1/packing/import', () => new HttpResponse(null, { status: 500 })))+ const { result } = renderPanel()++ act(() => result.current.setImportText('Gear, Rope'))+ await act(async () => { await result.current.handleBulkImport() })++ expect(toastSpy).toHaveBeenCalledWith('Import failed', 'error', undefined)+ })++ it('FE-W5HOOK-049: picking a CSV file loads its text into the import box', async () => {+ const { result } = renderPanel()+ const file = new File(['Gear, Rope'], 'list.csv', { type: 'text/plain' })+ const target = { files: [file], value: 'list.csv' } as unknown as HTMLInputElement++ act(() => result.current.handleCsvFile({ target } as unknown as ChangeEvent<HTMLInputElement>))++ await waitFor(() => expect(result.current.importText).toBe('Gear, Rope'))+ expect(target.value).toBe('')+ })++ it('FE-W5HOOK-050: an empty file picker selection is ignored', async () => {+ const { result } = renderPanel()+ const target = { files: null, value: 'x' } as unknown as HTMLInputElement++ act(() => result.current.handleCsvFile({ target } as unknown as ChangeEvent<HTMLInputElement>))++ await settled()+ expect(result.current.importText).toBe('')+ // The input is only reset once a file was actually taken.+ expect(target.value).toBe('x')+ })++ it('FE-W5HOOK-051: a non-text read result is ignored', async () => {+ class BinaryReader {+ result: unknown = new ArrayBuffer(4)+ onload: (() => void) | null = null+ readAsText() { this.onload?.() }+ }+ vi.stubGlobal('FileReader', BinaryReader)+ const { result } = renderPanel()+ const file = new File(['x'], 'list.csv')+ const target = { files: [file], value: 'list.csv' } as unknown as HTMLInputElement++ act(() => result.current.handleCsvFile({ target } as unknown as ChangeEvent<HTMLInputElement>))++ await settled()+ expect(result.current.importText).toBe('')+ })++ it('FE-W5HOOK-052: a raised import signal opens the import modal', async () => {+ const { result, rerender } = renderPanel({ openImportSignal: 0 })+ await settled()++ rerender({ tripId: 1, items: [], openImportSignal: 1 })++ expect(result.current.showImportModal).toBe(true)+ })++ it('FE-W5HOOK-053: a raised save-template signal opens the save form', async () => {+ const { result, rerender } = renderPanel({ saveTemplateSignal: 0 })+ await settled()++ rerender({ tripId: 1, items: [], saveTemplateSignal: 1 })++ expect(result.current.showSaveTemplate).toBe(true)+ })++ it('FE-W5HOOK-054: a raised clear-checked signal runs the bulk delete', async () => {+ vi.spyOn(window, 'confirm').mockReturnValue(true)+ const items = [buildPackingItem({ id: 81, checked: 1 })]+ let deleted = false+ server.use(http.delete('/api/trips/1/packing/81', () => { deleted = true; return HttpResponse.json({ success: true }) }))+ const { rerender } = renderPanel({ items, clearCheckedSignal: 0 })+ await settled()++ await act(async () => { rerender({ tripId: 1, items, clearCheckedSignal: 1 }) })++ await waitFor(() => expect(deleted).toBe(true))+ })++ it('FE-W5HOOK-055: a mousedown outside the template dropdown closes it', async () => {+ const { result } = renderPanel()+ await settled()++ act(() => { result.current.setShowTemplateDropdown(true) })+ act(() => { result.current.templateDropdownRef.current = document.createElement('div') })+ act(() => { document.dispatchEvent(new MouseEvent('mousedown', { bubbles: true })) })++ expect(result.current.showTemplateDropdown).toBe(false)+ })++ it('FE-W5HOOK-055a: a mousedown inside the template dropdown keeps it open', async () => {+ const { result } = renderPanel()+ await settled()++ const dropdown = document.createElement('div')+ const child = document.createElement('button')+ dropdown.appendChild(child)+ document.body.appendChild(dropdown)++ act(() => { result.current.setShowTemplateDropdown(true) })+ act(() => { result.current.templateDropdownRef.current = dropdown })+ act(() => { child.dispatchEvent(new MouseEvent('mousedown', { bubbles: true })) })++ expect(result.current.showTemplateDropdown).toBe(true)+ document.body.removeChild(dropdown)+ })+})++describe('usePackingList — permissions and sharing', () => {+ it('FE-W5HOOK-056: a restricted packing_edit permission removes edit rights', async () => {+ usePermissionsStore.setState({ permissions: { packing_edit: 'admin' } })+ seedStore(useAuthStore, { user: buildUser({ id: 2 }), isAuthenticated: true })+ const { result } = renderPanel()++ await settled()+ expect(result.current.canEdit).toBe(false)+ expect(result.current.isAdmin).toBe(false)+ })++ it('FE-W5HOOK-057: an admin keeps edit rights and the admin flag', async () => {+ usePermissionsStore.setState({ permissions: { packing_edit: 'admin' } })+ seedStore(useAuthStore, { user: buildAdmin({ id: 3 }), isAuthenticated: true })+ const { result } = renderPanel()++ await settled()+ expect(result.current.canEdit).toBe(true)+ expect(result.current.isAdmin).toBe(true)+ expect(result.current.currentUserId).toBe(3)+ })++ it('FE-W5HOOK-058: the sharing handlers delegate to the packing endpoints', async () => {+ const item = buildPackingItem({ id: 91, name: 'Stove' })+ seedStore(useTripStore, { packingItems: [item] })+ let sharingBody: Record<string, unknown> | null = null+ const hits: string[] = []+ server.use(+ http.put('/api/trips/1/packing/91/sharing', async ({ request }) => {+ sharingBody = (await request.json()) as Record<string, unknown>+ return HttpResponse.json({ item })+ }),+ http.post('/api/trips/1/packing/91/clone', () => { hits.push('clone'); return HttpResponse.json({ item }) }),+ http.post('/api/trips/1/packing/91/contributors', () => { hits.push('join'); return HttpResponse.json({ item }) }),+ http.delete('/api/trips/1/packing/91/contributors/2', () => { hits.push('leave'); return HttpResponse.json({ item }) }),+ )+ const { result } = renderPanel({ items: [item] })++ await act(async () => { await result.current.handleSetSharing(91, 'shared', [2]) })+ await act(async () => { await result.current.handleCloneItem(91) })+ await act(async () => { await result.current.handleJoinItem(91) })+ await act(async () => { await result.current.handleLeaveItem(91, 2) })++ expect(sharingBody).toEqual({ visibility: 'shared', recipient_ids: [2] })+ expect(hits).toEqual(['clone', 'join', 'leave'])+ })+})diff --git a/client/src/components/Plugins/PluginContributions.test.tsx b/client/src/components/Plugins/PluginContributions.test.tsxnew file mode 100644index 000000000..3f7f4398e--- /dev/null+++ b/client/src/components/Plugins/PluginContributions.test.tsx@@ -0,0 +1,206 @@+// FE-W4PCON-001 to FE-W4PCON-016+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { renderHook, waitFor } from '@testing-library/react'+import { render, screen, fireEvent } from '../../../tests/helpers/render'+import type { ViewContribution } from '../../api/client'++const viewContributions = vi.fn(async (_view: string, _tripId: string | number) => ({ contributions: [] as ViewContribution[] }))+const invoke = vi.fn(async (_id: string, _sub: string, _init?: unknown) => ({}))+const toast = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() }++vi.mock('../../api/client', () => ({+ pluginsApi: {+ viewContributions: (view: string, tripId: string | number) => viewContributions(view, tripId),+ invoke: (id: string, sub: string, init?: unknown) => invoke(id, sub, init),+ },+}))+vi.mock('../shared/Toast', () => ({ useToast: () => toast }))+vi.mock('./PluginFrame', () => ({+ default: ({ pluginId, tripId, fill }: { pluginId: string; tripId: string | null; fill?: boolean }) =>+ <div data-testid="frame" data-plugin={pluginId} data-trip={tripId ?? ''} data-fill={String(!!fill)} />,+}))++import { usePluginViewContributions, PluginColumns, PluginCardFooter, PluginActions } from './PluginContributions'++function column(overrides: Partial<Extract<ViewContribution, { kind: 'column' }>> = {}): ViewContribution {+ return { kind: 'column', pluginId: 'p1', entityId: 1, id: 'c1', label: 'Range', value: '320 km', tone: 'default', ...overrides }+}+function action(overrides: Partial<Extract<ViewContribution, { kind: 'action' }>> = {}): ViewContribution {+ return { kind: 'action', pluginId: 'p1', entityId: 1, id: 'a1', label: 'Recalculate', target: { kind: 'route', method: 'POST', sub: 'recalc' }, ...overrides }+}++beforeEach(() => {+ viewContributions.mockReset()+ viewContributions.mockResolvedValue({ contributions: [] })+ invoke.mockReset()+ invoke.mockResolvedValue({})+ Object.values(toast).forEach(f => f.mockClear())+})++describe('usePluginViewContributions', () => {+ it('FE-W4PCON-001: buckets contributions by entity id', async () => {+ viewContributions.mockResolvedValue({+ contributions: [column({ entityId: 1, id: 'a' }), column({ entityId: 2, id: 'b' }), column({ entityId: 1, id: 'c' })],+ })++ const { result } = renderHook(() => usePluginViewContributions('places', 4))++ await waitFor(() => expect(result.current(1)).toHaveLength(2))+ expect(viewContributions).toHaveBeenCalledWith('places', 4)+ expect(result.current(2).map(c => c.id)).toEqual(['b'])+ })++ it('FE-W4PCON-002: returns a shared empty array for an entity nobody contributed to', async () => {+ viewContributions.mockResolvedValue({ contributions: [column()] })+ const { result } = renderHook(() => usePluginViewContributions('day', 1))++ await waitFor(() => expect(result.current(1)).toHaveLength(1))+ expect(result.current(77)).toBe(result.current(78))+ })++ it('FE-W4PCON-003: skips the request without a trip', () => {+ const { result } = renderHook(() => usePluginViewContributions('costs', null))++ expect(viewContributions).not.toHaveBeenCalled()+ expect(result.current(1)).toEqual([])+ })++ it('FE-W4PCON-004: yields an empty lookup when the endpoint fails', async () => {+ viewContributions.mockRejectedValue(new Error('nope'))+ const { result } = renderHook(() => usePluginViewContributions('files', 1))++ await waitFor(() => expect(viewContributions).toHaveBeenCalled())+ expect(result.current(1)).toEqual([])+ })++ it('FE-W4PCON-005: tolerates a response without a contributions array', async () => {+ viewContributions.mockResolvedValue({} as { contributions: ViewContribution[] })+ const { result } = renderHook(() => usePluginViewContributions('todos', 1))++ await waitFor(() => expect(viewContributions).toHaveBeenCalled())+ expect(result.current(1)).toEqual([])+ })++ it('FE-W4PCON-006: refetches when the view changes', async () => {+ const { rerender } = renderHook(+ ({ view }: { view: 'places' | 'day' }) => usePluginViewContributions(view, 1),+ { initialProps: { view: 'places' as const } },+ )+ await waitFor(() => expect(viewContributions).toHaveBeenCalledTimes(1))++ rerender({ view: 'day' })+ await waitFor(() => expect(viewContributions).toHaveBeenLastCalledWith('day', 1))+ })+})++describe('PluginColumns', () => {+ it('FE-W4PCON-007: renders nothing when only actions were contributed', () => {+ const { container } = render(<PluginColumns items={[action()]} />)+ expect(container).toBeEmptyDOMElement()+ })++ it('FE-W4PCON-008: renders a label/value pair with the tone class', () => {+ render(<PluginColumns items={[column({ tone: 'danger' })]} />)++ expect(screen.getByText('Range')).toBeInTheDocument()+ expect(screen.getByText('320 km')).toHaveClass('text-danger')+ })++ it('FE-W4PCON-009: falls back to the muted tone for an unknown tone', () => {+ render(<PluginColumns items={[column({ tone: 'weird' as Extract<ViewContribution, { kind: 'column' }>['tone'] })]} />)++ expect(screen.getByText('320 km')).toHaveClass('text-content-muted')+ })++ it('FE-W4PCON-010: renders a url column as a new-tab link that does not open the row', () => {+ render(<PluginColumns items={[column({ url: 'https://example.com' })]} />)+ const link = screen.getByRole('link', { name: '320 km' })++ expect(link).toHaveAttribute('href', 'https://example.com')+ expect(link).toHaveAttribute('rel', 'noreferrer noopener')++ const click = new MouseEvent('click', { bubbles: true, cancelable: true })+ const stopped = vi.spyOn(click, 'stopPropagation')+ fireEvent(link, click)+ expect(stopped).toHaveBeenCalled()+ })++ it('FE-W4PCON-011: uses an arrow glyph for a link without a value', () => {+ render(<PluginColumns items={[column({ url: 'https://example.com', value: undefined })]} />)++ expect(screen.getByRole('link')).toHaveTextContent('↗')+ })+})++describe('PluginActions', () => {+ it('FE-W4PCON-012: renders nothing when only columns were contributed', () => {+ const { container } = render(<PluginActions items={[column()]} tripId={1} />)+ expect(container).toBeEmptyDOMElement()+ })++ it('FE-W4PCON-013: a route action invokes the plugin and toasts on success', async () => {+ render(<PluginActions items={[action()]} tripId={1} />)++ fireEvent.click(screen.getByRole('button', { name: 'Recalculate' }))++ await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Recalculate'))+ expect(invoke).toHaveBeenCalledWith('p1', 'recalc', { method: 'POST' })+ })++ it('FE-W4PCON-014: a failing route action toasts the error', async () => {+ invoke.mockRejectedValue(new Error('500'))+ render(<PluginActions items={[action()]} tripId={1} />)++ fireEvent.click(screen.getByRole('button', { name: 'Recalculate' }))++ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Recalculate'))+ })++ it('FE-W4PCON-015: a frame action opens the sandboxed modal and closes on the X', () => {+ render(<PluginActions items={[action({ label: 'Configure', target: { kind: 'frame', sub: 'config' } })]} tripId={9} />)++ fireEvent.click(screen.getByRole('button', { name: 'Configure' }))+ const frame = screen.getByTestId('frame')+ expect(frame).toHaveAttribute('data-plugin', 'p1')+ expect(frame).toHaveAttribute('data-trip', '9')+ expect(frame).toHaveAttribute('data-fill', 'true')+ expect(invoke).not.toHaveBeenCalled()++ fireEvent.click(screen.getAllByRole('button')[1])+ expect(screen.queryByTestId('frame')).toBeNull()+ })++ it('FE-W4PCON-016: the frame modal closes on backdrop click but not on card click', () => {+ const { container } = render(+ <PluginActions items={[action({ label: 'Configure', target: { kind: 'frame', sub: 'config' } })]} tripId={null} />,+ )+ fireEvent.click(screen.getByRole('button', { name: 'Configure' }))+ expect(screen.getByTestId('frame')).toHaveAttribute('data-trip', '')++ fireEvent.click(container.querySelector('.bg-surface-card')!)+ expect(screen.getByTestId('frame')).toBeInTheDocument()++ fireEvent.click(container.querySelector('.fixed.inset-0')!)+ expect(screen.queryByTestId('frame')).toBeNull()+ })++ it('FE-W4PCON-017: accepts a caller className for the action buttons', () => {+ render(<PluginActions items={[action()]} tripId={1} className="btn-sm" />)++ expect(screen.getByRole('button', { name: 'Recalculate' })).toHaveClass('btn-sm')+ })+})++describe('PluginCardFooter', () => {+ it('FE-W4PCON-018: renders nothing without contributions', () => {+ const { container } = render(<PluginCardFooter items={[]} tripId={1} />)+ expect(container).toBeEmptyDOMElement()+ })++ it('FE-W4PCON-019: renders columns and actions together under a divider', () => {+ render(<PluginCardFooter items={[column(), action()]} tripId={1} />)++ expect(screen.getByText('Range')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Recalculate' })).toBeInTheDocument()+ })+})diff --git a/client/src/components/Plugins/PluginDaySchedule.test.tsx b/client/src/components/Plugins/PluginDaySchedule.test.tsxnew file mode 100644index 000000000..92a81c146--- /dev/null+++ b/client/src/components/Plugins/PluginDaySchedule.test.tsx@@ -0,0 +1,165 @@+// FE-W4PDS-001 to FE-W4PDS-013+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { renderHook, waitFor } from '@testing-library/react'+import { render, screen } from '../../../tests/helpers/render'+import type { PluginDayScheduleItem } from '../../api/client'++const daySchedule = vi.fn(async (_tripId: number | string) => ({ items: [] as PluginDayScheduleItem[] }))++vi.mock('../../api/client', () => ({+ pluginsApi: { daySchedule: (tripId: number | string) => daySchedule(tripId) },+}))++import { usePluginDaySchedule, formatScheduleMinutes, PluginDayScheduleRow } from './PluginDaySchedule'++function item(overrides: Partial<PluginDayScheduleItem> = {}): PluginDayScheduleItem {+ return { pluginId: 'ev', id: 'i1', dayId: 1, label: 'Charging', tone: 'default', ...overrides }+}++beforeEach(() => {+ daySchedule.mockReset()+ daySchedule.mockResolvedValue({ items: [] })+})++describe('formatScheduleMinutes', () => {+ it('FE-W4PDS-001: formats sub-hour durations in minutes', () => {+ expect(formatScheduleMinutes(35)).toBe('35 min')+ expect(formatScheduleMinutes(0)).toBe('0 min')+ })++ it('FE-W4PDS-002: splits an hour or more into h + min', () => {+ expect(formatScheduleMinutes(60)).toBe('1 h 0 min')+ expect(formatScheduleMinutes(95)).toBe('1 h 35 min')+ expect(formatScheduleMinutes(1440)).toBe('24 h 0 min')+ })+})++describe('usePluginDaySchedule', () => {+ it('FE-W4PDS-003: returns the shared empty schedule without a trip', () => {+ const { result } = renderHook(() => usePluginDaySchedule(null))++ expect(daySchedule).not.toHaveBeenCalled()+ expect(result.current).toEqual({ byAssignment: {}, byReservation: {}, byPosition: {}, minutesByDay: {} })+ })++ it('FE-W4PDS-004: groups place-anchored rows by day and assignment', async () => {+ daySchedule.mockResolvedValue({+ items: [+ item({ id: 'a', dayId: 3, assignmentId: 10, minutes: 35 }),+ item({ id: 'b', dayId: 3, assignmentId: 10, minutes: 5 }),+ item({ id: 'c', dayId: 3, assignmentId: 11 }),+ ],+ })++ const { result } = renderHook(() => usePluginDaySchedule(7))++ await waitFor(() => expect(result.current.byAssignment[3]).toBeDefined())+ expect(result.current.byAssignment[3][10].map(i => i.id)).toEqual(['a', 'b'])+ expect(result.current.byAssignment[3][11].map(i => i.id)).toEqual(['c'])+ expect(daySchedule).toHaveBeenCalledWith(7)+ })++ it('FE-W4PDS-005: groups booking-anchored rows by day and reservation', async () => {+ daySchedule.mockResolvedValue({+ items: [+ item({ id: 'a', dayId: 2, reservationId: 55, minutes: 45 }),+ item({ id: 'b', dayId: 2, reservationId: 55 }),+ ],+ })++ const { result } = renderHook(() => usePluginDaySchedule(1))++ await waitFor(() => expect(result.current.byReservation[2]).toBeDefined())+ expect(result.current.byReservation[2][55].map(i => i.id)).toEqual(['a', 'b'])+ })++ it('FE-W4PDS-006: pins unanchored rows to the start or end of the day', async () => {+ daySchedule.mockResolvedValue({+ items: [+ item({ id: 'first', dayId: 4, position: 'start' }),+ item({ id: 'last', dayId: 4, position: 'end' }),+ item({ id: 'default', dayId: 4 }),+ ],+ })++ const { result } = renderHook(() => usePluginDaySchedule(1))++ await waitFor(() => expect(result.current.byPosition[4]).toBeDefined())+ expect(result.current.byPosition[4].start.map(i => i.id)).toEqual(['first'])+ expect(result.current.byPosition[4].end.map(i => i.id)).toEqual(['last', 'default'])+ })++ it('FE-W4PDS-007: sums the contributed minutes per day', async () => {+ daySchedule.mockResolvedValue({+ items: [+ item({ id: 'a', dayId: 1, assignmentId: 1, minutes: 35 }),+ item({ id: 'b', dayId: 1, reservationId: 2, minutes: 45 }),+ item({ id: 'c', dayId: 2, minutes: 10 }),+ item({ id: 'd', dayId: 2 }),+ ],+ })++ const { result } = renderHook(() => usePluginDaySchedule(1))++ await waitFor(() => expect(result.current.minutesByDay[1]).toBe(80))+ expect(result.current.minutesByDay[2]).toBe(10)+ })++ it('FE-W4PDS-008: prefers the assignment anchor when both ids are present', async () => {+ daySchedule.mockResolvedValue({ items: [item({ dayId: 1, assignmentId: 9, reservationId: 8 })] })+ const { result } = renderHook(() => usePluginDaySchedule(1))++ await waitFor(() => expect(result.current.byAssignment[1]).toBeDefined())+ expect(result.current.byReservation).toEqual({})+ })++ it('FE-W4PDS-009: falls back to no extra rows when the endpoint fails', async () => {+ daySchedule.mockRejectedValue(new Error('offline'))+ const { result } = renderHook(() => usePluginDaySchedule(1))++ await waitFor(() => expect(daySchedule).toHaveBeenCalled())+ expect(result.current.minutesByDay).toEqual({})+ })++ it('FE-W4PDS-010: tolerates a response without an items array', async () => {+ daySchedule.mockResolvedValue({} as { items: PluginDayScheduleItem[] })+ const { result } = renderHook(() => usePluginDaySchedule(1))++ await waitFor(() => expect(daySchedule).toHaveBeenCalled())+ expect(result.current.byPosition).toEqual({})+ })++ it('FE-W4PDS-011: refetches when the trip changes', async () => {+ const { rerender } = renderHook(({ id }: { id: number }) => usePluginDaySchedule(id), { initialProps: { id: 1 } })+ await waitFor(() => expect(daySchedule).toHaveBeenCalledTimes(1))++ rerender({ id: 2 })+ await waitFor(() => expect(daySchedule).toHaveBeenLastCalledWith(2))+ })+})++describe('PluginDayScheduleRow', () => {+ it('FE-W4PDS-012: renders the duration, separator and label', () => {+ render(<PluginDayScheduleRow item={item({ minutes: 95, label: 'Charging stop' })} />)++ expect(screen.getByText('1 h 35 min')).toBeInTheDocument()+ expect(screen.getByText('·')).toBeInTheDocument()+ expect(screen.getByText('Charging stop')).toBeInTheDocument()+ })++ it('FE-W4PDS-013: drops the duration when the plugin contributes none', () => {+ render(<PluginDayScheduleRow item={item({ label: 'Security check' })} />)++ expect(screen.getByText('Security check')).toBeInTheDocument()+ expect(screen.queryByText('·')).toBeNull()+ })++ it('FE-W4PDS-014: colours the icon by tone and falls back for an unknown tone', () => {+ const { container, unmount } = render(<PluginDayScheduleRow item={item({ tone: 'danger' })} />)+ expect((container.querySelector('svg') as SVGElement).style.color).toBe('rgb(239, 68, 68)')+ unmount()++ const odd = render(<PluginDayScheduleRow item={item({ tone: 'nope' as PluginDayScheduleItem['tone'] })} />)+ expect((odd.container.querySelector('svg') as SVGElement).style.color).toBe('rgb(79, 70, 229)')+ })+})diff --git a/client/src/components/Plugins/PluginFrame.test.tsx b/client/src/components/Plugins/PluginFrame.test.tsxindex aed4d785f..9501d2342 100644--- a/client/src/components/Plugins/PluginFrame.test.tsx+++ b/client/src/components/Plugins/PluginFrame.test.tsx@@ -1,4 +1,4 @@-// FE-PLUGINS-FRAME-001 to 012+// FE-PLUGINS-FRAME-001 to 046import { render, cleanup, waitFor, fireEvent, screen, act } from '@testing-library/react';import PluginFrame from './PluginFrame';import { usePluginStore } from '../../store/pluginStore';@@ -8,11 +8,22 @@ const toast = { info: vi.fn(), success: vi.fn(), warning: vi.fn(), error: vi.fn(const invoke = vi.fn((..._args: unknown[]) => Promise.resolve({ ok: true }));const wsListeners = new Set<(ev: Record<string, unknown>) => void>();+// Host state the frame mirrors into its context. Mutable so a single test can+// change one input (no user, another currency) without a second mock factory.+const DEFAULT_USER = { id: 7, username: 'ada', avatar_url: null, role: 'admin' };+const DEFAULT_SETTINGS = { default_currency: 'EUR', time_format: '24h', distance_unit: 'metric', temperature_unit: 'celsius', blur_booking_codes: true };+const host = vi.hoisted(() => ({+ user: { id: 7, username: 'ada', avatar_url: null, role: 'admin' } as Record<string, unknown> | null,+ settings: { default_currency: 'EUR', time_format: '24h', distance_unit: 'metric', temperature_unit: 'celsius', blur_booking_codes: true } as Record<string, unknown>,+ trip: null as Record<string, unknown> | null,+}));+vi.mock('react-router-dom', () => ({ useNavigate: () => navigate }));vi.mock('../shared/Toast', () => ({ useToast: () => toast }));vi.mock('../../i18n', () => ({ useTranslation: () => ({ locale: 'en', t: (k: string) => k }) }));-vi.mock('../../store/authStore', () => ({ useAuthStore: (sel: (s: unknown) => unknown) => sel({ user: { id: 7, username: 'ada', avatar_url: null, role: 'admin' } }) }));-vi.mock('../../store/settingsStore', () => ({ useSettingsStore: (sel: (s: unknown) => unknown) => sel({ settings: { default_currency: 'EUR', time_format: '24h', distance_unit: 'metric', temperature_unit: 'celsius', blur_booking_codes: true } }) }));+vi.mock('../../store/authStore', () => ({ useAuthStore: (sel: (s: unknown) => unknown) => sel({ user: host.user }) }));+vi.mock('../../store/settingsStore', () => ({ useSettingsStore: (sel: (s: unknown) => unknown) => sel({ settings: host.settings }) }));+vi.mock('../../store/tripStore', () => ({ useTripStore: (sel: (s: unknown) => unknown) => sel({ trip: host.trip }) }));vi.mock('../../api/client', () => ({ pluginsApi: { invoke: (id: string, sub: string, init?: unknown) => invoke(id, sub, init) } }));vi.mock('../../api/websocket', () => ({addListener: (fn: (ev: Record<string, unknown>) => void) => wsListeners.add(fn),@@ -23,6 +34,19 @@ function fromFrame(frame: HTMLIFrameElement, data: unknown) {window.dispatchEvent(new MessageEvent('message', { source: frame.contentWindow, data } as MessageEventInit));}+/** Mount a frame and capture everything the host posts into it. */+function mountFrame(props: Partial<Parameters<typeof PluginFrame>[0]> = {}) {+ const view = render(<PluginFrame pluginId="demo" {...props} />);+ const iframe = view.container.querySelector('iframe')!;+ const posted: Array<Record<string, unknown>> = [];+ (iframe.contentWindow as unknown as { postMessage: (m: unknown) => void }).postMessage = (m: unknown) =>+ posted.push(m as Record<string, unknown>);+ return { ...view, iframe, posted };+}++const answerFor = (posted: Array<Record<string, unknown>>, requestId: string) =>+ posted.find((m) => m.requestId === requestId);+afterEach(() => {cleanup();sessionStorage.clear();@@ -30,6 +54,17 @@ afterEach(() => {Object.values(toast).forEach((f) => f.mockClear());invoke.mockClear();wsListeners.clear();+ host.user = { ...DEFAULT_USER };+ host.settings = { ...DEFAULT_SETTINGS };+ host.trip = null;+ const html = document.documentElement;+ html.classList.remove('dark');+ html.removeAttribute('dir');+ html.removeAttribute('style');+ html.removeAttribute('data-scheme');+ html.removeAttribute('data-density');+ html.removeAttribute('data-no-transparency');+ html.removeAttribute('data-reduce-motion');});describe('PluginFrame', () => {@@ -317,6 +352,66 @@ describe('PluginFrame', () => {expect(posted.length).toBe(before);expect(geo.clearWatch).toHaveBeenCalledWith(7);});++ it('FE-PLUGINS-FRAME-023: a request without a requestId is dropped before the browser API', () => {+ const { iframe, posted } = mount(true);+ fromFrame(iframe, { type: 'trek:geolocation' });+ fromFrame(iframe, { type: 'trek:geolocation', requestId: '' });+ expect(posted.filter((m) => m.type === 'trek:geolocation:result')).toHaveLength(0);+ expect(geo.getCurrentPosition).not.toHaveBeenCalled();+ });++ it('FE-PLUGINS-FRAME-024: reports "unsupported" when the browser has no geolocation', () => {+ const own = Object.getOwnPropertyDescriptor(navigator, 'geolocation');+ delete (navigator as unknown as { geolocation?: unknown }).geolocation;+ try {+ const { iframe, posted } = mount(true);+ fromFrame(iframe, { type: 'trek:geolocation', requestId: 'g7' });+ expect(answerFor(posted, 'g7')).toMatchObject({ error: 'unsupported' });+ } finally {+ if (own) Object.defineProperty(navigator, 'geolocation', own);+ }+ });++ it('FE-PLUGINS-FRAME-025: maps the browser error codes onto the bridge vocabulary', () => {+ const codes: Array<[number, string]> = [[1, 'denied'], [3, 'timeout'], [2, 'unavailable']];+ for (const [code, expected] of codes) {+ geo.getCurrentPosition.mockImplementation((_ok: unknown, fail: (e: unknown) => void) =>+ fail({ code, PERMISSION_DENIED: 1, POSITION_UNAVAILABLE: 2, TIMEOUT: 3 }));+ const { iframe, posted, unmount } = mount(true);+ fromFrame(iframe, { type: 'trek:geolocation', requestId: `e${code}` });+ expect(answerFor(posted, `e${code}`)).toMatchObject({ error: expected });+ unmount();+ }+ });++ it('FE-PLUGINS-FRAME-026: a watch error is streamed as an update, not a result', () => {+ let boom: ((e: unknown) => void) | null = null;+ geo.watchPosition.mockImplementation((_ok: unknown, fail: (e: unknown) => void) => { boom = fail; return 7; });+ const { iframe, posted } = mount(true);++ fromFrame(iframe, { type: 'trek:geolocation', requestId: 'g8', action: 'watch' });+ act(() => boom!({ code: 3, PERMISSION_DENIED: 1, TIMEOUT: 3 }));++ expect(posted.find((m) => m.type === 'trek:geolocation:update')).toMatchObject({ error: 'timeout' });+ });++ it('FE-PLUGINS-FRAME-027: a second watch replaces the first one', () => {+ const { iframe } = mount(true);+ fromFrame(iframe, { type: 'trek:geolocation', requestId: 'g9', action: 'watch' });+ expect(geo.clearWatch).not.toHaveBeenCalled();++ fromFrame(iframe, { type: 'trek:geolocation', requestId: 'g10', action: 'watch' });+ expect(geo.clearWatch).toHaveBeenCalledWith(7);+ expect(geo.watchPosition).toHaveBeenCalledTimes(2);+ });++ it('FE-PLUGINS-FRAME-028: clear without a running watch still confirms', () => {+ const { iframe, posted } = mount(true);+ fromFrame(iframe, { type: 'trek:geolocation', requestId: 'g11', action: 'clear' });+ expect(geo.clearWatch).not.toHaveBeenCalled();+ expect(answerFor(posted, 'g11')).toMatchObject({ cleared: true });+ });});it('FE-PLUGINS-FRAME-020: brokered plugin session state round-trips through host sessionStorage', () => {diff --git a/client/src/components/Plugins/PluginWidgets.test.tsx b/client/src/components/Plugins/PluginWidgets.test.tsxnew file mode 100644index 000000000..cee93132b--- /dev/null+++ b/client/src/components/Plugins/PluginWidgets.test.tsx@@ -0,0 +1,59 @@+// FE-W4PW-001 to FE-W4PW-005+import { describe, it, expect, vi } from 'vitest'+import { render, screen } from '../../../tests/helpers/render'+import type { ActivePlugin } from '../../store/pluginStore'++vi.mock('./PluginFrame', () => ({+ default: ({ pluginId, tripId, title }: { pluginId: string; tripId: string | null; title?: string }) =>+ <div data-testid="frame" data-plugin={pluginId} data-trip={tripId ?? ''} data-title={title} />,+}))++import PluginWidgets from './PluginWidgets'++function plugin(overrides: Partial<ActivePlugin> = {}): ActivePlugin {+ return { id: 'weather', name: 'Weather', icon: 'CloudSun', ...overrides } as unknown as ActivePlugin+}++describe('PluginWidgets', () => {+ it('FE-W4PW-001: renders nothing without active widget plugins', () => {+ const { container } = render(<PluginWidgets plugins={[]} />)+ expect(container).toBeEmptyDOMElement()+ })++ it('FE-W4PW-002: renders one card per plugin with its name', () => {+ render(<PluginWidgets plugins={[plugin(), plugin({ id: 'fx', name: 'Currency' })]} />)++ expect(screen.getByText('Weather')).toBeInTheDocument()+ expect(screen.getByText('Currency')).toBeInTheDocument()+ expect(screen.getAllByTestId('frame')).toHaveLength(2)+ })++ it('FE-W4PW-003: hands each card its own sandboxed frame', () => {+ render(<PluginWidgets plugins={[plugin()]} />)+ const frame = screen.getByTestId('frame')++ expect(frame).toHaveAttribute('data-plugin', 'weather')+ expect(frame).toHaveAttribute('data-title', 'Weather')+ })++ it('FE-W4PW-004: defaults the trip context to null and forwards a given tripId', () => {+ const { unmount } = render(<PluginWidgets plugins={[plugin()]} />)+ expect(screen.getByTestId('frame')).toHaveAttribute('data-trip', '')+ unmount()++ render(<PluginWidgets plugins={[plugin()]} tripId="42" />)+ expect(screen.getByTestId('frame')).toHaveAttribute('data-trip', '42')+ })++ it('FE-W4PW-005: gives the body a pre-resize minimum height', () => {+ render(<PluginWidgets plugins={[plugin()]} />)++ expect(screen.getByTestId('frame').parentElement).toHaveStyle({ minHeight: '60px' })+ })++ it('FE-W4PW-006: renders the plugin icon in the card header', () => {+ const { container } = render(<PluginWidgets plugins={[plugin()]} />)++ expect(container.querySelector('.lucide-cloud-sun')).not.toBeNull()+ })+})diff --git a/client/src/components/Plugins/TripCardBadges.test.tsx b/client/src/components/Plugins/TripCardBadges.test.tsxnew file mode 100644index 000000000..20130e8ee--- /dev/null+++ b/client/src/components/Plugins/TripCardBadges.test.tsx@@ -0,0 +1,122 @@+// FE-W4TCB-001 to FE-W4TCB-011+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { renderHook, waitFor } from '@testing-library/react'+import { render, screen, fireEvent } from '../../../tests/helpers/render'+import type { TripCardBadge } from '../../api/client'++const tripCardContributions = vi.fn(async (_ids: Array<number | string>) => ({ contributions: [] as TripCardBadge[] }))++vi.mock('../../api/client', () => ({+ pluginsApi: { tripCardContributions: (ids: Array<number | string>) => tripCardContributions(ids) },+}))++import { TripCardBadges, useTripCardBadges } from './TripCardBadges'++function badge(overrides: Partial<TripCardBadge> = {}): TripCardBadge {+ return { pluginId: 'p1', tripId: 1, id: 'b1', label: 'CO2', value: '12 kg', tone: 'default', ...overrides }+}++beforeEach(() => {+ tripCardContributions.mockReset()+ tripCardContributions.mockResolvedValue({ contributions: [] })+})++describe('useTripCardBadges', () => {+ it('FE-W4TCB-001: fetches all visible trip ids in one call and buckets by trip', async () => {+ tripCardContributions.mockResolvedValue({+ contributions: [+ badge({ tripId: 1, id: 'a' }),+ badge({ tripId: 2, id: 'b' }),+ badge({ tripId: 1, id: 'c' }),+ ],+ })++ const { result } = renderHook(() => useTripCardBadges([1, 2], true))++ await waitFor(() => expect(result.current(1)).toHaveLength(2))+ expect(tripCardContributions).toHaveBeenCalledExactlyOnceWith([1, 2])+ expect(result.current(1).map(b => b.id)).toEqual(['a', 'c'])+ expect(result.current(2).map(b => b.id)).toEqual(['b'])+ })++ it('FE-W4TCB-002: returns a stable empty array for a trip with no badges', async () => {+ tripCardContributions.mockResolvedValue({ contributions: [badge({ tripId: 1 })] })+ const { result } = renderHook(() => useTripCardBadges([1], true))++ await waitFor(() => expect(result.current(1)).toHaveLength(1))+ expect(result.current(99)).toBe(result.current(98))+ })++ it('FE-W4TCB-003: never hits the endpoint when no plugin is active', () => {+ renderHook(() => useTripCardBadges([1, 2], false))+ expect(tripCardContributions).not.toHaveBeenCalled()+ })++ it('FE-W4TCB-004: never hits the endpoint for an empty dashboard', () => {+ renderHook(() => useTripCardBadges([], true))+ expect(tripCardContributions).not.toHaveBeenCalled()+ })++ it('FE-W4TCB-005: yields an empty lookup when the endpoint fails', async () => {+ tripCardContributions.mockRejectedValue(new Error('boom'))+ const { result } = renderHook(() => useTripCardBadges([1], true))++ await waitFor(() => expect(tripCardContributions).toHaveBeenCalled())+ expect(result.current(1)).toEqual([])+ })++ it('FE-W4TCB-006: tolerates a response without a contributions array', async () => {+ tripCardContributions.mockResolvedValue({} as { contributions: TripCardBadge[] })+ const { result } = renderHook(() => useTripCardBadges([1], true))++ await waitFor(() => expect(tripCardContributions).toHaveBeenCalled())+ expect(result.current(1)).toEqual([])+ })++ it('FE-W4TCB-007: refetches when the visible id set changes', async () => {+ const { rerender } = renderHook(({ ids }: { ids: number[] }) => useTripCardBadges(ids, true), {+ initialProps: { ids: [1] },+ })+ await waitFor(() => expect(tripCardContributions).toHaveBeenCalledTimes(1))++ rerender({ ids: [1, 2] })+ await waitFor(() => expect(tripCardContributions).toHaveBeenCalledTimes(2))+ expect(tripCardContributions).toHaveBeenLastCalledWith([1, 2])+ })+})++describe('TripCardBadges', () => {+ it('FE-W4TCB-008: renders nothing when no plugin contributes', () => {+ const { container } = render(<TripCardBadges items={[]} />)+ expect(container).toBeEmptyDOMElement()+ })++ it('FE-W4TCB-009: renders a plain chip with label, value and tone class', () => {+ const { container } = render(<TripCardBadges items={[badge({ tone: 'warn' })]} />)++ expect(screen.getByText('CO2')).toBeInTheDocument()+ expect(screen.getByText('12 kg')).toBeInTheDocument()+ expect(container.querySelector('.trip-plugin-badge')).toHaveClass('tone-warn')+ })++ it('FE-W4TCB-010: omits the value span when the badge carries none', () => {+ const { container } = render(<TripCardBadges items={[badge({ value: undefined }), badge({ id: 'b2', value: '' })]} />)++ expect(container.querySelectorAll('.badge-value')).toHaveLength(0)+ expect(container.querySelectorAll('.badge-label')).toHaveLength(2)+ })++ it('FE-W4TCB-011: renders a url badge as a safe new-tab link that does not open the card', () => {+ render(<TripCardBadges items={[badge({ url: 'https://example.com/report' })]} />)+ const link = screen.getByRole('link')++ expect(link).toHaveAttribute('href', 'https://example.com/report')+ expect(link).toHaveAttribute('target', '_blank')+ expect(link).toHaveAttribute('rel', 'noreferrer noopener')++ const click = new MouseEvent('click', { bubbles: true, cancelable: true })+ const stopped = vi.spyOn(click, 'stopPropagation')+ fireEvent(link, click)+ expect(stopped).toHaveBeenCalled()+ })+})diff --git a/client/src/components/Settings/AccountTab.test.tsx b/client/src/components/Settings/AccountTab.test.tsxindex 28bfba361..54a0abe2c 100644--- a/client/src/components/Settings/AccountTab.test.tsx+++ b/client/src/components/Settings/AccountTab.test.tsx@@ -1,5 +1,5 @@-// FE-COMP-ACCOUNT-001 to FE-COMP-ACCOUNT-012-import { render, screen, waitFor } from '../../../tests/helpers/render';+// FE-COMP-ACCOUNT-001 to FE-COMP-ACCOUNT-069+import { render, screen, waitFor, fireEvent } from '../../../tests/helpers/render';import userEvent from '@testing-library/user-event';import { http, HttpResponse } from 'msw';import { server } from '../../../tests/helpers/msw/server';@@ -534,3 +534,349 @@ describe('AccountTab – Role / OIDC display', () => {expect(screen.getByText('SSO')).toBeInTheDocument();});});++// ── Backup codes handoff (049–055) ────────────────────────────────────────────++const BACKUP_KEY = 'trek_mfa_backup_codes_pending';++function seedMfaUser() {+ seedStore(useAuthStore, {+ user: buildUser({ username: 'testuser', email: '[email protected]', mfa_enabled: true }),+ });+}++describe('AccountTab – Backup codes', () => {+ it('FE-COMP-ACCOUNT-049: a corrupt sessionStorage payload is dropped instead of rendered', async () => {+ sessionStorage.setItem(BACKUP_KEY, 'not-json');+ seedMfaUser();+ render(<AccountTab />);++ await waitFor(() => expect(sessionStorage.getItem(BACKUP_KEY)).toBeNull());+ expect(screen.queryByText('Backup codes')).not.toBeInTheDocument();+ });++ it('FE-COMP-ACCOUNT-050: a payload that is not a list of codes is ignored but kept', () => {+ sessionStorage.setItem(BACKUP_KEY, JSON.stringify({ codes: ['AAAA-1111'] }));+ seedMfaUser();+ render(<AccountTab />);++ expect(screen.queryByText('Backup codes')).not.toBeInTheDocument();+ expect(sessionStorage.getItem(BACKUP_KEY)).not.toBeNull();+ });++ it('FE-COMP-ACCOUNT-051: a blocked clipboard toasts an error', async () => {+ const user = userEvent.setup();+ Object.defineProperty(navigator, 'clipboard', {+ value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) },+ writable: true,+ configurable: true,+ });+ sessionStorage.setItem(BACKUP_KEY, JSON.stringify(['AAAA-1111']));+ seedMfaUser();+ render(<><ToastContainer /><AccountTab /></>);++ await user.click(await screen.findByRole('button', { name: 'Copy codes' }));++ await screen.findByText('Error');+ });++ it('FE-COMP-ACCOUNT-052: Download TXT builds a blob, names the file and revokes the URL', async () => {+ const user = userEvent.setup();+ const createObjectURL = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:codes');+ const revokeObjectURL = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});+ let downloadName = '';+ const anchorClick = vi+ .spyOn(HTMLAnchorElement.prototype, 'click')+ .mockImplementation(function (this: HTMLAnchorElement) {+ downloadName = this.download;+ });+ sessionStorage.setItem(BACKUP_KEY, JSON.stringify(['AAAA-1111']));+ seedMfaUser();+ render(<AccountTab />);++ await user.click(await screen.findByRole('button', { name: 'Download TXT' }));++ expect(createObjectURL).toHaveBeenCalledWith(expect.any(Blob));+ expect(downloadName).toBe('trek-mfa-backup-codes.txt');+ expect(revokeObjectURL).toHaveBeenCalledWith('blob:codes');+ expect(document.querySelector('a[download]')).toBeNull();++ createObjectURL.mockRestore();+ revokeObjectURL.mockRestore();+ anchorClick.mockRestore();+ });++ it('FE-COMP-ACCOUNT-053: Print writes the codes into the popup and triggers print', async () => {+ const user = userEvent.setup();+ const written: string[] = [];+ const print = vi.fn();+ const popup = {+ document: { open: vi.fn(), write: (html: string) => written.push(html), close: vi.fn() },+ focus: vi.fn(),+ print,+ };+ const openSpy = vi.spyOn(window, 'open').mockReturnValue(popup as unknown as Window);+ sessionStorage.setItem(BACKUP_KEY, JSON.stringify(['AAAA-1111', 'BBBB-2222']));+ seedMfaUser();+ render(<AccountTab />);++ await user.click(await screen.findByRole('button', { name: 'Print / PDF' }));++ expect(openSpy).toHaveBeenCalledWith('', '_blank', 'width=900,height=700');+ expect(written.join('')).toContain('AAAA-1111\nBBBB-2222');+ expect(popup.document.close).toHaveBeenCalled();+ expect(print).toHaveBeenCalled();+ openSpy.mockRestore();+ });++ it('FE-COMP-ACCOUNT-054: a blocked popup leaves printing a no-op', async () => {+ const user = userEvent.setup();+ const openSpy = vi.spyOn(window, 'open').mockReturnValue(null);+ sessionStorage.setItem(BACKUP_KEY, JSON.stringify(['AAAA-1111']));+ seedMfaUser();+ render(<AccountTab />);++ await user.click(await screen.findByRole('button', { name: 'Print / PDF' }));++ expect(openSpy).toHaveBeenCalled();+ expect(screen.getByText('Backup codes')).toBeInTheDocument();+ openSpy.mockRestore();+ });++ it('FE-COMP-ACCOUNT-055: dismissing the codes also clears sessionStorage', async () => {+ const user = userEvent.setup();+ sessionStorage.setItem(BACKUP_KEY, JSON.stringify(['AAAA-1111']));+ seedMfaUser();+ render(<AccountTab />);++ await user.click(await screen.findByRole('button', { name: 'OK' }));++ expect(sessionStorage.getItem(BACKUP_KEY)).toBeNull();+ expect(screen.queryByText('Backup codes')).not.toBeInTheDocument();+ });+});++// ── Avatar upload / removal (056–060) ─────────────────────────────────────────++describe('AccountTab – Avatar upload', () => {+ it('FE-COMP-ACCOUNT-056: picking a file uploads it and resets the input', async () => {+ const user = userEvent.setup();+ const uploadAvatar = vi.fn().mockResolvedValue(undefined);+ seedStore(useAuthStore, { uploadAvatar });+ render(<><ToastContainer /><AccountTab /></>);++ const input = document.querySelector('input[type="file"]') as HTMLInputElement;+ const file = new File(['avatar'], 'me.png', { type: 'image/png' });+ await user.upload(input, file);++ expect(uploadAvatar).toHaveBeenCalledWith(file);+ await screen.findByText('Profile picture updated');+ expect(input.value).toBe('');+ });++ it('FE-COMP-ACCOUNT-057: a failing upload toasts the avatar error', async () => {+ const user = userEvent.setup();+ seedStore(useAuthStore, { uploadAvatar: vi.fn().mockRejectedValue(new Error('too big')) });+ render(<><ToastContainer /><AccountTab /></>);++ const input = document.querySelector('input[type="file"]') as HTMLInputElement;+ await user.upload(input, new File(['avatar'], 'me.png', { type: 'image/png' }));++ await screen.findByText('Upload failed');+ });++ it('FE-COMP-ACCOUNT-058: a change event without a file uploads nothing', () => {+ const uploadAvatar = vi.fn().mockResolvedValue(undefined);+ seedStore(useAuthStore, { uploadAvatar });+ render(<AccountTab />);++ fireEvent.change(document.querySelector('input[type="file"]') as HTMLInputElement);++ expect(uploadAvatar).not.toHaveBeenCalled();+ });++ it('FE-COMP-ACCOUNT-059: the remove button deletes the avatar', async () => {+ const user = userEvent.setup();+ const deleteAvatar = vi.fn().mockResolvedValue(undefined);+ seedStore(useAuthStore, {+ user: buildUser({ username: 'testuser', email: '[email protected]', avatar_url: 'https://example.com/a.jpg' }),+ deleteAvatar,+ });+ render(<><ToastContainer /><AccountTab /></>);++ const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;+ const removeBtn = fileInput.parentElement!.querySelectorAll('button')[1];+ await user.click(removeBtn);++ expect(deleteAvatar).toHaveBeenCalled();+ await screen.findByText('Profile picture removed');+ });++ it('FE-COMP-ACCOUNT-060: a failing removal toasts the avatar error', async () => {+ const user = userEvent.setup();+ seedStore(useAuthStore, {+ user: buildUser({ username: 'testuser', email: '[email protected]', avatar_url: 'https://example.com/a.jpg' }),+ deleteAvatar: vi.fn().mockRejectedValue(new Error('nope')),+ });+ render(<><ToastContainer /><AccountTab /></>);++ const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;+ await user.click(fileInput.parentElement!.querySelectorAll('button')[1]);++ await screen.findByText('Upload failed');+ });+});++// ── MFA error paths (061–064) ─────────────────────────────────────────────────++describe('AccountTab – MFA error paths', () => {+ it('FE-COMP-ACCOUNT-061: a failing MFA setup surfaces the server error', async () => {+ const user = userEvent.setup();+ server.use(+ http.post('/api/auth/mfa/setup', () => HttpResponse.json({ error: 'Setup unavailable' }, { status: 500 })),+ );+ render(<><ToastContainer /><AccountTab /></>);++ await user.click(screen.getByText('Set up authenticator'));++ await screen.findByText('Setup unavailable');+ expect(screen.getByText('Set up authenticator')).toBeInTheDocument();+ });++ it('FE-COMP-ACCOUNT-062: cancelling the setup drops the QR code and the secret', async () => {+ const user = userEvent.setup();+ server.use(+ http.post('/api/auth/mfa/setup', () => HttpResponse.json({ qr_svg: '<svg>qr</svg>', secret: 'ABCDEF123' })),+ );+ render(<AccountTab />);++ await user.click(screen.getByText('Set up authenticator'));+ await screen.findByText('ABCDEF123');+ await user.click(screen.getByRole('button', { name: 'Cancel' }));++ expect(screen.queryByText('ABCDEF123')).not.toBeInTheDocument();+ expect(screen.getByText('Set up authenticator')).toBeInTheDocument();+ });++ it('FE-COMP-ACCOUNT-063: a rejected enable keeps the QR step and toasts the error', async () => {+ const user = userEvent.setup();+ server.use(+ http.post('/api/auth/mfa/setup', () => HttpResponse.json({ qr_svg: '<svg>qr</svg>', secret: 'ABCDEF123' })),+ http.post('/api/auth/mfa/enable', () => HttpResponse.json({ error: 'Invalid code' }, { status: 400 })),+ );+ render(<><ToastContainer /><AccountTab /></>);++ await user.click(screen.getByText('Set up authenticator'));+ await screen.findByText('ABCDEF123');+ await user.type(screen.getByPlaceholderText('6-digit code'), '123456');+ await user.click(screen.getByRole('button', { name: 'Enable 2FA' }));++ await screen.findByText('Invalid code');+ expect(screen.getByText('ABCDEF123')).toBeInTheDocument();+ });++ it('FE-COMP-ACCOUNT-064: a rejected disable toasts the error and keeps 2FA on', async () => {+ const user = userEvent.setup();+ seedMfaUser();+ server.use(+ http.post('/api/auth/mfa/disable', () => HttpResponse.json({ error: 'Wrong code' }, { status: 400 })),+ );+ render(<><ToastContainer /><AccountTab /></>);++ const passwordInputs = document.querySelectorAll('input[type="password"]');+ await user.type(passwordInputs[passwordInputs.length - 1], 'mypassword');+ await user.type(screen.getByPlaceholderText('6-digit code'), '123456');+ await user.click(screen.getByRole('button', { name: 'Disable 2FA' }));++ await screen.findByText('Wrong code');+ expect(screen.getByText('2FA is enabled on your account.')).toBeInTheDocument();+ });+});++// ── Modals, hover and field edits (065–068) ───────────────────────────────────++function backdropOf(title: string): HTMLElement {+ return screen.getByText(title).closest('div[class*="rgba"]') as HTMLElement;+}++describe('AccountTab – Modals and field edits', () => {+ it('FE-COMP-ACCOUNT-065: the confirm modal closes on the backdrop but not on the card', async () => {+ const user = userEvent.setup();+ render(<AccountTab />);+ await user.click(screen.getByText('Delete account'));+ await screen.findByText('Delete your account?');++ await user.click(screen.getByText('Delete your account?'));+ expect(screen.getByText('Delete your account?')).toBeInTheDocument();++ fireEvent.click(backdropOf('Delete your account?'));+ expect(screen.queryByText('Delete your account?')).not.toBeInTheDocument();+ });++ it('FE-COMP-ACCOUNT-066: the blocked modal closes on the backdrop', async () => {+ const user = userEvent.setup();+ seedStore(useAuthStore, {+ user: buildUser({ username: 'testuser', email: '[email protected]', role: 'admin' }),+ });+ render(<AccountTab />);+ await user.click(screen.getByText('Delete account'));+ await screen.findByText('Deletion not possible');++ fireEvent.click(backdropOf('Deletion not possible'));++ expect(screen.queryByText('Deletion not possible')).not.toBeInTheDocument();+ });++ it('FE-COMP-ACCOUNT-067: a failing deletion toasts the error and closes the modal', async () => {+ const user = userEvent.setup();+ const logout = vi.fn();+ seedStore(useAuthStore, {+ user: buildUser({ username: 'testuser', email: '[email protected]', role: 'user' }),+ logout,+ });+ server.use(+ http.delete('/api/auth/me', () => HttpResponse.json({ error: 'Account is locked' }, { status: 400 })),+ );+ render(<><ToastContainer /><AccountTab /></>);++ await user.click(screen.getByText('Delete account'));+ await screen.findByText('Delete your account?');+ await user.click(screen.getByText('Delete permanently'));++ await screen.findByText('Account is locked');+ expect(logout).not.toHaveBeenCalled();+ expect(screen.queryByText('Delete your account?')).not.toBeInTheDocument();+ });++ it('FE-COMP-ACCOUNT-068: editing the email field feeds the profile save', async () => {+ const user = userEvent.setup();+ const updateProfile = vi.fn().mockResolvedValue(undefined);+ seedStore(useAuthStore, { updateProfile });+ render(<AccountTab />);++ const emailInput = screen.getByDisplayValue('[email protected]');+ await user.clear(emailInput);+ await user.type(emailInput, '[email protected]');+ await user.click(screen.getByRole('button', { name: /save profile/i }));++ expect(updateProfile).toHaveBeenCalledWith({ username: 'testuser', email: '[email protected]' });+ });++ it('FE-COMP-ACCOUNT-069: hover styling on the password and camera buttons is reverted on leave', () => {+ render(<AccountTab />);++ const passwordBtn = screen.getByText('Update password').closest('button') as HTMLElement;+ fireEvent.mouseEnter(passwordBtn);+ expect(passwordBtn.style.background).toBe('var(--bg-hover)');+ fireEvent.mouseLeave(passwordBtn);+ expect(passwordBtn.style.background).toBe('var(--bg-card)');++ const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;+ const cameraBtn = fileInput.nextElementSibling as HTMLElement;+ fireEvent.mouseEnter(cameraBtn);+ expect(cameraBtn.style.transform).toBe('scale(1.15)');+ fireEvent.mouseLeave(cameraBtn);+ expect(cameraBtn.style.transform).toBe('scale(1)');+ expect(cameraBtn.style.opacity).toBe('1');+ });+});diff --git a/client/src/components/Settings/AirTrailConnectionSection.test.tsx b/client/src/components/Settings/AirTrailConnectionSection.test.tsxnew file mode 100644index 000000000..753f7cf77--- /dev/null+++ b/client/src/components/Settings/AirTrailConnectionSection.test.tsx@@ -0,0 +1,309 @@+// FE-COMP-AIRTRAIL-001 to FE-COMP-AIRTRAIL-016+import { render, screen, waitFor } from '../../../tests/helpers/render';+import userEvent from '@testing-library/user-event';+import { http, HttpResponse } from 'msw';+import { server } from '../../../tests/helpers/msw/server';+import { resetAllStores } from '../../../tests/helpers/store';+import { ToastContainer } from '../shared/Toast';+import AirTrailConnectionSection from './AirTrailConnectionSection';++interface SavedBody {+ url: string;+ apiKey?: string;+ allowInsecureTls?: boolean;+ writeEnabled?: boolean;+}++function stubSettings(over: Record<string, unknown> = {}) {+ server.use(+ http.get('/api/integrations/airtrail/settings', () =>+ HttpResponse.json({ url: '', allowInsecureTls: false, writeEnabled: false, connected: false, ...over }),+ ),+ );+}++function renderSection() {+ return render(+ <>+ <ToastContainer />+ <AirTrailConnectionSection />+ </>,+ );+}++// The desktop ToggleSwitch has no accessible name, so reach it through the label+// text it sits next to.+function toggleNextTo(label: string): HTMLElement {+ const row = screen.getByText(label).parentElement as HTMLElement;+ return row.querySelector('button') as HTMLElement;+}++beforeEach(() => {+ resetAllStores();+ vi.clearAllMocks();+ stubSettings();+});++describe('AirTrailConnectionSection', () => {+ it('FE-COMP-AIRTRAIL-001: hydrates url, toggles and the connected badge from the stored settings', async () => {+ stubSettings({ url: 'https://air.example.com', allowInsecureTls: true, writeEnabled: true, connected: true });+ renderSection();++ expect(await screen.findByDisplayValue('https://air.example.com')).toBeInTheDocument();+ expect(toggleNextTo('Allow self-signed certificates')).toHaveAttribute('aria-pressed', 'true');+ expect(toggleNextTo('Write changes back to AirTrail')).toHaveAttribute('aria-pressed', 'true');+ expect(screen.getByText('Connected')).toBeInTheDocument();+ });++ it('FE-COMP-AIRTRAIL-002: an unconfigured instance renders empty, disconnected and with both actions blocked', async () => {+ renderSection();++ await waitFor(() => expect(screen.getByRole('button', { name: /Test connection/ })).toBeDisabled());+ expect(screen.getByRole('button', { name: /^Save$/ })).toBeDisabled();+ expect(screen.getByText('Not connected')).toBeInTheDocument();+ expect(screen.getByPlaceholderText('Bearer API key')).toHaveValue('');+ expect(toggleNextTo('Allow self-signed certificates')).toHaveAttribute('aria-pressed', 'false');+ });++ it('FE-COMP-AIRTRAIL-003: a stored key is only masked by the placeholder, never prefilled', async () => {+ stubSettings({ url: 'https://air.example.com', connected: true });+ renderSection();++ const keyInput = await screen.findByPlaceholderText('••••••••');+ expect(keyInput).toHaveValue('');+ });++ it('FE-COMP-AIRTRAIL-004: a failing settings fetch still ends the loading state', async () => {+ server.use(+ http.get('/api/integrations/airtrail/settings', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),+ );+ renderSection();++ // Test stays disabled for the missing URL, but the buttons leave the `loading` lock.+ await waitFor(() => expect(screen.getByRole('button', { name: /Test connection/ })).toBeDisabled());+ expect(screen.getByText('Not connected')).toBeInTheDocument();+ expect(screen.getByPlaceholderText('https://airtrail.example.com')).toHaveValue('');+ });++ it('FE-COMP-AIRTRAIL-005: Save unlocks once a URL and a key are typed', async () => {+ const user = userEvent.setup();+ renderSection();++ const saveBtn = await screen.findByRole('button', { name: /^Save$/ });+ await waitFor(() => expect(saveBtn).toBeDisabled());++ await user.type(screen.getByPlaceholderText('https://airtrail.example.com'), 'https://air.example.com');+ expect(saveBtn).toBeDisabled();++ await user.type(screen.getByPlaceholderText('Bearer API key'), 'secret');+ expect(saveBtn).toBeEnabled();+ });++ it('FE-COMP-AIRTRAIL-006: a connected instance saves without retyping the key', async () => {+ const user = userEvent.setup();+ let body: SavedBody | undefined;+ stubSettings({ url: 'https://air.example.com', connected: true });+ server.use(+ http.put('/api/integrations/airtrail/settings', async ({ request }) => {+ body = (await request.json()) as SavedBody;+ return HttpResponse.json({ ok: true });+ }),+ http.get('/api/integrations/airtrail/status', () => HttpResponse.json({ connected: true })),+ );+ renderSection();++ await screen.findByDisplayValue('https://air.example.com');+ await user.click(screen.getByRole('button', { name: /^Save$/ }));++ await screen.findByText('AirTrail connection saved');+ expect(body).toEqual({ url: 'https://air.example.com', allowInsecureTls: false, writeEnabled: false });+ });++ it('FE-COMP-AIRTRAIL-007: a typed key and both toggles are sent along, then the key field is cleared', async () => {+ const user = userEvent.setup();+ let body: SavedBody | undefined;+ server.use(+ http.put('/api/integrations/airtrail/settings', async ({ request }) => {+ body = (await request.json()) as SavedBody;+ return HttpResponse.json({ ok: true });+ }),+ http.get('/api/integrations/airtrail/status', () => HttpResponse.json({ connected: true })),+ );+ renderSection();++ await user.type(await screen.findByPlaceholderText('https://airtrail.example.com'), ' https://air.example.com ');+ await user.type(screen.getByPlaceholderText('Bearer API key'), ' tok-123 ');+ await user.click(toggleNextTo('Allow self-signed certificates'));+ await user.click(toggleNextTo('Write changes back to AirTrail'));+ await user.click(screen.getByRole('button', { name: /^Save$/ }));++ await waitFor(() =>+ expect(body).toEqual({+ url: 'https://air.example.com',+ allowInsecureTls: true,+ writeEnabled: true,+ apiKey: 'tok-123',+ }),+ );+ await waitFor(() => expect(screen.getByPlaceholderText('••••••••')).toHaveValue(''));+ expect(screen.getByText('Connected')).toBeInTheDocument();+ });++ it('FE-COMP-AIRTRAIL-008: a warning from the server replaces the success toast', async () => {+ const user = userEvent.setup();+ stubSettings({ url: 'https://air.example.com', connected: true });+ server.use(+ http.put('/api/integrations/airtrail/settings', () => HttpResponse.json({ warning: 'TLS verification is off' })),+ http.get('/api/integrations/airtrail/status', () => HttpResponse.json({ connected: true })),+ );+ renderSection();++ await screen.findByDisplayValue('https://air.example.com');+ await user.click(screen.getByRole('button', { name: /^Save$/ }));++ await screen.findByText('TLS verification is off');+ expect(screen.queryByText('AirTrail connection saved')).not.toBeInTheDocument();+ });++ it('FE-COMP-AIRTRAIL-009: a failing status probe after a successful save marks the connection dead', async () => {+ const user = userEvent.setup();+ stubSettings({ url: 'https://air.example.com', connected: true });+ server.use(+ http.put('/api/integrations/airtrail/settings', () => HttpResponse.json({ ok: true })),+ http.get('/api/integrations/airtrail/status', () => HttpResponse.json({ error: 'down' }, { status: 500 })),+ );+ renderSection();++ await screen.findByDisplayValue('https://air.example.com');+ await user.click(screen.getByRole('button', { name: /^Save$/ }));++ await screen.findByText('Not connected');+ });++ it('FE-COMP-AIRTRAIL-010: a rejected save surfaces the server error message', async () => {+ const user = userEvent.setup();+ stubSettings({ url: 'https://air.example.com', connected: true });+ server.use(+ http.put('/api/integrations/airtrail/settings', () =>+ HttpResponse.json({ error: 'Instance unreachable' }, { status: 400 }),+ ),+ );+ renderSection();++ await screen.findByDisplayValue('https://air.example.com');+ await user.click(screen.getByRole('button', { name: /^Save$/ }));++ await screen.findByText('Instance unreachable');+ });++ it('FE-COMP-AIRTRAIL-011: a save failure without a server message falls back to the generic error', async () => {+ const user = userEvent.setup();+ stubSettings({ url: 'https://air.example.com', connected: true });+ server.use(+ http.put('/api/integrations/airtrail/settings', () => HttpResponse.error()),+ );+ renderSection();++ await screen.findByDisplayValue('https://air.example.com');+ await user.click(screen.getByRole('button', { name: /^Save$/ }));++ await screen.findByText('Could not save the connection');+ });++ it('FE-COMP-AIRTRAIL-012: Save is locked while the request is in flight', async () => {+ const user = userEvent.setup();+ let release!: () => void;+ stubSettings({ url: 'https://air.example.com', connected: true });+ server.use(+ http.put('/api/integrations/airtrail/settings', async () => {+ await new Promise<void>(resolve => {+ release = resolve;+ });+ return HttpResponse.json({ ok: true });+ }),+ http.get('/api/integrations/airtrail/status', () => HttpResponse.json({ connected: true })),+ );+ renderSection();++ await screen.findByDisplayValue('https://air.example.com');+ const saveBtn = screen.getByRole('button', { name: /^Save$/ });+ await user.click(saveBtn);++ await waitFor(() => expect(saveBtn).toBeDisabled());+ release();+ await waitFor(() => expect(saveBtn).toBeEnabled());+ });++ it('FE-COMP-AIRTRAIL-013: a successful test reports the flight count and flips the badge', async () => {+ const user = userEvent.setup();+ let body: { url?: string; apiKey?: string; allowInsecureTls?: boolean } | undefined;+ stubSettings({ url: 'https://air.example.com' });+ server.use(+ http.post('/api/integrations/airtrail/test', async ({ request }) => {+ body = (await request.json()) as { url?: string; allowInsecureTls?: boolean };+ return HttpResponse.json({ connected: true, flightCount: 12 });+ }),+ );+ renderSection();++ await screen.findByDisplayValue('https://air.example.com');+ await user.click(screen.getByRole('button', { name: /Test connection/ }));++ await screen.findByText('Connected — 12 flight(s) found');+ expect(screen.getByText('Connected')).toBeInTheDocument();+ expect(body).toEqual({ url: 'https://air.example.com', allowInsecureTls: false });+ });++ it('FE-COMP-AIRTRAIL-014: a test without a flight count still reports zero', async () => {+ const user = userEvent.setup();+ stubSettings({ url: 'https://air.example.com' });+ server.use(+ http.post('/api/integrations/airtrail/test', () => HttpResponse.json({ connected: true })),+ );+ renderSection();++ await screen.findByDisplayValue('https://air.example.com');+ await user.click(screen.getByRole('button', { name: /Test connection/ }));++ await screen.findByText('Connected — 0 flight(s) found');+ });++ it('FE-COMP-AIRTRAIL-015: a refused test shows the returned error and keeps the badge off', async () => {+ const user = userEvent.setup();+ stubSettings({ url: 'https://air.example.com' });+ server.use(+ http.post('/api/integrations/airtrail/test', () => HttpResponse.json({ connected: false, error: 'Bad token' })),+ );+ renderSection();++ await screen.findByDisplayValue('https://air.example.com');+ await user.click(screen.getByRole('button', { name: /Test connection/ }));++ await screen.findByText('Bad token');+ expect(screen.getByText('Not connected')).toBeInTheDocument();+ });++ it('FE-COMP-AIRTRAIL-016: a network failure during the test falls back to the generic message and shows a spinner', async () => {+ const user = userEvent.setup();+ let release!: () => void;+ stubSettings({ url: 'https://air.example.com' });+ server.use(+ http.post('/api/integrations/airtrail/test', async () => {+ await new Promise<void>(resolve => {+ release = resolve;+ });+ return HttpResponse.json({ error: 'nope' }, { status: 500 });+ }),+ );+ renderSection();++ await screen.findByDisplayValue('https://air.example.com');+ const testBtn = screen.getByRole('button', { name: /Test connection/ });+ await user.click(testBtn);++ await waitFor(() => expect(testBtn).toBeDisabled());+ expect(testBtn.querySelector('.animate-spin')).not.toBeNull();+ release();+ await screen.findByText('Connection failed');+ });+});diff --git a/client/src/components/Settings/AppearanceSettingsTab.test.tsx b/client/src/components/Settings/AppearanceSettingsTab.test.tsxindex 79d452d23..b6b5cfde1 100644--- a/client/src/components/Settings/AppearanceSettingsTab.test.tsx+++ b/client/src/components/Settings/AppearanceSettingsTab.test.tsx@@ -1,6 +1,6 @@// FE-COMP-APPEARANCE-001+ — color mode moved here from DisplaySettingsTab,// plus the new scheme / readability / dashboard-widget controls.-import { render, screen, waitFor } from '../../../tests/helpers/render';+import { render, screen, waitFor, fireEvent } from '../../../tests/helpers/render';import userEvent from '@testing-library/user-event';import { http, HttpResponse } from 'msw';import { server } from '../../../tests/helpers/msw/server';@@ -8,6 +8,7 @@ import { useAuthStore } from '../../store/authStore';import { useSettingsStore } from '../../store/settingsStore';import { resetAllStores, seedStore } from '../../../tests/helpers/store';import { buildUser, buildSettings } from '../../../tests/helpers/factories';+import { ToastContainer } from '../shared/Toast';import AppearanceSettingsTab from './AppearanceSettingsTab';beforeEach(() => {@@ -95,3 +96,206 @@ describe('AppearanceSettingsTab', () => {);});});++// ── Custom accent, sliders, widgets and error paths (010–021) ─────────────────++const PERSIST = { timeout: 1500 } as const;++function seedAppearance(updateSetting = vi.fn().mockResolvedValue(undefined)) {+ seedStore(useSettingsStore, { settings: buildSettings({ dark_mode: 'light', language: 'en' }), updateSetting });+ return updateSetting;+}++/** The last `appearance` payload the debounced persist wrote. */+function lastAppearance(updateSetting: ReturnType<typeof vi.fn>): Record<string, unknown> {+ const calls = updateSetting.mock.calls.filter(c => c[0] === 'appearance');+ return calls[calls.length - 1][1] as Record<string, unknown>;+}++describe('AppearanceSettingsTab – custom accent and sliders', () => {+ it('FE-COMP-APPEARANCE-010: a failing persist surfaces the error toast', async () => {+ const user = userEvent.setup();+ seedAppearance(vi.fn().mockRejectedValue(new Error('Appearance rejected')));+ render(<><ToastContainer /><AppearanceSettingsTab /></>);++ await user.click(screen.getByText('Teal'));++ await screen.findByText('Appearance rejected', undefined, PERSIST);+ });++ it('FE-COMP-APPEARANCE-011: a failing colour-mode change surfaces the error toast', async () => {+ const user = userEvent.setup();+ seedAppearance(vi.fn().mockRejectedValue(new Error('Mode rejected')));+ render(<><ToastContainer /><AppearanceSettingsTab /></>);++ await user.click(screen.getByText('Dark'));++ await screen.findByText('Mode rejected');+ });++ it('FE-COMP-APPEARANCE-012: picking Custom reveals the accent picker', async () => {+ const user = userEvent.setup();+ const updateSetting = seedAppearance();+ render(<AppearanceSettingsTab />);++ expect(screen.queryByText('Custom accent')).not.toBeInTheDocument();+ await user.click(screen.getByText('Custom'));++ expect(screen.getByText('Custom accent')).toBeInTheDocument();+ await waitFor(+ () => expect(updateSetting).toHaveBeenCalledWith('appearance', expect.objectContaining({ schemeId: 'custom' })),+ PERSIST,+ );+ });++ it('FE-COMP-APPEARANCE-013: an accent preset sets both the light and the dark accent', async () => {+ const user = userEvent.setup();+ const updateSetting = seedAppearance();+ render(<AppearanceSettingsTab />);++ await user.click(screen.getByText('Custom'));+ await user.click(screen.getByRole('button', { name: '#0d9488' }));++ await waitFor(+ () => expect(lastAppearance(updateSetting).accent).toEqual({ light: '#0d9488', dark: '#0d9488' }),+ PERSIST,+ );+ });++ it('FE-COMP-APPEARANCE-014: the two colour inputs edit the light and dark accent separately', async () => {+ const user = userEvent.setup();+ const updateSetting = seedAppearance();+ render(<AppearanceSettingsTab />);++ await user.click(screen.getByText('Custom'));+ const [light, dark] = Array.from(document.querySelectorAll('input[type="color"]')) as HTMLInputElement[];++ fireEvent.change(light, { target: { value: '#112233' } });+ await waitFor(() => expect(lastAppearance(updateSetting).accent).toMatchObject({ light: '#112233' }), PERSIST);++ fireEvent.change(dark, { target: { value: '#445566' } });+ await waitFor(() => expect(lastAppearance(updateSetting).accent).toEqual({ light: '#112233', dark: '#445566' }), PERSIST);+ });++ it('FE-COMP-APPEARANCE-015: the contrast hint follows the picked accent', async () => {+ const user = userEvent.setup();+ seedAppearance();+ render(<AppearanceSettingsTab />);++ await user.click(screen.getByText('Custom'));+ expect(screen.getByText(/Good contrast/)).toBeInTheDocument();++ // Near-white on white is unreadable — the hint has to say so.+ fireEvent.change(document.querySelectorAll('input[type="color"]')[0], { target: { value: '#fafafa' } });+ expect(screen.getByText(/Low contrast/)).toBeInTheDocument();+ });++ it('FE-COMP-APPEARANCE-016: reduce motion is persisted', async () => {+ const user = userEvent.setup();+ const updateSetting = seedAppearance();+ render(<AppearanceSettingsTab />);++ await user.click(screen.getByRole('button', { name: 'Reduce motion' }));++ await waitFor(+ () => expect(updateSetting).toHaveBeenCalledWith('appearance', expect.objectContaining({ reduceMotion: true })),+ PERSIST,+ );+ });++ it('FE-COMP-APPEARANCE-017: the global text-size slider persists fontScale', async () => {+ const updateSetting = seedAppearance();+ render(<AppearanceSettingsTab />);++ fireEvent.change(screen.getAllByRole('slider')[0], { target: { value: '1.2' } });++ await waitFor(() => expect(lastAppearance(updateSetting).fontScale).toBe(1.2), PERSIST);+ expect(screen.getAllByText('120%').length).toBeGreaterThan(0);+ });++ it('FE-COMP-APPEARANCE-018: each size row writes its own typeScale entry', async () => {+ const updateSetting = seedAppearance();+ render(<AppearanceSettingsTab />);+ const sliders = screen.getAllByRole('slider');++ fireEvent.change(sliders[1], { target: { value: '1.15' } });+ fireEvent.change(sliders[2], { target: { value: '1.1' } });+ fireEvent.change(sliders[3], { target: { value: '0.9' } });+ fireEvent.change(sliders[4], { target: { value: '0.85' } });++ await waitFor(+ () => expect(lastAppearance(updateSetting).typeScale).toMatchObject({+ title: 1.15,+ subtitle: 1.1,+ body: 0.9,+ caption: 0.85,+ }),+ PERSIST,+ );+ });+});++describe('AppearanceSettingsTab – dashboard widgets', () => {+ it('FE-COMP-APPEARANCE-019: toggling a desktop widget persists it under dashboard.desktop', async () => {+ const user = userEvent.setup();+ const updateSetting = seedAppearance();+ render(<AppearanceSettingsTab />);++ await user.click(screen.getByRole('button', { name: 'Atlas / countries' }));++ await waitFor(+ () => expect(lastAppearance(updateSetting).dashboard).toMatchObject({ desktop: { atlas: false } }),+ PERSIST,+ );+ });++ it('FE-COMP-APPEARANCE-020: turning the sidebar master off disables its child widgets', async () => {+ const user = userEvent.setup();+ const updateSetting = seedAppearance();+ render(<AppearanceSettingsTab />);+ const master = screen.getByRole('button', { name: 'Right sidebar' });+ expect(master).toHaveAttribute('aria-pressed', 'true');++ await user.click(master);++ await waitFor(+ () => expect(lastAppearance(updateSetting).dashboard).toMatchObject({ desktop: { sidebar: false } }),+ PERSIST,+ );+ expect(screen.getByRole('button', { name: 'Right sidebar' })).toHaveAttribute('aria-pressed', 'false');+ });++ it('FE-COMP-APPEARANCE-021: toggling a mobile widget only touches the mobile map', async () => {+ const user = userEvent.setup();+ const updateSetting = seedAppearance();+ render(<AppearanceSettingsTab />);++ // Currency exists on both devices; the second occurrence is the mobile row.+ const currencyToggles = screen.getAllByRole('button', { name: 'Currency' });+ await user.click(currencyToggles[1]);++ await waitFor(+ () => expect(lastAppearance(updateSetting).dashboard).toMatchObject({+ desktop: { currency: true },+ mobile: { currency: false },+ }),+ PERSIST,+ );+ });++ it('FE-COMP-APPEARANCE-022: Reset to defaults writes the whole default config back', async () => {+ const user = userEvent.setup();+ const updateSetting = seedAppearance();+ render(<AppearanceSettingsTab />);++ await user.click(screen.getByRole('button', { name: 'Atlas / countries' }));+ await waitFor(() => expect(lastAppearance(updateSetting).dashboard).toMatchObject({ desktop: { atlas: false } }), PERSIST);++ await user.click(screen.getByRole('button', { name: /Reset to defaults/ }));++ await waitFor(+ () => expect(lastAppearance(updateSetting).dashboard).toMatchObject({ desktop: { atlas: true } }),+ PERSIST,+ );+ });+});diff --git a/client/src/components/Settings/DisplaySettingsTab.test.tsx b/client/src/components/Settings/DisplaySettingsTab.test.tsxindex 84621b6ec..64e7342fe 100644--- a/client/src/components/Settings/DisplaySettingsTab.test.tsx+++ b/client/src/components/Settings/DisplaySettingsTab.test.tsx@@ -1,5 +1,5 @@-// FE-COMP-DISPLAY-001 to FE-COMP-DISPLAY-027-import { render, screen, within } from '../../../tests/helpers/render';+// FE-COMP-DISPLAY-001 to FE-COMP-DISPLAY-048+import { render, screen, within, fireEvent } from '../../../tests/helpers/render';import userEvent from '@testing-library/user-event';import { http, HttpResponse } from 'msw';import { server } from '../../../tests/helpers/msw/server';@@ -178,3 +178,220 @@ describe('DisplaySettingsTab', () => {expect(fahrenheitBtn.style.border).toContain('var(--text-primary)');});});++// ── Display currency (033–034) ────────────────────────────────────────────────++function seedFailing(message = 'Server error') {+ const updateSetting = vi.fn().mockRejectedValue(new Error(message));+ seedStore(useSettingsStore, { settings: buildSettings({ language: 'en' }), updateSetting });+ return updateSetting;+}++/** The block of buttons belonging to one labelled setting. */+function optionBlock(label: RegExp): HTMLElement {+ return screen.getByText(label).closest('div') as HTMLElement;+}++describe('DisplaySettingsTab – Display currency', () => {+ it('FE-COMP-DISPLAY-033: picking "Trip currency" clears the personal display currency', async () => {+ const user = userEvent.setup();+ const updateSetting = vi.fn().mockResolvedValue(undefined);+ seedStore(useSettingsStore, { settings: buildSettings({ default_currency: 'USD' }), updateSetting });+ render(<DisplaySettingsTab />);++ await user.click(screen.getByRole('button', { name: /USD/ }));+ await user.click(await screen.findByText('Trip currency'));++ expect(updateSetting).toHaveBeenCalledWith('default_currency', '');+ });++ it('FE-COMP-DISPLAY-034: a rejected currency change surfaces the error', async () => {+ const user = userEvent.setup();+ const updateSetting = vi.fn().mockRejectedValue(new Error('Currency locked'));+ seedStore(useSettingsStore, { settings: buildSettings({ default_currency: 'USD' }), updateSetting });+ render(<><ToastContainer /><DisplaySettingsTab /></>);++ await user.click(screen.getByRole('button', { name: /USD/ }));+ await user.click(await screen.findByText('Trip currency'));++ await screen.findByText('Currency locked');+ });+});++// ── Compact language dropdown (035–039) ───────────────────────────────────────++function mobileLangWrap(): HTMLElement {+ return screen.getByText('Language').closest('div')!.querySelector('.sm\\:hidden') as HTMLElement;+}++describe('DisplaySettingsTab – Compact language picker', () => {+ it('FE-COMP-DISPLAY-035: the compact trigger shows the active language and opens the list', async () => {+ const user = userEvent.setup();+ render(<DisplaySettingsTab />);+ const wrap = mobileLangWrap();++ expect(within(wrap).getAllByRole('button')).toHaveLength(1);+ expect(within(wrap).getByText('English')).toBeInTheDocument();++ await user.click(within(wrap).getByRole('button'));++ expect(within(wrap).getAllByRole('button').length).toBeGreaterThan(1);+ });++ it('FE-COMP-DISPLAY-036: picking a language from the list saves it and closes the list', async () => {+ const user = userEvent.setup();+ const updateSetting = vi.fn().mockResolvedValue(undefined);+ seedStore(useSettingsStore, { settings: buildSettings({ language: 'en' }), updateSetting });+ render(<DisplaySettingsTab />);+ const wrap = mobileLangWrap();++ await user.click(within(wrap).getByRole('button'));+ await user.click(within(wrap).getByText('Deutsch').closest('button')!);++ expect(updateSetting).toHaveBeenCalledWith('language', 'de');+ expect(within(wrap).getAllByRole('button')).toHaveLength(1);+ });++ it('FE-COMP-DISPLAY-037: a rejected pick from the list surfaces the error', async () => {+ const user = userEvent.setup();+ seedFailing('Language locked');+ render(<><ToastContainer /><DisplaySettingsTab /></>);+ const wrap = mobileLangWrap();++ await user.click(within(wrap).getByRole('button'));+ await user.click(within(wrap).getByText('Deutsch').closest('button')!);++ await screen.findByText('Language locked');+ });++ it('FE-COMP-DISPLAY-048: a rejected pick from the desktop grid surfaces the error', async () => {+ const user = userEvent.setup();+ seedFailing('Language locked');+ render(<><ToastContainer /><DisplaySettingsTab /></>);++ await user.click(screen.getByText('Deutsch'));++ await screen.findByText('Language locked');+ });++ it('FE-COMP-DISPLAY-038: a mousedown outside the picker closes it', async () => {+ const user = userEvent.setup();+ render(<DisplaySettingsTab />);+ const wrap = mobileLangWrap();++ await user.click(within(wrap).getByRole('button'));+ expect(within(wrap).getAllByRole('button').length).toBeGreaterThan(1);++ fireEvent.mouseDown(document.body);++ expect(within(wrap).getAllByRole('button')).toHaveLength(1);+ });++ it('FE-COMP-DISPLAY-039: a mousedown inside the picker keeps it open', async () => {+ const user = userEvent.setup();+ render(<DisplaySettingsTab />);+ const wrap = mobileLangWrap();++ await user.click(within(wrap).getByRole('button'));+ fireEvent.mouseDown(within(wrap).getByText('Deutsch'));++ expect(within(wrap).getAllByRole('button').length).toBeGreaterThan(1);+ });+});++// ── Map & privacy toggles (040–047) ───────────────────────────────────────────++describe('DisplaySettingsTab – Map and privacy toggles', () => {+ it('FE-COMP-DISPLAY-040: turning booking route labels off persists false', async () => {+ const user = userEvent.setup();+ const updateSetting = vi.fn().mockResolvedValue(undefined);+ seedStore(useSettingsStore, { settings: buildSettings({ map_booking_labels: true }), updateSetting });+ render(<DisplaySettingsTab />);++ await user.click(within(optionBlock(/booking route labels/i)).getByText(/^Off$/));++ expect(updateSetting).toHaveBeenCalledWith('map_booking_labels', false);+ });++ it('FE-COMP-DISPLAY-041: a rejected booking-labels change surfaces the error', async () => {+ const user = userEvent.setup();+ seedFailing('Labels locked');+ render(<><ToastContainer /><DisplaySettingsTab /></>);++ await user.click(within(optionBlock(/booking route labels/i)).getByText(/^On$/));++ await screen.findByText('Labels locked');+ });++ it('FE-COMP-DISPLAY-042: a rejected always-show-routes change surfaces the error', async () => {+ const user = userEvent.setup();+ seedFailing('Routes locked');+ render(<><ToastContainer /><DisplaySettingsTab /></>);++ await user.click(within(optionBlock(/always show booking routes/i)).getByText(/^On$/));++ await screen.findByText('Routes locked');+ });++ it('FE-COMP-DISPLAY-043: the POI pill defaults to On and can be turned off', async () => {+ const user = userEvent.setup();+ const updateSetting = vi.fn().mockResolvedValue(undefined);+ seedStore(useSettingsStore, { settings: buildSettings(), updateSetting });+ render(<DisplaySettingsTab />);+ const block = optionBlock(/explore places on the map/i);++ expect(within(block).getByText(/^On$/).closest('button')!.style.border).toContain('var(--text-primary)');+ await user.click(within(block).getByText(/^Off$/));++ expect(updateSetting).toHaveBeenCalledWith('map_poi_pill_enabled', false);+ });++ it('FE-COMP-DISPLAY-044: a rejected POI pill change surfaces the error', async () => {+ const user = userEvent.setup();+ seedFailing('POI locked');+ render(<><ToastContainer /><DisplaySettingsTab /></>);++ await user.click(within(optionBlock(/explore places on the map/i)).getByText(/^Off$/));++ await screen.findByText('POI locked');+ });++ it('FE-COMP-DISPLAY-045: turning blur booking codes on persists true', async () => {+ const user = userEvent.setup();+ const updateSetting = vi.fn().mockResolvedValue(undefined);+ seedStore(useSettingsStore, { settings: buildSettings({ blur_booking_codes: false }), updateSetting });+ render(<DisplaySettingsTab />);++ await user.click(within(optionBlock(/blur booking codes/i)).getByText(/^On$/));++ expect(updateSetting).toHaveBeenCalledWith('blur_booking_codes', true);+ });++ it('FE-COMP-DISPLAY-046: the accommodation optimisation defaults to On and can be turned off', async () => {+ const user = userEvent.setup();+ const updateSetting = vi.fn().mockResolvedValue(undefined);+ seedStore(useSettingsStore, { settings: buildSettings(), updateSetting });+ render(<DisplaySettingsTab />);+ const block = optionBlock(/optimize route from accommodation/i);++ expect(within(block).getByText(/^On$/).closest('button')!.style.border).toContain('var(--text-primary)');+ await user.click(within(block).getByText(/^Off$/));++ expect(updateSetting).toHaveBeenCalledWith('optimize_from_accommodation', false);+ });++ it('FE-COMP-DISPLAY-047: rejected blur, optimisation, distance and time-format changes all toast', async () => {+ const user = userEvent.setup();+ seedFailing('Nope');+ render(<><ToastContainer /><DisplaySettingsTab /></>);++ await user.click(within(optionBlock(/blur booking codes/i)).getByText(/^On$/));+ await screen.findByText('Nope');++ await user.click(within(optionBlock(/optimize route from accommodation/i)).getByText(/^Off$/));+ await user.click(screen.getByText('mi Imperial'));+ await user.click(screen.getByRole('button', { name: /24h/ }));++ expect(screen.getAllByText('Nope').length).toBeGreaterThan(0);+ });+});diff --git a/client/src/components/Settings/IntegrationsTab.test.tsx b/client/src/components/Settings/IntegrationsTab.test.tsxindex 7170da6ef..47ec0e49d 100644--- a/client/src/components/Settings/IntegrationsTab.test.tsx+++ b/client/src/components/Settings/IntegrationsTab.test.tsx@@ -1,4 +1,4 @@-// FE-COMP-INTEGRATIONS-001 to FE-COMP-INTEGRATIONS-032+// FE-COMP-INTEGRATIONS-001 to FE-COMP-INTEGRATIONS-047import { render, screen, waitFor } from '../../../tests/helpers/render';import userEvent from '@testing-library/user-event';import { http, HttpResponse } from 'msw';@@ -652,3 +652,306 @@ describe('IntegrationsTab', () => {await screen.findByText(/Failed to register/i);});});++// ── Copy buttons, cancels and the remaining failure toasts (033–047) ──────────++const oneClient = [+ {+ id: 'c-1',+ client_id: 'cid-1',+ name: 'Existing Client',+ redirect_uris: ['http://localhost'],+ allowed_scopes: ['trips:read'],+ created_at: '2025-01-01T00:00:00Z',+ },+];+const oneSession = [+ { id: 42, client_name: 'Session App', scopes: ['trips:read'], access_token_expires_at: '2025-12-31T00:00:00Z' },+];+const oneToken = [+ { id: 1, name: 'Token One', token_prefix: 'tk_one', created_at: '2025-01-01T00:00:00.000Z', last_used_at: null },+];++async function openTokensTab(user: ReturnType<typeof userEvent.setup>) {+ await screen.findByText('MCP Configuration');+ await user.click(screen.getByRole('button', { name: /API Tokens/i }));+}++/** The copy button inside a config panel — labelled, unlike the icon-only ones. */+function labelledCopyButton(): HTMLElement {+ return screen.getAllByRole('button', { name: /^Copy$/i })+ .find(b => b.textContent?.trim() === 'Copy') as HTMLElement;+}++describe('IntegrationsTab – copy actions and cancels', () => {+ it('FE-COMP-INTEGRATIONS-033: the OAuth client config can be expanded and copied', async () => {+ const user = userEvent.setup();+ enableMcp();+ render(<IntegrationsTab />);+ await screen.findByText('MCP Configuration');+ const writeSpy = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(undefined);++ await user.click(screen.getByRole('button', { name: /Client Configuration/i }));+ await user.click(labelledCopyButton());++ expect(writeSpy).toHaveBeenCalledWith(expect.stringContaining('mcp'));+ await screen.findByRole('button', { name: /Copied!/i });+ });++ it('FE-COMP-INTEGRATIONS-034: the API-token client config can be expanded and copied', async () => {+ const user = userEvent.setup();+ enableMcp();+ render(<IntegrationsTab />);+ await openTokensTab(user);+ const writeSpy = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(undefined);++ await user.click(screen.getByRole('button', { name: /Client Configuration/i }));+ await user.click(labelledCopyButton());++ expect(writeSpy).toHaveBeenCalledWith(expect.stringContaining('mcp'));+ await screen.findByRole('button', { name: /Copied!/i });+ });++ it('FE-COMP-INTEGRATIONS-035: Cancel closes the create-token modal', async () => {+ const user = userEvent.setup();+ enableMcp();+ render(<IntegrationsTab />);+ await openTokensTab(user);++ await user.click(screen.getByRole('button', { name: /Create New Token/i }));+ await screen.findByText('Create API Token');+ await user.click(screen.getByRole('button', { name: /^Cancel$/i }));++ expect(screen.queryByText('Create API Token')).toBeNull();+ });++ it('FE-COMP-INTEGRATIONS-036: the freshly created token can be copied from the modal', async () => {+ const user = userEvent.setup();+ server.use(+ http.post('/api/auth/mcp-tokens', () =>+ HttpResponse.json({+ token: { id: 7, name: 'Fresh', token_prefix: 'tk_fresh', raw_token: 'tk_fresh_raw_secret', created_at: '2025-01-01T00:00:00.000Z' },+ }),+ ),+ );+ enableMcp();+ render(<IntegrationsTab />);+ await openTokensTab(user);+ await user.click(screen.getByRole('button', { name: /Create New Token/i }));+ await user.type(screen.getByPlaceholderText(/Claude Desktop/i), 'Fresh');+ await user.click(screen.getByRole('button', { name: /^Create Token$/i }));+ await screen.findByText('Token Created');++ const writeSpy = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(undefined);+ const copyBtns = screen.getAllByTitle('Copy');+ await user.click(copyBtns[copyBtns.length - 1]);++ expect(writeSpy).toHaveBeenCalledWith('tk_fresh_raw_secret');+ });++ it('FE-COMP-INTEGRATIONS-037: Cancel closes the register-client modal', async () => {+ const user = userEvent.setup();+ enableMcp();+ render(<IntegrationsTab />);+ await screen.findByText('MCP Configuration');++ await user.click(screen.getByRole('button', { name: /New Client/i }));+ await screen.findByText('Register OAuth Client');+ await user.click(screen.getByRole('button', { name: /^Cancel$/i }));++ expect(screen.queryByText('Register OAuth Client')).toBeNull();+ });++ it('FE-COMP-INTEGRATIONS-038: the machine-client checkbox drops the redirect-URI field', async () => {+ const user = userEvent.setup();+ enableMcp();+ render(<IntegrationsTab />);+ await screen.findByText('MCP Configuration');+ await user.click(screen.getByRole('button', { name: /New Client/i }));+ await screen.findByText('Register OAuth Client');++ expect(screen.getByPlaceholderText(/https:\/\/your-app/i)).toBeInTheDocument();+ await user.click(screen.getAllByRole('checkbox')[0]);++ expect(screen.queryByPlaceholderText(/https:\/\/your-app/i)).toBeNull();+ await user.type(screen.getByPlaceholderText(/Claude Web, My MCP App/i), 'Robot');+ expect(screen.getByRole('button', { name: /Register Client/i })).toBeEnabled();+ });++ it('FE-COMP-INTEGRATIONS-039: the created client id and secret can both be copied', async () => {+ const user = userEvent.setup();+ server.use(+ http.post('/api/oauth/clients', () =>+ HttpResponse.json({+ client: {+ id: 'new-1',+ client_id: 'cid-new',+ client_secret: 'secret-new',+ name: 'Copyable',+ redirect_uris: ['http://localhost'],+ allowed_scopes: ['trips:read'],+ created_at: '2025-01-01T00:00:00Z',+ },+ }),+ ),+ );+ enableMcp();+ render(<IntegrationsTab />);+ await screen.findByText('MCP Configuration');+ await user.click(screen.getByRole('button', { name: /New Client/i }));+ await user.type(screen.getByPlaceholderText(/Claude Web, My MCP App/i), 'Copyable');+ await user.type(screen.getByPlaceholderText(/https:\/\/your-app/i), 'http://localhost');+ await user.click(screen.getByRole('button', { name: /Register Client/i }));+ await screen.findByText('cid-new');++ const writeSpy = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(undefined);+ const copyBtns = screen.getAllByRole('button').filter(b => b.querySelector('svg') && !b.textContent?.trim());+ await user.click(copyBtns[copyBtns.length - 2]);+ expect(writeSpy).toHaveBeenCalledWith('cid-new');++ await user.click(copyBtns[copyBtns.length - 1]);+ expect(writeSpy).toHaveBeenCalledWith('secret-new');+ });++ it('FE-COMP-INTEGRATIONS-040: Cancel keeps the OAuth client and closes the delete modal', async () => {+ const user = userEvent.setup();+ server.use(http.get('/api/oauth/clients', () => HttpResponse.json({ clients: oneClient })));+ enableMcp();+ render(<IntegrationsTab />);+ await screen.findByText('Existing Client');++ await user.click(screen.getByTitle('Delete Client'));+ await screen.findByRole('heading', { name: 'Delete Client' });+ await user.click(screen.getByRole('button', { name: /^Cancel$/i }));++ expect(screen.queryByRole('heading', { name: 'Delete Client' })).toBeNull();+ expect(screen.getByText('Existing Client')).toBeInTheDocument();+ });++ it('FE-COMP-INTEGRATIONS-041: Cancel closes the rotate-secret modal', async () => {+ const user = userEvent.setup();+ server.use(http.get('/api/oauth/clients', () => HttpResponse.json({ clients: oneClient })));+ enableMcp();+ render(<IntegrationsTab />);+ await screen.findByText('Existing Client');++ await user.click(screen.getByTitle('Rotate Secret'));+ await screen.findByRole('heading', { name: 'Rotate Secret' });+ await user.click(screen.getByRole('button', { name: /^Cancel$/i }));++ expect(screen.queryByRole('heading', { name: 'Rotate Secret' })).toBeNull();+ });++ it('FE-COMP-INTEGRATIONS-042: the rotated secret can be copied and dismissed', async () => {+ const user = userEvent.setup();+ server.use(+ http.get('/api/oauth/clients', () => HttpResponse.json({ clients: oneClient })),+ http.post('/api/oauth/clients/c-1/rotate', () => HttpResponse.json({ client_secret: 'rotated-xyz' })),+ );+ enableMcp();+ render(<IntegrationsTab />);+ await screen.findByText('Existing Client');+ await user.click(screen.getByTitle('Rotate Secret'));+ const rotateBtns = await screen.findAllByRole('button', { name: /^Rotate$/i });+ await user.click(rotateBtns[rotateBtns.length - 1]);+ await screen.findByText('New Secret Generated');++ const writeSpy = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(undefined);+ const copyBtn = screen.getAllByRole('button').filter(b => b.querySelector('svg') && !b.textContent?.trim());+ await user.click(copyBtn[copyBtn.length - 1]);+ expect(writeSpy).toHaveBeenCalledWith('rotated-xyz');++ await user.click(screen.getByRole('button', { name: /^Done$/i }));+ expect(screen.queryByText('New Secret Generated')).toBeNull();+ });++ it('FE-COMP-INTEGRATIONS-043: Cancel keeps the session and closes the revoke modal', async () => {+ const user = userEvent.setup();+ server.use(http.get('/api/oauth/sessions', () => HttpResponse.json({ sessions: oneSession })));+ enableMcp();+ render(<IntegrationsTab />);+ await screen.findByText('Session App');++ await user.click(screen.getByText('Revoke'));+ await screen.findByText('Revoke Session');+ await user.click(screen.getByRole('button', { name: /^Cancel$/i }));++ expect(screen.queryByText('Revoke Session')).toBeNull();+ expect(screen.getByText('Session App')).toBeInTheDocument();+ });+});++describe('IntegrationsTab – failure toasts', () => {+ it('FE-COMP-INTEGRATIONS-044: a failing token creation toasts', async () => {+ const user = userEvent.setup();+ server.use(http.post('/api/auth/mcp-tokens', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));+ enableMcp();+ render(<><ToastContainer /><IntegrationsTab /></>);+ await openTokensTab(user);++ await user.click(screen.getByRole('button', { name: /Create New Token/i }));+ await user.type(screen.getByPlaceholderText(/Claude Desktop/i), 'Doomed');+ await user.click(screen.getByRole('button', { name: /^Create Token$/i }));++ await screen.findByText('Failed to create token');+ });++ it('FE-COMP-INTEGRATIONS-045: a failing token deletion toasts and keeps the token', async () => {+ const user = userEvent.setup();+ server.use(+ http.get('/api/auth/mcp-tokens', () => HttpResponse.json({ tokens: oneToken })),+ http.delete('/api/auth/mcp-tokens/1', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),+ );+ enableMcp();+ render(<><ToastContainer /><IntegrationsTab /></>);+ await openTokensTab(user);+ await screen.findByText('Token One');++ await user.click(screen.getByTitle('Delete Token'));+ const confirmBtns = await screen.findAllByRole('button', { name: /^Delete Token$/i });+ await user.click(confirmBtns.find(b => !b.title) ?? confirmBtns[confirmBtns.length - 1]);++ await screen.findByText('Failed to delete token');+ expect(screen.getByText('Token One')).toBeInTheDocument();+ });++ it('FE-COMP-INTEGRATIONS-046: failing client deletion and rotation both toast', async () => {+ const user = userEvent.setup();+ server.use(+ http.get('/api/oauth/clients', () => HttpResponse.json({ clients: oneClient })),+ http.delete('/api/oauth/clients/c-1', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),+ http.post('/api/oauth/clients/c-1/rotate', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),+ );+ enableMcp();+ render(<><ToastContainer /><IntegrationsTab /></>);+ await screen.findByText('Existing Client');++ await user.click(screen.getByTitle('Delete Client'));+ const deleteBtns = await screen.findAllByRole('button', { name: /^Delete Client$/i });+ await user.click(deleteBtns[deleteBtns.length - 1]);+ await screen.findByText('Failed to delete OAuth client');++ await user.click(screen.getByTitle('Rotate Secret'));+ const rotateBtns = await screen.findAllByRole('button', { name: /^Rotate$/i });+ await user.click(rotateBtns[rotateBtns.length - 1]);+ await screen.findByText('Failed to rotate client secret');+ });++ it('FE-COMP-INTEGRATIONS-047: a failing session revoke toasts and keeps the session', async () => {+ const user = userEvent.setup();+ server.use(+ http.get('/api/oauth/sessions', () => HttpResponse.json({ sessions: oneSession })),+ http.delete('/api/oauth/sessions/42', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),+ );+ enableMcp();+ render(<><ToastContainer /><IntegrationsTab /></>);+ await screen.findByText('Session App');++ await user.click(screen.getByText('Revoke'));+ const revokeBtns = await screen.findAllByRole('button', { name: /^Revoke$/i });+ await user.click(revokeBtns[revokeBtns.length - 1]);++ await screen.findByText('Failed to revoke session');+ expect(screen.getByText('Session App')).toBeInTheDocument();+ });+});diff --git a/client/src/components/Settings/LlmConnectionSection.test.tsx b/client/src/components/Settings/LlmConnectionSection.test.tsxnew file mode 100644index 000000000..b78ab411d--- /dev/null+++ b/client/src/components/Settings/LlmConnectionSection.test.tsx@@ -0,0 +1,196 @@+// FE-COMP-LLM-001 to FE-COMP-LLM-013+import { render, screen, waitFor } from '../../../tests/helpers/render';+import userEvent from '@testing-library/user-event';+import { resetAllStores, seedStore } from '../../../tests/helpers/store';+import { buildSettings } from '../../../tests/helpers/factories';+import { useSettingsStore } from '../../store/settingsStore';+import type { Settings } from '../../types';+import { ToastContainer } from '../shared/Toast';+import LlmConnectionSection from './LlmConnectionSection';++function seedLlm(over: Partial<Settings> = {}, updateSettings = vi.fn().mockResolvedValue(undefined)) {+ seedStore(useSettingsStore, {+ settings: buildSettings({ language: 'en', ...over }),+ isLoaded: true,+ updateSettings,+ });+ return updateSettings;+}++function renderSection() {+ return render(+ <>+ <ToastContainer />+ <LlmConnectionSection />+ </>,+ );+}++function multimodalToggle(): HTMLElement {+ const row = screen.getByText('Send documents as images').parentElement as HTMLElement;+ return row.querySelector('button') as HTMLElement;+}++async function pickProvider(user: ReturnType<typeof userEvent.setup>, current: RegExp, next: string) {+ await user.click(screen.getByRole('button', { name: current }));+ await user.click(await screen.findByRole('button', { name: next }));+}++beforeEach(() => {+ resetAllStores();+ vi.clearAllMocks();+ seedLlm();+});++describe('LlmConnectionSection', () => {+ it('FE-COMP-LLM-001: defaults to the local provider with a base URL and without a key field', () => {+ renderSection();++ expect(screen.getByText('AI parsing')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /Local \(Ollama\)/ })).toBeInTheDocument();+ expect(screen.getByPlaceholderText('http://localhost:11434')).toBeInTheDocument();+ expect(screen.queryByPlaceholderText('API key')).not.toBeInTheDocument();+ });++ it('FE-COMP-LLM-002: hydrates provider, model, base URL and the multimodal toggle', () => {+ seedLlm({+ llm_provider: 'openai',+ llm_model: 'gpt-4o-mini',+ llm_base_url: 'https://api.openai.com/v1',+ llm_multimodal: true,+ });+ renderSection();++ expect(screen.getByRole('button', { name: /OpenAI/ })).toBeInTheDocument();+ expect(screen.getByDisplayValue('gpt-4o-mini')).toBeInTheDocument();+ expect(screen.getByDisplayValue('https://api.openai.com/v1')).toBeInTheDocument();+ expect(multimodalToggle()).toHaveAttribute('aria-pressed', 'true');+ });++ it('FE-COMP-LLM-003: nothing is hydrated and Save stays locked while the settings are loading', () => {+ seedStore(useSettingsStore, {+ settings: buildSettings({ language: 'en', llm_provider: 'anthropic', llm_model: 'claude-sonnet' }),+ isLoaded: false,+ });+ renderSection();++ expect(screen.getByRole('button', { name: /Local \(Ollama\)/ })).toBeInTheDocument();+ expect(screen.queryByDisplayValue('claude-sonnet')).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: /^Save$/ })).toBeDisabled();+ });++ it('FE-COMP-LLM-004: a stored key drives the masked placeholder and is never prefilled', () => {+ seedLlm({ llm_provider: 'anthropic', llm_api_key: '***' });+ renderSection();++ expect(screen.getByPlaceholderText('••••••••')).toHaveValue('');+ expect(screen.queryByPlaceholderText('http://localhost:11434')).not.toBeInTheDocument();+ });++ it('FE-COMP-LLM-005: without a stored key the field falls back to the plain label placeholder', () => {+ seedLlm({ llm_provider: 'anthropic' });+ renderSection();++ expect(screen.getByPlaceholderText('API key')).toHaveValue('');+ });++ it('FE-COMP-LLM-006: picking Anthropic hides the base URL and reveals the key field', async () => {+ const user = userEvent.setup();+ renderSection();++ await pickProvider(user, /Local \(Ollama\)/, 'Anthropic');++ expect(screen.queryByPlaceholderText('http://localhost:11434')).not.toBeInTheDocument();+ expect(screen.getByText('Stored encrypted. Leave blank to keep the current key.')).toBeInTheDocument();+ });++ it('FE-COMP-LLM-007: picking OpenAI keeps the base URL and adds the key field', async () => {+ const user = userEvent.setup();+ renderSection();++ await pickProvider(user, /Local \(Ollama\)/, 'OpenAI');++ expect(screen.getByPlaceholderText('http://localhost:11434')).toBeInTheDocument();+ expect(screen.getByPlaceholderText('API key')).toBeInTheDocument();+ });++ it('FE-COMP-LLM-008: saving trims the inputs and omits the key when none was typed', async () => {+ const user = userEvent.setup();+ const updateSettings = seedLlm({ llm_model: '', llm_base_url: '' });+ renderSection();++ await user.type(screen.getByPlaceholderText('qwen3:8b'), ' qwen3:8b ');+ await user.type(screen.getByPlaceholderText('http://localhost:11434'), ' http://ollama.local ');+ await user.click(screen.getByRole('button', { name: /^Save$/ }));++ expect(updateSettings).toHaveBeenCalledWith({+ llm_provider: 'local',+ llm_model: 'qwen3:8b',+ llm_base_url: 'http://ollama.local',+ llm_multimodal: false,+ });+ await screen.findByText('AI settings saved');+ });++ it('FE-COMP-LLM-009: a typed key is sent, the field is cleared and the mask takes over', async () => {+ const user = userEvent.setup();+ const updateSettings = seedLlm({ llm_provider: 'anthropic', llm_model: 'claude-sonnet' });+ renderSection();++ await user.type(screen.getByPlaceholderText('API key'), ' sk-test ');+ await user.click(screen.getByRole('button', { name: /^Save$/ }));++ expect(updateSettings).toHaveBeenCalledWith(expect.objectContaining({ llm_api_key: 'sk-test' }));+ await waitFor(() => expect(screen.getByPlaceholderText('••••••••')).toHaveValue(''));+ });++ it('FE-COMP-LLM-010: a non-local provider never persists a base URL', async () => {+ const user = userEvent.setup();+ const updateSettings = seedLlm({ llm_provider: 'anthropic', llm_base_url: 'http://leftover' });+ renderSection();++ await user.click(screen.getByRole('button', { name: /^Save$/ }));++ expect(updateSettings).toHaveBeenCalledWith(expect.objectContaining({ llm_base_url: '' }));+ });++ it('FE-COMP-LLM-011: the multimodal toggle is part of the saved payload', async () => {+ const user = userEvent.setup();+ const updateSettings = seedLlm();+ renderSection();++ await user.click(multimodalToggle());+ expect(multimodalToggle()).toHaveAttribute('aria-pressed', 'true');+ await user.click(screen.getByRole('button', { name: /^Save$/ }));++ expect(updateSettings).toHaveBeenCalledWith(expect.objectContaining({ llm_multimodal: true }));+ });++ it('FE-COMP-LLM-012: a failing save shows the error toast and re-enables the button', async () => {+ const user = userEvent.setup();+ seedLlm({}, vi.fn().mockRejectedValue(new Error('nope')));+ renderSection();++ const saveBtn = screen.getByRole('button', { name: /^Save$/ });+ await user.click(saveBtn);++ await screen.findByText('Could not save AI settings');+ await waitFor(() => expect(saveBtn).toBeEnabled());+ });++ it('FE-COMP-LLM-013: Save is locked while the request is in flight', async () => {+ const user = userEvent.setup();+ let release!: () => void;+ seedLlm({}, vi.fn().mockReturnValue(new Promise<void>(resolve => {+ release = resolve;+ })));+ renderSection();++ const saveBtn = screen.getByRole('button', { name: /^Save$/ });+ await user.click(saveBtn);++ await waitFor(() => expect(saveBtn).toBeDisabled());+ release();+ await waitFor(() => expect(saveBtn).toBeEnabled());+ });+});diff --git a/client/src/components/Settings/MapSettingsTab.test.tsx b/client/src/components/Settings/MapSettingsTab.test.tsxindex 8d7b8bf15..79e1934da 100644--- a/client/src/components/Settings/MapSettingsTab.test.tsx+++ b/client/src/components/Settings/MapSettingsTab.test.tsx@@ -1,5 +1,5 @@-// FE-COMP-MAP-001 to FE-COMP-MAP-017-import { render, screen, waitFor } from '../../../tests/helpers/render';+// FE-COMP-MAP-001 to FE-COMP-MAP-030+import { render, screen, waitFor, within, fireEvent } from '../../../tests/helpers/render';import userEvent from '@testing-library/user-event';import { useAuthStore } from '../../store/authStore';import { useSettingsStore } from '../../store/settingsStore';@@ -15,6 +15,23 @@ vi.mock('../Map/MapView', () => ({),}));+// The GL preview boots a real mapbox/maplibre instance; the tab only cares that+// it gets the right provider/style, so render those as data attributes.+vi.mock('./MapboxPreview', () => ({+ default: ({ provider, style, token, enable3d, quality }: {+ provider?: string; style: string; token?: string; enable3d: boolean; quality?: boolean;+ }) => (+ <div+ data-testid="gl-preview"+ data-provider={provider}+ data-style={style}+ data-token={token}+ data-3d={String(enable3d)}+ data-quality={String(quality)}+ />+ ),+}));+beforeEach(() => {resetAllStores();vi.clearAllMocks();@@ -138,3 +155,196 @@ describe('MapSettingsTab', () => {});});});++// ── Provider switching and GL settings (018–030) ──────────────────────────────++const MAPBOX_STANDARD = 'mapbox://styles/mapbox/standard';+const OFM_LIBERTY = 'https://tiles.openfreemap.org/styles/liberty';++/** The style preset picker sitting above the raw style input. */+function styleDropdown(): HTMLElement {+ return screen.getByText('Map Style').closest('div')!.querySelector('div.relative') as HTMLElement;+}++/** The ToggleSwitch belonging to a labelled GL option row. */+function toggleFor(label: string): HTMLElement {+ let el: HTMLElement | null = screen.getByText(label);+ while (el && !el.querySelector('button')) el = el.parentElement;+ return el!.querySelector('button') as HTMLElement;+}++describe('MapSettingsTab – GL providers', () => {+ it('FE-COMP-MAP-018: picking Mapbox GL reveals the token field, the style picker and the preview', async () => {+ const user = userEvent.setup();+ render(<MapSettingsTab />);++ await user.click(screen.getByText('Mapbox GL'));++ expect(screen.getByText('Mapbox Access Token')).toBeInTheDocument();+ expect(screen.getByText('Map Style')).toBeInTheDocument();+ expect(screen.queryByText('Map Template')).not.toBeInTheDocument();+ expect(screen.getByTestId('gl-preview')).toHaveAttribute('data-provider', 'mapbox-gl');+ expect(screen.getByDisplayValue(MAPBOX_STANDARD)).toBeInTheDocument();+ });++ it('FE-COMP-MAP-019: the style picker lists presets with their tag chips and applies the pick', async () => {+ const user = userEvent.setup();+ render(<MapSettingsTab />);+ await user.click(screen.getByText('Mapbox GL'));++ const dropdown = styleDropdown();+ await user.click(within(dropdown).getByRole('button'));++ expect(within(dropdown).getByText('Satellite Streets')).toBeInTheDocument();+ expect(within(dropdown).getAllByText('Apple-like').length).toBeGreaterThan(0);++ await user.click(within(dropdown).getByText('Streets'));++ expect(screen.getByDisplayValue('mapbox://styles/mapbox/streets-v12')).toBeInTheDocument();+ expect(within(dropdown).queryByText('Satellite Streets')).not.toBeInTheDocument();+ });++ it('FE-COMP-MAP-020: a mousedown outside the style picker closes it', async () => {+ const user = userEvent.setup();+ render(<MapSettingsTab />);+ await user.click(screen.getByText('Mapbox GL'));++ const dropdown = styleDropdown();+ await user.click(within(dropdown).getByRole('button'));+ expect(within(dropdown).getByText('Satellite Streets')).toBeInTheDocument();++ fireEvent.mouseDown(document.body);++ expect(within(dropdown).queryByText('Satellite Streets')).not.toBeInTheDocument();+ });++ it('FE-COMP-MAP-021: a custom style falls back to the picker placeholder', async () => {+ const user = userEvent.setup();+ render(<MapSettingsTab />);+ await user.click(screen.getByText('Mapbox GL'));++ const styleInput = screen.getByDisplayValue(MAPBOX_STANDARD);+ await user.clear(styleInput);+ await user.type(styleInput, 'mapbox://styles/me/custom');++ expect(within(styleDropdown()).getByText('Select a Mapbox style')).toBeInTheDocument();+ });++ it('FE-COMP-MAP-022: MapLibre needs no token and swaps in the OpenFreeMap presets', async () => {+ const user = userEvent.setup();+ render(<MapSettingsTab />);++ await user.click(screen.getByText('MapLibre GL'));++ expect(screen.queryByText('Mapbox Access Token')).not.toBeInTheDocument();+ expect(screen.queryByText('3D Buildings & Terrain')).not.toBeInTheDocument();+ expect(screen.getByDisplayValue(OFM_LIBERTY)).toBeInTheDocument();+ expect(screen.getByText('Preset or OpenFreeMap style URL. OpenFreeMap styles work without a token.')).toBeInTheDocument();+ expect(screen.getByTestId('gl-preview')).toHaveAttribute('data-provider', 'maplibre-gl');+ });++ it('FE-COMP-MAP-023: switching from MapLibre back to Mapbox drops the OpenFreeMap style', async () => {+ const user = userEvent.setup();+ render(<MapSettingsTab />);++ await user.click(screen.getByText('MapLibre GL'));+ expect(screen.getByDisplayValue(OFM_LIBERTY)).toBeInTheDocument();++ await user.click(screen.getByText('Mapbox GL'));++ expect(screen.getByDisplayValue(MAPBOX_STANDARD)).toBeInTheDocument();+ });++ it('FE-COMP-MAP-024: switching back to Leaflet restores the tile-template fields', async () => {+ const user = userEvent.setup();+ render(<MapSettingsTab />);++ await user.click(screen.getByText('Mapbox GL'));+ await user.click(screen.getByText('Leaflet'));++ expect(screen.getByText('Map Template')).toBeInTheDocument();+ expect(screen.queryByTestId('gl-preview')).not.toBeInTheDocument();+ expect(screen.getByTestId('map-view')).toBeInTheDocument();+ });++ it('FE-COMP-MAP-025: the token typed into the field reaches the preview', async () => {+ const user = userEvent.setup();+ render(<MapSettingsTab />);+ await user.click(screen.getByText('Mapbox GL'));++ await user.type(screen.getByPlaceholderText('pk.eyJ1Ijoi...'), 'pk.token');++ expect(screen.getByTestId('gl-preview')).toHaveAttribute('data-token', 'pk.token');+ });++ it('FE-COMP-MAP-026: the 3D and quality toggles drive the preview', async () => {+ const user = userEvent.setup();+ render(<MapSettingsTab />);+ await user.click(screen.getByText('Mapbox GL'));++ const preview = () => screen.getByTestId('gl-preview');+ expect(preview()).toHaveAttribute('data-3d', 'true');+ expect(preview()).toHaveAttribute('data-quality', 'false');++ await user.click(toggleFor('3D Buildings & Terrain'));+ expect(preview()).toHaveAttribute('data-3d', 'false');++ await user.click(toggleFor('High Quality Mode'));+ expect(preview()).toHaveAttribute('data-quality', 'true');+ });++ it('FE-COMP-MAP-027: saving under Mapbox writes the mapbox_style slot', async () => {+ const user = userEvent.setup();+ const updateSettings = vi.fn().mockResolvedValue(undefined);+ seedStore(useSettingsStore, { settings: buildSettings(), updateSettings });+ render(<MapSettingsTab />);++ await user.click(screen.getByText('Mapbox GL'));+ await user.click(screen.getByText('Save Map'));++ expect(updateSettings).toHaveBeenCalledWith(expect.objectContaining({+ map_provider: 'mapbox-gl',+ mapbox_style: MAPBOX_STANDARD,+ }));+ expect(updateSettings.mock.calls[0][0]).not.toHaveProperty('maplibre_style');+ });++ it('FE-COMP-MAP-028: saving under MapLibre writes the maplibre_style slot instead', async () => {+ const user = userEvent.setup();+ const updateSettings = vi.fn().mockResolvedValue(undefined);+ seedStore(useSettingsStore, { settings: buildSettings(), updateSettings });+ render(<MapSettingsTab />);++ await user.click(screen.getByText('MapLibre GL'));+ await user.click(screen.getByText('Save Map'));++ expect(updateSettings).toHaveBeenCalledWith(expect.objectContaining({+ map_provider: 'maplibre-gl',+ maplibre_style: OFM_LIBERTY,+ }));+ expect(updateSettings.mock.calls[0][0]).not.toHaveProperty('mapbox_style');+ });++ it('FE-COMP-MAP-029: a stored GL provider is restored from the settings', () => {+ seedStore(useSettingsStore, {+ settings: buildSettings({+ map_provider: 'maplibre-gl',+ maplibre_style: 'https://tiles.openfreemap.org/styles/bright',+ }),+ });+ render(<MapSettingsTab />);++ expect(screen.getByDisplayValue('https://tiles.openfreemap.org/styles/bright')).toBeInTheDocument();+ expect(within(styleDropdown()).getByText('OpenFreeMap Bright')).toBeInTheDocument();+ });++ it('FE-COMP-MAP-030: picking a Leaflet template fills the tile URL input', async () => {+ const user = userEvent.setup();+ render(<MapSettingsTab />);++ await user.click(screen.getByText('Select template...'));+ await user.click(await screen.findByText('CartoDB Dark'));++ expect(screen.getByDisplayValue('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png')).toBeInTheDocument();+ });+});diff --git a/client/src/components/Settings/MapboxPreview.test.tsx b/client/src/components/Settings/MapboxPreview.test.tsxnew file mode 100644index 000000000..882303667--- /dev/null+++ b/client/src/components/Settings/MapboxPreview.test.tsx@@ -0,0 +1,208 @@+// FE-COMP-GLPREVIEW-001 to FE-COMP-GLPREVIEW-014+import { render, screen, act } from '../../../tests/helpers/render';++type ClickHandler = (e: { lngLat: { lat: number; lng: number } }) => void;++const glHandlers = vi.hoisted(() => ({+ load: undefined as (() => void) | undefined,+ click: undefined as ClickHandler | undefined,+ reset() {+ this.load = undefined;+ this.click = undefined;+ },+}));++const glMap = vi.hoisted(() => ({+ on: vi.fn((event: string, cb: unknown) => {+ if (event === 'load') glHandlers.load = cb as () => void;+ if (event === 'click') glHandlers.click = cb as ClickHandler;+ }),+ remove: vi.fn(),+ jumpTo: vi.fn(),+ setTerrain: vi.fn(),+}));++const mapboxCtor = vi.hoisted(() => vi.fn(function (_options: Record<string, unknown>) {+ return glMap;+}));+const maplibreCtor = vi.hoisted(() => vi.fn(function (_options: Record<string, unknown>) {+ return glMap;+}));+const mapboxModule = vi.hoisted(() => ({ accessToken: '', Map: mapboxCtor }));++vi.mock('mapbox-gl', () => ({ default: mapboxModule }));+vi.mock('mapbox-gl/dist/mapbox-gl.css', () => ({}));+vi.mock('maplibre-gl', () => ({ default: { Map: maplibreCtor } }));+vi.mock('maplibre-gl/dist/maplibre-gl.css', () => ({}));++vi.mock('../Map/mapboxSetup', () => ({+ isStandardFamily: vi.fn(() => false),+ supportsCustom3d: vi.fn(() => true),+ addCustom3dBuildings: vi.fn(),+ addTerrainAndSky: vi.fn(),+}));++import { isStandardFamily, supportsCustom3d, addCustom3dBuildings, addTerrainAndSky } from '../Map/mapboxSetup';+import { MAPBOX_DEFAULT_STYLE, OPENFREEMAP_DEFAULT_STYLE } from '../Map/glProviders';+import GlMapPreview from './MapboxPreview';++const STREETS = 'mapbox://styles/mapbox/streets-v12';++function mapOptions(ctor: typeof mapboxCtor): Record<string, unknown> {+ return ctor.mock.calls[0][0] as Record<string, unknown>;+}++beforeEach(() => {+ vi.clearAllMocks();+ glHandlers.reset();+ mapboxModule.accessToken = '';+ document.documentElement.classList.remove('dark');+ vi.mocked(isStandardFamily).mockReturnValue(false);+ vi.mocked(supportsCustom3d).mockReturnValue(true);+});++describe('GlMapPreview', () => {+ it('FE-COMP-GLPREVIEW-001: without a Mapbox token it shows the hint instead of a map', () => {+ render(<GlMapPreview token="" style={STREETS} lat={48.8} lng={2.3} zoom={16} enable3d={false} />);++ expect(screen.getByText('Enter a Mapbox access token to preview')).toBeInTheDocument();+ expect(mapboxCtor).not.toHaveBeenCalled();+ expect(glMap.jumpTo).not.toHaveBeenCalled();+ });++ it('FE-COMP-GLPREVIEW-002: a token creates a Mapbox map centred on the given coordinates', () => {+ render(<GlMapPreview token="pk.test" style={STREETS} lat={48.8566} lng={2.3522} zoom={16} enable3d={false} />);++ expect(mapboxModule.accessToken).toBe('pk.test');+ expect(mapboxCtor).toHaveBeenCalledTimes(1);+ expect(mapOptions(mapboxCtor)).toMatchObject({+ style: STREETS,+ center: [2.3522, 48.8566],+ zoom: 16,+ pitch: 0,+ antialias: false,+ projection: 'mercator',+ });+ expect(screen.queryByText('Enter a Mapbox access token to preview')).not.toBeInTheDocument();+ });++ it('FE-COMP-GLPREVIEW-003: 3D pitches the camera on mount', () => {+ render(<GlMapPreview token="pk.test" style={STREETS} lat={48.8} lng={2.3} zoom={16} enable3d />);++ expect(mapOptions(mapboxCtor).pitch).toBe(45);+ });++ it('FE-COMP-GLPREVIEW-004: quality mode enables the globe projection and antialiasing', () => {+ render(<GlMapPreview token="pk.test" style={STREETS} lat={48.8} lng={2.3} zoom={16} enable3d={false} quality />);++ expect(mapOptions(mapboxCtor)).toMatchObject({ projection: 'globe', antialias: true });+ });++ it('FE-COMP-GLPREVIEW-005: MapLibre needs no token and never asks for a projection', () => {+ render(+ <GlMapPreview+ provider="maplibre-gl"+ style={OPENFREEMAP_DEFAULT_STYLE}+ lat={48.8}+ lng={2.3}+ zoom={16}+ enable3d+ />,+ );++ expect(maplibreCtor).toHaveBeenCalledTimes(1);+ expect(mapboxCtor).not.toHaveBeenCalled();+ const opts = mapOptions(maplibreCtor);+ expect(opts).toMatchObject({ aroundCenter: false, style: OPENFREEMAP_DEFAULT_STYLE, pitch: 0 });+ expect(opts).not.toHaveProperty('projection');+ });++ it('FE-COMP-GLPREVIEW-006: a Mapbox style is coerced to the OpenFreeMap default under MapLibre', () => {+ render(<GlMapPreview provider="maplibre-gl" style={STREETS} lat={48.8} lng={2.3} zoom={16} enable3d={false} />);++ expect(mapOptions(maplibreCtor).style).toBe(OPENFREEMAP_DEFAULT_STYLE);+ });++ it('FE-COMP-GLPREVIEW-007: loading a 3D-capable custom style adds terrain and buildings', () => {+ render(<GlMapPreview token="pk.test" style={STREETS} lat={48.8} lng={2.3} zoom={16} enable3d />);+ act(() => glHandlers.load?.());++ expect(addTerrainAndSky).toHaveBeenCalledWith(glMap);+ expect(addCustom3dBuildings).toHaveBeenCalledWith(glMap, false);+ expect(glMap.setTerrain).not.toHaveBeenCalled();+ });++ it('FE-COMP-GLPREVIEW-008: dark mode is passed through to the 3D building colours', () => {+ document.documentElement.classList.add('dark');+ render(<GlMapPreview token="pk.test" style={STREETS} lat={48.8} lng={2.3} zoom={16} enable3d />);+ act(() => glHandlers.load?.());++ expect(addCustom3dBuildings).toHaveBeenCalledWith(glMap, true);+ });++ it('FE-COMP-GLPREVIEW-009: a Standard-family style skips terrain and the custom building layer', () => {+ vi.mocked(isStandardFamily).mockReturnValue(true);+ vi.mocked(supportsCustom3d).mockReturnValue(false);+ render(<GlMapPreview token="pk.test" style={MAPBOX_DEFAULT_STYLE} lat={48.8} lng={2.3} zoom={16} enable3d />);+ act(() => glHandlers.load?.());++ expect(addTerrainAndSky).not.toHaveBeenCalled();+ expect(addCustom3dBuildings).not.toHaveBeenCalled();+ // The default style ships its own terrain, so the preview clears ours.+ expect(glMap.setTerrain).toHaveBeenCalledWith(null);+ });++ it('FE-COMP-GLPREVIEW-010: a failing setTerrain on load is swallowed', () => {+ glMap.setTerrain.mockImplementationOnce(() => {+ throw new Error('no terrain');+ });+ render(<GlMapPreview token="pk.test" style={MAPBOX_DEFAULT_STYLE} lat={48.8} lng={2.3} zoom={16} enable3d={false} />);++ expect(() => act(() => glHandlers.load?.())).not.toThrow();+ });++ it('FE-COMP-GLPREVIEW-011: with 3D off nothing is added on load', () => {+ render(<GlMapPreview token="pk.test" style={STREETS} lat={48.8} lng={2.3} zoom={16} enable3d={false} />);+ act(() => glHandlers.load?.());++ expect(addTerrainAndSky).not.toHaveBeenCalled();+ expect(addCustom3dBuildings).not.toHaveBeenCalled();+ });++ it('FE-COMP-GLPREVIEW-012: a map click reports the picked coordinates', () => {+ const onClick = vi.fn();+ render(<GlMapPreview token="pk.test" style={STREETS} lat={48.8} lng={2.3} zoom={16} enable3d={false} onClick={onClick} />);++ act(() => glHandlers.click?.({ lngLat: { lat: 51.5, lng: -0.12 } }));++ expect(onClick).toHaveBeenCalledWith({ lat: 51.5, lng: -0.12 });+ });++ it('FE-COMP-GLPREVIEW-013: moving the centre recenters instead of rebuilding the map', () => {+ const { rerender } = render(+ <GlMapPreview token="pk.test" style={STREETS} lat={48.8} lng={2.3} zoom={16} enable3d={false} />,+ );+ glMap.jumpTo.mockClear();++ rerender(<GlMapPreview token="pk.test" style={STREETS} lat={51.5} lng={-0.12} zoom={12} enable3d={false} />);++ expect(glMap.jumpTo).toHaveBeenCalledWith({ center: [-0.12, 51.5], zoom: 12 });+ expect(mapboxCtor).toHaveBeenCalledTimes(1);+ });++ it('FE-COMP-GLPREVIEW-014: a failing jumpTo is swallowed and unmounting removes the map', () => {+ glMap.jumpTo.mockImplementationOnce(() => {+ throw new Error('not ready');+ });+ const { unmount } = render(+ <GlMapPreview token="pk.test" style={STREETS} lat={48.8} lng={2.3} zoom={16} enable3d={false} />,+ );++ expect(glMap.jumpTo).toHaveBeenCalled();+ glMap.remove.mockImplementationOnce(() => {+ throw new Error('already gone');+ });+ expect(() => unmount()).not.toThrow();+ expect(glMap.remove).toHaveBeenCalled();+ });+});diff --git a/client/src/components/Settings/MobileNavPreview.test.tsx b/client/src/components/Settings/MobileNavPreview.test.tsxnew file mode 100644index 000000000..86ef00af9--- /dev/null+++ b/client/src/components/Settings/MobileNavPreview.test.tsx@@ -0,0 +1,70 @@+// FE-COMP-NAVPREVIEW-001 to FE-COMP-NAVPREVIEW-006+import { render, screen } from '../../../tests/helpers/render';+import { LayoutGrid, CalendarDays, Globe, Compass } from 'lucide-react';+import type { NavItemDef } from '../Layout/navItems';+import MobileNavPreview from './MobileNavPreview';++const DASHBOARD: NavItemDef = { id: 'dashboard', to: '/dashboard', label: 'My Trips', icon: LayoutGrid, pinned: true };+const VACAY: NavItemDef = { id: 'vacay', to: '/vacay', label: 'Vacay', icon: CalendarDays };+const ATLAS: NavItemDef = { id: 'atlas', to: '/atlas', label: 'Atlas', icon: Globe };+const JOURNEY: NavItemDef = { id: 'journey', to: '/journey', label: 'Journey', icon: Compass };++/** The dock's circles in DOM order, identified by their title attribute. */+function slots(container: HTMLElement): string[] {+ return Array.from(container.querySelectorAll('span[title]')).map(el => el.getAttribute('title') ?? '');+}++describe('MobileNavPreview', () => {+ it('FE-COMP-NAVPREVIEW-001: renders a circle per bar item plus the More slot', () => {+ const { container } = render(+ <MobileNavPreview bar={[DASHBOARD, VACAY, ATLAS]} hasMore moreLabel="More" />,+ );++ expect(slots(container)).toEqual(['My Trips', 'Vacay', 'Atlas', 'More']);+ expect(screen.getByTitle('Vacay')).toBeInTheDocument();+ });++ it('FE-COMP-NAVPREVIEW-002: the More circle is dropped when nothing is demoted', () => {+ const { container } = render(<MobileNavPreview bar={[DASHBOARD, VACAY]} hasMore={false} moreLabel="More" />);++ expect(slots(container)).toEqual(['My Trips', 'Vacay']);+ expect(screen.queryByTitle('More')).not.toBeInTheDocument();+ });++ it('FE-COMP-NAVPREVIEW-003: the raised centre button splits the slots evenly around it', () => {+ const { container } = render(+ <MobileNavPreview bar={[DASHBOARD, VACAY, ATLAS]} hasMore moreLabel="More" />,+ );++ const row = container.firstElementChild as HTMLElement;+ const children = Array.from(row.children);+ // 4 slots → 2 on the left, then the "+", then the rest.+ const centre = children.findIndex(c => !c.hasAttribute('title'));+ expect(centre).toBe(2);+ expect(children).toHaveLength(5);+ });++ it('FE-COMP-NAVPREVIEW-004: an odd slot count keeps the extra circle on the left', () => {+ const { container } = render(+ <MobileNavPreview bar={[DASHBOARD, VACAY, ATLAS, JOURNEY]} hasMore={false} moreLabel="More" />,+ );++ const children = Array.from((container.firstElementChild as HTMLElement).children);+ const centre = children.findIndex(c => !c.hasAttribute('title'));+ expect(centre).toBe(2);+ expect(slots(container)).toEqual(['My Trips', 'Vacay', 'Atlas', 'Journey']);+ });++ it('FE-COMP-NAVPREVIEW-005: an empty bar still renders the centre action', () => {+ const { container } = render(<MobileNavPreview bar={[]} hasMore={false} moreLabel="More" />);++ expect(slots(container)).toEqual([]);+ expect((container.firstElementChild as HTMLElement).children).toHaveLength(1);+ });++ it('FE-COMP-NAVPREVIEW-006: the More label comes from the caller', () => {+ render(<MobileNavPreview bar={[DASHBOARD]} hasMore moreLabel="Mehr" />);++ expect(screen.getByTitle('Mehr')).toBeInTheDocument();+ });+});diff --git a/client/src/components/Settings/NotificationsTab.test.tsx b/client/src/components/Settings/NotificationsTab.test.tsxindex d52b8500c..d5ceb72a6 100644--- a/client/src/components/Settings/NotificationsTab.test.tsx+++ b/client/src/components/Settings/NotificationsTab.test.tsx@@ -851,3 +851,284 @@ describe('NotificationsTab — plugin channels', () => {expect(screen.queryByText('Gotify')).not.toBeInTheDocument();});});++// ─────────────────────────────────────────────────────────────────────────────+// Ntfy credentials, webhook edge cases and channel-test failures (015–029)+// ─────────────────────────────────────────────────────────────────────────────++const ntfyMatrix = {+ preferences: { trip_invite: { inapp: true, ntfy: true } },+ channels: [+ { id: 'inapp', source: 'builtin', labelKey: 'settings.notificationPreferences.inapp', active: true, configured: true },+ { id: 'ntfy', source: 'builtin', labelKey: 'settings.notificationPreferences.ntfy', active: true, configured: true },+ ],+ event_types: ['trip_invite'],+ implemented_combos: { trip_invite: ['inapp', 'ntfy'] },+ defaults: { ntfyServer: 'https://ntfy.example.org' },+};++const webhookMatrix = {+ preferences: { trip_invite: { inapp: true, webhook: true } },+ channels: [+ { id: 'inapp', source: 'builtin', labelKey: 'settings.notificationPreferences.inapp', active: true, configured: true },+ { id: 'webhook', source: 'builtin', labelKey: 'settings.notificationPreferences.webhook', active: true, configured: true },+ ],+ event_types: ['trip_invite'],+ implemented_combos: { trip_invite: ['inapp', 'webhook'] },+};++function mockNtfy(settings: Record<string, unknown> = {}) {+ server.use(+ http.get('*/api/notifications/preferences', () => HttpResponse.json(ntfyMatrix)),+ http.get('*/api/settings', () => HttpResponse.json({ settings })),+ );+}++function tokenInput(): HTMLInputElement {+ return document.querySelector('input[type="password"]') as HTMLInputElement;+}++describe('NotificationsTab — ntfy credentials', () => {+ beforeEach(() => {+ resetAllStores();+ seedStore(useAuthStore, { isAuthenticated: true, user: buildUser() });+ });++ it('FE-COMP-NOTIFICATIONS-015: a stored token is masked and the server default fills the placeholder', async () => {+ mockNtfy({ ntfy_topic: 'alerts', ntfy_token: '••••••••' });+ render(<NotificationsTab />);++ expect(await screen.findByDisplayValue('alerts')).toBeInTheDocument();+ expect(tokenInput()).toHaveValue('');+ expect(tokenInput()).toHaveAttribute('placeholder', '••••••••');+ expect(screen.getByPlaceholderText('https://ntfy.example.org')).toHaveValue('');+ });++ it('FE-COMP-NOTIFICATIONS-016: saving sends topic and server but omits the untouched token', async () => {+ const user = userEvent.setup();+ let body: { settings: Record<string, unknown> } | null = null;+ mockNtfy({ ntfy_topic: 'alerts', ntfy_token: '••••••••' });+ server.use(+ http.post('*/api/settings/bulk', async ({ request }) => {+ body = (await request.json()) as { settings: Record<string, unknown> };+ return HttpResponse.json({ success: true });+ }),+ );+ render(<><NotificationsTab /><ToastContainer /></>);++ await user.type(await screen.findByPlaceholderText('https://ntfy.example.org'), 'https://ntfy.self.host');+ await user.click(screen.getByRole('button', { name: 'Save' }));++ await screen.findByText('Ntfy settings saved');+ expect(body!.settings).toEqual({ ntfy_topic: 'alerts', ntfy_server: 'https://ntfy.self.host' });+ });++ it('FE-COMP-NOTIFICATIONS-017: a freshly typed token is sent and switches the field to masked', async () => {+ const user = userEvent.setup();+ let body: { settings: Record<string, unknown> } | null = null;+ mockNtfy({ ntfy_topic: 'alerts' });+ server.use(+ http.post('*/api/settings/bulk', async ({ request }) => {+ body = (await request.json()) as { settings: Record<string, unknown> };+ return HttpResponse.json({ success: true });+ }),+ );+ render(<NotificationsTab />);++ await screen.findByDisplayValue('alerts');+ await user.type(tokenInput(), 'tk_secret');+ await user.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(body!.settings).toMatchObject({ ntfy_token: 'tk_secret' }));+ await waitFor(() => expect(screen.getByRole('button', { name: 'Clear' })).toBeInTheDocument());+ });++ it('FE-COMP-NOTIFICATIONS-018: a failing ntfy save toasts the generic error', async () => {+ const user = userEvent.setup();+ mockNtfy({ ntfy_topic: 'alerts' });+ server.use(+ http.post('*/api/settings/bulk', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),+ );+ render(<><NotificationsTab /><ToastContainer /></>);++ await screen.findByDisplayValue('alerts');+ await user.click(screen.getByRole('button', { name: 'Save' }));++ await screen.findByText('Error');+ });++ it('FE-COMP-NOTIFICATIONS-019: Clear wipes the stored token and hides the button', async () => {+ const user = userEvent.setup();+ let body: { key: string; value: unknown } | null = null;+ mockNtfy({ ntfy_topic: 'alerts', ntfy_token: '••••••••' });+ server.use(+ http.put('*/api/settings', async ({ request }) => {+ body = (await request.json()) as { key: string; value: unknown };+ return HttpResponse.json({ success: true });+ }),+ );+ render(<><NotificationsTab /><ToastContainer /></>);++ await user.click(await screen.findByRole('button', { name: 'Clear' }));++ await screen.findByText('Access token cleared');+ expect(body).toEqual({ key: 'ntfy_token', value: '' });+ expect(screen.queryByRole('button', { name: 'Clear' })).not.toBeInTheDocument();+ });++ it('FE-COMP-NOTIFICATIONS-020: a failing clear keeps the token and toasts', async () => {+ const user = userEvent.setup();+ mockNtfy({ ntfy_topic: 'alerts', ntfy_token: '••••••••' });+ server.use(+ http.put('*/api/settings', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),+ );+ render(<><NotificationsTab /><ToastContainer /></>);++ await user.click(await screen.findByRole('button', { name: 'Clear' }));++ await screen.findByText('Error');+ expect(screen.getByRole('button', { name: 'Clear' })).toBeInTheDocument();+ });++ it('FE-COMP-NOTIFICATIONS-021: a successful test posts topic and server, and never the masked token', async () => {+ const user = userEvent.setup();+ let body: Record<string, unknown> | null = null;+ mockNtfy({ ntfy_topic: 'alerts', ntfy_server: 'https://ntfy.sh', ntfy_token: '••••••••' });+ server.use(+ http.post('*/api/notifications/test-ntfy', async ({ request }) => {+ body = (await request.json()) as Record<string, unknown>;+ return HttpResponse.json({ success: true });+ }),+ );+ render(<><NotificationsTab /><ToastContainer /></>);++ await screen.findByDisplayValue('alerts');+ await user.click(screen.getByRole('button', { name: 'Test' }));++ await screen.findByText('Test ntfy notification sent successfully');+ expect(body).toEqual({ topic: 'alerts', server: 'https://ntfy.sh', token: null });+ });++ it('FE-COMP-NOTIFICATIONS-022: a refused test shows the message the server returned', async () => {+ const user = userEvent.setup();+ mockNtfy({ ntfy_topic: 'alerts' });+ server.use(+ http.post('*/api/notifications/test-ntfy', () => HttpResponse.json({ success: false, error: 'Topic not found' })),+ );+ render(<><NotificationsTab /><ToastContainer /></>);++ await screen.findByDisplayValue('alerts');+ await user.click(screen.getByRole('button', { name: 'Test' }));++ await screen.findByText('Topic not found');+ });++ it('FE-COMP-NOTIFICATIONS-023: a network error during the test falls back to the generic message', async () => {+ const user = userEvent.setup();+ mockNtfy({ ntfy_topic: 'alerts' });+ server.use(+ http.post('*/api/notifications/test-ntfy', () => HttpResponse.json({ error: 'down' }, { status: 500 })),+ );+ render(<><NotificationsTab /><ToastContainer /></>);++ await screen.findByDisplayValue('alerts');+ await user.click(screen.getByRole('button', { name: 'Test' }));++ await screen.findByText('Test ntfy notification failed');+ });++ it('FE-COMP-NOTIFICATIONS-024: without a topic the test button stays disabled', async () => {+ mockNtfy({});+ render(<NotificationsTab />);++ await waitFor(() => expect(screen.getByRole('button', { name: 'Test' })).toBeDisabled());+ expect(screen.getByPlaceholderText('my-trek-alerts')).toHaveValue('');+ });+});++describe('NotificationsTab — webhook and channel-test failures', () => {+ beforeEach(() => {+ resetAllStores();+ seedStore(useAuthStore, { isAuthenticated: true, user: buildUser() });+ server.use(+ http.get('*/api/notifications/preferences', () => HttpResponse.json(webhookMatrix)),+ http.get('*/api/settings', () => HttpResponse.json({ settings: { webhook_url: '••••••••' } })),+ );+ });++ it('FE-COMP-NOTIFICATIONS-025: saving an empty URL unsets the stored webhook', async () => {+ const user = userEvent.setup();+ let body: { key: string; value: unknown } | null = null;+ server.use(+ http.put('*/api/settings', async ({ request }) => {+ body = (await request.json()) as { key: string; value: unknown };+ return HttpResponse.json({ success: true });+ }),+ );+ render(<><NotificationsTab /><ToastContainer /></>);++ const input = await screen.findByRole('textbox');+ expect(input).toHaveAttribute('placeholder', '••••••••');+ await user.click(screen.getByRole('button', { name: 'Save' }));++ await screen.findByText('Webhook URL saved');+ expect(body).toEqual({ key: 'webhook_url', value: '' });+ await waitFor(() =>+ expect(screen.getByRole('textbox')).toHaveAttribute('placeholder', 'https://discord.com/api/webhooks/...'),+ );+ });++ it('FE-COMP-NOTIFICATIONS-026: a failing webhook save toasts the generic error', async () => {+ const user = userEvent.setup();+ server.use(+ http.put('*/api/settings', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),+ );+ render(<><NotificationsTab /><ToastContainer /></>);++ await screen.findByRole('textbox');+ await user.click(screen.getByRole('button', { name: 'Save' }));++ await screen.findByText('Error');+ });++ it('FE-COMP-NOTIFICATIONS-027: a network error during the webhook test falls back to the generic message', async () => {+ const user = userEvent.setup();+ server.use(+ http.post('*/api/notifications/test-webhook', () => HttpResponse.json({ error: 'down' }, { status: 500 })),+ );+ render(<><NotificationsTab /><ToastContainer /></>);++ await screen.findByRole('textbox');+ await user.click(screen.getByRole('button', { name: 'Test' }));++ await screen.findByText('Test webhook failed');+ });++ it('FE-COMP-NOTIFICATIONS-028: a refused plugin channel test reports the returned error', async () => {+ const user = userEvent.setup();+ mockMatrix(pluginMatrix());+ server.use(+ http.post('*/api/notifications/test/:channelId', () =>+ HttpResponse.json({ success: false, error: 'Gotify rejected the token' }),+ ),+ );+ render(<><NotificationsTab /><ToastContainer /></>);++ await user.click(await screen.findByRole('button', { name: /send test/i }));++ await screen.findByText('Gotify rejected the token');+ });++ it('FE-COMP-NOTIFICATIONS-029: a plugin channel test that errors out falls back to the generic message', async () => {+ const user = userEvent.setup();+ mockMatrix(pluginMatrix());+ server.use(+ http.post('*/api/notifications/test/:channelId', () => HttpResponse.json({ error: 'down' }, { status: 500 })),+ );+ render(<><NotificationsTab /><ToastContainer /></>);++ await user.click(await screen.findByRole('button', { name: /send test/i }));++ await screen.findByText('Test failed.');+ });+});diff --git a/client/src/components/Settings/OfflineTab.test.tsx b/client/src/components/Settings/OfflineTab.test.tsxnew file mode 100644index 000000000..ee37d2693--- /dev/null+++ b/client/src/components/Settings/OfflineTab.test.tsx@@ -0,0 +1,487 @@+// FE-COMP-OFFLINETAB-001 to FE-COMP-OFFLINETAB-024+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import userEvent from '@testing-library/user-event';+import { http, HttpResponse } from 'msw';+import { act, render, screen, waitFor, within } from '../../../tests/helpers/render';+import { resetAllStores, seedStore } from '../../../tests/helpers/store';+import { buildTrip, buildUser } from '../../../tests/helpers/factories';+import { server } from '../../../tests/helpers/msw/server';+import { useAuthStore } from '../../store/authStore';+import { _resetNetworkMode } from '../../sync/networkMode';+import { _resetOfflinePrefs, getOfflinePrefs } from '../../sync/offlinePrefs';+import type { QueuedMutation, SyncMeta } from '../../db/offlineDb';+import type { PrepareProgress } from '../../sync/tripSyncManager';+import type { Trip } from '../../types';+import OfflineTab from './OfflineTab';++// Dexie, the sync manager, the mutation queue and the tile cache are the four+// side-effecting neighbours of this tab; network mode, offline prefs and the+// trips API run for real.+const h = vi.hoisted(() => {+ const syncMetaToArray = vi.fn();+ const tripsGet = vi.fn();+ const tripsToArray = vi.fn();+ const placeCount = vi.fn();+ const fileCount = vi.fn();+ const counted = (fn: (id: number) => Promise<number>) => ({+ where: () => ({ equals: (id: number) => ({ count: () => fn(id) }) }),+ });+ return {+ syncMetaToArray, tripsGet, tripsToArray, placeCount, fileCount,+ fakeDb: {+ syncMeta: { toArray: syncMetaToArray },+ trips: { get: tripsGet, toArray: tripsToArray },+ places: counted(placeCount),+ tripFiles: counted(fileCount),+ },+ clearAll: vi.fn(),+ clearTripData: vi.fn(),+ prepareForOffline: vi.fn(),+ syncAll: vi.fn(),+ pendingCount: vi.fn(),+ failedCount: vi.fn(),+ conflicts: vi.fn(),+ resolveKeepMine: vi.fn(),+ resolveKeepServer: vi.fn(),+ clearTileCache: vi.fn(),+ };+});++vi.mock('../../db/offlineDb', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../../db/offlineDb')>();+ return { ...actual, offlineDb: h.fakeDb, clearAll: h.clearAll, clearTripData: h.clearTripData };+});++vi.mock('../../sync/tripSyncManager', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../../sync/tripSyncManager')>();+ return { ...actual, tripSyncManager: { prepareForOffline: h.prepareForOffline, syncAll: h.syncAll } };+});++vi.mock('../../sync/mutationQueue', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../../sync/mutationQueue')>();+ return {+ ...actual,+ mutationQueue: {+ pendingCount: h.pendingCount,+ failedCount: h.failedCount,+ conflicts: h.conflicts,+ resolveKeepMine: h.resolveKeepMine,+ resolveKeepServer: h.resolveKeepServer,+ },+ };+});++vi.mock('../../sync/tilePrefetcher', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../../sync/tilePrefetcher')>();+ return { ...actual, clearTileCache: h.clearTileCache };+});++const paris = buildTrip({ id: 1, title: 'Paris', start_date: '2025-06-01', end_date: '2025-06-05' });+const tokyo = buildTrip({ id: 2, title: 'Tokyo', start_date: '2025-09-01', end_date: '2025-09-15' });++const meta = (tripId: number, over: Partial<SyncMeta> = {}): SyncMeta => ({+ tripId,+ lastSyncedAt: null,+ status: 'idle',+ tilesBbox: null,+ filesCachedCount: 0,+ ...over,+});++const conflict = (over: Partial<QueuedMutation> = {}): QueuedMutation => ({+ id: 'c1',+ tripId: 1,+ method: 'PUT',+ url: '/trips/1/places/9',+ body: { name: 'Louvre' },+ createdAt: 0,+ status: 'conflict',+ attempts: 1,+ lastError: null,+ ...over,+});++/** Seed the Dexie cache with the given (trip, meta) pairs. */+function cache(rows: { trip: Trip; meta?: Partial<SyncMeta>; places?: number; files?: number }[]): void {+ h.syncMetaToArray.mockResolvedValue(rows.map(r => meta(r.trip.id, r.meta)));+ h.tripsGet.mockImplementation(async (id: number) => rows.find(r => r.trip.id === id)?.trip);+ h.placeCount.mockImplementation(async (id: number) => rows.find(r => r.trip.id === id)?.places ?? 0);+ h.fileCount.mockImplementation(async (id: number) => rows.find(r => r.trip.id === id)?.files ?? 0);+}++function setOnLine(value: boolean): void {+ Object.defineProperty(window.navigator, 'onLine', { value, configurable: true });+}++/** The Section wrapper card that carries the given heading. */+const card = (title: string) => screen.getByText(title).closest('div.rounded-xl') as HTMLElement;++/** The Stat tile that carries the given label. */+const stat = (label: string) => screen.getByText(label).parentElement as HTMLElement;++beforeEach(() => {+ vi.clearAllMocks();+ resetAllStores();+ _resetNetworkMode();+ _resetOfflinePrefs();+ setOnLine(true);+ seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });++ h.syncMetaToArray.mockResolvedValue([]);+ h.tripsGet.mockResolvedValue(undefined);+ h.tripsToArray.mockResolvedValue([]);+ h.placeCount.mockResolvedValue(0);+ h.fileCount.mockResolvedValue(0);+ h.pendingCount.mockResolvedValue(0);+ h.failedCount.mockResolvedValue(0);+ h.conflicts.mockResolvedValue([]);+ h.clearAll.mockResolvedValue(undefined);+ h.clearTripData.mockResolvedValue(undefined);+ h.clearTileCache.mockResolvedValue(undefined);+ h.prepareForOffline.mockResolvedValue(undefined);+ h.syncAll.mockResolvedValue(undefined);+ h.resolveKeepMine.mockResolvedValue(undefined);+ h.resolveKeepServer.mockResolvedValue(undefined);++ server.use(http.get('/api/trips', () => HttpResponse.json({ trips: [paris, tokyo] })));+});++afterEach(() => {+ setOnLine(true);+ vi.restoreAllMocks();+});++describe('OfflineTab', () => {+ it('FE-COMP-OFFLINETAB-001: shows the loading line while the cache is being read', () => {+ h.syncMetaToArray.mockReturnValue(new Promise(() => {}));+ render(<OfflineTab />);++ expect(screen.getByText('Loading…')).toBeInTheDocument();+ expect(screen.getByText('Offline mode')).toBeInTheDocument();+ expect(screen.queryByText('No trips cached yet. Connect to the internet to sync.')).not.toBeInTheDocument();+ });++ it('FE-COMP-OFFLINETAB-002: an empty cache reports zero stats and disables Clear cache', async () => {+ render(<OfflineTab />);++ expect(await screen.findByText('No trips cached yet. Connect to the internet to sync.')).toBeInTheDocument();+ expect(within(stat('Cached trips')).getByText('0')).toBeInTheDocument();+ expect(within(stat('Pending changes')).getByText('0')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Clear cache' })).toBeDisabled();+ expect(screen.queryByText('Failed changes')).not.toBeInTheDocument();+ expect(screen.queryByText('Conflicts')).not.toBeInTheDocument();+ expect(screen.queryByText('Sync conflicts')).not.toBeInTheDocument();+ });++ it('FE-COMP-OFFLINETAB-003: cached trips are listed oldest first with their place and file counts', async () => {+ cache([+ { trip: tokyo, places: 3, files: 1 },+ { trip: paris, places: 7, files: 2 },+ ]);+ render(<OfflineTab />);++ const cacheCard = card('Offline cache');+ await waitFor(() => expect(within(cacheCard).getByText('Paris')).toBeInTheDocument());+ const titles = within(cacheCard).getAllByText(/^(Paris|Tokyo)$/).map(el => el.textContent);+ expect(titles).toEqual(['Paris', 'Tokyo']);+ expect(within(cacheCard).getByText(/Jun 1, 2025 – Jun 5, 2025/)).toHaveTextContent('7');+ expect(within(cacheCard).getByText(/Sep 1, 2025 – Sep 15, 2025/)).toHaveTextContent('3');+ expect(within(stat('Cached trips')).getByText('2')).toBeInTheDocument();+ // Never synced → the time column shows a dash.+ expect(within(cacheCard).getAllByText('—')).toHaveLength(2);+ });++ it('FE-COMP-OFFLINETAB-004: a trip without dates renders dashes instead of a range', async () => {+ cache([{ trip: buildTrip({ id: 3, title: 'Someday', start_date: null, end_date: null }) }]);+ render(<OfflineTab />);++ const cacheCard = card('Offline cache');+ await waitFor(() => expect(within(cacheCard).getByText('Someday')).toBeInTheDocument());+ expect(within(cacheCard).getByText(/— – —/)).toBeInTheDocument();+ });++ it('FE-COMP-OFFLINETAB-005: a sync-meta row without its trip in Dexie is dropped', async () => {+ h.syncMetaToArray.mockResolvedValue([meta(1), meta(99)]);+ h.tripsGet.mockImplementation(async (id: number) => (id === 1 ? paris : undefined));+ render(<OfflineTab />);++ const cacheCard = card('Offline cache');+ await waitFor(() => expect(within(cacheCard).getByText('Paris')).toBeInTheDocument());+ expect(within(stat('Cached trips')).getByText('1')).toBeInTheDocument();+ });++ it('FE-COMP-OFFLINETAB-006: a synced trip shows its last sync time instead of a dash', async () => {+ const at = new Date('2025-06-02T09:30:00Z').getTime();+ cache([{ trip: paris, meta: { lastSyncedAt: at } }]);+ render(<OfflineTab />);++ const cacheCard = card('Offline cache');+ await waitFor(() => expect(within(cacheCard).getByText('Paris')).toBeInTheDocument());+ const expected = new Date(at).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });+ expect(within(cacheCard).getByText(expected)).toBeInTheDocument();+ });++ it('FE-COMP-OFFLINETAB-007: pending, failed and conflict counters only appear when they are non-zero', async () => {+ h.pendingCount.mockResolvedValue(4);+ h.failedCount.mockResolvedValue(2);+ h.conflicts.mockResolvedValue([conflict()]);+ render(<OfflineTab />);++ await waitFor(() => expect(screen.getByText('Failed changes')).toBeInTheDocument());+ expect(within(stat('Pending changes')).getByText('4')).toBeInTheDocument();+ expect(within(stat('Failed changes')).getByText('2')).toBeInTheDocument();+ expect(within(stat('Conflicts')).getByText('1')).toBeInTheDocument();+ });++ it('FE-COMP-OFFLINETAB-008: conflicts are named from the queued body, the server copy or the entity id', async () => {+ h.conflicts.mockResolvedValue([+ conflict({ id: 'a', body: { name: 'Louvre' } }),+ conflict({ id: 'b', body: {}, conflictServer: { name: 'Server name' } }),+ conflict({ id: 'c', body: {}, entityId: 42 }),+ ]);+ render(<OfflineTab />);++ await screen.findByText('Sync conflicts');+ expect(screen.getByText(/Louvre/)).toBeInTheDocument();+ expect(screen.getByText(/Server name/)).toBeInTheDocument();+ expect(screen.getByText(/#42/)).toBeInTheDocument();+ });++ it('FE-COMP-OFFLINETAB-009: keep-mine and keep-theirs resolve the right conflict and reload', async () => {+ const user = userEvent.setup();+ h.conflicts.mockResolvedValue([conflict({ id: 'a' }), conflict({ id: 'b', body: { name: 'Eiffel' } })]);+ render(<OfflineTab />);++ const row = (await screen.findByText(/Eiffel/)).parentElement as HTMLElement;+ await user.click(within(row).getByRole('button', { name: 'Keep mine' }));+ expect(h.resolveKeepMine).toHaveBeenCalledWith('b');+ expect(h.resolveKeepServer).not.toHaveBeenCalled();++ await user.click(within(row).getByRole('button', { name: 'Keep theirs' }));+ expect(h.resolveKeepServer).toHaveBeenCalledWith('b');+ // Both resolutions re-read the cache (once on mount + once per resolution).+ await waitFor(() => expect(h.conflicts).toHaveBeenCalledTimes(3));+ });++ it('FE-COMP-OFFLINETAB-010: the conflict strategy select persists the choice', async () => {+ const user = userEvent.setup();+ h.conflicts.mockResolvedValue([conflict()]);+ render(<OfflineTab />);++ await screen.findByText('When a conflict happens');+ const select = screen.getByRole('combobox') as HTMLSelectElement;+ expect(select.value).toBe('ask');++ await user.selectOptions(select, 'server');+ expect(getOfflinePrefs().conflictStrategy).toBe('server');+ await waitFor(() => expect(select.value).toBe('server'));+ });++ it('FE-COMP-OFFLINETAB-011: Prepare renders live progress and the done marker', async () => {+ const user = userEvent.setup();+ let release!: () => void;+ h.prepareForOffline.mockImplementation(async (cb: (p: PrepareProgress) => void) => {+ cb({ phase: 'files', current: 1, total: 4, label: 'Paris' });+ await new Promise<void>(resolve => { release = resolve; });+ cb({ phase: 'done', current: 4, total: 4 });+ });+ render(<OfflineTab />);++ await screen.findByText('No trips cached yet. Connect to the internet to sync.');+ await user.click(screen.getByRole('button', { name: 'Download for offline use' }));++ expect(await screen.findByText('Documents · 1/4 · Paris')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Downloading…' })).toBeDisabled();++ await act(async () => { release(); });+ expect(await screen.findByText('Ready for offline use')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Download for offline use' })).toBeEnabled();+ });++ it('FE-COMP-OFFLINETAB-012: a progress report without a total renders a full bar', async () => {+ const user = userEvent.setup();+ let release!: () => void;+ h.prepareForOffline.mockImplementation(async (cb: (p: PrepareProgress) => void) => {+ cb({ phase: 'tiles', current: 0, total: 0 });+ await new Promise<void>(resolve => { release = resolve; });+ });+ render(<OfflineTab />);++ await screen.findByText('No trips cached yet. Connect to the internet to sync.');+ await user.click(screen.getByRole('button', { name: 'Download for offline use' }));++ const label = await screen.findByText('Map tiles · 0/0');+ const bar = label.previousElementSibling?.firstElementChild as HTMLElement;+ expect(bar).toHaveStyle({ width: '100%' });+ await act(async () => { release(); });+ });++ it('FE-COMP-OFFLINETAB-013: a half-finished trips phase renders a proportional bar', async () => {+ const user = userEvent.setup();+ let release!: () => void;+ h.prepareForOffline.mockImplementation(async (cb: (p: PrepareProgress) => void) => {+ cb({ phase: 'trips', current: 1, total: 4 });+ await new Promise<void>(resolve => { release = resolve; });+ });+ render(<OfflineTab />);++ await screen.findByText('No trips cached yet. Connect to the internet to sync.');+ await user.click(screen.getByRole('button', { name: 'Download for offline use' }));++ const label = await screen.findByText('Trip data · 1/4');+ const bar = label.previousElementSibling?.firstElementChild as HTMLElement;+ expect(bar).toHaveStyle({ width: '25%' });+ await act(async () => { release(); });+ });++ it('FE-COMP-OFFLINETAB-014: forcing offline downloads first, then engages and locks the actions', async () => {+ const user = userEvent.setup();+ render(<OfflineTab />);++ await screen.findByText('No trips cached yet. Connect to the internet to sync.');+ await user.click(screen.getByRole('button', { name: 'Force offline mode' }));++ expect(h.prepareForOffline).toHaveBeenCalledTimes(1);+ expect(await screen.findByText(/Offline mode is on/)).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Download for offline use' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Re-sync now' })).toBeDisabled();++ await user.click(screen.getByRole('button', { name: 'Force offline mode' }));+ await waitFor(() => expect(screen.queryByText(/Offline mode is on/)).not.toBeInTheDocument());+ expect(screen.getByRole('button', { name: 'Re-sync now' })).toBeEnabled();+ });++ it('FE-COMP-OFFLINETAB-015: forcing offline while already disconnected skips the download', async () => {+ const user = userEvent.setup();+ setOnLine(false);+ render(<OfflineTab />);++ await screen.findByText('No trips cached yet. Connect to the internet to sync.');+ expect(screen.getByRole('button', { name: 'Download for offline use' })).toBeDisabled();+ await user.click(screen.getByRole('button', { name: 'Force offline mode' }));++ expect(h.prepareForOffline).not.toHaveBeenCalled();+ expect(await screen.findByText(/Offline mode is on/)).toBeInTheDocument();+ // Offline, the trip list comes out of Dexie instead of the API.+ expect(h.tripsToArray).toHaveBeenCalled();+ });++ it('FE-COMP-OFFLINETAB-016: Re-sync runs syncAll and re-reads the cache', async () => {+ const user = userEvent.setup();+ render(<OfflineTab />);++ await screen.findByText('No trips cached yet. Connect to the internet to sync.');+ await user.click(screen.getByRole('button', { name: 'Re-sync now' }));++ expect(h.syncAll).toHaveBeenCalledTimes(1);+ await waitFor(() => expect(h.syncMetaToArray).toHaveBeenCalledTimes(2));+ });++ it('FE-COMP-OFFLINETAB-017: Re-sync shows the syncing label while it runs', async () => {+ const user = userEvent.setup();+ let release!: () => void;+ h.syncAll.mockImplementation(() => new Promise<void>(resolve => { release = resolve; }));+ render(<OfflineTab />);++ await screen.findByText('No trips cached yet. Connect to the internet to sync.');+ await user.click(screen.getByRole('button', { name: 'Re-sync now' }));++ expect(await screen.findByRole('button', { name: 'Syncing…' })).toBeDisabled();+ await act(async () => { release(); });+ expect(await screen.findByRole('button', { name: 'Re-sync now' })).toBeEnabled();+ });++ it('FE-COMP-OFFLINETAB-018: turning map tiles off drops the tile cache, turning them back on does not', async () => {+ const user = userEvent.setup();+ render(<OfflineTab />);++ const toggle = await screen.findByRole('button', { name: 'Store map tiles offline' });+ expect(toggle).toHaveAttribute('aria-pressed', 'true');++ await user.click(toggle);+ expect(getOfflinePrefs().cacheTiles).toBe(false);+ expect(h.clearTileCache).toHaveBeenCalledTimes(1);+ await waitFor(() => expect(toggle).toHaveAttribute('aria-pressed', 'false'));++ await user.click(toggle);+ expect(getOfflinePrefs().cacheTiles).toBe(true);+ expect(h.clearTileCache).toHaveBeenCalledTimes(1);+ });++ it('FE-COMP-OFFLINETAB-019: switching a trip off evicts it, switching it back on re-syncs', async () => {+ const user = userEvent.setup();+ render(<OfflineTab />);++ const toggle = await screen.findByRole('button', { name: 'Tokyo' });+ expect(toggle).toHaveAttribute('aria-pressed', 'true');+ expect(screen.getAllByText('Stored offline')).toHaveLength(2);++ await user.click(toggle);+ expect(h.clearTripData).toHaveBeenCalledWith(2);+ await waitFor(() => expect(screen.getByText('Not stored')).toBeInTheDocument());++ await user.click(toggle);+ await waitFor(() => expect(h.syncAll).toHaveBeenCalledTimes(1));+ expect(h.clearTripData).toHaveBeenCalledTimes(1);+ });++ it('FE-COMP-OFFLINETAB-020: the per-trip section disappears when there are no trips at all', async () => {+ server.use(http.get('/api/trips', () => HttpResponse.json({ trips: [] })));+ render(<OfflineTab />);++ await screen.findByText('No trips cached yet. Connect to the internet to sync.');+ expect(screen.queryByText('Trips')).not.toBeInTheDocument();+ expect(screen.getByText('Store map tiles offline')).toBeInTheDocument();+ });++ it('FE-COMP-OFFLINETAB-021: a failing trips API falls back to the Dexie copy', async () => {+ server.use(http.get('/api/trips', () => HttpResponse.json({ error: 'down' }, { status: 500 })));+ h.tripsToArray.mockResolvedValue([tokyo, paris]);+ render(<OfflineTab />);++ await screen.findByRole('button', { name: 'Paris' });+ // Dexie rows are sorted by start date too.+ const labels = screen.getAllByRole('button')+ .map(el => el.getAttribute('aria-label'))+ .filter((l): l is string => l !== null);+ expect(labels).toEqual(['Force offline mode', 'Store map tiles offline', 'Paris', 'Tokyo']);+ });++ it('FE-COMP-OFFLINETAB-022: when both the API and Dexie fail the trip list is simply empty', async () => {+ server.use(http.get('/api/trips', () => HttpResponse.json({ error: 'down' }, { status: 500 })));+ h.tripsToArray.mockRejectedValue(new Error('dexie is gone'));+ render(<OfflineTab />);++ await screen.findByText('No trips cached yet. Connect to the internet to sync.');+ expect(screen.queryByText('Trips')).not.toBeInTheDocument();+ });++ it('FE-COMP-OFFLINETAB-023: Clear cache asks first and a declined confirm keeps the data', async () => {+ const user = userEvent.setup();+ const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);+ cache([{ trip: paris }]);+ render(<OfflineTab />);++ await waitFor(() => expect(screen.getByRole('button', { name: 'Clear cache' })).toBeEnabled());+ await user.click(screen.getByRole('button', { name: 'Clear cache' }));++ expect(confirmSpy).toHaveBeenCalledWith('Clear all offline trip data? You can re-sync anytime while online.');+ expect(h.clearAll).not.toHaveBeenCalled();+ expect(within(card('Offline cache')).getByText('Paris')).toBeInTheDocument();+ });++ it('FE-COMP-OFFLINETAB-024: confirming Clear cache wipes the database and reloads', async () => {+ const user = userEvent.setup();+ vi.spyOn(window, 'confirm').mockReturnValue(true);+ cache([{ trip: paris }]);+ render(<OfflineTab />);++ await waitFor(() => expect(screen.getByRole('button', { name: 'Clear cache' })).toBeEnabled());+ h.syncMetaToArray.mockResolvedValue([]);+ await user.click(screen.getByRole('button', { name: 'Clear cache' }));++ expect(h.clearAll).toHaveBeenCalledTimes(1);+ await screen.findByText('No trips cached yet. Connect to the internet to sync.');+ await waitFor(() => expect(screen.getByRole('button', { name: 'Clear cache' })).toBeDisabled());+ });+});diff --git a/client/src/components/Settings/PasskeysSection.test.tsx b/client/src/components/Settings/PasskeysSection.test.tsxnew file mode 100644index 000000000..634153438--- /dev/null+++ b/client/src/components/Settings/PasskeysSection.test.tsx@@ -0,0 +1,400 @@+// FE-COMP-PASSKEYS-001 to FE-COMP-PASSKEYS-022+import { describe, it, expect, beforeEach, vi } from 'vitest';+import userEvent from '@testing-library/user-event';+import { http, HttpResponse } from 'msw';+import { render, screen, waitFor, within } from '../../../tests/helpers/render';+import { server } from '../../../tests/helpers/msw/server';+import { ToastContainer } from '../shared/Toast';+import type { PasskeyCredential } from '../../api/client';+import PasskeysSection from './PasskeysSection';++// The WebAuthn ceremony is the one thing jsdom cannot do. @simplewebauthn/browser+// is the only caller of navigator.credentials here, so it is stubbed wholesale;+// navigator.credentials itself is stubbed too so nothing can slip past.+const startRegistration = vi.fn();+vi.mock('@simplewebauthn/browser', () => ({+ startRegistration: (...args: unknown[]) => startRegistration(...args),+}));++const cred = (over: Partial<PasskeyCredential> = {}): PasskeyCredential => ({+ id: 1,+ name: 'MacBook',+ device_type: 'multiDevice',+ backed_up: true,+ created_at: '2025-05-01 08:30:00',+ last_used_at: null,+ ...over,+});++function serve(opts: {+ credentials?: PasskeyCredential[]+ passkeyLogin?: boolean+ passkeyConfigured?: boolean+} = {}): void {+ server.use(+ http.get('/api/auth/app-config', () => HttpResponse.json({+ has_users: true,+ allow_registration: true,+ demo_mode: false,+ password_login: true,+ passkey_login: opts.passkeyLogin ?? true,+ passkey_configured: opts.passkeyConfigured ?? true,+ })),+ http.get('/api/auth/passkey/credentials', () =>+ HttpResponse.json({ credentials: opts.credentials ?? [] })),+ );+}++/** The <li> that carries the given credential name. */+const item = (name: string) => screen.getByText(name).closest('li') as HTMLElement;++beforeEach(() => {+ vi.clearAllMocks();+ Object.defineProperty(navigator, 'credentials', {+ configurable: true,+ writable: true,+ value: { create: vi.fn(async () => null), get: vi.fn(async () => null) },+ });+ startRegistration.mockResolvedValue({ id: 'cred-id', rawId: 'cred-id', type: 'public-key' });+ serve();+});++describe('PasskeysSection', () => {+ it('FE-COMP-PASSKEYS-001: renders nothing in demo mode', () => {+ const { container } = render(<PasskeysSection demoMode />);+ expect(container).toBeEmptyDOMElement();+ });++ it('FE-COMP-PASSKEYS-002: renders nothing once loaded when the feature is off and there are no credentials', async () => {+ serve({ passkeyLogin: false, credentials: [] });+ const { container } = render(<PasskeysSection />);++ await waitFor(() => expect(container).toBeEmptyDOMElement());+ });++ it('FE-COMP-PASSKEYS-003: keeps the list reachable when the feature is off but credentials exist', async () => {+ serve({ passkeyLogin: false, credentials: [cred()] });+ render(<PasskeysSection />);++ expect(await screen.findByText('MacBook')).toBeInTheDocument();+ expect(screen.getByText('Passkeys')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Add a passkey' })).not.toBeInTheDocument();+ });++ it('FE-COMP-PASSKEYS-004: warns when the feature is on but the server has no RP ID', async () => {+ serve({ passkeyLogin: true, passkeyConfigured: false });+ render(<PasskeysSection />);++ expect(await screen.findByText(/not fully configured on this server/)).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Add a passkey' })).not.toBeInTheDocument();+ });++ it('FE-COMP-PASSKEYS-005: offers the Add action when the feature is on and configured', async () => {+ render(<PasskeysSection />);++ expect(await screen.findByRole('button', { name: 'Add a passkey' })).toBeInTheDocument();+ expect(screen.queryByText(/not fully configured on this server/)).not.toBeInTheDocument();+ });++ it('FE-COMP-PASSKEYS-006: a synced credential shows its name, badge, added date and never-used note', async () => {+ serve({ credentials: [cred()] });+ render(<PasskeysSection />);++ await screen.findByText('MacBook');+ const li = item('MacBook');+ expect(within(li).getByText('Synced')).toBeInTheDocument();+ expect(within(li).getByText(/Added: 5\/1\/2025/)).toHaveTextContent('Never used');+ });++ it('FE-COMP-PASSKEYS-007: a device-bound credential without a name falls back to the default label', async () => {+ serve({ credentials: [cred({ name: null, backed_up: false, last_used_at: '2025-06-10T12:00:00Z' })] });+ render(<PasskeysSection />);++ await screen.findByText('Passkey');+ const li = item('Passkey');+ expect(within(li).getByText('This device')).toBeInTheDocument();+ expect(within(li).getByText(/Last used: 6\/10\/2025/)).toBeInTheDocument();+ });++ it('FE-COMP-PASSKEYS-008: an unparseable timestamp collapses to a dash', async () => {+ serve({ credentials: [cred({ created_at: 'never' })] });+ render(<PasskeysSection />);++ await screen.findByText('MacBook');+ expect(within(item('MacBook')).getByText(/Added: —/)).toBeInTheDocument();+ });++ it('FE-COMP-PASSKEYS-009: a failing credential list still renders the section', async () => {+ server.use(http.get('/api/auth/passkey/credentials', () =>+ HttpResponse.json({ error: 'boom' }, { status: 500 })));+ render(<PasskeysSection />);++ expect(await screen.findByRole('button', { name: 'Add a passkey' })).toBeInTheDocument();+ expect(screen.queryByRole('listitem')).not.toBeInTheDocument();+ });++ it('FE-COMP-PASSKEYS-010: a failing app-config leaves the feature off', async () => {+ server.use(+ http.get('/api/auth/app-config', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),+ http.get('/api/auth/passkey/credentials', () => HttpResponse.json({ credentials: [cred()] })),+ );+ render(<PasskeysSection />);++ expect(await screen.findByText('MacBook')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Add a passkey' })).not.toBeInTheDocument();+ });++ it('FE-COMP-PASSKEYS-011: the add form opens, requires a password and closes on Cancel', async () => {+ const user = userEvent.setup();+ render(<PasskeysSection />);++ await user.click(await screen.findByRole('button', { name: 'Add a passkey' }));+ expect(screen.getByText('Confirm your current password, then follow your device prompt.')).toBeInTheDocument();+ // The submit shares its label with the trigger — it is the only one left.+ expect(screen.getByRole('button', { name: 'Add a passkey' })).toBeDisabled();++ await user.type(screen.getByPlaceholderText('Current password'), 'hunter2');+ expect(screen.getByRole('button', { name: 'Add a passkey' })).toBeEnabled();++ await user.click(screen.getByRole('button', { name: 'Cancel' }));+ await waitFor(() => expect(screen.queryByPlaceholderText('Current password')).not.toBeInTheDocument());+ });++ it('FE-COMP-PASSKEYS-012: adding runs the WebAuthn ceremony and reloads the list', async () => {+ const user = userEvent.setup();+ const sent: { body?: { attestationResponse?: { id?: string }; name?: string } } = {};+ let listCalls = 0;+ server.use(+ http.get('/api/auth/passkey/credentials', () => {+ listCalls += 1;+ return HttpResponse.json({ credentials: listCalls === 1 ? [] : [cred({ name: 'YubiKey' })] });+ }),+ http.post('/api/auth/passkey/register/options', () => HttpResponse.json({ challenge: 'abc' })),+ http.post('/api/auth/passkey/register/verify', async ({ request }) => {+ sent.body = await request.json() as { attestationResponse?: { id?: string }; name?: string };+ return HttpResponse.json({ success: true });+ }),+ );+ render(<><ToastContainer /><PasskeysSection /></>);++ await user.click(await screen.findByRole('button', { name: 'Add a passkey' }));+ await user.type(screen.getByPlaceholderText('Current password'), 'hunter2');+ await user.type(screen.getByPlaceholderText(/Name \(optional/), ' YubiKey ');+ await user.click(screen.getByRole('button', { name: 'Add a passkey' }));++ await screen.findByText('Passkey added');+ expect(startRegistration).toHaveBeenCalledWith({ optionsJSON: { challenge: 'abc' } });+ expect(sent.body?.name).toBe('YubiKey');+ expect(sent.body?.attestationResponse?.id).toBe('cred-id');+ expect(await screen.findByText('YubiKey')).toBeInTheDocument();+ // The form closed and reset.+ expect(screen.queryByPlaceholderText('Current password')).not.toBeInTheDocument();+ });++ it('FE-COMP-PASSKEYS-013: an empty name is sent as undefined rather than a blank string', async () => {+ const user = userEvent.setup();+ const sent: { body?: Record<string, unknown> } = {};+ server.use(+ http.post('/api/auth/passkey/register/options', () => HttpResponse.json({ challenge: 'abc' })),+ http.post('/api/auth/passkey/register/verify', async ({ request }) => {+ sent.body = await request.json() as Record<string, unknown>;+ return HttpResponse.json({ success: true });+ }),+ );+ render(<><ToastContainer /><PasskeysSection /></>);++ await user.click(await screen.findByRole('button', { name: 'Add a passkey' }));+ await user.type(screen.getByPlaceholderText('Current password'), 'hunter2');+ await user.click(screen.getByRole('button', { name: 'Add a passkey' }));++ await screen.findByText('Passkey added');+ expect(sent.body).toBeDefined();+ expect(sent.body).not.toHaveProperty('name');+ });++ it('FE-COMP-PASSKEYS-014: a cancelled browser prompt reports the cancellation, not an error', async () => {+ const user = userEvent.setup();+ server.use(http.post('/api/auth/passkey/register/options', () => HttpResponse.json({ challenge: 'abc' })));+ const abort = new Error('user aborted');+ abort.name = 'NotAllowedError';+ startRegistration.mockRejectedValue(abort);+ render(<><ToastContainer /><PasskeysSection /></>);++ await user.click(await screen.findByRole('button', { name: 'Add a passkey' }));+ await user.type(screen.getByPlaceholderText('Current password'), 'hunter2');+ await user.click(screen.getByRole('button', { name: 'Add a passkey' }));++ await screen.findByText('Passkey setup cancelled');+ // The form stays open so the user can retry.+ expect(screen.getByPlaceholderText('Current password')).toBeInTheDocument();+ });++ it('FE-COMP-PASSKEYS-015: a rejected password surfaces the server message', async () => {+ const user = userEvent.setup();+ server.use(http.post('/api/auth/passkey/register/options', () =>+ HttpResponse.json({ error: 'Wrong password' }, { status: 401 })));+ render(<><ToastContainer /><PasskeysSection /></>);++ await user.click(await screen.findByRole('button', { name: 'Add a passkey' }));+ await user.type(screen.getByPlaceholderText('Current password'), 'nope');+ await user.click(screen.getByRole('button', { name: 'Add a passkey' }));++ await screen.findByText('Wrong password');+ expect(startRegistration).not.toHaveBeenCalled();+ });++ it('FE-COMP-PASSKEYS-016: renaming sends the trimmed name and refreshes', async () => {+ const user = userEvent.setup();+ const sent: { body?: { name?: string } } = {};+ let listCalls = 0;+ server.use(+ http.get('/api/auth/passkey/credentials', () => {+ listCalls += 1;+ return HttpResponse.json({ credentials: [cred({ name: listCalls === 1 ? 'MacBook' : 'Work laptop' })] });+ }),+ http.patch('/api/auth/passkey/credentials/1', async ({ request }) => {+ sent.body = await request.json() as { name?: string };+ return HttpResponse.json({ success: true });+ }),+ );+ render(<><ToastContainer /><PasskeysSection /></>);++ await screen.findByText('MacBook');+ await user.click(within(item('MacBook')).getByRole('button', { name: 'Rename' }));+ const input = screen.getByDisplayValue('MacBook');+ await user.clear(input);+ await user.type(input, ' Work laptop ');+ await user.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(sent.body).toEqual({ name: 'Work laptop' }));+ expect(await screen.findByText('Work laptop')).toBeInTheDocument();+ });++ it('FE-COMP-PASSKEYS-017: Enter commits a rename and Escape abandons it', async () => {+ const user = userEvent.setup();+ let patchCalls = 0;+ server.use(+ http.patch('/api/auth/passkey/credentials/1', () => {+ patchCalls += 1;+ return HttpResponse.json({ success: true });+ }),+ );+ serve({ credentials: [cred()] });+ render(<><ToastContainer /><PasskeysSection /></>);++ await screen.findByText('MacBook');+ await user.click(within(item('MacBook')).getByRole('button', { name: 'Rename' }));+ await user.type(screen.getByDisplayValue('MacBook'), '{Escape}');+ await waitFor(() => expect(screen.queryByDisplayValue('MacBook')).not.toBeInTheDocument());+ expect(patchCalls).toBe(0);++ await user.click(within(item('MacBook')).getByRole('button', { name: 'Rename' }));+ await user.type(screen.getByDisplayValue('MacBook'), '2{Enter}');+ await waitFor(() => expect(patchCalls).toBe(1));+ });++ it('FE-COMP-PASSKEYS-018: clearing the name cancels the rename without calling the API', async () => {+ const user = userEvent.setup();+ let patchCalls = 0;+ server.use(http.patch('/api/auth/passkey/credentials/1', () => {+ patchCalls += 1;+ return HttpResponse.json({ success: true });+ }));+ serve({ credentials: [cred()] });+ render(<><ToastContainer /><PasskeysSection /></>);++ await screen.findByText('MacBook');+ await user.click(within(item('MacBook')).getByRole('button', { name: 'Rename' }));+ await user.clear(screen.getByDisplayValue('MacBook'));+ await user.click(screen.getByRole('button', { name: 'Save' }));++ await waitFor(() => expect(screen.getByText('MacBook')).toBeInTheDocument());+ expect(patchCalls).toBe(0);+ });++ it('FE-COMP-PASSKEYS-022: the rename X button drops the edit and restores the row', async () => {+ const user = userEvent.setup();+ let patchCalls = 0;+ server.use(http.patch('/api/auth/passkey/credentials/1', () => {+ patchCalls += 1;+ return HttpResponse.json({ success: true });+ }));+ serve({ credentials: [cred()] });+ render(<><ToastContainer /><PasskeysSection /></>);++ await screen.findByText('MacBook');+ await user.click(within(item('MacBook')).getByRole('button', { name: 'Rename' }));+ await user.type(screen.getByDisplayValue('MacBook'), '-edited');+ await user.click(screen.getByRole('button', { name: 'Cancel' }));++ await waitFor(() => expect(screen.queryByRole('textbox')).not.toBeInTheDocument());+ expect(screen.getByText('MacBook')).toBeInTheDocument();+ expect(patchCalls).toBe(0);+ });++ it('FE-COMP-PASSKEYS-019: a failing rename surfaces the server message', async () => {+ const user = userEvent.setup();+ server.use(http.patch('/api/auth/passkey/credentials/1', () =>+ HttpResponse.json({ error: 'Name taken' }, { status: 409 })));+ serve({ credentials: [cred()] });+ render(<><ToastContainer /><PasskeysSection /></>);++ await screen.findByText('MacBook');+ await user.click(within(item('MacBook')).getByRole('button', { name: 'Rename' }));+ await user.type(screen.getByDisplayValue('MacBook'), '-x');+ await user.click(screen.getByRole('button', { name: 'Save' }));++ await screen.findByText('Name taken');+ });++ it('FE-COMP-PASSKEYS-020: deleting asks for the password, calls the API and can be cancelled', async () => {+ const user = userEvent.setup();+ const sent: { body?: { password?: string } } = {};+ let listCalls = 0;+ server.use(+ http.get('/api/auth/passkey/credentials', () => {+ listCalls += 1;+ return HttpResponse.json({ credentials: listCalls === 1 ? [cred()] : [] });+ }),+ http.delete('/api/auth/passkey/credentials/1', async ({ request }) => {+ sent.body = await request.json() as { password?: string };+ return HttpResponse.json({ success: true });+ }),+ );+ render(<><ToastContainer /><PasskeysSection /></>);++ await screen.findByText('MacBook');+ await user.click(within(item('MacBook')).getByRole('button', { name: 'Delete' }));+ const panel = screen.getByText('Remove this passkey? Confirm with your password.').parentElement as HTMLElement;+ expect(within(panel).getByRole('button', { name: 'Delete' })).toBeDisabled();++ await user.click(within(panel).getByRole('button', { name: 'Cancel' }));+ await waitFor(() => expect(screen.queryByText('Remove this passkey? Confirm with your password.')).not.toBeInTheDocument());++ await user.click(within(item('MacBook')).getByRole('button', { name: 'Delete' }));+ const panel2 = screen.getByText('Remove this passkey? Confirm with your password.').parentElement as HTMLElement;+ await user.type(within(panel2).getByPlaceholderText('Current password'), 'hunter2');+ await user.click(within(panel2).getByRole('button', { name: 'Delete' }));++ await screen.findByText('Passkey removed');+ expect(sent.body).toEqual({ password: 'hunter2' });+ await waitFor(() => expect(screen.queryByText('MacBook')).not.toBeInTheDocument());+ });++ it('FE-COMP-PASSKEYS-021: a failing delete surfaces the server message and keeps the panel open', async () => {+ const user = userEvent.setup();+ server.use(http.delete('/api/auth/passkey/credentials/1', () =>+ HttpResponse.json({ error: 'Wrong password' }, { status: 401 })));+ serve({ credentials: [cred()] });+ render(<><ToastContainer /><PasskeysSection /></>);++ await screen.findByText('MacBook');+ await user.click(within(item('MacBook')).getByRole('button', { name: 'Delete' }));+ const panel = screen.getByText('Remove this passkey? Confirm with your password.').parentElement as HTMLElement;+ await user.type(within(panel).getByPlaceholderText('Current password'), 'nope');+ await user.click(within(panel).getByRole('button', { name: 'Delete' }));++ await screen.findByText('Wrong password');+ expect(screen.getByText('Remove this passkey? Confirm with your password.')).toBeInTheDocument();+ });+});diff --git a/client/src/components/Settings/PhotoProvidersSection.test.tsx b/client/src/components/Settings/PhotoProvidersSection.test.tsxindex b52d2777f..67b32030f 100644--- a/client/src/components/Settings/PhotoProvidersSection.test.tsx+++ b/client/src/components/Settings/PhotoProvidersSection.test.tsx@@ -1,4 +1,4 @@-// FE-COMP-PHOTOPROVIDERS-001 to FE-COMP-PHOTOPROVIDERS-018+// FE-COMP-PHOTOPROVIDERS-001 to FE-COMP-PHOTOPROVIDERS-024import { render, screen, waitFor } from '../../../tests/helpers/render';import userEvent from '@testing-library/user-event';import { http, HttpResponse } from 'msw';@@ -15,12 +15,13 @@ const fakeProvider = {name: 'Immich',type: 'photo_provider',enabled: true,+ // Widened so per-test overrides can swap test_post for test_get.config: {settings_get: '/addons/immich/settings',settings_put: '/addons/immich/settings',status_get: '/addons/immich/status',test_post: '/addons/immich/test',- },+ } as Record<string, string>,fields: [{ key: 'url', label: 'url', input_type: 'text', placeholder: 'https://...', required: true, secret: false, settings_key: 'url', payload_key: 'url', sort_order: 0 },{ key: 'api_key', label: 'api_key', input_type: 'text', placeholder: null, required: true, secret: true, settings_key: 'api_key', payload_key: 'api_key', sort_order: 1 },@@ -329,3 +330,141 @@ describe('PhotoProvidersSection', () => {await screen.findByText('Piwigo');});});++// ── Checkbox fields, missing values and failing probes (019–023) ──────────────++const providerWithCheckbox = {+ ...fakeProvider,+ fields: [+ fakeProvider.fields[0],+ {+ key: 'verify_ssl',+ label: 'verify_ssl',+ input_type: 'checkbox',+ placeholder: null,+ required: false,+ secret: false,+ settings_key: 'verify_ssl',+ payload_key: 'verify_ssl',+ sort_order: 1,+ },+ ],+};++/** The ToggleSwitch rendered for a checkbox-typed provider field. */+function checkboxToggle(): HTMLElement {+ return screen.getAllByRole('button').find(b => b.hasAttribute('aria-pressed')) as HTMLElement;+}++describe('PhotoProvidersSection – checkbox fields and failures', () => {+ it('FE-COMP-PHOTOPROVIDERS-019: a checkbox field starts off and is sent as a boolean', async () => {+ const user = userEvent.setup();+ let body: Record<string, unknown> | null = null;+ server.use(+ http.put('/api/addons/immich/settings', async ({ request }) => {+ body = (await request.json()) as Record<string, unknown>;+ return HttpResponse.json({ success: true });+ }),+ );+ seedMemoriesEnabled([providerWithCheckbox]);+ render(<PhotoProvidersSection />);++ await screen.findByDisplayValue('https://photos.example.com');+ expect(checkboxToggle()).toHaveAttribute('aria-pressed', 'false');++ await user.click(checkboxToggle());+ expect(checkboxToggle()).toHaveAttribute('aria-pressed', 'true');++ await user.click(screen.getByRole('button', { name: /save/i }));++ await waitFor(() => expect(body).toEqual({ url: 'https://photos.example.com', verify_ssl: true }));+ });++ it('FE-COMP-PHOTOPROVIDERS-020: a stored checkbox value hydrates the toggle', async () => {+ server.use(+ http.get('/api/addons/immich/settings', () =>+ HttpResponse.json({ url: 'https://photos.example.com', verify_ssl: true, connected: false }),+ ),+ );+ seedMemoriesEnabled([providerWithCheckbox]);+ render(<PhotoProvidersSection />);++ await screen.findByDisplayValue('https://photos.example.com');+ await waitFor(() => expect(checkboxToggle()).toHaveAttribute('aria-pressed', 'true'));+ });++ it('FE-COMP-PHOTOPROVIDERS-021: a settings payload without the field leaves the input empty', async () => {+ server.use(+ http.get('/api/addons/immich/settings', () => HttpResponse.json({ connected: false })),+ );+ seedMemoriesEnabled([fakeProviderSimple]);+ render(<PhotoProvidersSection />);++ await screen.findByText('Immich');+ await waitFor(() => expect(screen.getByRole('textbox')).toHaveValue(''));+ expect(screen.getByRole('button', { name: /save/i })).toBeDisabled();+ });++ it('FE-COMP-PHOTOPROVIDERS-022: a failing status probe leaves the provider disconnected', async () => {+ server.use(+ http.get('/api/addons/immich/settings', () => HttpResponse.json({ url: 'https://photos.example.com' })),+ http.get('/api/addons/immich/status', () => HttpResponse.json({ error: 'down' }, { status: 500 })),+ );+ seedMemoriesEnabled([fakeProviderSimple]);+ render(<PhotoProvidersSection />);++ await screen.findByText('Immich');+ await waitFor(() => expect(screen.getByText('Not connected')).toBeInTheDocument());+ });++ it('FE-COMP-PHOTOPROVIDERS-023: a test request that errors out falls back to the plain error', async () => {+ const user = userEvent.setup();+ server.use(+ http.post('/api/addons/immich/test', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),+ );+ seedMemoriesEnabled([fakeProviderSimple]);+ render(+ <>+ <ToastContainer />+ <PhotoProvidersSection />+ </>,+ );++ await screen.findByText('Immich');+ await user.click(screen.getByRole('button', { name: /test connection/i }));++ await screen.findByText('Could not connect to Immich');+ });++ it('FE-COMP-PHOTOPROVIDERS-024: a provider without a test POST route probes over GET instead', async () => {+ const user = userEvent.setup();+ let probed = false;+ server.use(+ http.get('/api/addons/immich/probe', () => {+ probed = true;+ return HttpResponse.json({ connected: true });+ }),+ );+ seedMemoriesEnabled([{+ ...fakeProviderSimple,+ config: {+ settings_get: '/addons/immich/settings',+ settings_put: '/addons/immich/settings',+ status_get: '/addons/immich/status',+ test_get: '/addons/immich/probe',+ },+ }]);+ render(+ <>+ <ToastContainer />+ <PhotoProvidersSection />+ </>,+ );++ await screen.findByText('Immich');+ await user.click(screen.getByRole('button', { name: /test connection/i }));++ await waitFor(() => expect(probed).toBe(true));+ await screen.findByText('Connected to Immich');+ });+});diff --git a/client/src/components/Settings/PluginActivityPanel.test.tsx b/client/src/components/Settings/PluginActivityPanel.test.tsxnew file mode 100644index 000000000..ddefb277e--- /dev/null+++ b/client/src/components/Settings/PluginActivityPanel.test.tsx@@ -0,0 +1,134 @@+// FE-COMP-PLUGINACTIVITY-001 to FE-COMP-PLUGINACTIVITY-010+import { describe, it, expect, beforeEach, vi } from 'vitest';+import userEvent from '@testing-library/user-event';+import { http, HttpResponse } from 'msw';+import { render, screen, waitFor, within } from '../../../tests/helpers/render';+import { server } from '../../../tests/helpers/msw/server';+import PluginActivityPanel from './PluginActivityPanel';++interface ActivityRow {+ ts: string;+ plugin_id: string;+ plugin_name: string | null;+ method: string;+ resource: string | null;+ code: string;+}++const row = (over: Partial<ActivityRow> = {}): ActivityRow => ({+ ts: '2025-06-01T10:00:00.000Z',+ plugin_id: 'weather',+ plugin_name: 'Weather',+ method: 'trips.read',+ resource: 'trip:42',+ code: 'ok',+ ...over,+});++function serveActivity(activity: ActivityRow[]): void {+ server.use(http.get('/api/plugin-activity', () => HttpResponse.json({ activity })));+}++/** The <td> cells of the one rendered data row. */+const cells = () => within(screen.getByRole('table')).getAllByRole('row')[1].querySelectorAll('td');++beforeEach(() => {+ vi.clearAllMocks();+ serveActivity([]);+});++describe('PluginActivityPanel', () => {+ it('FE-COMP-PLUGINACTIVITY-001: shows the loading line before the log arrives', async () => {+ server.use(http.get('/api/plugin-activity', () => new Promise(() => {})));+ render(<PluginActivityPanel />);++ expect(screen.getByText('Plugin activity')).toBeInTheDocument();+ expect(screen.getByText('Loading...')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Refresh' })).toBeDisabled();+ });++ it('FE-COMP-PLUGINACTIVITY-002: an empty log renders the empty state instead of a table', async () => {+ render(<PluginActivityPanel />);++ expect(await screen.findByText('No plugin activity yet.')).toBeInTheDocument();+ expect(screen.queryByRole('table')).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Refresh' })).toBeEnabled();+ });++ it('FE-COMP-PLUGINACTIVITY-003: a failing request falls back to the empty state, not a crash', async () => {+ server.use(http.get('/api/plugin-activity', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));+ render(<PluginActivityPanel />);++ expect(await screen.findByText('No plugin activity yet.')).toBeInTheDocument();+ });++ it('FE-COMP-PLUGINACTIVITY-004: entries render as a table with all five columns', async () => {+ serveActivity([row()]);+ render(<PluginActivityPanel />);++ const table = await screen.findByRole('table');+ const headers = within(table).getAllByRole('columnheader').map(th => th.textContent);+ expect(headers).toEqual(['Plugin', 'Action', 'Resource', 'When', 'Result']);+ expect(within(table).getByText('Weather')).toBeInTheDocument();+ expect(within(table).getByText('trips.read')).toBeInTheDocument();+ expect(within(table).getByText('trip:42')).toBeInTheDocument();+ expect(within(table).getByText('ok')).toBeInTheDocument();+ });++ it('FE-COMP-PLUGINACTIVITY-005: a nameless plugin falls back to its id and a null resource to a dash', async () => {+ serveActivity([row({ plugin_name: null, resource: null })]);+ render(<PluginActivityPanel />);++ await screen.findByRole('table');+ expect(cells()[0]).toHaveTextContent('weather');+ expect(cells()[2]).toHaveTextContent('—');+ });++ it('FE-COMP-PLUGINACTIVITY-006: an "ok" code gets the neutral pill', async () => {+ serveActivity([row({ code: 'ok' })]);+ render(<PluginActivityPanel />);++ await screen.findByRole('table');+ expect(screen.getByText('ok')).toHaveClass('bg-surface-hover', 'text-content-secondary');+ });++ it('FE-COMP-PLUGINACTIVITY-007: an access denial gets the danger pill', async () => {+ serveActivity([row({ code: 'FORBIDDEN' })]);+ render(<PluginActivityPanel />);++ await screen.findByRole('table');+ expect(screen.getByText('FORBIDDEN')).toHaveClass('bg-danger-soft', 'text-danger');+ });++ it('FE-COMP-PLUGINACTIVITY-008: any other non-ok code gets the warning pill', async () => {+ serveActivity([row({ code: 'RATE_LIMITED' })]);+ render(<PluginActivityPanel />);++ await screen.findByRole('table');+ expect(screen.getByText('RATE_LIMITED')).toHaveClass('bg-warning-soft', 'text-warning');+ });++ it('FE-COMP-PLUGINACTIVITY-009: an unparseable timestamp is shown verbatim', async () => {+ serveActivity([row({ ts: 'not-a-date' })]);+ render(<PluginActivityPanel />);++ await screen.findByRole('table');+ expect(cells()[3]).toHaveTextContent('not-a-date');+ });++ it('FE-COMP-PLUGINACTIVITY-010: Refresh re-reads the log', async () => {+ const user = userEvent.setup();+ let calls = 0;+ server.use(http.get('/api/plugin-activity', () => {+ calls += 1;+ return HttpResponse.json({ activity: calls === 1 ? [] : [row({ plugin_name: 'Second pass' })] });+ }));+ render(<PluginActivityPanel />);++ await screen.findByText('No plugin activity yet.');+ await user.click(screen.getByRole('button', { name: 'Refresh' }));++ await waitFor(() => expect(screen.getByText('Second pass')).toBeInTheDocument());+ expect(calls).toBe(2);+ });+});diff --git a/client/src/components/Settings/PluginSettingsTab.test.tsx b/client/src/components/Settings/PluginSettingsTab.test.tsxnew file mode 100644index 000000000..820f35004--- /dev/null+++ b/client/src/components/Settings/PluginSettingsTab.test.tsx@@ -0,0 +1,451 @@+// FE-COMP-PLUGINSETTINGS-001 to FE-COMP-PLUGINSETTINGS-025+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import userEvent from '@testing-library/user-event';+import { http, HttpResponse } from 'msw';+import { render, screen, waitFor, within } from '../../../tests/helpers/render';+import { server } from '../../../tests/helpers/msw/server';+import { ToastContainer } from '../shared/Toast';+import { usePluginStore, type ActivePlugin } from '../../store/pluginStore';+import type { PluginAction, PluginUserSettingField } from '../../api/client';+import PluginSettingsTab from './PluginSettingsTab';++const plugin = (over: Partial<ActivePlugin> = {}): ActivePlugin => ({+ id: 'weather',+ name: 'Weather',+ type: 'widget',+ icon: 'Cloud',+ ...over,+});++interface SettingsPayload {+ fields?: PluginUserSettingField[]+ config?: Record<string, unknown>+ actions?: PluginAction[]+}++/** Wire the three per-plugin endpoints the form reads on mount. */+function serve(id: string, settings: SettingsPayload, oauth?: { configured: boolean; connected: boolean }): void {+ server.use(+ http.get(`/api/plugin-settings/${id}`, () => HttpResponse.json({+ fields: settings.fields ?? [],+ config: settings.config ?? {},+ actions: settings.actions ?? [],+ })),+ http.get(`/api/plugin-oauth/${id}/status`, () =>+ oauth ? HttpResponse.json(oauth) : HttpResponse.json({ error: 'not found' }, { status: 404 })),+ );+}++function setPlugins(plugins: ActivePlugin[]): void {+ usePluginStore.setState({ plugins });+}++/** The settings card for a plugin (the heading's rounded container). */+const cardFor = (name: string) => screen.getByRole('heading', { name }).closest('div.rounded-xl') as HTMLElement;++beforeEach(() => {+ vi.clearAllMocks();+ setPlugins([]);+ server.use(http.get('/api/plugin-activity', () => HttpResponse.json({ activity: [] })));+});++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('PluginSettingsTab', () => {+ it('FE-COMP-PLUGINSETTINGS-001: shows the header and the empty state when no plugin is active', async () => {+ render(<PluginSettingsTab />);++ expect(screen.getByRole('heading', { name: 'Plugin settings' })).toBeInTheDocument();+ expect(screen.getByText('Your personal settings for the plugins you use (API keys, preferences).')).toBeInTheDocument();+ expect(screen.getByText('No plugins are active.')).toBeInTheDocument();+ // The activity log is always mounted, plugins or not.+ expect(await screen.findByText('Plugin activity')).toBeInTheDocument();+ });++ it('FE-COMP-PLUGINSETTINGS-002: a plugin with nothing to configure renders no card', async () => {+ serve('weather', {});+ setPlugins([plugin()]);+ render(<PluginSettingsTab />);++ await screen.findByText('Plugin activity');+ expect(screen.queryByText('No plugins are active.')).not.toBeInTheDocument();+ await waitFor(() => expect(screen.queryByRole('heading', { name: 'Weather' })).not.toBeInTheDocument());+ });++ it('FE-COMP-PLUGINSETTINGS-003: a failing settings request leaves the card out', async () => {+ server.use(+ http.get('/api/plugin-settings/weather', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),+ http.get('/api/plugin-oauth/weather/status', () => HttpResponse.json({ configured: false, connected: false })),+ );+ setPlugins([plugin()]);+ render(<PluginSettingsTab />);++ await screen.findByText('Plugin activity');+ await waitFor(() => expect(screen.queryByRole('heading', { name: 'Weather' })).not.toBeInTheDocument());+ });++ it('FE-COMP-PLUGINSETTINGS-004: text fields are labelled, prefilled and marked required', async () => {+ serve('weather', {+ fields: [+ { key: 'api_key', label: 'API key', input_type: 'text', required: true, hint: 'From your provider' },+ { key: 'units', input_type: 'text' },+ ],+ config: { api_key: 'abc123', units: 'metric' },+ });+ setPlugins([plugin()]);+ render(<PluginSettingsTab />);++ await screen.findByDisplayValue('abc123');+ const card = cardFor('Weather');+ expect(within(card).getByText('API key')).toHaveTextContent('*');+ expect(within(card).getByText('From your provider')).toBeInTheDocument();+ // No label declared → the key stands in for it.+ expect(within(card).getByText('units')).toBeInTheDocument();+ expect(within(card).getByDisplayValue('metric')).toBeInTheDocument();+ });++ it('FE-COMP-PLUGINSETTINGS-005: a secret field renders as a password input with a placeholder', async () => {+ serve('weather', {+ fields: [{ key: 'token', label: 'Token', input_type: 'text', secret: true, placeholder: 'paste here' }],+ config: { token: '••••••••' },+ });+ setPlugins([plugin()]);+ render(<PluginSettingsTab />);++ const input = await screen.findByPlaceholderText('paste here') as HTMLInputElement;+ expect(input.type).toBe('password');+ expect(input.autocomplete).toBe('new-password');+ expect(input.value).toBe('••••••••');+ });++ it('FE-COMP-PLUGINSETTINGS-006: a number field renders a numeric input and a null config value is blank', async () => {+ serve('weather', {+ fields: [{ key: 'days', label: 'Days', input_type: 'number' }],+ config: { days: null },+ });+ setPlugins([plugin()]);+ render(<PluginSettingsTab />);++ const input = await screen.findByRole('spinbutton') as HTMLInputElement;+ expect(input.type).toBe('number');+ expect(input.value).toBe('');+ });++ it('FE-COMP-PLUGINSETTINGS-007: a checkbox field mirrors the boolean config and toggles', async () => {+ const user = userEvent.setup();+ serve('weather', {+ fields: [{ key: 'alerts', label: 'Alerts', input_type: 'checkbox' }],+ config: { alerts: true },+ });+ setPlugins([plugin()]);+ render(<PluginSettingsTab />);++ const box = await screen.findByRole('checkbox');+ expect(box).toBeChecked();+ await user.click(box);+ expect(box).not.toBeChecked();+ });++ it('FE-COMP-PLUGINSETTINGS-008: a select field lists its options and keeps the chosen one', async () => {+ const user = userEvent.setup();+ serve('weather', {+ fields: [{+ key: 'unit', label: 'Unit', input_type: 'select',+ options: [{ value: 'c', label: 'Celsius' }, { value: 'f', label: 'Fahrenheit' }],+ }],+ config: { unit: 'c' },+ });+ setPlugins([plugin()]);+ render(<PluginSettingsTab />);++ const select = await screen.findByRole('combobox') as HTMLSelectElement;+ expect(select.value).toBe('c');+ await user.selectOptions(select, 'f');+ expect(select.value).toBe('f');+ });++ it('FE-COMP-PLUGINSETTINGS-009: a select field without options falls back to a text input', async () => {+ serve('weather', {+ fields: [{ key: 'unit', label: 'Unit', input_type: 'select' }],+ config: { unit: 'c' },+ });+ setPlugins([plugin()]);+ render(<PluginSettingsTab />);++ expect(await screen.findByDisplayValue('c')).toHaveAttribute('type', 'text');+ expect(screen.queryByRole('combobox')).not.toBeInTheDocument();+ });++ it('FE-COMP-PLUGINSETTINGS-010: saving posts the edited values and echoes back the stored config', async () => {+ const user = userEvent.setup();+ const sent: { body?: { config?: Record<string, unknown> } } = {};+ serve('weather', {+ fields: [+ { key: 'api_key', label: 'API key', input_type: 'text' },+ { key: 'alerts', label: 'Alerts', input_type: 'checkbox' },+ ],+ config: { api_key: 'old', alerts: false },+ });+ server.use(http.post('/api/plugin-settings/weather', async ({ request }) => {+ sent.body = await request.json() as { config?: Record<string, unknown> };+ return HttpResponse.json({ config: { api_key: 'new-key', alerts: true } });+ }));+ setPlugins([plugin()]);+ render(<><ToastContainer /><PluginSettingsTab /></>);++ const input = await screen.findByDisplayValue('old');+ await user.clear(input);+ await user.type(input, 'new-key');+ await user.click(screen.getByRole('checkbox'));+ await user.click(screen.getByRole('button', { name: 'Save' }));++ await screen.findByText('Settings saved');+ expect(sent.body?.config).toEqual({ api_key: 'new-key', alerts: true });+ expect(await screen.findByDisplayValue('new-key')).toBeInTheDocument();+ expect(screen.getByRole('checkbox')).toBeChecked();+ });++ it('FE-COMP-PLUGINSETTINGS-011: an untouched secret is not overwritten with its mask', async () => {+ const user = userEvent.setup();+ const sent: { body?: { config?: Record<string, unknown> } } = {};+ serve('weather', {+ fields: [+ { key: 'token', label: 'Token', input_type: 'text', secret: true },+ { key: 'city', label: 'City', input_type: 'text' },+ ],+ config: { token: '••••••••', city: 'Berlin' },+ });+ server.use(http.post('/api/plugin-settings/weather', async ({ request }) => {+ sent.body = await request.json() as { config?: Record<string, unknown> };+ return HttpResponse.json({ config: { token: '••••••••', city: 'Paris' } });+ }));+ setPlugins([plugin()]);+ render(<><ToastContainer /><PluginSettingsTab /></>);++ const city = await screen.findByDisplayValue('Berlin');+ await user.clear(city);+ await user.type(city, 'Paris');+ await user.click(screen.getByRole('button', { name: 'Save' }));++ await screen.findByText('Settings saved');+ expect(sent.body?.config).toEqual({ city: 'Paris' });+ });++ it('FE-COMP-PLUGINSETTINGS-012: a changed secret IS sent', async () => {+ const user = userEvent.setup();+ const sent: { body?: { config?: Record<string, unknown> } } = {};+ serve('weather', {+ fields: [{ key: 'token', label: 'Token', input_type: 'text', secret: true }],+ config: { token: '••••••••' },+ });+ server.use(http.post('/api/plugin-settings/weather', async ({ request }) => {+ sent.body = await request.json() as { config?: Record<string, unknown> };+ return HttpResponse.json({ config: { token: '••••••••' } });+ }));+ setPlugins([plugin()]);+ render(<><ToastContainer /><PluginSettingsTab /></>);++ const token = await screen.findByDisplayValue('••••••••');+ await user.clear(token);+ await user.type(token, 'real-secret');+ await user.click(screen.getByRole('button', { name: 'Save' }));++ await screen.findByText('Settings saved');+ expect(sent.body?.config).toEqual({ token: 'real-secret' });+ });++ it('FE-COMP-PLUGINSETTINGS-013: a failing save reports an error and re-enables the button', async () => {+ const user = userEvent.setup();+ serve('weather', {+ fields: [{ key: 'city', label: 'City', input_type: 'text' }],+ config: { city: 'Berlin' },+ });+ server.use(http.post('/api/plugin-settings/weather', () =>+ HttpResponse.json({ error: 'nope' }, { status: 500 })));+ setPlugins([plugin()]);+ render(<><ToastContainer /><PluginSettingsTab /></>);++ await screen.findByDisplayValue('Berlin');+ await user.click(screen.getByRole('button', { name: 'Save' }));++ await screen.findByText('Error');+ expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled();+ });++ it('FE-COMP-PLUGINSETTINGS-014: a plugin with only actions gets a card without a Save button', async () => {+ serve('weather', { actions: [{ key: 'test', label: 'Test connection', hint: 'Pings the API', danger: false }] });+ setPlugins([plugin()]);+ render(<PluginSettingsTab />);++ await screen.findByRole('button', { name: 'Test connection' });+ const card = cardFor('Weather');+ expect(within(card).getByText('Actions')).toBeInTheDocument();+ expect(within(card).getByText('Pings the API')).toBeInTheDocument();+ expect(within(card).queryByRole('button', { name: 'Save' })).not.toBeInTheDocument();+ });++ it('FE-COMP-PLUGINSETTINGS-015: running an action shows the message it returns', async () => {+ const user = userEvent.setup();+ serve('weather', { actions: [{ key: 'test', label: 'Test connection', danger: false }] });+ server.use(http.post('/api/plugin-settings/weather/actions/test', () =>+ HttpResponse.json({ ok: true, message: 'Reached the API' })));+ setPlugins([plugin()]);+ render(<PluginSettingsTab />);++ await user.click(await screen.findByRole('button', { name: 'Test connection' }));+ expect(await screen.findByText('Reached the API')).toHaveClass('text-success');+ });++ it('FE-COMP-PLUGINSETTINGS-016: a message-less result falls back to the generic ok/error labels', async () => {+ const user = userEvent.setup();+ serve('weather', { actions: [{ key: 'test', label: 'Test connection', danger: false }] });+ server.use(http.post('/api/plugin-settings/weather/actions/test', () => HttpResponse.json({ ok: false })));+ setPlugins([plugin()]);+ render(<PluginSettingsTab />);++ await user.click(await screen.findByRole('button', { name: 'Test connection' }));+ expect(await screen.findByText('Error')).toHaveClass('text-danger');+ });++ it('FE-COMP-PLUGINSETTINGS-017: a failing action reports an error result', async () => {+ const user = userEvent.setup();+ serve('weather', { actions: [{ key: 'test', label: 'Test connection', danger: false }] });+ server.use(http.post('/api/plugin-settings/weather/actions/test', () =>+ HttpResponse.json({ error: 'down' }, { status: 500 })));+ setPlugins([plugin()]);+ render(<PluginSettingsTab />);++ const button = await screen.findByRole('button', { name: 'Test connection' });+ await user.click(button);+ expect(await screen.findByText('Error')).toHaveClass('text-danger');+ expect(button).toBeEnabled();+ });++ it('FE-COMP-PLUGINSETTINGS-018: a dangerous action asks first and a declined confirm skips it', async () => {+ const user = userEvent.setup();+ const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);+ let ran = 0;+ serve('weather', { actions: [{ key: 'wipe', label: 'Wipe cache', danger: true }] });+ server.use(http.post('/api/plugin-settings/weather/actions/wipe', () => {+ ran += 1;+ return HttpResponse.json({ ok: true, message: 'Wiped' });+ }));+ setPlugins([plugin()]);+ render(<PluginSettingsTab />);++ await user.click(await screen.findByRole('button', { name: 'Wipe cache' }));+ expect(confirmSpy).toHaveBeenCalledWith('Run this action?');+ expect(ran).toBe(0);++ confirmSpy.mockReturnValue(true);+ await user.click(screen.getByRole('button', { name: 'Wipe cache' }));+ await screen.findByText('Wiped');+ expect(ran).toBe(1);+ confirmSpy.mockRestore();+ });++ it('FE-COMP-PLUGINSETTINGS-019: an unconfigured OAuth integration renders no connect row', async () => {+ serve('weather', {+ fields: [{ key: 'city', label: 'City', input_type: 'text' }],+ config: { city: 'Berlin' },+ }, { configured: false, connected: false });+ setPlugins([plugin()]);+ render(<PluginSettingsTab />);++ await screen.findByDisplayValue('Berlin');+ expect(screen.queryByRole('button', { name: 'Connect' })).not.toBeInTheDocument();+ expect(screen.queryByText('Not connected')).not.toBeInTheDocument();+ });++ it('FE-COMP-PLUGINSETTINGS-020: an OAuth-only plugin gets a card and Connect hands off to the provider', async () => {+ const user = userEvent.setup();+ const loc = { href: 'http://localhost/settings', origin: 'http://localhost', pathname: '/settings' };+ vi.stubGlobal('location', loc);+ serve('weather', {}, { configured: true, connected: false });+ server.use(http.post('/api/plugin-oauth/weather/connect', () =>+ HttpResponse.json({ authorizeUrl: 'https://provider.example/authorize?x=1' })));+ setPlugins([plugin()]);+ render(<PluginSettingsTab />);++ expect(await screen.findByText('Not connected')).toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: 'Connect' }));++ await waitFor(() => expect(loc.href).toBe('https://provider.example/authorize?x=1'));+ });++ it('FE-COMP-PLUGINSETTINGS-021: a failing connect reports an error and frees the button', async () => {+ const user = userEvent.setup();+ serve('weather', {}, { configured: true, connected: false });+ server.use(http.post('/api/plugin-oauth/weather/connect', () =>+ HttpResponse.json({ error: 'nope' }, { status: 500 })));+ setPlugins([plugin()]);+ render(<><ToastContainer /><PluginSettingsTab /></>);++ await user.click(await screen.findByRole('button', { name: 'Connect' }));++ await screen.findByText('Error');+ await waitFor(() => expect(screen.getByRole('button', { name: 'Connect' })).toBeEnabled());+ });++ it('FE-COMP-PLUGINSETTINGS-022: disconnecting flips the row back to "not connected"', async () => {+ const user = userEvent.setup();+ serve('weather', {}, { configured: true, connected: true });+ server.use(http.post('/api/plugin-oauth/weather/disconnect', () => HttpResponse.json({ connected: false })));+ setPlugins([plugin()]);+ render(<PluginSettingsTab />);++ expect(await screen.findByText('Connected')).toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: 'Disconnect' }));++ expect(await screen.findByText('Not connected')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Connect' })).toBeInTheDocument();+ });++ it('FE-COMP-PLUGINSETTINGS-023: a failing disconnect keeps the connection and reports an error', async () => {+ const user = userEvent.setup();+ serve('weather', {}, { configured: true, connected: true });+ server.use(http.post('/api/plugin-oauth/weather/disconnect', () =>+ HttpResponse.json({ error: 'nope' }, { status: 500 })));+ setPlugins([plugin()]);+ render(<><ToastContainer /><PluginSettingsTab /></>);++ await user.click(await screen.findByRole('button', { name: 'Disconnect' }));++ await screen.findByText('Error');+ expect(screen.getByRole('button', { name: 'Disconnect' })).toBeEnabled();+ });++ it('FE-COMP-PLUGINSETTINGS-024: a settingsUi plugin also gets its own sandboxed frame card', async () => {+ serve('weather', {+ fields: [{ key: 'city', label: 'City', input_type: 'text' }],+ config: { city: 'Berlin' },+ });+ setPlugins([plugin({ settingsUi: true })]);+ const { container } = render(<PluginSettingsTab />);++ await screen.findByDisplayValue('Berlin');+ expect(screen.getAllByRole('heading', { name: 'Weather' })).toHaveLength(2);+ const frame = container.querySelector('iframe') as HTMLIFrameElement;+ expect(frame).not.toBeNull();+ expect(frame.getAttribute('src')).toBe('/plugin-frame/weather/settings.html');+ expect(frame.getAttribute('sandbox') || '').not.toContain('allow-same-origin');+ });++ it('FE-COMP-PLUGINSETTINGS-025: every active plugin gets its own form', async () => {+ serve('weather', { fields: [{ key: 'city', label: 'City', input_type: 'text' }], config: { city: 'Berlin' } });+ server.use(+ http.get('/api/plugin-settings/notes', () => HttpResponse.json({+ fields: [{ key: 'folder', label: 'Folder', input_type: 'text' }], config: { folder: 'Trips' }, actions: [],+ })),+ http.get('/api/plugin-oauth/notes/status', () => HttpResponse.json({ configured: false, connected: false })),+ );+ setPlugins([plugin(), plugin({ id: 'notes', name: 'Notes', icon: null })]);+ render(<PluginSettingsTab />);++ await screen.findByDisplayValue('Berlin');+ expect(await screen.findByDisplayValue('Trips')).toBeInTheDocument();+ expect(within(cardFor('Notes')).getByText('Folder')).toBeInTheDocument();+ });+});diff --git a/client/src/components/Settings/useMobileNavEditor.test.tsx b/client/src/components/Settings/useMobileNavEditor.test.tsxnew file mode 100644index 000000000..dc5244992--- /dev/null+++ b/client/src/components/Settings/useMobileNavEditor.test.tsx@@ -0,0 +1,159 @@+// FE-COMP-NAVEDITOR-001 to FE-COMP-NAVEDITOR-014+import React from 'react';+import { renderHook } from '../../../tests/helpers/render';+import { act } from '@testing-library/react';+import { resetAllStores, seedStore } from '../../../tests/helpers/store';+import { useAddonStore } from '../../store/addonStore';+import { usePluginStore } from '../../store/pluginStore';+import { TranslationProvider } from '../../i18n/TranslationContext';+import { useMobileNavEditor, type MobileNavValue } from './useMobileNavEditor';++const GLOBAL_ADDONS = [+ { id: 'vacay', name: 'Vacay', type: 'global', icon: 'calendar', enabled: true },+ { id: 'atlas', name: 'Atlas', type: 'global', icon: 'map', enabled: true },+ { id: 'journey', name: 'Journey', type: 'global', icon: 'compass', enabled: true },+ { id: 'collections', name: 'Collections', type: 'global', icon: 'bookmark', enabled: true },+];++function wrapper({ children }: { children: React.ReactNode }) {+ return <TranslationProvider>{children}</TranslationProvider>;+}++function setup(value: MobileNavValue) {+ const onChange = vi.fn<(next: MobileNavValue) => void>();+ const { result } = renderHook(() => useMobileNavEditor(value, onChange), { wrapper });+ return { result, onChange };+}++const ids = (items: { id: string }[]) => items.map(i => i.id);++beforeEach(() => {+ resetAllStores();+ vi.clearAllMocks();+ seedStore(useAddonStore, { addons: GLOBAL_ADDONS, loaded: true });+ usePluginStore.setState({ plugins: [], loaded: true });+});++describe('useMobileNavEditor', () => {+ it('FE-COMP-NAVEDITOR-001: an empty value falls back to the built-in dock split', () => {+ const { result } = setup({ bar: [], more: [] });++ expect(ids(result.current.barItems)).toEqual(['vacay', 'atlas']);+ expect(ids(result.current.moreItems)).toEqual(['journey', 'collections']);+ expect(result.current.hasMore).toBe(true);+ expect(result.current.barFull).toBe(true);+ });++ it('FE-COMP-NAVEDITOR-002: Dashboard is pinned, kept out of barItems and first in the preview', () => {+ const { result } = setup({ bar: ['vacay'], more: ['atlas'] });++ expect(result.current.dashboard?.id).toBe('dashboard');+ expect(ids(result.current.barItems)).toEqual(['vacay']);+ expect(ids(result.current.previewBar)).toEqual(['dashboard', 'vacay']);+ });++ it('FE-COMP-NAVEDITOR-003: a bar that is not full reports barFull false', () => {+ const { result } = setup({ bar: ['vacay'], more: ['atlas', 'journey', 'collections'] });++ expect(result.current.barFull).toBe(false);+ });++ it('FE-COMP-NAVEDITOR-004: everything in the bar leaves More empty', () => {+ seedStore(useAddonStore, { addons: GLOBAL_ADDONS.slice(0, 2), loaded: true });+ const { result } = setup({ bar: ['vacay', 'atlas'], more: [] });++ expect(result.current.moreItems).toEqual([]);+ expect(result.current.hasMore).toBe(false);+ });++ it('FE-COMP-NAVEDITOR-005: moving a bar item up emits the reordered id list', () => {+ const { result, onChange } = setup({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });++ act(() => result.current.move('bar', 1, 0));++ expect(onChange).toHaveBeenCalledWith({ bar: ['atlas', 'vacay'], more: ['journey', 'collections'] });+ });++ it('FE-COMP-NAVEDITOR-006: moving inside More leaves the bar untouched', () => {+ const { result, onChange } = setup({ bar: ['vacay'], more: ['journey', 'atlas', 'collections'] });++ act(() => result.current.move('more', 0, 1));++ expect(onChange).toHaveBeenCalledWith({ bar: ['vacay'], more: ['atlas', 'journey', 'collections'] });+ });++ it('FE-COMP-NAVEDITOR-007: a move past the end of a zone emits the list unchanged', () => {+ const { result, onChange } = setup({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });++ act(() => result.current.move('bar', 1, 2));++ expect(onChange).toHaveBeenCalledWith({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });+ });++ it('FE-COMP-NAVEDITOR-008: a move before the start of a zone emits the list unchanged', () => {+ const { result, onChange } = setup({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });++ act(() => result.current.move('bar', 0, -1));++ expect(onChange).toHaveBeenCalledWith({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });+ });++ it('FE-COMP-NAVEDITOR-009: a move onto itself emits the list unchanged', () => {+ const { result, onChange } = setup({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });++ act(() => result.current.move('bar', 1, 1));++ expect(onChange).toHaveBeenCalledWith({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });+ });++ it('FE-COMP-NAVEDITOR-010: demoting a bar item appends it to the end of More', () => {+ const { result, onChange } = setup({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });++ act(() => result.current.toMore('vacay'));++ expect(onChange).toHaveBeenCalledWith({ bar: ['atlas'], more: ['journey', 'collections', 'vacay'] });+ });++ it('FE-COMP-NAVEDITOR-011: demoting an id that is not in the bar is a no-op', () => {+ const { result, onChange } = setup({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });++ act(() => result.current.toMore('journey'));++ expect(onChange).not.toHaveBeenCalled();+ });++ it('FE-COMP-NAVEDITOR-012: promoting appends to the bar and drops the item from More', () => {+ const { result, onChange } = setup({ bar: ['vacay'], more: ['journey', 'atlas', 'collections'] });++ act(() => result.current.toBar('atlas'));++ expect(onChange).toHaveBeenCalledWith({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });+ });++ it('FE-COMP-NAVEDITOR-013: promoting is refused when the bar is full or the id is unknown', () => {+ const full = setup({ bar: ['vacay', 'atlas'], more: ['journey', 'collections'] });+ act(() => full.result.current.toBar('journey'));+ expect(full.onChange).not.toHaveBeenCalled();++ const room = setup({ bar: ['vacay'], more: ['journey', 'atlas', 'collections'] });+ act(() => room.result.current.toBar('does-not-exist'));+ expect(room.onChange).not.toHaveBeenCalled();+ });++ it('FE-COMP-NAVEDITOR-014: page plugins take part in the split under their plugin id', () => {+ usePluginStore.setState({+ plugins: [{ id: 'todos', name: 'Trip To-Dos', type: 'page', icon: 'list' }] as never,+ loaded: true,+ });+ const { result, onChange } = setup({ bar: ['vacay'], more: ['plugin:todos'] });++ // Items the stored config never mentioned are appended under More.+ expect(ids(result.current.moreItems)).toEqual(['plugin:todos', 'atlas', 'journey', 'collections']);++ act(() => result.current.toBar('plugin:todos'));+ expect(onChange).toHaveBeenCalledWith({+ bar: ['vacay', 'plugin:todos'],+ more: ['atlas', 'journey', 'collections'],+ });+ });+});diff --git a/client/src/components/SystemNotices/SystemNoticeBanner.extra.test.tsx b/client/src/components/SystemNotices/SystemNoticeBanner.extra.test.tsxnew file mode 100644index 000000000..14efa10a6--- /dev/null+++ b/client/src/components/SystemNotices/SystemNoticeBanner.extra.test.tsx@@ -0,0 +1,312 @@+// FE-W4SNB-001 to FE-W4SNB-029+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { act } from '@testing-library/react'+import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render'+import { useSystemNoticeStore, type SystemNoticeDTO } from '../../store/systemNoticeStore'+import { registerNoticeAction } from './noticeActions'+import { BannerRenderer, ToastRenderer } from './SystemNoticeBanner'++const navigate = vi.fn()+vi.mock('react-router-dom', async () => {+ const actual = await vi.importActual<typeof import('react-router-dom')>('react-router-dom')+ return { ...actual, useNavigate: () => navigate }+})++function notice(overrides: Partial<SystemNoticeDTO> & { id: string }): SystemNoticeDTO {+ return {+ display: 'banner',+ severity: 'info',+ titleKey: 'Maintenance',+ bodyKey: 'Back at noon.',+ dismissible: true,+ ...overrides,+ } as SystemNoticeDTO+}++const dismiss = vi.fn()++let realMatchMedia: typeof window.matchMedia+let realRaf: typeof globalThis.requestAnimationFrame+let realResizeObserver: typeof globalThis.ResizeObserver++beforeEach(() => {+ navigate.mockClear()+ dismiss.mockClear()+ useSystemNoticeStore.setState({ notices: [], loaded: true, dismiss })+ window.__addToast = vi.fn(() => 1)+ realMatchMedia = window.matchMedia+ realRaf = globalThis.requestAnimationFrame+ realResizeObserver = globalThis.ResizeObserver+})++afterEach(() => {+ vi.restoreAllMocks()+ delete window.__addToast+ document.documentElement.style.removeProperty('--banner-stack-h')+ window.matchMedia = realMatchMedia+ globalThis.requestAnimationFrame = realRaf+ globalThis.ResizeObserver = realResizeObserver+})++describe('BannerRenderer', () => {+ it('FE-W4SNB-001: renders nothing without banners', () => {+ const { container } = render(<BannerRenderer notices={[]} />)+ expect(container).toBeEmptyDOMElement()+ })++ it('FE-W4SNB-002: shows at most the two highest-priority banners', () => {+ render(<BannerRenderer notices={[notice({ id: 'a' }), notice({ id: 'b' }), notice({ id: 'c' })]} />)++ expect(screen.getAllByRole('status')).toHaveLength(2)+ })++ it('FE-W4SNB-003: a warn banner stays a polite status', () => {+ render(<BannerRenderer notices={[notice({ id: 'a', severity: 'warn' })]} />)+ const banner = screen.getByRole('status')++ expect(banner).toHaveAttribute('aria-live', 'polite')+ expect(banner.className).toContain('bg-amber-50')+ })++ it('FE-W4SNB-004: a critical banner is an assertive alert', () => {+ render(<BannerRenderer notices={[notice({ id: 'a', severity: 'critical' })]} />)+ const banner = screen.getByRole('alert')++ expect(banner).toHaveAttribute('aria-live', 'assertive')+ expect(banner.className).toContain('bg-rose-50')+ })++ it('FE-W4SNB-005: an unknown severity falls back to the info styling', () => {+ render(<BannerRenderer notices={[notice({ id: 'a', severity: 'weird' as SystemNoticeDTO['severity'] })]} />)++ expect(screen.getByRole('status').className).toContain('bg-white')+ })++ it('FE-W4SNB-006: hides the body when it repeats the title', () => {+ render(<BannerRenderer notices={[notice({ id: 'a', titleKey: 'Same', bodyKey: 'Same' })]} />)++ expect(screen.getAllByText('Same')).toHaveLength(1)+ })++ it('FE-W4SNB-007: the close button dismisses the notice', () => {+ render(<BannerRenderer notices={[notice({ id: 'a' })]} />)++ fireEvent.click(screen.getByLabelText('Dismiss: Maintenance'))++ expect(dismiss).toHaveBeenCalledWith('a')+ })++ it('FE-W4SNB-008: a non-dismissible banner has no close button', () => {+ render(<BannerRenderer notices={[notice({ id: 'a', dismissible: false })]} />)++ expect(screen.queryByLabelText(/^Dismiss:/)).toBeNull()+ })++ it('FE-W4SNB-009: a nav CTA routes in-app and dismisses the banner', () => {+ render(<BannerRenderer notices={[notice({ id: 'a', cta: { kind: 'nav', href: '/settings', labelKey: 'Open settings' } })]} />)++ fireEvent.click(screen.getByRole('link', { name: 'Open settings' }))++ expect(navigate).toHaveBeenCalledWith('/settings')+ expect(dismiss).toHaveBeenCalledWith('a')+ })++ it('FE-W4SNB-010: a nav CTA on a sticky banner does not dismiss it', () => {+ render(+ <BannerRenderer notices={[notice({ id: 'a', dismissible: false, cta: { kind: 'nav', href: '/settings', labelKey: 'Open settings' } })]} />,+ )++ fireEvent.click(screen.getByRole('link', { name: 'Open settings' }))++ expect(navigate).toHaveBeenCalledWith('/settings')+ expect(dismiss).not.toHaveBeenCalled()+ })++ it('FE-W4SNB-011: a link CTA opens a hardened new tab', () => {+ const open = vi.spyOn(window, 'open').mockImplementation(() => null)+ render(<BannerRenderer notices={[notice({ id: 'a', cta: { kind: 'link', href: 'https://trek.dev', labelKey: 'Read more' } })]} />)++ fireEvent.click(screen.getByRole('link', { name: 'Read more' }))++ expect(open).toHaveBeenCalledWith('https://trek.dev', '_blank', 'noopener,noreferrer')+ expect(dismiss).not.toHaveBeenCalled()+ })++ it('FE-W4SNB-012: an action CTA runs the registered handler and dismisses by default', () => {+ const handler = vi.fn(() => {})+ registerNoticeAction('open-support', handler)+ render(<BannerRenderer notices={[notice({ id: 'a', cta: { kind: 'action', actionId: 'open-support', labelKey: 'Support' } })]} />)++ fireEvent.click(screen.getByRole('button', { name: 'Support' }))++ expect(handler).toHaveBeenCalledWith({ navigate })+ expect(dismiss).toHaveBeenCalledWith('a')+ })++ it('FE-W4SNB-013: an action CTA can opt out of dismissing', () => {+ registerNoticeAction('stay-open', () => {})+ render(+ <BannerRenderer notices={[notice({ id: 'a', cta: { kind: 'action', actionId: 'stay-open', labelKey: 'Support', dismissOnAction: false } })]} />,+ )++ fireEvent.click(screen.getByRole('button', { name: 'Support' }))++ expect(dismiss).not.toHaveBeenCalled()+ })++ it('FE-W4SNB-014: resets the reported stack height on unmount', () => {+ const { unmount } = render(<BannerRenderer notices={[notice({ id: 'a' })]} />)++ unmount()++ expect(document.documentElement.style.getPropertyValue('--banner-stack-h')).toBe('0px')+ })++ it('FE-W4SNB-015: fades the banner in on the next frame', async () => {+ render(<BannerRenderer notices={[notice({ id: 'a' })]} />)+ expect(screen.getByRole('status').parentElement?.className).toContain('opacity-0')++ await waitFor(() => expect(screen.getByRole('status').parentElement?.className).toContain('opacity-100'))+ })++ it('FE-W4SNB-025: reduced motion drops the slide and fades only', () => {+ window.matchMedia = ((query: string) => ({+ matches: query.includes('prefers-reduced-motion'),+ media: query,+ onchange: null,+ addListener: () => {},+ removeListener: () => {},+ addEventListener: () => {},+ removeEventListener: () => {},+ dispatchEvent: () => false,+ })) as unknown as typeof window.matchMedia++ render(<BannerRenderer notices={[notice({ id: 'a' })]} />)++ expect(screen.getByRole('status').parentElement?.className).toContain('transition-opacity')+ expect(screen.getByRole('status').parentElement?.className).not.toContain('transition-all')+ })++ it('FE-W4SNB-026: a browser without matchMedia keeps the full transition', () => {+ ;(window as unknown as { matchMedia?: unknown }).matchMedia = undefined++ render(<BannerRenderer notices={[notice({ id: 'a' })]} />)++ expect(screen.getByRole('status').parentElement?.className).toContain('transition-all')+ })++ it('FE-W4SNB-027: without requestAnimationFrame the banner mounts already visible', () => {+ Reflect.deleteProperty(globalThis, 'requestAnimationFrame')++ render(<BannerRenderer notices={[notice({ id: 'a' })]} />)++ expect(screen.getByRole('status').parentElement?.className).toContain('opacity-100')+ })++ it('FE-W4SNB-028: publishes the measured stack height as a CSS variable', () => {+ let resize: ResizeObserverCallback | null = null+ class CapturingResizeObserver {+ observe = vi.fn()+ unobserve = vi.fn()+ disconnect = vi.fn()+ constructor(cb: ResizeObserverCallback) { resize = cb }+ }+ globalThis.ResizeObserver = CapturingResizeObserver as unknown as typeof globalThis.ResizeObserver++ render(<BannerRenderer notices={[notice({ id: 'a' })]} />)++ const stack = screen.getByRole('status').parentElement?.parentElement as HTMLElement+ Object.defineProperty(stack, 'offsetHeight', { configurable: true, value: 64 })++ act(() => {+ resize?.([], {} as ResizeObserver)+ })++ expect(document.documentElement.style.getPropertyValue('--banner-stack-h')).toBe('64px')+ })+})++describe('ToastRenderer', () => {+ beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true })+ })+ afterEach(() => {+ vi.useRealTimers()+ })++ it('FE-W4SNB-016: fires an info toast joining title and body', () => {+ render(<ToastRenderer notices={[notice({ id: 't1', display: 'toast' })]} />)++ expect(window.__addToast).toHaveBeenCalledWith('Maintenance: Back at noon.', 'info', 6000)+ })++ it('FE-W4SNB-017: a warn toast uses the warning variant and a longer duration', () => {+ render(<ToastRenderer notices={[notice({ id: 't1', display: 'toast', severity: 'warn' })]} />)++ expect(window.__addToast).toHaveBeenCalledWith('Maintenance: Back at noon.', 'warning', 9000)+ })++ it('FE-W4SNB-018: uses the title alone when the body repeats it', () => {+ render(<ToastRenderer notices={[notice({ id: 't1', display: 'toast', titleKey: 'Same', bodyKey: 'Same' })]} />)++ expect(window.__addToast).toHaveBeenCalledWith('Same', 'info', 6000)+ })++ it('FE-W4SNB-019: dismisses the notice once the toast has run its course', () => {+ render(<ToastRenderer notices={[notice({ id: 't1', display: 'toast' })]} />)++ act(() => { vi.advanceTimersByTime(6500) })++ expect(dismiss).toHaveBeenCalledWith('t1')+ })++ it('FE-W4SNB-020: refuses a critical toast and dismisses it instead', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ render(<ToastRenderer notices={[notice({ id: 't1', display: 'toast', severity: 'critical' })]} />)++ expect(window.__addToast).not.toHaveBeenCalled()+ expect(dismiss).toHaveBeenCalledWith('t1')+ expect(String(warn.mock.calls[0][0])).toContain('t1')+ })++ it('FE-W4SNB-021: fires each notice only once across rerenders', () => {+ const notices = [notice({ id: 't1', display: 'toast' })]+ const { rerender } = render(<ToastRenderer notices={notices} />)++ rerender(<ToastRenderer notices={[...notices]} />)++ expect(window.__addToast).toHaveBeenCalledTimes(1)+ })++ it('FE-W4SNB-022: retries on the next frame while the toast host is not registered yet', () => {+ delete window.__addToast+ const raf = vi.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 0)++ render(<ToastRenderer notices={[notice({ id: 't1', display: 'toast' })]} />)++ expect(raf).toHaveBeenCalled()+ expect(dismiss).not.toHaveBeenCalled()+ })++ it('FE-W4SNB-023: drops the toast after ten failed frames', () => {+ delete window.__addToast+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation((cb: FrameRequestCallback) => { cb(0); return 0 })++ render(<ToastRenderer notices={[notice({ id: 't1', display: 'toast' })]} />)++ expect(String(warn.mock.calls[warn.mock.calls.length - 1][0])).toContain('never registered')+ })++ it('FE-W4SNB-029: an unmapped severity falls back to the info variant', () => {+ render(<ToastRenderer notices={[notice({ id: 't1', display: 'toast', severity: 'legendary' as SystemNoticeDTO['severity'] })]} />)++ expect(window.__addToast).toHaveBeenCalledWith('Maintenance: Back at noon.', 'info', 6000)+ })++ it('FE-W4SNB-024: renders no DOM of its own', () => {+ const { container } = render(<ToastRenderer notices={[notice({ id: 't1', display: 'toast' })]} />)++ expect(container).toBeEmptyDOMElement()+ })+})diff --git a/client/src/components/SystemNotices/SystemNoticeHost.test.tsx b/client/src/components/SystemNotices/SystemNoticeHost.test.tsxnew file mode 100644index 000000000..84afad95a--- /dev/null+++ b/client/src/components/SystemNotices/SystemNoticeHost.test.tsx@@ -0,0 +1,155 @@+// FE-W4SNH-001 to FE-W4SNH-008+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { render, screen, act } from '../../../tests/helpers/render'+import { useSystemNoticeStore, type SystemNoticeDTO } from '../../store/systemNoticeStore'++vi.mock('./SystemNoticeModal.js', () => ({+ ModalRenderer: ({ notices }: { notices: SystemNoticeDTO[] }) =>+ <div data-testid="modals">{notices.map(n => n.id).join(',')}</div>,+}))+vi.mock('./SystemNoticeBanner.js', () => ({+ BannerRenderer: ({ notices }: { notices: SystemNoticeDTO[] }) =>+ <div data-testid="banners">{notices.map(n => n.id).join(',')}</div>,+ ToastRenderer: ({ notices }: { notices: SystemNoticeDTO[] }) =>+ <div data-testid="toasts">{notices.map(n => n.id).join(',')}</div>,+}))++import { SystemNoticeHost } from './SystemNoticeHost'++function notice(overrides: Partial<SystemNoticeDTO> & { id: string }): SystemNoticeDTO {+ return {+ display: 'banner',+ severity: 'info',+ titleKey: 'Title',+ bodyKey: 'Body',+ dismissible: true,+ ...overrides,+ } as SystemNoticeDTO+}++let mqListeners: Array<(e: MediaQueryListEvent) => void> = []++function stubMatchMedia(matches: boolean, { supported = true } = {}) {+ mqListeners = []+ Object.defineProperty(window, 'matchMedia', {+ writable: true,+ configurable: true,+ value: supported+ ? vi.fn((query: string) => ({+ matches,+ media: query,+ addEventListener: (_ev: string, fn: (e: MediaQueryListEvent) => void) => { mqListeners.push(fn) },+ removeEventListener: (_ev: string, fn: (e: MediaQueryListEvent) => void) => {+ mqListeners = mqListeners.filter(l => l !== fn)+ },+ }))+ : undefined,+ })+}++beforeEach(() => {+ stubMatchMedia(false)+ useSystemNoticeStore.setState({ notices: [], loaded: true, fetching: false })+})++afterEach(() => {+ vi.restoreAllMocks()+})++describe('SystemNoticeHost', () => {+ it('FE-W4SNH-001: renders nothing until the store has loaded', () => {+ useSystemNoticeStore.setState({ notices: [], loaded: false, fetching: true })+ const { container } = render(<SystemNoticeHost />)++ expect(container).toBeEmptyDOMElement()+ })++ it('FE-W4SNH-002: triggers a cold-session fetch when nothing is loaded yet', () => {+ const fetch = vi.fn(async () => {})+ useSystemNoticeStore.setState({ notices: [], loaded: false, fetching: false, fetch })++ render(<SystemNoticeHost />)++ expect(fetch).toHaveBeenCalledOnce()+ })++ it('FE-W4SNH-003: does not refetch when authStore already loaded the notices', () => {+ const fetch = vi.fn(async () => {})+ useSystemNoticeStore.setState({ notices: [], loaded: true, fetching: false, fetch })++ render(<SystemNoticeHost />)++ expect(fetch).not.toHaveBeenCalled()+ })++ it('FE-W4SNH-004: routes each notice to the renderer matching its display', () => {+ useSystemNoticeStore.setState({+ loaded: true,+ notices: [+ notice({ id: 'b1', display: 'banner' }),+ notice({ id: 'm1', display: 'modal' }),+ notice({ id: 't1', display: 'toast' }),+ notice({ id: 'b2', display: 'banner' }),+ ],+ })++ render(<SystemNoticeHost />)++ expect(screen.getByTestId('banners')).toHaveTextContent('b1,b2')+ expect(screen.getByTestId('modals')).toHaveTextContent('m1')+ expect(screen.getByTestId('toasts')).toHaveTextContent('t1')+ })++ it('FE-W4SNH-005: hides desktopOnly notices on a mobile viewport', () => {+ stubMatchMedia(true)+ useSystemNoticeStore.setState({+ loaded: true,+ notices: [+ notice({ id: 'thanks', display: 'modal', desktopOnly: true }),+ notice({ id: 'outage', display: 'modal' }),+ ],+ })++ render(<SystemNoticeHost />)++ expect(screen.getByTestId('modals')).toHaveTextContent('outage')+ expect(screen.getByTestId('modals')).not.toHaveTextContent('thanks')+ })++ it('FE-W4SNH-006: keeps desktopOnly notices on a desktop viewport', () => {+ useSystemNoticeStore.setState({+ loaded: true,+ notices: [notice({ id: 'thanks', display: 'modal', desktopOnly: true })],+ })++ render(<SystemNoticeHost />)++ expect(screen.getByTestId('modals')).toHaveTextContent('thanks')+ })++ it('FE-W4SNH-007: reacts to a viewport change reported by matchMedia', () => {+ useSystemNoticeStore.setState({+ loaded: true,+ notices: [notice({ id: 'thanks', display: 'modal', desktopOnly: true })],+ })++ render(<SystemNoticeHost />)+ expect(screen.getByTestId('modals')).toHaveTextContent('thanks')++ act(() => { mqListeners.forEach(fn => fn({ matches: true } as MediaQueryListEvent)) })++ expect(screen.getByTestId('modals')).toBeEmptyDOMElement()+ })++ it('FE-W4SNH-008: falls back to the desktop layout when matchMedia is unavailable', () => {+ stubMatchMedia(false, { supported: false })+ useSystemNoticeStore.setState({+ loaded: true,+ notices: [notice({ id: 'thanks', display: 'modal', desktopOnly: true })],+ })++ render(<SystemNoticeHost />)++ expect(screen.getByTestId('modals')).toHaveTextContent('thanks')+ })+})diff --git a/client/src/components/SystemNotices/SystemNoticeModal.test.tsx b/client/src/components/SystemNotices/SystemNoticeModal.test.tsxindex f7b030c33..e301473a8 100644--- a/client/src/components/SystemNotices/SystemNoticeModal.test.tsx+++ b/client/src/components/SystemNotices/SystemNoticeModal.test.tsx@@ -1,19 +1,142 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import type { ComponentType, ReactNode } from 'react';import { act } from '@testing-library/react';import { render, screen, fireEvent } from '../../../tests/helpers/render';import { http, HttpResponse } from 'msw';import { server } from '../../../tests/helpers/msw/server';import { useSystemNoticeStore } from '../../store/systemNoticeStore';+import { registerNoticeAction } from './noticeActions';import { ModalRenderer } from './SystemNoticeModal';import type { SystemNoticeDTO } from '../../store/systemNoticeStore';+const routerMocks = vi.hoisted(() => ({ navigate: vi.fn((_to: string) => {}) }));+vi.mock('react-router-dom', async () => {+ const actual = await vi.importActual<typeof import('react-router-dom')>('react-router-dom');+ return { ...actual, useNavigate: () => routerMocks.navigate };+});++// Flips isRtlLanguage on demand so the mirrored arrow-key / swipe branches can be+// driven without loading a real RTL locale bundle.+const i18nEnv = vi.hoisted(() => ({ rtl: false }));+vi.mock('../../i18n/index.js', async importOriginal => {+ const actual = await importOriginal<typeof import('../../i18n/index')>();+ return {+ ...actual,+ isRtlLanguage: (lang: string) => i18nEnv.rtl || actual.isRtlLanguage(lang),+ };+});++interface MarkdownOverrideProps {+ href?: string;+ children?: ReactNode;+}+interface MarkdownOverrides {+ a: ComponentType<MarkdownOverrideProps>;+ p: ComponentType<MarkdownOverrideProps>;+ hr: ComponentType<MarkdownOverrideProps>;+ strong: ComponentType<MarkdownOverrideProps>;+ ul: ComponentType<MarkdownOverrideProps>;+ ol: ComponentType<MarkdownOverrideProps>;+}++// Body marker that makes the stub render the element overrides the modal hands to+// react-markdown (links, signature paragraphs, rule, lists) — they are ordinary+// components, so rendering them directly is the only way to reach them.+const MD_PROBE = '@@md-probe';++function MarkdownOverrideProbe({ c }: { c: MarkdownOverrides }) {+ return (+ <span data-testid="md-parts">+ <c.a href="https://trek.app/changelog">changelog</c.a>+ <c.p>{'— Maurice'}</c.p>+ <c.p>{['— Julien', <em key="mark">!</em>]}</c.p>+ <c.p>{'— a closing line that runs past the signature length limit'}</c.p>+ <c.p>{'a plain paragraph'}</c.p>+ <c.p>{[<em key="only">no string child</em>]}</c.p>+ <c.p><em>single element child</em></c.p>+ <c.hr />+ <c.strong>bold bit</c.strong>+ <c.ul><li>bullet</li></c.ul>+ <c.ol><li>numbered</li></c.ol>+ </span>+ );+}+// Stub react-markdown to avoid async chunk issues in testsvi.mock('react-markdown', () => ({- default: ({ children }: { children: string }) => <span data-testid="md">{children}</span>,+ default: ({ children, components }: { children: string; components: MarkdownOverrides }) => (+ <span data-testid="md">+ {children}+ {children.includes(MD_PROBE) && <MarkdownOverrideProbe c={components} />}+ </span>+ ),}));vi.mock('remark-gfm', () => ({ default: () => ({}) }));vi.mock('rehype-sanitize', () => ({ default: () => ({}) }));+interface MediaEnv {+ mobile?: boolean;+ reducedMotion?: boolean;+}++// Listeners the component registers on the (max-width: 639px) query, so a viewport+// change can be replayed from a test.+const mqChangeListeners: Array<(e: MediaQueryListEvent) => void> = [];++function stubMatchMedia({ mobile = false, reducedMotion = false }: MediaEnv = {}) {+ mqChangeListeners.length = 0;+ window.matchMedia = ((query: string) => ({+ matches: query.includes('prefers-reduced-motion')+ ? reducedMotion+ : query.includes('max-width')+ ? mobile+ : false,+ media: query,+ onchange: null,+ addListener: () => {},+ removeListener: () => {},+ addEventListener: (_type: string, cb: (e: MediaQueryListEvent) => void) => {+ mqChangeListeners.push(cb);+ },+ removeEventListener: (_type: string, cb: (e: MediaQueryListEvent) => void) => {+ const at = mqChangeListeners.indexOf(cb);+ if (at >= 0) mqChangeListeners.splice(at, 1);+ },+ dispatchEvent: () => false,+ })) as unknown as typeof window.matchMedia;+}++// The mobile sheet is [drag handle, clip [ strip [ prev, center, next ] ] ]+function sheetParts() {+ const sheet = screen.getByRole('dialog');+ const strip = sheet.children[1].children[0] as HTMLElement;+ return {+ sheet,+ strip,+ prevSlot: strip.children[0] as HTMLElement,+ centerSlot: strip.children[1] as HTMLElement,+ nextSlot: strip.children[2] as HTMLElement,+ };+}++function swipeHorizontally(sheet: HTMLElement, from: number, to: number) {+ const lockStep = from + (to > from ? 12 : -12);+ fireEvent.touchStart(sheet, { touches: [{ clientX: from, clientY: 200 }] });+ // below the 8px classification threshold — gesture stays unclassified+ fireEvent.touchMove(sheet, { touches: [{ clientX: from + 2, clientY: 200 }] });+ fireEvent.touchMove(sheet, { touches: [{ clientX: lockStep, clientY: 200 }] });+ fireEvent.touchMove(sheet, { touches: [{ clientX: to, clientY: 200 }] });+ fireEvent.touchEnd(sheet, { changedTouches: [{ clientX: to, clientY: 200 }] });+}++function dragVertically(sheet: HTMLElement, from: number, to: number) {+ const lockStep = from + (to > from ? 12 : -12);+ fireEvent.touchStart(sheet, { touches: [{ clientX: 200, clientY: from }] });+ fireEvent.touchMove(sheet, { touches: [{ clientX: 200, clientY: lockStep }] });+ fireEvent.touchMove(sheet, { touches: [{ clientX: 200, clientY: to }] });+ fireEvent.touchEnd(sheet, { changedTouches: [{ clientX: 200, clientY: to }] });+}+function makeNotice(overrides: Partial<SystemNoticeDTO> = {}): SystemNoticeDTO {return {id: 'test-notice-1',@@ -38,6 +161,9 @@ async function flushGraceDelay() {}describe('ModalRenderer', () => {+ let realMatchMedia: typeof window.matchMedia;+ let realRaf: typeof globalThis.requestAnimationFrame;+beforeEach(() => {server.use(http.post('/api/system-notices/:id/dismiss', () => {@@ -45,6 +171,14 @@ describe('ModalRenderer', () => {}),);useSystemNoticeStore.setState({ notices: [], loaded: true });+ realMatchMedia = window.matchMedia;+ realRaf = globalThis.requestAnimationFrame;+ // jsdom has no Element.prototype.scrollTo; the mobile sheet resets slot scroll on paging+ Object.defineProperty(Element.prototype, 'scrollTo', {+ writable: true,+ configurable: true,+ value: vi.fn(),+ });vi.useFakeTimers();});@@ -52,6 +186,10 @@ describe('ModalRenderer', () => {vi.useRealTimers();vi.clearAllMocks();document.body.style.overflow = '';+ window.matchMedia = realMatchMedia;+ globalThis.requestAnimationFrame = realRaf;+ i18nEnv.rtl = false;+ document.documentElement.classList.remove('dark');});it('FE-SN-MODAL-001: renders title and body after grace delay', async () => {@@ -389,4 +527,843 @@ describe('ModalRenderer', () => {expect(container.firstChild).toBeNull();});++ // ── Media / icons / highlights ─────────────────────────────────────────────++ it('FE-SN-MODAL-019: hero media replaces the severity bubble and hides itself on load error', async () => {+ const notice = makeNotice({+ media: { src: '/uploads/hero.png', altKey: 'Release hero', placement: 'hero', aspectRatio: '4/3' },+ });+ const { container } = render(<ModalRenderer notices={[notice]} />);+ await flushGraceDelay();++ const img = screen.getByAltText('Release hero') as HTMLImageElement;+ expect(img.getAttribute('src')).toBe('/uploads/hero.png');+ expect((img.parentElement as HTMLElement).style.aspectRatio).toBe('4/3');+ // hero takes the place of the round severity icon+ expect(container.querySelector('.lucide-info')).toBeNull();++ await act(async () => {+ fireEvent.error(img);+ });++ expect(img.style.display).toBe('none');+ });++ it('FE-SN-MODAL-020: hero media falls back to 16/9 and swaps to the dark source', async () => {+ const notice = makeNotice({+ media: { src: '/uploads/light.png', srcDark: '/uploads/dark.png', altKey: 'Release hero' },+ });+ render(<ModalRenderer notices={[notice]} />);+ await flushGraceDelay();++ const img = () => screen.getByAltText('Release hero') as HTMLImageElement;+ expect(img().getAttribute('src')).toBe('/uploads/light.png');+ expect((img().parentElement as HTMLElement).style.aspectRatio).toBe('16/9');++ await act(async () => {+ document.documentElement.classList.add('dark');+ await Promise.resolve();+ await Promise.resolve();+ });++ expect(img().getAttribute('src')).toBe('/uploads/dark.png');+ });++ it('FE-SN-MODAL-021: inline media renders below the body and honours its own ratio', async () => {+ const withRatio = makeNotice({+ id: 'inline-1',+ media: { src: '/uploads/inline.png', altKey: 'Inline shot', placement: 'inline', aspectRatio: '1/1' },+ });+ const withoutRatio = makeNotice({+ id: 'inline-2',+ media: { src: '/uploads/plain.png', srcDark: '/uploads/plain-dark.png', altKey: 'Plain shot', placement: 'inline' },+ });++ const { rerender } = render(<ModalRenderer notices={[withRatio]} />);+ await flushGraceDelay();++ const first = screen.getByAltText('Inline shot') as HTMLImageElement;+ expect((first.parentElement as HTMLElement).style.aspectRatio).toBe('1/1');+ await act(async () => {+ fireEvent.error(first);+ });+ expect(first.style.display).toBe('none');++ rerender(<ModalRenderer notices={[withoutRatio]} />);+ await flushGraceDelay();++ const second = screen.getByAltText('Plain shot') as HTMLImageElement;+ expect((second.parentElement as HTMLElement).style.aspectRatio).toBe('16/9');+ expect(second.getAttribute('src')).toBe('/uploads/plain.png');++ await act(async () => {+ document.documentElement.classList.add('dark');+ await Promise.resolve();+ await Promise.resolve();+ });++ expect((screen.getByAltText('Plain shot') as HTMLImageElement).getAttribute('src')).toBe('/uploads/plain-dark.png');+ });++ it('FE-SN-MODAL-022: the Heart notice gets the gradient header instead of a plain title', async () => {+ const heartOnly = makeNotice({ id: 'heart-1', icon: 'Heart', titleKey: 'Thank you' });+ const heartWithMedia = makeNotice({+ id: 'heart-2',+ icon: 'Heart',+ titleKey: 'Thank you again',+ media: { src: '/uploads/heart.png', altKey: 'Heart hero' },+ });++ const { container, rerender } = render(<ModalRenderer notices={[heartOnly]} />);+ await flushGraceDelay();++ const heading = screen.getByText('Thank you');+ expect(heading.tagName).toBe('H2');+ expect((heading.parentElement as HTMLElement).className).toContain('bg-gradient-to-br');+ // no round severity bubble next to the gradient header+ expect(container.querySelector('.lucide-info')).toBeNull();++ // With a hero image the gradient header is dropped and the plain title returns+ rerender(<ModalRenderer notices={[heartWithMedia]} />);+ await flushGraceDelay();++ const plainHeading = screen.getByText('Thank you again');+ expect((plainHeading.parentElement as HTMLElement).className).not.toContain('bg-gradient-to-br');+ expect(screen.getByAltText('Heart hero')).toBeTruthy();+ });++ it('FE-SN-MODAL-023: a named lucide icon overrides the severity icon, unknown names fall back', async () => {+ const known = makeNotice({ id: 'icon-1', icon: 'Rocket' });+ const unknown = makeNotice({ id: 'icon-2', icon: 'ThisIconDoesNotExist' });++ const { container, rerender } = render(<ModalRenderer notices={[known]} />);+ await flushGraceDelay();++ expect(container.querySelector('.lucide-rocket')).not.toBeNull();+ expect(container.querySelector('.lucide-info')).toBeNull();++ rerender(<ModalRenderer notices={[unknown]} />);+ await flushGraceDelay();++ expect(container.querySelector('.lucide-info')).not.toBeNull();+ });++ it('FE-SN-MODAL-024: an unknown severity falls back to the info icon and drops the accent tint', async () => {+ const notice = makeNotice({ severity: 'obscure' as SystemNoticeDTO['severity'] });+ const { container } = render(<ModalRenderer notices={[notice]} />);+ await flushGraceDelay();++ const icon = container.querySelector('.lucide-info');+ expect(icon).not.toBeNull();+ const bubble = (icon as SVGElement).parentElement as HTMLElement;+ expect(bubble.className).toContain('rounded-full');+ expect(bubble.className).not.toContain('bg-blue-50');+ });++ it('FE-SN-MODAL-025: highlights render their lucide icon and fall back to a check mark', async () => {+ const notice = makeNotice({+ highlights: [+ { labelKey: 'Faster maps', iconName: 'Zap' },+ { labelKey: 'No icon given' },+ { labelKey: 'Unknown icon', iconName: 'NopeIcon' },+ ],+ });+ const { container } = render(<ModalRenderer notices={[notice]} />);+ await flushGraceDelay();++ expect(screen.getByText('Faster maps')).toBeTruthy();+ expect(screen.getByText('No icon given')).toBeTruthy();+ expect(screen.getByText('Unknown icon')).toBeTruthy();+ expect(container.querySelector('.lucide-zap')).not.toBeNull();+ expect(screen.getAllByText('✓')).toHaveLength(2);+ });++ it('FE-SN-MODAL-026: markdown overrides style links, signatures, rules and lists', async () => {+ const notice = makeNotice({ bodyKey: `Release notes ${MD_PROBE}` });+ render(<ModalRenderer notices={[notice]} />);+ await flushGraceDelay();++ const parts = screen.getByTestId('md-parts');++ const link = parts.querySelector('a') as HTMLAnchorElement;+ expect(link.getAttribute('href')).toBe('https://trek.app/changelog');+ expect(link.getAttribute('target')).toBe('_blank');+ expect(link.getAttribute('rel')).toBe('noopener noreferrer');++ const paragraphs = Array.from(parts.querySelectorAll('p'));+ // short em-dash lines are signatures, everything else is a normal paragraph+ expect(paragraphs[0].className).toContain('italic');+ expect(paragraphs[1].className).toContain('italic');+ expect(paragraphs[2].className).not.toContain('italic');+ expect(paragraphs[3].className).not.toContain('italic');+ expect(paragraphs[4].className).not.toContain('italic');+ expect(paragraphs[5].className).not.toContain('italic');++ expect(parts.textContent).toContain('♡');+ expect((parts.querySelector('strong') as HTMLElement).className).toContain('font-semibold');+ expect((parts.querySelector('ul') as HTMLElement).className).toContain('list-disc');+ expect((parts.querySelector('ol') as HTMLElement).className).toContain('list-decimal');+ });++ // ── CTAs ───────────────────────────────────────────────────────────────────++ it('FE-SN-MODAL-027: link CTAs open a new tab and leave the notice open', async () => {+ const open = vi.spyOn(window, 'open').mockImplementation(() => null);+ const notice = makeNotice({+ cta: { kind: 'link', href: 'https://example.com/support', labelKey: 'Support us' },+ secondaryCta: { kind: 'link', href: 'https://example.org/tip', labelKey: 'Tip us' },+ });+ useSystemNoticeStore.setState({ notices: [notice], loaded: true });+ const dismissSpy = vi.spyOn(useSystemNoticeStore.getState(), 'dismiss');++ const { container } = render(<ModalRenderer notices={[notice]} />);+ await flushGraceDelay();++ const primary = screen.getByRole('button', { name: 'Support us' });+ expect(primary.className).toContain('bg-[#FFDD00]');+ // unbranded links get the generic coffee glyph, not a brand mark+ expect(container.querySelector('.lucide-coffee')).not.toBeNull();++ await act(async () => {+ fireEvent.click(primary);+ });+ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: 'Tip us' }));+ });++ expect(open).toHaveBeenNthCalledWith(1, 'https://example.com/support', '_blank', 'noopener,noreferrer');+ expect(open).toHaveBeenNthCalledWith(2, 'https://example.org/tip', '_blank', 'noopener,noreferrer');+ expect(dismissSpy).not.toHaveBeenCalled();+ });++ it('FE-SN-MODAL-028: Buy Me a Coffee and Ko-fi links carry their own brand mark', async () => {+ vi.spyOn(window, 'open').mockImplementation(() => null);+ const notice = makeNotice({+ id: 'brands',+ cta: { kind: 'link', href: 'https://buymeacoffee.com/trek', labelKey: 'Buy me a coffee' },+ secondaryCta: { kind: 'link', href: 'https://ko-fi.com/trek', labelKey: 'Ko-fi' },+ });+ render(<ModalRenderer notices={[notice]} />);+ await flushGraceDelay();++ const primary = document.getElementById('notice-cta-brands') as HTMLElement;+ const secondary = document.getElementById('notice-cta2-brands') as HTMLElement;++ expect((primary.querySelector('path') as SVGPathElement).getAttribute('d')).toContain('M20.216');+ expect(secondary.className).toContain('bg-[#FF5E5B]');+ expect((secondary.querySelector('path') as SVGPathElement).getAttribute('d')).toContain('M11.351');+ });++ it('FE-SN-MODAL-029: a "kofi" link without the ko-fi.com host still resolves to the Ko-fi mark', async () => {+ vi.spyOn(window, 'open').mockImplementation(() => null);+ const notice = makeNotice({+ id: 'kofi-alt',+ cta: { kind: 'link', href: 'https://kofi.example/trek', labelKey: 'Ko-fi' },+ });+ render(<ModalRenderer notices={[notice]} />);+ await flushGraceDelay();++ const primary = document.getElementById('notice-cta-kofi-alt') as HTMLElement;+ expect((primary.querySelector('path') as SVGPathElement).getAttribute('d')).toContain('M11.351');+ });++ it('FE-SN-MODAL-030: a nav CTA on a non-dismissible notice navigates without dismissing', async () => {+ const notice = makeNotice({+ dismissible: false,+ cta: { kind: 'nav', href: '/settings', labelKey: 'Open settings' },+ });+ useSystemNoticeStore.setState({ notices: [notice], loaded: true });+ const dismissSpy = vi.spyOn(useSystemNoticeStore.getState(), 'dismiss');++ render(<ModalRenderer notices={[notice]} />);+ await flushGraceDelay();++ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: 'Open settings' }));+ });++ expect(routerMocks.navigate).toHaveBeenCalledWith('/settings');+ expect(dismissSpy).not.toHaveBeenCalled();+ });++ it('FE-SN-MODAL-031: an action CTA runs the registered handler and dismisses by default', async () => {+ const handler = vi.fn(() => {});+ registerNoticeAction('modal-open-support', handler);+ const notice = makeNotice({+ cta: { kind: 'action', actionId: 'modal-open-support', labelKey: 'Run it' },+ });+ useSystemNoticeStore.setState({ notices: [notice], loaded: true });+ const dismissSpy = vi.spyOn(useSystemNoticeStore.getState(), 'dismiss');++ render(<ModalRenderer notices={[notice]} />);+ await flushGraceDelay();++ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: 'Run it' }));+ });++ expect(handler).toHaveBeenCalledWith({ navigate: routerMocks.navigate });+ expect(dismissSpy).toHaveBeenCalledWith('test-notice-1');+ });++ it('FE-SN-MODAL-032: a secondary action CTA can opt out of dismissing', async () => {+ const handler = vi.fn(() => {});+ registerNoticeAction('modal-stay-open', handler);+ const notice = makeNotice({+ id: 'secondary-action',+ cta: { kind: 'nav', href: '/trips', labelKey: 'Go' },+ secondaryCta: {+ kind: 'action',+ actionId: 'modal-stay-open',+ labelKey: 'Later',+ dismissOnAction: false,+ },+ });+ useSystemNoticeStore.setState({ notices: [notice], loaded: true });+ const dismissSpy = vi.spyOn(useSystemNoticeStore.getState(), 'dismiss');++ render(<ModalRenderer notices={[notice]} />);+ await flushGraceDelay();++ const secondary = document.getElementById('notice-cta2-secondary-action') as HTMLElement;+ expect(secondary.className).toContain('bg-blue-600');++ await act(async () => {+ fireEvent.click(secondary);+ });++ expect(handler).toHaveBeenCalledWith({ navigate: routerMocks.navigate });+ expect(dismissSpy).not.toHaveBeenCalled();+ });++ // ── Pager edge cases ───────────────────────────────────────────────────────++ it('FE-SN-MODAL-033: ArrowLeft on the first page stays put', async () => {+ const notices = [+ makeNotice({ id: 'n1', titleKey: 'Notice A' }),+ makeNotice({ id: 'n2', titleKey: 'Notice B' }),+ ];+ render(<ModalRenderer notices={notices} />);+ await flushGraceDelay();++ await act(async () => {+ fireEvent.keyDown(document, { key: 'ArrowLeft' });+ });++ expect(screen.getByText('1 / 2')).toBeTruthy();+ // unrelated keys are ignored outright+ await act(async () => {+ fireEvent.keyDown(document, { key: 'ArrowUp' });+ });+ expect(screen.getByText('1 / 2')).toBeTruthy();+ });++ it('FE-SN-MODAL-034: clicking the dot of the current page is a no-op', async () => {+ const notices = [+ makeNotice({ id: 'n1', titleKey: 'Notice A' }),+ makeNotice({ id: 'n2', titleKey: 'Notice B' }),+ ];+ render(<ModalRenderer notices={notices} />);+ await flushGraceDelay();++ await act(async () => {+ fireEvent.click(screen.getByLabelText('Go to notice 1'));+ });++ expect(screen.getByText('1 / 2')).toBeTruthy();+ expect(screen.getByText('Notice A')).toBeTruthy();+ });++ it('FE-SN-MODAL-035: a locked pager ignores its enabled current dot', async () => {+ const notices = [+ makeNotice({ id: 'n1', titleKey: 'Notice A', dismissible: false }),+ makeNotice({ id: 'n2', titleKey: 'Notice B' }),+ ];+ render(<ModalRenderer notices={notices} />);+ await flushGraceDelay();++ const currentDot = screen.getByLabelText('Go to notice 1') as HTMLButtonElement;+ expect(currentDot.disabled).toBe(false);+ expect(currentDot.getAttribute('aria-current')).toBe('true');++ await act(async () => {+ fireEvent.click(currentDot);+ });++ expect(screen.getByText('1 / 2')).toBeTruthy();+ });++ it('FE-SN-MODAL-036: jumping backwards announces the new position', async () => {+ const notices = [+ makeNotice({ id: 'n1', titleKey: 'Notice A' }),+ makeNotice({ id: 'n2', titleKey: 'Notice B' }),+ makeNotice({ id: 'n3', titleKey: 'Notice C' }),+ ];+ render(<ModalRenderer notices={notices} />);+ await flushGraceDelay();++ await act(async () => {+ fireEvent.click(screen.getByLabelText('Go to notice 3'));+ });+ await flushGraceDelay();+ await act(async () => {+ fireEvent.click(screen.getByLabelText('Go to notice 1'));+ });+ await flushGraceDelay();++ expect(screen.getByText('Notice A')).toBeTruthy();+ expect(screen.getByRole('status').textContent).toBe('Notice 1 of 3');+ });++ it('FE-SN-MODAL-037: the page index clamps when the notice list shrinks', async () => {+ const notices = [+ makeNotice({ id: 'n1', titleKey: 'Notice A' }),+ makeNotice({ id: 'n2', titleKey: 'Notice B' }),+ makeNotice({ id: 'n3', titleKey: 'Notice C' }),+ ];+ const { rerender } = render(<ModalRenderer notices={notices} />);+ await flushGraceDelay();++ await act(async () => {+ fireEvent.click(screen.getByLabelText('Go to notice 3'));+ });+ await flushGraceDelay();+ expect(screen.getByText('Notice C')).toBeTruthy();++ await act(async () => {+ rerender(<ModalRenderer notices={[notices[0]]} />);+ });+ await flushGraceDelay();++ expect(screen.getByText('Notice A')).toBeTruthy();+ expect(screen.queryByText('Notice C')).toBeNull();+ });++ it('FE-SN-MODAL-038: the page slide clears its inline transform once the transition ends', async () => {+ const notices = [+ makeNotice({ id: 'n1', titleKey: 'Notice A' }),+ makeNotice({ id: 'n2', titleKey: 'Notice B' }),+ ];+ render(<ModalRenderer notices={notices} />);+ await flushGraceDelay();++ const wrapper = screen.getByRole('dialog').firstElementChild as HTMLElement;++ await act(async () => {+ fireEvent.click(screen.getByLabelText('Next notice'));+ });+ await flushGraceDelay();++ expect(wrapper.style.transition).toContain('260ms');+ expect(wrapper.style.transform).not.toBe('');++ await act(async () => {+ fireEvent.transitionEnd(wrapper);+ });++ expect(wrapper.style.transition).toBe('');+ expect(wrapper.style.transform).toBe('');+ });++ it('FE-SN-MODAL-039: RTL layouts mirror the arrow keys', async () => {+ i18nEnv.rtl = true;+ const notices = [+ makeNotice({ id: 'n1', titleKey: 'Notice A' }),+ makeNotice({ id: 'n2', titleKey: 'Notice B' }),+ ];+ render(<ModalRenderer notices={notices} />);+ await flushGraceDelay();++ await act(async () => {+ fireEvent.keyDown(document, { key: 'ArrowLeft' });+ });+ await flushGraceDelay();++ expect(screen.getByText('Notice B')).toBeTruthy();+ });++ // ── Environment ────────────────────────────────────────────────────────────++ it('FE-SN-MODAL-040: reduced motion swaps to the short fade and skips the slide transform', async () => {+ stubMatchMedia({ reducedMotion: true });+ const notices = [+ makeNotice({ id: 'n1', titleKey: 'Notice A' }),+ makeNotice({ id: 'n2', titleKey: 'Notice B' }),+ ];+ render(<ModalRenderer notices={notices} />);++ const dialog = screen.getByRole('dialog');+ expect(dialog.className).toContain('duration-[120ms]');+ expect(dialog.className).toContain('opacity-0');+ expect(dialog.className).not.toContain('scale-[0.97]');++ await flushGraceDelay();+ expect(screen.getByRole('dialog').className).toContain('opacity-100');++ const wrapper = screen.getByRole('dialog').firstElementChild as HTMLElement;+ await act(async () => {+ fireEvent.click(screen.getByLabelText('Next notice'));+ });+ await flushGraceDelay();++ expect(screen.getByText('Notice B')).toBeTruthy();+ expect(wrapper.style.transform).toBe('');+ });++ it('FE-SN-MODAL-041: a browser without matchMedia still renders the desktop modal', async () => {+ (window as unknown as { matchMedia?: unknown }).matchMedia = undefined;+ render(<ModalRenderer notices={[makeNotice()]} />);+ await flushGraceDelay();++ expect(screen.getByRole('dialog').className).toContain('rounded-2xl');+ expect(screen.getByText('Test Title')).toBeTruthy();+ });++ it('FE-SN-MODAL-042: without requestAnimationFrame the grace delay falls back to timeouts', async () => {+ Reflect.deleteProperty(globalThis, 'requestAnimationFrame');+ render(<ModalRenderer notices={[makeNotice()]} />);++ expect(screen.getByRole('dialog').className).toContain('opacity-0');+ await flushGraceDelay();++ expect(screen.getByRole('dialog').className).toContain('opacity-100');+ });++ it('FE-SN-MODAL-043: a viewport change swaps the desktop modal for the bottom sheet', async () => {+ stubMatchMedia({ mobile: false });+ render(<ModalRenderer notices={[makeNotice()]} />);+ await flushGraceDelay();++ expect(screen.getByRole('dialog').className).toContain('rounded-2xl');++ await act(async () => {+ mqChangeListeners.forEach(cb => cb({ matches: true } as MediaQueryListEvent));+ });++ expect(screen.getByRole('dialog').className).toContain('rounded-t-3xl');+ });++ // ── Mobile bottom sheet ────────────────────────────────────────────────────++ it('FE-SN-MODAL-044: the sheet keeps the neighbouring notices in its side slots', async () => {+ stubMatchMedia({ mobile: true });+ const notices = [+ makeNotice({ id: 'n1', titleKey: 'Notice A' }),+ makeNotice({ id: 'n2', titleKey: 'Notice B' }),+ makeNotice({ id: 'n3', titleKey: 'Notice C' }),+ ];+ render(<ModalRenderer notices={notices} />);+ await flushGraceDelay();++ const { prevSlot, centerSlot, nextSlot } = sheetParts();+ expect(prevSlot.textContent).toBe('');+ expect(centerSlot.textContent).toContain('Notice A');+ expect(nextSlot.textContent).toContain('Notice B');+ });++ it('FE-SN-MODAL-045: tapping the backdrop animates the sheet out before dismissing', async () => {+ stubMatchMedia({ mobile: true });+ const noticeA = makeNotice({ id: 'n-a', titleKey: 'Notice A' });+ const noticeB = makeNotice({ id: 'n-b', titleKey: 'Notice B' });+ useSystemNoticeStore.setState({ notices: [noticeA, noticeB], loaded: true });+ const dismissSpy = vi.spyOn(useSystemNoticeStore.getState(), 'dismiss');++ render(<ModalRenderer notices={[noticeA, noticeB]} />);+ await flushGraceDelay();++ const backdrop = screen.getByRole('presentation').children[1] as HTMLElement;+ await act(async () => {+ fireEvent.click(backdrop);+ });++ const { sheet } = sheetParts();+ expect(sheet.style.transform).toBe('translateY(110%)');+ expect(dismissSpy).not.toHaveBeenCalled();++ await act(async () => {+ fireEvent.transitionEnd(sheet);+ });++ expect(dismissSpy).toHaveBeenCalledWith('n-a');+ expect(dismissSpy).toHaveBeenCalledWith('n-b');+ });++ it('FE-SN-MODAL-046: with reduced motion the backdrop tap dismisses straight away', async () => {+ stubMatchMedia({ mobile: true, reducedMotion: true });+ const notice = makeNotice({ id: 'n-a' });+ useSystemNoticeStore.setState({ notices: [notice], loaded: true });+ const dismissSpy = vi.spyOn(useSystemNoticeStore.getState(), 'dismiss');++ render(<ModalRenderer notices={[notice]} />);+ await flushGraceDelay();++ expect(screen.getByRole('dialog').className).toContain('opacity-100');++ await act(async () => {+ fireEvent.click(screen.getByRole('presentation').children[1] as HTMLElement);+ });++ expect(dismissSpy).toHaveBeenCalledWith('n-a');+ });++ it('FE-SN-MODAL-047: horizontal swipes page forward and back', async () => {+ stubMatchMedia({ mobile: true });+ const notices = [+ makeNotice({ id: 'n1', titleKey: 'Notice A' }),+ makeNotice({ id: 'n2', titleKey: 'Notice B' }),+ makeNotice({ id: 'n3', titleKey: 'Notice C' }),+ ];+ render(<ModalRenderer notices={notices} />);+ await flushGraceDelay();++ const { sheet, strip } = sheetParts();++ await act(async () => {+ swipeHorizontally(sheet, 250, 120);+ });+ expect(strip.style.transform).toBe('translateX(-66.666%)');++ await act(async () => {+ fireEvent.transitionEnd(strip);+ });+ await flushGraceDelay();++ expect(sheetParts().centerSlot.textContent).toContain('Notice B');+ expect(sheetParts().prevSlot.textContent).toContain('Notice A');+ expect(strip.style.transform).toBe('translateX(-33.333%)');++ await act(async () => {+ swipeHorizontally(sheet, 120, 250);+ });+ expect(strip.style.transform).toBe('translateX(0%)');++ await act(async () => {+ fireEvent.transitionEnd(strip);+ });+ await flushGraceDelay();++ expect(sheetParts().centerSlot.textContent).toContain('Notice A');+ });++ it('FE-SN-MODAL-048: a swipe short of the threshold springs back to the current page', async () => {+ stubMatchMedia({ mobile: true });+ const notices = [+ makeNotice({ id: 'n1', titleKey: 'Notice A' }),+ makeNotice({ id: 'n2', titleKey: 'Notice B' }),+ ];+ render(<ModalRenderer notices={notices} />);+ await flushGraceDelay();++ const { sheet, strip } = sheetParts();++ await act(async () => {+ swipeHorizontally(sheet, 200, 180);+ });+ expect(strip.style.transform).toBe('translateX(-33.333%)');++ await act(async () => {+ fireEvent.transitionEnd(strip);+ });++ expect(strip.style.transition).toBe('');+ expect(sheetParts().centerSlot.textContent).toContain('Notice A');++ // a move without a preceding touchstart is ignored+ await act(async () => {+ fireEvent.touchMove(sheet, { touches: [{ clientX: 40, clientY: 200 }] });+ });+ expect(sheetParts().centerSlot.textContent).toContain('Notice A');+ });++ it('FE-SN-MODAL-049: RTL swipes are mirrored', async () => {+ i18nEnv.rtl = true;+ stubMatchMedia({ mobile: true });+ const notices = [+ makeNotice({ id: 'n1', titleKey: 'Notice A' }),+ makeNotice({ id: 'n2', titleKey: 'Notice B' }),+ ];+ render(<ModalRenderer notices={notices} />);+ await flushGraceDelay();++ const { sheet, strip } = sheetParts();+ await act(async () => {+ swipeHorizontally(sheet, 120, 250);+ });+ expect(strip.style.transform).toBe('translateX(-66.666%)');++ await act(async () => {+ fireEvent.transitionEnd(strip);+ });+ await flushGraceDelay();++ expect(sheetParts().centerSlot.textContent).toContain('Notice B');+ });++ it('FE-SN-MODAL-050: dragging the sheet down past the threshold dismisses it', async () => {+ stubMatchMedia({ mobile: true });+ const notice = makeNotice({ id: 'n-a' });+ useSystemNoticeStore.setState({ notices: [notice], loaded: true });+ const dismissSpy = vi.spyOn(useSystemNoticeStore.getState(), 'dismiss');++ render(<ModalRenderer notices={[notice]} />);+ await flushGraceDelay();++ const { sheet } = sheetParts();+ await act(async () => {+ dragVertically(sheet, 100, 220);+ });++ expect(sheet.style.transform).toBe('translateY(110%)');++ await act(async () => {+ fireEvent.transitionEnd(sheet);+ });++ expect(dismissSpy).toHaveBeenCalledWith('n-a');+ });++ it('FE-SN-MODAL-051: a short downward drag springs the sheet back', async () => {+ stubMatchMedia({ mobile: true });+ const notice = makeNotice({ id: 'n-a' });+ useSystemNoticeStore.setState({ notices: [notice], loaded: true });+ const dismissSpy = vi.spyOn(useSystemNoticeStore.getState(), 'dismiss');++ render(<ModalRenderer notices={[notice]} />);+ await flushGraceDelay();++ const { sheet } = sheetParts();+ await act(async () => {+ dragVertically(sheet, 100, 140);+ });++ expect(sheet.style.transform).toBe('translateY(0)');++ await act(async () => {+ fireEvent.transitionEnd(sheet);+ });++ expect(sheet.style.transform).toBe('');+ expect(sheet.style.transition).toBe('');+ expect(dismissSpy).not.toHaveBeenCalled();+ });++ it('FE-SN-MODAL-052: an upward drag never moves the sheet', async () => {+ stubMatchMedia({ mobile: true });+ const notice = makeNotice({ id: 'n-a' });+ useSystemNoticeStore.setState({ notices: [notice], loaded: true });+ const dismissSpy = vi.spyOn(useSystemNoticeStore.getState(), 'dismiss');++ render(<ModalRenderer notices={[notice]} />);+ await flushGraceDelay();++ const { sheet } = sheetParts();+ await act(async () => {+ dragVertically(sheet, 220, 100);+ });++ expect(sheet.style.transform).toBe('');+ expect(dismissSpy).not.toHaveBeenCalled();+ });++ it('FE-SN-MODAL-053: a sheet scrolled into its content does not drag away', async () => {+ stubMatchMedia({ mobile: true });+ const notice = makeNotice({ id: 'n-a' });+ useSystemNoticeStore.setState({ notices: [notice], loaded: true });+ const dismissSpy = vi.spyOn(useSystemNoticeStore.getState(), 'dismiss');++ render(<ModalRenderer notices={[notice]} />);+ await flushGraceDelay();++ const { sheet, centerSlot } = sheetParts();+ Object.defineProperty(centerSlot, 'scrollTop', { configurable: true, value: 150 });++ await act(async () => {+ dragVertically(sheet, 100, 260);+ });++ expect(sheet.style.transform).toBe('');+ expect(dismissSpy).not.toHaveBeenCalled();+ });++ it('FE-SN-MODAL-054: reduced motion disables sheet dragging entirely', async () => {+ stubMatchMedia({ mobile: true, reducedMotion: true });+ const notice = makeNotice({ id: 'n-a' });+ useSystemNoticeStore.setState({ notices: [notice], loaded: true });+ const dismissSpy = vi.spyOn(useSystemNoticeStore.getState(), 'dismiss');++ render(<ModalRenderer notices={[notice]} />);+ await flushGraceDelay();++ const { sheet } = sheetParts();+ await act(async () => {+ dragVertically(sheet, 100, 260);+ });++ expect(sheet.style.transform).toBe('');+ expect(dismissSpy).not.toHaveBeenCalled();+ });++ it('FE-SN-MODAL-055: a non-dismissible sheet ignores the backdrop tap and the drag', async () => {+ stubMatchMedia({ mobile: true });+ const notice = makeNotice({ id: 'n-a', dismissible: false });+ useSystemNoticeStore.setState({ notices: [notice], loaded: true });+ const dismissSpy = vi.spyOn(useSystemNoticeStore.getState(), 'dismiss');++ render(<ModalRenderer notices={[notice]} />);+ await flushGraceDelay();++ await act(async () => {+ fireEvent.click(screen.getByRole('presentation').children[1] as HTMLElement);+ });+ expect(dismissSpy).not.toHaveBeenCalled();++ const { sheet } = sheetParts();+ await act(async () => {+ dragVertically(sheet, 100, 260);+ });++ expect(dismissSpy).not.toHaveBeenCalled();+ });++ it('FE-SN-MODAL-056: pager buttons of the side slots cannot page past the ends', async () => {+ stubMatchMedia({ mobile: true });+ const notices = [+ makeNotice({ id: 'n1', titleKey: 'Notice A' }),+ makeNotice({ id: 'n2', titleKey: 'Notice B' }),+ makeNotice({ id: 'n3', titleKey: 'Notice C' }),+ ];+ render(<ModalRenderer notices={notices} />);+ await flushGraceDelay();++ // the next slot renders page 2's pager, whose "previous" button is enabled —+ // pressing it must not move the sheet below the first page+ const prevButtons = screen.getAllByLabelText('Previous notice') as HTMLButtonElement[];+ const enabledPrev = prevButtons.find(b => !b.disabled) as HTMLButtonElement;+ await act(async () => {+ fireEvent.click(enabledPrev);+ });+ await flushGraceDelay();+ expect(sheetParts().centerSlot.textContent).toContain('Notice A');++ // walk to the last page, then press the previous slot's enabled "next"+ await act(async () => {+ fireEvent.keyDown(document, { key: 'ArrowRight' });+ });+ await flushGraceDelay();+ await act(async () => {+ fireEvent.keyDown(document, { key: 'ArrowRight' });+ });+ await flushGraceDelay();+ expect(sheetParts().centerSlot.textContent).toContain('Notice C');++ const nextButtons = screen.getAllByLabelText('Next notice') as HTMLButtonElement[];+ const enabledNext = nextButtons.find(b => !b.disabled) as HTMLButtonElement;+ await act(async () => {+ fireEvent.click(enabledNext);+ });+ await flushGraceDelay();++ expect(sheetParts().centerSlot.textContent).toContain('Notice C');+ });});diff --git a/client/src/components/SystemNotices/noticeActions.test.ts b/client/src/components/SystemNotices/noticeActions.test.tsnew file mode 100644index 000000000..75259a876--- /dev/null+++ b/client/src/components/SystemNotices/noticeActions.test.ts@@ -0,0 +1,65 @@+// FE-W4SNA-001 to FE-W4SNA-005+import { describe, it, expect, vi, afterEach } from 'vitest'+import type { NavigateFunction } from 'react-router-dom'+import { registerNoticeAction, runNoticeAction } from './noticeActions'++const navigate = vi.fn() as unknown as NavigateFunction+const ctx = { navigate }++afterEach(() => {+ vi.restoreAllMocks()+})++describe('noticeActions', () => {+ it('FE-W4SNA-001: runs a registered handler with the navigate context', () => {+ const handler = vi.fn(() => {})+ registerNoticeAction('open-settings', handler)++ runNoticeAction('open-settings', ctx)++ expect(handler).toHaveBeenCalledWith(ctx)+ })++ it('FE-W4SNA-002: logs and does nothing for an unknown id', () => {+ const err = vi.spyOn(console, 'error').mockImplementation(() => {})++ expect(() => runNoticeAction('never-registered', ctx)).not.toThrow()+ expect(err).toHaveBeenCalledTimes(1)+ expect(String(err.mock.calls[0][0])).toContain('never-registered')+ })++ it('FE-W4SNA-003: a later registration replaces the handler for the same id', () => {+ const first = vi.fn(() => {})+ const second = vi.fn(() => {})+ registerNoticeAction('dup', first)+ registerNoticeAction('dup', second)++ runNoticeAction('dup', ctx)++ expect(first).not.toHaveBeenCalled()+ expect(second).toHaveBeenCalledOnce()+ })++ it('FE-W4SNA-004: fires an async handler without blocking the caller', async () => {+ let resolved = false+ registerNoticeAction('async-cta', async () => {+ await Promise.resolve()+ resolved = true+ })++ expect(runNoticeAction('async-cta', ctx)).toBeUndefined()+ expect(resolved).toBe(false)++ await Promise.resolve()+ await Promise.resolve()+ expect(resolved).toBe(true)+ })++ it('FE-W4SNA-005: hands the real navigate through to the handler', () => {+ registerNoticeAction('go-billing', c => { c.navigate('/settings/billing') })++ runNoticeAction('go-billing', ctx)++ expect(navigate).toHaveBeenCalledWith('/settings/billing')+ })+})diff --git a/client/src/components/Todo/TodoListPanel.test.tsx b/client/src/components/Todo/TodoListPanel.test.tsxindex 5b7dbe561..ba73f28b4 100644--- a/client/src/components/Todo/TodoListPanel.test.tsx+++ b/client/src/components/Todo/TodoListPanel.test.tsx@@ -1,10 +1,11 @@-// FE-COMP-TODO-001 to FE-COMP-TODO-015-import { render, screen, waitFor, fireEvent } from '../../../tests/helpers/render';+// FE-COMP-TODO-001 to FE-COMP-TODO-052+import { render, screen, waitFor, fireEvent, within } from '../../../tests/helpers/render';import userEvent from '@testing-library/user-event';import { http, HttpResponse } from 'msw';import { server } from '../../../tests/helpers/msw/server';import { useAuthStore } from '../../store/authStore';import { useTripStore } from '../../store/tripStore';+import { usePermissionsStore } from '../../store/permissionsStore';import { resetAllStores, seedStore } from '../../../tests/helpers/store';import { buildUser, buildTrip, buildTodoItem } from '../../../tests/helpers/factories';import TodoListPanel from './TodoListPanel';@@ -417,3 +418,829 @@ describe('TodoListPanel', () => {expect(screen.getByText('This is a task description')).toBeInTheDocument();});});++// ── Members served to the detail/new panes (owner + a member + a guest) ────────+const MEMBERS_RESPONSE = {+ owner: { id: 1, username: 'alice', avatar: null },+ members: [+ { id: 2, username: 'bob', avatar: 'bob.png' },+ { id: 3, username: 'gus', avatar: null, is_guest: true },+ ],+ current_user_id: 1,+};++function withMembers() {+ server.use(http.get('/api/trips/:id/members', () => HttpResponse.json(MEMBERS_RESPONSE)));+}++function dragOverRow(row: Element) {+ fireEvent.dragOver(row, { dataTransfer: { dropEffect: '' } });+}++/** Pick an option out of the CustomSelect dropdown, which renders into a body portal. */+function pickOption(label: string | RegExp) {+ const dropdown = document.querySelector('div[style*="z-index: 99999"]') as HTMLElement;+ fireEvent.click(within(dropdown).getByRole('button', { name: label }));+}++/**+ * The sidebar filters are an inline component, so every re-render (the members+ * fetch resolving, for one) swaps the button element. userEvent's async steps can+ * land on the detached node — fireEvent stays atomic.+ */+function clickFilter(name: RegExp | string) {+ fireEvent.click(screen.getByRole('button', { name }));+}++describe('TodoListPanel — sidebar', () => {+ it('FE-COMP-TODO-030: hovering an inactive filter highlights it and leaving clears it', () => {+ render(<TodoListPanel tripId={1} items={[]} />);+ const done = screen.getByRole('button', { name: /^Done/ });++ fireEvent.mouseEnter(done);+ expect(done.style.background).toBe('var(--bg-hover)');+ fireEvent.mouseLeave(done);+ expect(done.style.background).toBe('transparent');+ });++ it('FE-COMP-TODO-031: the active filter keeps its highlight on mouse-out', () => {+ render(<TodoListPanel tripId={1} items={[]} />);+ const all = screen.getByRole('button', { name: /^All/ });++ fireEvent.mouseLeave(all);+ // 'all' is the active filter, so the hover handlers must leave it alone.+ expect(all.style.background).toBe('var(--bg-hover)');+ });++ it('FE-COMP-TODO-032: hovering the priority sort toggles its background only while off', async () => {+ const user = userEvent.setup();+ render(<TodoListPanel tripId={1} items={[]} />);+ const sort = screen.getByRole('button', { name: 'Priority' });++ fireEvent.mouseEnter(sort);+ expect(sort.style.background).toBe('var(--bg-hover)');+ fireEvent.mouseLeave(sort);+ expect(sort.style.background).toBe('transparent');++ await user.click(sort);+ fireEvent.mouseEnter(sort);+ // Active sort keeps its amber tint instead of the neutral hover.+ expect(sort.style.background).toBe('rgba(245, 158, 11, 0.07)');+ });++ it('FE-COMP-TODO-033: Escape abandons the new-list input', async () => {+ const user = userEvent.setup();+ render(<TodoListPanel tripId={1} items={[]} />);++ await user.click(screen.getByRole('button', { name: 'Add list' }));+ const input = await screen.findByPlaceholderText('List name');+ await user.type(input, 'Errands');+ await user.keyboard('{Escape}');++ expect(screen.queryByPlaceholderText('List name')).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Add list' })).toBeInTheDocument();+ });++ it('FE-COMP-TODO-034: confirming a list that already exists just closes the input', async () => {+ const user = userEvent.setup();+ let posted = false;+ server.use(http.post('/api/trips/1/todo', () => { posted = true; return HttpResponse.json({ item: buildTodoItem() }); }));+ render(<TodoListPanel tripId={1} items={[buildTodoItem({ name: 'Task', category: 'Errands', checked: 0 })]} />);++ await user.click(screen.getByRole('button', { name: 'Add list' }));+ const input = await screen.findByPlaceholderText('List name');+ await user.type(input, 'Errands');+ fireEvent.click(input.nextElementSibling as HTMLElement);++ expect(posted).toBe(false);+ expect(screen.queryByPlaceholderText('List name')).not.toBeInTheDocument();+ });++ it('FE-COMP-TODO-035: without edit rights the list cannot be extended', () => {+ seedStore(usePermissionsStore, { permissions: { packing_edit: 'admin' } });+ render(<TodoListPanel tripId={1} items={[buildTodoItem({ name: 'Task', checked: 0 })]} />);++ expect(screen.queryByRole('button', { name: 'Add list' })).not.toBeInTheDocument();+ });++ it('FE-COMP-TODO-036: selecting a list filter titles the pane with the list name', () => {+ render(<TodoListPanel tripId={1} items={[buildTodoItem({ name: 'Task', category: 'Errands', checked: 0 })]} />);++ clickFilter(/Errands/);++ expect(screen.getByRole('heading', { name: 'Errands' })).toBeInTheDocument();+ });+});++describe('TodoListPanel — drag to reorder', () => {+ const rows = () => Array.from(document.querySelectorAll('[draggable="true"]')).map(h => h.parentElement!);++ it('FE-COMP-TODO-037: dropping a task onto another persists the new global order', async () => {+ let ordered: number[] | null = null;+ server.use(+ http.put('/api/trips/1/todo/reorder', async ({ request }) => {+ ordered = ((await request.json()) as { orderedIds: number[] }).orderedIds;+ return HttpResponse.json({ success: true });+ }),+ );+ const items = [+ buildTodoItem({ id: 1, name: 'First', checked: 0 }),+ buildTodoItem({ id: 2, name: 'Second', checked: 0 }),+ buildTodoItem({ id: 3, name: 'Done one', checked: 1 }),+ buildTodoItem({ id: 4, name: 'Third', checked: 0 }),+ ];+ render(<TodoListPanel tripId={1} items={items} />);++ const [first, , third] = rows();+ fireEvent.dragStart(document.querySelectorAll('[draggable="true"]')[0], { dataTransfer: { effectAllowed: '' } });+ dragOverRow(third);+ fireEvent.drop(third);++ // The checked task is filtered out of the view but keeps its slot in the payload.+ await waitFor(() => expect(ordered).toEqual([2, 4, 3, 1]));+ expect(first).toBeTruthy();+ });++ it('FE-COMP-TODO-038: dropping a task on itself changes nothing', async () => {+ let called = false;+ server.use(http.put('/api/trips/1/todo/reorder', () => { called = true; return HttpResponse.json({ success: true }); }));+ const items = [buildTodoItem({ id: 1, name: 'First', checked: 0 }), buildTodoItem({ id: 2, name: 'Second', checked: 0 })];+ render(<TodoListPanel tripId={1} items={items} />);++ const handles = document.querySelectorAll('[draggable="true"]');+ fireEvent.dragStart(handles[0], { dataTransfer: { effectAllowed: '' } });+ fireEvent.drop(handles[0].parentElement!);++ expect(called).toBe(false);+ });++ it('FE-COMP-TODO-039: ending a drag without a drop clears the drag state', () => {+ const items = [buildTodoItem({ id: 1, name: 'First', checked: 0 }), buildTodoItem({ id: 2, name: 'Second', checked: 0 })];+ render(<TodoListPanel tripId={1} items={items} />);++ const handles = document.querySelectorAll('[draggable="true"]');+ fireEvent.dragStart(handles[0], { dataTransfer: { effectAllowed: '' } });+ dragOverRow(handles[1].parentElement!);+ expect((handles[0].parentElement as HTMLElement).style.opacity).toBe('0.4');+ expect((handles[1].parentElement as HTMLElement).style.boxShadow).toBe('inset 3px 0 0 0 var(--accent)');++ fireEvent.dragEnd(handles[0]);+ expect((handles[0].parentElement as HTMLElement).style.opacity).toBe('1');+ expect((handles[1].parentElement as HTMLElement).style.boxShadow).toBe('none');+ });++ it('FE-COMP-TODO-040: sorting by priority disables the drag handles', async () => {+ const user = userEvent.setup();+ render(<TodoListPanel tripId={1} items={[buildTodoItem({ id: 1, name: 'First', checked: 0 })]} />);+ expect(document.querySelectorAll('[draggable="true"]')).toHaveLength(1);++ await user.click(screen.getByRole('button', { name: 'Priority' }));++ expect(document.querySelectorAll('[draggable="true"]')).toHaveLength(0);+ });+});++describe('TodoListPanel — detail pane', () => {+ const openDetail = async (user: ReturnType<typeof userEvent.setup>, item = buildTodoItem({ id: 40, name: 'Plan route', checked: 0 })) => {+ render(<TodoListPanel tripId={1} items={[item]} />);+ await user.click(screen.getByText(item.name));+ await screen.findByText('Task');+ };++ it('FE-COMP-TODO-041: description, priority and due date are saved together', async () => {+ const user = userEvent.setup();+ withMembers();+ let put: Record<string, unknown> | null = null;+ server.use(+ http.put('/api/trips/1/todo/40', async ({ request }) => {+ put = (await request.json()) as Record<string, unknown>;+ return HttpResponse.json({ item: buildTodoItem({ id: 40, name: 'Plan route' }) });+ }),+ );+ await openDetail(user);++ await user.type(screen.getByPlaceholderText('Description (optional)'), 'via the coast');+ await user.click(screen.getByRole('button', { name: 'P2' }));+ await user.click(screen.getByRole('button', { name: 'Date' }));+ await user.click(screen.getAllByRole('button').find(b => b.textContent?.trim() === '12')!);+ await user.click(screen.getByRole('button', { name: 'Save changes' }));++ await waitFor(() => expect(put).toBeTruthy());+ expect(put!.description).toBe('via the coast');+ expect(put!.priority).toBe(2);+ expect(String(put!.due_date)).toMatch(/^\d{4}-\d{2}-12$/);+ });++ it('FE-COMP-TODO-042: the + button swaps the list select for a free-text field', async () => {+ const user = userEvent.setup();+ withMembers();+ let put: Record<string, unknown> | null = null;+ server.use(+ http.put('/api/trips/1/todo/40', async ({ request }) => {+ put = (await request.json()) as Record<string, unknown>;+ return HttpResponse.json({ item: buildTodoItem({ id: 40, name: 'Plan route' }) });+ }),+ );+ await openDetail(user);++ await user.click(screen.getByRole('button', { name: 'List name' }));+ await user.type(await screen.findByPlaceholderText('List name'), 'Logistics');+ await user.keyboard('{Enter}');++ // Enter closes the inline editor and the typed list is offered as a new option.+ expect(screen.queryByPlaceholderText('List name')).not.toBeInTheDocument();+ expect(screen.getByText(/^Logistics/)).toBeInTheDocument();++ await user.click(screen.getByRole('button', { name: 'Save changes' }));+ await waitFor(() => expect(put).toBeTruthy());+ expect(put!.category).toBe('Logistics');+ });++ it('FE-COMP-TODO-043: Escape in the inline list editor clears the typed list', async () => {+ const user = userEvent.setup();+ withMembers();+ await openDetail(user);++ await user.click(screen.getByRole('button', { name: 'List name' }));+ await user.type(await screen.findByPlaceholderText('List name'), 'Logistics');+ await user.keyboard('{Escape}');++ expect(screen.queryByPlaceholderText('List name')).not.toBeInTheDocument();+ expect(screen.queryByText('Logistics')).not.toBeInTheDocument();+ // Nothing changed, so saving stays disabled.+ expect(screen.getByRole('button', { name: 'Save changes' })).toBeDisabled();+ });++ it('FE-COMP-TODO-044: picking an existing list from the dropdown marks the task changed', async () => {+ const user = userEvent.setup();+ withMembers();+ render(<TodoListPanel tripId={1} items={[+ buildTodoItem({ id: 40, name: 'Plan route', checked: 0 }),+ buildTodoItem({ id: 41, name: 'Other', category: 'Errands', checked: 0 }),+ ]} />);+ await user.click(screen.getByText('Plan route'));+ await screen.findByText('Task');++ const pane = screen.getByText('Task').closest('div[style*="border-left"]') as HTMLElement;+ await user.click(within(pane).getByRole('button', { name: 'No list' }));+ pickOption('Errands');++ expect(screen.getByRole('button', { name: 'Save changes' })).not.toBeDisabled();+ });++ it('FE-COMP-TODO-045: a guest assignee is labelled as a guest and persisted', async () => {+ const user = userEvent.setup();+ withMembers();+ let put: Record<string, unknown> | null = null;+ server.use(+ http.put('/api/trips/1/todo/40', async ({ request }) => {+ put = (await request.json()) as Record<string, unknown>;+ return HttpResponse.json({ item: buildTodoItem({ id: 40, name: 'Plan route' }) });+ }),+ );+ await openDetail(user);+ await screen.findByRole('button', { name: 'Unassigned' });++ await user.click(screen.getByRole('button', { name: 'Unassigned' }));+ await user.click(await screen.findByRole('button', { name: /gus · Guest/ }));+ await user.click(screen.getByRole('button', { name: 'Save changes' }));++ await waitFor(() => expect(put).toBeTruthy());+ expect(put!.assigned_user_id).toBe(3);+ });++ it('FE-COMP-TODO-046: a failing save surfaces the error as a toast', async () => {+ const user = userEvent.setup();+ const addToast = vi.fn();+ window.__addToast = addToast as unknown as typeof window.__addToast;+ server.use(http.put('/api/trips/1/todo/40', () => HttpResponse.json({ error: 'Nope' }, { status: 500 })));+ await openDetail(user);++ const nameInput = screen.getByDisplayValue('Plan route');+ await user.clear(nameInput);+ await user.type(nameInput, 'Renamed');+ await user.click(screen.getByRole('button', { name: 'Save changes' }));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Nope', 'error', undefined));+ delete window.__addToast;+ });++ it('FE-COMP-TODO-047: a failing delete surfaces the error and keeps the pane open', async () => {+ const user = userEvent.setup();+ const addToast = vi.fn();+ window.__addToast = addToast as unknown as typeof window.__addToast;+ server.use(http.delete('/api/trips/1/todo/40', () => HttpResponse.json({ error: 'Locked' }, { status: 409 })));+ await openDetail(user);++ await user.click(screen.getByRole('button', { name: 'Delete' }));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Locked', 'error', undefined));+ expect(screen.getByRole('button', { name: 'Save changes' })).toBeInTheDocument();+ delete window.__addToast;+ });++ it('FE-COMP-TODO-048: a read-only viewer gets no save or delete actions', async () => {+ const user = userEvent.setup();+ seedStore(usePermissionsStore, { permissions: { packing_edit: 'admin' } });+ await openDetail(user);++ expect(screen.queryByRole('button', { name: 'Save changes' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Delete' })).not.toBeInTheDocument();+ expect(screen.getByDisplayValue('Plan route')).toBeDisabled();+ });++ it('FE-COMP-TODO-049: switching the selected task reloads the pane fields', async () => {+ const user = userEvent.setup();+ withMembers();+ render(<TodoListPanel tripId={1} items={[+ buildTodoItem({ id: 40, name: 'Plan route', description: 'coast', checked: 0 }),+ buildTodoItem({ id: 41, name: 'Book ferry', description: null, checked: 0 }),+ ]} />);++ await user.click(screen.getByText('Plan route'));+ expect(await screen.findByDisplayValue('coast')).toBeInTheDocument();++ await user.click(screen.getByText('Book ferry'));+ await waitFor(() => expect(screen.queryByDisplayValue('coast')).not.toBeInTheDocument());+ expect(screen.getByDisplayValue('Book ferry')).toBeInTheDocument();+ });+});++describe('TodoListPanel — new task pane', () => {+ const openNew = async (items = [] as ReturnType<typeof buildTodoItem>[]) => {+ const { rerender } = render(<TodoListPanel tripId={1} items={items} addItemSignal={0} />);+ rerender(<TodoListPanel tripId={1} items={items} addItemSignal={1} />);+ await screen.findByText('Create task');+ return rerender;+ };++ it('FE-COMP-TODO-050: Enter in the name field creates the task', async () => {+ const user = userEvent.setup();+ let posted: Record<string, unknown> | null = null;+ server.use(+ http.post('/api/trips/1/todo', async ({ request }) => {+ posted = (await request.json()) as Record<string, unknown>;+ return HttpResponse.json({ item: buildTodoItem({ id: 77, name: 'Pack bags' }) });+ }),+ );+ await openNew();++ await user.type(screen.getByPlaceholderText('Task name'), 'Pack bags{Enter}');++ await waitFor(() => expect(posted).toBeTruthy());+ expect(posted!.name).toBe('Pack bags');+ // A created task closes the pane and becomes the selection.+ await waitFor(() => expect(screen.queryByText('Create task')).not.toBeInTheDocument());+ });++ it('FE-COMP-TODO-051: an empty name neither posts nor enables the button', async () => {+ const user = userEvent.setup();+ let posted = false;+ server.use(http.post('/api/trips/1/todo', () => { posted = true; return HttpResponse.json({ item: buildTodoItem() }); }));+ await openNew();++ await user.type(screen.getByPlaceholderText('Task name'), '{Enter}');++ expect(screen.getByRole('button', { name: 'Create task' })).toBeDisabled();+ expect(posted).toBe(false);+ });++ it('FE-COMP-TODO-052: description, list, priority, due date and assignee are all posted', async () => {+ const user = userEvent.setup();+ withMembers();+ let posted: Record<string, unknown> | null = null;+ server.use(+ http.post('/api/trips/1/todo', async ({ request }) => {+ posted = (await request.json()) as Record<string, unknown>;+ return HttpResponse.json({ item: buildTodoItem({ id: 78, name: 'Pack bags' }) });+ }),+ );+ await openNew();+ await screen.findByRole('button', { name: 'Unassigned' });++ await user.type(screen.getByPlaceholderText('Task name'), 'Pack bags');+ await user.type(screen.getByPlaceholderText('Description (optional)'), 'rain gear');+ await user.click(screen.getByRole('button', { name: 'List name' }));+ await user.type(await screen.findByPlaceholderText('List name'), 'Prep ');+ await user.keyboard('{Enter}');+ await user.click(screen.getByRole('button', { name: 'P1' }));+ await user.click(screen.getByRole('button', { name: 'Date' }));+ await user.click(screen.getAllByRole('button').find(b => b.textContent?.trim() === '9')!);+ await user.click(screen.getByRole('button', { name: 'Unassigned' }));+ pickOption('bob');+ await user.click(screen.getByRole('button', { name: 'Create task' }));++ await waitFor(() => expect(posted).toBeTruthy());+ expect(posted!.description).toBe('rain gear');+ expect(posted!.category).toBe('Prep'); // trimmed+ expect(posted!.priority).toBe(1);+ expect(posted!.assigned_user_id).toBe(2);+ expect(String(posted!.due_date)).toMatch(/^\d{4}-\d{2}-09$/);+ });++ it('FE-COMP-TODO-053: Escape in the inline list editor drops the typed list', async () => {+ const user = userEvent.setup();+ await openNew();++ await user.click(screen.getByRole('button', { name: 'List name' }));+ await user.type(await screen.findByPlaceholderText('List name'), 'Prep');+ await user.keyboard('{Escape}');++ expect(screen.queryByPlaceholderText('List name')).not.toBeInTheDocument();+ expect(screen.queryByText('Prep')).not.toBeInTheDocument();+ });++ it('FE-COMP-TODO-054: the active list filter preselects the new task’s list', async () => {+ const items = [buildTodoItem({ id: 60, name: 'Task', category: 'Errands', checked: 0 })];+ const { rerender } = render(<TodoListPanel tripId={1} items={items} addItemSignal={0} />);+ clickFilter(/Errands/);+ rerender(<TodoListPanel tripId={1} items={items} addItemSignal={1} />);+ await screen.findByText('Create task');++ const pane = document.querySelector('.trek-modal-backdrop') as HTMLElement;+ expect(within(pane).getByRole('button', { name: 'Errands' })).toBeInTheDocument();+ });++ it('FE-COMP-TODO-055: a failing create surfaces the error as a toast', async () => {+ const user = userEvent.setup();+ const addToast = vi.fn();+ window.__addToast = addToast as unknown as typeof window.__addToast;+ server.use(http.post('/api/trips/1/todo', () => HttpResponse.json({ error: 'Rejected' }, { status: 400 })));+ await openNew();++ await user.type(screen.getByPlaceholderText('Task name'), 'Pack bags');+ await user.click(screen.getByRole('button', { name: 'Create task' }));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Rejected', 'error', undefined));+ // The pane stays open so the user can retry.+ expect(screen.getByRole('button', { name: 'Create task' })).toBeInTheDocument();+ delete window.__addToast;+ });++ it('FE-COMP-TODO-056: closing the new task pane via the backdrop discards it', async () => {+ const user = userEvent.setup();+ await openNew();++ await user.click(document.querySelector('.trek-modal-backdrop')!);++ expect(screen.queryByText('Create task')).not.toBeInTheDocument();+ });+});++describe('TodoListPanel — mobile layout', () => {+ beforeEach(() => {+ Object.defineProperty(window, 'innerWidth', { value: 500, writable: true, configurable: true });+ });++ it('FE-COMP-TODO-057: the sidebar collapses to icons without the progress card', () => {+ render(<TodoListPanel tripId={1} items={[buildTodoItem({ name: 'Task', checked: 1 })]} />);++ expect(screen.queryByText('Tasks')).not.toBeInTheDocument();+ expect(screen.queryByText(/completed/)).not.toBeInTheDocument();+ // Labels move into titles so the icons stay tappable.+ expect(screen.getByTitle('All')).toBeInTheDocument();+ expect(screen.getByTitle('Priority')).toBeInTheDocument();+ expect(screen.getByTitle('Add list')).toBeInTheDocument();+ });++ it('FE-COMP-TODO-058: an open task opens as a bottom sheet that the backdrop closes', async () => {+ const user = userEvent.setup();+ render(<TodoListPanel tripId={1} items={[buildTodoItem({ id: 50, name: 'Plan route', checked: 0 })]} />);++ await user.click(screen.getByText('Plan route'));+ const sheet = await screen.findByText('Task');+ const backdrop = sheet.closest('div[style*="position: fixed"]') as HTMLElement;+ expect(backdrop).toBeTruthy();++ await user.click(backdrop);+ await waitFor(() => expect(screen.queryByText('Save changes')).not.toBeInTheDocument());+ });++ it('FE-COMP-TODO-059: the new task pane opens as a bottom sheet', async () => {+ const user = userEvent.setup();+ const { rerender } = render(<TodoListPanel tripId={1} items={[]} addItemSignal={0} />);+ rerender(<TodoListPanel tripId={1} items={[]} addItemSignal={1} />);+ await screen.findByText('Create task');++ const backdrop = document.querySelector('.trek-modal-backdrop') as HTMLElement;+ expect(backdrop.style.alignItems).toBe('flex-end');++ await user.click(backdrop);+ expect(screen.queryByText('Create task')).not.toBeInTheDocument();+ });++ it('FE-COMP-TODO-060: mobile filters show their counts as corner badges', () => {+ render(<TodoListPanel tripId={1} items={[buildTodoItem({ name: 'Old', checked: 0, due_date: '2020-01-01' })]} />);++ expect(within(screen.getByTitle('Overdue')).getByText('1')).toBeInTheDocument();+ });++ it('FE-COMP-TODO-074: list filters keep their colour dot but drop their label', () => {+ render(<TodoListPanel tripId={1} items={[buildTodoItem({ name: 'Task', category: 'Errands', checked: 0 })]} />);++ const filters = screen.getAllByRole('button');+ const listFilter = filters.find(b => b.getAttribute('title') === 'Errands')!;+ expect(listFilter).toBeInTheDocument();+ expect(listFilter.textContent).toBe('1');+ expect((listFilter.firstElementChild as HTMLElement).style.background).toBe('rgb(59, 130, 246)');+ });++ it('FE-COMP-TODO-075: the detail sheet closes via its own X and ignores taps inside it', async () => {+ const user = userEvent.setup();+ render(<TodoListPanel tripId={1} items={[buildTodoItem({ id: 50, name: 'Plan route', checked: 0 })]} />);++ await user.click(screen.getByText('Plan route'));+ const header = await screen.findByText('Task');++ await user.click(header);+ expect(screen.getByText('Save changes')).toBeInTheDocument();++ await user.click(header.parentElement!.querySelectorAll('button')[0]);+ await waitFor(() => expect(screen.queryByText('Save changes')).not.toBeInTheDocument());+ });++ it('FE-COMP-TODO-076: creating from the mobile sheet closes it and selects the new task', async () => {+ const user = userEvent.setup();+ server.use(http.post('/api/trips/1/todo', () => HttpResponse.json({ item: buildTodoItem({ id: 90, name: 'Pack bags' }) })));+ const items = [buildTodoItem({ id: 90, name: 'Pack bags', checked: 0 })];+ const { rerender } = render(<TodoListPanel tripId={1} items={items} addItemSignal={0} />);+ rerender(<TodoListPanel tripId={1} items={items} addItemSignal={1} />);+ await screen.findByText('Create task');++ await user.type(screen.getByPlaceholderText('Task name'), 'Pack bags');+ await user.click(screen.getByRole('button', { name: 'Create task' }));++ // onCreated closes the sheet and opens the detail sheet on the created task.+ await screen.findByText('Task');+ expect(screen.queryByText('Create task')).not.toBeInTheDocument();+ });++ it('FE-COMP-TODO-077: the mobile new task sheet closes via its own X', async () => {+ const user = userEvent.setup();+ const { rerender } = render(<TodoListPanel tripId={1} items={[]} addItemSignal={0} />);+ rerender(<TodoListPanel tripId={1} items={[]} addItemSignal={1} />);+ const header = await screen.findByText('New task');++ await user.click(header);+ expect(screen.getByText('Create task')).toBeInTheDocument();++ await user.click(header.parentElement!.querySelectorAll('button')[0]);+ expect(screen.queryByText('Create task')).not.toBeInTheDocument();+ });++ it('FE-COMP-TODO-078: the mobile new task sheet inherits the active list filter', async () => {+ const items = [buildTodoItem({ id: 60, name: 'Task', category: 'Errands', checked: 0 })];+ const { rerender } = render(<TodoListPanel tripId={1} items={items} addItemSignal={0} />);+ clickFilter('Errands');+ rerender(<TodoListPanel tripId={1} items={items} addItemSignal={1} />);+ await screen.findByText('Create task');++ const pane = document.querySelector('.trek-modal-backdrop') as HTMLElement;+ expect(within(pane).getByRole('button', { name: 'Errands' })).toBeInTheDocument();+ });+});++describe('TodoListPanel — remaining paths', () => {+ it('FE-COMP-TODO-062: ticking a task writes the new checked state back', async () => {+ let put: Record<string, unknown> | null = null;+ server.use(+ http.put('/api/trips/1/todo/5', async ({ request }) => {+ put = (await request.json()) as Record<string, unknown>;+ return HttpResponse.json({ item: buildTodoItem({ id: 5, name: 'Toggle', checked: 1 }) });+ }),+ );+ render(<TodoListPanel tripId={1} items={[buildTodoItem({ id: 5, name: 'Toggle', checked: 0 })]} />);++ const row = screen.getByText('Toggle').closest('div[style*="cursor: pointer"]') as HTMLElement;+ fireEvent.click(within(row).getAllByRole('button')[0]);++ await waitFor(() => expect(put).toEqual({ checked: true }));+ });++ it('FE-COMP-TODO-063: a task dragged out of the current view is not reordered', () => {+ let called = false;+ server.use(http.put('/api/trips/1/todo/reorder', () => { called = true; return HttpResponse.json({ success: true }); }));+ render(<TodoListPanel tripId={1} items={[+ buildTodoItem({ id: 1, name: 'Loose', checked: 0 }),+ buildTodoItem({ id: 2, name: 'Filed', category: 'Errands', checked: 0 }),+ ]} />);++ fireEvent.dragStart(document.querySelectorAll('[draggable="true"]')[0], { dataTransfer: { effectAllowed: '' } });+ clickFilter(/Errands/);+ fireEvent.drop(document.querySelectorAll('[draggable="true"]')[0].parentElement!);++ expect(called).toBe(false);+ });++ it('FE-COMP-TODO-064: hovering the active filter and the active sort leaves them styled', async () => {+ const user = userEvent.setup();+ render(<TodoListPanel tripId={1} items={[]} />);++ const all = screen.getByRole('button', { name: /^All/ });+ fireEvent.mouseEnter(all);+ expect(all.style.background).toBe('var(--bg-hover)');++ const sort = screen.getByRole('button', { name: 'Priority' });+ await user.click(sort);+ fireEvent.mouseLeave(sort);+ expect(sort.style.background).toBe('rgba(245, 158, 11, 0.07)');+ });++ it('FE-COMP-TODO-065: clearing the task name blocks the save', async () => {+ const user = userEvent.setup();+ let put = false;+ server.use(http.put('/api/trips/1/todo/40', () => { put = true; return HttpResponse.json({ item: buildTodoItem({ id: 40 }) }); }));+ render(<TodoListPanel tripId={1} items={[buildTodoItem({ id: 40, name: 'Plan route', checked: 0 })]} />);+ await user.click(screen.getByText('Plan route'));++ await user.clear(await screen.findByDisplayValue('Plan route'));+ await user.click(screen.getByRole('button', { name: 'Save changes' }));++ expect(put).toBe(false);+ });++ it('FE-COMP-TODO-066: the check button closes the inline list editor in both panes', async () => {+ const user = userEvent.setup();+ const { rerender } = render(<TodoListPanel tripId={1} items={[buildTodoItem({ id: 40, name: 'Plan route', checked: 0 })]} addItemSignal={0} />);++ await user.click(screen.getByText('Plan route'));+ await user.click(await screen.findByRole('button', { name: 'List name' }));+ let input = await screen.findByPlaceholderText('List name');+ await user.type(input, 'Logistics');+ fireEvent.click(input.nextElementSibling as HTMLElement);+ expect(screen.queryByPlaceholderText('List name')).not.toBeInTheDocument();+ expect(screen.getByText(/^Logistics/)).toBeInTheDocument();++ rerender(<TodoListPanel tripId={1} items={[buildTodoItem({ id: 40, name: 'Plan route', checked: 0 })]} addItemSignal={1} />);+ await screen.findByText('Create task');+ await user.click(screen.getByRole('button', { name: 'List name' }));+ input = await screen.findByPlaceholderText('List name');+ await user.type(input, 'Prep');+ fireEvent.click(input.nextElementSibling as HTMLElement);+ expect(screen.queryByPlaceholderText('List name')).not.toBeInTheDocument();+ expect(screen.getByText(/^Prep/)).toBeInTheDocument();+ });++ it('FE-COMP-TODO-067: the new task pane can pick an existing list from the dropdown', async () => {+ const user = userEvent.setup();+ let posted: Record<string, unknown> | null = null;+ server.use(+ http.post('/api/trips/1/todo', async ({ request }) => {+ posted = (await request.json()) as Record<string, unknown>;+ return HttpResponse.json({ item: buildTodoItem({ id: 80 }) });+ }),+ );+ const items = [buildTodoItem({ id: 60, name: 'Task', category: 'Errands', checked: 0 })];+ const { rerender } = render(<TodoListPanel tripId={1} items={items} addItemSignal={0} />);+ rerender(<TodoListPanel tripId={1} items={items} addItemSignal={1} />);+ await screen.findByText('Create task');++ const pane = document.querySelector('.trek-modal-backdrop') as HTMLElement;+ await user.type(within(pane).getByPlaceholderText('Task name'), 'Buy stamps');+ await user.click(within(pane).getByRole('button', { name: 'No list' }));+ pickOption('Errands');+ await user.click(screen.getByRole('button', { name: 'Create task' }));++ await waitFor(() => expect(posted).toBeTruthy());+ expect(posted!.category).toBe('Errands');+ });++ it('FE-COMP-TODO-068: clearing the assignee stores null in both panes', async () => {+ const user = userEvent.setup();+ withMembers();+ let put: Record<string, unknown> | null = null;+ let posted: Record<string, unknown> | null = null;+ server.use(+ http.put('/api/trips/1/todo/40', async ({ request }) => {+ put = (await request.json()) as Record<string, unknown>;+ return HttpResponse.json({ item: buildTodoItem({ id: 40, name: 'Plan route' }) });+ }),+ http.post('/api/trips/1/todo', async ({ request }) => {+ posted = (await request.json()) as Record<string, unknown>;+ return HttpResponse.json({ item: buildTodoItem({ id: 81 }) });+ }),+ );+ const items = [buildTodoItem({ id: 40, name: 'Plan route', assigned_user_id: 2, checked: 0 })];+ const { rerender } = render(<TodoListPanel tripId={1} items={items} addItemSignal={0} />);++ await user.click(screen.getByText('Plan route'));+ await user.click(await screen.findByRole('button', { name: 'bob' }));+ pickOption('Unassigned');+ await user.click(screen.getByRole('button', { name: 'Save changes' }));+ await waitFor(() => expect(put).toBeTruthy());+ expect(put!.assigned_user_id).toBeNull();++ rerender(<TodoListPanel tripId={1} items={items} addItemSignal={1} />);+ await screen.findByText('Create task');+ const pane = document.querySelector('.trek-modal-backdrop') as HTMLElement;+ await user.type(within(pane).getByPlaceholderText('Task name'), 'Buy stamps');+ await user.click(within(pane).getByRole('button', { name: 'Unassigned' }));+ pickOption('bob');+ await user.click(within(pane).getByRole('button', { name: 'bob' }));+ pickOption('Unassigned');+ await user.click(screen.getByRole('button', { name: 'Create task' }));++ await waitFor(() => expect(posted).toBeTruthy());+ expect(posted!.assigned_user_id).toBeNull();+ });++ it('FE-COMP-TODO-069: a rejection that is not an Error falls back to the generic message', async () => {+ const user = userEvent.setup();+ const addToast = vi.fn();+ window.__addToast = addToast as unknown as typeof window.__addToast;+ // The store always wraps failures in an Error; a bare throw is the only way+ // into the fallback message.+ const reject = async () => { throw 'boom' };+ useTripStore.setState({ updateTodoItem: reject, deleteTodoItem: reject });+ render(<TodoListPanel tripId={1} items={[buildTodoItem({ id: 40, name: 'Plan route', checked: 0 })]} />);+ await user.click(screen.getByText('Plan route'));++ const nameInput = await screen.findByDisplayValue('Plan route');+ await user.clear(nameInput);+ await user.type(nameInput, 'Renamed');+ await user.click(screen.getByRole('button', { name: 'Save changes' }));+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));++ addToast.mockClear();+ await user.click(screen.getByRole('button', { name: 'Delete' }));+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));+ delete window.__addToast;+ });++ it('FE-COMP-TODO-070: a create rejected without an Error keeps the pane open', async () => {+ const user = userEvent.setup();+ const addToast = vi.fn();+ window.__addToast = addToast as unknown as typeof window.__addToast;+ const reject = async () => { throw 'boom' };+ useTripStore.setState({ addTodoItem: reject });+ const { rerender } = render(<TodoListPanel tripId={1} items={[]} addItemSignal={0} />);+ rerender(<TodoListPanel tripId={1} items={[]} addItemSignal={1} />);+ await screen.findByText('Create task');++ await user.type(screen.getByPlaceholderText('Task name'), 'Pack bags');+ await user.click(screen.getByRole('button', { name: 'Create task' }));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));+ expect(screen.getByRole('button', { name: 'Create task' })).toBeInTheDocument();+ delete window.__addToast;+ });++ it('FE-COMP-TODO-073: a create that yields no id keeps the pane open', async () => {+ const user = userEvent.setup();+ server.use(http.post('/api/trips/1/todo', () => HttpResponse.json({ item: {} })));+ const { rerender } = render(<TodoListPanel tripId={1} items={[]} addItemSignal={0} />);+ rerender(<TodoListPanel tripId={1} items={[]} addItemSignal={1} />);+ await screen.findByText('Create task');++ await user.type(screen.getByPlaceholderText('Task name'), 'Pack bags');+ await user.click(screen.getByRole('button', { name: 'Create task' }));++ await waitFor(() => expect(screen.getByRole('button', { name: 'Create task' })).not.toBeDisabled());+ expect(screen.getByText('New task')).toBeInTheDocument();+ });++ it('FE-COMP-TODO-071: the new task pane closes via its own X', async () => {+ const user = userEvent.setup();+ const { rerender } = render(<TodoListPanel tripId={1} items={[]} addItemSignal={0} />);+ rerender(<TodoListPanel tripId={1} items={[]} addItemSignal={1} />);+ await screen.findByText('Create task');++ const pane = document.querySelector('.trek-modal-backdrop') as HTMLElement;+ // The header X is the only button without an accessible name.+ await user.click(within(pane).getAllByRole('button').find(b => !b.textContent?.trim())!);++ expect(screen.queryByText('Create task')).not.toBeInTheDocument();+ });++ it('FE-COMP-TODO-072: clicking inside a pane does not dismiss it', async () => {+ const user = userEvent.setup();+ const { rerender } = render(<TodoListPanel tripId={1} items={[]} addItemSignal={0} />);+ rerender(<TodoListPanel tripId={1} items={[]} addItemSignal={1} />);+ await screen.findByText('Create task');++ await user.click(screen.getByText('New task'));++ expect(screen.getByText('Create task')).toBeInTheDocument();+ });+});++describe('TodoListPanel — plugin contributions', () => {+ it('FE-COMP-TODO-061: a plugin column is appended under the contributing task', async () => {+ server.use(+ http.get('/api/view-contributions/todos/1', () =>+ HttpResponse.json({+ contributions: [+ { kind: 'column', pluginId: 'p1', id: 'c1', entityId: 12, label: 'Weather', value: 'Rainy', tone: 'default' },+ ],+ })+ ),+ );+ render(<TodoListPanel tripId={1} items={[+ buildTodoItem({ id: 12, name: 'Hike', checked: 0 }),+ buildTodoItem({ id: 13, name: 'Swim', checked: 0 }),+ ]} />);++ expect(await screen.findByText('Weather')).toBeInTheDocument();+ expect(screen.getByText('Rainy')).toBeInTheDocument();+ });+});diff --git a/client/src/components/Todo/TodoRow.test.tsx b/client/src/components/Todo/TodoRow.test.tsxnew file mode 100644index 000000000..f1d9501a1--- /dev/null+++ b/client/src/components/Todo/TodoRow.test.tsx@@ -0,0 +1,210 @@+// FE-W4TDR-001 to FE-W4TDR-020+import type { ComponentProps } from 'react'+import { describe, it, expect, vi } from 'vitest'+import type { TodoItem } from '../../types'+import { render, screen, fireEvent } from '../../../tests/helpers/render'+import TodoRow from './TodoRow'+import type { Member } from './todoListModel'++const MEMBERS: Member[] = [+ { id: 1, username: 'ada', avatar: 'ada.png' },+ { id: 2, username: 'bob', avatar: null, is_guest: true },+]++function todo(overrides: Partial<TodoItem> = {}): TodoItem {+ return {+ id: 10, trip_id: 1, name: 'Book ferry', checked: 0, priority: 0,+ description: null, due_date: null, category: null, assigned_user_id: null,+ ...overrides,+ } as unknown as TodoItem+}++function setup(item: TodoItem, overrides: Partial<ComponentProps<typeof TodoRow>> = {}) {+ const onSelect = vi.fn()+ const onToggle = vi.fn()+ const utils = render(+ <TodoRow+ item={item}+ members={MEMBERS}+ categories={['Docs', 'Gear']}+ today="2026-06-15"+ isSelected={false}+ canEdit+ formatDate={(d: string) => `on ${d}`}+ onSelect={onSelect}+ onToggle={onToggle}+ {...overrides}+ />,+ )+ return { onSelect, onToggle, ...utils }+}++const dragHandlers = () => ({+ isDragging: false,+ isOver: false,+ onStart: vi.fn(),+ onOver: vi.fn(),+ onEnd: vi.fn(),+ onDrop: vi.fn(),+})++describe('TodoRow', () => {+ it('FE-W4TDR-001: renders the task name without any badges', () => {+ const { container } = setup(todo())++ expect(screen.getByText('Book ferry')).toBeInTheDocument()+ expect(container.querySelectorAll('span')).toHaveLength(0)+ })++ it('FE-W4TDR-002: selecting an unselected row reports its id', () => {+ const { onSelect, container } = setup(todo())++ fireEvent.click(container.firstElementChild!)++ expect(onSelect).toHaveBeenCalledWith(10)+ })++ it('FE-W4TDR-003: clicking the selected row deselects it', () => {+ const { onSelect, container } = setup(todo(), { isSelected: true })++ fireEvent.click(container.firstElementChild!)++ expect(onSelect).toHaveBeenCalledWith(null)+ })++ it('FE-W4TDR-004: the checkbox toggles the task without selecting the row', () => {+ const { onToggle, onSelect } = setup(todo())++ fireEvent.click(screen.getAllByRole('button')[0])++ expect(onToggle).toHaveBeenCalledWith(10, true)+ expect(onSelect).not.toHaveBeenCalled()+ })++ it('FE-W4TDR-005: a done task strikes through and unchecks on click', () => {+ const { onToggle } = setup(todo({ checked: 1 } as Partial<TodoItem>))++ expect(screen.getByText('Book ferry')).toHaveStyle({ textDecoration: 'line-through' })+ fireEvent.click(screen.getAllByRole('button')[0])+ expect(onToggle).toHaveBeenCalledWith(10, false)+ })++ it('FE-W4TDR-006: a read-only row swallows the toggle', () => {+ const { onToggle } = setup(todo(), { canEdit: false })++ fireEvent.click(screen.getAllByRole('button')[0])++ expect(onToggle).not.toHaveBeenCalled()+ })++ it('FE-W4TDR-007: renders the description preview', () => {+ setup(todo({ description: 'Ferry to Vestmannaeyjar' } as Partial<TodoItem>))++ expect(screen.getByText('Ferry to Vestmannaeyjar')).toBeInTheDocument()+ })++ it('FE-W4TDR-008: renders the priority badge', () => {+ setup(todo({ priority: 2 } as Partial<TodoItem>))++ expect(screen.getByText('P2')).toBeInTheDocument()+ })++ it('FE-W4TDR-009: ignores a priority outside the configured range', () => {+ setup(todo({ priority: 9 } as Partial<TodoItem>))++ expect(screen.queryByText(/^P\d$/)).toBeNull()+ })++ it('FE-W4TDR-010: formats the due date through the caller formatter', () => {+ setup(todo({ due_date: '2026-06-20' } as Partial<TodoItem>))++ expect(screen.getByText('on 2026-06-20')).toBeInTheDocument()+ })++ it('FE-W4TDR-011: highlights an overdue date in red', () => {+ setup(todo({ due_date: '2026-06-01' } as Partial<TodoItem>))++ expect(screen.getByText('on 2026-06-01')).toHaveStyle({ color: 'rgb(239, 68, 68)' })+ })++ it('FE-W4TDR-012: does not treat a past date on a done task as overdue', () => {+ setup(todo({ due_date: '2026-06-01', checked: 1 } as Partial<TodoItem>))++ expect(screen.getByText('on 2026-06-01')).not.toHaveStyle({ color: 'rgb(239, 68, 68)' })+ })++ it('FE-W4TDR-013: renders the category chip with its palette dot', () => {+ const { container } = setup(todo({ category: 'Gear' } as Partial<TodoItem>))++ expect(screen.getByText('Gear')).toBeInTheDocument()+ expect(container.innerHTML).toContain('rgb(168, 85, 247)')+ })++ it('FE-W4TDR-014: renders the assignee avatar for a member with a picture', () => {+ const { container } = setup(todo({ assigned_user_id: 1 } as Partial<TodoItem>))++ expect(screen.getByText('ada')).toBeInTheDocument()+ expect(container.querySelector('img')).toHaveAttribute('src', '/uploads/avatars/ada.png')+ })++ it('FE-W4TDR-015: falls back to an initial and flags a guest assignee', () => {+ const { container } = setup(todo({ assigned_user_id: 2 } as Partial<TodoItem>))++ expect(screen.getByText('B')).toBeInTheDocument()+ expect(container.querySelector('img')).toBeNull()+ expect(container.querySelector('.lucide-user-round')).not.toBeNull()+ })++ it('FE-W4TDR-016: the drag handle starts and ends a reorder', () => {+ const drag = dragHandlers()+ const { container } = setup(todo(), { drag })+ const handle = container.querySelector('[draggable="true"]') as HTMLElement++ fireEvent.dragStart(handle, { dataTransfer: { effectAllowed: '' } })+ expect(drag.onStart).toHaveBeenCalledWith(10)++ fireEvent.dragEnd(handle)+ expect(drag.onEnd).toHaveBeenCalled()+ })++ it('FE-W4TDR-017: dragging over the row reports it and leaving clears the target', () => {+ const drag = dragHandlers()+ const { container } = setup(todo(), { drag })+ const row = container.firstElementChild as HTMLElement++ fireEvent.dragOver(row, { dataTransfer: { dropEffect: '' } })+ expect(drag.onOver).toHaveBeenCalledWith(10)++ fireEvent.dragLeave(row, { relatedTarget: document.body })+ expect(drag.onOver).toHaveBeenLastCalledWith(-1)+ })++ it('FE-W4TDR-018: dropping on the row reports the target id', () => {+ const drag = dragHandlers()+ const { container } = setup(todo(), { drag })++ fireEvent.drop(container.firstElementChild!)++ expect(drag.onDrop).toHaveBeenCalledWith(10)+ })++ it('FE-W4TDR-019: hides the drag handle when the user cannot edit', () => {+ const { container } = setup(todo(), { drag: dragHandlers(), canEdit: false })++ expect(container.querySelector('[draggable="true"]')).toBeNull()+ })++ it('FE-W4TDR-020: dims the dragged row and marks the drop target', () => {+ const { container, rerender } = setup(todo(), { drag: { ...dragHandlers(), isDragging: true } })+ expect((container.firstElementChild as HTMLElement).style.opacity).toBe('0.4')++ rerender(+ <TodoRow+ item={todo()} members={MEMBERS} categories={[]} today="2026-06-15" isSelected={false} canEdit+ formatDate={(d: string) => d} onSelect={() => {}} onToggle={() => {}}+ drag={{ ...dragHandlers(), isOver: true }}+ />,+ )+ expect((container.firstElementChild as HTMLElement).style.boxShadow).toBe('inset 3px 0 0 0 var(--accent)')+ })+})diff --git a/client/src/components/Todo/todoListModel.test.ts b/client/src/components/Todo/todoListModel.test.tsnew file mode 100644index 000000000..e8ab22bc9--- /dev/null+++ b/client/src/components/Todo/todoListModel.test.ts@@ -0,0 +1,46 @@+// FE-W4TDM-001 to FE-W4TDM-006+import { describe, it, expect } from 'vitest'+import { KAT_COLORS, PRIO_CONFIG, katColor } from './todoListModel'++describe('katColor', () => {+ it('FE-W4TDM-001: gives a known category the palette colour at its index', () => {+ const cats = ['Docs', 'Gear', 'Food']++ expect(katColor('Docs', cats)).toBe(KAT_COLORS[0])+ expect(katColor('Gear', cats)).toBe(KAT_COLORS[1])+ expect(katColor('Food', cats)).toBe(KAT_COLORS[2])+ })++ it('FE-W4TDM-002: wraps around when there are more categories than colours', () => {+ const cats = Array.from({ length: 12 }, (_, i) => `c${i}`)++ expect(katColor('c10', cats)).toBe(KAT_COLORS[0])+ expect(katColor('c11', cats)).toBe(KAT_COLORS[1])+ })++ it('FE-W4TDM-003: hashes an unlisted category into the palette', () => {+ const color = katColor('Ad-hoc', [])++ expect(KAT_COLORS).toContain(color)+ expect(katColor('Ad-hoc', [])).toBe(color)+ })++ it('FE-W4TDM-004: gives different unlisted categories different colours', () => {+ const seen = new Set(['Alpha', 'Bravo', 'Charlie', 'Delta'].map(c => katColor(c, [])))+ expect(seen.size).toBeGreaterThan(1)+ })++ it('FE-W4TDM-005: handles an empty category name without going out of range', () => {+ expect(KAT_COLORS).toContain(katColor('', []))+ })+})++describe('PRIO_CONFIG', () => {+ it('FE-W4TDM-006: maps the three priorities to labels and colours', () => {+ expect(PRIO_CONFIG[1]).toEqual({ label: 'P1', color: '#ef4444' })+ expect(PRIO_CONFIG[2].label).toBe('P2')+ expect(PRIO_CONFIG[3].label).toBe('P3')+ expect(PRIO_CONFIG[4]).toBeUndefined()+ expect(KAT_COLORS).toHaveLength(10)+ })+})diff --git a/client/src/components/Trips/TripFormModal.test.tsx b/client/src/components/Trips/TripFormModal.test.tsxindex 880515cf4..2b36e69ef 100644--- a/client/src/components/Trips/TripFormModal.test.tsx+++ b/client/src/components/Trips/TripFormModal.test.tsx@@ -1,12 +1,15 @@-// FE-COMP-TRIPFORM-001 to FE-COMP-TRIPFORM-031+// FE-COMP-TRIPFORM-001 to FE-COMP-TRIPFORM-082+import type { Mock } from 'vitest';import { render, screen, waitFor, fireEvent } from '../../../tests/helpers/render';import userEvent from '@testing-library/user-event';-import { http, HttpResponse } from 'msw';+import { delay, http, HttpResponse } from 'msw';import { useAuthStore } from '../../store/authStore';import { useTripStore } from '../../store/tripStore';+import { usePermissionsStore } from '../../store/permissionsStore';import { resetAllStores, seedStore } from '../../../tests/helpers/store';import { buildUser, buildTrip } from '../../../tests/helpers/factories';import { server } from '../../../tests/helpers/msw/server';+import type { Trip } from '../../types';import TripFormModal from './TripFormModal';const defaultProps = {@@ -17,12 +20,38 @@ const defaultProps = {onCoverUpdate: vi.fn(),};+type AddToast = NonNullable<typeof window.__addToast>;+let addToast: Mock<AddToast>;+/** Blob URLs handed out for staged cover files; jsdom has no real implementation. */+let createObjectURL: Mock<(obj: Blob) => string>;+let originalCreateObjectURL: typeof URL.createObjectURL;+beforeEach(() => {resetAllStores();seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });seedStore(useTripStore, { trip: buildTrip({ id: 1 }) });+ addToast = vi.fn<AddToast>(() => 0);+ window.__addToast = addToast;+ createObjectURL = vi.fn(() => 'blob:cover');+ originalCreateObjectURL = URL.createObjectURL;+ Object.defineProperty(URL, 'createObjectURL', { writable: true, configurable: true, value: createObjectURL });+});++afterEach(() => {+ delete window.__addToast;+ Object.defineProperty(URL, 'createObjectURL', { writable: true, configurable: true, value: originalCreateObjectURL });+ vi.restoreAllMocks();});+const pngFile = () => new File(['img'], 'cover.png', { type: 'image/png' });++const fileInput = () => document.querySelector('input[type="file"]') as HTMLInputElement;++const submitNewTrip = async (user: ReturnType<typeof userEvent.setup>) => {+ const btn = screen.getAllByText('Create New Trip').find(el => el.closest('button'))!;+ await user.click(btn.closest('button')!);+};+describe('TripFormModal', () => {it('FE-COMP-TRIPFORM-001: renders without crashing', () => {render(<TripFormModal {...defaultProps} />);@@ -454,4 +483,721 @@ describe('TripFormModal', () => {await waitFor(() => expect(onSave).toHaveBeenCalled());expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ currency: 'USD' }));});++ // ── App config / prefill fallbacks ────────────────────────────────────────++ it('FE-COMP-TRIPFORM-039: app config re-enables the reminder section', async () => {+ server.use(http.get('/api/auth/app-config', () => HttpResponse.json({ trip_reminders_enabled: true })));+ render(<TripFormModal {...defaultProps} trip={null} />);+ // Store default is false, so the section starts as the disabled hint.+ expect(screen.getByText(/Trip reminders are disabled/i)).toBeInTheDocument();+ await screen.findByRole('button', { name: 'Custom' });+ expect(useAuthStore.getState().tripRemindersEnabled).toBe(true);+ });++ it('FE-COMP-TRIPFORM-040: a users payload without a list hides the member section', async () => {+ server.use(http.get('/api/auth/users', () => HttpResponse.json({})));+ render(<TripFormModal {...defaultProps} trip={null} />);+ await screen.findByText('Cover Image');+ expect(screen.queryByText('Travel buddies')).not.toBeInTheDocument();+ });++ it('FE-COMP-TRIPFORM-041: a trip with blank fields falls back to the form defaults', async () => {+ server.use(http.get('/api/trips/5/members', () => HttpResponse.json({})));+ const bare = {+ ...buildTrip({ id: 5 }),+ title: '',+ description: null,+ start_date: null,+ end_date: null,+ currency: null,+ reminder_days: null,+ day_count: 0,+ } as unknown as Trip;+ render(<TripFormModal {...defaultProps} trip={bare} />);++ expect(screen.getByPlaceholderText(/Summer in Japan/i)).toHaveValue('');+ expect(screen.getByText(/^EUR/)).toBeInTheDocument();+ // No dates -> the day-count field appears and falls back to 7.+ expect(document.querySelector('input[max="365"]')).toHaveValue('7');+ });++ // ── Create follow-ups: members and cover ──────────────────────────────────++ it('FE-COMP-TRIPFORM-042: a save handler that returns nothing still closes the modal', async () => {+ const user = userEvent.setup();+ const onClose = vi.fn();+ const onSave = vi.fn(() => undefined);+ render(<TripFormModal {...defaultProps} onSave={onSave} onClose={onClose} />);+ await user.type(screen.getByPlaceholderText(/Summer in Japan/i), 'Void Trip');+ await submitNewTrip(user);+ await waitFor(() => expect(onClose).toHaveBeenCalled());+ });++ it('FE-COMP-TRIPFORM-043: selected members are attached to the freshly created trip', async () => {+ const user = userEvent.setup();+ seedStore(useAuthStore, { user: buildUser({ id: 1, username: 'me' }), isAuthenticated: true });+ const identifiers: string[] = [];+ server.use(+ http.get('/api/auth/users', () => HttpResponse.json({ users: [{ id: 100, username: 'alice' }] })),+ http.post('/api/trips/99/members', async ({ request }) => {+ identifiers.push(((await request.json()) as { identifier: string }).identifier);+ return HttpResponse.json({ success: true });+ }),+ );+ const onSave = vi.fn().mockResolvedValue({ trip: buildTrip({ id: 99 }) });+ render(<TripFormModal {...defaultProps} trip={null} onSave={onSave} />);++ await screen.findByText('Travel buddies');+ await user.click(screen.getByText('Add member').closest('button')!);+ await user.click(await screen.findByRole('button', { name: 'alice' }));+ await user.type(screen.getByPlaceholderText(/Summer in Japan/i), 'Group Trip');+ await submitNewTrip(user);++ await waitFor(() => expect(identifiers).toEqual(['alice']));+ expect(addToast).not.toHaveBeenCalled();+ });++ it('FE-COMP-TRIPFORM-044: a failing member add surfaces a toast but still closes', async () => {+ const user = userEvent.setup();+ const onClose = vi.fn();+ seedStore(useAuthStore, { user: buildUser({ id: 1, username: 'me' }), isAuthenticated: true });+ server.use(+ http.get('/api/auth/users', () => HttpResponse.json({ users: [{ id: 100, username: 'alice' }] })),+ http.post('/api/trips/99/members', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),+ );+ const onSave = vi.fn().mockResolvedValue({ trip: buildTrip({ id: 99 }) });+ render(<TripFormModal {...defaultProps} trip={null} onSave={onSave} onClose={onClose} />);++ await screen.findByText('Travel buddies');+ await user.click(screen.getByText('Add member').closest('button')!);+ await user.click(await screen.findByRole('button', { name: 'alice' }));+ await user.type(screen.getByPlaceholderText(/Summer in Japan/i), 'Group Trip');+ await submitNewTrip(user);++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Failed to add', 'error', undefined));+ expect(onClose).toHaveBeenCalled();+ });++ it('FE-COMP-TRIPFORM-045: a staged cover file is uploaded once the trip exists', async () => {+ const user = userEvent.setup();+ const onCoverUpdate = vi.fn();+ server.use(+ http.post('/api/trips/99/cover', () => HttpResponse.json({ cover_image: '/uploads/covers/new.jpg' })),+ );+ const onSave = vi.fn().mockResolvedValue({ trip: buildTrip({ id: 99 }) });+ render(<TripFormModal {...defaultProps} trip={null} onSave={onSave} onCoverUpdate={onCoverUpdate} />);++ fireEvent.change(fileInput(), { target: { files: [pngFile()] } });+ await waitFor(() => expect(createObjectURL).toHaveBeenCalled());+ await user.type(screen.getByPlaceholderText(/Summer in Japan/i), 'Cover Trip');+ await submitNewTrip(user);++ await waitFor(() => expect(onCoverUpdate).toHaveBeenCalledWith(99, '/uploads/covers/new.jpg'));+ });++ it('FE-COMP-TRIPFORM-046: a failing cover upload after create only warns', async () => {+ const user = userEvent.setup();+ const onCoverUpdate = vi.fn();+ server.use(http.post('/api/trips/99/cover', () => HttpResponse.json({}, { status: 500 })));+ const onSave = vi.fn().mockResolvedValue({ trip: buildTrip({ id: 99 }) });+ render(<TripFormModal {...defaultProps} trip={null} onSave={onSave} onCoverUpdate={onCoverUpdate} />);++ fireEvent.change(fileInput(), { target: { files: [pngFile()] } });+ await waitFor(() => expect(createObjectURL).toHaveBeenCalled());+ await user.type(screen.getByPlaceholderText(/Summer in Japan/i), 'Cover Trip');+ await submitNewTrip(user);++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Failed to upload', 'error', undefined));+ expect(onCoverUpdate).not.toHaveBeenCalled();+ });++ it('FE-COMP-TRIPFORM-047: a failing Unsplash cover save after create only warns', async () => {+ const user = userEvent.setup();+ server.use(+ http.get('/api/trips/cover-images/search', () =>+ HttpResponse.json({ photos: [{ id: 'p1', url: 'https://img/regular.jpg', thumb: 'https://img/t.jpg', photographer: 'Alice' }] })+ ),+ http.put('/api/trips/99', () => HttpResponse.json({}, { status: 500 })),+ );+ const onSave = vi.fn().mockResolvedValue({ trip: buildTrip({ id: 99 }) });+ render(<TripFormModal {...defaultProps} trip={null} onSave={onSave} />);++ await user.type(screen.getByPlaceholderText(/Summer in Japan/i), 'Alpine Trip');+ await user.click(screen.getByRole('button', { name: /Search Unsplash/i }));+ await user.click(await screen.findByRole('button', { name: /Use Unsplash photo by Alice/i }));+ await submitNewTrip(user);++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Failed to save cover image', 'error', undefined));+ });++ // ── Cover upload on an existing trip ──────────────────────────────────────++ it('FE-COMP-TRIPFORM-048: picking a file on an existing trip uploads it immediately', async () => {+ const onCoverUpdate = vi.fn();+ server.use(+ http.post('/api/trips/1/cover', () => HttpResponse.json({ cover_image: '/uploads/covers/edit.jpg' })),+ );+ render(<TripFormModal {...defaultProps} trip={buildTrip({ id: 1, title: 'Edit Me' })} onCoverUpdate={onCoverUpdate} />);++ fireEvent.change(fileInput(), { target: { files: [pngFile()] } });++ await waitFor(() => expect(onCoverUpdate).toHaveBeenCalledWith(1, '/uploads/covers/edit.jpg'));+ expect(addToast).toHaveBeenCalledWith('Cover image saved', 'success', undefined);+ expect(document.querySelector('img[src="/uploads/covers/edit.jpg"]')).toBeInTheDocument();+ // Staging a file is only for new trips — nothing gets a blob URL here.+ expect(createObjectURL).not.toHaveBeenCalled();+ });++ it('FE-COMP-TRIPFORM-049: a failing immediate cover upload shows an error toast', async () => {+ const onCoverUpdate = vi.fn();+ server.use(http.post('/api/trips/1/cover', () => HttpResponse.json({}, { status: 500 })));+ render(<TripFormModal {...defaultProps} trip={buildTrip({ id: 1 })} onCoverUpdate={onCoverUpdate} />);++ fireEvent.change(fileInput(), { target: { files: [pngFile()] } });++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Failed to upload', 'error', undefined));+ expect(onCoverUpdate).not.toHaveBeenCalled();+ });++ it('FE-COMP-TRIPFORM-050: clearing the file picker uploads nothing', async () => {+ let uploads = 0;+ server.use(http.post('/api/trips/1/cover', () => { uploads++; return HttpResponse.json({ cover_image: 'x' }); }));+ render(<TripFormModal {...defaultProps} trip={buildTrip({ id: 1 })} />);++ fireEvent.change(fileInput(), { target: { files: [] } });++ await waitFor(() => expect(fileInput().value).toBe(''));+ expect(uploads).toBe(0);+ expect(addToast).not.toHaveBeenCalled();+ expect(screen.getByRole('button', { name: /Add cover image/i })).toBeInTheDocument();+ });++ it('FE-COMP-TRIPFORM-051: the Change button opens the hidden file picker', async () => {+ const user = userEvent.setup();+ render(<TripFormModal {...defaultProps} trip={buildTrip({ id: 1, cover_image: '/uploads/covers/a.jpg' })} />);++ const clickSpy = vi.spyOn(fileInput(), 'click').mockImplementation(() => {});+ await user.click(screen.getByRole('button', { name: /Change/i }));++ expect(clickSpy).toHaveBeenCalled();+ expect(document.querySelector('img[src="/uploads/covers/a.jpg"]')).toBeInTheDocument();+ });++ // ── Unsplash search ───────────────────────────────────────────────────────++ it('FE-COMP-TRIPFORM-052: pressing Enter without a query or title asks for a search term', async () => {+ render(<TripFormModal {...defaultProps} trip={null} />);+ const search = screen.getByPlaceholderText('Search destination photos');++ fireEvent.keyDown(search, { key: 'a' });+ expect(screen.queryByText('Enter a search term')).not.toBeInTheDocument();++ fireEvent.keyDown(search, { key: 'Enter' });+ await screen.findByText('Enter a search term');+ });++ it('FE-COMP-TRIPFORM-053: a search without results reports it', async () => {+ const user = userEvent.setup();+ server.use(http.get('/api/trips/cover-images/search', () => HttpResponse.json({})));+ render(<TripFormModal {...defaultProps} trip={null} />);++ await user.type(screen.getByPlaceholderText('Search destination photos'), 'nowhere');+ await user.click(screen.getByRole('button', { name: /Search Unsplash/i }));++ await screen.findByText('No images found');+ });++ it('FE-COMP-TRIPFORM-054: a failing search shows the server error', async () => {+ const user = userEvent.setup();+ server.use(+ http.get('/api/trips/cover-images/search', () =>+ HttpResponse.json({ error: 'Unsplash key missing' }, { status: 500 })+ ),+ );+ render(<TripFormModal {...defaultProps} trip={null} />);++ await user.type(screen.getByPlaceholderText('Search destination photos'), 'alps');+ await user.click(screen.getByRole('button', { name: /Search Unsplash/i }));++ await screen.findByText('Unsplash key missing');+ });++ it('FE-COMP-TRIPFORM-055: a photo without a photographer falls back in the label and drops the credit', async () => {+ const user = userEvent.setup();+ server.use(+ http.get('/api/trips/cover-images/search', () =>+ HttpResponse.json({ photos: [{ id: 'p1', url: '', thumb: 'https://img/t.jpg', description: null, photographer: null }] })+ ),+ );+ render(<TripFormModal {...defaultProps} trip={null} />);++ await user.type(screen.getByPlaceholderText(/Summer in Japan/i), 'Alps');+ await user.click(screen.getByRole('button', { name: /Search Unsplash/i }));++ const photoBtn = await screen.findByRole('button', { name: 'Use Unsplash photo by Unsplash' });+ expect(photoBtn.querySelector('img')).toHaveAttribute('alt', '');+ expect(photoBtn.querySelector('span')).toBeNull();++ // An empty url is not selectable — nothing is staged.+ await user.click(photoBtn);+ expect(document.querySelector('img[src="https://img/t.jpg"]')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /Change/i })).not.toBeInTheDocument();+ });++ it('FE-COMP-TRIPFORM-056: picking an Unsplash photo while editing saves it right away', async () => {+ const user = userEvent.setup();+ const onCoverUpdate = vi.fn();+ let putBody: Record<string, unknown> | null = null;+ server.use(+ http.get('/api/trips/cover-images/search', () =>+ HttpResponse.json({ photos: [{ id: 'p1', url: 'https://img/regular.jpg', thumb: 'https://img/t.jpg', photographer: 'Bob' }] })+ ),+ http.put('/api/trips/1', async ({ request }) => {+ putBody = (await request.json()) as Record<string, unknown>;+ return HttpResponse.json({ trip: buildTrip({ id: 1 }) });+ }),+ );+ render(<TripFormModal {...defaultProps} trip={buildTrip({ id: 1, title: 'Edit Me' })} onCoverUpdate={onCoverUpdate} />);++ await user.type(screen.getByPlaceholderText('Search destination photos'), 'alps');+ await user.click(screen.getByRole('button', { name: /Search Unsplash/i }));+ await user.click(await screen.findByRole('button', { name: /Use Unsplash photo by Bob/i }));++ await waitFor(() => expect(putBody).toMatchObject({ cover_image: 'https://img/regular.jpg' }));+ expect(onCoverUpdate).toHaveBeenCalledWith(1, 'https://img/regular.jpg');+ expect(addToast).toHaveBeenCalledWith('Cover image saved', 'success', undefined);+ });++ it('FE-COMP-TRIPFORM-057: a failing Unsplash save while editing shows the server error', async () => {+ const user = userEvent.setup();+ server.use(+ http.get('/api/trips/cover-images/search', () =>+ HttpResponse.json({ photos: [{ id: 'p1', url: 'https://img/regular.jpg', thumb: 'https://img/t.jpg', photographer: 'Bob' }] })+ ),+ http.put('/api/trips/1', () => HttpResponse.json({ error: 'Cover rejected' }, { status: 500 })),+ );+ render(<TripFormModal {...defaultProps} trip={buildTrip({ id: 1, title: 'Edit Me' })} />);++ await user.type(screen.getByPlaceholderText('Search destination photos'), 'alps');+ await user.click(screen.getByRole('button', { name: /Search Unsplash/i }));+ await user.click(await screen.findByRole('button', { name: /Use Unsplash photo by Bob/i }));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Cover rejected', 'error', undefined));+ });++ // ── Removing a cover ──────────────────────────────────────────────────────++ it('FE-COMP-TRIPFORM-058: removing a staged cover only clears the preview', async () => {+ const user = userEvent.setup();+ let puts = 0;+ server.use(http.put('/api/trips/1', () => { puts++; return HttpResponse.json({}); }));+ render(<TripFormModal {...defaultProps} trip={null} />);++ fireEvent.change(fileInput(), { target: { files: [pngFile()] } });+ await waitFor(() => expect(document.querySelector('img[src="blob:cover"]')).toBeInTheDocument());++ await user.click(screen.getByRole('button', { name: /Change/i }).nextElementSibling as HTMLElement);++ await waitFor(() => expect(document.querySelector('img[src="blob:cover"]')).not.toBeInTheDocument());+ expect(puts).toBe(0);+ });++ it('FE-COMP-TRIPFORM-059: removing an existing cover clears it on the server', async () => {+ const user = userEvent.setup();+ const onCoverUpdate = vi.fn();+ let putBody: Record<string, unknown> | null = null;+ server.use(+ http.put('/api/trips/1', async ({ request }) => {+ putBody = (await request.json()) as Record<string, unknown>;+ return HttpResponse.json({ trip: buildTrip({ id: 1 }) });+ }),+ );+ render(<TripFormModal {...defaultProps} trip={buildTrip({ id: 1, cover_image: '/uploads/covers/a.jpg' })} onCoverUpdate={onCoverUpdate} />);++ await user.click(screen.getByRole('button', { name: /Change/i }).nextElementSibling as HTMLElement);++ await waitFor(() => expect(putBody).toMatchObject({ cover_image: null }));+ expect(onCoverUpdate).toHaveBeenCalledWith(1, null);+ expect(document.querySelector('img[src="/uploads/covers/a.jpg"]')).not.toBeInTheDocument();+ });++ it('FE-COMP-TRIPFORM-060: a failing cover removal keeps the preview and warns', async () => {+ const user = userEvent.setup();+ server.use(http.put('/api/trips/1', () => HttpResponse.json({}, { status: 500 })));+ render(<TripFormModal {...defaultProps} trip={buildTrip({ id: 1, cover_image: '/uploads/covers/a.jpg' })} />);++ await user.click(screen.getByRole('button', { name: /Change/i }).nextElementSibling as HTMLElement);++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Failed to remove', 'error', undefined));+ expect(document.querySelector('img[src="/uploads/covers/a.jpg"]')).toBeInTheDocument();+ });++ // ── Drag & drop / paste ───────────────────────────────────────────────────++ it('FE-COMP-TRIPFORM-061: the drop zone only accepts image drops', async () => {+ render(<TripFormModal {...defaultProps} trip={null} />);+ const zone = screen.getByRole('button', { name: /Add cover image/i });++ fireEvent.dragOver(zone);+ expect(zone.style.borderColor).toBe('rgb(99, 102, 241)');+ fireEvent.dragLeave(zone);+ expect(zone.style.borderColor).toBe('rgb(229, 231, 235)');+ fireEvent.mouseEnter(zone);+ expect(zone.style.color).toBe('rgb(107, 114, 128)');+ fireEvent.mouseLeave(zone);+ expect(zone.style.color).toBe('rgb(156, 163, 175)');++ fireEvent.drop(zone, { dataTransfer: { files: [new File(['x'], 'notes.txt', { type: 'text/plain' })] } });+ expect(createObjectURL).not.toHaveBeenCalled();++ fireEvent.drop(zone, { dataTransfer: { files: [pngFile()] } });+ await waitFor(() => expect(document.querySelector('img[src="blob:cover"]')).toBeInTheDocument());+ });++ it('FE-COMP-TRIPFORM-062: pastes without a usable image are ignored', () => {+ render(<TripFormModal {...defaultProps} trip={null} />);+ const form = document.querySelector('form')!;++ fireEvent.paste(form, { clipboardData: {} });+ fireEvent.paste(form, { clipboardData: { items: [{ type: 'text/plain', getAsFile: () => null }] } });+ fireEvent.paste(form, { clipboardData: { items: [{ type: 'image/png', getAsFile: () => null }] } });++ expect(createObjectURL).not.toHaveBeenCalled();+ });++ it('FE-COMP-TRIPFORM-063: without the cover permission the section and paste handler are inert', () => {+ seedStore(useAuthStore, { user: buildUser({ id: 7, role: 'user' }), isAuthenticated: true });+ seedStore(usePermissionsStore, { permissions: { trip_cover_upload: 'admin', trip_edit: 'admin' } });+ render(<TripFormModal {...defaultProps} trip={buildTrip({ id: 1, user_id: 7, title: 'Locked' })} />);++ expect(screen.queryByText('Cover Image')).not.toBeInTheDocument();+ fireEvent.paste(document.querySelector('form')!, {+ clipboardData: { items: [{ type: 'image/png', getAsFile: () => pngFile() }] },+ });+ expect(createObjectURL).not.toHaveBeenCalled();+ });++ it('FE-COMP-TRIPFORM-064: without the edit permission the text fields are read-only', () => {+ seedStore(useAuthStore, { user: buildUser({ id: 7, role: 'user' }), isAuthenticated: true });+ seedStore(usePermissionsStore, { permissions: { trip_edit: 'admin' } });+ render(<TripFormModal {...defaultProps} trip={buildTrip({ id: 1, user_id: 7, title: 'Locked', description: 'read only' })} />);++ const title = screen.getByPlaceholderText(/Summer in Japan/i);+ expect(title).toHaveAttribute('readonly');+ fireEvent.change(title, { target: { value: 'Hacked' } });+ expect(title).toHaveValue('Locked');++ const desc = screen.getByPlaceholderText(/What is this trip about/i);+ fireEvent.change(desc, { target: { value: 'Hacked' } });+ expect(desc).toHaveValue('read only');+ });++ // ── Dates, day count, currency, reminder ──────────────────────────────────++ it('FE-COMP-TRIPFORM-065: setting a start date without an end date mirrors it', async () => {+ const user = userEvent.setup();+ const onSave = vi.fn().mockResolvedValue({});+ render(<TripFormModal {...defaultProps} trip={null} onSave={onSave} />);++ await user.type(screen.getByPlaceholderText(/Summer in Japan/i), 'Open Ended');+ await user.click(screen.getAllByRole('button', { name: 'Enter date manually' })[0]);+ const input = screen.getByPlaceholderText('DD.MM.YYYY');+ fireEvent.change(input, { target: { value: '2026-04-10' } });+ fireEvent.keyDown(input, { key: 'Enter' });++ // The day-count field disappears once the trip is dated.+ await waitFor(() => expect(document.querySelector('input[max="365"]')).toBeNull());+ await submitNewTrip(user);+ await waitFor(() => expect(onSave).toHaveBeenCalledWith(+ expect.objectContaining({ start_date: '2026-04-10', end_date: '2026-04-10' })+ ));+ });++ it('FE-COMP-TRIPFORM-066: an end date set first survives a later, earlier start date', async () => {+ const user = userEvent.setup();+ const onSave = vi.fn().mockResolvedValue({});+ render(<TripFormModal {...defaultProps} trip={null} onSave={onSave} />);++ await user.type(screen.getByPlaceholderText(/Summer in Japan/i), 'Backwards');++ await user.click(screen.getAllByRole('button', { name: 'Enter date manually' })[1]);+ const endInput = screen.getByPlaceholderText('DD.MM.YYYY');+ fireEvent.change(endInput, { target: { value: '2026-03-01' } });+ fireEvent.keyDown(endInput, { key: 'Enter' });++ await user.click(screen.getAllByRole('button', { name: 'Enter date manually' })[0]);+ const startInput = screen.getByPlaceholderText('DD.MM.YYYY');+ fireEvent.change(startInput, { target: { value: '2026-01-01' } });+ fireEvent.keyDown(startInput, { key: 'Enter' });++ await submitNewTrip(user);+ await waitFor(() => expect(onSave).toHaveBeenCalledWith(+ expect.objectContaining({ start_date: '2026-01-01', end_date: '2026-03-01' })+ ));+ });++ it('FE-COMP-TRIPFORM-067: the day count is clamped to the 1..365 range', async () => {+ const user = userEvent.setup();+ const onSave = vi.fn().mockResolvedValue({});+ render(<TripFormModal {...defaultProps} trip={null} onSave={onSave} />);++ const dayInput = document.querySelector('input[max="365"]') as HTMLInputElement;+ fireEvent.change(dayInput, { target: { value: '400' } });+ expect(dayInput.value).toBe('365');++ await user.type(screen.getByPlaceholderText(/Summer in Japan/i), 'Long Trip');+ await submitNewTrip(user);+ await waitFor(() => expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ day_count: 365 })));+ });++ it('FE-COMP-TRIPFORM-068: a currency without a known symbol is labelled with its code', () => {+ render(<TripFormModal {...defaultProps} trip={buildTrip({ id: 1, currency: 'XTS' })} />);+ expect(screen.getByText('XTS (XTS)')).toBeInTheDocument();+ });++ it('FE-COMP-TRIPFORM-069: a reminder preset is sent on save', async () => {+ const user = userEvent.setup();+ seedStore(useAuthStore, { tripRemindersEnabled: true });+ const onSave = vi.fn().mockResolvedValue({});+ render(<TripFormModal {...defaultProps} trip={null} onSave={onSave} />);++ await user.type(screen.getByPlaceholderText(/Summer in Japan/i), 'Reminder Trip');+ await user.click(screen.getByRole('button', { name: '9 days' }));+ await submitNewTrip(user);++ await waitFor(() => expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ reminder_days: 9 })));+ });++ it('FE-COMP-TRIPFORM-070: switching to a custom reminder seeds 7 and clamps an empty value to 1', async () => {+ const user = userEvent.setup();+ seedStore(useAuthStore, { tripRemindersEnabled: true });+ const onSave = vi.fn().mockResolvedValue({});+ render(<TripFormModal {...defaultProps} trip={null} onSave={onSave} />);++ await user.click(screen.getByRole('button', { name: 'Custom' }));+ const custom = document.querySelector('input[max="30"]') as HTMLInputElement;+ expect(custom.value).toBe('7');++ fireEvent.change(custom, { target: { value: '' } });+ expect(custom.value).toBe('1');++ await user.type(screen.getByPlaceholderText(/Summer in Japan/i), 'Custom Reminder');+ await submitNewTrip(user);+ await waitFor(() => expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ reminder_days: 1 })));+ });++ it('FE-COMP-TRIPFORM-071: a trip with a custom reminder opens on the Custom tab', async () => {+ seedStore(useAuthStore, { user: buildUser({ id: 1 }), tripRemindersEnabled: true });+ render(<TripFormModal {...defaultProps} trip={buildTrip({ id: 1, user_id: 1, reminder_days: 14 })} />);++ const custom = document.querySelector('input[max="30"]') as HTMLInputElement;+ expect(custom.value).toBe('14');+ });++ // ── Members while editing ─────────────────────────────────────────────────++ const editMembersServer = (members: { id: number; username: string }[]) => {+ server.use(+ http.get('/api/auth/users', () =>+ HttpResponse.json({ users: [{ id: 1, username: 'me' }, { id: 100, username: 'alice' }, { id: 200, username: 'bob' }] })+ ),+ http.get('/api/trips/1/members', () => HttpResponse.json({ members })),+ );+ };++ it('FE-COMP-TRIPFORM-072: clicking a member chip removes them, the own chip is inert', async () => {+ const user = userEvent.setup();+ seedStore(useAuthStore, { user: buildUser({ id: 1, username: 'me' }), isAuthenticated: true });+ let deletedId: string | null = null;+ editMembersServer([{ id: 1, username: 'me' }, { id: 100, username: 'alice' }]);+ server.use(+ http.delete('/api/trips/1/members/:userId', ({ params }) => {+ deletedId = params.userId as string;+ return HttpResponse.json({ success: true });+ }),+ );+ render(<TripFormModal {...defaultProps} trip={buildTrip({ id: 1, title: 'Crew' })} />);++ const own = await screen.findByText('me');+ await user.click(own);+ expect(deletedId).toBeNull();++ await user.click(screen.getByText('alice'));+ await waitFor(() => expect(deletedId).toBe('100'));+ expect(addToast).toHaveBeenCalledWith('alice removed', 'success', undefined);+ await waitFor(() => expect(screen.queryByText('alice')).not.toBeInTheDocument());+ });++ it('FE-COMP-TRIPFORM-073: a failing member removal keeps the chip', async () => {+ const user = userEvent.setup();+ seedStore(useAuthStore, { user: buildUser({ id: 1, username: 'me' }), isAuthenticated: true });+ editMembersServer([{ id: 100, username: 'alice' }]);+ server.use(http.delete('/api/trips/1/members/:userId', () => HttpResponse.json({}, { status: 500 })));+ render(<TripFormModal {...defaultProps} trip={buildTrip({ id: 1, title: 'Crew' })} />);++ await user.click(await screen.findByText('alice'));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Failed to remove', 'error', undefined));+ expect(screen.getByText('alice')).toBeInTheDocument();+ });++ it('FE-COMP-TRIPFORM-074: picking a user while editing adds them straight away', async () => {+ const user = userEvent.setup();+ seedStore(useAuthStore, { user: buildUser({ id: 1, username: 'me' }), isAuthenticated: true });+ let identifier: string | null = null;+ editMembersServer([{ id: 100, username: 'alice' }]);+ server.use(+ http.post('/api/trips/1/members', async ({ request }) => {+ identifier = ((await request.json()) as { identifier: string }).identifier;+ return HttpResponse.json({ success: true });+ }),+ );+ render(<TripFormModal {...defaultProps} trip={buildTrip({ id: 1, title: 'Crew' })} />);++ await screen.findByText('alice');+ await user.click(screen.getByText('Add member').closest('button')!);+ // alice is already a member, so only bob is offered.+ expect(screen.queryAllByRole('button', { name: 'alice' })).toHaveLength(0);+ await user.click(await screen.findByRole('button', { name: 'bob' }));++ await waitFor(() => expect(identifier).toBe('bob'));+ expect(addToast).toHaveBeenCalledWith('bob added', 'success', undefined);+ expect(screen.getByText('bob')).toBeInTheDocument();+ });++ it('FE-COMP-TRIPFORM-075: a failing member add while editing shows an error', async () => {+ const user = userEvent.setup();+ seedStore(useAuthStore, { user: buildUser({ id: 1, username: 'me' }), isAuthenticated: true });+ editMembersServer([{ id: 100, username: 'alice' }]);+ server.use(http.post('/api/trips/1/members', () => HttpResponse.json({}, { status: 500 })));+ render(<TripFormModal {...defaultProps} trip={buildTrip({ id: 1, title: 'Crew' })} />);++ await screen.findByText('alice');+ await user.click(screen.getByText('Add member').closest('button')!);+ await user.click(await screen.findByRole('button', { name: 'bob' }));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Failed to add', 'error', undefined));+ });++ // ── Save error paths ──────────────────────────────────────────────────────++ it('FE-COMP-TRIPFORM-076: a non-Error rejection falls back to the generic save error', async () => {+ const user = userEvent.setup();+ const onSave = vi.fn().mockRejectedValue('boom');+ render(<TripFormModal {...defaultProps} trip={null} onSave={onSave} />);++ await user.type(screen.getByPlaceholderText(/Summer in Japan/i), 'Broken');+ await submitNewTrip(user);++ await screen.findByText('Failed to save');+ });++ it('FE-COMP-TRIPFORM-077: a save error from the date-shift step is shown on that step', async () => {+ const user = userEvent.setup();+ const onSave = vi.fn().mockRejectedValue(new Error('Shift failed'));+ render(<TripFormModal {...defaultProps} trip={buildTrip({ id: 1, title: 'Dated', start_date: '2025-06-01', end_date: '2025-06-05' })} onSave={onSave} />);++ await changeStartDate(user, '2025-05-31');+ await user.click(screen.getByRole('button', { name: /Update/i }));+ await screen.findByText('Keep bookings on their dates');++ await user.click(screen.getByRole('button', { name: /Update/i }));++ await waitFor(() => expect(screen.getAllByText('Shift failed').length).toBeGreaterThan(0));+ expect(screen.getByText('Keep bookings on their dates')).toBeInTheDocument();+ });++ it('FE-COMP-TRIPFORM-078: the empty drop zone opens the hidden file picker', async () => {+ const user = userEvent.setup();+ render(<TripFormModal {...defaultProps} trip={null} />);++ const clickSpy = vi.spyOn(fileInput(), 'click').mockImplementation(() => {});+ await user.click(screen.getByRole('button', { name: /Add cover image/i }));++ expect(clickSpy).toHaveBeenCalled();+ });++ it('FE-COMP-TRIPFORM-079: a typed description is sent on save', async () => {+ const user = userEvent.setup();+ const onSave = vi.fn().mockResolvedValue({});+ render(<TripFormModal {...defaultProps} trip={null} onSave={onSave} />);++ await user.type(screen.getByPlaceholderText(/Summer in Japan/i), 'Described');+ await user.type(screen.getByPlaceholderText(/What is this trip about/i), ' Two weeks off ');+ await submitNewTrip(user);++ await waitFor(() => expect(onSave).toHaveBeenCalledWith(+ expect.objectContaining({ description: 'Two weeks off' })+ ));+ });++ it('FE-COMP-TRIPFORM-080: the cover button reports the upload while it runs', async () => {+ server.use(+ http.post('/api/trips/1/cover', async () => {+ await delay(30);+ return HttpResponse.json({ cover_image: '/uploads/covers/late.jpg' });+ }),+ );+ render(<TripFormModal {...defaultProps} trip={buildTrip({ id: 1, cover_image: '/uploads/covers/a.jpg' })} />);++ fireEvent.change(fileInput(), { target: { files: [pngFile()] } });++ await screen.findByText(/Uploading/);+ await waitFor(() => expect(screen.getByRole('button', { name: /Change/i })).toBeInTheDocument());+ expect(document.querySelector('img[src="/uploads/covers/late.jpg"]')).toBeInTheDocument();+ });++ // A slow first search must never overwrite the results of a newer one (#1277).+ it('FE-COMP-TRIPFORM-081: a stale successful search response is discarded', async () => {+ let staleResolved = false;+ server.use(+ http.get('/api/trips/cover-images/search', async ({ request }) => {+ const query = new URL(request.url).searchParams.get('query');+ if (query === 'slow') {+ await delay(60);+ staleResolved = true;+ return HttpResponse.json({ photos: [{ id: 's', url: 'https://img/s.jpg', thumb: 'https://img/st.jpg', photographer: 'Stale' }] });+ }+ return HttpResponse.json({ photos: [{ id: 'f', url: 'https://img/f.jpg', thumb: 'https://img/ft.jpg', photographer: 'Fresh' }] });+ }),+ );+ render(<TripFormModal {...defaultProps} trip={null} />);+ const search = screen.getByPlaceholderText('Search destination photos');++ fireEvent.change(search, { target: { value: 'slow' } });+ fireEvent.keyDown(search, { key: 'Enter' });+ fireEvent.change(search, { target: { value: 'fast' } });+ fireEvent.keyDown(search, { key: 'Enter' });++ await screen.findByRole('button', { name: /Use Unsplash photo by Fresh/i });+ await waitFor(() => expect(staleResolved).toBe(true));+ expect(screen.queryByRole('button', { name: /Use Unsplash photo by Stale/i })).not.toBeInTheDocument();+ });++ it('FE-COMP-TRIPFORM-082: a stale failing search does not clobber fresh results', async () => {+ let staleResolved = false;+ server.use(+ http.get('/api/trips/cover-images/search', async ({ request }) => {+ const query = new URL(request.url).searchParams.get('query');+ if (query === 'slow') {+ await delay(60);+ staleResolved = true;+ return HttpResponse.json({ error: 'Stale failure' }, { status: 500 });+ }+ return HttpResponse.json({ photos: [{ id: 'f', url: 'https://img/f.jpg', thumb: 'https://img/ft.jpg', photographer: 'Fresh' }] });+ }),+ );+ render(<TripFormModal {...defaultProps} trip={null} />);+ const search = screen.getByPlaceholderText('Search destination photos');++ fireEvent.change(search, { target: { value: 'slow' } });+ fireEvent.keyDown(search, { key: 'Enter' });+ fireEvent.change(search, { target: { value: 'fast' } });+ fireEvent.keyDown(search, { key: 'Enter' });++ await screen.findByRole('button', { name: /Use Unsplash photo by Fresh/i });+ await waitFor(() => expect(staleResolved).toBe(true));+ expect(screen.queryByText('Stale failure')).not.toBeInTheDocument();+ });});diff --git a/client/src/components/Trips/TripMembersModal.test.tsx b/client/src/components/Trips/TripMembersModal.test.tsxindex 962c9b8e1..8f7e93534 100644--- a/client/src/components/Trips/TripMembersModal.test.tsx+++ b/client/src/components/Trips/TripMembersModal.test.tsx@@ -1,7 +1,8 @@-// FE-COMP-MEMBERS-001 to FE-COMP-MEMBERS-025-import { render, screen, waitFor } from '../../../tests/helpers/render';+// FE-COMP-MEMBERS-001 to FE-COMP-MEMBERS-054+import type { Mock } from 'vitest';+import { act, render, screen, fireEvent, waitFor } from '../../../tests/helpers/render';import userEvent from '@testing-library/user-event';-import { http, HttpResponse } from 'msw';+import { delay, http, HttpResponse } from 'msw';import { server } from '../../../tests/helpers/msw/server';import { useAuthStore } from '../../store/authStore';import { useTripStore } from '../../store/tripStore';@@ -20,6 +21,38 @@ const defaultProps = {const ownerUser = buildUser({ id: 1, username: 'owner' });const memberUser = buildUser({ id: 2, username: 'alice' });+type AddToast = NonNullable<typeof window.__addToast>;+let addToast: Mock<AddToast>;++interface MemberRow {+ id: number;+ username: string;+ avatar_url?: string | null;+ is_guest?: boolean;+}++/** Replaces the roster handler; `owner` defaults to the seeded owner user. */+function mockRoster(members: MemberRow[], owner: MemberRow = { id: ownerUser.id, username: ownerUser.username, avatar_url: null }): void {+ server.use(+ http.get('/api/trips/1/members', () =>+ HttpResponse.json({ owner, members, current_user_id: ownerUser.id })+ ),+ );+}++/** Owner-only permissions so the share/invite column renders for the seeded owner. */+function asShareOwner(): void {+ seedStore(usePermissionsStore, { permissions: { share_manage: 'trip_owner' } });+ seedStore(useTripStore, { trip: buildTrip({ id: 1, user_id: ownerUser.id }) });+ server.use(http.get('/api/trips/1/invite-link', () => HttpResponse.json({ token: null })));+}++function mockClipboard(): Mock<(text: string) => Promise<void>> {+ const writeText = vi.fn(async () => {});+ Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });+ return writeText;+}+beforeEach(() => {resetAllStores();server.use(@@ -39,6 +72,14 @@ beforeEach(() => {);seedStore(useAuthStore, { user: ownerUser, isAuthenticated: true });seedStore(useTripStore, { trip: buildTrip({ id: 1, title: 'Test Trip' }) });+ addToast = vi.fn<AddToast>(() => 0);+ window.__addToast = addToast;+});++afterEach(() => {+ delete window.__addToast;+ vi.useRealTimers();+ vi.restoreAllMocks();});describe('TripMembersModal', () => {@@ -462,4 +503,482 @@ describe('TripMembersModal', () => {// Access count covers owner + the real member only (2), not the guest.expect(screen.getByText(/Access \(2/)).toBeInTheDocument();});++ // ── Avatars and load failures (028-031) ───────────────────────────────────++ it('FE-COMP-MEMBERS-028: a member with an avatar renders the image instead of the initial', async () => {+ mockRoster([{ id: 2, username: 'alice', avatar_url: '/uploads/avatars/alice.png' }]);+ render(<TripMembersModal {...defaultProps} />);++ await screen.findByText('alice');+ expect(document.querySelector('img[src="/uploads/avatars/alice.png"]')).toBeInTheDocument();+ // The owner has no avatar and still gets a letter tile.+ expect(screen.getByText('O')).toBeInTheDocument();+ });++ it('FE-COMP-MEMBERS-029: a nameless member falls back to a question mark', async () => {+ mockRoster([], { id: ownerUser.id, username: '', avatar_url: null });+ render(<TripMembersModal {...defaultProps} />);++ await screen.findByText('?');+ });++ it('FE-COMP-MEMBERS-030: a failing roster load shows an error toast and an empty list', async () => {+ server.use(http.get('/api/trips/1/members', () => HttpResponse.json({}, { status: 500 })));+ render(<TripMembersModal {...defaultProps} />);++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Failed to load members', 'error', undefined));+ expect(screen.getByText(/Access \(0/)).toBeInTheDocument();+ });++ it('FE-COMP-MEMBERS-031: a failing share-link load still offers link creation', async () => {+ asShareOwner();+ server.use(http.get('/api/trips/1/share-link', () => HttpResponse.json({}, { status: 500 })));+ render(<TripMembersModal {...defaultProps} />);++ await screen.findByText('Create link');+ expect(screen.getByText('Public Link')).toBeInTheDocument();+ });++ // ── Share link errors and defaults (032-036) ──────────────────────────────++ it('FE-COMP-MEMBERS-032: a failing share-link creation is reported', async () => {+ const user = userEvent.setup();+ asShareOwner();+ server.use(http.post('/api/trips/1/share-link', () => HttpResponse.json({}, { status: 500 })));+ render(<TripMembersModal {...defaultProps} />);++ await user.click(await screen.findByText('Create link'));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Could not create link', 'error', undefined));+ expect(screen.getByText('Create link')).toBeInTheDocument();+ });++ it('FE-COMP-MEMBERS-033: missing permission flags fall back to map+bookings, and Map is not toggleable', async () => {+ const user = userEvent.setup();+ asShareOwner();+ let postedPerms: Record<string, unknown> | null = null;+ server.use(+ http.get('/api/trips/1/share-link', () => HttpResponse.json({ token: 'tok77' })),+ http.post('/api/trips/1/share-link', async ({ request }) => {+ postedPerms = (await request.json()) as Record<string, unknown>;+ return HttpResponse.json({ token: 'tok77', ...postedPerms });+ }),+ );+ render(<TripMembersModal {...defaultProps} />);++ // The always-on Map & Plan pill ignores clicks.+ await user.click(await screen.findByText('Map & Plan'));+ expect(postedPerms).toBeNull();++ await user.click(screen.getByText('Costs'));+ await waitFor(() => expect(postedPerms).toMatchObject({+ share_map: true, share_bookings: true, share_packing: false, share_budget: true, share_collab: false,+ }));+ });++ it('FE-COMP-MEMBERS-034: a failing permission update is reported', async () => {+ const user = userEvent.setup();+ asShareOwner();+ server.use(+ http.get('/api/trips/1/share-link', () => HttpResponse.json({ token: 'tok77' })),+ http.post('/api/trips/1/share-link', () => HttpResponse.json({}, { status: 500 })),+ );+ render(<TripMembersModal {...defaultProps} />);++ await user.click(await screen.findByText('Packing'));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Could not create link', 'error', undefined));+ });++ it('FE-COMP-MEMBERS-035: a failing share-link deletion keeps the link', async () => {+ const user = userEvent.setup();+ asShareOwner();+ server.use(+ http.get('/api/trips/1/share-link', () => HttpResponse.json({ token: 'tok77' })),+ http.delete('/api/trips/1/share-link', () => HttpResponse.json({}, { status: 500 })),+ );+ render(<TripMembersModal {...defaultProps} />);++ await user.click(await screen.findByText('Delete link'));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));+ expect(screen.getByDisplayValue(/\/shared\/tok77/)).toBeInTheDocument();+ });++ it('FE-COMP-MEMBERS-036: the copied badge resets two seconds after the last copy', async () => {+ asShareOwner();+ const writeText = mockClipboard();+ server.use(http.get('/api/trips/1/share-link', () => HttpResponse.json({ token: 'tok77' })));+ const view = render(<TripMembersModal {...defaultProps} />);++ const copyBtn = (await screen.findByText('Copy')).closest('button')!;++ vi.useFakeTimers();+ fireEvent.click(copyBtn);+ expect(screen.getByText('Copied')).toBeInTheDocument();+ // A second copy replaces the pending reset rather than stacking timers.+ fireEvent.click(screen.getByText('Copied').closest('button')!);+ act(() => { vi.advanceTimersByTime(2000); });++ expect(screen.getByText('Copy')).toBeInTheDocument();+ expect(writeText).toHaveBeenCalledTimes(2);+ view.unmount();+ });++ // ── Trip invite link (037-039) ────────────────────────────────────────────++ it('FE-COMP-MEMBERS-037: an invite link can be created, copied, regenerated and disabled', async () => {+ const user = userEvent.setup();+ asShareOwner();+ const writeText = mockClipboard();+ const tokens = ['inv1', 'inv2'];+ server.use(+ http.post('/api/trips/1/invite-link', async () => {+ await delay(20);+ return HttpResponse.json({ token: tokens.shift() });+ }),+ http.delete('/api/trips/1/invite-link', () => HttpResponse.json({ success: true })),+ );+ const view = render(<TripMembersModal {...defaultProps} />);++ const createBtn = await screen.findByRole('button', { name: /Create invite link/i });+ fireEvent.click(createBtn);+ expect(createBtn).toBeDisabled();++ await screen.findByDisplayValue(/\/join\/inv1$/);++ await user.click(screen.getByText('Copy').closest('button')!);+ expect(writeText).toHaveBeenCalledWith(expect.stringContaining('/join/inv1'));+ await screen.findByText('Copied');+ // Copying again swaps the pending reset instead of queueing a second one.+ await user.click(screen.getByText('Copied').closest('button')!);++ const regenerate = screen.getByRole('button', { name: /Regenerate/i });+ fireEvent.click(regenerate);+ expect(regenerate).toBeDisabled();+ expect(screen.getByRole('button', { name: /Disable/i })).toBeDisabled();+ await screen.findByDisplayValue(/\/join\/inv2$/);++ await user.click(screen.getByRole('button', { name: /Disable/i }));+ await screen.findByRole('button', { name: /Create invite link/i });++ view.unmount();+ });++ it('FE-COMP-MEMBERS-038: a failing invite-link creation is reported', async () => {+ const user = userEvent.setup();+ asShareOwner();+ server.use(http.post('/api/trips/1/invite-link', () => HttpResponse.json({}, { status: 500 })));+ render(<TripMembersModal {...defaultProps} />);++ await user.click(await screen.findByRole('button', { name: /Create invite link/i }));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Could not create link', 'error', undefined));+ expect(screen.getByRole('button', { name: /Create invite link/i })).toBeEnabled();+ });++ it('FE-COMP-MEMBERS-039: a failing invite-link removal keeps the link', async () => {+ const user = userEvent.setup();+ asShareOwner();+ server.use(+ http.get('/api/trips/1/invite-link', () => HttpResponse.json({ token: 'inv9' })),+ http.delete('/api/trips/1/invite-link', () => HttpResponse.json({}, { status: 500 })),+ );+ render(<TripMembersModal {...defaultProps} />);++ await user.click(await screen.findByRole('button', { name: /Disable/i }));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Error', 'error', undefined));+ expect(screen.getByDisplayValue(/\/join\/inv9$/)).toBeInTheDocument();+ });++ // ── Member management errors and ownership transfer (040-045) ─────────────++ it('FE-COMP-MEMBERS-040: a failing invite surfaces the server error', async () => {+ const user = userEvent.setup();+ server.use(http.post('/api/trips/1/members', () => HttpResponse.json({ error: 'User is already a member' }, { status: 409 })));+ render(<TripMembersModal {...defaultProps} />);++ await screen.findByText('Invite User');+ await user.click(screen.getByText('Select user…'));+ await user.click(await screen.findByRole('button', { name: 'alice' }));+ await user.click(screen.getByRole('button', { name: 'Invite' }));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('User is already a member', 'error', undefined));+ });++ it('FE-COMP-MEMBERS-041: a successful invite reloads the roster and notifies the planner', async () => {+ const user = userEvent.setup();+ const onMembersChanged = vi.fn();+ server.use(http.post('/api/trips/1/members', () => HttpResponse.json({ success: true })));+ render(<TripMembersModal {...defaultProps} onMembersChanged={onMembersChanged} />);++ await screen.findByText('Invite User');+ await user.click(screen.getByText('Select user…'));+ await user.click(await screen.findByRole('button', { name: 'alice' }));+ await user.click(screen.getByRole('button', { name: 'Invite' }));++ await waitFor(() => expect(onMembersChanged).toHaveBeenCalled());+ expect(addToast).toHaveBeenCalledWith('alice added', 'success', undefined);+ });++ it('FE-COMP-MEMBERS-042: transferring ownership reloads the app', async () => {+ const user = userEvent.setup();+ const onClose = vi.fn();+ const reload = vi.fn();+ Object.defineProperty(window, 'location', { value: { ...window.location, reload }, writable: true, configurable: true });+ vi.spyOn(window, 'confirm').mockReturnValue(true);+ mockRoster([{ id: memberUser.id, username: 'alice', avatar_url: null }]);+ let transferBody: Record<string, unknown> | null = null;+ server.use(+ http.post('/api/trips/1/transfer', async ({ request }) => {+ transferBody = (await request.json()) as Record<string, unknown>;+ await delay(20);+ return HttpResponse.json({ success: true });+ }),+ );+ render(<TripMembersModal {...defaultProps} onClose={onClose} />);++ const crown = await screen.findByTitle('Make owner');+ fireEvent.click(crown);+ expect(crown).toBeDisabled();++ await waitFor(() => expect(reload).toHaveBeenCalled());+ expect(transferBody).toMatchObject({ newOwnerId: memberUser.id });+ expect(onClose).toHaveBeenCalled();+ });++ it('FE-COMP-MEMBERS-043: declining the transfer confirmation does nothing', async () => {+ const user = userEvent.setup();+ vi.spyOn(window, 'confirm').mockReturnValue(false);+ mockRoster([{ id: memberUser.id, username: 'alice', avatar_url: null }]);+ let transferCalled = false;+ server.use(http.post('/api/trips/1/transfer', () => { transferCalled = true; return HttpResponse.json({}); }));+ render(<TripMembersModal {...defaultProps} />);++ const crown = await screen.findByTitle('Make owner');+ fireEvent.mouseEnter(crown);+ expect(crown.style.color).toBe('rgb(217, 119, 6)');+ fireEvent.mouseLeave(crown);+ expect(crown.style.color).toBe('rgb(156, 163, 175)');++ await user.click(crown);++ expect(transferCalled).toBe(false);+ expect(window.confirm).toHaveBeenCalledWith('Transfer ownership to alice? You will become a regular member.');+ });++ it('FE-COMP-MEMBERS-044: a failing transfer re-enables the button', async () => {+ const user = userEvent.setup();+ vi.spyOn(window, 'confirm').mockReturnValue(true);+ mockRoster([{ id: memberUser.id, username: 'alice', avatar_url: null }]);+ server.use(http.post('/api/trips/1/transfer', () => HttpResponse.json({ error: 'Not allowed' }, { status: 403 })));+ render(<TripMembersModal {...defaultProps} />);++ await user.click(await screen.findByTitle('Make owner'));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Not allowed', 'error', undefined));+ expect(screen.getByTitle('Make owner')).toBeEnabled();+ });++ it('FE-COMP-MEMBERS-045: member removal is cancellable and reports failures', async () => {+ const user = userEvent.setup();+ const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);+ mockRoster([{ id: memberUser.id, username: 'alice', avatar_url: null }]);+ let deletes = 0;+ server.use(http.delete('/api/trips/1/members/:userId', () => { deletes++; return HttpResponse.json({}, { status: 500 }); }));+ render(<TripMembersModal {...defaultProps} />);++ const removeBtn = await screen.findByTitle('Remove access');+ fireEvent.mouseEnter(removeBtn);+ expect(removeBtn.style.color).toBe('rgb(239, 68, 68)');+ fireEvent.mouseLeave(removeBtn);+ expect(removeBtn.style.color).toBe('rgb(156, 163, 175)');++ await user.click(removeBtn);+ expect(deletes).toBe(0);++ confirmSpy.mockReturnValue(true);+ await user.click(screen.getByTitle('Remove access'));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Failed to remove', 'error', undefined));+ expect(screen.getByText('alice')).toBeInTheDocument();+ });++ // ── Guests (046-051) ──────────────────────────────────────────────────────++ const guestRow = { id: 3, username: 'Grandma', avatar_url: null, is_guest: true };++ it('FE-COMP-MEMBERS-046: pressing Enter adds a guest, an empty name is ignored', async () => {+ const user = userEvent.setup();+ const onMembersChanged = vi.fn();+ let createdName: string | null = null;+ server.use(+ http.post('/api/trips/1/guests', async ({ request }) => {+ createdName = ((await request.json()) as { name: string }).name;+ return HttpResponse.json({ member: { id: 9, username: createdName, is_guest: true } });+ }),+ );+ render(<TripMembersModal {...defaultProps} onMembersChanged={onMembersChanged} />);++ const input = await screen.findByPlaceholderText('Guest name');+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(createdName).toBeNull();++ await user.type(input, 'Grandpa');+ fireEvent.keyDown(input, { key: 'Enter' });++ await waitFor(() => expect(createdName).toBe('Grandpa'));+ expect(addToast).toHaveBeenCalledWith('Guest added', 'success', undefined);+ await waitFor(() => expect(onMembersChanged).toHaveBeenCalled());+ });++ it('FE-COMP-MEMBERS-047: a failing guest creation is reported', async () => {+ const user = userEvent.setup();+ server.use(http.post('/api/trips/1/guests', () => HttpResponse.json({ error: 'Guest limit reached' }, { status: 400 })));+ render(<TripMembersModal {...defaultProps} />);++ await user.type(await screen.findByPlaceholderText('Guest name'), 'Grandpa');+ await user.click(screen.getByRole('button', { name: /Add guest/i }));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Guest limit reached', 'error', undefined));+ });++ it('FE-COMP-MEMBERS-048: renaming a guest saves on Enter', async () => {+ const user = userEvent.setup();+ mockRoster([guestRow]);+ let renamed: { id: string; name: string } | null = null;+ server.use(+ http.put('/api/trips/1/guests/:userId', async ({ params, request }) => {+ renamed = { id: params.userId as string, name: ((await request.json()) as { name: string }).name };+ return HttpResponse.json({ success: true });+ }),+ );+ render(<TripMembersModal {...defaultProps} />);++ const pencil = await screen.findByTitle('Rename');+ fireEvent.mouseEnter(pencil);+ fireEvent.mouseLeave(pencil);+ await user.click(pencil);++ const input = screen.getByDisplayValue('Grandma');+ fireEvent.change(input, { target: { value: 'Granny' } });+ fireEvent.keyDown(input, { key: 'Enter' });++ await waitFor(() => expect(renamed).toEqual({ id: '3', name: 'Granny' }));+ await waitFor(() => expect(screen.queryByDisplayValue('Granny')).not.toBeInTheDocument());+ });++ it('FE-COMP-MEMBERS-049: Escape cancels a rename and a blank name saves nothing', async () => {+ const user = userEvent.setup();+ mockRoster([guestRow]);+ let renames = 0;+ server.use(http.put('/api/trips/1/guests/:userId', () => { renames++; return HttpResponse.json({ success: true }); }));+ render(<TripMembersModal {...defaultProps} />);++ await user.click(await screen.findByTitle('Rename'));+ fireEvent.keyDown(screen.getByDisplayValue('Grandma'), { key: 'Escape' });+ expect(screen.queryByDisplayValue('Grandma')).not.toBeInTheDocument();++ await user.click(screen.getByTitle('Rename'));+ const input = screen.getByDisplayValue('Grandma');+ fireEvent.change(input, { target: { value: ' ' } });+ fireEvent.blur(input);++ await waitFor(() => expect(screen.queryByDisplayValue(' ')).not.toBeInTheDocument());+ expect(renames).toBe(0);+ });++ it('FE-COMP-MEMBERS-050: a failing rename is reported', async () => {+ const user = userEvent.setup();+ mockRoster([guestRow]);+ server.use(http.put('/api/trips/1/guests/:userId', () => HttpResponse.json({ error: 'Name taken' }, { status: 409 })));+ render(<TripMembersModal {...defaultProps} />);++ await user.click(await screen.findByTitle('Rename'));+ const input = screen.getByDisplayValue('Grandma');+ fireEvent.change(input, { target: { value: 'Granny' } });+ fireEvent.keyDown(input, { key: 'Enter' });++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Name taken', 'error', undefined));+ });++ it('FE-COMP-MEMBERS-051: removing a guest is confirmed, refreshes costs and notifies', async () => {+ const user = userEvent.setup();+ const onMembersChanged = vi.fn();+ const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);+ mockRoster([guestRow]);+ let deletedId: string | null = null;+ server.use(+ http.delete('/api/trips/1/guests/:userId', async ({ params }) => {+ deletedId = params.userId as string;+ await delay(20);+ return HttpResponse.json({ success: true });+ }),+ );+ render(<TripMembersModal {...defaultProps} onMembersChanged={onMembersChanged} />);++ const trash = await screen.findByTitle('Remove access');+ fireEvent.mouseEnter(trash);+ fireEvent.mouseLeave(trash);+ await user.click(trash);+ expect(deletedId).toBeNull();++ confirmSpy.mockReturnValue(true);+ fireEvent.click(screen.getByTitle('Remove access'));+ await waitFor(() => expect(screen.getByTitle('Remove access')).toBeDisabled());++ await waitFor(() => expect(deletedId).toBe('3'));+ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Guest removed', 'success', undefined));+ expect(onMembersChanged).toHaveBeenCalled();+ });++ it('FE-COMP-MEMBERS-052: a failing guest removal is reported', async () => {+ const user = userEvent.setup();+ vi.spyOn(window, 'confirm').mockReturnValue(true);+ mockRoster([guestRow]);+ server.use(http.delete('/api/trips/1/guests/:userId', () => HttpResponse.json({}, { status: 500 })));+ render(<TripMembersModal {...defaultProps} />);++ await user.click(await screen.findByTitle('Remove access'));++ await waitFor(() => expect(addToast).toHaveBeenCalledWith('Failed to remove', 'error', undefined));+ expect(screen.getByText('Grandma')).toBeInTheDocument();+ });++ it('FE-COMP-MEMBERS-053: without member_manage a plain member sees no invite or guest controls', async () => {+ const stranger = buildUser({ id: 99, username: 'stranger' });+ seedStore(useAuthStore, { user: stranger, isAuthenticated: true });+ seedStore(useTripStore, { trip: buildTrip({ id: 1, user_id: ownerUser.id }) });+ seedStore(usePermissionsStore, { permissions: { member_manage: 'trip_owner', share_manage: 'trip_owner' } });+ mockRoster([{ id: memberUser.id, username: 'alice', avatar_url: null }]);+ render(<TripMembersModal {...defaultProps} />);++ await screen.findByText('alice');+ expect(screen.queryByText('Invite User')).not.toBeInTheDocument();+ expect(screen.queryByPlaceholderText('Guest name')).not.toBeInTheDocument();+ expect(screen.queryByText('Guests')).not.toBeInTheDocument();+ expect(screen.queryByText('Public Link')).not.toBeInTheDocument();+ // Nothing to remove either — a plain member can only leave themselves.+ expect(screen.queryByTitle('Remove access')).not.toBeInTheDocument();+ });++ it('FE-COMP-MEMBERS-054: the invite-link copied badge resets after two seconds', async () => {+ asShareOwner();+ const writeText = mockClipboard();+ server.use(http.get('/api/trips/1/invite-link', () => HttpResponse.json({ token: 'inv9' })));+ const view = render(<TripMembersModal {...defaultProps} />);++ const copyBtn = (await screen.findByText('Copy')).closest('button')!;++ vi.useFakeTimers();+ fireEvent.click(copyBtn);+ expect(screen.getByText('Copied')).toBeInTheDocument();+ act(() => { vi.advanceTimersByTime(2000); });++ expect(screen.getByText('Copy')).toBeInTheDocument();+ expect(writeText).toHaveBeenCalledWith(expect.stringContaining('/join/inv9'));+ view.unmount();+ });});diff --git a/client/src/components/Vacay/VacayCalendar.overlays.test.tsx b/client/src/components/Vacay/VacayCalendar.overlays.test.tsxnew file mode 100644index 000000000..7df0aae4f--- /dev/null+++ b/client/src/components/Vacay/VacayCalendar.overlays.test.tsx@@ -0,0 +1,275 @@+// FE-COMP-VCYCAL-001 to FE-COMP-VCYCAL-010+// Covers what the mocked month card in VacayCalendar.test.tsx cannot reach: the+// trip overlay, the per-day maps handed down to the cards, and the hover tooltip.+import React from 'react'+import { describe, it, expect, beforeEach, vi } from 'vitest'+import { http, HttpResponse } from 'msw'+import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render'+import { server } from '../../../tests/helpers/msw/server'+import { resetAllStores } from '../../../tests/helpers/store'+import { useVacayStore } from '../../store/vacayStore'+import VacayCalendar from './VacayCalendar'+import type { HolidaysMap, VacayEntry, VacayPlan } from '../../types'++interface MonthCardStubProps {+ month: number+ entryMap: Record<string, VacayEntry[]>+ sharedMap?: Record<string, { color: string }[]>+ companyHolidaySet: Set<string>+ tripDates?: Set<string>+ onCellClick: (date: string) => void+ onCellHover?: (date: string | null, el: HTMLElement | null) => void+}++vi.mock('./VacayMonthCard', () => ({+ default: ({ month, entryMap, sharedMap, companyHolidaySet, tripDates, onCellClick, onCellHover }: MonthCardStubProps) => (+ <div+ data-testid={`card-${month}`}+ data-entries={JSON.stringify(entryMap)}+ data-shared={JSON.stringify(sharedMap)}+ data-company={JSON.stringify([...companyHolidaySet])}+ data-trips={JSON.stringify([...(tripDates ?? [])].sort())}+ >+ <button type="button" onClick={() => onCellClick(`2026-${String(month + 1).padStart(2, '0')}-13`)}>sat-{month}</button>+ <button type="button" onClick={() => onCellClick(`2026-${String(month + 1).padStart(2, '0')}-15`)}>mon-{month}</button>+ <button type="button" onClick={() => onCellClick('2026-12-24')}>company-{month}</button>+ <button type="button" onClick={e => onCellHover?.('2026-06-15', e.currentTarget)}>hover-{month}</button>+ <button type="button" onClick={() => onCellHover?.(null, null)}>unhover-{month}</button>+ </div>+ ),+}))++function buildPlan(over: Partial<VacayPlan> = {}): VacayPlan {+ return {+ id: 1,+ holidays_enabled: false,+ holidays_region: null,+ holiday_calendars: [],+ block_weekends: true,+ carry_over_enabled: false,+ company_holidays_enabled: true,+ ...over,+ }+}++function tripsRespond(trips: { start_date?: string | null; end_date?: string | null }[]) {+ server.use(http.get('/api/trips', () => HttpResponse.json({ trips })))+}++const schoolHolidays: HolidaysMap = {+ '2026-06-15': [+ { name: 'Sommerferien', localName: 'Sommerferien', color: '#bbf7d0', label: 'NRW', type: 'school_holiday' },+ { name: 'Christmas', localName: 'Weihnachten', color: '#fecaca', label: null, type: 'public_holiday' },+ ],+}++beforeEach(() => {+ resetAllStores()+ tripsRespond([])+ useVacayStore.setState({ selectedYear: 2026, plan: buildPlan() })+})++/** Reads a JSON prop off the first stubbed month card. */+function cardProp(name: string): unknown {+ return JSON.parse(screen.getByTestId('card-0').getAttribute(name) as string)+}++describe('VacayCalendar overlays', () => {+ it('FE-COMP-VCYCAL-001: collects trip days inside the window and skips open-ended trips', async () => {+ tripsRespond([+ { start_date: '2026-03-30', end_date: '2026-04-01' },+ { start_date: '2026-05-01', end_date: null },+ { start_date: '2025-12-31', end_date: '2025-12-31' },+ ])+ render(<VacayCalendar />)++ await waitFor(() => expect(cardProp('data-trips')).toEqual(['2026-03-30', '2026-03-31', '2026-04-01']))+ })++ it('FE-COMP-VCYCAL-002: a failing trip list leaves the overlay empty', async () => {+ server.use(http.get('/api/trips', () => HttpResponse.json({ error: 'boom' }, { status: 500 })))+ render(<VacayCalendar />)++ await waitFor(() => expect(cardProp('data-trips')).toEqual([]))+ })++ it('FE-COMP-VCYCAL-003: groups entries and company holidays per day for the cards', () => {+ useVacayStore.setState({+ entries: [+ { date: '2026-06-15', user_id: 1, person_name: 'alice', person_color: '#3b82f6' },+ { date: '2026-06-15', user_id: 2, person_name: 'bob', person_color: '#ec4899', fraction: 0.5 },+ { date: '2026-06-16', user_id: 1 },+ ],+ companyHolidays: [{ date: '2026-12-24' }, { date: '2026-12-31' }],+ })+ render(<VacayCalendar />)++ const entryMap = cardProp('data-entries') as Record<string, VacayEntry[]>+ expect(entryMap['2026-06-15']).toHaveLength(2)+ expect(entryMap['2026-06-16']).toHaveLength(1)+ expect(cardProp('data-company')).toEqual(['2026-12-24', '2026-12-31'])+ })++ it('FE-COMP-VCYCAL-004: visible shared calendars contribute entries and company days as rings', () => {+ useVacayStore.setState({+ sharedCalendars: [+ {+ share_id: 1, owner_id: 3, owner_name: 'carol', color: '#f59e0b', hidden: false,+ entries: [{ date: '2026-06-15', fraction: 0.5, kind: 'comp' }],+ companyHolidays: [{ date: '2026-12-24' }],+ },+ {+ share_id: 2, owner_id: 4, owner_name: 'dan', color: '#10b981', hidden: true,+ entries: [{ date: '2026-06-16' }], companyHolidays: [],+ },+ ],+ })+ render(<VacayCalendar />)++ const sharedMap = cardProp('data-shared') as Record<string, { color: string; name: string; company?: boolean }[]>+ expect(sharedMap['2026-06-15']).toEqual([{ color: '#f59e0b', name: 'carol', fraction: 0.5, kind: 'comp' }])+ expect(sharedMap['2026-12-24']).toEqual([{ color: '#f59e0b', name: 'carol', company: true }])+ expect(sharedMap['2026-06-16']).toBeUndefined()+ })++ it('FE-COMP-VCYCAL-005: blocked weekends and company days swallow the click', async () => {+ const toggleEntry = vi.fn(async (_d: string, _u?: number, _f?: 0.5 | 1, _k?: 'vacation' | 'comp') => {})+ useVacayStore.setState({ toggleEntry, companyHolidays: [{ date: '2026-12-24' }], selectedUserId: 7 })+ render(<VacayCalendar />)++ // 2026-06-13 is a Saturday, and 2026-12-24 is a company holiday.+ fireEvent.click(screen.getByText('sat-5'))+ fireEvent.click(screen.getByText('company-5'))+ expect(toggleEntry).not.toHaveBeenCalled()++ fireEvent.click(screen.getByText('mon-5'))+ await waitFor(() => expect(toggleEntry).toHaveBeenCalledWith('2026-06-15', 7, 1, 'vacation'))+ })++ it('FE-COMP-VCYCAL-006: the toolbar modifiers are applied to the logged day', async () => {+ const toggleEntry = vi.fn(async (_d: string, _u?: number, _f?: 0.5 | 1, _k?: 'vacation' | 'comp') => {})+ useVacayStore.setState({ toggleEntry, plan: buildPlan({ block_weekends: false }) })+ render(<VacayCalendar />)++ fireEvent.click(screen.getByRole('button', { name: 'Comp / Flex' }))+ fireEvent.click(screen.getByRole('button', { name: 'Half day' }))+ fireEvent.click(screen.getByText('mon-5'))++ await waitFor(() => expect(toggleEntry).toHaveBeenCalledWith('2026-06-15', undefined, 0.5, 'comp'))+ })++ it('FE-COMP-VCYCAL-007: company mode toggles a company day, and does nothing while disabled', async () => {+ const toggleCompanyHoliday = vi.fn(async (_date: string) => {})+ useVacayStore.setState({ toggleCompanyHoliday, plan: buildPlan({ company_holidays_enabled: false }) })+ const { rerender } = render(<VacayCalendar />)++ // Without company holidays the mode button is not offered at all.+ expect(screen.queryByRole('button', { name: 'Company Holiday' })).not.toBeInTheDocument()++ useVacayStore.setState({ plan: buildPlan({ company_holidays_enabled: true }) })+ rerender(<VacayCalendar />)+ fireEvent.click(screen.getByRole('button', { name: 'Company Holiday' }))+ fireEvent.click(screen.getByText('company-5'))++ await waitFor(() => expect(toggleCompanyHoliday).toHaveBeenCalledWith('2026-12-24'))+ })++ it('FE-COMP-VCYCAL-007b: company mode left over from an enabled plan stops logging', async () => {+ const toggleCompanyHoliday = vi.fn(async (_date: string) => {})+ useVacayStore.setState({ toggleCompanyHoliday })+ const { rerender } = render(<VacayCalendar />)++ fireEvent.click(screen.getByRole('button', { name: 'Company Holiday' }))+ useVacayStore.setState({ plan: buildPlan({ company_holidays_enabled: false }) })+ rerender(<VacayCalendar />)++ fireEvent.click(screen.getByText('company-5'))+ expect(toggleCompanyHoliday).not.toHaveBeenCalled()+ })++ it('FE-COMP-VCYCAL-007c: the toolbar switches back to logging the selected person', () => {+ render(<VacayCalendar />)++ fireEvent.click(screen.getByRole('button', { name: 'Company Holiday' }))+ fireEvent.click(screen.getByRole('button', { name: 'Vacation' }))+ // Back in vacation mode the person button is the active one.+ expect(screen.getByRole('button', { name: 'Vacation' }).style.background).toBe('var(--vg-ink)')+ })++ it('FE-COMP-VCYCAL-008: hovering a logged day explains who is off and how much', () => {+ useVacayStore.setState({+ entries: [+ { date: '2026-06-15', user_id: 1, person_name: 'alice', person_color: '#3b82f6' },+ { date: '2026-06-15', user_id: 2, person_name: 'bob', person_color: '#ec4899', fraction: 0.5 },+ { date: '2026-06-15', user_id: 3, person_name: 'carol', person_color: '#10b981', kind: 'comp' },+ { date: '2026-06-15', user_id: 4, person_name: 'dan', person_color: '#f59e0b', fraction: 0.5, kind: 'comp' },+ ],+ })+ render(<VacayCalendar />)++ fireEvent.click(screen.getByText('hover-5'))+ const tip = screen.getByText('alice').closest('.vg-card') as HTMLElement++ expect(within(tip).getByText('Full day')).toBeInTheDocument()+ expect(within(tip).getByText('Half day')).toBeInTheDocument()+ expect(within(tip).getByText('Comp / Flex')).toBeInTheDocument()+ expect(within(tip).getByText('Half comp day')).toBeInTheDocument()++ fireEvent.click(screen.getByText('unhover-5'))+ expect(screen.queryByText('alice')).not.toBeInTheDocument()+ })++ it('FE-COMP-VCYCAL-009: the tooltip lists shared calendars as their own rows', () => {+ useVacayStore.setState({+ sharedCalendars: [{+ share_id: 1, owner_id: 3, owner_name: 'carol', color: '#f59e0b', hidden: false,+ entries: [{ date: '2026-06-15', fraction: 0.5 }],+ companyHolidays: [{ date: '2026-06-15' }],+ }],+ })+ render(<VacayCalendar />)++ fireEvent.click(screen.getByText('hover-5'))+ const tip = screen.getAllByText('carol')[0].closest('.vg-card') as HTMLElement++ expect(within(tip).getByText('Half day')).toBeInTheDocument()+ expect(within(tip).getByText('Company Holiday')).toBeInTheDocument()+ })++ it('FE-COMP-VCYCAL-010: school breaks are folded into the tooltip under a heading', () => {+ useVacayStore.setState({+ holidays: schoolHolidays,+ entries: [{ date: '2026-06-15', user_id: 1, person_name: 'alice', person_color: '#3b82f6' }],+ })+ render(<VacayCalendar />)++ fireEvent.click(screen.getByText('hover-5'))+ const tip = screen.getByText('alice').closest('.vg-card') as HTMLElement++ expect(within(tip).getByText('School Holidays')).toBeInTheDocument()+ expect(within(tip).getByText('NRW: Sommerferien')).toBeInTheDocument()+ // The public-holiday marker on the same day is not part of the school block.+ expect(within(tip).queryByText('Weihnachten')).not.toBeInTheDocument()+ })++ it('FE-COMP-VCYCAL-011: a single unlabelled school marker still renders its local name', () => {+ useVacayStore.setState({+ holidays: {+ '2026-06-15': { name: 'Herfstvakantie', localName: 'Herfstvakantie', color: '#bbf7d0', label: null, type: 'school_holiday' },+ },+ })+ render(<VacayCalendar />)++ fireEvent.click(screen.getByText('hover-5'))+ expect(screen.getByText('Herfstvakantie')).toBeInTheDocument()+ expect(screen.getByText('School Holidays')).toBeInTheDocument()+ })++ it('FE-COMP-VCYCAL-012: a day with nothing to explain shows no tooltip', () => {+ render(<VacayCalendar />)++ fireEvent.click(screen.getByText('hover-5'))+ expect(screen.queryByText('School Holidays')).not.toBeInTheDocument()+ expect(document.querySelectorAll('.vg-card.rounded-xl')).toHaveLength(0)+ })+})diff --git a/client/src/components/Vacay/VacayMonthCard.rings.test.tsx b/client/src/components/Vacay/VacayMonthCard.rings.test.tsxnew file mode 100644index 000000000..8d1c4b2c6--- /dev/null+++ b/client/src/components/Vacay/VacayMonthCard.rings.test.tsx@@ -0,0 +1,117 @@+// FE-COMP-VCYMC-001 to FE-COMP-VCYMC-004+import React from 'react'+import { describe, it, expect, vi } from 'vitest'+import { render, screen, fireEvent, within } from '../../../tests/helpers/render'+import VacayMonthCard from './VacayMonthCard'+import type { HolidaysMap, VacayEntry } from '../../types'++interface CardProps {+ entryMap?: Record<string, VacayEntry[]>+ sharedMap?: Record<string, { color: string }[]>+ holidays?: HolidaysMap+ companyHolidaySet?: Set<string>+ weekStart?: number+ onCellHover?: (date: string | null, el: HTMLElement | null) => void+}++function renderCard(over: CardProps & { year?: number; month?: number } = {}) {+ const {+ entryMap = {}, sharedMap, holidays = {}, companyHolidaySet = new Set<string>(),+ weekStart = 1, onCellHover, year = 2026, month = 5,+ } = over+ return render(+ <VacayMonthCard+ year={year}+ month={month}+ holidays={holidays}+ companyHolidaySet={companyHolidaySet}+ entryMap={entryMap}+ sharedMap={sharedMap}+ onCellClick={() => {}}+ onCellHover={onCellHover}+ companyMode={false}+ blockWeekends={false}+ weekStart={weekStart}+ />,+ )+}++/** Day cells carry the number as their only text. */+function cell(day: number): HTMLElement {+ return screen.getByText(String(day)).closest('div[style]') as HTMLElement+}++/** Position of the 1st inside the day grid — the lead depends on the week start. */+function firstOfMonthSlot(container: HTMLElement): number {+ const first = within(container).getByText('1')+ const grid = first.closest('.grid') as HTMLElement+ return [...grid.children].findIndex(c => c.contains(first))+}++describe('VacayMonthCard rings', () => {+ it('FE-COMP-VCYMC-001: a Sunday week start pushes the 1st one slot further', () => {+ // 2026-06-01 is a Monday: first slot with Monday first, second with Sunday first.+ expect(firstOfMonthSlot(renderCard().container)).toBe(0)+ expect(firstOfMonthSlot(renderCard({ weekStart: 0 }).container)).toBe(1)+ })++ it('FE-COMP-VCYMC-001b: a month starting on Sunday fills a whole leading week', () => {+ // 2026-02-01 is a Sunday, so a Monday-first grid needs six blanks in front.+ expect(firstOfMonthSlot(renderCard({ month: 1 }).container)).toBe(6)+ })++ it('FE-COMP-VCYMC-001c: today is outlined, nested inside any shared rings', () => {+ const now = new Date()+ const today = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`+ renderCard({+ year: now.getFullYear(),+ month: now.getMonth(),+ sharedMap: { [today]: [{ color: '#f59e0b' }] },+ })++ const shadow = cell(now.getDate()).style.boxShadow+ expect(shadow).toContain('inset 0 0 0 2px var(--vg-ink)')+ expect(shadow).toContain('inset 0 0 0 4px #f59e0b')+ })++ it('FE-COMP-VCYMC-002: shared calendars stack up to two inset rings on a day', () => {+ renderCard({+ sharedMap: {+ '2026-06-10': [{ color: '#f59e0b' }, { color: '#10b981' }, { color: '#3b82f6' }],+ },+ })++ const shadow = cell(10).style.boxShadow+ expect(shadow).toContain('#f59e0b')+ expect(shadow).toContain('#10b981')+ expect(shadow).not.toContain('#3b82f6')+ })++ it('FE-COMP-VCYMC-003: hovering only reports days that have something to explain', () => {+ const onCellHover = vi.fn((_date: string | null, _el: HTMLElement | null) => {})+ renderCard({+ onCellHover,+ entryMap: { '2026-06-10': [{ date: '2026-06-10', user_id: 1, person_color: '#3b82f6' }] },+ })++ fireEvent.mouseEnter(cell(11))+ expect(onCellHover).not.toHaveBeenCalled()++ fireEvent.mouseEnter(cell(10))+ expect(onCellHover).toHaveBeenCalledWith('2026-06-10', expect.anything())++ fireEvent.mouseLeave(cell(10))+ expect(onCellHover).toHaveBeenLastCalledWith(null, null)+ })++ it('FE-COMP-VCYMC-004: a plain day gets a hover background that is restored on leave', () => {+ renderCard()+ const plain = cell(11)++ fireEvent.mouseEnter(plain)+ expect(plain.style.background).toBe('var(--vg-surf2)')++ fireEvent.mouseLeave(plain)+ expect(plain.style.background).toBe('transparent')+ })+})diff --git a/client/src/components/Vacay/VacayPersons.modals.test.tsx b/client/src/components/Vacay/VacayPersons.modals.test.tsxnew file mode 100644index 000000000..5de8015ef--- /dev/null+++ b/client/src/components/Vacay/VacayPersons.modals.test.tsx@@ -0,0 +1,130 @@+// FE-COMP-VCYPERS-001 to FE-COMP-VCYPERS-007+import React from 'react'+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { http, HttpResponse } from 'msw'+import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render'+import { server } from '../../../tests/helpers/msw/server'+import { resetAllStores } from '../../../tests/helpers/store'+import { useVacayStore } from '../../store/vacayStore'+import { useAuthStore } from '../../store/authStore'+import VacayPersons from './VacayPersons'++const toasts: { type: string; message: string }[] = []++function availableRespond(users: { id: number; username: string; email: string }[]) {+ server.use(http.get('/api/addons/vacay/available-users', () => HttpResponse.json({ users })))+}++beforeEach(() => {+ resetAllStores()+ toasts.length = 0+ window.__addToast = ((message: string, type?: string) => {+ toasts.push({ type: type ?? 'info', message })+ return 1+ }) as Window['__addToast']+ availableRespond([{ id: 2, username: 'bob', email: '[email protected]' }])+ useAuthStore.setState({ user: { id: 1, username: 'alice', email: '[email protected]', role: 'user' } as never })+ useVacayStore.setState({ users: [{ id: 1, username: 'alice', color: '#3b82f6' }], selectedUserId: null })+})++afterEach(() => {+ delete window.__addToast+})++/** The invite trigger is an unlabelled icon button in the card header. */+function openInvite() {+ const header = screen.getByText('Persons').closest('.justify-between') as HTMLElement+ fireEvent.click(within(header).getByRole('button'))+}++describe('VacayPersons modals', () => {+ it('FE-COMP-VCYPERS-001: the active person defaults to the signed-in user', async () => {+ render(<VacayPersons />)++ await waitFor(() => expect(useVacayStore.getState().selectedUserId).toBe(1))+ })++ it('FE-COMP-VCYPERS-002: sending an invite posts the picked user', async () => {+ let invited: number | undefined+ server.use(http.post('/api/addons/vacay/invite', async ({ request }) => {+ invited = ((await request.json()) as { user_id: number }).user_id+ return HttpResponse.json({ success: true })+ }))+ render(<VacayPersons />)++ openInvite()+ fireEvent.click(await screen.findByRole('button', { name: 'Select user' }))+ fireEvent.click(screen.getByRole('button', { name: 'bob ([email protected])' }))+ fireEvent.click(screen.getByRole('button', { name: 'Send Invite' }))++ await waitFor(() => expect(invited).toBe(2))+ await waitFor(() => expect(screen.queryByRole('button', { name: 'Send Invite' })).not.toBeInTheDocument())+ })++ it('FE-COMP-VCYPERS-003: a rejected invite is reported and keeps the modal open', async () => {+ server.use(http.post('/api/addons/vacay/invite', () =>+ HttpResponse.json({ error: 'Already invited' }, { status: 409 })))+ render(<VacayPersons />)++ openInvite()+ fireEvent.click(await screen.findByRole('button', { name: 'Select user' }))+ fireEvent.click(screen.getByRole('button', { name: 'bob ([email protected])' }))+ fireEvent.click(screen.getByRole('button', { name: 'Send Invite' }))++ await waitFor(() => expect(toasts).toEqual([{ type: 'error', message: 'Already invited' }]))+ expect(screen.getByRole('button', { name: 'Send Invite' })).toBeInTheDocument()+ })++ it('FE-COMP-VCYPERS-004: the invite modal closes through the backdrop, the X and Cancel', async () => {+ render(<VacayPersons />)++ openInvite()+ const modal = await screen.findByText('Invite another TREK user to share a combined vacation calendar.')+ fireEvent.click(modal.closest('.fixed') as HTMLElement)+ expect(screen.queryByRole('button', { name: 'Send Invite' })).not.toBeInTheDocument()++ openInvite()+ const header = (await screen.findByText('Invite User')).closest('.justify-between') as HTMLElement+ fireEvent.click(within(header).getByRole('button'))+ expect(screen.queryByRole('button', { name: 'Send Invite' })).not.toBeInTheDocument()++ openInvite()+ fireEvent.click(await screen.findByRole('button', { name: 'Cancel' }))+ expect(screen.queryByRole('button', { name: 'Send Invite' })).not.toBeInTheDocument()+ })++ it('FE-COMP-VCYPERS-005: with nobody left to invite the modal says so', async () => {+ availableRespond([])+ render(<VacayPersons />)++ openInvite()+ expect(await screen.findByText('No users available')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Send Invite' })).toBeDisabled()+ })++ it('FE-COMP-VCYPERS-006: pending invites can be withdrawn from the list', () => {+ const cancelInvite = vi.fn(async (_userId: number) => {})+ useVacayStore.setState({ pendingInvites: [{ user_id: 9, username: 'dan' }], cancelInvite })+ render(<VacayPersons />)++ const row = screen.getByText('dan').closest('.group') as HTMLElement+ fireEvent.click(within(row).getByRole('button', { name: 'Cancel' }))+ expect(cancelInvite).toHaveBeenCalledWith(9)+ })++ it('FE-COMP-VCYPERS-007: the color picker opens from a person dot and closes both ways', async () => {+ const updateColor = vi.fn(async (_color: string, _target?: number) => {})+ useVacayStore.setState({ updateColor })+ render(<VacayPersons />)++ fireEvent.click(screen.getByTitle('Change color'))+ const heading = await screen.findByText('Change color')+ fireEvent.click(within(heading.closest('.justify-between') as HTMLElement).getByRole('button'))+ expect(screen.queryByText('Change color', { selector: 'h2' })).not.toBeInTheDocument()++ fireEvent.click(screen.getByTitle('Change color'))+ const dialog = await screen.findByText('Change color', { selector: 'h2' })+ fireEvent.click(dialog.closest('.fixed') as HTMLElement)+ expect(screen.queryByText('Change color', { selector: 'h2' })).not.toBeInTheDocument()+ })+})diff --git a/client/src/components/Vacay/VacaySettings.calendars.test.tsx b/client/src/components/Vacay/VacaySettings.calendars.test.tsxnew file mode 100644index 000000000..ffa38343b--- /dev/null+++ b/client/src/components/Vacay/VacaySettings.calendars.test.tsx@@ -0,0 +1,324 @@+// FE-COMP-VCYSET-001 to FE-COMP-VCYSET-014+// Covers the calendar editor / draft rows and the leave-year block of VacaySettings,+// which VacaySettings.test.tsx only reaches at the surface.+import React from 'react'+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { http, HttpResponse } from 'msw'+import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render'+import { server } from '../../../tests/helpers/msw/server'+import { resetAllStores } from '../../../tests/helpers/store'+import { useVacayStore } from '../../store/vacayStore'+import VacaySettings from './VacaySettings'+import type { VacayHolidayCalendar, VacayPlan } from '../../types'++const toasts: { type: string; message: string }[] = []++function buildPlan(over: Partial<VacayPlan> = {}): VacayPlan {+ return {+ id: 1,+ holidays_enabled: false,+ school_holidays_enabled: false,+ holidays_region: null,+ holiday_calendars: [],+ block_weekends: true,+ carry_over_enabled: false,+ company_holidays_enabled: false,+ ...over,+ }+}++function countriesRespond(rows: { countryCode: string; name: string }[]) {+ server.use(http.get('/api/addons/vacay/holidays/countries', () => HttpResponse.json(rows)))+}++function regionalHolidays() {+ server.use(http.get('/api/addons/vacay/holidays/:year/:country', () => HttpResponse.json([+ { date: '2026-11-01', name: 'All Saints', localName: 'Allerheiligen', global: false, counties: ['DE-BY', 'DE-NW'] },+ ])))+}++/** The SettingToggle switch carries no label of its own — reach it through its row. */+function toggleFor(label: string): HTMLElement {+ const row = screen.getByText(label).closest('.justify-between') as HTMLElement+ return within(row).getByRole('button')+}++/** CustomSelect: click the trigger, then the option with that label. */+function pickOption(triggerName: string | RegExp, optionLabel: string) {+ fireEvent.click(screen.getByRole('button', { name: triggerName }))+ fireEvent.click(screen.getByRole('button', { name: optionLabel }))+}++/** Same, but waits for the option list — countries and regions load asynchronously. */+async function pickLoadedOption(triggerName: string | RegExp, optionLabel: string) {+ fireEvent.click(await screen.findByRole('button', { name: triggerName }))+ fireEvent.click(await screen.findByRole('button', { name: optionLabel }))+}++/** The trash icon in a calendar row carries no text of its own. */+function trashButtons(container: HTMLElement): HTMLElement[] {+ return [...container.querySelectorAll<HTMLElement>('button.shrink-0.rounded-md')]+}++beforeEach(() => {+ resetAllStores()+ toasts.length = 0+ window.__addToast = ((message: string, type?: string) => {+ toasts.push({ type: type ?? 'info', message })+ return 1+ }) as Window['__addToast']+ countriesRespond([+ { countryCode: 'DE', name: 'Germany' },+ { countryCode: 'NL', name: 'Netherlands' },+ ])+ useVacayStore.setState({ plan: buildPlan(), selectedYear: 2026 })+})++afterEach(() => {+ delete window.__addToast+})++describe('VacaySettings calendars', () => {+ it('FE-COMP-VCYSET-001: the week-start buttons save the other day', () => {+ const updatePlan = vi.fn(async (_u: Partial<VacayPlan>) => {})+ useVacayStore.setState({ updatePlan })+ render(<VacaySettings onClose={vi.fn()} />)++ // 'Sun' is also a weekend-day chip; the week-start pair comes second.+ fireEvent.click(screen.getAllByRole('button', { name: 'Sun' })[1])+ expect(updatePlan).toHaveBeenCalledWith({ week_start: 0 })+ })++ it('FE-COMP-VCYSET-002: the holiday toggles flip their own plan flag', () => {+ const updatePlan = vi.fn(async (_u: Partial<VacayPlan>) => {})+ useVacayStore.setState({ updatePlan })+ render(<VacaySettings onClose={vi.fn()} />)++ fireEvent.click(toggleFor('Public Holidays'))+ expect(updatePlan).toHaveBeenLastCalledWith({ holidays_enabled: true })++ fireEvent.click(toggleFor('School Holidays'))+ expect(updatePlan).toHaveBeenLastCalledWith({ school_holidays_enabled: true })+ })++ it('FE-COMP-VCYSET-003: empty holiday sections explain that nothing is configured', () => {+ useVacayStore.setState({ plan: buildPlan({ holidays_enabled: true, school_holidays_enabled: true }) })+ render(<VacaySettings onClose={vi.fn()} />)++ expect(screen.getByText('No holiday calendars added yet')).toBeInTheDocument()+ expect(screen.getByText('No school holiday calendars added yet')).toBeInTheDocument()+ expect(screen.getAllByRole('button', { name: 'Add calendar' })).toHaveLength(2)+ })++ it('FE-COMP-VCYSET-004: a calendar label is written back on blur and Enter blurs the field', () => {+ const updateHolidayCalendar = vi.fn(async (_id: number, _d: Record<string, unknown>) => {})+ const calendars: VacayHolidayCalendar[] = [+ { id: 3, plan_id: 1, region: 'DE', label: 'Germany', color: '#fecaca', sort_order: 0 },+ ]+ useVacayStore.setState({ plan: buildPlan({ holidays_enabled: true, holiday_calendars: calendars }), updateHolidayCalendar })+ render(<VacaySettings onClose={vi.fn()} />)++ const input = screen.getByDisplayValue('Germany')+ fireEvent.blur(input)+ expect(updateHolidayCalendar).not.toHaveBeenCalled()++ fireEvent.change(input, { target: { value: ' Deutschland ' } })+ fireEvent.keyDown(input, { key: 'Enter' })+ fireEvent.blur(input)+ expect(updateHolidayCalendar).toHaveBeenCalledWith(3, { label: 'Deutschland' })+ })++ it('FE-COMP-VCYSET-005: a calendar can switch country and, once regional, region', async () => {+ regionalHolidays()+ const updateHolidayCalendar = vi.fn(async (_id: number, _d: Record<string, unknown>) => {})+ useVacayStore.setState({+ plan: buildPlan({+ holidays_enabled: true,+ holiday_calendars: [{ id: 3, plan_id: 1, region: 'DE', label: null, color: '#fecaca', sort_order: 0 }],+ }),+ updateHolidayCalendar,+ })+ render(<VacaySettings onClose={vi.fn()} />)++ await pickLoadedOption('Germany', 'Netherlands')+ expect(updateHolidayCalendar).toHaveBeenLastCalledWith(3, { region: 'NL' })++ // The region list is only offered because the holiday data is county-split.+ await pickLoadedOption('Select region (optional)', 'Nordrhein-Westfalen')+ expect(updateHolidayCalendar).toHaveBeenLastCalledWith(3, { region: 'DE-NW' })+ })++ it('FE-COMP-VCYSET-006: a calendar without a country offers no region list, and can be deleted', () => {+ const deleteHolidayCalendar = vi.fn(async (_id: number) => {})+ useVacayStore.setState({+ plan: buildPlan({+ holidays_enabled: true,+ holiday_calendars: [{ id: 4, plan_id: 1, region: '', label: null, color: '#fecaca', sort_order: 0 }],+ }),+ deleteHolidayCalendar,+ })+ const { container } = render(<VacaySettings onClose={vi.fn()} />)++ expect(screen.queryByRole('button', { name: 'Select region (optional)' })).not.toBeInTheDocument()++ const trash = trashButtons(container)[0]+ fireEvent.mouseEnter(trash)+ expect(trash.style.background).toBe('rgba(239, 68, 68, 0.1)')+ fireEvent.mouseLeave(trash)+ expect(trash.style.background).toBe('transparent')++ fireEvent.click(trash)+ expect(deleteHolidayCalendar).toHaveBeenCalledWith(4)+ })++ it('FE-COMP-VCYSET-007: the public draft picks a color, a label and a country before adding', async () => {+ const addHolidayCalendar = vi.fn(async (_d: Record<string, unknown>) => {})+ useVacayStore.setState({ plan: buildPlan({ holidays_enabled: true }), addHolidayCalendar })+ const { container } = render(<VacaySettings onClose={vi.fn()} />)++ fireEvent.click(screen.getByRole('button', { name: 'Add calendar' }))+ expect(screen.getByRole('button', { name: 'Add' })).toBeDisabled()++ fireEvent.click(screen.getByTitle('Color'))+ const presets = container.querySelectorAll('div[style*="grid"] > button')+ expect(presets.length).toBeGreaterThan(1)+ fireEvent.click(presets[2])++ fireEvent.change(screen.getByPlaceholderText('Label (optional)'), { target: { value: ' Feiertage ' } })+ await pickLoadedOption('Select country', 'Germany')+ fireEvent.click(screen.getByRole('button', { name: 'Add' }))++ await waitFor(() => expect(addHolidayCalendar).toHaveBeenCalledWith(expect.objectContaining({+ region: 'DE', label: 'Feiertage', type: 'public_holiday',+ })))+ await waitFor(() => expect(screen.getByRole('button', { name: 'Add calendar' })).toBeInTheDocument())+ })++ it('FE-COMP-VCYSET-008: a regional country blocks the draft until a region is chosen', async () => {+ regionalHolidays()+ const addHolidayCalendar = vi.fn(async (_d: Record<string, unknown>) => {})+ useVacayStore.setState({ plan: buildPlan({ holidays_enabled: true }), addHolidayCalendar })+ render(<VacaySettings onClose={vi.fn()} />)++ fireEvent.click(screen.getByRole('button', { name: 'Add calendar' }))+ await pickLoadedOption('Select country', 'Germany')++ await screen.findByRole('button', { name: 'Select region (optional)' })+ expect(screen.getByRole('button', { name: 'Add' })).toBeDisabled()++ await pickLoadedOption('Select region (optional)', 'Bayern')+ fireEvent.click(screen.getByRole('button', { name: 'Add' }))++ await waitFor(() => expect(addHolidayCalendar).toHaveBeenCalledWith(expect.objectContaining({ region: 'DE-BY' })))+ })++ it('FE-COMP-VCYSET-009: the school draft opens, cancels and adds a school calendar', async () => {+ const addHolidayCalendar = vi.fn(async (_d: Record<string, unknown>) => {})+ countriesRespond([+ { countryCode: 'NL', name: 'Netherlands' },+ { countryCode: 'US', name: 'United States' },+ ])+ useVacayStore.setState({ plan: buildPlan({ school_holidays_enabled: true }), addHolidayCalendar })+ render(<VacaySettings onClose={vi.fn()} />)++ fireEvent.click(screen.getByRole('button', { name: 'Add calendar' }))+ fireEvent.click(screen.getByRole('button', { name: '✕' }))+ expect(screen.getByRole('button', { name: 'Add calendar' })).toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: 'Add calendar' }))+ // Only countries with OpenHolidays school-holiday coverage are offered.+ fireEvent.click(screen.getByRole('button', { name: 'Select country' }))+ expect(await screen.findByRole('button', { name: 'Netherlands' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'United States' })).not.toBeInTheDocument()+ fireEvent.click(screen.getByRole('button', { name: 'Netherlands' }))++ await pickLoadedOption('Select region (optional)', 'Northern Region')+ fireEvent.click(screen.getByRole('button', { name: 'Add' }))++ await waitFor(() => expect(addHolidayCalendar).toHaveBeenCalledWith(expect.objectContaining({+ region: 'NL|group:NL-NO', type: 'school_holiday',+ })))+ })++ it('FE-COMP-VCYSET-010: an existing school calendar is editable and removable', async () => {+ const updateHolidayCalendar = vi.fn(async (_id: number, _d: Record<string, unknown>) => {})+ const deleteHolidayCalendar = vi.fn(async (_id: number) => {})+ useVacayStore.setState({+ plan: buildPlan({+ school_holidays_enabled: true,+ holiday_calendars: [{ id: 8, plan_id: 1, region: 'NL|group:NL-MI', label: 'Midden', color: '#a5f3fc', sort_order: 0, type: 'school_holiday' }],+ }),+ updateHolidayCalendar,+ deleteHolidayCalendar,+ })+ const { container } = render(<VacaySettings onClose={vi.fn()} />)++ await pickLoadedOption('Central Region', 'Southern Region')+ expect(updateHolidayCalendar).toHaveBeenCalledWith(8, { region: 'NL|group:NL-ZU' })++ fireEvent.click(trashButtons(container)[0])+ expect(deleteHolidayCalendar).toHaveBeenCalledWith(8)+ })++ it('FE-COMP-VCYSET-011: the fused member chips list every person', () => {+ useVacayStore.setState({+ isFused: true,+ users: [{ id: 1, username: 'alice', color: '#3b82f6' }, { id: 2, username: 'bob', color: null }],+ })+ render(<VacaySettings onClose={vi.fn()} />)++ expect(screen.getByText('alice')).toBeInTheDocument()+ expect(screen.getByText('bob')).toBeInTheDocument()+ })++ it('FE-COMP-VCYSET-012: switching the leave-year type saves it and reveals its fields', () => {+ const updateYearSettings = vi.fn(async () => {})+ useVacayStore.setState({ updateYearSettings })+ render(<VacaySettings onClose={vi.fn()} />)++ fireEvent.click(screen.getByRole('button', { name: 'Fiscal' }))+ expect(updateYearSettings).toHaveBeenCalledWith({+ year_type: 'fiscal', year_start_month: 1, year_start_day: 1, hire_date: null,+ })+ })++ it('FE-COMP-VCYSET-013: the fiscal month and day selects save, clamping February', () => {+ const updateYearSettings = vi.fn(async () => {})+ useVacayStore.setState({+ updateYearSettings,+ yearSettings: { year_type: 'fiscal', year_start_month: 1, year_start_day: 31, hire_date: null },+ })+ render(<VacaySettings onClose={vi.fn()} />)++ pickOption('January', 'February')+ expect(updateYearSettings).toHaveBeenLastCalledWith({+ year_type: 'fiscal', year_start_month: 2, year_start_day: 28, hire_date: null,+ })++ pickOption('31', '15')+ expect(updateYearSettings).toHaveBeenLastCalledWith({+ year_type: 'fiscal', year_start_month: 1, year_start_day: 15, hire_date: null,+ })+ })++ it('FE-COMP-VCYSET-014: the anniversary year takes its start from the hire date', () => {+ const updateYearSettings = vi.fn(async () => {})+ useVacayStore.setState({+ updateYearSettings,+ yearSettings: { year_type: 'anniversary', year_start_month: 1, year_start_day: 1, hire_date: '2020-09-14' },+ })+ render(<VacaySettings onClose={vi.fn()} />)++ expect(screen.getByLabelText('Hire date')).toHaveValue('2020-09-14')++ fireEvent.change(screen.getByLabelText('Hire date'), { target: { value: '2021-03-02' } })+ expect(updateYearSettings).toHaveBeenLastCalledWith({+ year_type: 'anniversary', year_start_month: 1, year_start_day: 1, hire_date: '2021-03-02',+ })++ fireEvent.change(screen.getByLabelText('Hire date'), { target: { value: '' } })+ expect(updateYearSettings).toHaveBeenLastCalledWith({+ year_type: 'anniversary', year_start_month: 1, year_start_day: 1, hire_date: null,+ })+ })+})diff --git a/client/src/components/Vacay/VacaySharedCalendars.errors.test.tsx b/client/src/components/Vacay/VacaySharedCalendars.errors.test.tsxnew file mode 100644index 000000000..ba3be73aa--- /dev/null+++ b/client/src/components/Vacay/VacaySharedCalendars.errors.test.tsx@@ -0,0 +1,122 @@+// FE-COMP-VCYSHR-001 to FE-COMP-VCYSHR-006+import React from 'react'+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { http, HttpResponse } from 'msw'+import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render'+import { server } from '../../../tests/helpers/msw/server'+import { resetAllStores } from '../../../tests/helpers/store'+import { useVacayStore } from '../../store/vacayStore'+import VacaySharedCalendars from './VacaySharedCalendars'++const toasts: { type: string; message: string }[] = []++function candidatesRespond(users: { id: number; username: string; email: string }[]) {+ server.use(http.get('/api/addons/vacay/shares/available-users', () => HttpResponse.json({ users })))+}++beforeEach(() => {+ resetAllStores()+ toasts.length = 0+ window.__addToast = ((message: string, type?: string) => {+ toasts.push({ type: type ?? 'info', message })+ return 1+ }) as Window['__addToast']+ candidatesRespond([{ id: 2, username: 'bob', email: '[email protected]' }])+})++afterEach(() => {+ delete window.__addToast+})++describe('VacaySharedCalendars errors', () => {+ it('FE-COMP-VCYSHR-001: sharing posts the picked user and closes the modal', async () => {+ let shared: number | undefined+ server.use(http.post('/api/addons/vacay/shares', async ({ request }) => {+ shared = ((await request.json()) as { user_id: number }).user_id+ return HttpResponse.json({ success: true })+ }))+ render(<VacaySharedCalendars />)++ fireEvent.click(screen.getByTitle('Share calendar'))+ fireEvent.click(await screen.findByRole('button', { name: 'Select user' }))+ fireEvent.click(screen.getByRole('button', { name: 'bob' }))+ fireEvent.click(screen.getByRole('button', { name: 'Share' }))++ await waitFor(() => expect(shared).toBe(2))+ await waitFor(() => expect(screen.queryByRole('button', { name: 'Select user' })).not.toBeInTheDocument())+ expect(toasts).toEqual([{ type: 'success', message: 'Calendar shared' }])+ })++ it('FE-COMP-VCYSHR-002: a rejected share is reported', async () => {+ server.use(http.post('/api/addons/vacay/shares', () =>+ HttpResponse.json({ error: 'Already shared' }, { status: 409 })))+ render(<VacaySharedCalendars />)++ fireEvent.click(screen.getByTitle('Share calendar'))+ fireEvent.click(await screen.findByRole('button', { name: 'Select user' }))+ fireEvent.click(screen.getByRole('button', { name: 'bob' }))+ fireEvent.click(screen.getByRole('button', { name: 'Share' }))++ await waitFor(() => expect(toasts).toEqual([{ type: 'error', message: 'Already shared' }]))+ })++ it('FE-COMP-VCYSHR-003: a failing hide toggle reports instead of silently reverting', async () => {+ const setShareHidden = vi.fn(async (_id: number, _hidden: boolean) => {+ throw { response: { data: { error: 'Share vanished' } }, message: 'nope' }+ })+ useVacayStore.setState({+ incomingShares: [{ id: 5, owner_id: 3, username: 'carol', color: '#f59e0b', hidden: false }],+ setShareHidden,+ })+ render(<VacaySharedCalendars />)++ fireEvent.click(screen.getByTitle('Hide from calendar'))+ expect(setShareHidden).toHaveBeenCalledWith(5, true)+ await waitFor(() => expect(toasts).toEqual([{ type: 'error', message: 'Share vanished' }]))+ })++ it('FE-COMP-VCYSHR-004: both share directions can be revoked and report failures', async () => {+ const removeShare = vi.fn(async (_id: number) => { throw { status: 500 } })+ useVacayStore.setState({+ incomingShares: [{ id: 5, owner_id: 3, username: 'carol', color: '#f59e0b', hidden: true }],+ outgoingShares: [{ id: 11, user_id: 8, username: 'erin' }],+ removeShare,+ })+ render(<VacaySharedCalendars />)++ fireEvent.click(screen.getByTitle('Remove'))+ fireEvent.click(screen.getByRole('button', { name: 'Stop sharing' }))++ expect(removeShare).toHaveBeenNthCalledWith(1, 5)+ expect(removeShare).toHaveBeenNthCalledWith(2, 11)+ await waitFor(() => expect(toasts).toHaveLength(2))+ expect(toasts[0].message).toBe('Could not share calendar')+ })++ it('FE-COMP-VCYSHR-005: the share modal closes through the backdrop, the X and Cancel', async () => {+ render(<VacaySharedCalendars />)++ fireEvent.click(screen.getByTitle('Share calendar'))+ const hint = await screen.findByRole('button', { name: 'Share' })+ fireEvent.click(hint.closest('.fixed') as HTMLElement)+ expect(screen.queryByRole('button', { name: 'Share' })).not.toBeInTheDocument()++ fireEvent.click(screen.getByTitle('Share calendar'))+ const header = (await screen.findByText('Share calendar')).closest('.justify-between') as HTMLElement+ fireEvent.click(within(header).getByRole('button'))+ expect(screen.queryByRole('button', { name: 'Share' })).not.toBeInTheDocument()++ fireEvent.click(screen.getByTitle('Share calendar'))+ fireEvent.click(await screen.findByRole('button', { name: 'Cancel' }))+ expect(screen.queryByRole('button', { name: 'Share' })).not.toBeInTheDocument()+ })++ it('FE-COMP-VCYSHR-006: with nobody left to share with the modal says so', async () => {+ candidatesRespond([])+ render(<VacaySharedCalendars />)++ fireEvent.click(screen.getByTitle('Share calendar'))+ expect(await screen.findByText('No users available')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Share' })).toBeDisabled()+ })+})diff --git a/client/src/components/Vacay/VacayStats.storage.test.tsx b/client/src/components/Vacay/VacayStats.storage.test.tsxnew file mode 100644index 000000000..cebf216c4--- /dev/null+++ b/client/src/components/Vacay/VacayStats.storage.test.tsx@@ -0,0 +1,41 @@+// FE-COMP-VCYSTAT-001 to FE-COMP-VCYSTAT-002+import React from 'react'+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { render, screen } from '../../../tests/helpers/render'+import { resetAllStores } from '../../../tests/helpers/store'+import { useVacayStore } from '../../store/vacayStore'+import { useAuthStore } from '../../store/authStore'+import VacayStats from './VacayStats'++const COLLAPSED_KEY_STAT = {+ user_id: 1, person_name: 'alice', person_color: '#3b82f6', year: 2026,+ vacation_days: 30, carried_over: 0, total_available: 30, used: 4, remaining: 26,+}++beforeEach(() => {+ resetAllStores()+ useAuthStore.setState({ user: { id: 1, username: 'alice', email: '[email protected]', role: 'user' } as never })+ useVacayStore.setState({ selectedYear: 2026, stats: [COLLAPSED_KEY_STAT] })+})++afterEach(() => {+ vi.restoreAllMocks()+ localStorage.clear()+})++describe('VacayStats storage', () => {+ it('FE-COMP-VCYSTAT-001: a blocked localStorage still renders the expanded card', () => {+ vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw new Error('denied') })+ render(<VacayStats />)++ // Expanded is the fallback, so the person's numbers are on screen.+ expect(screen.getByText('alice')).toBeInTheDocument()+ })++ it('FE-COMP-VCYSTAT-002: a persisted collapsed flag is honoured on mount', () => {+ localStorage.setItem('vacay-stats-collapsed', '1')+ render(<VacayStats />)++ expect(screen.queryByText('alice')).not.toBeInTheDocument()+ })+})diff --git a/client/src/components/Vacay/holidayRegions.test.ts b/client/src/components/Vacay/holidayRegions.test.tsnew file mode 100644index 000000000..a24678e65--- /dev/null+++ b/client/src/components/Vacay/holidayRegions.test.ts@@ -0,0 +1,104 @@+// FE-COMP-VCYREG-001 to FE-COMP-VCYREG-007+import { describe, it, expect, beforeEach } from 'vitest'+import { http, HttpResponse } from 'msw'+import { server } from '../../../tests/helpers/msw/server'+import { fetchRegionOptions, fetchSchoolHolidayRegionOptions } from './holidayRegions'++function holidaysRespond(rows: unknown) {+ server.use(http.get('/api/addons/vacay/holidays/:year/:country', () => HttpResponse.json(rows)))+}++function regionsRespond(body: unknown) {+ server.use(http.get('/api/addons/vacay/school-holidays/regions/:country', () => HttpResponse.json(body)))+}++beforeEach(() => {+ server.resetHandlers()+})++describe('fetchRegionOptions', () => {+ it('FE-COMP-VCYREG-001: a country with only nationwide holidays offers no regions', async () => {+ holidaysRespond([+ { date: '2026-12-25', name: 'Christmas', localName: 'Weihnachten', global: true, counties: null },+ ])++ expect(await fetchRegionOptions('DE')).toEqual([])+ })++ it('FE-COMP-VCYREG-002: region-split data returns the full ISO subdivision list, sorted', async () => {+ holidaysRespond([+ { date: '2026-11-01', name: 'All Saints', localName: 'Allerheiligen', global: false, counties: ['DE-BY'] },+ ])++ const options = await fetchRegionOptions('DE')+ expect(options.length).toBeGreaterThan(15)+ expect(options[0].label).toBe('Baden-Württemberg')+ expect(options.map(o => o.value)).toContain('DE-NW')+ // The list stays alphabetical by label.+ expect([...options].sort((a, b) => a.label.localeCompare(b.label))).toEqual(options)+ })++ it('FE-COMP-VCYREG-003: a county code ISO does not know is kept with a derived label', async () => {+ holidaysRespond([+ { date: '2026-11-01', name: 'Local', localName: 'Local', global: false, counties: ['DE-ZZ'] },+ ])++ const options = await fetchRegionOptions('DE')+ expect(options.find(o => o.value === 'DE-ZZ')).toEqual({ value: 'DE-ZZ', label: 'ZZ' })+ })++ it('FE-COMP-VCYREG-004: a failing request degrades to no regions', async () => {+ holidaysRespond({ error: 'down' })+ server.use(http.get('/api/addons/vacay/holidays/:year/:country', () =>+ HttpResponse.json({ error: 'down' }, { status: 500 })))++ expect(await fetchRegionOptions('DE')).toEqual([])+ })+})++describe('fetchSchoolHolidayRegionOptions', () => {+ it('FE-COMP-VCYREG-005: unsupported and nationwide countries are not queried', async () => {+ expect(await fetchSchoolHolidayRegionOptions('US')).toEqual([])+ // Ireland is covered, but only at country level.+ expect(await fetchSchoolHolidayRegionOptions('IE')).toEqual([])+ })++ it('FE-COMP-VCYREG-006: a group country prefixes its codes and flattens nested children', async () => {+ regionsRespond({+ groups: [+ {+ code: 'NL-NO', shortName: 'NO', name: [{ language: 'EN', text: 'North' }],+ children: [{ code: 'NL-NO-1', name: [{ language: 'EN', text: 'Sub' }] }],+ },+ ],+ subdivisions: [],+ })++ expect(await fetchSchoolHolidayRegionOptions('NL')).toEqual([+ { value: 'NL|group:NL-NO', label: 'North' },+ { value: 'NL|group:NL-NO-1', label: 'North / Sub' },+ ])+ })++ it('FE-COMP-VCYREG-007: a subdivision country prefers the German name and falls back to the code', async () => {+ regionsRespond({+ groups: [],+ subdivisions: [+ { code: 'DE-BY', name: [{ language: 'DE', text: 'Bayern' }, { language: 'EN', text: 'Bavaria' }] },+ { code: 'DE-XX' },+ ],+ })++ expect(await fetchSchoolHolidayRegionOptions('DE')).toEqual([+ { value: 'DE-BY', label: 'Bayern' },+ { value: 'DE-XX', label: 'DE-XX' },+ ])+ })++ it('FE-COMP-VCYREG-008: a failing region request degrades to no regions', async () => {+ server.use(http.get('/api/addons/vacay/school-holidays/regions/:country', () =>+ HttpResponse.json({ error: 'down' }, { status: 500 })))++ expect(await fetchSchoolHolidayRegionOptions('NL')).toEqual([])+ })+})diff --git a/client/src/components/Vacay/holidayVisual.test.ts b/client/src/components/Vacay/holidayVisual.test.tsnew file mode 100644index 000000000..d0b6dd7cf--- /dev/null+++ b/client/src/components/Vacay/holidayVisual.test.ts@@ -0,0 +1,29 @@+// FE-COMP-VCYVIS-001 to FE-COMP-VCYVIS-004+import { describe, it, expect } from 'vitest'+import { schoolHolidayBand, schoolHolidayWash } from './holidayVisual'++describe('holidayVisual', () => {+ it('FE-COMP-VCYVIS-001: a day without a school break has no band', () => {+ expect(schoolHolidayBand([])).toBe('transparent')+ })++ it('FE-COMP-VCYVIS-002: one calendar paints the band in its own colour', () => {+ expect(schoolHolidayBand(['#bbf7d0'])).toBe('#bbf7d0')+ })++ it('FE-COMP-VCYVIS-003: several calendars split the band into equal segments', () => {+ expect(schoolHolidayBand(['#bbf7d0', '#fecaca'])).toBe(+ 'linear-gradient(90deg, #bbf7d0 0% 50%, #fecaca 50% 100%)',+ )+ })++ it('FE-COMP-VCYVIS-004: the band caps at three segments', () => {+ const band = schoolHolidayBand(['#a', '#b', '#c', '#d'])+ expect(band).toBe('linear-gradient(90deg, #a 0% 33%, #b 33% 67%, #c 67% 100%)')+ expect(band).not.toContain('#d')+ })++ it('FE-COMP-VCYVIS-005: the wash keeps the calendar colour at a readable 15%', () => {+ expect(schoolHolidayWash('#bbf7d0')).toBe('color-mix(in srgb, #bbf7d0 15%, transparent)')+ })+})diff --git a/client/src/components/shared/ContextMenu.extra.test.tsx b/client/src/components/shared/ContextMenu.extra.test.tsxnew file mode 100644index 000000000..67e274eb3--- /dev/null+++ b/client/src/components/shared/ContextMenu.extra.test.tsx@@ -0,0 +1,117 @@+// FE-W4CTX-001 to FE-W4CTX-010+import { describe, it, expect, vi, afterEach } from 'vitest'+import { Trash2 } from 'lucide-react'+import { renderHook, act } from '@testing-library/react'+import { render, screen, fireEvent } from '../../../tests/helpers/render'+import { ContextMenu, useContextMenu } from './ContextMenu'++afterEach(() => {+ vi.restoreAllMocks()+})++describe('useContextMenu', () => {+ it('FE-W4CTX-001: opening stores the pointer position and the items', () => {+ const { result } = renderHook(() => useContextMenu())+ const preventDefault = vi.fn()+ const stopPropagation = vi.fn()+ const items = [{ label: 'Delete' }]++ act(() => {+ result.current.open({ clientX: 120, clientY: 40, preventDefault, stopPropagation } as unknown as React.MouseEvent, items)+ })++ expect(result.current.menu).toEqual({ x: 120, y: 40, items })+ expect(preventDefault).toHaveBeenCalled()+ expect(stopPropagation).toHaveBeenCalled()+ })++ it('FE-W4CTX-002: closing clears the menu', () => {+ const { result } = renderHook(() => useContextMenu())+ act(() => {+ result.current.open({ clientX: 0, clientY: 0, preventDefault() {}, stopPropagation() {} } as unknown as React.MouseEvent, [])+ })++ act(() => { result.current.close() })++ expect(result.current.menu).toBeNull()+ })+})++describe('ContextMenu', () => {+ it('FE-W4CTX-003: renders nothing without a menu', () => {+ const { container, baseElement } = render(<ContextMenu menu={null} onClose={() => {}} />)++ expect(container).toBeEmptyDOMElement()+ expect(baseElement.querySelector('.trek-popover-enter')).toBeNull()+ })++ it('FE-W4CTX-004: renders one button per item at the pointer position', () => {+ const { baseElement } = render(+ <ContextMenu menu={{ x: 40, y: 20, items: [{ label: 'Open' }, { label: 'Delete', icon: Trash2, danger: true }] }} onClose={() => {}} />,+ )++ expect(screen.getAllByRole('button')).toHaveLength(2)+ expect(baseElement.querySelector('.trek-popover-enter')).toHaveStyle({ left: '40px', top: '20px' })+ })++ it('FE-W4CTX-005: a danger item is red and carries its icon', () => {+ render(<ContextMenu menu={{ x: 0, y: 0, items: [{ label: 'Delete', icon: Trash2, danger: true }] }} onClose={() => {}} />)+ const button = screen.getByRole('button', { name: 'Delete' })++ expect(button).toHaveStyle({ color: 'rgb(239, 68, 68)' })+ expect(button.querySelector('svg')).not.toBeNull()+ })++ it('FE-W4CTX-006: a divider entry renders a rule instead of a button', () => {+ render(<ContextMenu menu={{ x: 0, y: 0, items: [{ label: 'Open' }, { divider: true }, { label: 'Delete' }] }} onClose={() => {}} />)++ expect(screen.getAllByRole('button')).toHaveLength(2)+ })++ it('FE-W4CTX-007: clicking an item runs it and closes the menu', () => {+ const onClick = vi.fn()+ const onClose = vi.fn()+ render(<ContextMenu menu={{ x: 0, y: 0, items: [{ label: 'Open', onClick }] }} onClose={onClose} />)++ fireEvent.click(screen.getByRole('button', { name: 'Open' }))++ expect(onClick).toHaveBeenCalledOnce()+ expect(onClose).toHaveBeenCalled()+ })++ it('FE-W4CTX-008: an item without a handler still closes the menu', () => {+ const onClose = vi.fn()+ render(<ContextMenu menu={{ x: 0, y: 0, items: [{ label: 'Open' }] }} onClose={onClose} />)++ fireEvent.click(screen.getByRole('button', { name: 'Open' }))++ expect(onClose).toHaveBeenCalled()+ })++ it('FE-W4CTX-009: a document click or right-click dismisses the menu', () => {+ const onClose = vi.fn()+ const { unmount } = render(<ContextMenu menu={{ x: 0, y: 0, items: [{ label: 'Open' }] }} onClose={onClose} />)++ fireEvent.click(document)+ fireEvent.contextMenu(document)+ expect(onClose).toHaveBeenCalledTimes(2)++ unmount()+ fireEvent.click(document)+ expect(onClose).toHaveBeenCalledTimes(2)+ })++ it('FE-W4CTX-010: flips the menu back inside the viewport when it would overflow', () => {+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue({+ width: 200, height: 120, top: 0, left: 0, right: 0, bottom: 0, x: 0, y: 0, toJSON: () => ({}),+ } as DOMRect)+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 400 })+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 300 })++ const { baseElement } = render(<ContextMenu menu={{ x: 380, y: 290, items: [{ label: 'Open' }] }} onClose={() => {}} />)++ const menu = baseElement.querySelector('.trek-popover-enter') as HTMLElement+ expect(menu.style.left).toBe('192px')+ expect(menu.style.top).toBe('172px')+ })+})diff --git a/client/src/components/shared/CopyTripDialog.test.tsx b/client/src/components/shared/CopyTripDialog.test.tsxnew file mode 100644index 000000000..0a991c92b--- /dev/null+++ b/client/src/components/shared/CopyTripDialog.test.tsx@@ -0,0 +1,97 @@+// FE-W4CTD-001 to FE-W4CTD-009+import type { ComponentProps } from 'react'+import { describe, it, expect, vi } from 'vitest'+import { render, screen, fireEvent } from '../../../tests/helpers/render'+import CopyTripDialog from './CopyTripDialog'++function setup(overrides: Partial<ComponentProps<typeof CopyTripDialog>> = {}) {+ const onClose = vi.fn()+ const onConfirm = vi.fn()+ const utils = render(+ <CopyTripDialog isOpen tripTitle="Iceland 2026" onClose={onClose} onConfirm={onConfirm} {...overrides} />,+ )+ return { onClose, onConfirm, ...utils }+}++describe('CopyTripDialog', () => {+ it('FE-W4CTD-001: renders nothing while closed', () => {+ const { container } = render(+ <CopyTripDialog isOpen={false} tripTitle="Iceland 2026" onClose={() => {}} onConfirm={() => {}} />,+ )++ expect(container).toBeEmptyDOMElement()+ expect(screen.queryByText('Iceland 2026')).toBeNull()+ })++ it('FE-W4CTD-002: shows the trip title and both copy lists', () => {+ setup()++ expect(screen.getByText('Iceland 2026')).toBeInTheDocument()+ // 6 "will copy" + 4 "won't copy" bullets.+ expect(screen.getAllByRole('listitem')).toHaveLength(10)+ })++ it('FE-W4CTD-003: confirming calls onConfirm and then closes', () => {+ const { onClose, onConfirm } = setup()++ fireEvent.click(screen.getByRole('button', { name: /copy/i }))++ expect(onConfirm).toHaveBeenCalledOnce()+ expect(onClose).toHaveBeenCalledOnce()+ })++ it('FE-W4CTD-004: cancel closes without confirming', () => {+ const { onClose, onConfirm } = setup()++ fireEvent.click(screen.getByRole('button', { name: /cancel/i }))++ expect(onClose).toHaveBeenCalledOnce()+ expect(onConfirm).not.toHaveBeenCalled()+ })++ it('FE-W4CTD-005: clicking the backdrop closes the dialog', () => {+ const { onClose, baseElement } = setup()+ const backdrop = baseElement.querySelector('.trek-backdrop-enter')!++ fireEvent.click(backdrop)++ expect(onClose).toHaveBeenCalledOnce()+ })++ it('FE-W4CTD-006: clicking inside the card does not close it', () => {+ const { onClose, baseElement } = setup()++ fireEvent.click(baseElement.querySelector('.trek-modal-enter')!)++ expect(onClose).not.toHaveBeenCalled()+ })++ it('FE-W4CTD-007: Escape closes the dialog', () => {+ const { onClose } = setup()++ fireEvent.keyDown(document, { key: 'Escape' })++ expect(onClose).toHaveBeenCalledOnce()+ })++ it('FE-W4CTD-008: other keys are ignored and the listener is dropped on close', () => {+ const onClose = vi.fn()+ const { rerender } = render(+ <CopyTripDialog isOpen tripTitle="Iceland 2026" onClose={onClose} onConfirm={() => {}} />,+ )++ fireEvent.keyDown(document, { key: 'Enter' })+ expect(onClose).not.toHaveBeenCalled()++ rerender(<CopyTripDialog isOpen={false} tripTitle="Iceland 2026" onClose={onClose} onConfirm={() => {}} />)+ fireEvent.keyDown(document, { key: 'Escape' })+ expect(onClose).not.toHaveBeenCalled()+ })++ it('FE-W4CTD-009: portals the dialog to document.body', () => {+ const { container, baseElement } = setup()++ expect(container).toBeEmptyDOMElement()+ expect(baseElement.querySelector('.trek-backdrop-enter')).not.toBeNull()+ })+})diff --git a/client/src/components/shared/CustomDateTimePicker.test.tsx b/client/src/components/shared/CustomDateTimePicker.test.tsxindex 3745e74da..d771b0f3f 100644--- a/client/src/components/shared/CustomDateTimePicker.test.tsx+++ b/client/src/components/shared/CustomDateTimePicker.test.tsx@@ -367,3 +367,351 @@ describe('CustomDateTimePicker', () => {expect(yr2026.getAttribute('aria-pressed')).toBe('true');});});++// FE-W5DP-001 to FE-W5DP-021 — the remaining calendar branches: year/month+// wrapping, the locale-order parser arms, viewport clamping of the popup,+// compact/borderless layout and the hover styling of every grid cell.+describe('CustomDatePicker branches', () => {+ const onChange = vi.fn();+ const openCalendar = () => fireEvent.click(screen.getAllByRole('button')[0]);+ const dayCell = (label: string) =>+ screen.getAllByRole('button').find((b) => b.textContent?.trim() === label) as HTMLButtonElement;++ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('FE-W5DP-001: a mousedown inside the trigger or the popup keeps the calendar open', () => {+ const { container } = render(<CustomDatePicker value="2026-03-15" onChange={onChange} />);+ openCalendar();+ const dialog = screen.getByRole('dialog');++ fireEvent.mouseDown(container.firstElementChild!);+ expect(screen.getByRole('dialog')).toBeInTheDocument();++ fireEvent.mouseDown(dialog);+ expect(screen.getByRole('dialog')).toBeInTheDocument();+ });++ it('FE-W5DP-002: with only a max bound the calendar opens on that month', () => {+ render(<CustomDatePicker value="" onChange={onChange} max="2026-11-20" />);+ openCalendar();+ expect(screen.getByText(/november 2026/i)).toBeInTheDocument();+ });++ it('FE-W5DP-003: paging back from January lands on the previous December', () => {+ render(<CustomDatePicker value="2026-01-15" onChange={onChange} />);+ openCalendar();+ fireEvent.click(screen.getByRole('button', { name: /previous month/i }));+ expect(screen.getByText(/december 2025/i)).toBeInTheDocument();+ });++ it('FE-W5DP-004: paging forward from December lands on the next January', () => {+ render(<CustomDatePicker value="2026-12-15" onChange={onChange} />);+ openCalendar();+ fireEvent.click(screen.getByRole('button', { name: /next month/i }));+ expect(screen.getByText(/january 2027/i)).toBeInTheDocument();+ });++ it('FE-W5DP-005: the months view pages the year in both directions', () => {+ render(<CustomDatePicker value="2026-03-15" onChange={onChange} />);+ openCalendar();+ fireEvent.click(screen.getByRole('button', { name: /select month/i }));++ fireEvent.click(screen.getByRole('button', { name: /next year/i }));+ expect(screen.getByRole('button', { name: 'March 2027' })).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: /previous year/i }));+ expect(screen.getByRole('button', { name: 'March 2026' })).toBeInTheDocument();+ });++ it('FE-W5DP-006: the years view pages the grid in both directions', () => {+ render(<CustomDatePicker value="2026-03-15" onChange={onChange} />);+ openCalendar();+ fireEvent.click(screen.getByRole('button', { name: /select month/i }));+ fireEvent.click(screen.getByRole('button', { name: /select year/i }));++ fireEvent.click(screen.getByRole('button', { name: /previous years/i }));+ expect(screen.getByRole('button', { name: '2014' })).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: /next years/i }));+ expect(screen.getByRole('button', { name: '2026' })).toBeInTheDocument();+ });++ it('FE-W5DP-007: compact mode renders the short numeric date and drops the calendar glyph', () => {+ const { container } = render(<CustomDatePicker value="2026-03-15" onChange={onChange} compact />);+ expect(screen.getByText('03/15/26')).toBeInTheDocument();+ expect(container.querySelector('.lucide-calendar')).toBeNull();+ });++ it('FE-W5DP-008: borderless mode drops the border and the inline keyboard trigger', () => {+ render(<CustomDatePicker value="2026-03-15" onChange={onChange} borderless />);+ const trigger = screen.getAllByRole('button')[0];+ expect(trigger.style.borderStyle).toBe('none');+ expect(trigger.style.background).toBe('transparent');+ expect(screen.queryByRole('button', { name: /enter date manually/i })).not.toBeInTheDocument();+ });++ it('FE-W5DP-009: the trigger only resets its border colour while the calendar is closed', () => {+ render(<CustomDatePicker value="" onChange={onChange} />);+ const trigger = screen.getAllByRole('button')[0];++ fireEvent.mouseEnter(trigger);+ expect(trigger.style.borderColor).toBe('var(--text-faint)');+ fireEvent.mouseLeave(trigger);+ expect(trigger.style.borderColor).toBe('var(--border-primary)');++ fireEvent.click(trigger);+ fireEvent.mouseEnter(trigger);+ fireEvent.mouseLeave(trigger);+ expect(trigger.style.borderColor).toBe('var(--text-faint)');+ });++ it('FE-W5DP-022: the inline manual-entry trigger highlights on hover', () => {+ render(<CustomDatePicker value="" onChange={onChange} />);+ const keyboard = screen.getByRole('button', { name: /enter date manually/i });++ fireEvent.mouseEnter(keyboard);+ expect(keyboard.style.color).toBe('var(--text-primary)');+ expect(keyboard.style.borderColor).toBe('var(--text-faint)');+ fireEvent.mouseLeave(keyboard);+ expect(keyboard.style.color).toBe('var(--text-faint)');+ expect(keyboard.style.borderColor).toBe('var(--border-primary)');+ });++ it('FE-W5DP-023: the compact footer trigger opens an empty manual entry when no date is set', () => {+ render(<CustomDatePicker value="" onChange={onChange} compact />);+ openCalendar();+ fireEvent.click(screen.getByRole('button', { name: /enter date manually/i }));++ expect(screen.getByPlaceholderText('DD.MM.YYYY')).toHaveProperty('value', '');+ });++ it('FE-W5DP-010: submitting an empty manual entry does nothing', () => {+ render(<CustomDatePicker value="" onChange={onChange} />);+ fireEvent.click(screen.getByRole('button', { name: /enter date manually/i }));+ fireEvent.blur(screen.getByPlaceholderText('DD.MM.YYYY'));++ expect(onChange).not.toHaveBeenCalled();+ expect(screen.queryByPlaceholderText('DD.MM.YYYY')).not.toBeInTheDocument();+ });++ it('FE-W5DP-011: a manual entry without three number groups is ignored', () => {+ render(<CustomDatePicker value="" onChange={onChange} />);+ fireEvent.click(screen.getByRole('button', { name: /enter date manually/i }));+ const input = screen.getByPlaceholderText('DD.MM.YYYY');+ fireEvent.change(input, { target: { value: '17.07' } });+ fireEvent.keyDown(input, { key: 'Enter' });++ expect(onChange).not.toHaveBeenCalled();+ });++ it('FE-W5DP-012: a manual entry already in locale order is taken as typed', () => {+ render(<CustomDatePicker value="" onChange={onChange} />);+ fireEvent.click(screen.getByRole('button', { name: /enter date manually/i }));+ const input = screen.getByPlaceholderText('DD.MM.YYYY');+ fireEvent.change(input, { target: { value: '07/17/2026' } });+ fireEvent.keyDown(input, { key: 'Enter' });++ expect(onChange).toHaveBeenCalledWith('2026-07-17');+ });++ it('FE-W5DP-013: a two-digit year is expanded into the 2000s', () => {+ render(<CustomDatePicker value="" onChange={onChange} />);+ fireEvent.click(screen.getByRole('button', { name: /enter date manually/i }));+ const input = screen.getByPlaceholderText('DD.MM.YYYY');+ fireEvent.change(input, { target: { value: '07/17/26' } });+ fireEvent.keyDown(input, { key: 'Enter' });++ expect(onChange).toHaveBeenCalledWith('2026-07-17');+ });++ it('FE-W5DP-014: an impossible day/month combination is rejected', () => {+ render(<CustomDatePicker value="" onChange={onChange} />);+ fireEvent.click(screen.getByRole('button', { name: /enter date manually/i }));+ const input = screen.getByPlaceholderText('DD.MM.YYYY');+ fireEvent.change(input, { target: { value: '13/45/2026' } });+ fireEvent.keyDown(input, { key: 'Enter' });++ expect(onChange).not.toHaveBeenCalled();+ });++ it('FE-W5DP-015: a localised manual entry outside [min,max] is rejected', () => {+ render(<CustomDatePicker value="" onChange={onChange} min="2026-03-10" max="2026-03-20" />);+ fireEvent.click(screen.getByRole('button', { name: /enter date manually/i }));+ const input = screen.getByPlaceholderText('DD.MM.YYYY');+ fireEvent.change(input, { target: { value: '03/25/2026' } });+ fireEvent.keyDown(input, { key: 'Enter' });++ expect(onChange).not.toHaveBeenCalled();+ });++ it('FE-W5DP-016: the popup is clamped back into a narrow viewport', () => {+ const originalRect = Element.prototype.getBoundingClientRect;+ const originalWidth = window.innerWidth;+ Element.prototype.getBoundingClientRect = function () {+ return { left: 900, top: 700, right: 1100, bottom: 740, width: 200, height: 40, x: 900, y: 700, toJSON: () => ({}) } as DOMRect;+ };+ Object.defineProperty(window, 'innerWidth', { value: 320, configurable: true });++ try {+ render(<CustomDatePicker value="2026-03-15" onChange={onChange} />);+ openCalendar();+ const dialog = screen.getByRole('dialog');+ // vw < 360 centres the 268px popup; the popup flips above the trigger+ expect(dialog.style.left).toBe('26px');+ expect(dialog.style.top).toBe('336px');+ } finally {+ Element.prototype.getBoundingClientRect = originalRect;+ Object.defineProperty(window, 'innerWidth', { value: originalWidth, configurable: true });+ }+ });++ it('FE-W5DP-017: the popup prefers the visual viewport height when one is reported', () => {+ const originalRect = Element.prototype.getBoundingClientRect;+ Element.prototype.getBoundingClientRect = function () {+ return { left: 20, top: 40, right: 220, bottom: 80, width: 200, height: 40, x: 20, y: 40, toJSON: () => ({}) } as DOMRect;+ };+ Object.defineProperty(window, 'visualViewport', { value: { height: 900 }, configurable: true });++ try {+ render(<CustomDatePicker value="2026-03-15" onChange={onChange} />);+ openCalendar();+ const dialog = screen.getByRole('dialog');+ expect(dialog.style.left).toBe('20px');+ expect(dialog.style.top).toBe('84px');+ } finally {+ Element.prototype.getBoundingClientRect = originalRect;+ Object.defineProperty(window, 'visualViewport', { value: undefined, configurable: true });+ }+ });++ it('FE-W5DP-018: the header arrows and the label highlight on hover', () => {+ render(<CustomDatePicker value="2026-03-15" onChange={onChange} />);+ openCalendar();++ for (const name of [/previous month/i, /next month/i]) {+ const btn = screen.getByRole('button', { name });+ fireEvent.mouseEnter(btn);+ expect(btn.style.color).toBe('var(--text-primary)');+ fireEvent.mouseLeave(btn);+ expect(btn.style.color).toBe('var(--text-faint)');+ }++ const header = screen.getByRole('button', { name: /select month/i });+ fireEvent.mouseEnter(header);+ expect(header.style.background).toBe('var(--bg-hover)');+ fireEvent.mouseLeave(header);+ expect(header.style.background).toBe('none');+ });++ it('FE-W5DP-019: only free day cells take the hover background', () => {+ render(<CustomDatePicker value="2026-03-15" onChange={onChange} min="2026-03-10" max="2026-03-20" />);+ openCalendar();++ const free = dayCell('12');+ fireEvent.mouseEnter(free);+ expect(free.style.background).toBe('var(--bg-hover)');+ fireEvent.mouseLeave(free);+ expect(free.style.background).toBe('transparent');++ const selected = dayCell('15');+ fireEvent.mouseEnter(selected);+ expect(selected.style.background).toBe('var(--accent)');+ fireEvent.mouseLeave(selected);+ expect(selected.style.background).toBe('var(--accent)');++ const blocked = dayCell('5');+ fireEvent.mouseEnter(blocked);+ expect(blocked.style.background).toBe('transparent');+ });++ it('FE-W5DP-020: month and year cells take the hover background unless selected', () => {+ render(<CustomDatePicker value="2026-03-15" onChange={onChange} />);+ openCalendar();+ fireEvent.click(screen.getByRole('button', { name: /select month/i }));++ const may = screen.getByRole('button', { name: 'May 2026' });+ fireEvent.mouseEnter(may);+ expect(may.style.background).toBe('var(--bg-hover)');+ fireEvent.mouseLeave(may);+ expect(may.style.background).toBe('transparent');++ const march = screen.getByRole('button', { name: 'March 2026' });+ fireEvent.mouseEnter(march);+ fireEvent.mouseLeave(march);+ expect(march.style.background).toBe('var(--accent)');++ fireEvent.click(screen.getByRole('button', { name: /select year/i }));+ const y2027 = screen.getByRole('button', { name: '2027' });+ fireEvent.mouseEnter(y2027);+ expect(y2027.style.background).toBe('var(--bg-hover)');+ fireEvent.mouseLeave(y2027);+ expect(y2027.style.background).toBe('transparent');++ const y2026 = screen.getByRole('button', { name: '2026' });+ fireEvent.mouseEnter(y2026);+ fireEvent.mouseLeave(y2026);+ expect(y2026.style.background).toBe('var(--accent)');+ });++ it('FE-W5DP-021: in compact mode the manual-entry trigger moves into the popup footer', () => {+ render(<CustomDatePicker value="2026-03-15" onChange={onChange} compact />);+ openCalendar();++ const keyboard = screen.getByRole('button', { name: /enter date manually/i });+ fireEvent.mouseEnter(keyboard);+ expect(keyboard.style.color).toBe('var(--text-primary)');+ fireEvent.mouseLeave(keyboard);+ expect(keyboard.style.color).toBe('var(--text-faint)');++ const clear = screen.getByRole('button', { name: /clear date/i });+ fireEvent.mouseEnter(clear);+ expect(clear.style.color).toBe('rgb(239, 68, 68)');+ fireEvent.mouseLeave(clear);+ expect(clear.style.color).toBe('var(--text-faint)');++ fireEvent.click(keyboard);+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+ expect(screen.getByPlaceholderText('DD.MM.YYYY')).toHaveProperty('value', '03/15/2026');+ });+});++// FE-W5DTP-001 to FE-W5DTP-002+describe('CustomDateTimePicker branches', () => {+ const onChange = vi.fn();++ beforeEach(() => {+ vi.clearAllMocks();+ useSettingsStore.setState({+ settings: { ...useSettingsStore.getState().settings, time_format: '24h' },+ });+ });++ it('FE-W5DTP-001: clearing the date clears the whole value', () => {+ render(<CustomDateTimePicker value="2026-03-15T09:30" onChange={onChange} />);+ fireEvent.click(screen.getAllByRole('button')[0]);+ fireEvent.click(screen.getByRole('button', { name: /clear date/i }));++ expect(onChange).toHaveBeenCalledWith('');+ });++ it('FE-W5DTP-003: setting a time without a date falls back to today', () => {+ render(<CustomDateTimePicker value="" onChange={onChange} />);+ const clockBtn = screen.getAllByRole('button').filter((b) => b.textContent?.trim() === '').pop();+ fireEvent.click(clockBtn!);+ // hour up on an empty time yields 01:00 on today's date+ const steppers = screen.getAllByRole('button').filter((b) => b.textContent?.trim() === '');+ fireEvent.click(steppers[steppers.length - 4]);++ const today = new Date().toISOString().split('T')[0];+ expect(onChange).toHaveBeenCalledWith(`${today}T01:00`);+ });++ it('FE-W5DTP-002: clearing the time keeps the date part', () => {+ render(<CustomDateTimePicker value="2026-03-15T09:30" onChange={onChange} />);+ const clockBtn = screen.getAllByRole('button').filter((b) => b.textContent?.trim() === '').pop();+ fireEvent.click(clockBtn!);+ fireEvent.click(screen.getByText('✕'));++ expect(onChange).toHaveBeenCalledWith('2026-03-15');+ });+});diff --git a/client/src/components/shared/CustomTimePicker.test.tsx b/client/src/components/shared/CustomTimePicker.test.tsxindex 55e84a305..9c6b8d1a8 100644--- a/client/src/components/shared/CustomTimePicker.test.tsx+++ b/client/src/components/shared/CustomTimePicker.test.tsx@@ -206,3 +206,273 @@ describe('CustomTimePicker', () => {expect(screen.queryByText('✕')).toBeNull(); // clear button gone = dropdown closed});});++// FE-W5TP-001 to FE-W5TP-024 — remaining branches: 12h display arms, null-hour+// stepping, the minute-down button, handleInput/handleBlur parse arms and the+// hover styling of the stepper buttons.+describe('CustomTimePicker branches', () => {+ const onChange = vi.fn();++ // [0] clock trigger, [1] hour up, [2] hour down, [3] min up, [4] min down,+ // [5]/[6] AM/PM up/down (12h only). The clear button carries a glyph.+ const steppers = () => screen.getAllByRole('button').filter(b => b.textContent?.trim() === '');+ const openDropdown = () => fireEvent.click(steppers()[0]);++ beforeEach(() => {+ vi.clearAllMocks();+ resetAllStores();+ seedStore(useSettingsStore, { settings: buildSettings({ time_format: '24h' }) });+ });++ const use12h = () => seedStore(useSettingsStore, { settings: buildSettings({ time_format: '12h' }) });++ it('FE-W5TP-001: renders midnight as 12 AM in 12h mode', () => {+ use12h();+ render(<CustomTimePicker value="00:15" onChange={onChange} />);+ expect(screen.getByRole('textbox')).toHaveProperty('value', '12:15 AM');+ });++ it('FE-W5TP-002: keeps morning hours unshifted in 12h mode', () => {+ use12h();+ render(<CustomTimePicker value="09:05" onChange={onChange} />);+ expect(screen.getByRole('textbox')).toHaveProperty('value', '9:05 AM');+ });++ it('FE-W5TP-003: leaves an unparseable value untouched in 12h mode', () => {+ use12h();+ render(<CustomTimePicker value="later" onChange={onChange} />);+ expect(screen.getByRole('textbox')).toHaveProperty('value', 'later');+ });++ it('FE-W5TP-004: shows -- for an unparseable hour and minute', () => {+ render(<CustomTimePicker value="later" onChange={onChange} />);+ openDropdown();+ expect(screen.getAllByText('--')).toHaveLength(2);+ });++ it('FE-W5TP-005: stepping up from an unparseable hour lands on 00', () => {+ render(<CustomTimePicker value="later" onChange={onChange} />);+ openDropdown();+ fireEvent.click(steppers()[1]);+ expect(onChange).toHaveBeenCalledWith('00:00');+ });++ it('FE-W5TP-006: stepping down from an unparseable hour lands on 00', () => {+ render(<CustomTimePicker value="later" onChange={onChange} />);+ openDropdown();+ fireEvent.click(steppers()[2]);+ expect(onChange).toHaveBeenCalledWith('00:00');+ });++ it('FE-W5TP-007: the minute-down button borrows an hour when it wraps below zero', () => {+ render(<CustomTimePicker value="10:00" onChange={onChange} />);+ openDropdown();+ fireEvent.click(steppers()[4]);+ expect(onChange).toHaveBeenCalledWith('09:55');+ });++ it('FE-W5TP-008: the minute-down button keeps the hour when it does not wrap', () => {+ render(<CustomTimePicker value="10:30" onChange={onChange} />);+ openDropdown();+ fireEvent.click(steppers()[4]);+ expect(onChange).toHaveBeenCalledWith('10:25');+ });++ it('FE-W5TP-009: stepping minutes with no minute set falls back to :00', () => {+ render(<CustomTimePicker value="10" onChange={onChange} />);+ openDropdown();+ fireEvent.click(steppers()[3]);+ expect(onChange).toHaveBeenLastCalledWith('10:00');+ fireEvent.click(steppers()[4]);+ expect(onChange).toHaveBeenLastCalledWith('10:00');+ });++ it('FE-W5TP-010: typing in 12h mode is passed through unparsed', () => {+ use12h();+ render(<CustomTimePicker value="" onChange={onChange} />);+ fireEvent.change(screen.getByRole('textbox'), { target: { value: '5:30 pm' } });+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith('5:30 pm');+ });++ it('FE-W5TP-011: typing four digits inserts the colon while editing', () => {+ render(<CustomTimePicker value="" onChange={onChange} />);+ fireEvent.change(screen.getByRole('textbox'), { target: { value: '1430' } });+ expect(onChange).toHaveBeenLastCalledWith('14:30');+ });++ it('FE-W5TP-012: typing a single-digit hour pads it while editing', () => {+ render(<CustomTimePicker value="" onChange={onChange} />);+ fireEvent.change(screen.getByRole('textbox'), { target: { value: '9:05' } });+ expect(onChange).toHaveBeenLastCalledWith('09:05');+ });++ it('FE-W5TP-013: typing a complete HH:MM leaves it as is', () => {+ render(<CustomTimePicker value="" onChange={onChange} />);+ fireEvent.change(screen.getByRole('textbox'), { target: { value: '14:30' } });+ expect(onChange).toHaveBeenCalledTimes(2);+ expect(onChange).toHaveBeenLastCalledWith('14:30');+ });++ it('FE-W5TP-014: blurring an empty field does not emit', () => {+ render(<CustomTimePicker value="" onChange={onChange} />);+ fireEvent.blur(screen.getByRole('textbox'));+ expect(onChange).not.toHaveBeenCalled();+ });++ it('FE-W5TP-015: blurring an unparseable value does not emit', () => {+ render(<CustomTimePicker value="later" onChange={onChange} />);+ fireEvent.blur(screen.getByRole('textbox'));+ expect(onChange).not.toHaveBeenCalled();+ });++ it('FE-W5TP-016: 12h blur handles a bare hour with a meridiem', () => {+ use12h();+ render(<CustomTimePicker value="5pm" onChange={onChange} />);+ fireEvent.blur(screen.getByRole('textbox'));+ expect(onChange).toHaveBeenCalledWith('17:00');+ });++ it('FE-W5TP-017: 12h blur maps 12 AM to midnight and 12 PM to noon', () => {+ use12h();+ const { unmount } = render(<CustomTimePicker value="12:30 AM" onChange={onChange} />);+ fireEvent.blur(screen.getByRole('textbox'));+ expect(onChange).toHaveBeenCalledWith('00:30');+ unmount();++ onChange.mockClear();+ render(<CustomTimePicker value="12:30 PM" onChange={onChange} />);+ fireEvent.blur(screen.getByRole('textbox'));+ expect(onChange).toHaveBeenCalledWith('12:30');+ });++ it('FE-W5TP-018: 12h blur falls back to the numeric parser when no meridiem is given', () => {+ use12h();+ render(<CustomTimePicker value="1430" onChange={onChange} />);+ fireEvent.blur(screen.getByRole('textbox'));+ expect(onChange).toHaveBeenCalledWith('14:30');+ });++ it('FE-W5TP-019: blur clamps out-of-range hours and minutes', () => {+ render(<CustomTimePicker value="99:99" onChange={onChange} />);+ fireEvent.blur(screen.getByRole('textbox'));+ expect(onChange).toHaveBeenCalledWith('23:59');+ });++ it('FE-W5TP-020: blur pads a three-digit entry to HH:MM', () => {+ render(<CustomTimePicker value="945" onChange={onChange} />);+ fireEvent.blur(screen.getByRole('textbox'));+ expect(onChange).toHaveBeenCalledWith('09:45');+ });++ it('FE-W5TP-021: a mousedown inside the field keeps the dropdown open', () => {+ const { container } = render(<CustomTimePicker value="10:00" onChange={onChange} />);+ openDropdown();+ fireEvent.mouseDown(container.firstElementChild!);+ expect(screen.getByText('✕')).toBeInTheDocument();++ fireEvent.mouseDown(screen.getByText('✕'));+ expect(screen.getByText('✕')).toBeInTheDocument();+ });++ it('FE-W5TP-022: the AM/PM stepper flips an AM hour to PM in both directions', () => {+ use12h();+ render(<CustomTimePicker value="02:00" onChange={onChange} />);+ openDropdown();+ expect(screen.getByText('AM')).toBeInTheDocument();++ fireEvent.click(steppers()[5]);+ expect(onChange).toHaveBeenLastCalledWith('14:00');+ fireEvent.click(steppers()[6]);+ expect(onChange).toHaveBeenLastCalledWith('14:00');+ });++ it('FE-W5TP-023: the AM/PM stepper flips a PM hour back to AM', () => {+ use12h();+ render(<CustomTimePicker value="14:00" onChange={onChange} />);+ openDropdown();+ fireEvent.click(steppers()[5]);+ expect(onChange).toHaveBeenLastCalledWith('02:00');+ fireEvent.click(steppers()[6]);+ expect(onChange).toHaveBeenLastCalledWith('02:00');+ });++ it('FE-W5TP-025: stepping minutes with neither hour nor minute set lands on 00:00', () => {+ render(<CustomTimePicker value="later" onChange={onChange} />);+ openDropdown();+ fireEvent.click(steppers()[3]);+ expect(onChange).toHaveBeenLastCalledWith('00:00');+ fireEvent.click(steppers()[4]);+ expect(onChange).toHaveBeenLastCalledWith('00:00');+ });++ it('FE-W5TP-028: minute wrapping carries an unparseable hour to 01 and 23', () => {+ const { unmount } = render(<CustomTimePicker value="x:55" onChange={onChange} />);+ openDropdown();+ fireEvent.click(steppers()[3]);+ expect(onChange).toHaveBeenLastCalledWith('01:00');+ unmount();++ onChange.mockClear();+ render(<CustomTimePicker value="x:00" onChange={onChange} />);+ openDropdown();+ fireEvent.click(steppers()[4]);+ expect(onChange).toHaveBeenLastCalledWith('23:55');+ });++ it('FE-W5TP-029: the AM/PM stepper defaults the minute when none is set', () => {+ use12h();+ const { unmount } = render(<CustomTimePicker value="14" onChange={onChange} />);+ openDropdown();+ fireEvent.click(steppers()[5]);+ expect(onChange).toHaveBeenLastCalledWith('02:00');++ onChange.mockClear();+ fireEvent.click(steppers()[6]);+ expect(onChange).toHaveBeenLastCalledWith('02:00');+ unmount();++ onChange.mockClear();+ render(<CustomTimePicker value="02" onChange={onChange} />);+ openDropdown();+ fireEvent.click(steppers()[5]);+ expect(onChange).toHaveBeenLastCalledWith('14:00');+ fireEvent.click(steppers()[6]);+ expect(onChange).toHaveBeenLastCalledWith('14:00');+ });++ it('FE-W5TP-026: typing a value with no digits is passed through unchanged', () => {+ render(<CustomTimePicker value="" onChange={onChange} />);+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'noon' } });+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith('noon');+ });++ it('FE-W5TP-027: 12h blur keeps an AM hour below noon', () => {+ use12h();+ render(<CustomTimePicker value="5:30 AM" onChange={onChange} />);+ fireEvent.blur(screen.getByRole('textbox'));+ expect(onChange).toHaveBeenCalledWith('05:30');+ });++ it('FE-W5TP-024: the steppers and the clear button highlight on hover', () => {+ use12h();+ render(<CustomTimePicker value="00:30" onChange={onChange} />);+ openDropdown();+ // 12 is the 12h rendering of hour 0+ expect(screen.getByText('12')).toBeInTheDocument();++ for (const btn of steppers()) {+ fireEvent.mouseEnter(btn);+ expect(btn.style.color).toBe('var(--text-primary)');+ fireEvent.mouseLeave(btn);+ expect(btn.style.color).toBe('var(--text-faint)');+ }++ const clear = screen.getByText('✕');+ fireEvent.mouseEnter(clear);+ expect(clear.style.color).toBe('rgb(239, 68, 68)');+ fireEvent.mouseLeave(clear);+ expect(clear.style.color).toBe('var(--text-faint)');+ });+});diff --git a/client/src/components/shared/GuestBadge.test.tsx b/client/src/components/shared/GuestBadge.test.tsxnew file mode 100644index 000000000..b5a2f4311--- /dev/null+++ b/client/src/components/shared/GuestBadge.test.tsx@@ -0,0 +1,24 @@+// FE-W4GB-001 to FE-W4GB-003+import { describe, it, expect } from 'vitest'+import { render, screen } from '../../../tests/helpers/render'+import GuestBadge from './GuestBadge'++describe('GuestBadge', () => {+ it('FE-W4GB-001: renders the translated guest label with the accountless hint as title', () => {+ render(<GuestBadge />)+ const pill = screen.getByTitle(/without an account/i)++ expect(pill).toHaveTextContent('Guest')+ expect(pill.querySelector('svg')).not.toBeNull()+ })++ it('FE-W4GB-002: sizes the label at 10px by default', () => {+ render(<GuestBadge />)+ expect(screen.getByTitle(/without an account/i)).toHaveStyle({ fontSize: 'calc(10px * var(--fs-scale-caption, 1))' })+ })++ it('FE-W4GB-003: shrinks to 9px in the xs variant', () => {+ render(<GuestBadge size="xs" />)+ expect(screen.getByTitle(/without an account/i)).toHaveStyle({ fontSize: 'calc(9px * var(--fs-scale-caption, 1))' })+ })+})diff --git a/client/src/components/shared/Skeleton.test.tsx b/client/src/components/shared/Skeleton.test.tsxnew file mode 100644index 000000000..59af118f1--- /dev/null+++ b/client/src/components/shared/Skeleton.test.tsx@@ -0,0 +1,66 @@+// FE-W4SKEL-001 to FE-W4SKEL-008+import { describe, it, expect } from 'vitest'+import { render } from '../../../tests/helpers/render'+import Skeleton, { SpotlightSkeleton, TripCardSkeleton, DaySkeleton } from './Skeleton'++describe('Skeleton', () => {+ it('FE-W4SKEL-001: defaults to a 14px-high shimmer bar hidden from a11y', () => {+ const { container } = render(<Skeleton />)+ const el = container.querySelector('.trek-skeleton') as HTMLElement++ expect(el).not.toBeNull()+ expect(el.style.height).toBe('14px')+ expect(el).toHaveAttribute('aria-hidden')+ })++ it('FE-W4SKEL-002: applies width, height and radius', () => {+ const { container } = render(<Skeleton width={120} height={40} radius={8} />)+ const el = container.querySelector('.trek-skeleton') as HTMLElement++ expect(el.style.width).toBe('120px')+ expect(el.style.height).toBe('40px')+ expect(el.style.borderRadius).toBe('8px')+ })++ it('FE-W4SKEL-003: accepts string sizes and merges extra style', () => {+ const { container } = render(<Skeleton width="60%" style={{ marginBottom: 8 }} />)+ const el = container.querySelector('.trek-skeleton') as HTMLElement++ expect(el.style.width).toBe('60%')+ expect(el.style.marginBottom).toBe('8px')+ })++ it('FE-W4SKEL-004: appends a caller className without dropping the base class', () => {+ const { container } = render(<Skeleton className="mt-2" />)+ const el = container.querySelector('.trek-skeleton') as HTMLElement++ expect(el.className).toBe('trek-skeleton mt-2')+ })++ it('FE-W4SKEL-005: trims the class list when no className is given', () => {+ const { container } = render(<Skeleton />)+ expect((container.firstElementChild as HTMLElement).className).toBe('trek-skeleton')+ })+})++describe('composed skeletons', () => {+ it('FE-W4SKEL-006: SpotlightSkeleton renders the hero backdrop plus two bars', () => {+ const { container } = render(<SpotlightSkeleton />)++ expect(container.querySelectorAll('.trek-skeleton')).toHaveLength(3)+ expect((container.firstElementChild as HTMLElement).style.minHeight).toBe('340px')+ })++ it('FE-W4SKEL-007: TripCardSkeleton renders a cover plus two text bars', () => {+ const { container } = render(<TripCardSkeleton />)+ const bars = container.querySelectorAll('.trek-skeleton')++ expect(bars).toHaveLength(3)+ expect((bars[0] as HTMLElement).style.height).toBe('140px')+ })++ it('FE-W4SKEL-008: DaySkeleton renders three stacked bars', () => {+ const { container } = render(<DaySkeleton />)+ expect(container.querySelectorAll('.trek-skeleton')).toHaveLength(3)+ })+})diff --git a/client/src/components/shared/Spinner.test.tsx b/client/src/components/shared/Spinner.test.tsxnew file mode 100644index 000000000..84b4996ca--- /dev/null+++ b/client/src/components/shared/Spinner.test.tsx@@ -0,0 +1,44 @@+// FE-W4SPIN-001 to FE-W4SPIN-005+import { describe, it, expect } from 'vitest'+import { render } from '../../../tests/helpers/render'+import { Spinner, PageSpinner } from './Spinner'++describe('Spinner', () => {+ it('FE-W4SPIN-001: renders the default page-loader ring', () => {+ const { container } = render(<Spinner />)+ const el = container.firstElementChild as HTMLElement++ expect(el.className).toBe('w-6 h-6 border-2 border-zinc-300 border-t-zinc-900 rounded-full animate-spin')+ })++ it('FE-W4SPIN-002: keeps caller classes and still spins', () => {+ const { container } = render(<Spinner className="w-10 h-10 border-4 border-accent" />)+ const el = container.firstElementChild as HTMLElement++ expect(el.className).toBe('w-10 h-10 border-4 border-accent rounded-full animate-spin')+ })+})++describe('PageSpinner', () => {+ it('FE-W4SPIN-003: centres the ring in a flex wrapper by default', () => {+ const { container } = render(<PageSpinner />)+ const wrapper = container.firstElementChild as HTMLElement++ expect(wrapper.className).toBe('flex items-center justify-center')+ expect((wrapper.firstElementChild as HTMLElement).className).toContain('animate-spin')+ })++ it('FE-W4SPIN-004: forwards wrapper classes and style', () => {+ const { container } = render(<PageSpinner wrapperClassName="h-screen grid place-items-center" wrapperStyle={{ minHeight: 200 }} />)+ const wrapper = container.firstElementChild as HTMLElement++ expect(wrapper.className).toBe('h-screen grid place-items-center')+ expect(wrapper.style.minHeight).toBe('200px')+ })++ it('FE-W4SPIN-005: forwards the ring className down to the Spinner', () => {+ const { container } = render(<PageSpinner className="w-8 h-8 border-2" />)++ expect((container.querySelector('.animate-spin') as HTMLElement).className).toBe('w-8 h-8 border-2 rounded-full animate-spin')+ })+})diff --git a/client/src/components/shared/StarRating.test.tsx b/client/src/components/shared/StarRating.test.tsxnew file mode 100644index 000000000..c02fe01b5--- /dev/null+++ b/client/src/components/shared/StarRating.test.tsx@@ -0,0 +1,144 @@+// FE-W4STAR-001 to FE-W4STAR-014+import { describe, it, expect, vi, beforeEach } from 'vitest'+import type { PlaceRatingVote } from '@trek/shared'+import { render, screen, fireEvent, within } from '../../../tests/helpers/render'+import { useAuthStore } from '../../store/authStore'+import PlaceRating, { Stars } from './StarRating'++const VOTES: PlaceRatingVote[] = [+ { user_id: 1, username: 'ada', avatar: 'ada.png', rating: 5 },+ { user_id: 2, username: 'bob', avatar: null, rating: 3 },+]++beforeEach(() => {+ useAuthStore.setState({ user: { id: 1, username: 'ada' } as never })+})++describe('Stars', () => {+ it('FE-W4STAR-001: renders five stars and is not a radiogroup in display mode', () => {+ const { container } = render(<Stars value={3} />)++ expect(container.querySelectorAll('svg')).toHaveLength(3 + 5)+ expect(container.querySelector('[role="radiogroup"]')).toBeNull()+ expect(container.querySelectorAll('button')).toHaveLength(0)+ })++ it('FE-W4STAR-002: clips the overlay for a fractional average', () => {+ const { container } = render(<Stars value={3.4} />)+ const overlays = Array.from(container.querySelectorAll('span > span')) as HTMLElement[]+ const widths = overlays.map(o => o.style.width).filter(Boolean)++ expect(widths).toHaveLength(4)+ expect(widths.slice(0, 3)).toEqual(['100%', '100%', '100%'])+ expect(Math.round(parseFloat(widths[3]))).toBe(40)+ })++ it('FE-W4STAR-003: exposes a radiogroup with five radios when interactive', () => {+ render(<Stars value={0} onRate={() => {}} ariaLabel="Your rating" />)++ expect(screen.getByRole('radiogroup', { name: 'Your rating' })).toBeInTheDocument()+ expect(screen.getAllByRole('radio')).toHaveLength(5)+ })++ it('FE-W4STAR-004: marks the own vote as checked', () => {+ render(<Stars value={4} onRate={() => {}} myRating={4} />)++ expect(screen.getByRole('radio', { name: '4' })).toHaveAttribute('aria-checked', 'true')+ expect(screen.getByRole('radio', { name: '2' })).toHaveAttribute('aria-checked', 'false')+ })++ it('FE-W4STAR-005: casting a new vote reports the star index', () => {+ const onRate = vi.fn()+ render(<Stars value={0} onRate={onRate} myRating={null} />)++ fireEvent.click(screen.getByRole('radio', { name: '4' }))++ expect(onRate).toHaveBeenCalledWith(4)+ })++ it('FE-W4STAR-006: clicking the own vote clears it', () => {+ const onRate = vi.fn()+ render(<Stars value={3} onRate={onRate} myRating={3} />)++ fireEvent.click(screen.getByRole('radio', { name: '3' }))++ expect(onRate).toHaveBeenCalledWith(null)+ })++ it('FE-W4STAR-007: hovering previews the hovered value and leaving restores it', () => {+ const { container } = render(<Stars value={1} onRate={() => {}} />)+ const filled = () => Array.from(container.querySelectorAll('span > span')).filter(o => (o as HTMLElement).style.width).length++ expect(filled()).toBe(1)+ fireEvent.mouseEnter(screen.getByRole('radio', { name: '4' }))+ expect(filled()).toBe(4)++ fireEvent.mouseLeave(container.querySelector('[role="radiogroup"]')!)+ expect(filled()).toBe(1)+ })++ it('FE-W4STAR-008: focus previews and blur clears the preview', () => {+ const { container } = render(<Stars value={0} onRate={() => {}} />)+ const filled = () => Array.from(container.querySelectorAll('span > span')).filter(o => (o as HTMLElement).style.width).length++ fireEvent.focus(screen.getByRole('radio', { name: '5' }))+ expect(filled()).toBe(5)++ fireEvent.blur(screen.getByRole('radio', { name: '5' }))+ expect(filled()).toBe(0)+ })+})++describe('PlaceRating', () => {+ it('FE-W4STAR-009: shows the rounded average and the vote count', () => {+ render(<PlaceRating ratings={VOTES} ratingAvg={4.25} />)++ // The average is rendered through toLocaleString, so build the expectation the same way.+ expect(screen.getByText('(2)').parentElement).toHaveTextContent(`${(4.3).toLocaleString()} (2)`)+ })++ it('FE-W4STAR-010: shows the not-rated hint when there is no average', () => {+ render(<PlaceRating ratings={[]} ratingAvg={null} />)++ expect(screen.getByText(/not rated/i)).toBeInTheDocument()+ })++ it('FE-W4STAR-011: renders the voter avatar strip with image and initial fallback', () => {+ const { container } = render(<PlaceRating ratings={VOTES} ratingAvg={4} />)++ expect(container.querySelector('img')).toHaveAttribute('src', '/uploads/avatars/ada.png')+ expect(screen.getByText('B')).toBeInTheDocument()+ })++ it('FE-W4STAR-012: hides the avatar strip in compact mode', () => {+ const { container } = render(<PlaceRating ratings={VOTES} ratingAvg={4} compact />)++ expect(container.querySelector('img')).toBeNull()+ })++ it('FE-W4STAR-013: hovering opens a voter tooltip that marks the current user', () => {+ const { container } = render(<PlaceRating ratings={VOTES} ratingAvg={4} />)+ fireEvent.mouseEnter(container.firstElementChild!)++ const tip = screen.getByRole('tooltip')+ expect(within(tip).getByText('ada (you)')).toBeInTheDocument()+ expect(within(tip).getByText('bob')).toBeInTheDocument()++ fireEvent.mouseLeave(container.firstElementChild!)+ expect(screen.queryByRole('tooltip')).toBeNull()+ })++ it('FE-W4STAR-014: does not open a tooltip when nobody voted', () => {+ const { container } = render(<PlaceRating ratings={[]} ratingAvg={null} />)+ fireEvent.mouseEnter(container.firstElementChild!)++ expect(screen.queryByRole('tooltip')).toBeNull()+ })++ it('FE-W4STAR-015: pre-selects the signed-in user own vote in the stars', () => {+ useAuthStore.setState({ user: { id: 2, username: 'bob' } as never })+ render(<PlaceRating ratings={VOTES} ratingAvg={4} onRate={() => {}} />)++ expect(screen.getByRole('radio', { name: '3' })).toHaveAttribute('aria-checked', 'true')+ })+})diff --git a/client/src/components/shared/Tooltip.test.tsx b/client/src/components/shared/Tooltip.test.tsxnew file mode 100644index 000000000..3652c5356--- /dev/null+++ b/client/src/components/shared/Tooltip.test.tsx@@ -0,0 +1,173 @@+// FE-W4TIP-001 to FE-W4TIP-013+import { createRef, useRef } from 'react'+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { render, screen, fireEvent, act } from '../../../tests/helpers/render'+import Tooltip from './Tooltip'++beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true })+})++afterEach(() => {+ vi.useRealTimers()+ vi.restoreAllMocks()+})++function hover(el: HTMLElement) {+ fireEvent.mouseEnter(el)+ act(() => { vi.advanceTimersByTime(300) })+}++describe('Tooltip', () => {+ it('FE-W4TIP-001: renders the trigger and no tooltip until hovered', () => {+ render(<Tooltip label="Delete"><button>x</button></Tooltip>)++ expect(screen.getByRole('button', { name: 'x' })).toBeInTheDocument()+ expect(screen.queryByRole('tooltip')).toBeNull()+ })++ it('FE-W4TIP-002: opens only after the delay has elapsed', () => {+ render(<Tooltip label="Delete" delay={250}><button>x</button></Tooltip>)++ fireEvent.mouseEnter(screen.getByRole('button'))+ act(() => { vi.advanceTimersByTime(200) })+ expect(screen.queryByRole('tooltip')).toBeNull()++ act(() => { vi.advanceTimersByTime(100) })+ expect(screen.getByRole('tooltip')).toHaveTextContent('Delete')+ })++ it('FE-W4TIP-003: leaving cancels a pending open', () => {+ render(<Tooltip label="Delete"><button>x</button></Tooltip>)+ const trigger = screen.getByRole('button')++ fireEvent.mouseEnter(trigger)+ fireEvent.mouseLeave(trigger)+ act(() => { vi.advanceTimersByTime(500) })++ expect(screen.queryByRole('tooltip')).toBeNull()+ })++ it('FE-W4TIP-004: focus opens and blur closes the tooltip', () => {+ render(<Tooltip label="Delete"><button>x</button></Tooltip>)+ const trigger = screen.getByRole('button')++ fireEvent.focus(trigger)+ act(() => { vi.advanceTimersByTime(300) })+ expect(screen.getByRole('tooltip')).toBeInTheDocument()++ fireEvent.blur(trigger)+ expect(screen.queryByRole('tooltip')).toBeNull()+ })++ it('FE-W4TIP-005: a disabled tooltip never opens', () => {+ render(<Tooltip label="Delete" disabled><button>x</button></Tooltip>)++ hover(screen.getByRole('button'))++ expect(screen.queryByRole('tooltip')).toBeNull()+ })++ it('FE-W4TIP-006: an empty label never opens', () => {+ render(<Tooltip label=""><button>x</button></Tooltip>)++ hover(screen.getByRole('button'))++ expect(screen.queryByRole('tooltip')).toBeNull()+ })++ it('FE-W4TIP-007: still chains the original handlers of the child', () => {+ const onMouseEnter = vi.fn()+ const onMouseLeave = vi.fn()+ const onFocus = vi.fn()+ const onBlur = vi.fn()+ render(+ <Tooltip label="Delete">+ <button onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} onFocus={onFocus} onBlur={onBlur}>x</button>+ </Tooltip>,+ )+ const trigger = screen.getByRole('button')++ fireEvent.mouseEnter(trigger)+ fireEvent.mouseLeave(trigger)+ fireEvent.focus(trigger)+ fireEvent.blur(trigger)++ expect(onMouseEnter).toHaveBeenCalledOnce()+ expect(onMouseLeave).toHaveBeenCalledOnce()+ expect(onFocus).toHaveBeenCalledOnce()+ expect(onBlur).toHaveBeenCalledOnce()+ })++ it('FE-W4TIP-008: forwards the node to an object ref on the child', () => {+ const ref = createRef<HTMLButtonElement>()+ render(<Tooltip label="Delete"><button ref={ref}>x</button></Tooltip>)++ expect(ref.current).toBe(screen.getByRole('button'))+ })++ it('FE-W4TIP-009: forwards the node to a callback ref on the child', () => {+ const seen: (HTMLElement | null)[] = []+ render(<Tooltip label="Delete"><button ref={(n: HTMLButtonElement | null) => { seen.push(n) }}>x</button></Tooltip>)++ expect(seen[0]).toBe(screen.getByRole('button'))+ })++ it('FE-W4TIP-010: positions the tooltip per placement and clamps it into the viewport', () => {+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue({+ top: 100, bottom: 130, left: 200, right: 260, width: 60, height: 30, x: 200, y: 100, toJSON: () => ({}),+ } as DOMRect)++ const { unmount } = render(<Tooltip label="Delete" placement="bottom"><button>x</button></Tooltip>)+ hover(screen.getByRole('button'))+ expect(screen.getByRole('tooltip')).toHaveStyle({ top: '136px' })+ unmount()++ render(<Tooltip label="Delete" placement="right"><button>x</button></Tooltip>)+ hover(screen.getByRole('button'))+ expect(screen.getByRole('tooltip')).toHaveStyle({ left: '266px' })+ })++ it('FE-W4TIP-011: clamps a top/left placement to the viewport padding', () => {+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue({+ top: 0, bottom: 20, left: 0, right: 20, width: 20, height: 20, x: 0, y: 0, toJSON: () => ({}),+ } as DOMRect)++ const { unmount } = render(<Tooltip label="Delete" placement="top"><button>x</button></Tooltip>)+ hover(screen.getByRole('button'))+ expect(screen.getByRole('tooltip')).toHaveStyle({ top: '6px' })+ unmount()++ render(<Tooltip label="Delete" placement="left"><button>x</button></Tooltip>)+ hover(screen.getByRole('button'))+ expect(screen.getByRole('tooltip')).toHaveStyle({ left: '6px' })+ })++ it('FE-W4TIP-012: clears a pending timer when the trigger unmounts', () => {+ const clear = vi.spyOn(window, 'clearTimeout')+ const { unmount } = render(<Tooltip label="Delete"><button>x</button></Tooltip>)++ fireEvent.mouseEnter(screen.getByRole('button'))+ unmount()++ expect(clear).toHaveBeenCalled()+ })+})++describe('Tooltip — inside a component that owns the ref', () => {+ it('FE-W4TIP-013: keeps the owner ref pointing at the trigger', () => {+ function Owner() {+ const ref = useRef<HTMLButtonElement>(null)+ return (+ <Tooltip label="Delete">+ <button ref={ref} onClick={() => { ref.current?.setAttribute('data-clicked', '1') }}>x</button>+ </Tooltip>+ )+ }+ render(<Owner />)++ fireEvent.click(screen.getByRole('button'))++ expect(screen.getByRole('button')).toHaveAttribute('data-clicked', '1')+ })+})diff --git a/client/src/components/shared/TripLoadingSplash.test.tsx b/client/src/components/shared/TripLoadingSplash.test.tsxnew file mode 100644index 000000000..b78820325--- /dev/null+++ b/client/src/components/shared/TripLoadingSplash.test.tsx@@ -0,0 +1,99 @@+// FE-W4TLS-001 to FE-W4TLS-007+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { render, screen, act } from '../../../tests/helpers/render'++vi.mock('../../mobile/components/MDancingTrek', () => ({+ default: ({ scene, mood, size }: { scene: string; mood: string; size: number }) =>+ <div data-testid="mascot" data-scene={scene} data-mood={mood} data-size={size} />,+}))++import TripLoadingSplash from './TripLoadingSplash'++function stubReducedMotion(reduce: boolean) {+ Object.defineProperty(window, 'matchMedia', {+ writable: true,+ configurable: true,+ value: vi.fn((query: string) => ({+ matches: reduce && query.includes('reduced-motion'),+ media: query,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ })),+ })+}++beforeEach(() => {+ stubReducedMotion(false)+ vi.useFakeTimers({ shouldAdvanceTime: true })+})++afterEach(() => {+ vi.useRealTimers()+ vi.restoreAllMocks()+})++describe('TripLoadingSplash', () => {+ it('FE-W4TLS-001: announces itself as a status region labelled with the trip title', () => {+ render(<TripLoadingSplash title="Iceland 2026" />)+ const root = screen.getByRole('status')++ expect(root).toHaveAttribute('aria-label', 'Iceland 2026')+ expect(screen.getByText('Iceland 2026')).toBeInTheDocument()+ })++ it('FE-W4TLS-002: falls back to the TREK wordmark without a title', () => {+ render(<TripLoadingSplash />)++ expect(screen.getByRole('status')).toHaveAttribute('aria-label', 'TREK')+ expect(screen.getByText('TREK')).toBeInTheDocument()+ })++ it('FE-W4TLS-003: starts on the packing scene', () => {+ render(<TripLoadingSplash />)++ expect(screen.getByTestId('mascot')).toHaveAttribute('data-scene', 'packing')+ expect(screen.getByTestId('mascot')).toHaveAttribute('data-mood', 'happy')+ })++ it('FE-W4TLS-004: advances through the journey scenes and loops', () => {+ render(<TripLoadingSplash />)++ act(() => { vi.advanceTimersByTime(1400) })+ expect(screen.getByTestId('mascot')).toHaveAttribute('data-scene', 'transport')++ act(() => { vi.advanceTimersByTime(1400 * 2) })+ expect(screen.getByTestId('mascot')).toHaveAttribute('data-scene', 'collections')++ act(() => { vi.advanceTimersByTime(1400) })+ expect(screen.getByTestId('mascot')).toHaveAttribute('data-scene', 'packing')+ })++ it('FE-W4TLS-005: widens the beat dot of the active step', () => {+ const { container } = render(<TripLoadingSplash />)+ const dots = () => Array.from(container.querySelectorAll('.rounded-full')) as HTMLElement[]++ expect(dots().map(d => d.style.width)).toEqual(['20px', '6px', '6px', '6px'])++ act(() => { vi.advanceTimersByTime(1400) })+ expect(dots().map(d => d.style.width)).toEqual(['6px', '20px', '6px', '6px'])+ })++ it('FE-W4TLS-006: parks on the loading-photos step under reduced motion', () => {+ stubReducedMotion(true)+ const { container } = render(<TripLoadingSplash />)++ expect(screen.getByTestId('mascot')).toHaveAttribute('data-scene', 'dashboard')++ act(() => { vi.advanceTimersByTime(1400 * 3) })+ expect(screen.getByTestId('mascot')).toHaveAttribute('data-scene', 'dashboard')+ expect((container.querySelectorAll('.rounded-full')[2] as HTMLElement).style.width).toBe('20px')+ })++ it('FE-W4TLS-007: skips the mascot entry animation under reduced motion', () => {+ stubReducedMotion(true)+ const { container } = render(<TripLoadingSplash />)+ const stage = container.querySelector('.m-splash-content > div > div') as HTMLElement++ expect(stage.style.animation).toBe('')+ })+})