Files
minstrel/web/src/routes/playlists/[id]/+page.svelte
T
bvandeusenandClaude Opus 5.5 dbaa8b7d57
release / web (push) Successful in 1m24s
release / go (push) Successful in 1m47s
release / govulncheck (push) Successful in 25s
release / integration (push) Failing after 4m38s
release / android (push) Successful in 4m3s
release / Build signed APK (push) Successful in 4m34s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped
feat: genre mixes — a daily playlist per genre you listen to, on a "Your genres" Home row (#6904)
A new system playlist kind, genre_mix: up to 10 "{Genre} mix" playlists per
user, rebuilt daily with the other system mixes.

Which genres: library genres with at least 25 playable tracks across 3
artists, ranked in tiers — taste-profile genres first (matched
case-insensitively, so ID3 "Post-Punk" and folksonomy "post-punk" are one),
then genres the user has played or liked, then the rest of the library, which
only tops a short shelf up to 4. A genre whose artist set is a near
duplicate of one already picked (Jaccard >= 0.5) is skipped, so "Lo-Fi" and
"Lo-Fi Hip Hop" don't both appear but "Alternative Rock" survives "Rock". A
genre that can't fill 15 tracks gives way to the next.

Each mix is 50 tracks: 3 in 5 the user already knows (played through or
liked), the rest unheard in that genre, interleaved, with the usual
per-album/per-artist caps. Tracks skipped twice and more often than played
are left out. The order changes daily and holds within a day. Picks are
stamped taste / taste_unheard, and genre_mix plays count toward rotation and
the recommendation metrics.

Migration 0102 adds genre_mix to the playlists variant constraints.

Web and Android each get a "Your genres" row in name order, hidden until a
mix exists. Kinds with several playlists per user now play by playlist id
wherever the client used to test seed_artist_id (web card, detail page
self-heal), keyed on the server's refreshable flag; on Android genre_mix
joins songs_like_artist as not refreshable. The web detail page's
"mix was rebuilt" reload now finds a Songs-like or genre mix by name instead
of calling the by-kind shuffle, which those kinds don't have.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 22:30:41 -05:00

398 lines
15 KiB
Svelte
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script lang="ts">
import { plural } from '#lib/utils/plural.js';
import PageColumn from '#lib/components/PageColumn.svelte';
import { page } from '$app/state';
import { goto } from '$app/navigation';
import { untrack } from 'svelte';
import { pageTitle } from '#lib/branding.js';
import { Pencil, Trash2, Link as LinkIcon } from 'lucide-svelte';
import { useQueryClient } from '@tanstack/svelte-query';
import PlaylistTrackRow from '#lib/components/PlaylistTrackRow.svelte';
import TrackList from '#lib/components/TrackList.svelte';
import CollectionHeader from '#lib/components/CollectionHeader.svelte';
import { playlistTrackToRef } from '#lib/playlists/playlistTrackToRef.js';
import { shuffled } from '#lib/utils/shuffle.js';
import ApiErrorBanner from '#lib/components/ApiErrorBanner.svelte';
import {
createPlaylistQuery,
updatePlaylist,
deletePlaylist,
removePlaylistTrack,
reorderPlaylist,
refreshSystem,
systemShuffle,
listPlaylists
} from '#lib/api/playlists.js';
import { qk } from '#lib/api/queries.js';
import { user } from '#lib/auth/store.svelte.js';
import { errCode, errMessage } from '#lib/api/errors.js';
import { playQueue } from '#lib/player/store.svelte.js';
import { systemPlaylistRefetch } from '#lib/playlists/systemRefetch.js';
import { systemRebuilt } from '#lib/serverEvents.svelte.js';
import { pushToast } from '#lib/stores/toast.svelte.js';
import type { PlaylistDetail, TrackRef } from '#lib/api/types.js';
// SvelteKit types page.params.id as string | undefined (the route
// could in principle render with the slot empty); empty-string fallback
// keeps every downstream call typed and falls back to a 404 if the
// operator ever lands here without a real id.
const id = $derived(page.params.id ?? '');
const queryClient = useQueryClient();
const playlistStore = $derived(createPlaylistQuery(id));
const playlistQuery = $derived($playlistStore);
const isOwner = $derived(user.value?.id === playlistQuery?.data?.user_id);
async function onMove(fromPos: number, toPos: number) {
if (!playlistQuery?.data) return;
const tracks = playlistQuery.data.tracks;
// Clamp toPos so a drag past the list edges resolves cleanly to the
// first/last slot rather than producing an out-of-range index.
const clamped = Math.max(0, Math.min(tracks.length - 1, toPos));
if (fromPos === clamped) return;
const cur = tracks.map((t) => t.position);
const moved = cur.splice(fromPos, 1)[0];
cur.splice(clamped, 0, moved);
// Show the new order on drop rather than after the round trip, so the
// dragged row lands in its slot at once. Positions are
// renumbered the way the server renumbers them; the invalidate below
// replaces this with the server's copy either way.
const previous = playlistQuery.data;
const byPosition = new Map(tracks.map((t) => [t.position, t]));
queryClient.setQueryData<PlaylistDetail>(qk.playlist(id), {
...previous,
tracks: cur.map((pos, i) => ({ ...byPosition.get(pos)!, position: i }))
});
try {
await reorderPlaylist(id, cur);
} catch (e: unknown) {
queryClient.setQueryData(qk.playlist(id), previous);
alert(errMessage(e));
}
await queryClient.invalidateQueries({ queryKey: qk.playlist(id) });
}
async function onRemove(position: number) {
try {
await removePlaylistTrack(id, position);
await queryClient.invalidateQueries({ queryKey: qk.playlist(id) });
await queryClient.invalidateQueries({ queryKey: qk.playlists() });
} catch (e: unknown) {
alert(errMessage(e));
}
}
// Every entry that can be played, in playlist order. playlistTrackToRef
// drops both kinds of dead entry, removed tracks and missing files,
// so neither is ever queued.
function playable(data: PlaylistDetail): { refs: TrackRef[]; positions: number[] } {
const refs: TrackRef[] = [];
const positions: number[] = [];
for (const row of data.tracks) {
const ref = playlistTrackToRef(row);
if (ref) {
refs.push(ref);
positions.push(row.position);
}
}
return { refs, positions };
}
function startQueue(data: PlaylistDetail, tracks: TrackRef[], startIdx: number) {
// A system playlist played from its detail page is tagged with its
// source (so play_started advances the rotation, matching the home tile and
// the Android detail screen) and gets the self-heal closure so a stale
// snapshot re-pulls on total failure.
const variant = data.system_variant;
if (variant != null) {
playQueue(tracks, Math.max(0, startIdx), {
source: variant,
refetch: systemPlaylistRefetch({
variant,
playlistId: id,
perArtist: !data.refreshable
})
});
} else {
playQueue(tracks, Math.max(0, startIdx));
}
}
function onPlay(position: number) {
if (!playlistQuery?.data) return;
const data = playlistQuery.data;
const { refs, positions } = playable(data);
startQueue(data, refs, positions.indexOf(position));
}
function onPlayAll() {
if (!playlistQuery?.data) return;
startQueue(playlistQuery.data, playable(playlistQuery.data).refs, 0);
}
function onShuffle() {
if (!playlistQuery?.data) return;
startQueue(playlistQuery.data, shuffled(playable(playlistQuery.data).refs), 0);
}
let editing = $state(false);
let editName = $state('');
let editDesc = $state('');
let editIsPublic = $state(false);
function startEdit() {
if (!playlistQuery?.data) return;
editName = playlistQuery.data.name;
editDesc = playlistQuery.data.description;
editIsPublic = playlistQuery.data.is_public;
editing = true;
}
async function submitEdit() {
try {
await updatePlaylist(id, { name: editName, description: editDesc, is_public: editIsPublic });
await queryClient.invalidateQueries({ queryKey: qk.playlist(id) });
await queryClient.invalidateQueries({ queryKey: qk.playlists() });
editing = false;
} catch (e: unknown) {
alert(errMessage(e));
}
}
async function submitDelete() {
if (!confirm('Delete this playlist? This cannot be undone.')) return;
try {
await deletePlaylist(id);
await queryClient.invalidateQueries({ queryKey: qk.playlists() });
goto('/playlists');
} catch (e: unknown) {
alert(errMessage(e));
}
}
async function onCopyLink() {
const href = `${window.location.origin}/playlists/${id}`;
try {
await navigator.clipboard.writeText(href);
pushToast('Link copied to clipboard.');
} catch {
// navigator.clipboard fails in insecure contexts and older browsers.
// Fall back to selecting the link in a prompt so the user can copy.
window.prompt('Copy the playlist link:', href);
}
}
// --- System-playlist refresh (generic by-kind) ---
let refreshingSystem = $state(false);
async function onRefreshSystem(variant: string) {
refreshingSystem = true;
try {
await refreshSystem(variant);
pushToast('Refreshed.');
await queryClient.invalidateQueries({ queryKey: qk.playlist(id) });
await queryClient.invalidateQueries({ queryKey: qk.playlists() });
} catch (e: unknown) {
pushToast(`Refresh failed: ${errCode(e)}`, 'error');
} finally {
refreshingSystem = false;
}
}
// --- Stale-view banner for an open system-playlist detail page ---
// The daily rebuild rotates the playlist id, so this page's cached data goes
// stale and can't be refetched in place (the old id 404s). Watch the global
// rebuild counter; when it advances while we're on a system playlist, offer a
// Refresh that re-resolves the variant to the fresh playlist.
const isSystemPlaylist = $derived(playlistQuery?.data?.system_variant != null);
// Baseline starts at the current count so a rebuild earlier this session
// doesn't flash the banner on open; re-synced on navigation below.
let acknowledgedRebuild = $state(systemRebuilt.count);
$effect(() => {
id; // re-sync the baseline whenever we land on a different playlist
acknowledgedRebuild = untrack(() => systemRebuilt.count);
});
const staleSystemView = $derived(
isSystemPlaylist && systemRebuilt.count > acknowledgedRebuild
);
let reloadingStale = $state(false);
async function onReloadStale() {
const current = playlistQuery?.data;
const variant = current?.system_variant;
if (!current || !variant) return;
reloadingStale = true;
try {
// The rebuild minted a new playlist id; resolve it and navigate there
// so the page loads the fresh mix. A kind with one playlist per user
// resolves by kind. A kind with several (Songs like…, genre mixes)
// resolves by kind and name — "Jazz mix" stays "Jazz mix" — and goes
// Home when today's build no longer has that mix.
if (current.refreshable) {
const fresh = await systemShuffle(variant);
await goto(`/playlists/${fresh.id}`);
return;
}
const { owned } = await listPlaylists('system');
const fresh = owned.find((p) => p.system_variant === variant && p.name === current.name);
await goto(fresh ? `/playlists/${fresh.id}` : '/');
} catch (e: unknown) {
pushToast(`Couldn’t load the refreshed mix: ${errCode(e)}`, 'error');
} finally {
reloadingStale = false;
}
}
</script>
<svelte:head>
<title>{pageTitle(playlistQuery?.data?.name ? `Playlist · ${playlistQuery.data.name}` : 'Playlist')}</title>
</svelte:head>
<PageColumn>
{#if playlistQuery?.isPending}
<p class="text-text-muted">Loading…</p>
{:else if playlistQuery?.isError}
<ApiErrorBanner error={playlistQuery.error} onRetry={() => playlistQuery.refetch()} />
{:else if playlistQuery?.data}
{@const pl = playlistQuery.data}
{#if staleSystemView}
<div
role="status"
class="mb-4 flex items-center justify-between gap-3 rounded-md border border-accent/40
bg-accent/10 px-4 py-2.5 text-sm"
>
<span class="text-text-primary">This mix was refreshed since you opened it.</span>
<button
type="button"
onclick={onReloadStale}
disabled={reloadingStale}
class="shrink-0 rounded-md bg-action-secondary px-3 py-1 text-xs font-medium
text-action-fg disabled:opacity-50"
>
{reloadingStale ? 'Refreshing…' : 'Refresh'}
</button>
</div>
{/if}
{#if !editing}
<CollectionHeader
title={pl.name}
coverUrl={pl.cover_url}
playDisabled={!pl.tracks.some((t) => playlistTrackToRef(t) !== null)}
onPlay={onPlayAll}
{onShuffle}
>
{#if pl.description}
<p class="text-sm text-text-muted">{pl.description}</p>
{/if}
<p class="text-xs text-text-muted">
{plural(pl.track_count, 'track', 'tracks')}
{#if pl.is_public}· public{:else}· private{/if}
{#if !isOwner}· by {pl.owner_username}{/if}
</p>
{#snippet tools()}
{#if pl.refreshable && pl.system_variant}
<button
type="button"
disabled={refreshingSystem}
onclick={() => onRefreshSystem(pl.system_variant as string)}
class="rounded-md border border-border px-3 py-1.5 text-sm text-text-muted hover:text-text-primary"
aria-label="Refresh playlist"
>
{refreshingSystem ? 'Refreshing…' : 'Refresh'}
</button>
{/if}
{#if isOwner && pl.is_public}
<button
type="button"
onclick={onCopyLink}
aria-label="Copy public link to this playlist"
title="Copy link"
class="rounded p-2 text-text-muted hover:bg-surface-hover hover:text-text-primary"
>
<LinkIcon size={16} strokeWidth={1} />
</button>
{/if}
{#if isOwner}
<button
type="button"
onclick={startEdit}
aria-label="Edit playlist"
class="rounded p-2 text-text-muted hover:bg-surface-hover hover:text-text-primary"
>
<Pencil size={16} strokeWidth={1} />
</button>
<button
type="button"
onclick={submitDelete}
aria-label="Delete playlist"
class="rounded p-2 text-text-muted hover:bg-surface-hover hover:text-action-destructive"
>
<Trash2 size={16} strokeWidth={1} />
</button>
{/if}
{/snippet}
</CollectionHeader>
{:else}
<section class="mb-6 rounded-md border border-border bg-surface p-4">
<label class="block text-sm font-medium text-text-primary">
Name
<input
type="text"
bind:value={editName}
class="mt-1 w-full rounded border border-border bg-background px-3 py-1.5 text-sm text-text-primary"
/>
</label>
<label class="mt-3 block text-sm font-medium text-text-primary">
Description
<textarea
bind:value={editDesc}
rows="2"
class="mt-1 w-full rounded border border-border bg-background px-3 py-1.5 text-sm text-text-primary"
></textarea>
</label>
<label class="mt-3 flex items-center gap-2 text-sm text-text-primary">
<input type="checkbox" bind:checked={editIsPublic} class="rounded border-border" />
Make this playlist public
</label>
<div class="mt-3 flex justify-end gap-2">
<button
type="button"
onclick={() => (editing = false)}
class="rounded-md border border-border px-3 py-1.5 text-sm text-text-muted hover:text-text-primary"
>
Cancel
</button>
<button
type="button"
onclick={submitEdit}
class="rounded-md bg-action-secondary px-3 py-1.5 text-sm text-action-fg"
>
Save
</button>
</div>
</section>
{/if}
{#if pl.tracks.length === 0}
<p class="rounded-md border border-border px-3 py-6 text-sm text-text-muted">
{#if isOwner}
No tracks yet. Add some via the "Add to playlist…" entry on any track row.
{:else}
No tracks in this playlist.
{/if}
</p>
{:else}
<TrackList>
{#each pl.tracks as row (row.position)}
<PlaylistTrackRow
{row}
isOwner={isOwner ?? false}
onRemove={onRemove}
onPlay={onPlay}
onMove={onMove}
/>
{/each}
</TrackList>
{/if}
{/if}
</PageColumn>