feat(web/playlists): Discover refresh button (detail + home kebab)
Operator can refresh their Discover playlist without waiting for the next daily cron tick. Two surfaces, both gated on system_variant === 'discover': - Detail page header: "Refresh" button next to the cover art / meta. - Home Playlists row tile kebab: "Refresh Discover" menu item. Both call POST /api/playlists/system/discover/refresh, show a confirmation toast, and invalidate the playlist + playlists queries so the new content lands without a manual page reload. Extends Playlist.system_variant union with 'discover'. Adds refreshDiscover() typed client. Tests cover client behaviour (success + empty-library) plus conditional rendering on both surfaces.
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { refreshDiscover } from './playlists';
|
||||
|
||||
vi.mock('./client', () => ({
|
||||
apiFetch: vi.fn()
|
||||
}));
|
||||
|
||||
import { apiFetch } from './client';
|
||||
|
||||
describe('refreshDiscover', () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it('POSTs the correct path and returns the response', async () => {
|
||||
const sample = { playlist_id: 'abc-123', track_count: 100 };
|
||||
(apiFetch as unknown as ReturnType<typeof vi.fn>).mockResolvedValueOnce(sample);
|
||||
const got = await refreshDiscover();
|
||||
expect(apiFetch).toHaveBeenCalledWith(
|
||||
'/api/playlists/system/discover/refresh',
|
||||
expect.objectContaining({ method: 'POST' })
|
||||
);
|
||||
expect(got).toEqual(sample);
|
||||
});
|
||||
|
||||
it('handles empty-library response', async () => {
|
||||
const sample = { playlist_id: null, track_count: 0 };
|
||||
(apiFetch as unknown as ReturnType<typeof vi.fn>).mockResolvedValueOnce(sample);
|
||||
const got = await refreshDiscover();
|
||||
expect(got.playlist_id).toBe(null);
|
||||
expect(got.track_count).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -91,3 +91,20 @@ export function createPlaylistQuery(id: string) {
|
||||
staleTime: 30_000
|
||||
});
|
||||
}
|
||||
|
||||
// System playlist refresh ----------------------------------------------------
|
||||
|
||||
export type RefreshDiscoverResponse = {
|
||||
playlist_id: string | null;
|
||||
track_count: number;
|
||||
};
|
||||
|
||||
// Re-runs the daily system playlist build for the calling user and
|
||||
// returns the resulting Discover playlist's id + track count.
|
||||
// Used by the detail-page Refresh button and the home tile kebab.
|
||||
export async function refreshDiscover(): Promise<RefreshDiscoverResponse> {
|
||||
return (await apiFetch('/api/playlists/system/discover/refresh', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({})
|
||||
})) as RefreshDiscoverResponse;
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ export type Playlist = {
|
||||
description: string;
|
||||
is_public: boolean;
|
||||
kind: 'user' | 'system';
|
||||
system_variant: 'for_you' | 'songs_like_artist' | null;
|
||||
system_variant: 'for_you' | 'songs_like_artist' | 'discover' | null;
|
||||
seed_artist_id: string | null;
|
||||
cover_url: string; // empty string when no cover; UI renders glyph
|
||||
track_count: number;
|
||||
|
||||
@@ -1,15 +1,37 @@
|
||||
<script lang="ts">
|
||||
import { Play } from 'lucide-svelte';
|
||||
import { Play, MoreVertical, RefreshCcw } from 'lucide-svelte';
|
||||
import { useQueryClient } from '@tanstack/svelte-query';
|
||||
import type { Playlist, PlaylistTrack, TrackRef } from '$lib/api/types';
|
||||
import { user } from '$lib/auth/store.svelte';
|
||||
import { getPlaylist } from '$lib/api/playlists';
|
||||
import { getPlaylist, refreshDiscover } from '$lib/api/playlists';
|
||||
import { qk } from '$lib/api/queries';
|
||||
import { playQueue } from '$lib/player/store.svelte';
|
||||
|
||||
let { playlist }: { playlist: Playlist } = $props();
|
||||
|
||||
const isOwn = $derived(user.value?.id === playlist.user_id);
|
||||
const isDiscover = $derived(playlist.system_variant === 'discover');
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
let starting = $state(false);
|
||||
let menuOpen = $state(false);
|
||||
|
||||
// --- Toast ---
|
||||
let toast = $state<string | null>(null);
|
||||
let toastTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
function showToast(msg: string) {
|
||||
if (toastTimer) clearTimeout(toastTimer);
|
||||
toast = msg;
|
||||
toastTimer = setTimeout(() => { toast = null; }, 5000);
|
||||
}
|
||||
|
||||
function toggleMenu(e: MouseEvent) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
menuOpen = !menuOpen;
|
||||
}
|
||||
|
||||
// Map PlaylistTrack rows to TrackRef shape and drop tracks whose upstream
|
||||
// file has been removed (track_id is null). Mirrors PlaylistTrackRow's
|
||||
@@ -47,9 +69,67 @@
|
||||
starting = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function onRefreshDiscover(e: MouseEvent) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
menuOpen = false;
|
||||
try {
|
||||
await refreshDiscover();
|
||||
showToast('Discover refreshed.');
|
||||
await queryClient.invalidateQueries({ queryKey: qk.playlist(playlist.id) });
|
||||
await queryClient.invalidateQueries({ queryKey: qk.playlists() });
|
||||
} catch (err: unknown) {
|
||||
showToast(`Refresh failed: ${(err as { code?: string })?.code ?? 'unknown'}`);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:window onclick={() => { menuOpen = false; }} />
|
||||
|
||||
{#if toast}
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
class="fixed bottom-4 left-1/2 z-50 -translate-x-1/2 rounded-md border border-border bg-surface px-4 py-2 text-sm text-text-primary shadow-md"
|
||||
>
|
||||
{toast}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="card relative">
|
||||
{#if isDiscover}
|
||||
<div class="kebab-wrap absolute right-1 top-1 z-10">
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Playlist actions"
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={menuOpen}
|
||||
onclick={toggleMenu}
|
||||
class="rounded p-1 text-text-muted hover:bg-surface-hover hover:text-text-primary"
|
||||
>
|
||||
<MoreVertical size={16} strokeWidth={1} />
|
||||
</button>
|
||||
{#if menuOpen}
|
||||
<div
|
||||
role="menu"
|
||||
tabindex="-1"
|
||||
class="absolute right-0 top-full z-20 mt-1 w-44 rounded-md border border-border bg-surface p-1 shadow-lg"
|
||||
onclick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
onclick={onRefreshDiscover}
|
||||
class="flex w-full items-center gap-2 rounded px-2 py-1.5 text-sm text-text-primary hover:bg-surface-hover"
|
||||
>
|
||||
<RefreshCcw size={14} strokeWidth={1} />
|
||||
Refresh Discover
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
<a
|
||||
href={`/playlists/${playlist.id}`}
|
||||
class="group flex w-full flex-col items-start gap-2 rounded-md p-2 text-left hover:bg-surface-hover"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/svelte';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/svelte';
|
||||
import PlaylistCard from './PlaylistCard.svelte';
|
||||
import type { Playlist, PlaylistDetail } from '$lib/api/types';
|
||||
|
||||
@@ -7,6 +7,14 @@ vi.mock('$lib/auth/store.svelte', () => ({
|
||||
user: { value: { id: 'u-self', username: 'me', is_admin: false } }
|
||||
}));
|
||||
|
||||
vi.mock('@tanstack/svelte-query', async (orig) => {
|
||||
const actual = (await orig()) as Record<string, unknown>;
|
||||
return {
|
||||
...actual,
|
||||
useQueryClient: () => ({ invalidateQueries: vi.fn().mockResolvedValue(undefined) })
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('$lib/api/playlists', () => ({
|
||||
getPlaylist: vi.fn().mockResolvedValue({
|
||||
id: 'p-1',
|
||||
@@ -37,13 +45,21 @@ vi.mock('$lib/api/playlists', () => ({
|
||||
added_at: '2026-01-01T00:00:00Z'
|
||||
}
|
||||
]
|
||||
} as PlaylistDetail)
|
||||
} as PlaylistDetail),
|
||||
refreshDiscover: vi.fn().mockResolvedValue({ playlist_id: 'p-1', track_count: 5 })
|
||||
}));
|
||||
|
||||
vi.mock('$lib/player/store.svelte', () => ({
|
||||
playQueue: vi.fn()
|
||||
}));
|
||||
|
||||
vi.mock('$lib/api/queries', () => ({
|
||||
qk: {
|
||||
playlist: (id: string) => ['playlist', id],
|
||||
playlists: (kind?: string) => ['playlists', { kind: kind ?? 'user' }]
|
||||
}
|
||||
}));
|
||||
|
||||
const base: Playlist = {
|
||||
id: 'p-1',
|
||||
user_id: 'u-self',
|
||||
@@ -133,4 +149,71 @@ describe('PlaylistCard', () => {
|
||||
expect(getPlaylist).toHaveBeenCalledWith('p-1');
|
||||
expect(playQueue).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('shows kebab button only on Discover playlists', () => {
|
||||
const discoverPlaylist: Playlist = {
|
||||
...base,
|
||||
kind: 'system',
|
||||
system_variant: 'discover',
|
||||
name: 'Discover'
|
||||
};
|
||||
render(PlaylistCard, { props: { playlist: discoverPlaylist } });
|
||||
expect(screen.getByLabelText(/playlist actions/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('does not show kebab button on for_you playlists', () => {
|
||||
const forYouPlaylist: Playlist = {
|
||||
...base,
|
||||
kind: 'system',
|
||||
system_variant: 'for_you',
|
||||
name: 'For You'
|
||||
};
|
||||
render(PlaylistCard, { props: { playlist: forYouPlaylist } });
|
||||
expect(screen.queryByLabelText(/playlist actions/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('does not show kebab button on user playlists', () => {
|
||||
render(PlaylistCard, { props: { playlist: base } });
|
||||
expect(screen.queryByLabelText(/playlist actions/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('Refresh Discover item appears in kebab menu when opened', async () => {
|
||||
const discoverPlaylist: Playlist = {
|
||||
...base,
|
||||
kind: 'system',
|
||||
system_variant: 'discover',
|
||||
name: 'Discover'
|
||||
};
|
||||
render(PlaylistCard, { props: { playlist: discoverPlaylist } });
|
||||
const kebabBtn = screen.getByLabelText(/playlist actions/i);
|
||||
await fireEvent.click(kebabBtn);
|
||||
expect(screen.getByRole('menuitem', { name: /refresh discover/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('Refresh Discover item is absent from for_you card kebab', () => {
|
||||
const forYouPlaylist: Playlist = {
|
||||
...base,
|
||||
kind: 'system',
|
||||
system_variant: 'for_you',
|
||||
name: 'For You'
|
||||
};
|
||||
render(PlaylistCard, { props: { playlist: forYouPlaylist } });
|
||||
expect(screen.queryByRole('menuitem', { name: /refresh discover/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('clicking Refresh Discover calls refreshDiscover', async () => {
|
||||
const { refreshDiscover } = await import('$lib/api/playlists');
|
||||
const discoverPlaylist: Playlist = {
|
||||
...base,
|
||||
kind: 'system',
|
||||
system_variant: 'discover',
|
||||
name: 'Discover'
|
||||
};
|
||||
render(PlaylistCard, { props: { playlist: discoverPlaylist } });
|
||||
const kebabBtn = screen.getByLabelText(/playlist actions/i);
|
||||
await fireEvent.click(kebabBtn);
|
||||
const refreshItem = screen.getByRole('menuitem', { name: /refresh discover/i });
|
||||
await fireEvent.click(refreshItem);
|
||||
await waitFor(() => expect(refreshDiscover).toHaveBeenCalled());
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,7 +11,8 @@
|
||||
updatePlaylist,
|
||||
deletePlaylist,
|
||||
removePlaylistTrack,
|
||||
reorderPlaylist
|
||||
reorderPlaylist,
|
||||
refreshDiscover
|
||||
} from '$lib/api/playlists';
|
||||
import { qk } from '$lib/api/queries';
|
||||
import { user } from '$lib/auth/store.svelte';
|
||||
@@ -135,12 +136,49 @@
|
||||
alert(copyForCode(code));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Toast (detail page) ---
|
||||
let toast = $state<string | null>(null);
|
||||
let toastTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
function showToast(msg: string) {
|
||||
if (toastTimer) clearTimeout(toastTimer);
|
||||
toast = msg;
|
||||
toastTimer = setTimeout(() => { toast = null; }, 5000);
|
||||
}
|
||||
|
||||
// --- Discover refresh ---
|
||||
let refreshingDiscover = $state(false);
|
||||
|
||||
async function onRefreshDiscover() {
|
||||
refreshingDiscover = true;
|
||||
try {
|
||||
await refreshDiscover();
|
||||
showToast('Discover refreshed.');
|
||||
await queryClient.invalidateQueries({ queryKey: qk.playlist(id) });
|
||||
await queryClient.invalidateQueries({ queryKey: qk.playlists() });
|
||||
} catch (e: unknown) {
|
||||
showToast(`Refresh failed: ${(e as { code?: string })?.code ?? 'unknown'}`);
|
||||
} finally {
|
||||
refreshingDiscover = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>{pageTitle(playlistQuery?.data?.name ? `Playlist · ${playlistQuery.data.name}` : 'Playlist')}</title>
|
||||
</svelte:head>
|
||||
|
||||
{#if toast}
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
class="fixed bottom-4 left-1/2 z-50 -translate-x-1/2 rounded-md border border-border bg-surface px-4 py-2 text-sm text-text-primary shadow-md"
|
||||
>
|
||||
{toast}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mx-auto max-w-4xl px-4 py-6">
|
||||
{#if playlistQuery?.isPending}
|
||||
<p class="text-text-muted">Loading…</p>
|
||||
@@ -166,6 +204,17 @@
|
||||
{#if !isOwner}· by {pl.owner_username}{/if}
|
||||
</p>
|
||||
</div>
|
||||
{#if pl.system_variant === 'discover'}
|
||||
<button
|
||||
type="button"
|
||||
disabled={refreshingDiscover}
|
||||
onclick={onRefreshDiscover}
|
||||
class="rounded-md border border-border px-3 py-1.5 text-sm text-text-muted hover:text-text-primary"
|
||||
aria-label="Refresh Discover"
|
||||
>
|
||||
{refreshingDiscover ? 'Refreshing…' : 'Refresh'}
|
||||
</button>
|
||||
{/if}
|
||||
{#if isOwner}
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -17,7 +17,8 @@ vi.mock('$lib/api/playlists', () => ({
|
||||
updatePlaylist: vi.fn().mockResolvedValue(undefined),
|
||||
deletePlaylist: vi.fn().mockResolvedValue(undefined),
|
||||
removePlaylistTrack: vi.fn().mockResolvedValue(undefined),
|
||||
reorderPlaylist: vi.fn().mockResolvedValue(undefined)
|
||||
reorderPlaylist: vi.fn().mockResolvedValue(undefined),
|
||||
refreshDiscover: vi.fn().mockResolvedValue({ playlist_id: 'p1', track_count: 5 })
|
||||
}));
|
||||
|
||||
vi.mock('@tanstack/svelte-query', async (orig) => {
|
||||
@@ -50,7 +51,7 @@ vi.mock('$lib/api/quarantine', () => ({
|
||||
vi.mock('$lib/api/admin/tracks', () => ({ removeTrack: vi.fn() }));
|
||||
|
||||
import PlaylistDetailPage from './+page.svelte';
|
||||
import { createPlaylistQuery, deletePlaylist } from '$lib/api/playlists';
|
||||
import { createPlaylistQuery, deletePlaylist, refreshDiscover } from '$lib/api/playlists';
|
||||
|
||||
const mockedQuery = createPlaylistQuery as ReturnType<typeof vi.fn>;
|
||||
|
||||
@@ -92,4 +93,44 @@ describe('Playlist detail page', () => {
|
||||
await waitFor(() => expect(deletePlaylist).toHaveBeenCalledWith('p1'));
|
||||
confirmSpy.mockRestore();
|
||||
});
|
||||
|
||||
test('renders Refresh button only on Discover playlists', () => {
|
||||
const discoverDetail: PlaylistDetail = {
|
||||
...ownDetail,
|
||||
kind: 'system',
|
||||
system_variant: 'discover'
|
||||
};
|
||||
mockedQuery.mockReturnValue(mockQuery({ data: discoverDetail }));
|
||||
render(PlaylistDetailPage);
|
||||
expect(screen.getByLabelText(/refresh discover/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('does not render Refresh button on for_you playlists', () => {
|
||||
const forYouDetail: PlaylistDetail = {
|
||||
...ownDetail,
|
||||
kind: 'system',
|
||||
system_variant: 'for_you'
|
||||
};
|
||||
mockedQuery.mockReturnValue(mockQuery({ data: forYouDetail }));
|
||||
render(PlaylistDetailPage);
|
||||
expect(screen.queryByLabelText(/refresh discover/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('does not render Refresh button on user playlists', () => {
|
||||
mockedQuery.mockReturnValue(mockQuery({ data: ownDetail }));
|
||||
render(PlaylistDetailPage);
|
||||
expect(screen.queryByLabelText(/refresh discover/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('Refresh button calls refreshDiscover when clicked', async () => {
|
||||
const discoverDetail: PlaylistDetail = {
|
||||
...ownDetail,
|
||||
kind: 'system',
|
||||
system_variant: 'discover'
|
||||
};
|
||||
mockedQuery.mockReturnValue(mockQuery({ data: discoverDetail }));
|
||||
render(PlaylistDetailPage);
|
||||
await fireEvent.click(screen.getByLabelText(/refresh discover/i));
|
||||
await waitFor(() => expect(refreshDiscover).toHaveBeenCalled());
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user