Merge feature/ux-improvements-180226: UX improvements and playback context

Major UX improvements:
- Playback context tracking from albums/playlists/artists/favorites/home/search
- Stack icon showing context origin with clickable navigation
- Autoplay behavior setting with persistence
- Context menu actions (Play track only, Play from here)
- Track row pause on hover across all views
- Volume indicators while dragging (all 4 players)
- Favorites customization (custom icon, background, sticky nav, search)
- Theme expansion (Nord, Dracula, Tokyo Night, Catppuccin, Rosé Pine, Breeze, Adwaita)
- Layout fix: NowPlayingBar moved outside app-body flex row

Database migrations (safe for existing users 1.1.5+):
- playback_preferences table (autoplay + show_context_icon)
- favorites_preferences table (custom_icon_path, preset, icon_background, tab_order)
- Favorites icon now stored in cache dir with auto-migration

Audio backend: ✅ UNTOUCHED (bit-perfect playback preserved)

Known gaps (to fix in next branch):
- Track focus on context navigation not implemented
- Volume indicator in FocusMode/MiniPlayer not confirmed tested

# Conflicts:
#	src/lib/components/AlbumCard.svelte
This commit is contained in:
vicrodh committed 2026-01-19 15:04:12 -06:00
commit e2afc25175
36 files changed
+4091 -411

No files matched your search

+2
View File
@@ -10,6 +10,7 @@ pub mod favorites;
pub mod lastfm; pub mod lastfm;
pub mod notification; pub mod notification;
pub mod playback; pub mod playback;
pub mod playback_context;
pub mod playlist; pub mod playlist;
pub mod playlist_import; pub mod playlist_import;
pub mod queue; pub mod queue;
@@ -24,6 +25,7 @@ pub use favorites::*;
pub use lastfm::*; pub use lastfm::*;
pub use notification::*; pub use notification::*;
pub use playback::*; pub use playback::*;
pub use playback_context::*;
pub use playlist::*; pub use playlist::*;
pub use playlist_import::*; pub use playlist_import::*;
pub use queue::*; pub use queue::*;
@@ -0,0 +1,64 @@
//! Playback context commands
use tauri::State;
use crate::playback_context::{PlaybackContext, ContextType, ContentSource};
use crate::AppState;
/// Get the current playback context
#[tauri::command]
pub fn get_playback_context(state: State<'_, AppState>) -> Option<PlaybackContext> {
state.context.get_context()
}
/// Set a new playback context
#[tauri::command]
pub fn set_playback_context(
context_type: String,
id: String,
label: String,
source: String,
track_ids: Vec<u64>,
start_position: usize,
state: State<'_, AppState>,
) -> Result<(), String> {
// Parse context type
let ctx_type = match context_type.as_str() {
"album" => ContextType::Album,
"playlist" => ContextType::Playlist,
"artist_top" => ContextType::ArtistTop,
"home_list" => ContextType::HomeList,
"favorites" => ContextType::Favorites,
_ => return Err(format!("Invalid context type: {}", context_type)),
};
// Parse source
let content_source = match source.as_str() {
"qobuz" => ContentSource::Qobuz,
"local" => ContentSource::Local,
_ => return Err(format!("Invalid source: {}", source)),
};
let context = PlaybackContext::new(
ctx_type,
id,
label,
content_source,
track_ids,
start_position,
);
state.context.set_context(context);
Ok(())
}
/// Clear the current playback context
#[tauri::command]
pub fn clear_playback_context(state: State<'_, AppState>) {
state.context.clear_context();
}
/// Check if a playback context is active
#[tauri::command]
pub fn has_playback_context(state: State<'_, AppState>) -> bool {
state.context.has_context()
}
@@ -0,0 +1,315 @@
use rusqlite::{params, Connection, Result};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use chrono::Utc;
use md5::{Md5, Digest};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FavoritesPreferences {
pub custom_icon_path: Option<String>,
pub custom_icon_preset: Option<String>,
pub icon_background: Option<String>,
pub tab_order: Vec<String>,
}
impl Default for FavoritesPreferences {
fn default() -> Self {
Self {
custom_icon_path: None,
custom_icon_preset: Some("heart".to_string()),
icon_background: None,
tab_order: vec![
"tracks".to_string(),
"albums".to_string(),
"artists".to_string(),
"playlists".to_string(),
],
}
}
}
pub struct FavoritesPreferencesStore {
conn: Connection,
}
impl FavoritesPreferencesStore {
pub fn new() -> Result<Self, String> {
let data_dir = dirs::data_dir()
.ok_or("Could not determine data directory")?
.join("qbz");
std::fs::create_dir_all(&data_dir)
.map_err(|e| format!("Failed to create data directory: {}", e))?;
let db_path = data_dir.join("favorites_preferences.db");
let conn = Connection::open(&db_path)
.map_err(|e| format!("Failed to open favorites preferences database: {}", e))?;
conn.execute(
"CREATE TABLE IF NOT EXISTS favorites_preferences (
id INTEGER PRIMARY KEY CHECK (id = 1),
custom_icon_path TEXT,
custom_icon_preset TEXT,
tab_order TEXT NOT NULL
)",
[],
)
.map_err(|e| format!("Failed to create favorites preferences table: {}", e))?;
// Migration: Add icon_background column if it doesn't exist
let has_icon_background = conn
.prepare("SELECT icon_background FROM favorites_preferences LIMIT 1")
.is_ok();
if !has_icon_background {
conn.execute(
"ALTER TABLE favorites_preferences ADD COLUMN icon_background TEXT",
[],
)
.map_err(|e| format!("Failed to add icon_background column: {}", e))?;
}
Ok(Self { conn })
}
fn favorites_icon_dir() -> Result<PathBuf, String> {
let cache_dir = dirs::cache_dir()
.ok_or("Could not determine cache directory")?
.join("qbz")
.join("favorites");
fs::create_dir_all(&cache_dir)
.map_err(|e| format!("Failed to create favorites icon directory: {}", e))?;
Ok(cache_dir)
}
fn normalize_custom_icon_path(&self, path: String) -> Result<String, String> {
let trimmed = path.trim();
if trimmed.is_empty() {
return Ok(String::new());
}
let source = Path::new(trimmed);
if !source.exists() {
return Err(format!("Source icon does not exist: {}", trimmed));
}
let icon_dir = Self::favorites_icon_dir()?;
if source.starts_with(&icon_dir) {
return Ok(trimmed.to_string());
}
let extension = source
.extension()
.and_then(|e| e.to_str())
.unwrap_or("png");
let mut hasher = Md5::new();
hasher.update(trimmed.as_bytes());
let hash = format!("{:x}", hasher.finalize());
let filename = format!(
"favorites_icon_{}_{}.{}",
hash,
Utc::now().timestamp(),
extension
);
let dest_path = icon_dir.join(filename);
fs::copy(source, &dest_path)
.map_err(|e| format!("Failed to copy favorites icon: {}", e))?;
Ok(dest_path.to_string_lossy().to_string())
}
pub fn get_preferences(&self) -> Result<FavoritesPreferences, String> {
let mut stmt = self.conn.prepare("SELECT custom_icon_path, custom_icon_preset, icon_background, tab_order FROM favorites_preferences WHERE id = 1")
.map_err(|e| format!("Failed to prepare select: {}", e))?;
let result = stmt.query_row([], |row| {
let custom_icon_path: Option<String> = row.get(0)?;
let custom_icon_preset: Option<String> = row.get(1)?;
let icon_background: Option<String> = row.get(2)?;
let tab_order_str: String = row.get(3)?;
let custom_icon_path = custom_icon_path
.and_then(|value| if value.trim().is_empty() { None } else { Some(value) });
let tab_order: Vec<String> = serde_json::from_str(&tab_order_str).unwrap_or_else(|_| {
vec![
"tracks".to_string(),
"albums".to_string(),
"artists".to_string(),
"playlists".to_string(),
]
});
Ok(FavoritesPreferences {
custom_icon_path,
custom_icon_preset,
icon_background,
tab_order,
})
});
match result {
Ok(mut prefs) => {
if let Some(path) = prefs.custom_icon_path.clone() {
match self.normalize_custom_icon_path(path) {
Ok(resolved) => {
let normalized = if resolved.trim().is_empty() {
None
} else {
Some(resolved)
};
if normalized != prefs.custom_icon_path {
prefs.custom_icon_path = normalized;
let _ = self.save_preferences(prefs.clone());
}
}
Err(_) => {
prefs.custom_icon_path = None;
let _ = self.save_preferences(prefs.clone());
}
}
}
Ok(prefs)
}
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(FavoritesPreferences::default()),
Err(e) => Err(format!("Failed to query preferences: {}", e)),
}
}
pub fn save_preferences(&self, mut prefs: FavoritesPreferences) -> Result<FavoritesPreferences, String> {
if let Some(path) = prefs.custom_icon_path.clone() {
let resolved = self.normalize_custom_icon_path(path)?;
if resolved.is_empty() {
prefs.custom_icon_path = None;
} else {
prefs.custom_icon_path = Some(resolved);
}
}
let tab_order_str = serde_json::to_string(&prefs.tab_order)
.map_err(|e| format!("Failed to serialize tab_order: {}", e))?;
self.conn.execute(
"INSERT OR REPLACE INTO favorites_preferences (id, custom_icon_path, custom_icon_preset, icon_background, tab_order)
VALUES (1, ?1, ?2, ?3, ?4)",
params![prefs.custom_icon_path, prefs.custom_icon_preset, prefs.icon_background, tab_order_str],
)
.map_err(|e| format!("Failed to save preferences: {}", e))?;
Ok(prefs)
}
}
pub struct FavoritesPreferencesState {
pub store: Arc<Mutex<FavoritesPreferencesStore>>,
}
impl FavoritesPreferencesState {
pub fn new() -> Result<Self, String> {
let store = FavoritesPreferencesStore::new()?;
Ok(Self {
store: Arc::new(Mutex::new(store)),
})
}
}
#[tauri::command]
pub fn get_favorites_preferences(
state: tauri::State<FavoritesPreferencesState>,
) -> Result<FavoritesPreferences, String> {
let store = state
.store
.lock()
.map_err(|_| "Failed to lock favorites preferences store".to_string())?;
store.get_preferences()
}
#[tauri::command]
pub fn save_favorites_preferences(
prefs: FavoritesPreferences,
state: tauri::State<FavoritesPreferencesState>,
) -> Result<FavoritesPreferences, String> {
let store = state
.store
.lock()
.map_err(|_| "Failed to lock favorites preferences store".to_string())?;
store.save_preferences(prefs)
}
pub fn create_table(conn: &Connection) -> Result<()> {
conn.execute(
"CREATE TABLE IF NOT EXISTS favorites_preferences (
id INTEGER PRIMARY KEY CHECK (id = 1),
custom_icon_path TEXT,
custom_icon_preset TEXT,
tab_order TEXT NOT NULL
)",
[],
)?;
// Migration: Add icon_background column if it doesn't exist
let has_icon_background = conn
.prepare("SELECT icon_background FROM favorites_preferences LIMIT 1")
.is_ok();
if !has_icon_background {
conn.execute(
"ALTER TABLE favorites_preferences ADD COLUMN icon_background TEXT",
[],
)?;
}
Ok(())
}
pub fn load_preferences(conn: &Connection) -> Result<FavoritesPreferences> {
let mut stmt = conn.prepare("SELECT custom_icon_path, custom_icon_preset, icon_background, tab_order FROM favorites_preferences WHERE id = 1")?;
let result = stmt.query_row([], |row| {
let custom_icon_path: Option<String> = row.get(0)?;
let custom_icon_preset: Option<String> = row.get(1)?;
let icon_background: Option<String> = row.get(2)?;
let tab_order_str: String = row.get(3)?;
let custom_icon_path = custom_icon_path
.and_then(|value| if value.trim().is_empty() { None } else { Some(value) });
let tab_order: Vec<String> = serde_json::from_str(&tab_order_str).unwrap_or_else(|_| {
vec![
"tracks".to_string(),
"albums".to_string(),
"artists".to_string(),
"playlists".to_string(),
]
});
Ok(FavoritesPreferences {
custom_icon_path,
custom_icon_preset,
icon_background,
tab_order,
})
});
match result {
Ok(prefs) => Ok(prefs),
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(FavoritesPreferences::default()),
Err(e) => Err(e),
}
}
pub fn save_preferences(conn: &Connection, prefs: &FavoritesPreferences) -> Result<()> {
let tab_order_str = serde_json::to_string(&prefs.tab_order).unwrap();
conn.execute(
"INSERT OR REPLACE INTO favorites_preferences (id, custom_icon_path, custom_icon_preset, icon_background, tab_order)
VALUES (1, ?1, ?2, ?3, ?4)",
params![prefs.custom_icon_path, prefs.custom_icon_preset, prefs.icon_background, tab_order_str],
)?;
Ok(())
}
+18
View File
@@ -4,12 +4,15 @@
//! - User credentials (encrypted) //! - User credentials (encrypted)
//! - Audio preferences //! - Audio preferences
//! - Download preferences //! - Download preferences
//! - Playback preferences
//! - UI preferences //! - UI preferences
//! - Local playlists //! - Local playlists
//! - Cached favorites //! - Cached favorites
pub mod audio_settings; pub mod audio_settings;
pub mod download_settings; pub mod download_settings;
pub mod playback_preferences;
pub mod favorites_preferences;
pub use audio_settings::{ pub use audio_settings::{
AudioSettings, AudioSettings,
@@ -29,3 +32,18 @@ pub use download_settings::{
set_show_downloads_in_library, set_show_downloads_in_library,
validate_download_root, validate_download_root,
}; };
pub use playback_preferences::{
AutoplayMode,
PlaybackPreferences,
PlaybackPreferencesState,
get_playback_preferences,
set_autoplay_mode,
};
pub use favorites_preferences::{
FavoritesPreferences,
FavoritesPreferencesState,
get_favorites_preferences,
save_favorites_preferences,
};
@@ -0,0 +1,208 @@
//! Playback preferences
//!
//! Stores user preferences for playback behavior (autoplay mode, etc.)
use rusqlite::{Connection, params};
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};
use log::info;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AutoplayMode {
/// Continue playing within the source (album, playlist, etc.)
#[serde(rename = "continue")]
ContinueWithinSource,
/// Play only the selected track, then stop
#[serde(rename = "track_only")]
PlayTrackOnly,
}
impl Default for AutoplayMode {
fn default() -> Self {
Self::ContinueWithinSource
}
}
impl AutoplayMode {
fn to_db_value(&self) -> &'static str {
match self {
AutoplayMode::ContinueWithinSource => "continue",
AutoplayMode::PlayTrackOnly => "track_only",
}
}
fn from_db_value(s: &str) -> Self {
match s {
"track_only" => AutoplayMode::PlayTrackOnly,
_ => AutoplayMode::ContinueWithinSource,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlaybackPreferences {
pub autoplay_mode: AutoplayMode,
pub show_context_icon: bool,
}
impl Default for PlaybackPreferences {
fn default() -> Self {
Self {
autoplay_mode: AutoplayMode::ContinueWithinSource,
show_context_icon: true,
}
}
}
pub struct PlaybackPreferencesStore {
conn: Connection,
}
impl PlaybackPreferencesStore {
pub fn new() -> Result<Self, String> {
let data_dir = dirs::data_dir()
.ok_or("Could not determine data directory")?
.join("qbz");
std::fs::create_dir_all(&data_dir)
.map_err(|e| format!("Failed to create data directory: {}", e))?;
let db_path = data_dir.join("playback_preferences.db");
let conn = Connection::open(&db_path)
.map_err(|e| format!("Failed to open playback preferences database: {}", e))?;
// Step 1: Create table with old schema (for new installs) or do nothing if exists
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS playback_preferences (
id INTEGER PRIMARY KEY CHECK (id = 1),
autoplay_mode TEXT NOT NULL DEFAULT 'continue'
);"
).map_err(|e| format!("Failed to create playback preferences table: {}", e))?;
// Step 2: Check if show_context_icon column exists
let column_exists: bool = conn
.query_row(
"SELECT COUNT(*) FROM pragma_table_info('playback_preferences') WHERE name='show_context_icon'",
[],
|row| {
let count: i32 = row.get(0)?;
Ok(count > 0)
}
)
.unwrap_or(false);
info!("[PlaybackPrefs] Column show_context_icon exists: {}", column_exists);
// Step 3: Add column if it doesn't exist (migration for existing users)
if !column_exists {
info!("[PlaybackPrefs] Migrating: adding show_context_icon column");
conn.execute(
"ALTER TABLE playback_preferences ADD COLUMN show_context_icon INTEGER NOT NULL DEFAULT 1",
[]
).map_err(|e| format!("Failed to add show_context_icon column: {}", e))?;
info!("[PlaybackPrefs] Migration successful");
}
// Step 4: Insert default row if it doesn't exist
conn.execute(
"INSERT OR IGNORE INTO playback_preferences (id, autoplay_mode, show_context_icon)
VALUES (1, 'continue', 1)",
[]
).map_err(|e| format!("Failed to insert default preferences: {}", e))?;
Ok(Self { conn })
}
pub fn get_preferences(&self) -> Result<PlaybackPreferences, String> {
self.conn
.query_row(
"SELECT autoplay_mode, show_context_icon FROM playback_preferences WHERE id = 1",
[],
|row| {
let autoplay_str: String = row.get(0)?;
let show_icon: i32 = row.get(1)?;
Ok(PlaybackPreferences {
autoplay_mode: AutoplayMode::from_db_value(&autoplay_str),
show_context_icon: show_icon != 0,
})
},
)
.map_err(|e| format!("Failed to get playback preferences: {}", e))
}
pub fn set_autoplay_mode(&self, mode: AutoplayMode) -> Result<(), String> {
self.conn
.execute(
"UPDATE playback_preferences SET autoplay_mode = ?1 WHERE id = 1",
params![mode.to_db_value()],
)
.map_err(|e| format!("Failed to set autoplay mode: {}", e))?;
Ok(())
}
pub fn set_show_context_icon(&self, show: bool) -> Result<(), String> {
self.conn
.execute(
"UPDATE playback_preferences SET show_context_icon = ?1 WHERE id = 1",
params![if show { 1 } else { 0 }],
)
.map_err(|e| format!("Failed to set show context icon: {}", e))?;
Ok(())
}
}
/// Global state wrapper for thread-safe access
pub struct PlaybackPreferencesState {
store: Arc<Mutex<PlaybackPreferencesStore>>,
}
impl PlaybackPreferencesState {
pub fn new() -> Result<Self, String> {
let store = PlaybackPreferencesStore::new()?;
Ok(Self {
store: Arc::new(Mutex::new(store)),
})
}
pub fn get_preferences(&self) -> Result<PlaybackPreferences, String> {
self.store.lock().unwrap().get_preferences()
}
pub fn set_autoplay_mode(&self, mode: AutoplayMode) -> Result<(), String> {
self.store.lock().unwrap().set_autoplay_mode(mode)
}
pub fn set_show_context_icon(&self, show: bool) -> Result<(), String> {
self.store.lock().unwrap().set_show_context_icon(show)
}
}
// Tauri commands
#[tauri::command]
pub fn get_playback_preferences(
state: tauri::State<PlaybackPreferencesState>,
) -> Result<PlaybackPreferences, String> {
state.get_preferences()
}
#[tauri::command]
pub fn set_autoplay_mode(
mode: String,
state: tauri::State<PlaybackPreferencesState>,
) -> Result<(), String> {
let autoplay_mode = match mode.as_str() {
"continue" => AutoplayMode::ContinueWithinSource,
"track_only" => AutoplayMode::PlayTrackOnly,
_ => return Err(format!("Invalid autoplay mode: {}", mode)),
};
state.set_autoplay_mode(autoplay_mode)
}
#[tauri::command]
pub fn set_show_context_icon(
show: bool,
state: tauri::State<PlaybackPreferencesState>,
) -> Result<(), String> {
state.set_show_context_icon(show)
}
+23
View File
@@ -19,6 +19,7 @@ pub mod lyrics;
pub mod media_controls; pub mod media_controls;
pub mod network; pub mod network;
pub mod offline; pub mod offline;
pub mod playback_context;
pub mod player; pub mod player;
pub mod playlist_import; pub mod playlist_import;
pub mod queue; pub mod queue;
@@ -35,6 +36,7 @@ use api::QobuzClient;
use cache::{AudioCache, PlaybackCache}; use cache::{AudioCache, PlaybackCache};
use lastfm::LastFmClient; use lastfm::LastFmClient;
use media_controls::{MediaControlsManager, TrackInfo}; use media_controls::{MediaControlsManager, TrackInfo};
use playback_context::ContextManager;
use player::Player; use player::Player;
use queue::QueueManager; use queue::QueueManager;
use share::SongLinkClient; use share::SongLinkClient;
@@ -44,6 +46,7 @@ pub struct AppState {
pub client: Arc<Mutex<QobuzClient>>, pub client: Arc<Mutex<QobuzClient>>,
pub player: Player, pub player: Player,
pub queue: QueueManager, pub queue: QueueManager,
pub context: ContextManager,
pub media_controls: MediaControlsManager, pub media_controls: MediaControlsManager,
pub audio_cache: Arc<AudioCache>, pub audio_cache: Arc<AudioCache>,
pub lastfm: Arc<Mutex<LastFmClient>>, pub lastfm: Arc<Mutex<LastFmClient>>,
@@ -83,6 +86,7 @@ impl AppState {
client: Arc::new(Mutex::new(QobuzClient::default())), client: Arc::new(Mutex::new(QobuzClient::default())),
player: Player::new(device_name, audio_settings), player: Player::new(device_name, audio_settings),
queue: QueueManager::new(), queue: QueueManager::new(),
context: ContextManager::new(),
media_controls: MediaControlsManager::new(), media_controls: MediaControlsManager::new(),
audio_cache, audio_cache,
lastfm: Arc::new(Mutex::new(LastFmClient::default())), lastfm: Arc::new(Mutex::new(LastFmClient::default())),
@@ -168,6 +172,12 @@ pub fn run() {
// Initialize offline mode state // Initialize offline mode state
let offline_state = offline::OfflineState::new() let offline_state = offline::OfflineState::new()
.expect("Failed to initialize offline state"); .expect("Failed to initialize offline state");
// Initialize playback preferences state
let playback_prefs_state = config::playback_preferences::PlaybackPreferencesState::new()
.expect("Failed to initialize playback preferences");
// Initialize favorites preferences state
let favorites_prefs_state = config::favorites_preferences::FavoritesPreferencesState::new()
.expect("Failed to initialize favorites preferences");
// Read saved audio device and settings for player initialization // Read saved audio device and settings for player initialization
let (saved_device, audio_settings) = audio_settings_state let (saved_device, audio_settings) = audio_settings_state
@@ -292,6 +302,8 @@ pub fn run() {
.manage(audio_settings_state) .manage(audio_settings_state)
.manage(download_settings_state) .manage(download_settings_state)
.manage(offline_state) .manage(offline_state)
.manage(playback_prefs_state)
.manage(favorites_prefs_state)
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![
// Auth commands // Auth commands
commands::init_client, commands::init_client,
@@ -352,6 +364,11 @@ pub fn run() {
commands::set_repeat, commands::set_repeat,
commands::get_repeat, commands::get_repeat,
commands::get_queue_state, commands::get_queue_state,
// Playback context commands
commands::get_playback_context,
commands::set_playback_context,
commands::clear_playback_context,
commands::has_playback_context,
// Playlist commands // Playlist commands
commands::get_user_playlists, commands::get_user_playlists,
commands::get_playlist, commands::get_playlist,
@@ -561,6 +578,12 @@ pub fn run() {
offline::commands::set_manual_offline, offline::commands::set_manual_offline,
offline::commands::set_show_partial_playlists, offline::commands::set_show_partial_playlists,
offline::commands::set_allow_cast_while_offline, offline::commands::set_allow_cast_while_offline,
// Playback preferences commands
config::playback_preferences::get_playback_preferences,
config::playback_preferences::set_autoplay_mode,
config::playback_preferences::set_show_context_icon,
config::favorites_preferences::get_favorites_preferences,
config::favorites_preferences::save_favorites_preferences,
offline::commands::set_allow_immediate_scrobbling, offline::commands::set_allow_immediate_scrobbling,
offline::commands::set_allow_accumulated_scrobbling, offline::commands::set_allow_accumulated_scrobbling,
offline::commands::set_show_network_folders_in_manual_offline, offline::commands::set_show_network_folders_in_manual_offline,
+213
View File
@@ -0,0 +1,213 @@
//! Playback context module
//!
//! Manages the semantic origin of playback to determine what "next" means.
//! A playback context is NOT the queue - it's the source that defines
//! the boundaries and continuation behavior for playback.
//!
//! Examples:
//! - Album: next track in the album
//! - Playlist: next track in the playlist
//! - Artist Top Songs: next ranked track
//! - Single track: no context, playback ends when track finishes
use std::sync::Mutex;
use serde::{Deserialize, Serialize};
/// Type of playback context
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContextType {
Album,
Playlist,
ArtistTop,
HomeList,
Favorites,
}
/// Source of the content (Qobuz or Local Library)
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ContentSource {
Qobuz,
Local,
}
/// Playback context - the semantic origin of playback
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlaybackContext {
/// Type of context (album, playlist, etc.)
#[serde(rename = "type")]
pub context_type: ContextType,
/// Unique identifier for this context
pub id: String,
/// Human-readable label
pub label: String,
/// Source of content
pub source: ContentSource,
/// Original track list for this context (track IDs)
pub track_ids: Vec<u64>,
/// Current position in the context
pub current_position: usize,
}
impl PlaybackContext {
/// Create a new playback context
pub fn new(
context_type: ContextType,
id: String,
label: String,
source: ContentSource,
track_ids: Vec<u64>,
start_position: usize,
) -> Self {
Self {
context_type,
id,
label,
source,
track_ids,
current_position: start_position,
}
}
/// Get the next track ID in this context (if any)
pub fn next_track_id(&self) -> Option<u64> {
let next_pos = self.current_position + 1;
if next_pos < self.track_ids.len() {
self.track_ids.get(next_pos).copied()
} else {
None
}
}
/// Get multiple upcoming track IDs in this context
pub fn upcoming_track_ids(&self, count: usize) -> Vec<u64> {
let start_pos = self.current_position + 1;
self.track_ids
.iter()
.skip(start_pos)
.take(count)
.copied()
.collect()
}
/// Advance to the next track in context
pub fn advance(&mut self) -> bool {
let next_pos = self.current_position + 1;
if next_pos < self.track_ids.len() {
self.current_position = next_pos;
true
} else {
false
}
}
/// Check if context has more tracks
pub fn has_next(&self) -> bool {
self.current_position + 1 < self.track_ids.len()
}
/// Get total tracks in context
pub fn total_tracks(&self) -> usize {
self.track_ids.len()
}
/// Get context info for display
pub fn display_info(&self) -> String {
let type_str = match self.context_type {
ContextType::Album => "Album",
ContextType::Playlist => "Playlist",
ContextType::ArtistTop => "Artist Top Songs",
ContextType::HomeList => "Home List",
ContextType::Favorites => "Favorites",
};
format!("{} · {}", type_str, self.label)
}
}
/// Manager for the current playback context
pub struct ContextManager {
current: Mutex<Option<PlaybackContext>>,
}
impl Default for ContextManager {
fn default() -> Self {
Self::new()
}
}
impl ContextManager {
pub fn new() -> Self {
Self {
current: Mutex::new(None),
}
}
/// Set the current playback context
pub fn set_context(&self, context: PlaybackContext) {
let mut current = self.current.lock().unwrap();
*current = Some(context);
log::info!("Playback context set: {:?}", current.as_ref().map(|c| &c.label));
}
/// Clear the current context (for single track playback)
pub fn clear_context(&self) {
let mut current = self.current.lock().unwrap();
*current = None;
log::info!("Playback context cleared");
}
/// Get the current context (cloned)
pub fn get_context(&self) -> Option<PlaybackContext> {
self.current.lock().unwrap().clone()
}
/// Check if a context is active
pub fn has_context(&self) -> bool {
self.current.lock().unwrap().is_some()
}
/// Get the next track ID from the current context
pub fn next_track_id(&self) -> Option<u64> {
self.current
.lock()
.unwrap()
.as_ref()
.and_then(|ctx| ctx.next_track_id())
}
/// Get multiple upcoming track IDs from the current context
pub fn upcoming_track_ids(&self, count: usize) -> Vec<u64> {
self.current
.lock()
.unwrap()
.as_ref()
.map(|ctx| ctx.upcoming_track_ids(count))
.unwrap_or_default()
}
/// Advance the context to the next track
pub fn advance_context(&self) -> bool {
let mut current = self.current.lock().unwrap();
if let Some(ctx) = current.as_mut() {
let advanced = ctx.advance();
if !advanced {
log::info!("Playback context ended (no more tracks)");
}
advanced
} else {
false
}
}
/// Update current track position in context (when user seeks within context)
pub fn set_position(&self, track_id: u64) {
let mut current = self.current.lock().unwrap();
if let Some(ctx) = current.as_mut() {
if let Some(pos) = ctx.track_ids.iter().position(|&id| id == track_id) {
ctx.current_position = pos;
log::debug!("Context position updated to {}", pos);
}
}
}
}
+243 -28
View File
@@ -19,6 +19,10 @@
--border-subtle: #2a2a2a; --border-subtle: #2a2a2a;
--border-strong: #3a3a3a; --border-strong: #3a3a3a;
/* Layout */
--sidebar-width: 240px;
--now-playing-height: 80px;
/* Spacing System */ /* Spacing System */
--spacing-micro: 4px; --spacing-micro: 4px;
--spacing-tight: 8px; --spacing-tight: 8px;
@@ -33,24 +37,20 @@
--font-mono: 'JetBrains Mono', monospace; --font-mono: 'JetBrains Mono', monospace;
} }
/* Light Theme (Alucard - soft cream tones inspired by Dracula inverted) */ /* Light Theme */
[data-theme="light"] { [data-theme="light"] {
--bg-primary: #F8F8F2; --bg-primary: #ffffff;
--bg-secondary: #EEF0F5; --bg-secondary: #f5f5f5;
--bg-tertiary: #E2E5EB; --bg-tertiary: #e8e8e8;
--bg-hover: #D8DCE5; --bg-hover: #f0f0f0;
--text-primary: #282A36; --text-primary: #0f0f0f;
--text-secondary: #44475A; --text-secondary: #444444;
--text-muted: #6272A4; --text-muted: #666666;
--text-disabled: #9CA3C0; --text-disabled: #999999;
--accent-primary: #8B5CF6; --border-subtle: #e0e0e0;
--accent-hover: #7C3AED; --border-strong: #cccccc;
--accent-active: #6D28D9;
--border-subtle: #D8DCE5;
--border-strong: #C8CCD5;
} }
/* OLED Theme */ /* OLED Theme */
@@ -63,14 +63,194 @@
/* Warm Theme */ /* Warm Theme */
[data-theme="warm"] { [data-theme="warm"] {
--bg-primary: #1a1512; --bg-primary: #1a1814;
--bg-secondary: #231d18; --bg-secondary: #242018;
--bg-tertiary: #2d2520; --bg-tertiary: #2e2820;
--bg-hover: #28211c; --bg-hover: #282218;
--accent-primary: #e89b5a; --accent-primary: #d4a574;
--accent-hover: #f0ab6e; --accent-hover: #e0b888;
--accent-active: #d88b4a; --accent-active: #c49460;
}
/* Nord Theme */
[data-theme="nord"] {
--bg-primary: #2e3440;
--bg-secondary: #3b4252;
--bg-tertiary: #434c5e;
--bg-hover: #4c566a;
--text-primary: #eceff4;
--text-secondary: #e5e9f0;
--text-muted: #d8dee9;
--text-disabled: #4c566a;
--accent-primary: #88c0d0;
--accent-hover: #81a1c1;
--accent-active: #5e81ac;
--border-subtle: #434c5e;
--border-strong: #4c566a;
}
/* Dracula Theme */
[data-theme="dracula"] {
--bg-primary: #282a36;
--bg-secondary: #343746;
--bg-tertiary: #44475a;
--bg-hover: #6272a4;
--text-primary: #f8f8f2;
--text-secondary: #e4e8f2;
--text-muted: #9da5c0;
--text-disabled: #6272a4;
--accent-primary: #bd93f9;
--accent-hover: #ff79c6;
--accent-active: #8be9fd;
--border-subtle: #44475a;
--border-strong: #6272a4;
}
/* Tokyo Night Theme */
[data-theme="tokyo-night"] {
--bg-primary: #1a1b26;
--bg-secondary: #1f2335;
--bg-tertiary: #292e42;
--bg-hover: #414868;
--text-primary: #c0caf5;
--text-secondary: #a9b1d6;
--text-muted: #565f89;
--text-disabled: #414868;
--accent-primary: #7aa2f7;
--accent-hover: #bb9af7;
--accent-active: #2ac3de;
--border-subtle: #292e42;
--border-strong: #414868;
}
/* Catppuccin Mocha Theme */
[data-theme="catppuccin-mocha"] {
--bg-primary: #11111b;
--bg-secondary: #181825;
--bg-tertiary: #1e1e2e;
--bg-hover: #313244;
--text-primary: #cdd6f4;
--text-secondary: #bac2de;
--text-muted: #6c7086;
--text-disabled: #313244;
--accent-primary: #89b4fa;
--accent-hover: #74c7ec;
--accent-active: #b4befe;
--border-subtle: #1e1e2e;
--border-strong: #313244;
}
/* Rose Pine Dawn Theme */
[data-theme="rose-pine-dawn"] {
--bg-primary: #faf4ed;
--bg-secondary: #fffaf3;
--bg-tertiary: #f2e9e1;
--bg-hover: #dfdad9;
--text-primary: #575279;
--text-secondary: #797593;
--text-muted: #9893a5;
--text-disabled: #dfdad9;
--accent-primary: #907aa9;
--accent-hover: #286983;
--accent-active: #d7827e;
--border-subtle: #f2e9e1;
--border-strong: #dfdad9;
}
/* Breeze Dark Theme */
[data-theme="breeze-dark"] {
--bg-primary: #141618;
--bg-secondary: #202326;
--bg-tertiary: #292c30;
--bg-hover: #31363b;
--text-primary: #ffffff;
--text-secondary: #fcfcfc;
--text-muted: #a1a9b1;
--text-disabled: #31363b;
--accent-primary: #3daee9;
--accent-hover: #9b59b6;
--accent-active: #1d99f3;
--border-subtle: #292c30;
--border-strong: #31363b;
}
/* Breeze Light Theme */
[data-theme="breeze-light"] {
--bg-primary: #ffffff;
--bg-secondary: #eff0f1;
--bg-tertiary: #dee0e2;
--bg-hover: #c8cdd3;
--text-primary: #1b1f23;
--text-secondary: #232629;
--text-muted: #5f6a75;
--text-disabled: #c8cdd3;
--accent-primary: #3daee9;
--accent-hover: #9b59b6;
--accent-active: #2980b9;
--border-subtle: #dee0e2;
--border-strong: #c8cdd3;
}
/* Adwaita Dark Theme */
[data-theme="adwaita-dark"] {
--bg-primary: #1d1d20;
--bg-secondary: #222226;
--bg-tertiary: #28282c;
--bg-hover: #2e2e32;
--text-primary: #ffffff;
--text-secondary: #ffffff;
--text-muted: #b3b3b8;
--text-disabled: #2e2e32;
--accent-primary: #3584e4;
--accent-hover: #1c71d8;
--accent-active: #1a5fb4;
--border-subtle: #28282c;
--border-strong: #2e2e32;
}
/* Adwaita Light Theme */
[data-theme="adwaita-light"] {
--bg-primary: #fafafb;
--bg-secondary: #ffffff;
--bg-tertiary: #f3f3f5;
--bg-hover: #deddda;
--text-primary: #241f31;
--text-secondary: #333338;
--text-muted: #5e5c64;
--text-disabled: #deddda;
--accent-primary: #3584e4;
--accent-hover: #1c71d8;
--accent-active: #1a5fb4;
--border-subtle: #f3f3f5;
--border-strong: #deddda;
} }
* { * {
@@ -81,34 +261,69 @@
html { html {
font-size: 16px; font-size: 16px;
height: 100%;
width: 100%;
overflow: hidden;
} }
body { body {
font-family: var(--font-sans); font-family: var(--font-sans);
font-size: 14px;
line-height: 1.5;
background-color: var(--bg-primary); background-color: var(--bg-primary);
color: var(--text-primary); color: var(--text-primary);
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale; -moz-osx-font-smoothing: grayscale;
overflow-x: hidden; overflow: hidden;
} }
/* Scrollbar Styling */ /* Scrollbar Styling */
::-webkit-scrollbar { ::-webkit-scrollbar {
width: 12px; width: 8px;
height: 12px; height: 8px;
} }
::-webkit-scrollbar-track { ::-webkit-scrollbar-track {
background: var(--bg-secondary); background: transparent;
} }
::-webkit-scrollbar-thumb { ::-webkit-scrollbar-thumb {
background: var(--bg-tertiary); background: var(--bg-tertiary);
border-radius: 6px; border-radius: 9999px;
} }
::-webkit-scrollbar-thumb:hover { ::-webkit-scrollbar-thumb:hover {
background: var(--border-strong); background: var(--text-muted);
}
::selection {
background-color: var(--accent-primary);
color: var(--text-primary);
}
:focus-visible {
outline: 2px solid var(--accent-primary);
outline-offset: 2px;
}
button {
background: none;
border: none;
cursor: pointer;
font: inherit;
color: inherit;
}
a {
color: inherit;
text-decoration: none;
}
input,
textarea,
select {
font: inherit;
color: inherit;
} }
/* Hide scrollbar for horizontal scroll containers */ /* Hide scrollbar for horizontal scroll containers */
+59 -2
View File
@@ -2,6 +2,7 @@
import { invoke } from '@tauri-apps/api/core'; import { invoke } from '@tauri-apps/api/core';
import { X, Shuffle, SkipBack, Play, Pause, SkipForward, Repeat, Heart, List, Maximize2, MoreHorizontal, Cast } from 'lucide-svelte'; import { X, Shuffle, SkipBack, Play, Pause, SkipForward, Repeat, Heart, List, Maximize2, MoreHorizontal, Cast } from 'lucide-svelte';
import QualityBadge from './QualityBadge.svelte'; import QualityBadge from './QualityBadge.svelte';
import StackIcon from './StackIcon.svelte';
import LyricsLines from './lyrics/LyricsLines.svelte'; import LyricsLines from './lyrics/LyricsLines.svelte';
import { startActiveLineUpdates } from '$lib/stores/lyricsStore'; import { startActiveLineUpdates } from '$lib/stores/lyricsStore';
@@ -49,6 +50,7 @@
onOpenFocusMode?: () => void; onOpenFocusMode?: () => void;
onCast?: () => void; onCast?: () => void;
isCastConnected?: boolean; isCastConnected?: boolean;
onContextClick?: () => void;
// Lyrics props // Lyrics props
lyricsLines?: LyricsLine[]; lyricsLines?: LyricsLine[];
lyricsActiveIndex?: number; lyricsActiveIndex?: number;
@@ -88,6 +90,7 @@
onOpenFocusMode, onOpenFocusMode,
onCast, onCast,
isCastConnected = false, isCastConnected = false,
onContextClick,
lyricsLines = [], lyricsLines = [],
lyricsActiveIndex = -1, lyricsActiveIndex = -1,
lyricsActiveProgress = 0, lyricsActiveProgress = 0,
@@ -245,8 +248,12 @@
<div class="track-info"> <div class="track-info">
<h1 class="title">{trackTitle}</h1> <h1 class="title">{trackTitle}</h1>
<div class="artist-album-row">
<StackIcon size={16} class="stack-icon" onClick={onContextClick} />
<h2 class="artist">{artist}</h2> <h2 class="artist">{artist}</h2>
<span class="separator">·</span>
<h3 class="album">{album}</h3> <h3 class="album">{album}</h3>
</div>
<div class="quality-info"> <div class="quality-info">
<QualityBadge {quality} {bitDepth} samplingRate={displaySamplingRate} /> <QualityBadge {quality} {bitDepth} samplingRate={displaySamplingRate} />
</div> </div>
@@ -311,6 +318,7 @@
<!-- Volume Control --> <!-- Volume Control -->
<div class="volume-container"> <div class="volume-container">
<div class="volume-value" class:visible={isDraggingVolume}>{volume}</div>
<div <div
class="volume-bar" class="volume-bar"
bind:this={volumeRef} bind:this={volumeRef}
@@ -508,6 +516,17 @@
width: 100%; width: 100%;
} }
.title-row {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 6px;
}
.title-row :global(.stack-icon) {
flex-shrink: 0;
}
.title { .title {
font-size: 22px; font-size: 22px;
font-weight: 600; font-weight: 600;
@@ -518,15 +537,31 @@
white-space: nowrap; white-space: nowrap;
} }
.artist-album-row {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 4px;
}
.artist-album-row :global(.stack-icon) {
flex-shrink: 0;
}
.artist-album-row .separator {
color: rgba(255, 255, 255, 0.5);
margin: 0 2px;
}
.artist { .artist {
font-size: 16px; font-size: 16px;
font-weight: 400; font-weight: 400;
color: rgba(255, 255, 255, 0.7); color: rgba(255, 255, 255, 0.7);
margin: 0 0 4px; margin: 0;
} }
.album { .album {
font-size: 14px; font-size: 16px;
font-weight: 400; font-weight: 400;
color: rgba(255, 255, 255, 0.5); color: rgba(255, 255, 255, 0.5);
margin: 0; margin: 0;
@@ -652,6 +687,7 @@
width: 100%; width: 100%;
max-width: 180px; max-width: 180px;
margin-bottom: 24px; margin-bottom: 24px;
position: relative;
} }
.volume-bar { .volume-bar {
@@ -684,6 +720,27 @@
opacity: 1; opacity: 1;
} }
.volume-value {
position: absolute;
right: 0;
top: -26px;
padding: 4px 8px;
border-radius: 6px;
background: rgba(0, 0, 0, 0.6);
color: rgba(255, 255, 255, 0.9);
font-size: 12px;
font-weight: 600;
opacity: 0;
transform: translateY(4px);
transition: opacity 120ms ease, transform 120ms ease;
pointer-events: none;
}
.volume-value.visible {
opacity: 1;
transform: translateY(0);
}
/* Bottom Actions */ /* Bottom Actions */
.bottom-actions { .bottom-actions {
display: flex; display: flex;
@@ -0,0 +1,701 @@
<script lang="ts">
import { invoke } from '@tauri-apps/api/core';
import { open } from '@tauri-apps/plugin-dialog';
import Modal from './Modal.svelte';
import { Heart, Star, Music, Folder, Disc, Library, Upload, GripVertical } from 'lucide-svelte';
import type { FavoritesPreferences } from '../types';
interface Props {
isOpen: boolean;
onClose: () => void;
onSave: (prefs: FavoritesPreferences) => void;
initialPreferences: FavoritesPreferences;
}
let { isOpen, onClose, onSave, initialPreferences }: Props = $props();
let customIconPath = $state<string | null>(initialPreferences.custom_icon_path || null);
let customIconPreset = $state<string | null>(initialPreferences.custom_icon_preset || 'heart');
let iconBackground = $state<string | null>(initialPreferences.icon_background || null);
let tabOrder = $state<string[]>([...initialPreferences.tab_order]);
let useCustomImage = $state(!!initialPreferences.custom_icon_path);
let saving = $state(false);
const presetIcons = [
{ id: 'heart', label: 'Heart', icon: Heart },
{ id: 'star', label: 'Star', icon: Star },
{ id: 'music', label: 'Music', icon: Music },
{ id: 'folder', label: 'Folder', icon: Folder },
{ id: 'disc', label: 'Disc', icon: Disc },
{ id: 'library', label: 'Library', icon: Library },
];
const solidColors = [
{ id: 'accent', label: 'Accent', value: 'var(--accent-primary)' },
{ id: 'red', label: 'Red', value: '#ef4444' },
{ id: 'orange', label: 'Orange', value: '#f97316' },
{ id: 'amber', label: 'Amber', value: '#f59e0b' },
{ id: 'green', label: 'Green', value: '#10b981' },
{ id: 'cyan', label: 'Cyan', value: '#06b6d4' },
{ id: 'blue', label: 'Blue', value: '#3b82f6' },
{ id: 'purple', label: 'Purple', value: '#a855f7' },
{ id: 'pink', label: 'Pink', value: '#ec4899' },
{ id: 'rose', label: 'Rose', value: '#f43f5e' },
{ id: 'slate', label: 'Slate', value: '#64748b' },
];
const gradients = [
{ id: 'sunset', label: 'Sunset', value: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' },
{ id: 'ocean', label: 'Ocean', value: 'linear-gradient(135deg, #2e3192 0%, #1bffff 100%)' },
{ id: 'fire', label: 'Fire', value: 'linear-gradient(135deg, #ff0844 0%, #ffb199 100%)' },
{ id: 'mint', label: 'Mint', value: 'linear-gradient(135deg, #00b09b 0%, #96c93d 100%)' },
{ id: 'candy', label: 'Candy', value: 'linear-gradient(135deg, #fc6767 0%, #ec008c 100%)' },
{ id: 'forest', label: 'Forest', value: 'linear-gradient(135deg, #134e5e 0%, #71b280 100%)' },
];
let customGradientColors = $state<string[]>(['#667eea', '#764ba2']);
let showCustomGradientPicker = $state(false);
function addGradientColor() {
if (customGradientColors.length < 3) {
customGradientColors = [...customGradientColors, '#888888'];
}
}
function removeGradientColor(index: number) {
if (customGradientColors.length > 2) {
customGradientColors = customGradientColors.filter((_, i) => i !== index);
}
}
function updateGradientColor(index: number, value: string) {
customGradientColors[index] = value;
}
function applyCustomGradient() {
const stops = customGradientColors.map((c, i) => {
const percent = (i / (customGradientColors.length - 1)) * 100;
return `${c} ${percent}%`;
}).join(', ');
iconBackground = `linear-gradient(135deg, ${stops})`;
showCustomGradientPicker = false;
}
const tabLabels: Record<string, string> = {
tracks: 'Tracks',
albums: 'Albums',
artists: 'Artists',
playlists: 'Playlists',
};
function selectPreset(presetId: string) {
customIconPreset = presetId;
useCustomImage = false;
customIconPath = null;
}
function syncFromPreferences() {
customIconPath = initialPreferences.custom_icon_path || null;
customIconPreset = initialPreferences.custom_icon_preset || 'heart';
iconBackground = initialPreferences.icon_background || null;
tabOrder = [...initialPreferences.tab_order];
useCustomImage = !!initialPreferences.custom_icon_path;
}
async function handleUploadClick() {
try {
const selected = await open({
multiple: false,
filters: [{
name: 'Images',
extensions: ['png', 'jpg', 'jpeg', 'webp', 'gif']
}]
});
if (selected && typeof selected === 'string') {
customIconPath = selected;
useCustomImage = true;
customIconPreset = null;
}
} catch (err) {
console.error('Failed to open file picker:', err);
}
}
function moveUp(index: number) {
if (index === 0) return;
const temp = tabOrder[index];
tabOrder[index] = tabOrder[index - 1];
tabOrder[index - 1] = temp;
}
function moveDown(index: number) {
if (index === tabOrder.length - 1) return;
const temp = tabOrder[index];
tabOrder[index] = tabOrder[index + 1];
tabOrder[index + 1] = temp;
}
async function handleSave() {
saving = true;
try {
const prefs: FavoritesPreferences = {
custom_icon_path: useCustomImage ? customIconPath : null,
custom_icon_preset: useCustomImage ? null : customIconPreset,
icon_background: iconBackground,
tab_order: tabOrder,
};
const saved = await invoke<FavoritesPreferences>('save_favorites_preferences', { prefs });
onSave(saved);
onClose();
} catch (err) {
console.error('Failed to save favorites preferences:', err);
} finally {
saving = false;
}
}
function handleCancel() {
syncFromPreferences();
onClose();
}
$effect(() => {
if (isOpen) {
syncFromPreferences();
}
});
</script>
<Modal {isOpen} onClose={handleCancel} title="Favorites Settings" maxWidth="736px">
{#snippet children()}
<div class="modal-columns">
<!-- Left Column: Icon Customization -->
<div class="modal-column">
<div class="modal-section">
<h3>Icon</h3>
<p class="section-description">Choose an icon for the Favorites page header</p>
<div class="icon-grid">
{#each presetIcons as preset}
<button
class="icon-preset-btn"
class:active={!useCustomImage && customIconPreset === preset.id}
onclick={() => selectPreset(preset.id)}
title={preset.label}
>
<svelte:component this={preset.icon} size={24} />
</button>
{/each}
</div>
<div class="custom-upload">
<button class="upload-btn" onclick={handleUploadClick}>
<Upload size={16} />
<span>Upload Custom Image</span>
</button>
{#if useCustomImage && customIconPath}
<span class="upload-filename">{customIconPath.split('/').pop()}</span>
{/if}
</div>
</div>
<div class="modal-section">
<h3>Background</h3>
<p class="section-description">Choose a background color or gradient</p>
<div class="color-section">
<h4>Solid Colors</h4>
<div class="color-grid">
<button
class="color-btn"
class:active={iconBackground === null}
onclick={() => iconBackground = null}
title="None"
>
<div class="color-swatch no-color"></div>
</button>
{#each solidColors as color}
<button
class="color-btn"
class:active={iconBackground === color.value}
onclick={() => iconBackground = color.value}
title={color.label}
>
<div class="color-swatch" style="background: {color.value};"></div>
</button>
{/each}
</div>
</div>
<div class="color-section">
<h4>Gradients</h4>
<div class="color-grid">
{#each gradients as gradient}
<button
class="color-btn"
class:active={iconBackground === gradient.value}
onclick={() => iconBackground = gradient.value}
title={gradient.label}
>
<div class="color-swatch" style="background: {gradient.value};"></div>
</button>
{/each}
</div>
</div>
<div class="color-section">
<h4>Custom Gradient</h4>
{#if !showCustomGradientPicker}
<button class="btn-custom-gradient" onclick={() => showCustomGradientPicker = true}>
Create Custom Gradient
</button>
{:else}
<div class="custom-gradient-editor">
{#each customGradientColors as color, i}
<div class="gradient-color-row">
<input
type="color"
value={color}
oninput={(e) => updateGradientColor(i, e.currentTarget.value)}
class="color-input"
/>
{#if customGradientColors.length > 2}
<button class="btn-remove-color" onclick={() => removeGradientColor(i)} title="Remove">
✕
</button>
{/if}
</div>
{/each}
<div class="gradient-actions">
{#if customGradientColors.length < 3}
<button class="btn-add-color" onclick={addGradientColor}>+ Add Color</button>
{/if}
<button class="btn-apply-gradient" onclick={applyCustomGradient}>Apply</button>
<button class="btn-cancel-gradient" onclick={() => showCustomGradientPicker = false}>Cancel</button>
</div>
</div>
{/if}
</div>
</div>
</div>
<!-- Right Column: Tab Order -->
<div class="modal-column">
<div class="modal-section">
<h3>Tab Order</h3>
<p class="section-description">Reorder tabs in the Favorites page navigation</p>
<div class="tab-order-list">
{#each tabOrder as tab, index}
<div class="tab-order-item">
<div class="tab-grip">
<GripVertical size={16} />
</div>
<div class="tab-label">{tabLabels[tab] || tab}</div>
<div class="tab-controls">
<button
class="tab-move-btn"
onclick={() => moveUp(index)}
disabled={index === 0}
title="Move up"
>
↑
</button>
<button
class="tab-move-btn"
onclick={() => moveDown(index)}
disabled={index === tabOrder.length - 1}
title="Move down"
>
↓
</button>
</div>
</div>
{/each}
</div>
</div>
</div>
</div>
{/snippet}
{#snippet footer()}
<div class="modal-actions">
<button class="btn btn-secondary" onclick={handleCancel} disabled={saving}>
Cancel
</button>
<button class="btn btn-primary" onclick={handleSave} disabled={saving}>
{saving ? 'Saving...' : 'Save'}
</button>
</div>
{/snippet}
</Modal>
<style>
.modal-columns {
display: grid;
grid-template-columns: 65fr 35fr;
gap: 32px;
}
.modal-column {
min-width: 0;
}
.modal-section {
margin-bottom: 32px;
}
.modal-section:last-of-type {
margin-bottom: 0;
}
.modal-section h3 {
font-size: 15px;
font-weight: 600;
margin: 0 0 4px 0;
color: var(--text-primary);
}
.modal-section h4 {
font-size: 13px;
font-weight: 600;
margin: 0 0 8px 0;
color: var(--text-secondary);
}
.section-description {
font-size: 13px;
color: var(--text-muted);
margin: 0 0 16px 0;
}
.color-section {
margin-bottom: 20px;
}
.color-section:last-of-type {
margin-bottom: 0;
}
.icon-grid {
display: grid;
grid-template-columns: repeat(6, 1fr);
gap: 12px;
margin-bottom: 16px;
}
.icon-preset-btn {
aspect-ratio: 1;
display: flex;
align-items: center;
justify-content: center;
background: var(--bg-secondary);
border: 2px solid transparent;
border-radius: 8px;
cursor: pointer;
transition: all 150ms ease;
color: var(--text-secondary);
}
.icon-preset-btn:hover {
background: var(--bg-tertiary);
border-color: var(--accent-primary);
color: var(--text-primary);
}
.icon-preset-btn.active {
background: var(--accent-primary);
border-color: var(--accent-primary);
color: var(--bg-primary);
}
.color-grid {
display: grid;
grid-template-columns: repeat(12, 1fr);
gap: 2px;
}
.color-btn {
aspect-ratio: 1;
width: 30px;
height: 30px;
display: flex;
align-items: center;
justify-content: center;
background: transparent;
font-size: 0;
border: 2px solid transparent;
border-radius: 6px;
cursor: pointer;
transition: all 150ms ease;
padding: 3px;
}
.color-btn:hover {
border-color: var(--accent-primary);
}
.color-btn.active {
border-color: var(--accent-primary);
box-shadow: 0 0 0 1px var(--accent-primary);
}
.color-swatch {
width: 100%;
height: 100%;
border-radius: 4px;
border: 1px solid var(--bg-tertiary);
}
.color-swatch.no-color {
background: linear-gradient(
45deg,
var(--bg-tertiary) 25%,
transparent 25%,
transparent 75%,
var(--bg-tertiary) 75%,
var(--bg-tertiary)
),
linear-gradient(
45deg,
var(--bg-tertiary) 25%,
transparent 25%,
transparent 75%,
var(--bg-tertiary) 75%,
var(--bg-tertiary)
);
background-size: 10px 10px;
background-position: 0 0, 5px 5px;
}
.custom-upload {
display: flex;
align-items: center;
gap: 12px;
}
.upload-btn {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 16px;
background: var(--bg-secondary);
border: 1px solid var(--bg-tertiary);
border-radius: 6px;
color: var(--text-secondary);
font-size: 13px;
cursor: pointer;
transition: all 150ms ease;
}
.upload-btn:hover {
background: var(--bg-tertiary);
color: var(--text-primary);
}
.upload-filename {
font-size: 13px;
color: var(--text-muted);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tab-order-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.tab-order-item {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 16px;
background: var(--bg-secondary);
border: 1px solid var(--bg-tertiary);
border-radius: 6px;
}
.tab-grip {
color: var(--text-muted);
cursor: grab;
}
.tab-label {
flex: 1;
font-size: 14px;
color: var(--text-primary);
}
.tab-controls {
display: flex;
gap: 4px;
}
.tab-move-btn {
width: 28px;
height: 28px;
display: flex;
align-items: center;
justify-content: center;
background: var(--bg-primary);
border: 1px solid var(--bg-tertiary);
border-radius: 4px;
color: var(--text-secondary);
font-size: 14px;
cursor: pointer;
transition: all 150ms ease;
}
.tab-move-btn:hover:not(:disabled) {
background: var(--bg-tertiary);
color: var(--text-primary);
}
.tab-move-btn:disabled {
opacity: 0.3;
cursor: not-allowed;
}
.modal-actions {
display: flex;
justify-content: flex-end;
gap: 12px;
padding-top: 24px;
}
.btn {
padding: 8px 20px;
border-radius: 6px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 150ms ease;
border: none;
}
.btn-secondary {
background: var(--bg-secondary);
color: var(--text-primary);
}
.btn-secondary:hover:not(:disabled) {
background: var(--bg-tertiary);
}
.btn-primary {
background: var(--accent-primary);
color: var(--bg-primary);
}
.btn-primary:hover:not(:disabled) {
opacity: 0.9;
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn-custom-gradient {
width: 100%;
padding: 8px 16px;
background: var(--bg-secondary);
border: 1px solid var(--bg-tertiary);
border-radius: 6px;
color: var(--text-secondary);
font-size: 13px;
cursor: pointer;
transition: all 150ms ease;
}
.btn-custom-gradient:hover {
background: var(--bg-tertiary);
color: var(--text-primary);
}
.custom-gradient-editor {
display: flex;
flex-direction: column;
gap: 8px;
padding: 12px;
background: var(--bg-secondary);
border: 1px solid var(--bg-tertiary);
border-radius: 6px;
}
.gradient-color-row {
display: flex;
align-items: center;
gap: 8px;
}
.color-input {
flex: 1;
height: 32px;
border: 1px solid var(--bg-tertiary);
border-radius: 4px;
cursor: pointer;
background: var(--bg-primary);
}
.btn-remove-color {
width: 28px;
height: 28px;
display: flex;
align-items: center;
justify-content: center;
background: var(--bg-primary);
border: 1px solid var(--bg-tertiary);
border-radius: 4px;
color: var(--text-secondary);
font-size: 16px;
cursor: pointer;
transition: all 150ms ease;
}
.btn-remove-color:hover {
background: var(--bg-danger);
border-color: var(--bg-danger);
color: white;
}
.gradient-actions {
display: flex;
gap: 6px;
margin-top: 4px;
}
.btn-add-color,
.btn-apply-gradient,
.btn-cancel-gradient {
flex: 1;
padding: 6px 12px;
background: var(--bg-primary);
border: 1px solid var(--bg-tertiary);
border-radius: 4px;
color: var(--text-secondary);
font-size: 12px;
cursor: pointer;
transition: all 150ms ease;
}
.btn-add-color:hover,
.btn-cancel-gradient:hover {
background: var(--bg-tertiary);
color: var(--text-primary);
}
.btn-apply-gradient {
background: var(--accent-primary);
border-color: var(--accent-primary);
color: var(--bg-primary);
}
.btn-apply-gradient:hover {
opacity: 0.9;
}
</style>
+140 -5
View File
@@ -1,5 +1,6 @@
<script lang="ts"> <script lang="ts">
import { SkipBack, Play, Pause, SkipForward, ChevronDown } from 'lucide-svelte'; import { SkipBack, Play, Pause, SkipForward, ChevronDown } from 'lucide-svelte';
import StackIcon from './StackIcon.svelte';
import LyricsLines from './lyrics/LyricsLines.svelte'; import LyricsLines from './lyrics/LyricsLines.svelte';
import { startActiveLineUpdates, stopActiveLineUpdates } from '$lib/stores/lyricsStore'; import { startActiveLineUpdates, stopActiveLineUpdates } from '$lib/stores/lyricsStore';
import { t } from '$lib/i18n'; import { t } from '$lib/i18n';
@@ -21,6 +22,9 @@
currentTime: number; currentTime: number;
duration: number; duration: number;
onSeek: (time: number) => void; onSeek: (time: number) => void;
volume: number;
onVolumeChange: (volume: number) => void;
onContextClick?: () => void;
// Lyrics props // Lyrics props
lyricsLines?: LyricsLine[]; lyricsLines?: LyricsLine[];
lyricsActiveIndex?: number; lyricsActiveIndex?: number;
@@ -43,6 +47,9 @@
currentTime, currentTime,
duration, duration,
onSeek, onSeek,
volume,
onVolumeChange,
onContextClick,
lyricsLines = [], lyricsLines = [],
lyricsActiveIndex = -1, lyricsActiveIndex = -1,
lyricsActiveProgress = 0, lyricsActiveProgress = 0,
@@ -64,6 +71,8 @@
let showControls = $state(true); let showControls = $state(true);
let hideTimeout: ReturnType<typeof setTimeout> | null = null; let hideTimeout: ReturnType<typeof setTimeout> | null = null;
let progressRef: HTMLDivElement | null = $state(null); let progressRef: HTMLDivElement | null = $state(null);
let volumeRef: HTMLDivElement | null = $state(null);
let isDraggingVolume = $state(false);
const progress = $derived((currentTime / duration) * 100 || 0); const progress = $derived((currentTime / duration) * 100 || 0);
const hasLyrics = $derived(lyricsLines.length > 0); const hasLyrics = $derived(lyricsLines.length > 0);
@@ -93,6 +102,31 @@
} }
} }
function handleVolumeMouseDown(e: MouseEvent) {
e.stopPropagation();
isDraggingVolume = true;
updateVolume(e);
document.addEventListener('mousemove', handleVolumeMouseMove);
document.addEventListener('mouseup', handleVolumeMouseUp);
}
function handleVolumeMouseMove(e: MouseEvent) {
if (isDraggingVolume) updateVolume(e);
}
function handleVolumeMouseUp() {
isDraggingVolume = false;
document.removeEventListener('mousemove', handleVolumeMouseMove);
document.removeEventListener('mouseup', handleVolumeMouseUp);
}
function updateVolume(e: MouseEvent) {
if (!volumeRef) return;
const rect = volumeRef.getBoundingClientRect();
const percentage = Math.max(0, Math.min(100, ((e.clientX - rect.left) / rect.width) * 100));
onVolumeChange(Math.round(percentage));
}
function showControlsTemporarily() { function showControlsTemporarily() {
showControls = true; showControls = true;
if (hideTimeout) clearTimeout(hideTimeout); if (hideTimeout) clearTimeout(hideTimeout);
@@ -185,9 +219,12 @@
<img src={artwork} alt="" class="mini-artwork" /> <img src={artwork} alt="" class="mini-artwork" />
<div class="track-meta"> <div class="track-meta">
<div class="track-title">{trackTitle}</div> <div class="track-title">{trackTitle}</div>
<div class="track-artist-row">
<StackIcon size={12} class="stack-icon" onClick={onContextClick} />
<div class="track-artist">{artist}</div> <div class="track-artist">{artist}</div>
</div> </div>
</div> </div>
</div>
<!-- Center: Playback Controls + Progress --> <!-- Center: Playback Controls + Progress -->
<div class="playback-section"> <div class="playback-section">
@@ -233,8 +270,26 @@
</div> </div>
</div> </div>
<!-- Right: Spacer for balance --> <!-- Right: Volume Control -->
<div class="right-spacer"></div> <div class="right-controls">
<div class="volume-control">
<div class="volume-value" class:visible={isDraggingVolume}>{volume}</div>
<div
class="volume-bar"
bind:this={volumeRef}
onmousedown={handleVolumeMouseDown}
role="slider"
tabindex="0"
aria-valuenow={volume}
aria-valuemin={0}
aria-valuemax={100}
title={$t('player.volume')}
>
<div class="volume-fill" style="width: {volume}%"></div>
<div class="volume-thumb" style="left: {volume}%"></div>
</div>
</div>
</div>
</div> </div>
</div> </div>
{/if} {/if}
@@ -464,6 +519,18 @@
flex: 1; flex: 1;
} }
.track-title-row {
display: flex;
align-items: center;
gap: 6px;
white-space: nowrap;
overflow: hidden;
}
.track-title-row :global(.stack-icon) {
flex-shrink: 0;
}
.track-title { .track-title {
font-size: 14px; font-size: 14px;
font-weight: 600; font-weight: 600;
@@ -473,13 +540,23 @@
text-overflow: ellipsis; text-overflow: ellipsis;
} }
.track-artist-row {
display: flex;
align-items: center;
gap: 6px;
margin-top: 2px;
}
.track-artist-row :global(.stack-icon) {
flex-shrink: 0;
}
.track-artist { .track-artist {
font-size: 12px; font-size: 12px;
color: rgba(255, 255, 255, 0.6); color: rgba(255, 255, 255, 0.6);
white-space: nowrap; white-space: nowrap;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
margin-top: 2px;
} }
/* Playback Section */ /* Playback Section */
@@ -592,8 +669,66 @@
opacity: 1; opacity: 1;
} }
.right-spacer { .right-controls {
min-width: 200px; min-width: 200px;
display: flex;
justify-content: flex-end;
}
.volume-control {
position: relative;
display: flex;
align-items: center;
}
.volume-bar {
width: 140px;
height: 6px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.15);
cursor: pointer;
position: relative;
}
.volume-fill {
height: 100%;
border-radius: 999px;
background: rgba(255, 255, 255, 0.7);
}
.volume-thumb {
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
width: 12px;
height: 12px;
border-radius: 50%;
background: #fff;
opacity: 0;
transition: opacity 150ms ease;
}
.volume-bar:hover .volume-thumb {
opacity: 1;
}
.volume-value {
position: absolute;
right: 0;
top: -26px;
padding: 4px 8px;
border-radius: 999px;
background: rgba(0, 0, 0, 0.5);
color: #fff;
font-size: 12px;
opacity: 0;
transform: translateY(4px);
transition: opacity 150ms ease, transform 150ms ease;
}
.volume-value.visible {
opacity: 1;
transform: translateY(0);
} }
/* Responsive Breakpoints */ /* Responsive Breakpoints */
@@ -639,7 +774,7 @@
display: none; display: none;
} }
.right-spacer { .right-controls {
display: none; display: none;
} }
+1
View File
@@ -77,6 +77,7 @@
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
padding-left: 140px; /* Half of sidebar width (280px) for visual center */
z-index: 1000; z-index: 1000;
animation: fade-in 150ms ease; animation: fade-in 150ms ease;
} }
+47 -1
View File
@@ -20,6 +20,7 @@
} from 'lucide-svelte'; } from 'lucide-svelte';
import QualityBadge from './QualityBadge.svelte'; import QualityBadge from './QualityBadge.svelte';
import AudioOutputBadges from './AudioOutputBadges.svelte'; import AudioOutputBadges from './AudioOutputBadges.svelte';
import StackIcon from './StackIcon.svelte';
import { t } from '$lib/i18n'; import { t } from '$lib/i18n';
import { import {
subscribe as subscribeOffline, subscribe as subscribeOffline,
@@ -62,6 +63,7 @@
isCastConnected?: boolean; isCastConnected?: boolean;
onArtistClick?: () => void; onArtistClick?: () => void;
onAlbumClick?: () => void; onAlbumClick?: () => void;
onContextClick?: () => void;
} }
let { let {
@@ -97,7 +99,8 @@
lyricsActive = false, lyricsActive = false,
isCastConnected = false, isCastConnected = false,
onArtistClick, onArtistClick,
onAlbumClick onAlbumClick,
onContextClick
}: Props = $props(); }: Props = $props();
let progressRef: HTMLDivElement; let progressRef: HTMLDivElement;
@@ -296,6 +299,7 @@
<div class="song-info"> <div class="song-info">
<span class="song-title" title={trackTitle}>{trackTitle}</span> <span class="song-title" title={trackTitle}>{trackTitle}</span>
<div class="song-meta"> <div class="song-meta">
<StackIcon size={12} class="stack-icon" onClick={onContextClick} />
{#if artist} {#if artist}
<button class="meta-link" onclick={onArtistClick} title={$t('actions.goToArtist')}> <button class="meta-link" onclick={onArtistClick} title={$t('actions.goToArtist')}>
{artist} {artist}
@@ -374,6 +378,7 @@
<!-- Volume Control --> <!-- Volume Control -->
<div class="volume-control"> <div class="volume-control">
<div class="volume-value" class:visible={isDraggingVolume}>{volume}</div>
<button <button
class="control-btn volume-btn" class="control-btn volume-btn"
onclick={() => onVolumeChange?.(volume === 0 ? 70 : 0)} onclick={() => onVolumeChange?.(volume === 0 ? 70 : 0)}
@@ -676,6 +681,20 @@
align-self: center; align-self: center;
} }
.song-title-row {
display: flex;
align-items: center;
gap: 6px;
white-space: nowrap;
overflow: hidden;
width: 100%;
}
.song-title-row :global(.stack-icon) {
flex-shrink: 0;
margin-top: 1px;
}
.song-title { .song-title {
font-size: 13px; font-size: 13px;
font-weight: 500; font-weight: 500;
@@ -695,6 +714,11 @@
overflow: hidden; overflow: hidden;
} }
.song-meta :global(.stack-icon) {
flex-shrink: 0;
margin-right: 2px;
}
.meta-link { .meta-link {
background: none; background: none;
border: none; border: none;
@@ -743,6 +767,7 @@
display: flex; display: flex;
align-items: center; align-items: center;
gap: 8px; gap: 8px;
position: relative;
} }
.volume-slider { .volume-slider {
@@ -788,4 +813,25 @@
.volume-slider:hover .volume-thumb { .volume-slider:hover .volume-thumb {
opacity: 1; opacity: 1;
} }
.volume-value {
position: absolute;
right: 0;
bottom: calc(100% + 6px);
padding: 4px 6px;
border-radius: 6px;
background: var(--bg-tertiary);
color: var(--text-primary);
font-size: 11px;
font-weight: 600;
opacity: 0;
transform: translateY(4px);
transition: opacity 120ms ease, transform 120ms ease;
pointer-events: none;
}
.volume-value.visible {
opacity: 1;
transform: translateY(0);
}
</style> </style>
+19 -1
View File
@@ -48,6 +48,8 @@
let lockedProvider = $state<ProviderKey | null>(null); let lockedProvider = $state<ProviderKey | null>(null);
let logEntries = $state<{ message: string; status: 'info' | 'success' | 'error' }[]>([]); let logEntries = $state<{ message: string; status: 'info' | 'success' | 'error' }[]>([]);
let isOffline = $state(checkIsOffline()); let isOffline = $state(checkIsOffline());
let importCompleted = $state(false);
let lastImportedUrl = $state('');
// Subscribe to offline state changes // Subscribe to offline state changes
$effect(() => { $effect(() => {
@@ -76,6 +78,20 @@
summary = null; summary = null;
lockedProvider = null; lockedProvider = null;
logEntries = []; logEntries = [];
importCompleted = false;
lastImportedUrl = '';
}
});
$effect(() => {
if (!importCompleted) return;
const trimmed = url.trim();
if (trimmed !== lastImportedUrl) {
error = null;
summary = null;
lockedProvider = null;
logEntries = [];
importCompleted = false;
} }
}); });
@@ -127,6 +143,8 @@
}); });
summary = result; summary = result;
importCompleted = true;
lastImportedUrl = url.trim();
pushLog(`Imported ${result.matched_tracks} of ${result.total_tracks} tracks into QBZ.`, 'success'); pushLog(`Imported ${result.matched_tracks} of ${result.total_tracks} tracks into QBZ.`, 'success');
if (result.qobuz_playlist_id) { if (result.qobuz_playlist_id) {
@@ -259,7 +277,7 @@
<div class="modal-footer"> <div class="modal-footer">
<button class="btn-secondary" onclick={onClose} disabled={loading}>Close</button> <button class="btn-secondary" onclick={onClose} disabled={loading}>Close</button>
<button class="btn-primary" onclick={handleImport} disabled={!isValid || loading}> <button class="btn-primary" onclick={handleImport} disabled={!isValid || loading || importCompleted}>
{#if loading} {#if loading}
Importing... Importing...
{:else} {:else}
+1 -1
View File
@@ -511,7 +511,7 @@
<nav class="nav-section"> <nav class="nav-section">
<NavigationItem <NavigationItem
label={$t('nav.favorites')} label={$t('nav.favorites')}
active={activeView === 'favorites'} active={activeView.startsWith('favorites-')}
onclick={() => handleViewChange('favorites')} onclick={() => handleViewChange('favorites')}
> >
{#snippet icon()}<Heart size={14} />{/snippet} {#snippet icon()}<Heart size={14} />{/snippet}
+95
View File
@@ -0,0 +1,95 @@
<script lang="ts">
import { Layers } from 'lucide-svelte';
import { subscribe, getCurrentContext, getContextDisplayInfo } from '$lib/stores/playbackContextStore';
import { subscribe as subscribePrefs, getCachedPreferences } from '$lib/stores/playbackPreferencesStore';
interface Props {
size?: number;
class?: string;
onClick?: () => void;
}
let { size = 16, class: className = '', onClick }: Props = $props();
let context = $state(getCurrentContext());
let displayInfo = $state(context ? getContextDisplayInfo() : null);
let showIcon = $state(getCachedPreferences().show_context_icon);
function handleClick(e: MouseEvent) {
e.stopPropagation();
e.preventDefault();
if (onClick) {
onClick();
}
}
// Subscribe to context changes
$effect(() => {
const unsubscribe = subscribe(() => {
const newContext = getCurrentContext();
const newDisplayInfo = newContext ? getContextDisplayInfo() : null;
context = newContext;
displayInfo = newDisplayInfo;
});
return () => {
unsubscribe();
};
});
// Subscribe to preferences changes
$effect(() => {
const unsubscribe = subscribePrefs(() => {
showIcon = getCachedPreferences().show_context_icon;
});
return () => {
unsubscribe();
};
});
</script>
{#if context && displayInfo && showIcon}
<button
class="stack-icon-wrapper {className}"
onclick={handleClick}
title={displayInfo ? `Playing from: ${displayInfo}` : undefined}
aria-label={displayInfo ? `Playing from: ${displayInfo}` : 'Playback context'}
type="button"
>
<Layers size={size} strokeWidth={2} />
</button>
{/if}
<style>
.stack-icon-wrapper {
display: inline-flex;
align-items: center;
justify-content: center;
color: var(--text-secondary);
opacity: 0.7;
transition: all 0.2s;
flex-shrink: 0;
background: none;
border: none;
padding: 4px;
border-radius: 4px;
cursor: pointer;
position: relative;
}
.stack-icon-wrapper:hover {
opacity: 1;
background: rgba(255, 255, 255, 0.05);
color: var(--text-primary);
}
.stack-icon-wrapper:active {
transform: scale(0.95);
}
.stack-icon-wrapper:focus-visible {
outline: 2px solid var(--accent-primary);
outline-offset: 2px;
}
</style>
+17 -1
View File
@@ -17,6 +17,8 @@
interface Props { interface Props {
onPlayNow?: () => void; onPlayNow?: () => void;
onPlayTrackOnly?: () => void;
onPlayFromHere?: () => void;
onPlayNext?: () => void; onPlayNext?: () => void;
onPlayLater?: () => void; onPlayLater?: () => void;
onAddFavorite?: () => void; onAddFavorite?: () => void;
@@ -30,6 +32,8 @@
let { let {
onPlayNow, onPlayNow,
onPlayTrackOnly,
onPlayFromHere,
onPlayNext, onPlayNext,
onPlayLater, onPlayLater,
onAddFavorite, onAddFavorite,
@@ -63,7 +67,7 @@
}; };
} }
const hasPlayback = $derived(!!(onPlayNow || onPlayNext || onPlayLater)); const hasPlayback = $derived(!!(onPlayNow || onPlayTrackOnly || onPlayFromHere || onPlayNext || onPlayLater));
const hasLibrary = $derived(!!(onAddFavorite || onAddToPlaylist || onRemoveFromPlaylist)); const hasLibrary = $derived(!!(onAddFavorite || onAddToPlaylist || onRemoveFromPlaylist));
const hasShare = $derived(!!(onShareQobuz || onShareSonglink)); const hasShare = $derived(!!(onShareQobuz || onShareSonglink));
const hasNav = $derived(!!(onGoToAlbum || onGoToArtist)); const hasNav = $derived(!!(onGoToAlbum || onGoToArtist));
@@ -193,6 +197,18 @@
<span>Play now</span> <span>Play now</span>
</button> </button>
{/if} {/if}
{#if onPlayTrackOnly}
<button class="menu-item" onclick={() => handleAction(onPlayTrackOnly)}>
<Play size={14} />
<span>Play track only</span>
</button>
{/if}
{#if onPlayFromHere}
<button class="menu-item" onclick={() => handleAction(onPlayFromHere)}>
<Play size={14} />
<span>Play from here</span>
</button>
{/if}
{#if onPlayNext} {#if onPlayNext}
<button class="menu-item" onclick={() => handleAction(onPlayNext)}> <button class="menu-item" onclick={() => handleAction(onPlayNext)}>
<ListPlus size={14} /> <ListPlus size={14} />
+41 -4
View File
@@ -1,6 +1,6 @@
<script lang="ts"> <script lang="ts">
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import { Play, Heart, HardDrive } from 'lucide-svelte'; import { Play, Pause, Heart, HardDrive } from 'lucide-svelte';
import TrackMenu from './TrackMenu.svelte'; import TrackMenu from './TrackMenu.svelte';
import DownloadButton from './DownloadButton.svelte'; import DownloadButton from './DownloadButton.svelte';
import { import {
@@ -8,6 +8,7 @@
isTrackFavorite, isTrackFavorite,
toggleTrackFavorite toggleTrackFavorite
} from '$lib/stores/favoritesStore'; } from '$lib/stores/favoritesStore';
import { togglePlay } from '$lib/stores/playerStore';
type DownloadStatus = 'none' | 'queued' | 'downloading' | 'ready' | 'failed'; type DownloadStatus = 'none' | 'queued' | 'downloading' | 'ready' | 'failed';
@@ -37,6 +38,8 @@
interface TrackMenuActions { interface TrackMenuActions {
onPlayNow?: () => void; onPlayNow?: () => void;
onPlayTrackOnly?: () => void;
onPlayFromHere?: () => void;
onPlayNext?: () => void; onPlayNext?: () => void;
onPlayLater?: () => void; onPlayLater?: () => void;
onAddToPlaylist?: () => void; onAddToPlaylist?: () => void;
@@ -108,6 +111,11 @@
e.stopPropagation(); e.stopPropagation();
albumClickAction?.(); albumClickAction?.();
} }
function handlePauseClick(e: MouseEvent) {
e.stopPropagation();
void togglePlay();
}
</script> </script>
<div <div
@@ -115,6 +123,7 @@
class:playing={isPlaying} class:playing={isPlaying}
class:hovered={isHovered && !isPlaying} class:hovered={isHovered && !isPlaying}
class:compact class:compact
data-track-id={trackId ?? undefined}
onmouseenter={() => (isHovered = true)} onmouseenter={() => (isHovered = true)}
onmouseleave={() => (isHovered = false)} onmouseleave={() => (isHovered = false)}
onclick={onPlay} onclick={onPlay}
@@ -124,14 +133,20 @@
> >
<!-- Track Number / Play Button --> <!-- Track Number / Play Button -->
<div class="track-number"> <div class="track-number">
{#if isHovered && !isPlaying} {#if isPlaying}
<Play size={16} class="play-icon" fill="white" /> {#if isHovered}
{:else if isPlaying} <button class="pause-btn" type="button" onclick={handlePauseClick} aria-label="Pause">
<Pause size={16} class="pause-icon" />
</button>
{:else}
<div class="playing-indicator"> <div class="playing-indicator">
<div class="bar"></div> <div class="bar"></div>
<div class="bar"></div> <div class="bar"></div>
<div class="bar"></div> <div class="bar"></div>
</div> </div>
{/if}
{:else if isHovered}
<Play size={16} class="play-icon" fill="white" />
{:else} {:else}
<span>{number}</span> <span>{number}</span>
{/if} {/if}
@@ -217,6 +232,8 @@
<div class="track-actions"> <div class="track-actions">
<TrackMenu <TrackMenu
onPlayNow={playNowAction} onPlayNow={playNowAction}
onPlayTrackOnly={menuActions?.onPlayTrackOnly}
onPlayFromHere={menuActions?.onPlayFromHere}
onPlayNext={menuActions?.onPlayNext} onPlayNext={menuActions?.onPlayNext}
onPlayLater={menuActions?.onPlayLater} onPlayLater={menuActions?.onPlayLater}
onAddFavorite={trackId !== undefined ? () => toggleTrackFavorite(trackId) : undefined} onAddFavorite={trackId !== undefined ? () => toggleTrackFavorite(trackId) : undefined}
@@ -283,6 +300,26 @@
color: rgba(40, 42, 54, 0.85); color: rgba(40, 42, 54, 0.85);
} }
.pause-btn {
width: 24px;
height: 24px;
display: inline-flex;
align-items: center;
justify-content: center;
background: transparent;
border: none;
cursor: pointer;
padding: 0;
}
.pause-btn :global(.pause-icon) {
color: white;
}
:global([data-theme="light"]) .pause-btn :global(.pause-icon) {
color: rgba(40, 42, 54, 0.85);
}
.playing-indicator { .playing-indicator {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -1,9 +1,10 @@
<script lang="ts"> <script lang="ts">
import { onMount } from 'svelte'; import { onMount, tick } from 'svelte';
import { ArrowLeft, Play, Shuffle, Heart } from 'lucide-svelte'; import { ArrowLeft, Play, Shuffle, Heart } from 'lucide-svelte';
import TrackRow from '../TrackRow.svelte'; import TrackRow from '../TrackRow.svelte';
import AlbumMenu from '../AlbumMenu.svelte'; import AlbumMenu from '../AlbumMenu.svelte';
import { getDownloadState, type DownloadStatus, isAlbumFullyDownloaded } from '$lib/stores/downloadState'; import { getDownloadState, type DownloadStatus, isAlbumFullyDownloaded } from '$lib/stores/downloadState';
import { consumeContextTrackFocus } from '$lib/stores/playbackContextStore';
import { import {
subscribe as subscribeAlbumFavorites, subscribe as subscribeAlbumFavorites,
isAlbumFavorite, isAlbumFavorite,
@@ -101,6 +102,7 @@
let isFavorite = $state(false); let isFavorite = $state(false);
let isFavoriteLoading = $state(false); let isFavoriteLoading = $state(false);
let playBtnHovered = $state(false); let playBtnHovered = $state(false);
let scrollContainer: HTMLDivElement | null = $state(null);
const albumFullyDownloaded = $derived( const albumFullyDownloaded = $derived(
isAlbumFullyDownloaded(album.tracks.map(t => t.id)) isAlbumFullyDownloaded(album.tracks.map(t => t.id))
@@ -110,6 +112,12 @@
album.artist?.trim().toLowerCase() === 'various artists' album.artist?.trim().toLowerCase() === 'various artists'
); );
async function scrollToTrack(trackId: number) {
await tick();
const target = scrollContainer?.querySelector<HTMLElement>(`[data-track-id="${trackId}"]`);
target?.scrollIntoView({ block: 'center' });
}
// Check if album is in favorites on mount // Check if album is in favorites on mount
onMount(() => { onMount(() => {
let unsubscribe: (() => void) | null = null; let unsubscribe: (() => void) | null = null;
@@ -130,6 +138,14 @@
}; };
}); });
$effect(() => {
if (!album.tracks?.length) return;
const targetId = consumeContextTrackFocus('album', album.id);
if (targetId !== null) {
void scrollToTrack(targetId);
}
});
async function toggleFavorite() { async function toggleFavorite() {
if (isFavoriteLoading) return; if (isFavoriteLoading) return;
@@ -144,7 +160,7 @@
} }
</script> </script>
<div class="album-detail"> <div class="album-detail" bind:this={scrollContainer}>
<!-- Back Navigation --> <!-- Back Navigation -->
<button class="back-btn" onclick={onBack}> <button class="back-btn" onclick={onBack}>
<ArrowLeft size={16} /> <ArrowLeft size={16} />
@@ -224,7 +240,7 @@
<!-- Track Rows --> <!-- Track Rows -->
<div class="tracks"> <div class="tracks">
{#each album.tracks as track (`${track.id}-${downloadStateVersion}`)} {#each album.tracks as track, trackIndex (`${track.id}-${downloadStateVersion}`)}
{@const downloadInfo = getTrackDownloadStatus?.(track.id) ?? { status: 'none' as const, progress: 0 }} {@const downloadInfo = getTrackDownloadStatus?.(track.id) ?? { status: 'none' as const, progress: 0 }}
<TrackRow <TrackRow
trackId={track.id} trackId={track.id}
+182 -20
View File
@@ -1,9 +1,12 @@
<script lang="ts"> <script lang="ts">
import { invoke } from '@tauri-apps/api/core'; import { invoke } from '@tauri-apps/api/core';
import { ArrowLeft, User, ChevronDown, ChevronUp, Play, Music, Heart, Search, X, ChevronLeft, ChevronRight } from 'lucide-svelte'; import { ArrowLeft, User, ChevronDown, ChevronUp, Play, Pause, Music, Heart, Search, X, ChevronLeft, ChevronRight } from 'lucide-svelte';
import type { ArtistDetail, QobuzArtist } from '$lib/types'; import type { ArtistDetail, QobuzArtist } from '$lib/types';
import AlbumCard from '../AlbumCard.svelte'; import AlbumCard from '../AlbumCard.svelte';
import TrackMenu from '../TrackMenu.svelte'; import TrackMenu from '../TrackMenu.svelte';
import { consumeContextTrackFocus, setPlaybackContext } from '$lib/stores/playbackContextStore';
import { togglePlay } from '$lib/stores/playerStore';
import { tick } from 'svelte';
interface Track { interface Track {
id: number; id: number;
@@ -68,6 +71,8 @@
onTrackShareSonglink?: (track: Track) => void; onTrackShareSonglink?: (track: Track) => void;
onTrackGoToAlbum?: (albumId: string) => void; onTrackGoToAlbum?: (albumId: string) => void;
onTrackGoToArtist?: (artistId: number) => void; onTrackGoToArtist?: (artistId: number) => void;
activeTrackId?: number | null;
isPlaybackActive?: boolean;
} }
let { let {
@@ -95,7 +100,9 @@
onTrackShareQobuz, onTrackShareQobuz,
onTrackShareSonglink, onTrackShareSonglink,
onTrackGoToAlbum, onTrackGoToAlbum,
onTrackGoToArtist onTrackGoToArtist,
activeTrackId = null,
isPlaybackActive = false
}: Props = $props(); }: Props = $props();
let bioExpanded = $state(false); let bioExpanded = $state(false);
@@ -297,7 +304,51 @@
return `${mins}:${secs.toString().padStart(2, '0')}`; return `${mins}:${secs.toString().padStart(2, '0')}`;
} }
function handleTrackPlay(track: Track) { function handlePausePlayback(event: MouseEvent) {
event.stopPropagation();
void togglePlay();
}
function buildTopTracksQueue(tracks: Track[]) {
return tracks.map(t => ({
id: t.id,
title: t.title,
artist: t.performer?.name || artist.name,
album: t.album?.title || '',
duration_secs: t.duration,
artwork_url: t.album?.image?.large || t.album?.image?.thumbnail || '',
hires: t.hires_streamable ?? false,
bit_depth: t.maximum_bit_depth ?? null,
sample_rate: t.maximum_sampling_rate ?? null,
}));
}
async function handleTrackPlay(track: Track, trackIndex?: number) {
// Create artist top tracks context
if (topTracks.length > 0) {
const trackIds = topTracks.map(t => t.id);
const index = trackIndex !== undefined ? trackIndex : trackIds.indexOf(track.id);
if (index >= 0) {
setPlaybackContext(
'artist_top',
artist.id.toString(),
artist.name,
'qobuz',
trackIds,
index
);
console.log(`[Artist] Context created: "${artist.name}" top tracks, ${trackIds.length} tracks, starting at ${index}`);
try {
const queueTracks = buildTopTracksQueue(topTracks);
await invoke('set_queue', { tracks: queueTracks, startIndex: index });
} catch (err) {
console.error('Failed to set queue:', err);
}
}
}
// Play track
if (onTrackPlay) { if (onTrackPlay) {
onTrackPlay({ onTrackPlay({
id: track.id, id: track.id,
@@ -320,21 +371,8 @@
async function handlePlayAllTracks() { async function handlePlayAllTracks() {
if (topTracks.length === 0 || !onTrackPlay) return; if (topTracks.length === 0 || !onTrackPlay) return;
const queueTracks = topTracks.map(t => ({
id: t.id,
title: t.title,
artist: t.performer?.name || artist.name,
album: t.album?.title || '',
duration_secs: t.duration,
artwork_url: t.album?.image?.large || t.album?.image?.thumbnail || '',
hires: t.hires_streamable ?? false,
bit_depth: t.maximum_bit_depth ?? null,
sample_rate: t.maximum_sampling_rate ?? null,
}));
try { try {
await invoke('set_queue', { tracks: queueTracks, startIndex: 0 }); await handleTrackPlay(topTracks[0], 0);
handleTrackPlay(topTracks[0]);
} catch (err) { } catch (err) {
console.error('Failed to set queue:', err); console.error('Failed to set queue:', err);
} }
@@ -495,6 +533,20 @@
target?.scrollIntoView({ behavior: 'smooth', block: 'start' }); target?.scrollIntoView({ behavior: 'smooth', block: 'start' });
} }
async function scrollToTrack(trackId: number) {
await tick();
const target = artistDetailEl?.querySelector<HTMLElement>(`[data-track-id="${trackId}"]`);
target?.scrollIntoView({ block: 'center' });
}
$effect(() => {
if (!artistDetailEl || topTracks.length === 0) return;
const targetId = consumeContextTrackFocus('artist_top', artist.id.toString());
if (targetId !== null) {
void scrollToTrack(targetId);
}
});
$effect(() => { $effect(() => {
if (!artistDetailEl) return; if (!artistDetailEl) return;
if (jumpObserver) { if (jumpObserver) {
@@ -743,12 +795,14 @@
{:else} {:else}
<div class="tracks-list"> <div class="tracks-list">
{#each topTracks as track, index} {#each topTracks as track, index}
{@const isActiveTrack = isPlaybackActive && activeTrackId === track.id}
<div <div
class="track-row" class="track-row"
class:playing={isActiveTrack}
role="button" role="button"
tabindex="0" tabindex="0"
onclick={() => handleTrackPlay(track)} onclick={() => handleTrackPlay(track, index)}
onkeydown={(e) => e.key === 'Enter' && handleTrackPlay(track)} onkeydown={(e) => e.key === 'Enter' && handleTrackPlay(track, index)}
> >
<div class="track-number">{index + 1}</div> <div class="track-number">{index + 1}</div>
<div class="track-artwork"> <div class="track-artwork">
@@ -759,6 +813,29 @@
<Music size={16} /> <Music size={16} />
</div> </div>
{/if} {/if}
<button
class="track-play-overlay"
class:is-playing={isActiveTrack}
onclick={(event) => {
if (isActiveTrack) {
handlePausePlayback(event);
} else {
event.stopPropagation();
handleTrackPlay(track, index);
}
}}
aria-label={isActiveTrack ? 'Pause track' : 'Play track'}
>
<span class="play-icon" aria-hidden="true">
<Play size={18} />
</span>
<div class="playing-indicator" aria-hidden="true">
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
</div>
<Pause size={18} class="pause-icon" aria-hidden="true" />
</button>
</div> </div>
<div class="track-info"> <div class="track-info">
<div class="track-title">{track.title}</div> <div class="track-title">{track.title}</div>
@@ -780,7 +857,7 @@
<div class="track-duration">{formatDuration(track.duration)}</div> <div class="track-duration">{formatDuration(track.duration)}</div>
<div class="track-actions"> <div class="track-actions">
<TrackMenu <TrackMenu
onPlayNow={() => handleTrackPlay(track)} onPlayNow={() => handleTrackPlay(track, index)}
onPlayNext={onTrackPlayNext ? () => onTrackPlayNext(track) : undefined} onPlayNext={onTrackPlayNext ? () => onTrackPlayNext(track) : undefined}
onPlayLater={onTrackPlayLater ? () => onTrackPlayLater(track) : undefined} onPlayLater={onTrackPlayLater ? () => onTrackPlayLater(track) : undefined}
onAddFavorite={onTrackAddFavorite ? () => onTrackAddFavorite(track.id) : undefined} onAddFavorite={onTrackAddFavorite ? () => onTrackAddFavorite(track.id) : undefined}
@@ -1651,6 +1728,7 @@
border-radius: 4px; border-radius: 4px;
overflow: hidden; overflow: hidden;
flex-shrink: 0; flex-shrink: 0;
position: relative;
} }
.track-artwork img { .track-artwork img {
@@ -1669,6 +1747,90 @@
color: var(--text-muted); color: var(--text-muted);
} }
.track-play-overlay {
position: absolute;
inset: 0;
display: none;
align-items: center;
justify-content: center;
background: rgba(0, 0, 0, 0.6);
border: none;
cursor: pointer;
transition: background 150ms ease;
}
.track-row:hover .track-play-overlay {
display: flex;
}
.track-row.playing .track-play-overlay {
display: flex;
}
.track-play-overlay:hover {
background: rgba(0, 0, 0, 0.75);
}
.track-play-overlay .playing-indicator,
.track-play-overlay .pause-icon {
display: none;
}
.track-row.playing .track-play-overlay .play-icon {
display: none;
}
.track-row.playing .track-play-overlay .playing-indicator {
display: flex;
}
.track-row.playing:hover .track-play-overlay .playing-indicator {
display: none;
}
.track-row.playing:hover .track-play-overlay .pause-icon {
display: inline-flex;
}
.playing-indicator {
display: flex;
align-items: center;
gap: 2px;
}
.playing-indicator .bar {
width: 3px;
background-color: var(--accent-primary);
border-radius: 9999px;
transform-origin: bottom;
animation: artist-equalize 1s ease-in-out infinite;
}
.playing-indicator .bar:nth-child(1) {
height: 10px;
}
.playing-indicator .bar:nth-child(2) {
height: 14px;
animation-delay: 0.15s;
}
.playing-indicator .bar:nth-child(3) {
height: 8px;
animation-delay: 0.3s;
}
@keyframes artist-equalize {
0%, 100% {
transform: scaleY(0.5);
opacity: 0.7;
}
50% {
transform: scaleY(1);
opacity: 1;
}
}
.track-info { .track-info {
flex: 1; flex: 1;
min-width: 0; min-width: 0;
+402 -125
View File
@@ -1,11 +1,15 @@
<script lang="ts"> <script lang="ts">
import { invoke } from '@tauri-apps/api/core'; import { invoke, convertFileSrc } from '@tauri-apps/api/core';
import { onMount } from 'svelte'; import { onMount, tick } from 'svelte';
import { Heart, Play, Disc3, Mic2, Music, Search, X, LayoutGrid, List, ChevronDown, ListMusic } from 'lucide-svelte'; import { Heart, Play, Disc3, Mic2, Music, Search, X, LayoutGrid, List, ChevronDown, ListMusic, Edit3, Star, Folder, Library } from 'lucide-svelte';
import AlbumCard from '../AlbumCard.svelte'; import AlbumCard from '../AlbumCard.svelte';
import TrackRow from '../TrackRow.svelte'; import TrackRow from '../TrackRow.svelte';
import PlaylistCollage from '../PlaylistCollage.svelte'; import PlaylistCollage from '../PlaylistCollage.svelte';
import FavoritesEditModal from '../FavoritesEditModal.svelte';
import { type DownloadStatus } from '$lib/stores/downloadState'; import { type DownloadStatus } from '$lib/stores/downloadState';
import { consumeContextTrackFocus, setPlaybackContext } from '$lib/stores/playbackContextStore';
import { normalizeFavoritesTabOrder } from '$lib/utils/favorites';
import type { FavoritesPreferences } from '$lib/types';
interface FavoriteAlbum { interface FavoriteAlbum {
id: string; id: string;
@@ -73,6 +77,10 @@
onTrackRemoveDownload?: (trackId: number) => void; onTrackRemoveDownload?: (trackId: number) => void;
getTrackDownloadStatus?: (trackId: number) => { status: DownloadStatus; progress: number }; getTrackDownloadStatus?: (trackId: number) => { status: DownloadStatus; progress: number };
onPlaylistSelect?: (playlistId: number) => void; onPlaylistSelect?: (playlistId: number) => void;
selectedTab?: TabType;
onTabNavigate?: (tab: TabType) => void;
activeTrackId?: number | null;
isPlaybackActive?: boolean;
} }
interface DisplayTrack { interface DisplayTrack {
@@ -117,11 +125,23 @@
onTrackDownload, onTrackDownload,
onTrackRemoveDownload, onTrackRemoveDownload,
getTrackDownloadStatus, getTrackDownloadStatus,
onPlaylistSelect onPlaylistSelect,
selectedTab,
onTabNavigate,
activeTrackId = null,
isPlaybackActive = false
}: Props = $props(); }: Props = $props();
type TabType = 'tracks' | 'albums' | 'artists' | 'playlists'; type TabType = 'tracks' | 'albums' | 'artists' | 'playlists';
let activeTab = $state<TabType>('tracks'); let activeTab = $state<TabType>('tracks');
let preferencesLoaded = $state(false);
const tabLabels: Record<TabType, string> = {
tracks: 'Tracks',
albums: 'Albums',
artists: 'Artists',
playlists: 'Playlists',
};
let favoriteAlbums = $state<FavoriteAlbum[]>([]); let favoriteAlbums = $state<FavoriteAlbum[]>([]);
let favoriteTracks = $state<FavoriteTrack[]>([]); let favoriteTracks = $state<FavoriteTrack[]>([]);
@@ -130,6 +150,14 @@
let loading = $state(false); let loading = $state(false);
let loadingPlaylists = $state(false); let loadingPlaylists = $state(false);
let editModalOpen = $state(false);
let scrollContainer: HTMLDivElement | null = $state(null);
let favoritesPreferences = $state<FavoritesPreferences>({
custom_icon_path: null,
custom_icon_preset: 'heart',
icon_background: null,
tab_order: ['tracks', 'albums', 'artists', 'playlists'],
});
// Download status tracking // Download status tracking
let albumDownloadStatuses = $state<Map<string, boolean>>(new Map()); let albumDownloadStatuses = $state<Map<string, boolean>>(new Map());
@@ -162,6 +190,7 @@
let albumSearch = $state(''); let albumSearch = $state('');
let artistSearch = $state(''); let artistSearch = $state('');
let playlistSearch = $state(''); let playlistSearch = $state('');
let searchExpanded = $state(false);
let albumViewMode = $state<'grid' | 'list'>('grid'); let albumViewMode = $state<'grid' | 'list'>('grid');
type AlbumGroupMode = 'alpha' | 'artist'; type AlbumGroupMode = 'alpha' | 'artist';
@@ -176,6 +205,24 @@
let showArtistGroupMenu = $state(false); let showArtistGroupMenu = $state(false);
let artistGroupingEnabled = $state(false); let artistGroupingEnabled = $state(false);
function resolveCustomIconSrc(path: string | null): string | null {
if (!path) return null;
if (path.startsWith('asset://') || path.startsWith('http://asset.localhost') || path.startsWith('https://asset.localhost')) {
return path;
}
if (path.startsWith('file://')) {
return path;
}
return convertFileSrc(path);
}
let customIconSrc = $derived.by(() => resolveCustomIconSrc(favoritesPreferences.custom_icon_path));
async function scrollToTrack(trackId: number) {
await tick();
const target = scrollContainer?.querySelector<HTMLElement>(`[data-track-id="${trackId}"]`);
target?.scrollIntoView({ block: 'center' });
}
// Filtered lists based on search // Filtered lists based on search
let filteredTracks = $derived.by(() => { let filteredTracks = $derived.by(() => {
@@ -240,6 +287,43 @@
return fallback; return fallback;
} }
function getCurrentSearchValue(): string {
switch (activeTab) {
case 'tracks': return trackSearch;
case 'albums': return albumSearch;
case 'artists': return artistSearch;
case 'playlists': return playlistSearch;
default: return '';
}
}
function setCurrentSearchValue(value: string) {
switch (activeTab) {
case 'tracks': trackSearch = value; break;
case 'albums': albumSearch = value; break;
case 'artists': artistSearch = value; break;
case 'playlists': playlistSearch = value; break;
}
}
function clearCurrentSearch() {
setCurrentSearchValue('');
searchExpanded = false;
}
function getTabIcon(tab: TabType) {
switch (tab) {
case 'tracks': return Music;
case 'albums': return Disc3;
case 'artists': return Mic2;
case 'playlists': return ListMusic;
}
}
function getTabLabel(tab: TabType): string {
return tabLabels[tab] || tab.charAt(0).toUpperCase() + tab.slice(1);
}
onMount(() => { onMount(() => {
albumViewMode = loadStoredString('qbz-favorites-album-view', 'grid', ['grid', 'list']); albumViewMode = loadStoredString('qbz-favorites-album-view', 'grid', ['grid', 'list']);
albumGroupMode = loadStoredString('qbz-favorites-album-group', 'alpha', ['alpha', 'artist']); albumGroupMode = loadStoredString('qbz-favorites-album-group', 'alpha', ['alpha', 'artist']);
@@ -247,8 +331,40 @@
albumGroupingEnabled = loadStoredBool('qbz-favorites-album-group-enabled', false); albumGroupingEnabled = loadStoredBool('qbz-favorites-album-group-enabled', false);
trackGroupingEnabled = loadStoredBool('qbz-favorites-track-group-enabled', false); trackGroupingEnabled = loadStoredBool('qbz-favorites-track-group-enabled', false);
artistGroupingEnabled = loadStoredBool('qbz-favorites-artist-group-enabled', false); artistGroupingEnabled = loadStoredBool('qbz-favorites-artist-group-enabled', false);
loadFavorites('tracks'); loadFavoritesPreferences().then(() => {
preferencesLoaded = true;
if (selectedTab) {
activeTab = selectedTab;
} else {
activeTab = favoritesPreferences.tab_order[0] as TabType;
}
loadTabIfNeeded(activeTab);
}); });
});
async function loadFavoritesPreferences() {
try {
const prefs = await invoke<FavoritesPreferences>('get_favorites_preferences');
favoritesPreferences = {
...prefs,
tab_order: normalizeFavoritesTabOrder(prefs.tab_order)
};
} catch (err) {
console.error('Failed to load favorites preferences:', err);
favoritesPreferences = {
...favoritesPreferences,
tab_order: normalizeFavoritesTabOrder(favoritesPreferences.tab_order)
};
}
}
function handlePreferencesSaved(prefs: FavoritesPreferences) {
favoritesPreferences = {
...prefs,
tab_order: normalizeFavoritesTabOrder(prefs.tab_order)
};
}
$effect(() => { $effect(() => {
try { try {
@@ -263,6 +379,21 @@
} }
}); });
$effect(() => {
if (preferencesLoaded && selectedTab && selectedTab !== activeTab) {
activeTab = selectedTab;
loadTabIfNeeded(activeTab);
}
});
$effect(() => {
if (!preferencesLoaded || activeTab !== 'tracks' || favoriteTracks.length === 0) return;
const targetId = consumeContextTrackFocus('favorites', 'favorites');
if (targetId !== null) {
void scrollToTrack(targetId);
}
});
const FAVORITES_PAGE_SIZE = 200; const FAVORITES_PAGE_SIZE = 200;
const FAVORITES_MAX_PAGES = 50; const FAVORITES_MAX_PAGES = 50;
@@ -356,11 +487,7 @@
} }
} }
function handleTabChange(tab: TabType) { function loadTabIfNeeded(tab: TabType) {
activeTab = tab;
showAlbumGroupMenu = false;
showTrackGroupMenu = false;
showArtistGroupMenu = false;
if (tab === 'tracks' && favoriteTracks.length === 0) { if (tab === 'tracks' && favoriteTracks.length === 0) {
loadFavorites(tab); loadFavorites(tab);
} else if (tab === 'albums' && favoriteAlbums.length === 0) { } else if (tab === 'albums' && favoriteAlbums.length === 0) {
@@ -372,6 +499,15 @@
} }
} }
function handleTabChange(tab: TabType) {
activeTab = tab;
showAlbumGroupMenu = false;
showTrackGroupMenu = false;
showArtistGroupMenu = false;
onTabNavigate?.(tab);
loadTabIfNeeded(tab);
}
function formatDuration(seconds: number): string { function formatDuration(seconds: number): string {
const mins = Math.floor(seconds / 60); const mins = Math.floor(seconds / 60);
const secs = seconds % 60; const secs = seconds % 60;
@@ -591,16 +727,8 @@
}; };
} }
function handleTrackClick(track: FavoriteTrack, index: number) { function buildFavoritesQueueTracks(tracks: FavoriteTrack[]) {
if (onTrackPlay) { return tracks.map(t => ({
onTrackPlay(buildDisplayTrack(track, index));
}
}
async function handlePlayAllTracks() {
if (filteredTracks.length === 0 || !onTrackPlay) return;
const queueTracks = filteredTracks.map(t => ({
id: t.id, id: t.id,
title: t.title, title: t.title,
artist: t.performer?.name || 'Unknown Artist', artist: t.performer?.name || 'Unknown Artist',
@@ -611,10 +739,48 @@
bit_depth: t.maximum_bit_depth ?? null, bit_depth: t.maximum_bit_depth ?? null,
sample_rate: t.maximum_sampling_rate ?? null, sample_rate: t.maximum_sampling_rate ?? null,
})); }));
}
function setFavoritesContext(trackIds: number[], index: number) {
if (trackIds.length === 0) return;
setPlaybackContext(
'favorites',
'favorites',
'Favorites',
'qobuz',
trackIds,
index
);
}
async function setFavoritesQueue(startIndex: number) {
if (filteredTracks.length === 0) return;
const queueTracks = buildFavoritesQueueTracks(filteredTracks);
await invoke('set_queue', { tracks: queueTracks, startIndex });
}
async function handleTrackClick(track: FavoriteTrack, index: number) {
const trackIds = filteredTracks.map(t => t.id);
setFavoritesContext(trackIds, index);
try { try {
await invoke('set_queue', { tracks: queueTracks, startIndex: 0 }); await setFavoritesQueue(index);
handleTrackClick(filteredTracks[0], 0); } catch (err) {
console.error('Failed to set queue:', err);
}
if (onTrackPlay) {
onTrackPlay(buildDisplayTrack(track, index));
}
}
async function handlePlayAllTracks() {
if (filteredTracks.length === 0 || !onTrackPlay) return;
try {
await setFavoritesQueue(0);
setFavoritesContext(filteredTracks.map(t => t.id), 0);
onTrackPlay(buildDisplayTrack(filteredTracks[0], 0));
} catch (err) { } catch (err) {
console.error('Failed to set queue:', err); console.error('Failed to set queue:', err);
} }
@@ -622,110 +788,88 @@
</script> </script>
<div class="favorites-view"> <div class="favorites-view" bind:this={scrollContainer}>
<!-- Header --> <!-- Header -->
<div class="header"> <div class="header">
<div class="header-icon"> <div
class="header-icon"
style={favoritesPreferences.icon_background ? `background: ${favoritesPreferences.icon_background};` : ''}
>
{#if customIconSrc}
<img
src={customIconSrc}
alt="Custom Icon"
class="custom-icon-img"
/>
{:else if favoritesPreferences.custom_icon_preset}
{#if favoritesPreferences.custom_icon_preset === 'heart'}
<Heart size={32} fill="var(--accent-primary)" color="var(--accent-primary)" /> <Heart size={32} fill="var(--accent-primary)" color="var(--accent-primary)" />
{:else if favoritesPreferences.custom_icon_preset === 'star'}
<svelte:component this={Star} size={32} fill="var(--accent-primary)" color="var(--accent-primary)" />
{:else if favoritesPreferences.custom_icon_preset === 'music'}
<Music size={32} color="var(--accent-primary)" />
{:else if favoritesPreferences.custom_icon_preset === 'folder'}
<svelte:component this={Folder} size={32} color="var(--accent-primary)" />
{:else if favoritesPreferences.custom_icon_preset === 'disc'}
<Disc3 size={32} color="var(--accent-primary)" />
{:else if favoritesPreferences.custom_icon_preset === 'library'}
<svelte:component this={Library} size={32} color="var(--accent-primary)" />
{/if}
{:else}
<Heart size={32} fill="var(--accent-primary)" color="var(--accent-primary)" />
{/if}
</div> </div>
<div class="header-content"> <div class="header-content">
<h1>Favorites</h1> <h1>Favorites</h1>
<p class="subtitle">Your liked tracks, albums, and artists</p> <p class="subtitle">Your liked tracks, albums, and artists</p>
</div> </div>
</div> <button class="edit-btn" onclick={() => editModalOpen = true} title="Edit Favorites settings">
<Edit3 size={16} />
<!-- Tabs -->
<div class="tabs">
<button
class="tab"
class:active={activeTab === 'tracks'}
onclick={() => handleTabChange('tracks')}
>
<Music size={16} />
<span>Tracks</span>
</button>
<button
class="tab"
class:active={activeTab === 'albums'}
onclick={() => handleTabChange('albums')}
>
<Disc3 size={16} />
<span>Albums</span>
</button>
<button
class="tab"
class:active={activeTab === 'artists'}
onclick={() => handleTabChange('artists')}
>
<Mic2 size={16} />
<span>Artists</span>
</button>
<button
class="tab"
class:active={activeTab === 'playlists'}
onclick={() => handleTabChange('playlists')}
>
<ListMusic size={16} />
<span>Playlists</span>
</button> </button>
</div> </div>
<!-- Toolbar with search and actions --> <!-- Navigation Bar (Artist-style) -->
<div class="toolbar"> <div class="favorites-nav">
<!-- Search input --> <div class="nav-left">
<div class="search-container"> {#each favoritesPreferences.tab_order as tab}
<Search size={16} class="search-icon" /> <button
{#if activeTab === 'tracks'} class="nav-link"
<input class:active={activeTab === tab}
type="text" onclick={() => handleTabChange(tab as TabType)}
placeholder="Search tracks..." >
bind:value={trackSearch} <svelte:component this={getTabIcon(tab as TabType)} size={16} />
class="search-input" <span>{getTabLabel(tab as TabType)}</span>
/>
{#if trackSearch}
<button class="search-clear" onclick={() => trackSearch = ''}>
<X size={14} />
</button> </button>
{/if} {/each}
{:else if activeTab === 'albums'} </div>
<input <div class="nav-right">
type="text" {#if !searchExpanded}
placeholder="Search albums..." <button class="search-icon-btn" onclick={() => searchExpanded = true} title="Search">
bind:value={albumSearch} <Search size={16} />
class="search-input"
/>
{#if albumSearch}
<button class="search-clear" onclick={() => albumSearch = ''}>
<X size={14} />
</button> </button>
{/if}
{:else if activeTab === 'artists'}
<input
type="text"
placeholder="Search artists..."
bind:value={artistSearch}
class="search-input"
/>
{#if artistSearch}
<button class="search-clear" onclick={() => artistSearch = ''}>
<X size={14} />
</button>
{/if}
{:else} {:else}
<div class="search-expanded">
<Search size={16} class="search-icon-inline" />
<input <input
type="text" type="text"
placeholder="Search playlists..." placeholder={`Search ${getTabLabel(activeTab).toLowerCase()}...`}
bind:value={playlistSearch} value={getCurrentSearchValue()}
class="search-input" oninput={(e) => setCurrentSearchValue(e.currentTarget.value)}
class="search-input-inline"
autofocus
/> />
{#if playlistSearch} {#if getCurrentSearchValue()}
<button class="search-clear" onclick={() => playlistSearch = ''}> <button class="search-clear-btn" onclick={clearCurrentSearch} title="Clear">
<X size={14} /> <X size={14} />
</button> </button>
{/if} {/if}
</div>
{/if} {/if}
</div> </div>
</div>
<!-- Toolbar with actions -->
<div class="toolbar">
{#if activeTab === 'albums'} {#if activeTab === 'albums'}
<div class="toolbar-controls"> <div class="toolbar-controls">
<div class="dropdown-container"> <div class="dropdown-container">
@@ -890,7 +1034,7 @@
<div class="error"> <div class="error">
<p>Failed to load favorites</p> <p>Failed to load favorites</p>
<p class="error-detail">{error}</p> <p class="error-detail">{error}</p>
<button class="retry-btn" onclick={() => loadFavorites(activeTab)}>Retry</button> <button class="retry-btn" onclick={() => loadTabIfNeeded(activeTab)}>Retry</button>
</div> </div>
{:else if activeTab === 'tracks'} {:else if activeTab === 'tracks'}
{#if favoriteTracks.length === 0} {#if favoriteTracks.length === 0}
@@ -941,6 +1085,7 @@
{@const globalIndex = trackIndexMap.get(track.id) ?? index} {@const globalIndex = trackIndexMap.get(track.id) ?? index}
{@const displayTrack = buildDisplayTrack(track, globalIndex)} {@const displayTrack = buildDisplayTrack(track, globalIndex)}
{@const downloadInfo = getTrackDownloadStatus?.(track.id) ?? { status: 'none' as const, progress: 0 }} {@const downloadInfo = getTrackDownloadStatus?.(track.id) ?? { status: 'none' as const, progress: 0 }}
{@const isActiveTrack = isPlaybackActive && activeTrackId === track.id}
<TrackRow <TrackRow
trackId={track.id} trackId={track.id}
number={track.track_number || index + 1} number={track.track_number || index + 1}
@@ -948,6 +1093,7 @@
artist={track.performer?.name} artist={track.performer?.name}
duration={formatDuration(track.duration)} duration={formatDuration(track.duration)}
quality={getQualityLabel(track)} quality={getQualityLabel(track)}
isPlaying={isActiveTrack}
isFavoriteOverride={true} isFavoriteOverride={true}
downloadStatus={downloadInfo.status} downloadStatus={downloadInfo.status}
downloadProgress={downloadInfo.progress} downloadProgress={downloadInfo.progress}
@@ -990,6 +1136,7 @@
{#each filteredTracks as track, index (`${track.id}-${downloadStateVersion}`)} {#each filteredTracks as track, index (`${track.id}-${downloadStateVersion}`)}
{@const displayTrack = buildDisplayTrack(track, index)} {@const displayTrack = buildDisplayTrack(track, index)}
{@const downloadInfo = getTrackDownloadStatus?.(track.id) ?? { status: 'none' as const, progress: 0 }} {@const downloadInfo = getTrackDownloadStatus?.(track.id) ?? { status: 'none' as const, progress: 0 }}
{@const isActiveTrack = isPlaybackActive && activeTrackId === track.id}
<TrackRow <TrackRow
trackId={track.id} trackId={track.id}
number={index + 1} number={index + 1}
@@ -997,6 +1144,7 @@
artist={track.performer?.name} artist={track.performer?.name}
duration={formatDuration(track.duration)} duration={formatDuration(track.duration)}
quality={getQualityLabel(track)} quality={getQualityLabel(track)}
isPlaying={isActiveTrack}
isFavoriteOverride={true} isFavoriteOverride={true}
downloadStatus={downloadInfo.status} downloadStatus={downloadInfo.status}
downloadProgress={downloadInfo.progress} downloadProgress={downloadInfo.progress}
@@ -1281,6 +1429,13 @@
</div> </div>
</div> </div>
<FavoritesEditModal
isOpen={editModalOpen}
onClose={() => editModalOpen = false}
onSave={handlePreferencesSaved}
initialPreferences={favoritesPreferences}
/>
<style> <style>
.favorites-view { .favorites-view {
padding: 24px; padding: 24px;
@@ -1313,6 +1468,7 @@
align-items: center; align-items: center;
gap: 20px; gap: 20px;
margin-bottom: 32px; margin-bottom: 32px;
position: relative;
} }
.header-icon { .header-icon {
@@ -1323,6 +1479,17 @@
justify-content: center; justify-content: center;
background: linear-gradient(135deg, var(--accent-primary) 0%, #ff6b9d 100%); background: linear-gradient(135deg, var(--accent-primary) 0%, #ff6b9d 100%);
border-radius: 16px; border-radius: 16px;
overflow: hidden;
}
.custom-icon-img {
width: 100%;
height: 100%;
object-fit: cover;
}
.header-content {
flex: 1;
} }
.header-content h1 { .header-content h1 {
@@ -1338,37 +1505,147 @@
margin: 0; margin: 0;
} }
.tabs { .edit-btn {
display: flex; position: absolute;
gap: 8px; top: 0;
margin-bottom: 24px; right: 0;
border-bottom: 1px solid var(--bg-tertiary); width: 36px;
padding-bottom: 16px; height: 36px;
}
.tab {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 8px; justify-content: center;
padding: 10px 20px; background: transparent;
background: none;
border: none; border: none;
border-radius: 8px; color: var(--text-secondary);
color: var(--text-muted);
font-size: 14px;
font-weight: 500;
cursor: pointer; cursor: pointer;
transition: all 150ms ease; transition: all 150ms ease;
} }
.tab:hover { .edit-btn:hover {
color: var(--text-primary); color: var(--accent-primary);
background-color: var(--bg-tertiary);
} }
.tab.active { .favorites-nav {
position: sticky;
top: -24px;
z-index: 4;
display: flex;
justify-content: space-between;
align-items: center;
gap: 10px;
padding: 12px 24px;
margin: 0 -32px 16px -32px;
background-color: var(--bg-primary);
border-bottom: 1px solid var(--bg-tertiary);
}
.nav-left {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 20px;
}
.nav-link {
display: flex;
align-items: center;
gap: 6px;
padding: 4px 0;
border: none;
background: none;
color: var(--text-muted);
font-size: 13px;
cursor: pointer;
border-bottom: 2px solid transparent;
transition: color 150ms ease, border-color 150ms ease;
}
.nav-link:hover {
color: var(--text-secondary);
}
.nav-link.active {
color: var(--text-primary); color: var(--text-primary);
background-color: var(--bg-tertiary); border-bottom-color: var(--accent-primary);
}
.nav-right {
display: flex;
align-items: center;
gap: 8px;
}
.search-icon-btn {
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
border: none;
background: none;
color: var(--text-muted);
cursor: pointer;
border-radius: 6px;
transition: all 150ms ease;
}
.search-icon-btn:hover {
color: var(--text-primary);
background: var(--bg-tertiary);
}
.search-expanded {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 12px;
background: var(--bg-secondary);
border: 1px solid var(--bg-tertiary);
border-radius: 8px;
min-width: 240px;
}
.search-icon-inline {
color: var(--text-muted);
flex-shrink: 0;
}
.search-input-inline {
flex: 1;
background: none;
border: none;
outline: none;
color: var(--text-primary);
font-size: 13px;
}
.search-input-inline::placeholder {
color: var(--text-muted);
}
.search-clear-btn {
display: flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
border: none;
background: none;
color: var(--text-muted);
cursor: pointer;
border-radius: 4px;
transition: all 150ms ease;
flex-shrink: 0;
}
.search-clear-btn:hover {
color: var(--text-primary);
background: var(--bg-tertiary);
}
.search-clear-btn:hover {
color: var(--text-primary);
background: var(--bg-tertiary);
} }
.toolbar { .toolbar {
+55 -3
View File
@@ -15,6 +15,7 @@
type HomeSettings, type HomeSettings,
type HomeSectionId type HomeSectionId
} from '$lib/stores/homeSettingsStore'; } from '$lib/stores/homeSettingsStore';
import { setPlaybackContext } from '$lib/stores/playbackContextStore';
import type { QobuzAlbum, QobuzArtist, QobuzTrack, DisplayTrack } from '$lib/types'; import type { QobuzAlbum, QobuzArtist, QobuzTrack, DisplayTrack } from '$lib/types';
interface TopArtistSeed { interface TopArtistSeed {
@@ -60,6 +61,8 @@
downloadStateVersion?: number; downloadStateVersion?: number;
onArtistClick?: (artistId: number) => void; onArtistClick?: (artistId: number) => void;
onTrackPlay?: (track: DisplayTrack) => void; onTrackPlay?: (track: DisplayTrack) => void;
activeTrackId?: number | null;
isPlaybackActive?: boolean;
} }
let { let {
@@ -76,7 +79,9 @@
checkAlbumFullyDownloaded, checkAlbumFullyDownloaded,
downloadStateVersion, downloadStateVersion,
onArtistClick, onArtistClick,
onTrackPlay onTrackPlay,
activeTrackId = null,
isPlaybackActive = false
}: Props = $props(); }: Props = $props();
// Home settings state // Home settings state
@@ -334,6 +339,51 @@
return formatQuality(track.hires, track.bitDepth, track.samplingRate); return formatQuality(track.hires, track.bitDepth, track.samplingRate);
} }
function buildContinueQueueTracks(tracks: DisplayTrack[]) {
return tracks.map(t => ({
id: t.id,
title: t.title,
artist: t.artist || 'Unknown Artist',
album: t.album || '',
duration_secs: t.durationSeconds,
artwork_url: t.albumArt || '',
hires: t.hires ?? false,
bit_depth: t.bitDepth ?? null,
sample_rate: t.samplingRate ?? null,
}));
}
async function handleContinueTrackPlay(track: DisplayTrack, trackIndex: number) {
// Create continue listening context
if (continueTracks.length > 0) {
const trackIds = continueTracks.map(t => t.id);
setPlaybackContext(
'home_list',
'continue_listening',
'Continue Listening',
'qobuz',
trackIds,
trackIndex
);
console.log(`[Home] Context created: Continue Listening, ${trackIds.length} tracks, starting at ${trackIndex}`);
}
if (continueTracks.length > 0) {
try {
const queueTracks = buildContinueQueueTracks(continueTracks);
await invoke('set_queue', { tracks: queueTracks, startIndex: trackIndex });
} catch (err) {
console.error('Failed to set queue:', err);
}
}
// Play track
if (onTrackPlay) {
onTrackPlay(track);
}
}
function buildTopArtistSeedsFromTracks(tracks: DisplayTrack[]): TopArtistSeed[] { function buildTopArtistSeedsFromTracks(tracks: DisplayTrack[]): TopArtistSeed[] {
const counts = new Map<number, number>(); const counts = new Map<number, number>();
for (const track of tracks) { for (const track of tracks) {
@@ -729,6 +779,7 @@
</div> </div>
<div class="track-list compact"> <div class="track-list compact">
{#each continueTracks as track, index} {#each continueTracks as track, index}
{@const isActiveTrack = isPlaybackActive && activeTrackId === track.id}
<TrackRow <TrackRow
trackId={track.id} trackId={track.id}
number={index + 1} number={index + 1}
@@ -737,13 +788,14 @@
album={track.album} album={track.album}
duration={track.duration} duration={track.duration}
quality={getTrackQuality(track)} quality={getTrackQuality(track)}
isPlaying={isActiveTrack}
hideDownload={true} hideDownload={true}
compact={true} compact={true}
onArtistClick={track.artistId && onArtistClick ? () => onArtistClick(track.artistId!) : undefined} onArtistClick={track.artistId && onArtistClick ? () => onArtistClick(track.artistId!) : undefined}
onAlbumClick={track.albumId && onAlbumClick ? () => onAlbumClick(track.albumId!) : undefined} onAlbumClick={track.albumId && onAlbumClick ? () => onAlbumClick(track.albumId!) : undefined}
onPlay={() => onTrackPlay?.(track)} onPlay={() => handleContinueTrackPlay(track, index)}
menuActions={{ menuActions={{
onPlayNow: () => onTrackPlay?.(track) onPlayNow: () => handleContinueTrackPlay(track, index)
}} }}
/> />
{/each} {/each}
@@ -131,6 +131,8 @@
onTrackPlayLater?: (track: LocalTrack) => void; onTrackPlayLater?: (track: LocalTrack) => void;
onTrackAddToPlaylist?: (trackId: number) => void; onTrackAddToPlaylist?: (trackId: number) => void;
onSetLocalQueue?: (trackIds: number[]) => void; onSetLocalQueue?: (trackIds: number[]) => void;
activeTrackId?: number | null;
isPlaybackActive?: boolean;
} }
let { let {
@@ -140,7 +142,9 @@
onTrackPlayNext, onTrackPlayNext,
onTrackPlayLater, onTrackPlayLater,
onTrackAddToPlaylist, onTrackAddToPlaylist,
onSetLocalQueue onSetLocalQueue,
activeTrackId = null,
isPlaybackActive = false
}: Props = $props(); }: Props = $props();
// View state // View state
@@ -710,6 +714,15 @@
async function handleTrackPlay(track: LocalTrack) { async function handleTrackPlay(track: LocalTrack) {
try { try {
if (selectedAlbum && albumTracks.length > 0) {
const trackIndex = albumTracks.findIndex(t => t.id === track.id);
await setQueueForAlbumTracks(albumTracks, trackIndex >= 0 ? trackIndex : 0);
} else if (activeTab === 'tracks' && tracks.length > 0) {
const orderedTracks = getDisplayedTrackOrder();
const trackIndex = orderedTracks.findIndex(t => t.id === track.id);
await setQueueForLocalTracks(orderedTracks, trackIndex >= 0 ? trackIndex : 0);
}
await invoke('library_play_track', { trackId: track.id }); await invoke('library_play_track', { trackId: track.id });
onTrackPlay?.(track); onTrackPlay?.(track);
} catch (err) { } catch (err) {
@@ -722,7 +735,6 @@
if (!selectedAlbum || albumTracks.length === 0) return; if (!selectedAlbum || albumTracks.length === 0) return;
try { try {
await setQueueForAlbumTracks(albumTracks);
await handleTrackPlay(albumTracks[0]); await handleTrackPlay(albumTracks[0]);
} catch (err) { } catch (err) {
console.error('Failed to play album:', err); console.error('Failed to play album:', err);
@@ -740,7 +752,7 @@
} }
} }
async function setQueueForAlbumTracks(tracks: LocalTrack[]) { async function setQueueForLocalTracks(tracks: LocalTrack[], startIndex = 0) {
const queueTracks = tracks.map(t => ({ const queueTracks = tracks.map(t => ({
id: t.id, id: t.id,
title: t.title, title: t.title,
@@ -753,10 +765,14 @@
sample_rate: t.sample_rate ?? null, sample_rate: t.sample_rate ?? null,
})); }));
await invoke('set_queue', { tracks: queueTracks, startIndex: 0 }); await invoke('set_queue', { tracks: queueTracks, startIndex });
onSetLocalQueue?.(tracks.map(t => t.id)); onSetLocalQueue?.(tracks.map(t => t.id));
} }
async function setQueueForAlbumTracks(tracks: LocalTrack[], startIndex = 0) {
await setQueueForLocalTracks(tracks, startIndex);
}
function formatDuration(seconds: number): string { function formatDuration(seconds: number): string {
const mins = Math.floor(seconds / 60); const mins = Math.floor(seconds / 60);
const secs = seconds % 60; const secs = seconds % 60;
@@ -1424,6 +1440,22 @@
tracks: groups.get(key)?.tracks ?? [] tracks: groups.get(key)?.tracks ?? []
})); }));
} }
function getDisplayedTrackOrder(): LocalTrack[] {
if (!trackGroupingEnabled) return tracks;
const grouped = groupTracks(tracks, trackGroupMode);
if (trackGroupMode === 'album') {
const ordered: LocalTrack[] = [];
for (const group of grouped) {
const sections = buildAlbumSections(group.tracks);
for (const section of sections) {
ordered.push(...section.tracks);
}
}
return ordered;
}
return grouped.flatMap(group => group.tracks);
}
</script> </script>
<div class="library-view"> <div class="library-view">
@@ -1499,6 +1531,7 @@
artist={track.artist !== selectedAlbum?.artist ? track.artist : undefined} artist={track.artist !== selectedAlbum?.artist ? track.artist : undefined}
duration={formatDuration(track.duration_secs)} duration={formatDuration(track.duration_secs)}
quality={getQualityBadge(track)} quality={getQualityBadge(track)}
isPlaying={isPlaybackActive && activeTrackId === track.id}
isLocal={true} isLocal={true}
hideDownload={true} hideDownload={true}
hideFavorite={true} hideFavorite={true}
@@ -2139,6 +2172,7 @@
artist={track.artist} artist={track.artist}
duration={formatDuration(track.duration_secs)} duration={formatDuration(track.duration_secs)}
quality={getQualityBadge(track)} quality={getQualityBadge(track)}
isPlaying={isPlaybackActive && activeTrackId === track.id}
isLocal={true} isLocal={true}
hideDownload={true} hideDownload={true}
hideFavorite={true} hideFavorite={true}
@@ -2162,6 +2196,7 @@
artist={track.artist} artist={track.artist}
duration={formatDuration(track.duration_secs)} duration={formatDuration(track.duration_secs)}
quality={getQualityBadge(track)} quality={getQualityBadge(track)}
isPlaying={isPlaybackActive && activeTrackId === track.id}
isLocal={true} isLocal={true}
hideDownload={true} hideDownload={true}
hideFavorite={true} hideFavorite={true}
@@ -13,8 +13,9 @@
getStatus as getOfflineStatus, getStatus as getOfflineStatus,
type OfflineStatus type OfflineStatus
} from '$lib/stores/offlineStore'; } from '$lib/stores/offlineStore';
import { consumeContextTrackFocus, setPlaybackContext } from '$lib/stores/playbackContextStore';
import { t } from '$lib/i18n'; import { t } from '$lib/i18n';
import { onMount } from 'svelte'; import { onMount, tick } from 'svelte';
interface PlaylistTrack { interface PlaylistTrack {
id: number; id: number;
@@ -181,6 +182,7 @@
let loading = $state(true); let loading = $state(true);
let error = $state<string | null>(null); let error = $state<string | null>(null);
let playBtnHovered = $state(false); let playBtnHovered = $state(false);
let scrollContainer: HTMLDivElement | null = $state(null);
// Offline mode state // Offline mode state
let offlineStatus = $state<OfflineStatus>(getOfflineStatus()); let offlineStatus = $state<OfflineStatus>(getOfflineStatus());
@@ -197,6 +199,12 @@
let editModalOpen = $state(false); let editModalOpen = $state(false);
let isFavorite = $state(false); let isFavorite = $state(false);
async function scrollToTrack(trackId: number) {
await tick();
const target = scrollContainer?.querySelector<HTMLElement>(`[data-track-id="${trackId}"]`);
target?.scrollIntoView({ block: 'center' });
}
// Subscribe to offline status changes // Subscribe to offline status changes
onMount(() => { onMount(() => {
const unsubscribe = subscribeOffline(() => { const unsubscribe = subscribeOffline(() => {
@@ -209,6 +217,14 @@
return unsubscribe; return unsubscribe;
}); });
$effect(() => {
if (!playlist || displayTracks.length === 0) return;
const targetId = consumeContextTrackFocus('playlist', playlist.id.toString());
if (targetId !== null) {
void scrollToTrack(targetId);
}
});
// Check if a track is available (has local copy when offline, always available when online) // Check if a track is available (has local copy when offline, always available when online)
function isTrackAvailable(track: DisplayTrack): boolean { function isTrackAvailable(track: DisplayTrack): boolean {
if (!offlineStatus.isOffline) return true; if (!offlineStatus.isOffline) return true;
@@ -528,7 +544,66 @@
return ''; return '';
} }
function handleTrackClick(track: DisplayTrack) { function buildQueueTracks(tracks: DisplayTrack[]) {
const queueTracks = tracks.map(t => ({
id: t.isLocal ? Math.abs(t.id) : t.id,
title: t.title,
artist: t.artist || 'Unknown Artist',
album: t.album || playlist?.name || 'Playlist',
duration_secs: t.durationSeconds,
artwork_url: t.albumArt || getPlaylistImage(),
hires: t.hires ?? false,
bit_depth: t.bitDepth ?? null,
sample_rate: t.samplingRate != null ? (t.isLocal ? t.samplingRate * 1000 : t.samplingRate) : null,
is_local: t.isLocal ?? false,
}));
const localIds = tracks
.filter(t => t.isLocal)
.map(t => Math.abs(t.id));
return { queueTracks, localIds };
}
async function setPlaylistQueue(startIndex: number) {
const allTracks = displayTracks;
if (allTracks.length === 0) return;
const { queueTracks, localIds } = buildQueueTracks(allTracks);
await invoke('set_queue', { tracks: queueTracks, startIndex });
if (localIds.length > 0) {
onSetLocalQueue?.(localIds);
}
}
async function handleTrackClick(track: DisplayTrack, trackIndex: number) {
// Create playlist context before playing
if (playlist) {
const trackIds = displayTracks
.filter(t => !t.isLocal) // Only Qobuz tracks in context
.map(t => t.id);
const contextIndex = trackIds.indexOf(track.id);
if (contextIndex >= 0 && trackIds.length > 0) {
setPlaybackContext(
'playlist',
playlist.id.toString(),
playlist.name,
'qobuz',
trackIds,
contextIndex
);
console.log(`[Playlist] Context created: "${playlist.name}", ${trackIds.length} tracks, starting at ${contextIndex}`);
}
}
// Handle playback
try {
await setPlaylistQueue(trackIndex);
} catch (err) {
console.error('Failed to set queue:', err);
}
if (track.isLocal && track.localTrackId) { if (track.isLocal && track.localTrackId) {
// Handle local track play // Handle local track play
const localTrack = localTracksMap.get(track.localTrackId); const localTrack = localTracksMap.get(track.localTrackId);
@@ -590,32 +665,8 @@
const allTracks = displayTracks; const allTracks = displayTracks;
if (allTracks.length === 0) return; if (allTracks.length === 0) return;
// Build queue tracks, using absolute ID for local tracks
const queueTracks = allTracks.map(t => ({
id: t.isLocal ? Math.abs(t.id) : t.id,
title: t.title,
artist: t.artist || 'Unknown Artist',
album: t.album || playlist?.name || 'Playlist',
duration_secs: t.durationSeconds,
artwork_url: t.albumArt || getPlaylistImage(),
hires: t.hires ?? false,
bit_depth: t.bitDepth ?? null,
sample_rate: t.samplingRate != null ? (t.isLocal ? t.samplingRate * 1000 : t.samplingRate) : null,
is_local: t.isLocal ?? false,
}));
// Collect local track IDs (original positive IDs)
const localIds = allTracks
.filter(t => t.isLocal)
.map(t => Math.abs(t.id));
try { try {
await invoke('set_queue', { tracks: queueTracks, startIndex: 0 }); await setPlaylistQueue(0);
// Tell parent about local tracks in queue
if (localIds.length > 0) {
onSetLocalQueue?.(localIds);
}
// Play first track (handle local vs Qobuz) // Play first track (handle local vs Qobuz)
const firstTrack = allTracks[0]; const firstTrack = allTracks[0];
@@ -745,7 +796,7 @@
} }
</script> </script>
<div class="playlist-detail"> <div class="playlist-detail" bind:this={scrollContainer}>
<!-- Navigation Row --> <!-- Navigation Row -->
<div class="nav-row"> <div class="nav-row">
<button class="back-btn" onclick={onBack}> <button class="back-btn" onclick={onBack}>
@@ -953,11 +1004,11 @@
hideDownload={track.isLocal} hideDownload={track.isLocal}
downloadStatus={downloadInfo.status} downloadStatus={downloadInfo.status}
downloadProgress={downloadInfo.progress} downloadProgress={downloadInfo.progress}
onPlay={available ? () => handleTrackClick(track) : undefined} onPlay={available ? () => handleTrackClick(track, idx) : undefined}
onDownload={available && !track.isLocal && onTrackDownload ? () => onTrackDownload(track) : undefined} onDownload={available && !track.isLocal && onTrackDownload ? () => onTrackDownload(track) : undefined}
onRemoveDownload={available && !track.isLocal && onTrackRemoveDownload ? () => onTrackRemoveDownload(track.id) : undefined} onRemoveDownload={available && !track.isLocal && onTrackRemoveDownload ? () => onTrackRemoveDownload(track.id) : undefined}
menuActions={available ? { menuActions={available ? {
onPlayNow: () => handleTrackClick(track), onPlayNow: () => handleTrackClick(track, idx),
onPlayNext: track.isLocal ? () => handleTrackPlayNext(track) : (onTrackPlayNext ? () => onTrackPlayNext(track) : undefined), onPlayNext: track.isLocal ? () => handleTrackPlayNext(track) : (onTrackPlayNext ? () => onTrackPlayNext(track) : undefined),
onPlayLater: track.isLocal ? () => handleTrackPlayLater(track) : (onTrackPlayLater ? () => onTrackPlayLater(track) : undefined), onPlayLater: track.isLocal ? () => handleTrackPlayLater(track) : (onTrackPlayLater ? () => onTrackPlayLater(track) : undefined),
onAddToPlaylist: !track.isLocal && onTrackAddToPlaylist ? () => onTrackAddToPlaylist(track.id) : undefined, onAddToPlaylist: !track.isLocal && onTrackAddToPlaylist ? () => onTrackAddToPlaylist(track.id) : undefined,
+231 -10
View File
@@ -1,10 +1,12 @@
<script lang="ts"> <script lang="ts">
import { onMount, tick } from 'svelte'; import { onMount, tick } from 'svelte';
import { invoke } from '@tauri-apps/api/core'; import { invoke } from '@tauri-apps/api/core';
import { Search, Disc3, Music, Mic2, User, X, ChevronLeft, ChevronRight, Crown } from 'lucide-svelte'; import { Search, Disc3, Music, Mic2, User, X, ChevronLeft, ChevronRight, Crown, Pause } from 'lucide-svelte';
import AlbumCard from '../AlbumCard.svelte'; import AlbumCard from '../AlbumCard.svelte';
import TrackMenu from '../TrackMenu.svelte'; import TrackMenu from '../TrackMenu.svelte';
import { getSearchState, setSearchState, type SearchResults, type SearchAllResults, type SearchTab } from '$lib/stores/searchState'; import { getSearchState, setSearchState, type SearchResults, type SearchAllResults, type SearchTab } from '$lib/stores/searchState';
import { setPlaybackContext } from '$lib/stores/playbackContextStore';
import { togglePlay } from '$lib/stores/playerStore';
import { t } from '$lib/i18n'; import { t } from '$lib/i18n';
let searchInput: HTMLInputElement | null = null; let searchInput: HTMLInputElement | null = null;
@@ -86,6 +88,8 @@
onTrackGoToAlbum?: (albumId: string) => void; onTrackGoToAlbum?: (albumId: string) => void;
onTrackGoToArtist?: (artistId: number) => void; onTrackGoToArtist?: (artistId: number) => void;
onArtistClick?: (artistId: number) => void; onArtistClick?: (artistId: number) => void;
activeTrackId?: number | null;
isPlaybackActive?: boolean;
} }
let { let {
@@ -109,7 +113,9 @@
onTrackShareSonglink, onTrackShareSonglink,
onTrackGoToAlbum, onTrackGoToAlbum,
onTrackGoToArtist, onTrackGoToArtist,
onArtistClick onArtistClick,
activeTrackId = null,
isPlaybackActive = false
}: Props = $props(); }: Props = $props();
interface Album { interface Album {
@@ -375,6 +381,56 @@
return track.album?.image?.large || track.album?.image?.thumbnail || track.album?.image?.small || ''; return track.album?.image?.large || track.album?.image?.thumbnail || track.album?.image?.small || '';
} }
function buildSearchQueueTracks(tracks: Track[]) {
return tracks.map(t => ({
id: t.id,
title: t.title,
artist: t.performer?.name || 'Unknown Artist',
album: t.album?.title || '',
duration_secs: t.duration,
artwork_url: t.album?.image?.large || t.album?.image?.thumbnail || t.album?.image?.small || '',
hires: t.hires_streamable ?? false,
bit_depth: t.maximum_bit_depth ?? null,
sample_rate: t.maximum_sampling_rate ?? null,
}));
}
async function handleSearchTrackPlay(track: Track, trackIndex: number) {
// Create search results context
if (trackResults && trackResults.items.length > 0) {
const trackIds = trackResults.items.map(t => t.id);
setPlaybackContext(
'search',
currentQuery,
`Search: ${currentQuery}`,
'qobuz',
trackIds,
trackIndex
);
console.log(`[Search] Context created: "${currentQuery}", ${trackIds.length} tracks, starting at ${trackIndex}`);
}
if (trackResults && trackResults.items.length > 0) {
try {
const queueTracks = buildSearchQueueTracks(trackResults.items);
await invoke('set_queue', { tracks: queueTracks, startIndex: trackIndex });
} catch (err) {
console.error('Failed to set queue:', err);
}
}
// Play track
if (onTrackPlay) {
onTrackPlay(track);
}
}
function handlePausePlayback(event: MouseEvent) {
event.stopPropagation();
void togglePlay();
}
function getArtistImage(artist: Artist): string { function getArtistImage(artist: Artist): string {
return artist.image?.large || artist.image?.thumbnail || artist.image?.small || ''; return artist.image?.large || artist.image?.thumbnail || artist.image?.small || '';
} }
@@ -721,29 +777,74 @@
</div> </div>
<div class="tracks-list-compact"> <div class="tracks-list-compact">
{#each allResults.tracks.items.slice(0, 6) as track, index} {#each allResults.tracks.items.slice(0, 6) as track, index}
{@const isActiveTrack = isPlaybackActive && activeTrackId === track.id}
<div <div
class="track-row" class="track-row"
class:playing={isActiveTrack}
role="button" role="button"
tabindex="0" tabindex="0"
onclick={() => onTrackPlay?.(track)} onclick={() => handleSearchTrackPlay(track, index)}
onkeydown={(e) => e.key === 'Enter' && onTrackPlay?.(track)} onkeydown={(e) => e.key === 'Enter' && handleSearchTrackPlay(track, index)}
> >
<div class="track-number">{index + 1}</div> <div class="track-number">{index + 1}</div>
{#if failedTrackImages.has(track.id) || !getTrackArtwork(track)} {#if failedTrackImages.has(track.id) || !getTrackArtwork(track)}
<div class="track-artwork-container">
<div class="track-artwork-placeholder"> <div class="track-artwork-placeholder">
<Music size={20} /> <Music size={20} />
</div> </div>
<button
class="track-play-overlay"
class:is-playing={isActiveTrack}
onclick={(e) => {
if (isActiveTrack) {
handlePausePlayback(e);
} else {
e.stopPropagation();
handleSearchTrackPlay(track, index);
}
}}
aria-label={isActiveTrack ? 'Pause track' : 'Play track'}
>
<span class="play-icon" aria-hidden="true">
<svg width="24" height="24" viewBox="0 0 24 24" fill="white">
<path d="M8 5v14l11-7z"/>
</svg>
</span>
<div class="playing-indicator" aria-hidden="true">
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
</div>
<Pause size={20} class="pause-icon" aria-hidden="true" />
</button>
</div>
{:else} {:else}
<div class="track-artwork-container"> <div class="track-artwork-container">
<img src={getTrackArtwork(track)} alt={track.title} class="track-artwork" onerror={() => handleTrackImageError(track.id)} /> <img src={getTrackArtwork(track)} alt={track.title} class="track-artwork" onerror={() => handleTrackImageError(track.id)} />
<button <button
class="track-play-overlay" class="track-play-overlay"
onclick={(e) => { e.stopPropagation(); onTrackPlay?.(track); }} class:is-playing={isActiveTrack}
aria-label="Play track" onclick={(e) => {
if (isActiveTrack) {
handlePausePlayback(e);
} else {
e.stopPropagation();
handleSearchTrackPlay(track, index);
}
}}
aria-label={isActiveTrack ? 'Pause track' : 'Play track'}
> >
<span class="play-icon" aria-hidden="true">
<svg width="24" height="24" viewBox="0 0 24 24" fill="white"> <svg width="24" height="24" viewBox="0 0 24 24" fill="white">
<path d="M8 5v14l11-7z"/> <path d="M8 5v14l11-7z"/>
</svg> </svg>
</span>
<div class="playing-indicator" aria-hidden="true">
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
</div>
<Pause size={20} class="pause-icon" aria-hidden="true" />
</button> </button>
</div> </div>
{/if} {/if}
@@ -768,7 +869,7 @@
<div class="track-duration">{formatDuration(track.duration)}</div> <div class="track-duration">{formatDuration(track.duration)}</div>
<div class="track-actions"> <div class="track-actions">
<TrackMenu <TrackMenu
onPlayNow={() => onTrackPlay?.(track)} onPlayNow={() => handleSearchTrackPlay(track, index)}
onPlayNext={onTrackPlayNext ? () => onTrackPlayNext(track) : undefined} onPlayNext={onTrackPlayNext ? () => onTrackPlayNext(track) : undefined}
onPlayLater={onTrackPlayLater ? () => onTrackPlayLater(track) : undefined} onPlayLater={onTrackPlayLater ? () => onTrackPlayLater(track) : undefined}
onAddFavorite={onTrackAddFavorite ? () => onTrackAddFavorite(track.id) : undefined} onAddFavorite={onTrackAddFavorite ? () => onTrackAddFavorite(track.id) : undefined}
@@ -826,20 +927,76 @@
{:else} {:else}
<div class="tracks-list"> <div class="tracks-list">
{#each trackResults.items as track, index} {#each trackResults.items as track, index}
{@const isActiveTrack = isPlaybackActive && activeTrackId === track.id}
<div <div
class="track-row" class="track-row"
class:playing={isActiveTrack}
role="button" role="button"
tabindex="0" tabindex="0"
onclick={() => onTrackPlay?.(track)} onclick={() => handleSearchTrackPlay(track, index)}
onkeydown={(e) => e.key === 'Enter' && onTrackPlay?.(track)} onkeydown={(e) => e.key === 'Enter' && handleSearchTrackPlay(track, index)}
> >
<div class="track-number">{index + 1}</div> <div class="track-number">{index + 1}</div>
{#if failedTrackImages.has(track.id) || !getTrackArtwork(track)} {#if failedTrackImages.has(track.id) || !getTrackArtwork(track)}
<div class="track-artwork-container">
<div class="track-artwork-placeholder"> <div class="track-artwork-placeholder">
<Music size={20} /> <Music size={20} />
</div> </div>
<button
class="track-play-overlay"
class:is-playing={isActiveTrack}
onclick={(e) => {
if (isActiveTrack) {
handlePausePlayback(e);
} else {
e.stopPropagation();
handleSearchTrackPlay(track, index);
}
}}
aria-label={isActiveTrack ? 'Pause track' : 'Play track'}
>
<span class="play-icon" aria-hidden="true">
<svg width="24" height="24" viewBox="0 0 24 24" fill="white">
<path d="M8 5v14l11-7z"/>
</svg>
</span>
<div class="playing-indicator" aria-hidden="true">
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
</div>
<Pause size={20} class="pause-icon" aria-hidden="true" />
</button>
</div>
{:else} {:else}
<div class="track-artwork-container">
<img src={getTrackArtwork(track)} alt={track.title} class="track-artwork" onerror={() => handleTrackImageError(track.id)} /> <img src={getTrackArtwork(track)} alt={track.title} class="track-artwork" onerror={() => handleTrackImageError(track.id)} />
<button
class="track-play-overlay"
class:is-playing={isActiveTrack}
onclick={(e) => {
if (isActiveTrack) {
handlePausePlayback(e);
} else {
e.stopPropagation();
handleSearchTrackPlay(track, index);
}
}}
aria-label={isActiveTrack ? 'Pause track' : 'Play track'}
>
<span class="play-icon" aria-hidden="true">
<svg width="24" height="24" viewBox="0 0 24 24" fill="white">
<path d="M8 5v14l11-7z"/>
</svg>
</span>
<div class="playing-indicator" aria-hidden="true">
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
</div>
<Pause size={20} class="pause-icon" aria-hidden="true" />
</button>
</div>
{/if} {/if}
<div class="track-info"> <div class="track-info">
<div class="track-title">{track.title}</div> <div class="track-title">{track.title}</div>
@@ -862,7 +1019,7 @@
<div class="track-duration">{formatDuration(track.duration)}</div> <div class="track-duration">{formatDuration(track.duration)}</div>
<div class="track-actions"> <div class="track-actions">
<TrackMenu <TrackMenu
onPlayNow={() => onTrackPlay?.(track)} onPlayNow={() => handleSearchTrackPlay(track, index)}
onPlayNext={onTrackPlayNext ? () => onTrackPlayNext(track) : undefined} onPlayNext={onTrackPlayNext ? () => onTrackPlayNext(track) : undefined}
onPlayLater={onTrackPlayLater ? () => onTrackPlayLater(track) : undefined} onPlayLater={onTrackPlayLater ? () => onTrackPlayLater(track) : undefined}
onAddFavorite={onTrackAddFavorite ? () => onTrackAddFavorite(track.id) : undefined} onAddFavorite={onTrackAddFavorite ? () => onTrackAddFavorite(track.id) : undefined}
@@ -1590,10 +1747,74 @@
display: flex; display: flex;
} }
.track-row.playing .track-play-overlay {
display: flex;
}
.track-play-overlay:hover { .track-play-overlay:hover {
background: rgba(0, 0, 0, 0.75); background: rgba(0, 0, 0, 0.75);
} }
.track-play-overlay .playing-indicator,
.track-play-overlay .pause-icon {
display: none;
}
.track-row.playing .track-play-overlay .play-icon {
display: none;
}
.track-row.playing .track-play-overlay .playing-indicator {
display: flex;
}
.track-row.playing:hover .track-play-overlay .playing-indicator {
display: none;
}
.track-row.playing:hover .track-play-overlay .pause-icon {
display: inline-flex;
}
.playing-indicator {
display: flex;
align-items: center;
gap: 2px;
}
.playing-indicator .bar {
width: 3px;
background-color: var(--accent-primary);
border-radius: 9999px;
transform-origin: bottom;
animation: search-equalize 1s ease-in-out infinite;
}
.playing-indicator .bar:nth-child(1) {
height: 10px;
}
.playing-indicator .bar:nth-child(2) {
height: 14px;
animation-delay: 0.15s;
}
.playing-indicator .bar:nth-child(3) {
height: 8px;
animation-delay: 0.3s;
}
@keyframes search-equalize {
0%, 100% {
transform: scaleY(0.5);
opacity: 0.7;
}
50% {
transform: scaleY(1);
opacity: 1;
}
}
@media (max-width: 1024px) { @media (max-width: 1024px) {
.top-section { .top-section {
grid-template-columns: 1fr; grid-template-columns: 1fr;
+147 -3
View File
@@ -43,6 +43,12 @@
type OfflineSettings type OfflineSettings
} from '$lib/stores/offlineStore'; } from '$lib/stores/offlineStore';
import { showToast } from '$lib/stores/toastStore'; import { showToast } from '$lib/stores/toastStore';
import {
getPlaybackPreferences,
setAutoplayMode,
setShowContextIcon,
type AutoplayMode
} from '$lib/stores/playbackPreferencesStore';
interface Props { interface Props {
onBack?: () => void; onBack?: () => void;
@@ -173,14 +179,32 @@
'Dark': '', 'Dark': '',
'Light': 'light', 'Light': 'light',
'OLED Black': 'oled', 'OLED Black': 'oled',
'Warm': 'warm' 'Warm': 'warm',
'Nord': 'nord',
'Dracula': 'dracula',
'Tokyo Night': 'tokyo-night',
'Catppuccin Mocha': 'catppuccin-mocha',
'Rose Pine Dawn': 'rose-pine-dawn',
'Breeze Dark': 'breeze-dark',
'Breeze Light': 'breeze-light',
'Adwaita Dark': 'adwaita-dark',
'Adwaita Light': 'adwaita-light'
}; };
const themeReverseMap: Record<string, string> = { const themeReverseMap: Record<string, string> = {
'': 'Dark', '': 'Dark',
'light': 'Light', 'light': 'Light',
'oled': 'OLED Black', 'oled': 'OLED Black',
'warm': 'Warm' 'warm': 'Warm',
'nord': 'Nord',
'dracula': 'Dracula',
'tokyo-night': 'Tokyo Night',
'catppuccin-mocha': 'Catppuccin Mocha',
'rose-pine-dawn': 'Rose Pine Dawn',
'breeze-dark': 'Breeze Dark',
'breeze-light': 'Breeze Light',
'adwaita-dark': 'Adwaita Dark',
'adwaita-light': 'Adwaita Light'
}; };
// Language mapping: display name -> locale code // Language mapping: display name -> locale code
@@ -316,6 +340,8 @@
); );
// Playback settings // Playback settings
let autoplayMode = $state<AutoplayMode>('continue');
let showContextIcon = $state(true);
let gaplessPlayback = $state(true); let gaplessPlayback = $state(true);
let crossfade = $state(0); let crossfade = $state(0);
let normalizeVolume = $state(false); let normalizeVolume = $state(false);
@@ -423,6 +449,9 @@
loadSystemNotificationsPreference(); loadSystemNotificationsPreference();
systemNotificationsEnabled = getSystemNotificationsEnabled(); systemNotificationsEnabled = getSystemNotificationsEnabled();
// Load playback preferences
loadPlaybackPreferences();
// Check for legacy downloads // Check for legacy downloads
checkLegacyDownloads(); checkLegacyDownloads();
@@ -462,6 +491,15 @@
}; };
}); });
// Reload playback preferences each time the view becomes visible
// This ensures settings are fresh when navigating back to settings
$effect(() => {
// This effect runs whenever the component is rendered
// We reload preferences to ensure they're in sync with backend
console.log('[Settings] Component rendered, reloading playback preferences');
loadPlaybackPreferences();
});
async function loadLastfmState() { async function loadLastfmState() {
try { try {
// Check if embedded (build-time) credentials are available // Check if embedded (build-time) credentials are available
@@ -1110,6 +1148,44 @@
} }
} }
async function loadPlaybackPreferences() {
console.log('[Settings] Loading playback preferences...');
try {
const prefs = await getPlaybackPreferences();
console.log('[Settings] Loaded preferences:', prefs);
autoplayMode = prefs.autoplay_mode;
showContextIcon = prefs.show_context_icon;
console.log('[Settings] Set autoplayMode to:', autoplayMode);
console.log('[Settings] Set showContextIcon to:', showContextIcon);
} catch (err) {
console.error('Failed to load playback preferences:', err);
}
}
async function handleAutoplayModeChange(mode: AutoplayMode) {
console.log('[Settings] Changing autoplay mode to:', mode);
try {
await setAutoplayMode(mode);
autoplayMode = mode;
console.log('[Settings] Autoplay mode saved successfully');
} catch (err) {
console.error('[Settings] Failed to set autoplay mode:', err);
showToast('Failed to save autoplay preference', 'error');
}
}
async function handleShowContextIconChange(show: boolean) {
console.log('[Settings] Changing show context icon to:', show);
try {
await setShowContextIcon(show);
showContextIcon = show;
console.log('[Settings] Show context icon saved successfully');
} catch (err) {
console.error('[Settings] Failed to set show context icon:', err);
showToast('Failed to save icon visibility preference', 'error');
}
}
async function checkLegacyDownloads() { async function checkLegacyDownloads() {
try { try {
const result = await invoke<{has_legacy_files: boolean, total_tracks: number}>('detect_legacy_downloads'); const result = await invoke<{has_legacy_files: boolean, total_tracks: number}>('detect_legacy_downloads');
@@ -1438,6 +1514,20 @@
<!-- Playback Section --> <!-- Playback Section -->
<section class="section" bind:this={playbackSection}> <section class="section" bind:this={playbackSection}>
<h3 class="section-title">{$t('settings.playback.title')}</h3> <h3 class="section-title">{$t('settings.playback.title')}</h3>
<div class="setting-row">
<div class="setting-info">
<span class="setting-label">{$t('settings.playback.autoplayBehavior')}</span>
<span class="setting-desc">{$t('settings.playback.autoplayBehaviorDesc')}</span>
</div>
<Toggle enabled={autoplayMode === 'continue'} onchange={(enabled) => handleAutoplayModeChange(enabled ? 'continue' : 'track_only')} />
</div>
<div class="setting-row">
<div class="label-with-tooltip">
<span class="setting-label">{$t('settings.playback.showContextIcon')}</span>
<Tooltip text={$t('settings.playback.showContextIconTooltip')} />
</div>
<Toggle enabled={showContextIcon} onchange={handleShowContextIconChange} />
</div>
<div class="setting-row"> <div class="setting-row">
<div class="label-with-tooltip"> <div class="label-with-tooltip">
<span class="setting-label">{$t('settings.playback.gapless')}</span> <span class="setting-label">{$t('settings.playback.gapless')}</span>
@@ -1538,7 +1628,21 @@
<span class="setting-label">{$t('settings.appearance.theme')}</span> <span class="setting-label">{$t('settings.appearance.theme')}</span>
<Dropdown <Dropdown
value={theme} value={theme}
options={['Dark', 'Light', 'OLED Black', 'Warm']} options={[
'Dark',
'Light',
'OLED Black',
'Warm',
'Nord',
'Dracula',
'Tokyo Night',
'Catppuccin Mocha',
'Rose Pine Dawn',
'Breeze Dark',
'Breeze Light',
'Adwaita Dark',
'Adwaita Light'
]}
onchange={handleThemeChange} onchange={handleThemeChange}
/> />
</div> </div>
@@ -2060,6 +2164,13 @@
padding: 12px 0; padding: 12px 0;
} }
.setting-row:has(.radio-group) {
height: auto;
min-height: 48px;
padding: 12px 0;
align-items: flex-start;
}
.setting-value { .setting-value {
font-size: 14px; font-size: 14px;
color: var(--text-muted); color: var(--text-muted);
@@ -2086,6 +2197,39 @@
width: 240px; width: 240px;
} }
.radio-group {
display: flex;
flex-direction: column;
gap: 8px;
}
.radio-option {
display: flex;
align-items: center;
gap: 10px;
cursor: pointer;
padding: 8px 12px;
border-radius: 6px;
transition: background 0.15s;
}
.radio-option:hover {
background: rgba(255, 255, 255, 0.05);
}
.radio-option input[type="radio"] {
width: 18px;
height: 18px;
cursor: pointer;
accent-color: var(--accent-color, #1db954);
}
.radio-option span {
font-size: 14px;
color: var(--text-primary);
user-select: none;
}
.connect-btn { .connect-btn {
padding: 8px 16px; padding: 8px 16px;
border-radius: 8px; border-radius: 8px;
+26 -2
View File
@@ -196,7 +196,25 @@
"artists": "Artists", "artists": "Artists",
"noFavorites": "No favorites yet", "noFavorites": "No favorites yet",
"addedToFavorites": "Added to favorites", "addedToFavorites": "Added to favorites",
"removedFromFavorites": "Removed from favorites" "removedFromFavorites": "Removed from favorites",
"editSettings": "Edit Favorites Settings",
"settingsModalTitle": "Favorites Settings",
"iconSectionTitle": "Icon",
"iconSectionDescription": "Choose an icon for the Favorites page header",
"uploadCustomImage": "Upload Custom Image",
"tabOrderSectionTitle": "Tab Order",
"tabOrderSectionDescription": "Reorder tabs in the Favorites page navigation",
"tabLabels": {
"tracks": "Tracks",
"albums": "Albums",
"artists": "Artists",
"playlists": "Playlists"
},
"moveUp": "Move up",
"moveDown": "Move down",
"save": "Save",
"saving": "Saving...",
"cancel": "Cancel"
}, },
"player": { "player": {
"nowPlaying": "Now Playing", "nowPlaying": "Now Playing",
@@ -311,7 +329,13 @@
"gapless": "Gapless Playback", "gapless": "Gapless Playback",
"crossfade": "Crossfade", "crossfade": "Crossfade",
"crossfadeSeconds": "{seconds}s", "crossfadeSeconds": "{seconds}s",
"normalizeVolume": "Normalize Volume" "normalizeVolume": "Normalize Volume",
"autoplayBehavior": "Continue playback after track ends",
"autoplayBehaviorDesc": "When enabled, plays next track in the source. When disabled, stops after each track",
"continueWithinSource": "Continue within source",
"playOnlySelectedTrack": "Play only selected track",
"showContextIcon": "Show track playing context in player",
"showContextIconTooltip": "Shows the context from which the current track is being played (album, artist, playlist, etc.)"
}, },
"appearance": { "appearance": {
"title": "Appearance", "title": "Appearance",
+26 -2
View File
@@ -196,7 +196,25 @@
"artists": "Artistas", "artists": "Artistas",
"noFavorites": "Aún no hay favoritos", "noFavorites": "Aún no hay favoritos",
"addedToFavorites": "Agregado a favoritos", "addedToFavorites": "Agregado a favoritos",
"removedFromFavorites": "Eliminado de favoritos" "removedFromFavorites": "Eliminado de favoritos",
"editSettings": "Editar configuracion de Favoritos",
"settingsModalTitle": "Configuracion de Favoritos",
"iconSectionTitle": "Icono",
"iconSectionDescription": "Elige un icono para el encabezado de la pagina de Favoritos",
"uploadCustomImage": "Subir imagen personalizada",
"tabOrderSectionTitle": "Orden de pestanas",
"tabOrderSectionDescription": "Reordena las pestanas en la navegacion de Favoritos",
"tabLabels": {
"tracks": "Pistas",
"albums": "Albumes",
"artists": "Artistas",
"playlists": "Listas"
},
"moveUp": "Subir",
"moveDown": "Bajar",
"save": "Guardar",
"saving": "Guardando...",
"cancel": "Cancelar"
}, },
"player": { "player": {
"nowPlaying": "Reproduciendo", "nowPlaying": "Reproduciendo",
@@ -311,7 +329,13 @@
"gapless": "Reproducción Sin Pausas", "gapless": "Reproducción Sin Pausas",
"crossfade": "Crossfade", "crossfade": "Crossfade",
"crossfadeSeconds": "{seconds}s", "crossfadeSeconds": "{seconds}s",
"normalizeVolume": "Normalizar Volumen" "normalizeVolume": "Normalizar Volumen",
"autoplayBehavior": "Continuar reproducción al finalizar pista",
"autoplayBehaviorDesc": "Cuando está activado, reproduce la siguiente pista del contexto. Cuando está desactivado, se detiene después de cada pista",
"continueWithinSource": "Continuar dentro del contexto",
"playOnlySelectedTrack": "Reproducir solo la pista seleccionada",
"showContextIcon": "Mostrar contexto de reproducción en el reproductor",
"showContextIconTooltip": "Muestra el contexto desde donde se reproduce la pista actual (álbum, artista, playlist, etc.)"
}, },
"appearance": { "appearance": {
"title": "Apariencia", "title": "Apariencia",
+68 -1
View File
@@ -6,7 +6,21 @@
* fetched data, but selectedPlaylistId is managed here as it's just an ID. * fetched data, but selectedPlaylistId is managed here as it's just an ID.
*/ */
export type ViewType = 'home' | 'search' | 'library' | 'library-album' | 'settings' | 'album' | 'artist' | 'playlist' | 'playlist-manager' | 'favorites'; export type ViewType =
| 'home'
| 'search'
| 'library'
| 'library-album'
| 'settings'
| 'album'
| 'artist'
| 'playlist'
| 'playlist-manager'
| 'favorites-tracks'
| 'favorites-albums'
| 'favorites-artists'
| 'favorites-playlists';
export type FavoritesTab = 'tracks' | 'albums' | 'artists' | 'playlists';
// Navigation state // Navigation state
let activeView: ViewType = 'home'; let activeView: ViewType = 'home';
@@ -19,6 +33,39 @@ let selectedPlaylistId: number | null = null;
// Selected local album ID (for library-album view) // Selected local album ID (for library-album view)
let selectedLocalAlbumId: string | null = null; let selectedLocalAlbumId: string | null = null;
// Last visited Favorites tab (used as default when navigating to Favorites)
let lastFavoritesTab: FavoritesTab = 'tracks';
const favoritesViewMap: Record<FavoritesTab, ViewType> = {
tracks: 'favorites-tracks',
albums: 'favorites-albums',
artists: 'favorites-artists',
playlists: 'favorites-playlists'
};
export function isFavoritesView(view: ViewType): boolean {
return view.startsWith('favorites-');
}
export function favoritesViewForTab(tab: FavoritesTab): ViewType {
return favoritesViewMap[tab];
}
export function getFavoritesTabFromView(view: ViewType): FavoritesTab | null {
switch (view) {
case 'favorites-tracks':
return 'tracks';
case 'favorites-albums':
return 'albums';
case 'favorites-artists':
return 'artists';
case 'favorites-playlists':
return 'playlists';
default:
return null;
}
}
// Listeners // Listeners
const listeners = new Set<() => void>(); const listeners = new Set<() => void>();
@@ -47,6 +94,12 @@ export function navigateTo(view: ViewType): void {
viewHistory = [...viewHistory, view]; viewHistory = [...viewHistory, view];
forwardHistory = []; forwardHistory = [];
activeView = view; activeView = view;
const tab = getFavoritesTabFromView(view);
if (tab) {
lastFavoritesTab = tab;
}
notifyListeners(); notifyListeners();
} }
} }
@@ -61,6 +114,10 @@ export function goBack(): boolean {
viewHistory = viewHistory.slice(0, -1); viewHistory = viewHistory.slice(0, -1);
forwardHistory = [...forwardHistory, lastView]; forwardHistory = [...forwardHistory, lastView];
activeView = viewHistory[viewHistory.length - 1]; activeView = viewHistory[viewHistory.length - 1];
const tab = getFavoritesTabFromView(activeView);
if (tab) {
lastFavoritesTab = tab;
}
notifyListeners(); notifyListeners();
return true; return true;
} }
@@ -77,6 +134,10 @@ export function goForward(): boolean {
forwardHistory = forwardHistory.slice(0, -1); forwardHistory = forwardHistory.slice(0, -1);
viewHistory = [...viewHistory, nextView]; viewHistory = [...viewHistory, nextView];
activeView = nextView; activeView = nextView;
const tab = getFavoritesTabFromView(activeView);
if (tab) {
lastFavoritesTab = tab;
}
notifyListeners(); notifyListeners();
return true; return true;
} }
@@ -152,6 +213,12 @@ export function getSelectedLocalAlbumId(): string | null {
return selectedLocalAlbumId; return selectedLocalAlbumId;
} }
// ============ Favorites Navigation ============
export function navigateToFavorites(tab?: FavoritesTab): void {
const targetTab = tab ?? lastFavoritesTab;
navigateTo(favoritesViewForTab(targetTab));
}
// ============ Getters ============ // ============ Getters ============
export function getActiveView(): ViewType { export function getActiveView(): ViewType {
+179
View File
@@ -0,0 +1,179 @@
/**
* Playback Context Store
*
* Manages the semantic origin of playback (album, playlist, artist top, etc.)
* Determines what "next" means and displays the stack icon.
*/
import { invoke } from '@tauri-apps/api/core';
// ============ Types ============
export type ContextType = 'album' | 'playlist' | 'artist_top' | 'home_list' | 'favorites';
export type ContentSource = 'qobuz' | 'local';
export interface PlaybackContext {
type: ContextType;
id: string;
label: string;
source: ContentSource;
track_ids: number[];
current_position: number;
}
// ============ State ============
let currentContext: PlaybackContext | null = null;
let pendingFocus: { contextType: ContextType; contextId: string; trackId: number } | null = null;
const listeners = new Set<() => void>();
function notifyListeners(): void {
for (const listener of listeners) {
listener();
}
}
// ============ Public API ============
/**
* Set a playback context (e.g., when playing from album/playlist)
*/
export async function setPlaybackContext(
contextType: ContextType,
id: string,
label: string,
source: ContentSource,
trackIds: number[],
startPosition: number
): Promise<void> {
console.log('[PlaybackContext] Setting context:', { contextType, id, label, trackIds: trackIds.length, startPosition });
await invoke('set_playback_context', {
contextType,
id,
label,
source,
trackIds,
startPosition
});
// Update local state
currentContext = {
type: contextType,
id,
label,
source,
track_ids: trackIds,
current_position: startPosition
};
console.log('[PlaybackContext] Context set, notifying listeners. Current context:', currentContext);
notifyListeners();
}
/**
* Clear the playback context (e.g., when playing single track)
*/
export async function clearPlaybackContext(): Promise<void> {
console.log('[PlaybackContext] Clearing context');
await invoke('clear_playback_context');
currentContext = null;
console.log('[PlaybackContext] Context cleared, notifying listeners');
notifyListeners();
}
/**
* Get the current playback context
*/
export async function getPlaybackContext(): Promise<PlaybackContext | null> {
const context = await invoke<PlaybackContext | null>('get_playback_context');
currentContext = context;
notifyListeners();
return context;
}
/**
* Check if a context is active
*/
export async function hasPlaybackContext(): Promise<boolean> {
return await invoke<boolean>('has_playback_context');
}
/**
* Get the current context (cached, no backend call)
*/
export function getCurrentContext(): PlaybackContext | null {
return currentContext;
}
export function requestContextTrackFocus(
contextType: ContextType,
contextId: string,
trackId: number
): void {
pendingFocus = { contextType, contextId, trackId };
}
export function consumeContextTrackFocus(
contextType: ContextType,
contextId: string
): number | null {
if (!pendingFocus) return null;
if (pendingFocus.contextType !== contextType || pendingFocus.contextId !== contextId) {
return null;
}
const { trackId } = pendingFocus;
pendingFocus = null;
return trackId;
}
/**
* Get display info for the current context
*/
export function getContextDisplayInfo(): string | null {
if (!currentContext) return null;
const typeStr = {
album: 'Album',
playlist: 'Playlist',
artist_top: 'Artist Top Songs',
home_list: 'Home List',
favorites: 'Favorites'
}[currentContext.type];
return `${typeStr} · ${currentContext.label}`;
}
/**
* Subscribe to context changes
*/
export function subscribe(listener: () => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
/**
* Initialize context store (call on app startup)
*/
export async function initPlaybackContextStore(): Promise<void> {
// Sync initial state from backend
await getPlaybackContext();
}
// Export a reactive getter for Svelte components
export function usePlaybackContext() {
let context = currentContext;
const unsubscribe = subscribe(() => {
context = currentContext;
});
return {
get context() {
return context;
},
unsubscribe
};
}
@@ -0,0 +1,92 @@
/**
* Playback Preferences Store
*
* Manages global playback behavior preferences (autoplay mode, etc.)
*/
import { invoke } from '@tauri-apps/api/core';
// ============ Types ============
export type AutoplayMode = 'continue' | 'track_only';
export interface PlaybackPreferences {
autoplay_mode: AutoplayMode;
show_context_icon: boolean;
}
// ============ State ============
let preferences: PlaybackPreferences = {
autoplay_mode: 'continue',
show_context_icon: true
};
const listeners = new Set<() => void>();
function notifyListeners(): void {
for (const listener of listeners) {
listener();
}
}
// ============ Public API ============
/**
* Get current playback preferences
*/
export async function getPlaybackPreferences(): Promise<PlaybackPreferences> {
const prefs = await invoke<PlaybackPreferences>('get_playback_preferences');
preferences = prefs;
notifyListeners();
return prefs;
}
/**
* Set autoplay mode
*/
export async function setAutoplayMode(mode: AutoplayMode): Promise<void> {
await invoke('set_autoplay_mode', { mode });
preferences.autoplay_mode = mode;
notifyListeners();
}
/**
* Set whether to show context icon in player
*/
export async function setShowContextIcon(show: boolean): Promise<void> {
await invoke('set_show_context_icon', { show });
preferences.show_context_icon = show;
notifyListeners();
}
/**
* Get cached preferences (no backend call)
*/
export function getCachedPreferences(): PlaybackPreferences {
return preferences;
}
/**
* Check if autoplay is enabled (continue within source)
*/
export function isAutoplayEnabled(): boolean {
return preferences.autoplay_mode === 'continue';
}
/**
* Subscribe to preference changes
*/
export function subscribe(listener: () => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
/**
* Initialize preferences store (call on app startup)
*/
export async function initPlaybackPreferences(): Promise<void> {
await getPlaybackPreferences();
}
+9
View File
@@ -244,3 +244,12 @@ export interface SongLinkResponse {
identifier: string; identifier: string;
contentType: string; contentType: string;
} }
// ============ Preferences Types ============
export interface FavoritesPreferences {
custom_icon_path: string | null;
custom_icon_preset: string | null;
icon_background: string | null;
tab_order: string[];
}
+32
View File
@@ -0,0 +1,32 @@
import type { FavoritesTab } from '$lib/stores/navigationStore';
const FALLBACK_ORDER: FavoritesTab[] = ['tracks', 'albums', 'artists', 'playlists'];
export function normalizeFavoritesTabOrder(order?: string[] | null): FavoritesTab[] {
const result: FavoritesTab[] = [];
const seen = new Set<FavoritesTab>();
if (Array.isArray(order)) {
for (const entry of order) {
if (FALLBACK_ORDER.includes(entry as FavoritesTab)) {
const tab = entry as FavoritesTab;
if (!seen.has(tab)) {
seen.add(tab);
result.push(tab);
}
}
}
}
for (const tab of FALLBACK_ORDER) {
if (!seen.has(tab)) {
result.push(tab);
}
}
return result;
}
export function getDefaultFavoritesTab(order?: string[] | null): FavoritesTab {
return normalizeFavoritesTabOrder(order)[0] ?? 'tracks';
}
-161
View File
@@ -23,115 +23,6 @@
{/if} {/if}
<style> <style>
:global(*) {
box-sizing: border-box;
margin: 0;
padding: 0;
}
:global(html, body) {
height: 100%;
width: 100%;
overflow: hidden;
}
:global(body) {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
font-size: 14px;
line-height: 1.5;
color: var(--text-primary);
background-color: var(--bg-primary);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* CSS Variables - Dark Theme (Default) */
:global(:root) {
/* Backgrounds */
--bg-primary: #0f0f0f;
--bg-secondary: #1a1a1a;
--bg-tertiary: #2a2a2a;
--bg-hover: #1f1f1f;
/* Text */
--text-primary: #ffffff;
--text-secondary: #cccccc;
--text-muted: #888888;
--text-disabled: #555555;
/* Accent */
--accent-primary: #4285F4;
--accent-hover: #5a9bf4;
--accent-active: #3275e4;
/* Borders */
--border-subtle: #2a2a2a;
--border-strong: #3a3a3a;
/* Shadows */
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.3);
--shadow-md: 0 4px 8px rgba(0, 0, 0, 0.3);
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.4);
/* Spacing */
--spacing-xs: 4px;
--spacing-sm: 8px;
--spacing-md: 12px;
--spacing-lg: 16px;
--spacing-xl: 24px;
--spacing-2xl: 32px;
--spacing-3xl: 48px;
/* Layout */
--sidebar-width: 240px;
--now-playing-height: 80px;
/* Border Radius */
--radius-sm: 4px;
--radius-md: 8px;
--radius-lg: 12px;
--radius-xl: 16px;
--radius-full: 9999px;
/* Transitions */
--transition-fast: 150ms ease-out;
--transition-normal: 200ms ease-out;
--transition-slow: 300ms ease-out;
}
/* Light Theme */
:global([data-theme="light"]) {
--bg-primary: #ffffff;
--bg-secondary: #f5f5f5;
--bg-tertiary: #e8e8e8;
--bg-hover: #f0f0f0;
--text-primary: #0f0f0f;
--text-secondary: #444444;
--text-muted: #666666;
--text-disabled: #999999;
--border-subtle: #e0e0e0;
--border-strong: #cccccc;
}
/* OLED Black Theme */
:global([data-theme="oled"]) {
--bg-primary: #000000;
--bg-secondary: #0a0a0a;
--bg-tertiary: #1a1a1a;
--bg-hover: #111111;
}
/* Warm Theme */
:global([data-theme="warm"]) {
--bg-primary: #1a1814;
--bg-secondary: #242018;
--bg-tertiary: #2e2820;
--bg-hover: #282218;
--accent-primary: #d4a574;
--accent-hover: #e0b888;
--accent-active: #c49460;
}
.loading { .loading {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -154,56 +45,4 @@
transform: rotate(360deg); transform: rotate(360deg);
} }
} }
/* Scrollbar styling */
:global(::-webkit-scrollbar) {
width: 8px;
height: 8px;
}
:global(::-webkit-scrollbar-track) {
background: transparent;
}
:global(::-webkit-scrollbar-thumb) {
background: var(--bg-tertiary);
border-radius: var(--radius-full);
}
:global(::-webkit-scrollbar-thumb:hover) {
background: var(--text-muted);
}
/* Selection */
:global(::selection) {
background-color: var(--accent-primary);
color: var(--text-primary);
}
/* Focus visible */
:global(:focus-visible) {
outline: 2px solid var(--accent-primary);
outline-offset: 2px;
}
/* Button reset */
:global(button) {
background: none;
border: none;
cursor: pointer;
font: inherit;
color: inherit;
}
/* Link reset */
:global(a) {
color: inherit;
text-decoration: none;
}
/* Input reset */
:global(input, textarea, select) {
font: inherit;
color: inherit;
}
</style> </style>
+184 -4
View File
@@ -25,6 +25,20 @@
type Toast as ToastData type Toast as ToastData
} from '$lib/stores/toastStore'; } from '$lib/stores/toastStore';
// Playback context and preferences
import {
initPlaybackContextStore,
setPlaybackContext,
clearPlaybackContext,
getCurrentContext,
requestContextTrackFocus
} from '$lib/stores/playbackContextStore';
import {
initPlaybackPreferences,
getCachedPreferences,
isAutoplayEnabled
} from '$lib/stores/playbackPreferencesStore';
// UI state management // UI state management
import { import {
subscribe as subscribeUI, subscribe as subscribeUI,
@@ -59,17 +73,23 @@
// Favorites state management // Favorites state management
import { loadFavorites } from '$lib/stores/favoritesStore'; import { loadFavorites } from '$lib/stores/favoritesStore';
import { getDefaultFavoritesTab } from '$lib/utils/favorites';
import type { FavoritesPreferences } from '$lib/types';
// Navigation state management // Navigation state management
import { import {
subscribe as subscribeNav, subscribe as subscribeNav,
navigateTo as navTo, navigateTo as navTo,
navigateToFavorites,
goBack as navGoBack, goBack as navGoBack,
goForward as navGoForward, goForward as navGoForward,
selectPlaylist, selectPlaylist,
getNavigationState, getNavigationState,
getFavoritesTabFromView,
isFavoritesView,
type ViewType, type ViewType,
type NavigationState type NavigationState,
type FavoritesTab
} from '$lib/stores/navigationStore'; } from '$lib/stores/navigationStore';
// Player state management // Player state management
@@ -323,9 +343,26 @@
let lyricsActiveProgress = $state(0); let lyricsActiveProgress = $state(0);
let lyricsSidebarVisible = $state(false); let lyricsSidebarVisible = $state(false);
let favoritesDefaultTab = $state<FavoritesTab>('tracks');
async function loadFavoritesDefaultTab(): Promise<void> {
try {
const prefs = await invoke<FavoritesPreferences>('get_favorites_preferences');
favoritesDefaultTab = getDefaultFavoritesTab(prefs.tab_order);
} catch (err) {
console.error('Failed to load favorites preferences:', err);
favoritesDefaultTab = 'tracks';
}
}
// Navigation wrapper (keeps debug logging) // Navigation wrapper (keeps debug logging)
function navigateTo(view: string) { async function navigateTo(view: string) {
console.log('navigateTo called with:', view, 'current activeView:', activeView); console.log('navigateTo called with:', view, 'current activeView:', activeView);
if (view === 'favorites') {
await loadFavoritesDefaultTab();
navigateToFavorites(favoritesDefaultTab);
return;
}
navTo(view as ViewType); navTo(view as ViewType);
} }
@@ -360,6 +397,77 @@
} }
} }
/**
* Navigate to the source of current playback context
*/
async function handleContextNavigation() {
const context = getCurrentContext();
if (!context) {
console.log('[ContextNav] No context available');
return;
}
console.log('[ContextNav] Navigating to:', context);
const focusTrackId = currentTrack?.id;
const requestFocus = (contextType: typeof context.type, contextId: string) => {
if (typeof focusTrackId === 'number') {
requestContextTrackFocus(contextType, contextId, focusTrackId);
}
};
try {
switch (context.type) {
case 'album':
// Navigate to album page
requestFocus('album', context.id);
await handleAlbumClick(context.id);
break;
case 'playlist':
// Navigate to playlist page
const playlistId = parseInt(context.id);
if (!isNaN(playlistId)) {
requestFocus('playlist', context.id);
selectedPlaylistId = playlistId;
navigateTo('playlist');
}
break;
case 'artist_top':
// Navigate to artist page
const artistId = parseInt(context.id);
if (!isNaN(artistId)) {
requestFocus('artist_top', context.id);
await handleArtistClick(artistId);
}
break;
case 'favorites':
// Navigate to favorites page
requestFocus('favorites', 'favorites');
navigateToFavorites('tracks');
break;
case 'home_list':
// Navigate to home page
navigateTo('home');
break;
case 'search':
// Navigate to search (could restore query if needed)
navigateTo('search');
break;
default:
console.warn('[ContextNav] Unknown context type:', context.type);
}
} catch (err) {
console.error('[ContextNav] Navigation failed:', err);
showToast('Failed to navigate to source', 'error');
}
}
interface ArtistAlbumsResponse { interface ArtistAlbumsResponse {
items: QobuzAlbum[]; items: QobuzAlbum[];
total: number; total: number;
@@ -587,6 +695,26 @@
async function handleAlbumTrackPlay(track: Track) { async function handleAlbumTrackPlay(track: Track) {
console.log('Playing album track:', track); console.log('Playing album track:', track);
// ALWAYS create context when playing from an album
// The setting only affects menu options visibility, not implicit behavior
if (selectedAlbum?.tracks) {
const trackIndex = selectedAlbum.tracks.findIndex(t => t.id === track.id);
const trackIds = selectedAlbum.tracks.map(t => t.id);
console.log('[Album] Creating context with', trackIds.length, 'tracks, starting at', trackIndex);
await setPlaybackContext(
'album',
selectedAlbum.id,
selectedAlbum.title,
'qobuz',
trackIds,
trackIndex >= 0 ? trackIndex : 0
);
console.log('[Album] Context created - stack icon should appear');
} else {
console.log('[Album] No album tracks found, cannot create context');
}
const artwork = selectedAlbum?.artwork || ''; const artwork = selectedAlbum?.artwork || '';
const quality = track.hires && track.bitDepth && track.samplingRate const quality = track.hires && track.bitDepth && track.samplingRate
? `${track.bitDepth}bit/${track.samplingRate}kHz` ? `${track.bitDepth}bit/${track.samplingRate}kHz`
@@ -1192,8 +1320,35 @@
}); });
} }
/**
* Helper: Create context and play display track
*/
async function createContextAndPlayDisplayTrack(
track: DisplayTrack,
contextType: ContextType,
contextId: string,
contextLabel: string,
trackIds: number[],
startIndex: number
) {
// Create context
await setPlaybackContext(
contextType,
contextId,
contextLabel,
'qobuz',
trackIds,
startIndex
);
console.log(`[Context] Created for ${contextType}: ${contextLabel}, starting at index ${startIndex}`);
// Play track
handleDisplayTrackPlay(track);
}
async function handleLocalTrackPlay(track: LocalLibraryTrack) { async function handleLocalTrackPlay(track: LocalLibraryTrack) {
console.log('Playing local track:', track); console.log('Playing local track:', track);
await clearPlaybackContext();
const artwork = track.artwork_path ? convertFileSrc(track.artwork_path) : ''; const artwork = track.artwork_path ? convertFileSrc(track.artwork_path) : '';
const quality = track.bit_depth && track.sample_rate const quality = track.bit_depth && track.sample_rate
@@ -1579,6 +1734,10 @@
initDownloadStates(); initDownloadStates();
startDownloadEventListeners(); startDownloadEventListeners();
// Initialize playback context and preferences stores
initPlaybackContextStore();
initPlaybackPreferences();
// Note: loadFavorites() is called in handleLoginSuccess after login is confirmed // Note: loadFavorites() is called in handleLoginSuccess after login is confirmed
// This prevents API calls before authentication is complete // This prevents API calls before authentication is complete
@@ -1696,6 +1855,10 @@
// Set up track ended callback for auto-advance // Set up track ended callback for auto-advance
setOnTrackEnded(async () => { setOnTrackEnded(async () => {
if (!isAutoplayEnabled()) {
setQueueEnded(true);
return;
}
const nextTrackResult = await nextTrack(); const nextTrackResult = await nextTrack();
if (nextTrackResult) { if (nextTrackResult) {
await playQueueTrack(nextTrackResult); await playQueueTrack(nextTrackResult);
@@ -1896,6 +2059,8 @@
{downloadStateVersion} {downloadStateVersion}
onArtistClick={handleArtistClick} onArtistClick={handleArtistClick}
onTrackPlay={handleDisplayTrackPlay} onTrackPlay={handleDisplayTrackPlay}
activeTrackId={currentTrack?.id ?? null}
isPlaybackActive={isPlaying}
/> />
{/if} {/if}
{:else if activeView === 'search'} {:else if activeView === 'search'}
@@ -1927,6 +2092,8 @@
onTrackGoToAlbum={handleAlbumClick} onTrackGoToAlbum={handleAlbumClick}
onTrackGoToArtist={handleArtistClick} onTrackGoToArtist={handleArtistClick}
onArtistClick={handleArtistClick} onArtistClick={handleArtistClick}
activeTrackId={currentTrack?.id ?? null}
isPlaybackActive={isPlaying}
/> />
{/if} {/if}
{:else if activeView === 'settings'} {:else if activeView === 'settings'}
@@ -1993,6 +2160,8 @@
onTrackGoToAlbum={handleAlbumClick} onTrackGoToAlbum={handleAlbumClick}
onTrackGoToArtist={handleArtistClick} onTrackGoToArtist={handleArtistClick}
onPlaylistClick={selectPlaylist} onPlaylistClick={selectPlaylist}
activeTrackId={currentTrack?.id ?? null}
isPlaybackActive={isPlaying}
/> />
{:else if activeView === 'library' || activeView === 'library-album'} {:else if activeView === 'library' || activeView === 'library-album'}
<LocalLibraryView <LocalLibraryView
@@ -2002,6 +2171,8 @@
onTrackAddToPlaylist={(trackId) => openAddToPlaylist([trackId], true)} onTrackAddToPlaylist={(trackId) => openAddToPlaylist([trackId], true)}
onSetLocalQueue={handleSetLocalQueue} onSetLocalQueue={handleSetLocalQueue}
onQobuzArtistClick={handleArtistClick} onQobuzArtistClick={handleArtistClick}
activeTrackId={currentTrack?.id ?? null}
isPlaybackActive={isPlaying}
/> />
{:else if activeView === 'playlist' && selectedPlaylistId} {:else if activeView === 'playlist' && selectedPlaylistId}
<PlaylistDetailView <PlaylistDetailView
@@ -2035,7 +2206,7 @@
}} }}
onPlaylistDeleted={() => { sidebarRef?.refreshPlaylists(); navGoBack(); }} onPlaylistDeleted={() => { sidebarRef?.refreshPlaylists(); navGoBack(); }}
/> />
{:else if activeView === 'favorites'} {:else if isFavoritesView(activeView)}
{#if offlineStatus.isOffline} {#if offlineStatus.isOffline}
<OfflinePlaceholder <OfflinePlaceholder
reason={offlineStatus.reason} reason={offlineStatus.reason}
@@ -2068,6 +2239,10 @@
onTrackRemoveDownload={handleTrackRemoveDownload} onTrackRemoveDownload={handleTrackRemoveDownload}
getTrackDownloadStatus={getTrackDownloadStatus} getTrackDownloadStatus={getTrackDownloadStatus}
onPlaylistSelect={selectPlaylist} onPlaylistSelect={selectPlaylist}
selectedTab={getFavoritesTabFromView(activeView) ?? favoritesDefaultTab}
onTabNavigate={(tab) => navigateToFavorites(tab)}
activeTrackId={currentTrack?.id ?? null}
isPlaybackActive={isPlaying}
/> />
{/if} {/if}
{:else if activeView === 'playlist-manager'} {:else if activeView === 'playlist-manager'}
@@ -2092,6 +2267,7 @@
/> />
{/if} {/if}
</div> </div>
</div><!-- end app-body -->
<!-- Now Playing Bar --> <!-- Now Playing Bar -->
{#if currentTrack} {#if currentTrack}
@@ -2140,6 +2316,7 @@
handleAlbumClick(currentTrack.albumId); handleAlbumClick(currentTrack.albumId);
} }
}} }}
onContextClick={handleContextNavigation}
/> />
{:else} {:else}
<NowPlayingBar <NowPlayingBar
@@ -2150,7 +2327,6 @@
{isCastConnected} {isCastConnected}
/> />
{/if} {/if}
</div><!-- end app-body -->
<!-- Queue Panel --> <!-- Queue Panel -->
<QueuePanel <QueuePanel
@@ -2202,6 +2378,7 @@
}} }}
onCast={openCastPicker} onCast={openCastPicker}
{isCastConnected} {isCastConnected}
onContextClick={handleContextNavigation}
lyricsLines={lyricsLines.map(l => ({ text: l.text }))} lyricsLines={lyricsLines.map(l => ({ text: l.text }))}
lyricsActiveIndex={lyricsActiveIndex} lyricsActiveIndex={lyricsActiveIndex}
lyricsActiveProgress={lyricsActiveProgress} lyricsActiveProgress={lyricsActiveProgress}
@@ -2226,12 +2403,15 @@
{currentTime} {currentTime}
{duration} {duration}
onSeek={handleSeek} onSeek={handleSeek}
{volume}
onVolumeChange={handleVolumeChange}
lyricsLines={lyricsLines.map(l => ({ text: l.text }))} lyricsLines={lyricsLines.map(l => ({ text: l.text }))}
lyricsActiveIndex={lyricsActiveIndex} lyricsActiveIndex={lyricsActiveIndex}
lyricsActiveProgress={lyricsActiveProgress} lyricsActiveProgress={lyricsActiveProgress}
lyricsSynced={lyricsIsSynced} lyricsSynced={lyricsIsSynced}
lyricsLoading={lyricsStatus === 'loading'} lyricsLoading={lyricsStatus === 'loading'}
lyricsError={lyricsStatus === 'error' ? lyricsError : (lyricsStatus === 'not_found' ? 'No lyrics found' : null)} lyricsError={lyricsStatus === 'error' ? lyricsError : (lyricsStatus === 'not_found' ? 'No lyrics found' : null)}
onContextClick={handleContextNavigation}
/> />
{/if} {/if}
+112
View File
@@ -12,6 +12,7 @@
Maximize2, Maximize2,
ListMusic ListMusic
} from 'lucide-svelte'; } from 'lucide-svelte';
import StackIcon from '$lib/components/StackIcon.svelte';
import { import {
subscribe as subscribePlayer, subscribe as subscribePlayer,
getPlayerState, getPlayerState,
@@ -39,10 +40,12 @@
let repeatMode = $state<RepeatMode>('off'); let repeatMode = $state<RepeatMode>('off');
let isDragging = $state(false); let isDragging = $state(false);
let isDraggingProgress = $state(false); let isDraggingProgress = $state(false);
let isDraggingVolume = $state(false);
let queueCount = $state(0); let queueCount = $state(0);
// Refs // Refs
let progressRef: HTMLDivElement; let progressRef: HTMLDivElement;
let volumeRef: HTMLDivElement | null = null;
// Derived state // Derived state
const progress = $derived(playerState.duration > 0 ? (playerState.currentTime / playerState.duration) * 100 : 0); const progress = $derived(playerState.duration > 0 ? (playerState.currentTime / playerState.duration) * 100 : 0);
@@ -163,6 +166,31 @@
} }
} }
function handleVolumeMouseDown(e: MouseEvent): void {
e.stopPropagation();
isDraggingVolume = true;
updateVolume(e);
document.addEventListener('mousemove', handleVolumeMouseMove);
document.addEventListener('mouseup', handleVolumeMouseUp);
}
function handleVolumeMouseMove(e: MouseEvent): void {
if (isDraggingVolume) updateVolume(e);
}
function handleVolumeMouseUp(): void {
isDraggingVolume = false;
document.removeEventListener('mousemove', handleVolumeMouseMove);
document.removeEventListener('mouseup', handleVolumeMouseUp);
}
function updateVolume(e: MouseEvent): void {
if (!volumeRef) return;
const rect = volumeRef.getBoundingClientRect();
const percentage = Math.max(0, Math.min(100, ((e.clientX - rect.left) / rect.width) * 100));
playerSetVolume(Math.round(percentage));
}
// Window controls - stop propagation to prevent drag from capturing // Window controls - stop propagation to prevent drag from capturing
async function handleRestore(e: MouseEvent): Promise<void> { async function handleRestore(e: MouseEvent): Promise<void> {
e.stopPropagation(); e.stopPropagation();
@@ -232,6 +260,7 @@
<div class="track-info"> <div class="track-info">
<div class="title">{playerState.currentTrack?.title ?? 'No track'}</div> <div class="title">{playerState.currentTrack?.title ?? 'No track'}</div>
<div class="artist-album"> <div class="artist-album">
<StackIcon size={12} class="stack-icon" />
{playerState.currentTrack?.artist ?? '—'} {playerState.currentTrack?.artist ?? '—'}
{#if playerState.currentTrack?.album} {#if playerState.currentTrack?.album}
<span class="separator">—</span> <span class="separator">—</span>
@@ -302,6 +331,24 @@
</button> </button>
</div> </div>
<div class="volume-control">
<div class="volume-value" class:visible={isDraggingVolume}>{Math.round(playerState.volume)}</div>
<div
class="volume-bar"
bind:this={volumeRef}
onmousedown={handleVolumeMouseDown}
role="slider"
tabindex="0"
aria-valuenow={playerState.volume}
aria-valuemin={0}
aria-valuemax={100}
title="Volume"
>
<div class="volume-fill" style="width: {playerState.volume}%"></div>
<div class="volume-thumb" style="left: {playerState.volume}%"></div>
</div>
</div>
<div class="window-controls"> <div class="window-controls">
<button class="ctrl-btn" onclick={handleOpenQueue} title="Queue ({queueCount})"> <button class="ctrl-btn" onclick={handleOpenQueue} title="Queue ({queueCount})">
<ListMusic size={14} /> <ListMusic size={14} />
@@ -419,6 +466,9 @@
} }
.artist-album { .artist-album {
display: flex;
align-items: center;
gap: 4px;
font-size: 12px; font-size: 12px;
color: rgba(255, 255, 255, 0.5); color: rgba(255, 255, 255, 0.5);
white-space: nowrap; white-space: nowrap;
@@ -427,6 +477,10 @@
margin-top: 2px; margin-top: 2px;
} }
.artist-album :global(.stack-icon) {
flex-shrink: 0;
}
.separator { .separator {
margin: 0 4px; margin: 0 4px;
opacity: 0.5; opacity: 0.5;
@@ -470,6 +524,7 @@
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
flex-shrink: 0; flex-shrink: 0;
gap: 12px;
} }
.media-controls { .media-controls {
@@ -484,6 +539,63 @@
gap: 2px; gap: 2px;
} }
.volume-control {
position: relative;
display: flex;
align-items: center;
flex-shrink: 0;
}
.volume-bar {
width: 90px;
height: 4px;
background: rgba(255, 255, 255, 0.18);
border-radius: 999px;
cursor: pointer;
position: relative;
}
.volume-fill {
height: 100%;
border-radius: 999px;
background: rgba(255, 255, 255, 0.8);
}
.volume-thumb {
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
width: 10px;
height: 10px;
border-radius: 50%;
background: #fff;
opacity: 0;
transition: opacity 150ms ease;
}
.volume-bar:hover .volume-thumb {
opacity: 1;
}
.volume-value {
position: absolute;
right: 0;
top: -22px;
padding: 2px 6px;
border-radius: 999px;
background: rgba(0, 0, 0, 0.6);
color: #fff;
font-size: 11px;
opacity: 0;
transform: translateY(4px);
transition: opacity 150ms ease, transform 150ms ease;
}
.volume-value.visible {
opacity: 1;
transform: translateY(0);
}
.ctrl-btn { .ctrl-btn {
display: flex; display: flex;
align-items: center; align-items: center;