feat(web): add /discover route with search + request flow

Local-input + 250ms debounce drives Lidarr search; tab switch refetches
with new kind. Track-kind Request opens a confirm modal explaining the
album that will be added; Confirm fires createRequest, Cancel is a no-op.
Successful requests flip the card to 'requested' optimistically.
Shell nav now exposes /discover between Search and Playlists.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-04-29 22:15:52 -04:00
parent d27b381250
commit 8a12b8c571
4 changed files with 467 additions and 1 deletions
+1
View File
@@ -25,6 +25,7 @@
{ href: '/', label: 'Library' },
{ href: '/library/liked', label: 'Liked' },
{ href: '/search', label: 'Search' },
{ href: '/discover', label: 'Discover' },
{ href: '/playlists', label: 'Playlists' },
{ href: '/settings', label: 'Settings' }
];
+2 -1
View File
@@ -28,10 +28,11 @@ describe('Shell', () => {
expect(screen.getByText('alice')).toBeInTheDocument();
});
test('renders three nav items: Library, Search, Playlists', () => {
test('renders nav items including Discover between Search and Playlists', () => {
render(Shell);
expect(screen.getByRole('link', { name: 'Library' })).toHaveAttribute('href', '/');
expect(screen.getByRole('link', { name: 'Search' })).toHaveAttribute('href', '/search');
expect(screen.getByRole('link', { name: 'Discover' })).toHaveAttribute('href', '/discover');
expect(screen.getByRole('link', { name: 'Playlists' })).toHaveAttribute('href', '/playlists');
});
+222
View File
@@ -0,0 +1,222 @@
<script lang="ts">
import { createLidarrSearchQuery } from '$lib/api/lidarr';
import { createRequest } from '$lib/api/requests';
import DiscoverResultCard from '$lib/components/DiscoverResultCard.svelte';
import ApiErrorBanner from '$lib/components/ApiErrorBanner.svelte';
import type {
LidarrRequestKind,
LidarrSearchResult
} from '$lib/api/types';
// Local input is the source of truth for the discover query — Shell's global
// SearchInput targets /search, not /discover. We debounce by 250ms before
// pushing into `debouncedQ`, which is what the query factory observes.
let inputValue = $state('');
let debouncedQ = $state('');
let activeKind: LidarrRequestKind = $state('artist');
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
$effect(() => {
const v = inputValue;
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
debouncedQ = v.trim();
}, 250);
return () => {
if (debounceTimer) clearTimeout(debounceTimer);
};
});
const queryStore = $derived(createLidarrSearchQuery(debouncedQ, activeKind));
const query = $derived($queryStore);
const results = $derived((query.data ?? []) as LidarrSearchResult[]);
// Track-kind confirm modal: nulled out = closed.
let modalResult: LidarrSearchResult | null = $state(null);
// In-session optimistic flip — once a Request goes through, we flip the
// card to 'requested' immediately. Cleared only on full page reload, which
// is fine for a short-lived discover session.
let optimisticRequested: Set<string> = $state(new Set());
function cardState(r: LidarrSearchResult) {
if (r.in_library) return 'kept' as const;
if (r.requested || optimisticRequested.has(r.mbid)) return 'requested' as const;
return 'requestable' as const;
}
// Backend validates kind→required-MBID-fields, not the human strings, so
// imperfect derivations of artist_name from secondary_text won't block the
// request. We pass the data we have and let the server take care of the rest.
function buildRequestParams(r: LidarrSearchResult, kind: LidarrRequestKind) {
if (kind === 'artist') {
return {
kind,
lidarr_artist_mbid: r.artist_mbid || r.mbid,
artist_name: r.name
};
}
if (kind === 'album') {
return {
kind,
lidarr_artist_mbid: r.artist_mbid,
lidarr_album_mbid: r.album_mbid || r.mbid,
artist_name: r.secondary_text,
album_title: r.name
};
}
// track
return {
kind,
lidarr_artist_mbid: r.artist_mbid,
lidarr_album_mbid: r.album_mbid,
lidarr_track_mbid: r.mbid,
artist_name: r.secondary_text,
album_title: r.secondary_text,
track_title: r.name
};
}
async function submitRequest(r: LidarrSearchResult) {
try {
await createRequest(buildRequestParams(r, activeKind));
const next = new Set(optimisticRequested);
next.add(r.mbid);
optimisticRequested = next;
} catch {
// Swallow for v1: error toasts land in a later UX pass. The card stays
// in 'requestable' so the user can retry.
}
}
function handleRequestClick(r: LidarrSearchResult) {
if (activeKind === 'track') {
modalResult = r;
} else {
submitRequest(r);
}
}
function confirmModal() {
if (modalResult) submitRequest(modalResult);
modalResult = null;
}
function cancelModal() {
modalResult = null;
}
const tabs: { kind: LidarrRequestKind; label: string }[] = [
{ kind: 'artist', label: 'Artists' },
{ kind: 'album', label: 'Albums' },
{ kind: 'track', label: 'Tracks' }
];
</script>
<div class="space-y-6">
<header class="space-y-1">
<h2 class="font-display text-2xl font-medium text-text-primary">
Add music to the library
</h2>
<p class="text-text-secondary">
Search Lidarr to add new artists, albums, or tracks.
</p>
</header>
<input
type="search"
aria-label="Search Lidarr"
placeholder="Search artists, albums, or tracks"
bind:value={inputValue}
class="w-full rounded-md border border-border bg-background px-3 py-2 text-text-primary placeholder:text-text-muted focus:outline-none focus:ring-2 focus:ring-accent"
/>
<nav aria-label="Result kind" class="border-b border-border">
<ul class="flex gap-2">
{#each tabs as tab (tab.kind)}
<li>
<button
type="button"
aria-pressed={activeKind === tab.kind}
class="border-b-2 px-3 py-2 text-sm {activeKind === tab.kind
? 'border-accent text-text-primary'
: 'border-transparent text-text-secondary hover:text-text-primary'}"
onclick={() => (activeKind = tab.kind)}
>
{tab.label}
</button>
</li>
{/each}
</ul>
</nav>
{#if !debouncedQ}
<p class="text-text-secondary">
Search Lidarr for music to add to the library.
</p>
{:else if query.isError}
<ApiErrorBanner error={query.error} onRetry={query.refetch} />
{:else if query.isPending}
<p class="text-text-secondary">Searching…</p>
{:else if results.length === 0}
<p class="text-text-secondary">Nothing to add for that search yet.</p>
{:else}
<div class="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
{#each results as r (r.mbid)}
<DiscoverResultCard
kind={activeKind}
title={r.name}
subtitle={r.secondary_text}
imageUrl={r.image_url || undefined}
state={cardState(r)}
onRequest={() => handleRequestClick(r)}
/>
{/each}
</div>
{/if}
</div>
{#if modalResult}
<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="fixed inset-0 z-50 flex items-center justify-center"
style="background: rgba(0,0,0,0.5);"
onclick={cancelModal}
>
<div
role="dialog"
aria-modal="true"
aria-labelledby="track-confirm-title"
class="w-full max-w-md rounded-xl border border-border bg-surface p-5 shadow-lg"
onclick={(e) => e.stopPropagation()}
onkeydown={(e) => e.stopPropagation()}
tabindex="-1"
>
<h3 id="track-confirm-title" class="font-display text-lg font-medium text-text-primary">
Add the album?
</h3>
<p class="mt-2 text-text-secondary">
Requesting <em class="font-medium text-text-primary">{modalResult.name}</em>
will add <em class="font-medium text-text-primary">{modalResult.secondary_text}</em>.
Continue?
</p>
<div class="mt-5 flex justify-end gap-2">
<button
type="button"
class="rounded-md bg-action-secondary px-3 py-1.5 text-sm text-text-primary"
onclick={cancelModal}
>
Cancel
</button>
<button
type="button"
class="rounded-md bg-action-primary px-3 py-1.5 text-sm text-text-primary"
onclick={confirmModal}
>
Add the album
</button>
</div>
</div>
</div>
{/if}
+242
View File
@@ -0,0 +1,242 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/svelte';
import { mockQuery } from '../../test-utils/query';
import type { LidarrSearchResult } from '$lib/api/types';
// Lidarr search query factory and createRequest are mocked at the module
// level so each test can shape what the page sees without standing up a
// real QueryClient + network.
vi.mock('$lib/api/lidarr', () => ({
createLidarrSearchQuery: vi.fn()
}));
vi.mock('$lib/api/requests', () => ({
createRequest: vi.fn().mockResolvedValue({ id: 'r1' })
}));
vi.mock('$lib/api/client', () => ({
api: { get: vi.fn(), post: vi.fn(), put: vi.fn(), del: vi.fn() }
}));
vi.mock('@tanstack/svelte-query', async (orig) => {
const actual = (await orig()) as Record<string, unknown>;
return { ...actual, useQueryClient: () => ({}) };
});
import DiscoverPage from './+page.svelte';
import { createLidarrSearchQuery } from '$lib/api/lidarr';
import { createRequest } from '$lib/api/requests';
const mockedCreateQuery = createLidarrSearchQuery as ReturnType<typeof vi.fn>;
const mockedCreateRequest = createRequest as ReturnType<typeof vi.fn>;
function result(over: Partial<LidarrSearchResult> = {}): LidarrSearchResult {
return {
mbid: 'mbid-1',
name: 'Boards of Canada',
secondary_text: 'Electronic',
image_url: '',
artist_mbid: 'art-1',
album_mbid: '',
in_library: false,
requested: false,
...over
};
}
beforeEach(() => {
// Default: empty results, non-pending. Tests override per-case.
mockedCreateQuery.mockReturnValue(mockQuery<LidarrSearchResult[]>({ data: [] }));
});
afterEach(() => {
vi.clearAllMocks();
});
describe('Discover page', () => {
test('initial state (no query) shows the search prompt copy', () => {
render(DiscoverPage);
expect(
screen.getByText(/search lidarr for music to add/i)
).toBeInTheDocument();
});
test('debounced input fires query factory with typed value after 250ms', async () => {
vi.useFakeTimers();
render(DiscoverPage);
const input = screen.getByLabelText(/search lidarr/i);
await fireEvent.input(input, { target: { value: 'boards' } });
// Before the timer elapses, the factory was called only with the
// initial empty string — never with 'boards'.
expect(mockedCreateQuery).not.toHaveBeenCalledWith('boards', 'artist');
await vi.advanceTimersByTimeAsync(250);
expect(mockedCreateQuery).toHaveBeenLastCalledWith('boards', 'artist');
vi.useRealTimers();
});
test('switching tabs refetches with the new kind', async () => {
vi.useFakeTimers();
render(DiscoverPage);
const input = screen.getByLabelText(/search lidarr/i);
await fireEvent.input(input, { target: { value: 'boards' } });
await vi.advanceTimersByTimeAsync(250);
// Switch to Albums.
await fireEvent.click(screen.getByRole('button', { name: 'Albums' }));
expect(mockedCreateQuery).toHaveBeenLastCalledWith('boards', 'album');
// Then to Tracks.
await fireEvent.click(screen.getByRole('button', { name: 'Tracks' }));
expect(mockedCreateQuery).toHaveBeenLastCalledWith('boards', 'track');
vi.useRealTimers();
});
test('empty results state renders the voice-rule copy', async () => {
vi.useFakeTimers();
mockedCreateQuery.mockReturnValue(mockQuery<LidarrSearchResult[]>({ data: [] }));
render(DiscoverPage);
const input = screen.getByLabelText(/search lidarr/i);
await fireEvent.input(input, { target: { value: 'zzz' } });
await vi.advanceTimersByTimeAsync(250);
await waitFor(() =>
expect(
screen.getByText(/nothing to add for that search yet\./i)
).toBeInTheDocument()
);
vi.useRealTimers();
});
test('artist-kind Request click calls createRequest immediately (no modal)', async () => {
vi.useFakeTimers();
const r = result({
mbid: 'art-mbid',
artist_mbid: 'art-mbid',
name: 'Boards of Canada'
});
mockedCreateQuery.mockReturnValue(mockQuery<LidarrSearchResult[]>({ data: [r] }));
render(DiscoverPage);
const input = screen.getByLabelText(/search lidarr/i);
await fireEvent.input(input, { target: { value: 'boards' } });
await vi.advanceTimersByTimeAsync(250);
vi.useRealTimers();
const requestBtn = await screen.findByRole('button', {
name: /request boards of canada/i
});
await fireEvent.click(requestBtn);
expect(mockedCreateRequest).toHaveBeenCalledTimes(1);
expect(mockedCreateRequest).toHaveBeenCalledWith(
expect.objectContaining({ kind: 'artist' })
);
// Modal must not be present for non-track kinds.
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
test('requestable card flips to "Requested" after a successful request', async () => {
vi.useFakeTimers();
const r = result({
mbid: 'art-mbid',
artist_mbid: 'art-mbid',
name: 'Boards of Canada'
});
mockedCreateQuery.mockReturnValue(mockQuery<LidarrSearchResult[]>({ data: [r] }));
render(DiscoverPage);
const input = screen.getByLabelText(/search lidarr/i);
await fireEvent.input(input, { target: { value: 'boards' } });
await vi.advanceTimersByTimeAsync(250);
vi.useRealTimers();
const requestBtn = await screen.findByRole('button', {
name: /request boards of canada/i
});
await fireEvent.click(requestBtn);
await waitFor(() => {
const flipped = screen.getByRole('button', { name: /already requested/i });
expect(flipped).toBeDisabled();
});
});
test('track-kind Request click opens confirm modal; Confirm calls createRequest', async () => {
vi.useFakeTimers();
const r = result({
mbid: 'tr-mbid',
artist_mbid: 'art-mbid',
album_mbid: 'al-mbid',
name: 'Roygbiv',
secondary_text: 'Music Has The Right To Children · Boards of Canada'
});
mockedCreateQuery.mockReturnValue(mockQuery<LidarrSearchResult[]>({ data: [r] }));
render(DiscoverPage);
// Switch to track kind first.
await fireEvent.click(screen.getByRole('button', { name: 'Tracks' }));
const input = screen.getByLabelText(/search lidarr/i);
await fireEvent.input(input, { target: { value: 'roy' } });
await vi.advanceTimersByTimeAsync(250);
vi.useRealTimers();
const requestBtn = await screen.findByRole('button', {
name: /request roygbiv/i
});
await fireEvent.click(requestBtn);
// Modal opens with the explanation copy.
const dialog = await screen.findByRole('dialog');
expect(dialog).toBeInTheDocument();
expect(dialog.textContent).toMatch(/continue/i);
// Confirm fires createRequest with kind=track.
await fireEvent.click(screen.getByRole('button', { name: /add the album/i }));
expect(mockedCreateRequest).toHaveBeenCalledTimes(1);
expect(mockedCreateRequest).toHaveBeenCalledWith(
expect.objectContaining({
kind: 'track',
lidarr_track_mbid: 'tr-mbid',
lidarr_album_mbid: 'al-mbid',
lidarr_artist_mbid: 'art-mbid'
})
);
});
test('track-kind modal Cancel does not call createRequest', async () => {
vi.useFakeTimers();
const r = result({
mbid: 'tr-mbid',
artist_mbid: 'art-mbid',
album_mbid: 'al-mbid',
name: 'Roygbiv',
secondary_text: 'Music Has The Right To Children · Boards of Canada'
});
mockedCreateQuery.mockReturnValue(mockQuery<LidarrSearchResult[]>({ data: [r] }));
render(DiscoverPage);
await fireEvent.click(screen.getByRole('button', { name: 'Tracks' }));
const input = screen.getByLabelText(/search lidarr/i);
await fireEvent.input(input, { target: { value: 'roy' } });
await vi.advanceTimersByTimeAsync(250);
vi.useRealTimers();
const requestBtn = await screen.findByRole('button', {
name: /request roygbiv/i
});
await fireEvent.click(requestBtn);
await screen.findByRole('dialog');
await fireEvent.click(screen.getByRole('button', { name: /^cancel$/i }));
expect(mockedCreateRequest).not.toHaveBeenCalled();
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
test('in_library result renders kept state regardless of requested', async () => {
vi.useFakeTimers();
const r = result({
mbid: 'kept-1',
name: 'Kind of Blue',
in_library: true,
requested: true
});
mockedCreateQuery.mockReturnValue(mockQuery<LidarrSearchResult[]>({ data: [r] }));
render(DiscoverPage);
const input = screen.getByLabelText(/search lidarr/i);
await fireEvent.input(input, { target: { value: 'kind' } });
await vi.advanceTimersByTimeAsync(250);
vi.useRealTimers();
await waitFor(() => {
expect(screen.getByRole('button', { name: /in library/i })).toBeDisabled();
});
});
});