feat(home): add Qobuz discover playlists section with tag filter

- Add backend endpoint for /discover/playlists API
- Add PlaylistTagFilter dropdown component for filtering by genre
- Add QobuzPlaylistCard with CSS blur background effect (color-thief style)
- Add HorizontalScrollRow header snippet for custom headers with scroll controls
- Add session cache store for caching API responses
- Add i18n keys for playlist filter and discover section

cc
This commit is contained in:
vicrodh committed 2026-02-03 21:37:26 -06:00
1 parent 9341e9ee19
commit deaffa183d
15 files changed
+1608 -63

No files matched your search

+117
View File
@@ -452,6 +452,100 @@ impl QobuzClient {
Ok(serde_json::from_value(genres.clone())?) Ok(serde_json::from_value(genres.clone())?)
} }
/// Get discover index (home page content: playlists, ideal discography, etc.)
pub async fn get_discover_index(
&self,
genre_ids: Option<Vec<u64>>,
) -> Result<DiscoverResponse> {
let url = endpoints::build_url(paths::DISCOVER_INDEX);
let mut query: Vec<(&str, String)> = vec![];
// Add genre_ids as comma-separated list if provided
if let Some(gids) = genre_ids {
if !gids.is_empty() {
let ids_str = gids.iter().map(|id| id.to_string()).collect::<Vec<_>>().join(",");
query.push(("genre_ids", ids_str));
}
}
let response: Value = self
.http
.get(&url)
.header("X-App-Id", self.app_id().await?)
.header("X-User-Auth-Token", self.auth_token().await?)
.query(&query)
.send()
.await?
.json()
.await?;
// Debug: log the response structure
if let Some(obj) = response.as_object() {
log::info!("Discover API response keys: {:?}", obj.keys().collect::<Vec<_>>());
if let Some(err) = obj.get("message") {
log::error!("Discover API error: {:?}", err);
}
if let Some(code) = obj.get("code") {
log::error!("Discover API error code: {:?}", code);
}
}
Ok(serde_json::from_value(response)?)
}
/// Get discover playlists with optional tag filter
/// Example: tags=label, tags=partner
pub async fn get_discover_playlists(
&self,
tag: Option<String>,
limit: Option<u32>,
offset: Option<u32>,
) -> Result<DiscoverPlaylistsResponse> {
let url = endpoints::build_url(paths::DISCOVER_PLAYLISTS);
let mut query: Vec<(&str, String)> = vec![];
// Add tag filter if provided (e.g., "label", "partner")
if let Some(ref t) = tag {
query.push(("tags", t.clone()));
}
// Add limit (default 20)
let lim = limit.unwrap_or(20);
query.push(("limit", lim.to_string()));
// Add offset (default 0)
let off = offset.unwrap_or(0);
query.push(("offset", off.to_string()));
log::debug!("[API] get_discover_playlists URL: {} query: {:?}", url, query);
// First get raw JSON to debug structure
let raw_response: serde_json::Value = self
.http
.get(&url)
.header("X-App-Id", self.app_id().await?)
.header("X-User-Auth-Token", self.auth_token().await?)
.query(&query)
.send()
.await?
.json()
.await?;
log::debug!("[API] get_discover_playlists raw response keys: {:?}", raw_response.as_object().map(|o| o.keys().collect::<Vec<_>>()));
// Try to parse as expected structure
let response: DiscoverPlaylistsResponse = serde_json::from_value(raw_response.clone())
.map_err(|e| {
log::error!("[API] Failed to parse discover playlists response: {}", e);
log::error!("[API] Raw response: {}", serde_json::to_string_pretty(&raw_response).unwrap_or_default());
e
})?;
log::debug!("[API] get_discover_playlists response: {} playlists", response.items.len());
Ok(response)
}
/// Get track by ID /// Get track by ID
pub async fn get_track(&self, track_id: u64) -> Result<Track> { pub async fn get_track(&self, track_id: u64) -> Result<Track> {
let url = endpoints::build_url(paths::TRACK_GET); let url = endpoints::build_url(paths::TRACK_GET);
@@ -468,6 +562,29 @@ impl QobuzClient {
Ok(serde_json::from_value(response)?) Ok(serde_json::from_value(response)?)
} }
/// Get artist by ID (basic info only - no albums, faster response)
pub async fn get_artist_basic(&self, artist_id: u64) -> Result<Artist> {
let url = endpoints::build_url(paths::ARTIST_GET);
let locale = self.locale().await;
let query = vec![
("artist_id", artist_id.to_string()),
("lang", locale),
// No "extra" parameter = only basic info (id, name, image)
];
let response: Value = self
.http
.get(&url)
.header("X-App-Id", self.app_id().await?)
.query(&query)
.send()
.await?
.json()
.await?;
Ok(serde_json::from_value(response)?)
}
/// Get artist by ID /// Get artist by ID
pub async fn get_artist( pub async fn get_artist(
&self, &self,
+4
View File
@@ -45,6 +45,10 @@ pub mod paths {
// Catalog (combined search) // Catalog (combined search)
pub const CATALOG_SEARCH: &str = "/catalog/search"; pub const CATALOG_SEARCH: &str = "/catalog/search";
// Discover (home page content)
pub const DISCOVER_INDEX: &str = "/discover/index";
pub const DISCOVER_PLAYLISTS: &str = "/discover/playlists";
} }
/// Build full URL for an endpoint /// Build full URL for an endpoint
+126 -4
View File
@@ -7,9 +7,9 @@ use serde::{Deserialize, Serialize};
#[repr(u32)] #[repr(u32)]
pub enum Quality { pub enum Quality {
Mp3 = 5, Mp3 = 5,
Lossless = 6, // 16-bit/44.1kHz (CD Quality) Lossless = 6, // 16-bit/44.1kHz (CD Quality)
HiRes = 7, // 24-bit/≤96kHz HiRes = 7, // 24-bit/≤96kHz
UltraHiRes = 27, // 24-bit/>96kHz UltraHiRes = 27, // 24-bit/>96kHz
} }
impl Quality { impl Quality {
@@ -38,7 +38,12 @@ impl Quality {
/// Quality levels in descending order for fallback /// Quality levels in descending order for fallback
pub fn fallback_order() -> &'static [Quality] { pub fn fallback_order() -> &'static [Quality] {
&[Quality::UltraHiRes, Quality::HiRes, Quality::Lossless, Quality::Mp3] &[
Quality::UltraHiRes,
Quality::HiRes,
Quality::Lossless,
Quality::Mp3,
]
} }
} }
@@ -344,3 +349,120 @@ pub struct Favorites {
pub tracks: Option<SearchResultsPage<Track>>, pub tracks: Option<SearchResultsPage<Track>>,
pub artists: Option<SearchResultsPage<Artist>>, pub artists: Option<SearchResultsPage<Artist>>,
} }
// ============ Discover API Models ============
/// Discover index response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoverResponse {
pub containers: DiscoverContainers,
}
/// All discover containers
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoverContainers {
pub playlists: Option<DiscoverContainer<DiscoverPlaylist>>,
pub ideal_discography: Option<DiscoverContainer<DiscoverAlbum>>,
pub playlists_tags: Option<DiscoverContainer<PlaylistTag>>,
pub new_releases: Option<DiscoverContainer<DiscoverAlbum>>,
}
/// Generic discover container
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoverContainer<T> {
pub id: String,
pub data: DiscoverData<T>,
}
/// Generic discover data with items
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoverData<T> {
pub has_more: bool,
pub items: Vec<T>,
}
/// Playlist from discover endpoint (different structure than regular Playlist)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoverPlaylist {
pub id: u64,
pub name: String,
pub owner: PlaylistOwner,
pub image: DiscoverPlaylistImage,
pub description: Option<String>,
pub duration: u32,
pub tracks_count: u32,
pub genres: Option<Vec<PlaylistGenre>>,
pub tags: Option<Vec<PlaylistTag>>,
}
/// Playlist image structure from discover (has rectangle and covers)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoverPlaylistImage {
pub rectangle: Option<String>,
pub covers: Option<Vec<String>>,
}
/// Playlist tag (for filtering)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlaylistTag {
pub id: u64,
pub slug: String,
pub name: String,
}
/// Response from discover/playlists endpoint
/// Note: This endpoint returns items directly at root level (not wrapped in "playlists")
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoverPlaylistsResponse {
pub has_more: bool,
pub items: Vec<DiscoverPlaylist>,
}
/// Album from discover endpoint
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoverAlbum {
pub id: String,
pub title: String,
pub version: Option<String>,
pub track_count: Option<u32>,
pub duration: Option<u32>,
pub parental_warning: Option<bool>,
pub image: DiscoverAlbumImage,
pub artists: Vec<DiscoverArtist>,
pub label: Option<Label>,
pub genre: Option<Genre>,
pub dates: Option<DiscoverAlbumDates>,
pub audio_info: Option<DiscoverAudioInfo>,
}
/// Album image from discover endpoint
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoverAlbumImage {
pub small: Option<String>,
pub thumbnail: Option<String>,
pub large: Option<String>,
}
/// Artist in discover album
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoverArtist {
pub id: u64,
pub name: String,
pub roles: Option<Vec<String>>,
}
/// Album dates from discover
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoverAlbumDates {
pub download: Option<String>,
pub original: Option<String>,
pub stream: Option<String>,
}
/// Audio info from discover album
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoverAudioInfo {
pub maximum_sampling_rate: Option<f64>,
pub maximum_bit_depth: Option<u32>,
pub maximum_channel_count: Option<u32>,
}
+77 -1
View File
@@ -2,7 +2,7 @@
use tauri::State; use tauri::State;
use crate::api::{endpoints, endpoints::paths, Album, Artist, ArtistAlbums, LabelDetail, Playlist, SearchResultsPage, Track, TracksContainer}; use crate::api::{endpoints, endpoints::paths, Album, Artist, ArtistAlbums, DiscoverResponse, DiscoverPlaylistsResponse, LabelDetail, Playlist, SearchResultsPage, Track, TracksContainer};
use crate::api_cache::ApiCacheState; use crate::api_cache::ApiCacheState;
use crate::artist_blacklist::BlacklistState; use crate::artist_blacklist::BlacklistState;
use crate::AppState; use crate::AppState;
@@ -416,6 +416,50 @@ pub async fn get_artist(
Ok(artist) Ok(artist)
} }
/// Get artist basic info only (no albums - faster for lists/cards)
#[tauri::command]
pub async fn get_artist_basic(
artist_id: u64,
state: State<'_, AppState>,
cache_state: State<'_, ApiCacheState>,
) -> Result<Artist, String> {
log::debug!("Command: get_artist_basic {}", artist_id);
// Get current locale
let locale = {
let client = state.client.lock().await;
client.get_locale().await
};
// Check cache first (reuse same cache - basic response works for both)
{
let cache = cache_state.cache.lock().await;
if let Some(cached_data) = cache.get_artist(artist_id, &locale, None)? {
log::debug!("Cache hit for artist_basic {} (locale: {})", artist_id, locale);
return serde_json::from_str(&cached_data)
.map_err(|e| format!("Failed to parse cached artist: {}", e));
}
}
// Cache miss - fetch from API (without albums - much faster)
log::debug!("Cache miss for artist_basic {} (locale: {}), fetching from API", artist_id, locale);
let client = state.client.lock().await;
let artist = client
.get_artist_basic(artist_id)
.await
.map_err(|e| e.to_string())?;
// Cache the result
{
let cache = cache_state.cache.lock().await;
let json = serde_json::to_string(&artist)
.map_err(|e| format!("Failed to serialize artist: {}", e))?;
cache.set_artist(artist_id, &locale, &json)?;
}
Ok(artist)
}
/// Get artist detail with albums, playlists, and appears-on tracks /// Get artist detail with albums, playlists, and appears-on tracks
/// Fetches 1000 albums initially to ensure each album type section /// Fetches 1000 albums initially to ensure each album type section
/// (Discography, EPs, Live, etc.) has enough albums loaded /// (Discography, EPs, Live, etc.) has enough albums loaded
@@ -552,3 +596,35 @@ pub async fn get_genres(
.await .await
.map_err(|e| e.to_string()) .map_err(|e| e.to_string())
} }
/// Get discover index (home page content: playlists, ideal discography, etc.)
#[tauri::command]
pub async fn get_discover_index(
genre_ids: Option<Vec<u64>>,
state: State<'_, AppState>,
) -> Result<DiscoverResponse, String> {
log::debug!("Command: get_discover_index genre_ids={:?}", genre_ids);
let client = state.client.lock().await;
client
.get_discover_index(genre_ids)
.await
.map_err(|e| e.to_string())
}
/// Get discover playlists with optional tag filter
#[tauri::command]
pub async fn get_discover_playlists(
tag: Option<String>,
limit: Option<u32>,
offset: Option<u32>,
state: State<'_, AppState>,
) -> Result<DiscoverPlaylistsResponse, String> {
log::debug!("Command: get_discover_playlists tag={:?} limit={:?} offset={:?}", tag, limit, offset);
let client = state.client.lock().await;
client
.get_discover_playlists(tag, limit, offset)
.await
.map_err(|e| e.to_string())
}
+3
View File
@@ -529,8 +529,11 @@ pub fn run() {
commands::get_album, commands::get_album,
commands::get_featured_albums, commands::get_featured_albums,
commands::get_genres, commands::get_genres,
commands::get_discover_index,
commands::get_discover_playlists,
commands::get_track, commands::get_track,
commands::get_artist, commands::get_artist,
commands::get_artist_basic,
commands::get_artist_detail, commands::get_artist_detail,
commands::get_artist_tracks, commands::get_artist_tracks,
commands::get_artist_albums, commands::get_artist_albums,
+32 -12
View File
@@ -3,11 +3,12 @@
import type { Snippet } from 'svelte'; import type { Snippet } from 'svelte';
interface Props { interface Props {
title: string; title?: string;
header?: Snippet;
children: Snippet; children: Snippet;
} }
let { title, children }: Props = $props(); let { title, header, children }: Props = $props();
let scrollContainer: HTMLDivElement; let scrollContainer: HTMLDivElement;
@@ -25,21 +26,31 @@
}); });
} }
} }
const hasHeader = $derived(!!title || !!header);
</script> </script>
<div class="scroll-row"> <div class="scroll-row">
<!-- Section Header --> <!-- Section Header -->
<div class="header"> {#if hasHeader}
<h2 class="title">{title}</h2> <div class="header">
<div class="nav-buttons"> {#if header}
<button onclick={() => scroll('left')} class="nav-btn"> <div class="header-content">
<ChevronLeft size={24} /> {@render header()}
</button> </div>
<button onclick={() => scroll('right')} class="nav-btn"> {:else if title}
<ChevronRight size={24} /> <h2 class="title">{title}</h2>
</button> {/if}
<div class="nav-buttons">
<button onclick={() => scroll('left')} class="nav-btn">
<ChevronLeft size={24} />
</button>
<button onclick={() => scroll('right')} class="nav-btn">
<ChevronRight size={24} />
</button>
</div>
</div> </div>
</div> {/if}
<!-- Horizontal Scroll Container --> <!-- Horizontal Scroll Container -->
<div class="scroll-container hide-scrollbar" bind:this={scrollContainer}> <div class="scroll-container hide-scrollbar" bind:this={scrollContainer}>
@@ -61,6 +72,14 @@
margin-bottom: 16px; margin-bottom: 16px;
} }
.header-content {
display: flex;
align-items: center;
gap: 16px;
flex: 1;
min-width: 0;
}
.title { .title {
font-size: 22px; font-size: 22px;
font-weight: 600; font-weight: 600;
@@ -71,6 +90,7 @@
display: flex; display: flex;
align-items: center; align-items: center;
gap: 8px; gap: 8px;
flex-shrink: 0;
} }
.nav-btn { .nav-btn {
+215
View File
@@ -0,0 +1,215 @@
<script lang="ts">
import { tick } from 'svelte';
import { ChevronDown, Check } from 'lucide-svelte';
import { t } from '$lib/i18n';
import type { PlaylistTag } from '$lib/types';
interface Props {
tags: PlaylistTag[];
selectedTag: string | null;
onTagChange: (tag: string | null) => void;
}
let { tags, selectedTag, onTagChange }: Props = $props();
let isOpen = $state(false);
let buttonEl: HTMLButtonElement | null = $state(null);
let menuEl: HTMLDivElement | null = $state(null);
let menuStyle = $state('');
const selectedTagName = $derived.by(() => {
if (!selectedTag) return null;
const tag = tags.find(t => t.slug === selectedTag);
return tag?.name ?? null;
});
function portal(node: HTMLElement) {
document.body.appendChild(node);
return {
destroy() {
if (node.parentNode) node.parentNode.removeChild(node);
}
};
}
async function positionMenu() {
await tick();
if (!buttonEl || !menuEl) return;
const btnRect = buttonEl.getBoundingClientRect();
const menuRect = menuEl.getBoundingClientRect();
let left = btnRect.left;
let top = btnRect.bottom + 4;
// Keep within viewport
if (left + menuRect.width > window.innerWidth - 8) {
left = window.innerWidth - menuRect.width - 8;
}
if (top + menuRect.height > window.innerHeight - 8) {
top = btnRect.top - menuRect.height - 4;
}
menuStyle = `left: ${left}px; top: ${top}px;`;
}
function toggleMenu() {
isOpen = !isOpen;
if (isOpen) positionMenu();
}
function selectTag(slug: string | null) {
onTagChange(slug);
isOpen = false;
}
function handleClickOutside(event: MouseEvent) {
if (isOpen && menuEl && !menuEl.contains(event.target as Node) &&
buttonEl && !buttonEl.contains(event.target as Node)) {
isOpen = false;
}
}
$effect(() => {
if (isOpen) {
document.addEventListener('click', handleClickOutside);
return () => document.removeEventListener('click', handleClickOutside);
}
});
</script>
<div class="tag-filter-wrapper">
<button
class="tag-filter-btn"
class:active={selectedTag !== null}
bind:this={buttonEl}
onclick={toggleMenu}
type="button"
>
<span class="filter-label">
{#if selectedTagName}
{selectedTagName}
{:else}
{$t('home.allTags')}
{/if}
</span>
<ChevronDown size={14} class={isOpen ? 'rotated' : ''} />
</button>
{#if isOpen}
<div class="tag-menu" bind:this={menuEl} style={menuStyle} use:portal>
<button
class="tag-item"
class:selected={selectedTag === null}
onclick={() => selectTag(null)}
>
<span>{$t('home.allTags')}</span>
{#if selectedTag === null}
<Check size={14} />
{/if}
</button>
{#each tags as tag (tag.id)}
<button
class="tag-item"
class:selected={selectedTag === tag.slug}
onclick={() => selectTag(tag.slug)}
>
<span>{tag.name}</span>
{#if selectedTag === tag.slug}
<Check size={14} />
{/if}
</button>
{/each}
</div>
{/if}
</div>
<style>
.tag-filter-wrapper {
position: relative;
}
.tag-filter-btn {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 12px;
border: 1px solid var(--border-subtle);
border-radius: 6px;
background: transparent;
color: var(--text-secondary);
font-size: 12px;
cursor: pointer;
transition: all 150ms ease;
}
.tag-filter-btn:hover {
background: var(--bg-hover);
color: var(--text-primary);
border-color: var(--border-subtle);
}
.tag-filter-btn.active {
background: var(--accent-primary);
color: white;
border-color: var(--accent-primary);
}
.tag-filter-btn.active:hover {
background: var(--accent-hover);
border-color: var(--accent-hover);
}
.filter-label {
max-width: 120px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tag-filter-btn :global(.rotated) {
transform: rotate(180deg);
}
.tag-menu {
position: fixed;
z-index: 30000;
min-width: 140px;
max-height: 280px;
overflow-y: auto;
background-color: var(--bg-tertiary);
border: 1px solid var(--border-subtle);
border-radius: 8px;
padding: 4px 0;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
}
.tag-item {
width: 100%;
padding: 8px 12px;
background: none;
border: none;
color: var(--text-secondary);
text-align: left;
font-size: 12px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
transition: background-color 150ms ease, color 150ms ease;
}
.tag-item:hover {
background-color: var(--bg-hover);
color: var(--text-primary);
}
.tag-item.selected {
color: var(--accent-primary);
}
.tag-item.selected:hover {
color: var(--accent-primary);
}
</style>
+473
View File
@@ -0,0 +1,473 @@
<script lang="ts">
import { tick } from 'svelte';
import { Play, ListMusic, Plus, MoreHorizontal, ListPlus, Library, Share2 } from 'lucide-svelte';
import { t } from '$lib/i18n';
interface Props {
playlistId: number;
name: string;
owner: string;
image?: string;
trackCount?: number;
duration?: number;
genre?: string;
onclick?: () => void;
onPlay?: () => void;
onPlayNext?: () => void;
onPlayLater?: () => void;
onCopyToLibrary?: () => void;
onShareQobuz?: () => void;
}
let {
playlistId,
name,
owner,
image,
trackCount,
duration,
genre,
onclick,
onPlay,
onPlayNext,
onPlayLater,
onCopyToLibrary,
onShareQobuz
}: Props = $props();
let imageError = $state(false);
let imageLoaded = $state(false);
let menuOpen = $state(false);
let menuTriggerRef: HTMLButtonElement | null = $state(null);
let menuEl: HTMLDivElement | null = $state(null);
let menuStyle = $state('');
const cardSize = 180;
function handleImageError() {
imageError = true;
}
function handleImageLoad() {
imageLoaded = true;
}
function handlePlay(event: MouseEvent) {
event.stopPropagation();
onPlay?.();
}
function handleCopyToLibrary(event: MouseEvent) {
event.stopPropagation();
onCopyToLibrary?.();
}
function handleCardClick(event: MouseEvent) {
const target = event.target;
if (target instanceof HTMLElement && target.closest('.action-buttons')) return;
onclick?.();
}
function formatDuration(seconds: number): string {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
if (hours > 0) {
return `${hours}h ${minutes}m`;
}
return `${minutes}m`;
}
// Portal for menu
function portal(node: HTMLElement) {
document.body.appendChild(node);
return {
destroy() {
if (node.parentNode) node.parentNode.removeChild(node);
}
};
}
async function positionMenu() {
await tick();
if (!menuTriggerRef || !menuEl) return;
const triggerRect = menuTriggerRef.getBoundingClientRect();
const menuRect = menuEl.getBoundingClientRect();
let left = triggerRect.right - menuRect.width;
let top = triggerRect.bottom + 8;
if (left < 8) left = 8;
if (left + menuRect.width > window.innerWidth - 8) {
left = window.innerWidth - menuRect.width - 8;
}
if (top + menuRect.height > window.innerHeight - 8) {
top = triggerRect.top - menuRect.height - 8;
}
menuStyle = `left: ${left}px; top: ${top}px;`;
}
function toggleMenu(event: MouseEvent) {
event.stopPropagation();
menuOpen = !menuOpen;
if (menuOpen) positionMenu();
}
function closeMenu() {
menuOpen = false;
}
function handleClickOutside(event: MouseEvent) {
if (menuOpen && menuEl && !menuEl.contains(event.target as Node) &&
menuTriggerRef && !menuTriggerRef.contains(event.target as Node)) {
menuOpen = false;
}
}
$effect(() => {
if (menuOpen) {
document.addEventListener('click', handleClickOutside);
return () => document.removeEventListener('click', handleClickOutside);
}
});
const hasOverlay = $derived(!!(onPlay || onCopyToLibrary || genre || trackCount || duration));
</script>
<div
class="playlist-card"
class:menu-open={menuOpen}
style="width: {cardSize}px"
onclick={handleCardClick}
role="button"
tabindex="0"
onkeydown={(e) => e.key === 'Enter' && onclick?.()}
>
<!-- Artwork Container (Square) -->
<div
class="artwork-container"
style="width: {cardSize}px; height: {cardSize}px;"
>
<!-- Blurred background image for color effect -->
{#if !imageError && image}
<div
class="artwork-bg"
style="background-image: url({image});"
></div>
{/if}
<!-- Placeholder -->
<div class="artwork-placeholder">
<ListMusic size={48} />
</div>
<!-- Main Image (contain) -->
{#if !imageError && image}
<img
src={image}
alt={name}
class="artwork-main"
loading="lazy"
decoding="async"
onerror={handleImageError}
onload={handleImageLoad}
/>
{/if}
<!-- Action Overlay -->
{#if hasOverlay}
<div class="action-overlay">
<!-- Overlay Info (top) -->
<div class="overlay-info">
{#if genre}
<span class="overlay-genre">{genre}</span>
{/if}
<div class="overlay-meta">
{#if trackCount}
<span>{trackCount} {$t('playlist.tracks')}</span>
{/if}
{#if duration}
<span>{formatDuration(duration)}</span>
{/if}
</div>
</div>
<!-- Action Buttons (bottom) -->
<div class="action-buttons">
{#if onCopyToLibrary}
<button
class="overlay-btn overlay-btn--minor"
type="button"
onclick={handleCopyToLibrary}
title={$t('playlist.copyToLibrary')}
>
<Plus size={18} />
</button>
{:else}
<div class="overlay-btn--spacer"></div>
{/if}
{#if onPlay}
<button class="overlay-btn" type="button" onclick={handlePlay} title={$t('actions.play')}>
<Play size={18} fill="white" color="white" />
</button>
{/if}
<button
class="overlay-btn overlay-btn--minor"
type="button"
bind:this={menuTriggerRef}
onclick={toggleMenu}
title={$t('actions.moreOptions')}
>
<MoreHorizontal size={18} />
</button>
</div>
</div>
{/if}
</div>
<!-- Text Info -->
<div class="info">
<div class="title" title={name}>{name}</div>
<div class="owner">{owner}</div>
</div>
</div>
<!-- Context Menu Portal -->
{#if menuOpen}
<div class="playlist-menu" bind:this={menuEl} style={menuStyle} use:portal>
{#if onPlayNext}
<button class="menu-item" onclick={() => { onPlayNext(); closeMenu(); }}>
<ListPlus size={14} /> <span>{$t('player.playNext')}</span>
</button>
{/if}
{#if onPlayLater}
<button class="menu-item" onclick={() => { onPlayLater(); closeMenu(); }}>
<ListMusic size={14} /> <span>{$t('player.addToQueue')}</span>
</button>
{/if}
{#if (onPlayNext || onPlayLater) && (onCopyToLibrary || onShareQobuz)}
<div class="menu-separator"></div>
{/if}
{#if onCopyToLibrary}
<button class="menu-item" onclick={() => { onCopyToLibrary(); closeMenu(); }}>
<Library size={14} /> <span>{$t('playlist.copyToLibrary')}</span>
</button>
{/if}
{#if onCopyToLibrary && onShareQobuz}
<div class="menu-separator"></div>
{/if}
{#if onShareQobuz}
<button class="menu-item" onclick={() => { onShareQobuz(); closeMenu(); }}>
<Share2 size={14} /> <span>{$t('actions.shareQobuz')}</span>
</button>
{/if}
</div>
{/if}
<style>
.playlist-card {
flex-shrink: 0;
cursor: pointer;
transition: transform 150ms ease;
}
.artwork-container {
position: relative;
margin-bottom: 8px;
border-radius: 8px;
overflow: hidden;
background: var(--bg-tertiary);
}
/* Blurred background - simulates dominant color */
.artwork-bg {
position: absolute;
inset: -20px;
background-size: cover;
background-position: center;
filter: blur(30px) saturate(1.5);
transform: scale(1.2);
z-index: 0;
}
/* Darken overlay on blurred bg */
.artwork-bg::after {
content: '';
position: absolute;
inset: 0;
background: rgba(0, 0, 0, 0.25);
}
.artwork-main {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: contain;
border-radius: inherit;
z-index: 1;
}
.artwork-placeholder {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
color: var(--text-muted);
z-index: 0;
}
/* Hide placeholder when image exists */
.artwork-container:has(.artwork-bg) .artwork-placeholder {
display: none;
}
.action-overlay {
position: absolute;
inset: 0;
background: linear-gradient(180deg, rgba(0,0,0,0.7) 0%, transparent 40%, transparent 60%, rgba(0,0,0,0.7) 100%);
opacity: 0;
transition: opacity 150ms ease;
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 8px 12px 12px;
border-radius: inherit;
z-index: 2;
}
.playlist-card:hover .action-overlay,
.playlist-card.menu-open .action-overlay {
opacity: 1;
}
.overlay-info {
display: flex;
flex-direction: column;
gap: 4px;
}
.overlay-genre {
font-size: 14px;
font-weight: 600;
color: white;
text-shadow: 0 1px 3px rgba(0, 0, 0, 0.8);
word-wrap: break-word;
overflow-wrap: break-word;
}
.overlay-meta {
display: flex;
gap: 8px;
font-size: 12px;
font-weight: 400;
color: rgba(255, 255, 255, 0.85);
text-shadow: 0 1px 3px rgba(0, 0, 0, 0.8);
}
.overlay-meta span:not(:last-child)::after {
content: '\2022';
margin-left: 8px;
opacity: 0.6;
}
.action-buttons {
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
}
.overlay-btn {
width: 38px;
height: 38px;
border-radius: 50%;
border: none;
background: transparent;
color: white;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.85), 0 0 1px rgba(0, 0, 0, 0.3);
transition: transform 150ms ease, background-color 150ms ease, box-shadow 150ms ease;
}
.overlay-btn:hover {
background-color: rgba(0, 0, 0, 0.3);
box-shadow: inset 0 0 0 1px var(--accent-primary), 0 0 4px rgba(0, 0, 0, 0.5);
}
.overlay-btn--minor {
width: 30px;
height: 30px;
}
.overlay-btn--spacer {
width: 30px;
height: 30px;
visibility: hidden;
}
.info {
width: 100%;
}
.title {
font-size: 14px;
font-weight: 500;
color: var(--text-primary);
line-height: 1.4;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
margin-bottom: 2px;
}
.owner {
font-size: 12px;
font-weight: 400;
color: var(--text-muted);
line-height: 1.4;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* Context Menu */
.playlist-menu {
position: fixed;
z-index: 30000;
min-width: 160px;
background-color: var(--bg-tertiary);
border-radius: 8px;
padding: 2px 0;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
}
.menu-item {
width: 100%;
padding: 8px 12px;
background: none;
border: none;
color: var(--text-secondary);
text-align: left;
font-size: 12px;
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
transition: background-color 150ms ease, color 150ms ease;
}
.menu-item:hover {
background-color: var(--bg-hover);
color: var(--text-primary);
}
.menu-separator {
height: 1px;
background-color: var(--bg-hover);
margin: 4px 0;
}
</style>
+387 -42
View File
@@ -5,9 +5,11 @@
import { t } from '$lib/i18n'; import { t } from '$lib/i18n';
import HorizontalScrollRow from '../HorizontalScrollRow.svelte'; import HorizontalScrollRow from '../HorizontalScrollRow.svelte';
import AlbumCard from '../AlbumCard.svelte'; import AlbumCard from '../AlbumCard.svelte';
import QobuzPlaylistCard from '../QobuzPlaylistCard.svelte';
import TrackRow from '../TrackRow.svelte'; import TrackRow from '../TrackRow.svelte';
import HomeSettingsModal from '../HomeSettingsModal.svelte'; import HomeSettingsModal from '../HomeSettingsModal.svelte';
import GenreFilterButton from '../GenreFilterButton.svelte'; import GenreFilterButton from '../GenreFilterButton.svelte';
import PlaylistTagFilter from '../PlaylistTagFilter.svelte';
import { formatDuration, formatQuality, getQobuzImage } from '$lib/adapters/qobuzAdapters'; import { formatDuration, formatQuality, getQobuzImage } from '$lib/adapters/qobuzAdapters';
import { isBlacklisted as isArtistBlacklisted } from '$lib/stores/artistBlacklistStore'; import { isBlacklisted as isArtistBlacklisted } from '$lib/stores/artistBlacklistStore';
import { import {
@@ -24,7 +26,25 @@
hasActiveFilter as hasGenreFilter hasActiveFilter as hasGenreFilter
} from '$lib/stores/genreFilterStore'; } from '$lib/stores/genreFilterStore';
import { setPlaybackContext } from '$lib/stores/playbackContextStore'; import { setPlaybackContext } from '$lib/stores/playbackContextStore';
import type { QobuzAlbum, QobuzArtist, QobuzTrack, DisplayTrack } from '$lib/types'; import {
getCachedArtist,
setCachedArtist,
getCachedAlbum,
setCachedAlbum,
getCachedTrack,
setCachedTrack
} from '$lib/stores/sessionCacheStore';
import type {
QobuzAlbum,
QobuzArtist,
QobuzTrack,
DisplayTrack,
DiscoverResponse,
DiscoverPlaylist,
DiscoverPlaylistsResponse,
DiscoverAlbum,
PlaylistTag
} from '$lib/types';
interface TopArtistSeed { interface TopArtistSeed {
artistId: number; artistId: number;
@@ -85,6 +105,12 @@
onTrackReDownload?: (track: DisplayTrack) => void; onTrackReDownload?: (track: DisplayTrack) => void;
checkTrackDownloaded?: (trackId: number) => boolean; checkTrackDownloaded?: (trackId: number) => boolean;
getTrackOfflineCacheStatus?: (trackId: number) => { status: string; progress: number }; getTrackOfflineCacheStatus?: (trackId: number) => { status: string; progress: number };
onPlaylistClick?: (playlistId: number) => void;
onPlaylistPlay?: (playlistId: number) => void;
onPlaylistPlayNext?: (playlistId: number) => void;
onPlaylistPlayLater?: (playlistId: number) => void;
onPlaylistCopyToLibrary?: (playlistId: number) => void;
onPlaylistShareQobuz?: (playlistId: number) => void;
activeTrackId?: number | null; activeTrackId?: number | null;
isPlaybackActive?: boolean; isPlaybackActive?: boolean;
sidebarExpanded?: boolean; sidebarExpanded?: boolean;
@@ -119,6 +145,12 @@
onTrackReDownload, onTrackReDownload,
checkTrackDownloaded, checkTrackDownloaded,
getTrackOfflineCacheStatus, getTrackOfflineCacheStatus,
onPlaylistClick,
onPlaylistPlay,
onPlaylistPlayNext,
onPlaylistPlayLater,
onPlaylistCopyToLibrary,
onPlaylistShareQobuz,
activeTrackId = null, activeTrackId = null,
isPlaybackActive = false, isPlaybackActive = false,
sidebarExpanded = true sidebarExpanded = true
@@ -149,13 +181,28 @@
homeSettings.sections.filter(s => s.visible).map(s => s.id) homeSettings.sections.filter(s => s.visible).map(s => s.id)
); );
// Deferred rendering: only render first N sections immediately, defer the rest
const IMMEDIATE_SECTIONS = 3;
let deferredSectionsReady = $state(false);
// Sections to render immediately vs deferred
const immediateSections = $derived(visibleSections.slice(0, IMMEDIATE_SECTIONS));
const deferredSections = $derived(visibleSections.slice(IMMEDIATE_SECTIONS));
// All sections ready to render
const renderableSections = $derived(
deferredSectionsReady ? visibleSections : immediateSections
);
const LIMITS = { const LIMITS = {
recentAlbums: 20, recentAlbums: 20,
continueTracks: 10, continueTracks: 10,
topArtists: 20, topArtists: 8,
favoriteAlbums: 12, favoriteAlbums: 12,
favoriteTracks: 10, favoriteTracks: 10,
featuredAlbums: 12 featuredAlbums: 12,
qobuzPlaylists: 15,
essentialDiscography: 15
}; };
let homeLimits = $state(getSettings().limits); let homeLimits = $state(getSettings().limits);
@@ -173,6 +220,8 @@
let loadingContinueTracks = $state(true); let loadingContinueTracks = $state(true);
let loadingTopArtists = $state(true); let loadingTopArtists = $state(true);
let loadingFavoriteAlbums = $state(true); let loadingFavoriteAlbums = $state(true);
let loadingQobuzPlaylists = $state(true);
let loadingEssentialDiscography = $state(true);
// Track loading completion for overlay // Track loading completion for overlay
let totalVisibleSections = $state(0); let totalVisibleSections = $state(0);
@@ -191,6 +240,12 @@
let topArtists = $state<ArtistCardData[]>([]); let topArtists = $state<ArtistCardData[]>([]);
let favoriteAlbums = $state<AlbumCardData[]>([]); let favoriteAlbums = $state<AlbumCardData[]>([]);
// Discover sections
let qobuzPlaylists = $state<DiscoverPlaylist[]>([]);
let essentialDiscography = $state<DiscoverAlbum[]>([]);
let playlistTags = $state<PlaylistTag[]>([]);
let selectedTagSlug = $state<string | null>(null);
let failedArtistImages = $state<Set<number>>(new Set()); let failedArtistImages = $state<Set<number>>(new Set());
// Download status tracking // Download status tracking
@@ -211,7 +266,12 @@
async function loadAllAlbumDownloadStatuses(albums: AlbumCardData[]) { async function loadAllAlbumDownloadStatuses(albums: AlbumCardData[]) {
if (!checkAlbumFullyDownloaded || albums.length === 0) return; if (!checkAlbumFullyDownloaded || albums.length === 0) return;
await Promise.all(albums.map(album => loadAlbumDownloadStatus(album.id)));
const BATCH_SIZE = 6;
for (let i = 0; i < albums.length; i += BATCH_SIZE) {
const batch = albums.slice(i, i + BATCH_SIZE);
await Promise.all(batch.map(album => loadAlbumDownloadStatus(album.id)));
}
} }
function isAlbumDownloaded(albumId: string): boolean { function isAlbumDownloaded(albumId: string): boolean {
@@ -245,6 +305,8 @@
|| continueTracks.length > 0 || continueTracks.length > 0
|| topArtists.length > 0 || topArtists.length > 0
|| favoriteAlbums.length > 0 || favoriteAlbums.length > 0
|| qobuzPlaylists.length > 0
|| essentialDiscography.length > 0
); );
// Mark a section as finished loading and check if we can hide overlay // Mark a section as finished loading and check if we can hide overlay
@@ -261,6 +323,17 @@
isOverlayVisible = false; isOverlayVisible = false;
isInitializing = false; isInitializing = false;
}, 150); }, 150);
// Enable deferred sections after a short delay using requestIdleCallback
if ('requestIdleCallback' in window) {
requestIdleCallback(() => {
deferredSectionsReady = true;
}, { timeout: 500 });
} else {
setTimeout(() => {
deferredSectionsReady = true;
}, 300);
}
} }
} }
@@ -288,40 +361,106 @@
async function fetchAlbums(ids: string[]): Promise<AlbumCardData[]> { async function fetchAlbums(ids: string[]): Promise<AlbumCardData[]> {
if (ids.length === 0) return []; if (ids.length === 0) return [];
const results = await Promise.allSettled(
ids.map(albumId => invoke<QobuzAlbum>('get_album', { albumId })) const BATCH_SIZE = 6;
); const albums: AlbumCardData[] = [];
// Separate cached vs uncached
const uncachedIds: string[] = [];
for (const id of ids) {
const cached = getCachedAlbum(id);
if (cached) {
albums.push(toAlbumCard(cached));
} else {
uncachedIds.push(id);
}
}
// Fetch uncached in batches
for (let i = 0; i < uncachedIds.length; i += BATCH_SIZE) {
const batch = uncachedIds.slice(i, i + BATCH_SIZE);
const results = await Promise.allSettled(
batch.map(albumId => invoke<QobuzAlbum>('get_album', { albumId }))
);
for (const result of results) {
if (result.status === 'fulfilled') {
setCachedAlbum(result.value);
albums.push(toAlbumCard(result.value));
}
}
}
return results.flatMap(result => { return albums;
if (result.status !== 'fulfilled') return [];
return [toAlbumCard(result.value)];
});
} }
async function fetchTracks(ids: number[]): Promise<DisplayTrack[]> { async function fetchTracks(ids: number[]): Promise<DisplayTrack[]> {
if (ids.length === 0) return []; if (ids.length === 0) return [];
const results = await Promise.allSettled(
ids.map(trackId => invoke<QobuzTrack>('get_track', { trackId })) const BATCH_SIZE = 6;
); const tracks: DisplayTrack[] = [];
// Separate cached vs uncached
const uncachedIds: number[] = [];
for (const id of ids) {
const cached = getCachedTrack(id);
if (cached) {
tracks.push(toDisplayTrack(cached));
} else {
uncachedIds.push(id);
}
}
// Fetch uncached in batches
for (let i = 0; i < uncachedIds.length; i += BATCH_SIZE) {
const batch = uncachedIds.slice(i, i + BATCH_SIZE);
const results = await Promise.allSettled(
batch.map(trackId => invoke<QobuzTrack>('get_track', { trackId }))
);
for (const result of results) {
if (result.status === 'fulfilled') {
setCachedTrack(result.value);
tracks.push(toDisplayTrack(result.value));
}
}
}
return results.flatMap(result => { return tracks;
if (result.status !== 'fulfilled') return [];
return [toDisplayTrack(result.value)];
});
} }
// Fetch artists with limited concurrency and session cache
async function fetchArtists(seeds: TopArtistSeed[]): Promise<ArtistCardData[]> { async function fetchArtists(seeds: TopArtistSeed[]): Promise<ArtistCardData[]> {
if (seeds.length === 0) return []; if (seeds.length === 0) return [];
const results = await Promise.allSettled(
seeds.map(seed => invoke<QobuzArtist>('get_artist', { artistId: seed.artistId })) const BATCH_SIZE = 6; // Fetch 6 artists at a time (min visible at HD resolution)
);
const artists: ArtistCardData[] = []; const artists: ArtistCardData[] = [];
results.forEach((result, index) => {
if (result.status !== 'fulfilled') return; // Separate cached vs uncached
const seed = seeds[index]; const uncachedSeeds: TopArtistSeed[] = [];
artists.push(toArtistCard(result.value, seed.playCount)); for (const seed of seeds) {
}); const cached = getCachedArtist(seed.artistId);
if (cached) {
artists.push(toArtistCard(cached, seed.playCount));
} else {
uncachedSeeds.push(seed);
}
}
// Fetch uncached in batches (using basic endpoint - no albums, much faster)
for (let i = 0; i < uncachedSeeds.length; i += BATCH_SIZE) {
const batch = uncachedSeeds.slice(i, i + BATCH_SIZE);
const results = await Promise.allSettled(
batch.map(seed => invoke<QobuzArtist>('get_artist_basic', { artistId: seed.artistId }))
);
results.forEach((result, index) => {
if (result.status !== 'fulfilled') return;
const seed = batch[index];
setCachedArtist(result.value);
artists.push(toArtistCard(result.value, seed.playCount));
});
}
return artists; return artists;
} }
@@ -493,6 +632,76 @@
); );
} }
// Handle tag selection - fetch playlists with the new tag filter
async function handleTagChange(slug: string | null) {
selectedTagSlug = slug;
loadingQobuzPlaylists = true;
try {
console.log('[Home] Fetching playlists with tag:', slug);
const response = await invoke<DiscoverPlaylistsResponse>('get_discover_playlists', {
tag: slug,
limit: LIMITS.qobuzPlaylists,
offset: 0
});
console.log('[Home] Response:', response);
console.log('[Home] Playlists count:', response.items?.length);
if (response.items) {
qobuzPlaylists = response.items;
} else {
console.warn('[Home] No playlists in response:', response);
}
} catch (err) {
console.error('Failed to fetch playlists by tag:', err);
} finally {
loadingQobuzPlaylists = false;
}
}
async function fetchDiscoverData() {
try {
const response = await invoke<DiscoverResponse>('get_discover_index', { genreIds: null });
// Extract playlists (limited) - initial load without tag filter
if (response.containers.playlists?.data?.items) {
qobuzPlaylists = response.containers.playlists.data.items.slice(0, LIMITS.qobuzPlaylists);
}
// Extract playlist tags
if (response.containers.playlists_tags?.data?.items) {
playlistTags = response.containers.playlists_tags.data.items;
}
// Extract essential discography (limited)
if (response.containers.ideal_discography?.data?.items) {
essentialDiscography = response.containers.ideal_discography.data.items.slice(0, LIMITS.essentialDiscography);
}
loadingQobuzPlaylists = false;
loadingEssentialDiscography = false;
if (isSectionVisible('qobuzPlaylists')) {
markSectionFinished();
}
if (isSectionVisible('essentialDiscography')) {
markSectionFinished();
}
} catch (err) {
console.error('Failed to fetch discover data:', err);
loadingQobuzPlaylists = false;
loadingEssentialDiscography = false;
// Still mark sections as finished even on error
if (isSectionVisible('qobuzPlaylists')) {
markSectionFinished();
}
if (isSectionVisible('essentialDiscography')) {
markSectionFinished();
}
}
}
async function loadHome() { async function loadHome() {
isInitializing = true; isInitializing = true;
isOverlayVisible = true; isOverlayVisible = true;
@@ -507,6 +716,8 @@
loadingContinueTracks = true; loadingContinueTracks = true;
loadingTopArtists = true; loadingTopArtists = true;
loadingFavoriteAlbums = true; loadingFavoriteAlbums = true;
loadingQobuzPlaylists = true;
loadingEssentialDiscography = true;
// Count total visible sections to know when we're done // Count total visible sections to know when we're done
totalVisibleSections = 0; totalVisibleSections = 0;
@@ -519,6 +730,8 @@
if (isSectionVisible('continueTracks')) totalVisibleSections++; if (isSectionVisible('continueTracks')) totalVisibleSections++;
if (isSectionVisible('topArtists')) totalVisibleSections++; if (isSectionVisible('topArtists')) totalVisibleSections++;
if (isSectionVisible('favoriteAlbums')) totalVisibleSections++; if (isSectionVisible('favoriteAlbums')) totalVisibleSections++;
if (isSectionVisible('qobuzPlaylists')) totalVisibleSections++;
if (isSectionVisible('essentialDiscography')) totalVisibleSections++;
// Start ML data loading FIRST (local SQLite) - this gets the seeds // Start ML data loading FIRST (local SQLite) - this gets the seeds
const mlPromise = invoke<HomeSeeds>('reco_get_home_ml', { const mlPromise = invoke<HomeSeeds>('reco_get_home_ml', {
@@ -587,6 +800,15 @@
loadingEditorPicks = false; loadingEditorPicks = false;
} }
// Fetch Discover data (Qobuz Playlists + Essential Discography)
const needsDiscoverData = isSectionVisible('qobuzPlaylists') || isSectionVisible('essentialDiscography');
if (needsDiscoverData) {
fetchDiscoverData();
} else {
loadingQobuzPlaylists = false;
loadingEssentialDiscography = false;
}
try { try {
// Wait for ML seeds (local data) // Wait for ML seeds (local data)
const seeds = await mlPromise; const seeds = await mlPromise;
@@ -660,6 +882,8 @@
loadingContinueTracks = false; loadingContinueTracks = false;
loadingTopArtists = false; loadingTopArtists = false;
loadingFavoriteAlbums = false; loadingFavoriteAlbums = false;
loadingQobuzPlaylists = false;
loadingEssentialDiscography = false;
} }
} }
</script> </script>
@@ -711,7 +935,7 @@
</div> </div>
{:else if hasContent} {:else if hasContent}
<!-- Render sections in user-defined order --> <!-- Render sections in user-defined order -->
{#each visibleSections as sectionId (sectionId)} {#each renderableSections as sectionId (sectionId)}
{#if sectionId === 'newReleases' && newReleases.length > 0} {#if sectionId === 'newReleases' && newReleases.length > 0}
<HorizontalScrollRow title={$t('home.newReleases')}> <HorizontalScrollRow title={$t('home.newReleases')}>
{#snippet children()} {#snippet children()}
@@ -872,6 +1096,83 @@
</HorizontalScrollRow> </HorizontalScrollRow>
{/if} {/if}
{#if sectionId === 'qobuzPlaylists' && qobuzPlaylists.length > 0}
<HorizontalScrollRow>
{#snippet header()}
<h2 class="section-title">{$t('home.qobuzPlaylists')}</h2>
{#if playlistTags.length > 0}
<PlaylistTagFilter
tags={playlistTags}
selectedTag={selectedTagSlug}
onTagChange={handleTagChange}
/>
{/if}
{/snippet}
{#snippet children()}
{#if loadingQobuzPlaylists}
<div class="loading-playlists">
<Loader2 size={24} class="spinner" />
</div>
{:else}
{#each qobuzPlaylists as playlist (playlist.id)}
<QobuzPlaylistCard
playlistId={playlist.id}
name={playlist.name}
owner={playlist.owner?.name || 'Qobuz'}
image={playlist.image?.rectangle || playlist.image?.covers?.[0]}
trackCount={playlist.tracks_count}
duration={playlist.duration}
genre={playlist.genres?.[0]?.name}
onclick={onPlaylistClick ? () => onPlaylistClick(playlist.id) : undefined}
onPlay={onPlaylistPlay ? () => onPlaylistPlay(playlist.id) : undefined}
onPlayNext={onPlaylistPlayNext ? () => onPlaylistPlayNext(playlist.id) : undefined}
onPlayLater={onPlaylistPlayLater ? () => onPlaylistPlayLater(playlist.id) : undefined}
onCopyToLibrary={onPlaylistCopyToLibrary ? () => onPlaylistCopyToLibrary(playlist.id) : undefined}
onShareQobuz={onPlaylistShareQobuz ? () => onPlaylistShareQobuz(playlist.id) : undefined}
/>
{/each}
{/if}
<div class="spacer"></div>
{/snippet}
</HorizontalScrollRow>
{/if}
{#if sectionId === 'essentialDiscography' && essentialDiscography.length > 0}
<HorizontalScrollRow title={$t('home.essentialDiscography')}>
{#snippet children()}
{#each essentialDiscography as album (album.id)}
<AlbumCard
albumId={album.id}
artwork={album.image?.large || album.image?.small || ''}
title={album.title}
artist={album.artists?.[0]?.name || 'Unknown Artist'}
genre={album.genre?.name || ''}
releaseDate={album.dates?.original}
size="large"
quality={formatQuality(
(album.audio_info?.maximum_bit_depth ?? 16) > 16,
album.audio_info?.maximum_bit_depth,
album.audio_info?.maximum_sampling_rate
)}
onPlay={onAlbumPlay ? () => onAlbumPlay(album.id) : undefined}
onPlayNext={onAlbumPlayNext ? () => onAlbumPlayNext(album.id) : undefined}
onPlayLater={onAlbumPlayLater ? () => onAlbumPlayLater(album.id) : undefined}
onAddAlbumToPlaylist={onAddAlbumToPlaylist ? () => onAddAlbumToPlaylist(album.id) : undefined}
onShareQobuz={onAlbumShareQobuz ? () => onAlbumShareQobuz(album.id) : undefined}
onShareSonglink={onAlbumShareSonglink ? () => onAlbumShareSonglink(album.id) : undefined}
onDownload={onAlbumDownload ? () => onAlbumDownload(album.id) : undefined}
isAlbumFullyDownloaded={isAlbumDownloaded(album.id)}
onOpenContainingFolder={onOpenAlbumFolder ? () => onOpenAlbumFolder(album.id) : undefined}
onReDownloadAlbum={onReDownloadAlbum ? () => onReDownloadAlbum(album.id) : undefined}
{downloadStateVersion}
onclick={() => { onAlbumClick?.(album.id); loadAlbumDownloadStatus(album.id); }}
/>
{/each}
<div class="spacer"></div>
{/snippet}
</HorizontalScrollRow>
{/if}
{#if sectionId === 'recentAlbums' && recentAlbums.length > 0} {#if sectionId === 'recentAlbums' && recentAlbums.length > 0}
<HorizontalScrollRow title={$t('home.recentlyPlayed')}> <HorizontalScrollRow title={$t('home.recentlyPlayed')}>
{#snippet children()} {#snippet children()}
@@ -964,18 +1265,21 @@
{#snippet children()} {#snippet children()}
{#each topArtists as artist} {#each topArtists as artist}
<button class="artist-card" onclick={() => onArtistClick?.(artist.id)}> <button class="artist-card" onclick={() => onArtistClick?.(artist.id)}>
{#if failedArtistImages.has(artist.id) || !artist.image} <div class="artist-image-wrapper">
<div class="artist-image-placeholder"> <div class="artist-image-placeholder">
<User size={32} /> <User size={48} />
</div> </div>
{:else} {#if !failedArtistImages.has(artist.id) && artist.image}
<img <img
src={artist.image} src={artist.image}
alt={artist.name} alt={artist.name}
class="artist-image" class="artist-image"
onerror={() => handleArtistImageError(artist.id)} loading="lazy"
/> decoding="async"
{/if} onerror={() => handleArtistImageError(artist.id)}
/>
{/if}
</div>
<div class="artist-name">{artist.name}</div> <div class="artist-name">{artist.name}</div>
{#if artist.playCount} {#if artist.playCount}
<div class="artist-meta">{$t('home.artistPlays', { values: { count: artist.playCount } })}</div> <div class="artist-meta">{$t('home.artistPlays', { values: { count: artist.playCount } })}</div>
@@ -1048,6 +1352,16 @@
position: relative; position: relative;
} }
/* Add spacing between sections - using :global to affect child components */
.home-view > :global(*:not(:first-child)) {
margin-top: 60px !important;
}
/* Second child (first section after header) gets less spacing */
.home-view > :global(*:nth-child(2)) {
margin-top: 30px !important;
}
/* Custom scrollbar */ /* Custom scrollbar */
.home-view::-webkit-scrollbar { .home-view::-webkit-scrollbar {
width: 6px; width: 6px;
@@ -1190,6 +1504,26 @@
color: var(--text-primary); color: var(--text-primary);
} }
.section-title {
font-size: 22px;
font-weight: 600;
color: var(--text-primary);
margin: 0;
}
.loading-playlists {
display: flex;
align-items: center;
justify-content: center;
min-width: 180px;
min-height: 180px;
color: var(--text-muted);
}
.loading-playlists :global(.spinner) {
animation: spin 1s linear infinite;
}
.track-list { .track-list {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -1206,11 +1540,11 @@
} }
.artist-card { .artist-card {
width: 160px; width: 180px;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
gap: 8px; gap: 10px;
background: var(--bg-secondary); background: var(--bg-secondary);
border: 1px solid var(--bg-tertiary); border: 1px solid var(--bg-tertiary);
border-radius: 12px; border-radius: 12px;
@@ -1225,15 +1559,26 @@
background-color: var(--bg-hover); background-color: var(--bg-hover);
} }
.artist-image-wrapper {
position: relative;
width: 140px;
height: 140px;
border-radius: 50%;
overflow: hidden;
}
.artist-image, .artist-image,
.artist-image-placeholder { .artist-image-placeholder {
width: 96px; width: 140px;
height: 96px; height: 140px;
border-radius: 50%; border-radius: 50%;
} }
.artist-image { .artist-image {
position: absolute;
inset: 0;
object-fit: cover; object-fit: cover;
z-index: 1;
} }
.artist-image-placeholder { .artist-image-placeholder {
+8 -2
View File
@@ -38,6 +38,9 @@
"popularAlbums": "Popular Albums", "popularAlbums": "Popular Albums",
"qobuzissimes": "Qobuzissimes", "qobuzissimes": "Qobuzissimes",
"editorPicks": "Editor's Picks", "editorPicks": "Editor's Picks",
"qobuzPlaylists": "Qobuz Playlists",
"essentialDiscography": "Essential Discography",
"allTags": "All",
"continueListening": "Continue Listening", "continueListening": "Continue Listening",
"yourTopArtists": "Your Top Artists", "yourTopArtists": "Your Top Artists",
"artistPlays": "{count} plays", "artistPlays": "{count} plays",
@@ -265,7 +268,8 @@
"makePublic": "Make playlist public", "makePublic": "Make playlist public",
"hideFromSidebar": "Hide from sidebar", "hideFromSidebar": "Hide from sidebar",
"createAndAdd": "Create & Add", "createAndAdd": "Create & Add",
"playlistWithTracks": "{name} ({count} tracks)" "playlistWithTracks": "{name} ({count} tracks)",
"copyToLibrary": "Copy to library"
}, },
"sort": { "sort": {
"nameAZ": "Name (A-Z)", "nameAZ": "Name (A-Z)",
@@ -458,7 +462,9 @@
"loading": "Loading...", "loading": "Loading...",
"loadMore": "Load More", "loadMore": "Load More",
"collapse": "Collapse sidebar", "collapse": "Collapse sidebar",
"expand": "Expand sidebar" "expand": "Expand sidebar",
"moreOptions": "More options",
"shareQobuz": "Share (Qobuz)"
}, },
"settings": { "settings": {
"title": "Settings", "title": "Settings",
+8 -2
View File
@@ -38,6 +38,9 @@
"popularAlbums": "Álbumes Populares", "popularAlbums": "Álbumes Populares",
"qobuzissimes": "Qobuzissimes", "qobuzissimes": "Qobuzissimes",
"editorPicks": "Selección del Editor", "editorPicks": "Selección del Editor",
"qobuzPlaylists": "Playlists de Qobuz",
"essentialDiscography": "Discografía Esencial",
"allTags": "Todo",
"continueListening": "Continuar Escuchando", "continueListening": "Continuar Escuchando",
"yourTopArtists": "Tus Artistas Favoritos", "yourTopArtists": "Tus Artistas Favoritos",
"artistPlays": "{count} reproducciones", "artistPlays": "{count} reproducciones",
@@ -265,7 +268,8 @@
"makePublic": "Hacer lista pública", "makePublic": "Hacer lista pública",
"hideFromSidebar": "Ocultar de la barra lateral", "hideFromSidebar": "Ocultar de la barra lateral",
"createAndAdd": "Crear y Agregar", "createAndAdd": "Crear y Agregar",
"playlistWithTracks": "{name} ({count} pistas)" "playlistWithTracks": "{name} ({count} pistas)",
"copyToLibrary": "Copiar a mi biblioteca"
}, },
"sort": { "sort": {
"nameAZ": "Nombre (A-Z)", "nameAZ": "Nombre (A-Z)",
@@ -458,7 +462,9 @@
"loading": "Cargando...", "loading": "Cargando...",
"loadMore": "Cargar Más", "loadMore": "Cargar Más",
"collapse": "Contraer barra lateral", "collapse": "Contraer barra lateral",
"expand": "Expandir barra lateral" "expand": "Expandir barra lateral",
"moreOptions": "Más opciones",
"shareQobuz": "Compartir (Qobuz)"
}, },
"settings": { "settings": {
"title": "Ajustes", "title": "Ajustes",
+4
View File
@@ -12,6 +12,8 @@ export type HomeSectionId =
| 'mostStreamed' | 'mostStreamed'
| 'qobuzissimes' | 'qobuzissimes'
| 'editorPicks' | 'editorPicks'
| 'qobuzPlaylists'
| 'essentialDiscography'
| 'recentAlbums' | 'recentAlbums'
| 'continueTracks' | 'continueTracks'
| 'topArtists' | 'topArtists'
@@ -50,6 +52,8 @@ const DEFAULT_SECTIONS: HomeSection[] = [
{ id: 'mostStreamed', label: 'Popular Albums', visible: false, source: 'qobuz' }, { id: 'mostStreamed', label: 'Popular Albums', visible: false, source: 'qobuz' },
{ id: 'qobuzissimes', label: 'Qobuzissimes', visible: false, source: 'qobuz' }, { id: 'qobuzissimes', label: 'Qobuzissimes', visible: false, source: 'qobuz' },
{ id: 'editorPicks', label: "Editor's Picks", visible: false, source: 'qobuz' }, { id: 'editorPicks', label: "Editor's Picks", visible: false, source: 'qobuz' },
{ id: 'qobuzPlaylists', label: 'Qobuz Playlists', visible: true, source: 'qobuz' },
{ id: 'essentialDiscography', label: 'Essential Discography', visible: true, source: 'qobuz' },
{ id: 'recentAlbums', label: 'Recently Played', visible: true, source: 'ml' }, { id: 'recentAlbums', label: 'Recently Played', visible: true, source: 'ml' },
{ id: 'continueTracks', label: 'Continue Listening', visible: true, source: 'ml' }, { id: 'continueTracks', label: 'Continue Listening', visible: true, source: 'ml' },
{ id: 'topArtists', label: 'Your Top Artists', visible: true, source: 'ml' }, { id: 'topArtists', label: 'Your Top Artists', visible: true, source: 'ml' },
+56
View File
@@ -0,0 +1,56 @@
/**
* In-memory session cache for API responses.
* Data is cached for the lifetime of the app session (cleared on app close).
* This avoids repeated API calls for the same data during a session.
*/
import type { QobuzArtist, QobuzAlbum, QobuzTrack } from '$lib/types';
// Artist cache by ID
const artistCache = new Map<number, QobuzArtist>();
// Album cache by ID
const albumCache = new Map<string, QobuzAlbum>();
// Track cache by ID
const trackCache = new Map<number, QobuzTrack>();
export function getCachedArtist(artistId: number): QobuzArtist | undefined {
return artistCache.get(artistId);
}
export function setCachedArtist(artist: QobuzArtist): void {
artistCache.set(artist.id, artist);
}
export function getCachedAlbum(albumId: string): QobuzAlbum | undefined {
return albumCache.get(albumId);
}
export function setCachedAlbum(album: QobuzAlbum): void {
albumCache.set(album.id, album);
}
export function getCachedTrack(trackId: number): QobuzTrack | undefined {
return trackCache.get(trackId);
}
export function setCachedTrack(track: QobuzTrack): void {
trackCache.set(track.id, track);
}
// Clear all caches (useful for logout or refresh)
export function clearSessionCache(): void {
artistCache.clear();
albumCache.clear();
trackCache.clear();
}
// Get cache stats (for debugging)
export function getCacheStats(): { artists: number; albums: number; tracks: number } {
return {
artists: artistCache.size,
albums: albumCache.size,
tracks: trackCache.size
};
}
+92
View File
@@ -389,3 +389,95 @@ export interface FavoritesPreferences {
icon_background: string | null; icon_background: string | null;
tab_order: string[]; tab_order: string[];
} }
// ============ Discover API Types ============
export interface DiscoverResponse {
containers: DiscoverContainers;
}
export interface DiscoverContainers {
playlists?: DiscoverContainer<DiscoverPlaylist>;
ideal_discography?: DiscoverContainer<DiscoverAlbum>;
playlists_tags?: DiscoverContainer<PlaylistTag>;
new_releases?: DiscoverContainer<DiscoverAlbum>;
}
export interface DiscoverContainer<T> {
id: string;
data: DiscoverData<T>;
}
export interface DiscoverData<T> {
has_more: boolean;
items: T[];
}
export interface DiscoverPlaylist {
id: number;
name: string;
owner: { id: number; name: string };
image: DiscoverPlaylistImage;
description?: string;
duration: number;
tracks_count: number;
genres?: { id: number; name: string; path: number[] }[];
tags?: PlaylistTag[];
}
export interface DiscoverPlaylistImage {
rectangle?: string;
covers?: string[];
}
export interface PlaylistTag {
id: number;
slug: string;
name: string;
}
// Response from discover/playlists endpoint
// Note: This endpoint returns items directly at root level (not wrapped in "playlists")
export interface DiscoverPlaylistsResponse {
has_more: boolean;
items: DiscoverPlaylist[];
}
export interface DiscoverAlbum {
id: string;
title: string;
version?: string;
track_count?: number;
duration?: number;
parental_warning?: boolean;
image: DiscoverAlbumImage;
artists: DiscoverArtist[];
label?: { id: number; name: string };
genre?: { name: string };
dates?: DiscoverAlbumDates;
audio_info?: DiscoverAudioInfo;
}
export interface DiscoverAlbumImage {
small?: string;
thumbnail?: string;
large?: string;
}
export interface DiscoverArtist {
id: number;
name: string;
roles?: string[];
}
export interface DiscoverAlbumDates {
download?: string;
original?: string;
stream?: string;
}
export interface DiscoverAudioInfo {
maximum_sampling_rate?: number;
maximum_bit_depth?: number;
maximum_channel_count?: number;
}
+6
View File
@@ -2935,6 +2935,12 @@
onTrackRemoveDownload={handleTrackRemoveDownload} onTrackRemoveDownload={handleTrackRemoveDownload}
checkTrackDownloaded={checkTrackDownloaded} checkTrackDownloaded={checkTrackDownloaded}
getTrackOfflineCacheStatus={getTrackOfflineCacheStatus} getTrackOfflineCacheStatus={getTrackOfflineCacheStatus}
onPlaylistClick={selectPlaylist}
onPlaylistPlay={playPlaylistById}
onPlaylistPlayNext={queuePlaylistNextById}
onPlaylistPlayLater={queuePlaylistLaterById}
onPlaylistCopyToLibrary={copyPlaylistToLibraryById}
onPlaylistShareQobuz={sharePlaylistQobuzLinkById}
activeTrackId={currentTrack?.id ?? null} activeTrackId={currentTrack?.id ?? null}
isPlaybackActive={isPlaying} isPlaybackActive={isPlaying}
sidebarExpanded={sidebarExpanded} sidebarExpanded={sidebarExpanded}