feat(favorites): make tabs history-aware views and normalize order

cx
This commit is contained in:
vicrodh committed 2026-01-19 11:11:03 -06:00
1 parent b82abb145b
commit 7831b07c30
5 files changed
+165 -95

No files matched your search

+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}
+42 -45
View File
@@ -8,7 +8,7 @@
import FavoritesEditModal from '../FavoritesEditModal.svelte'; import FavoritesEditModal from '../FavoritesEditModal.svelte';
import { type DownloadStatus } from '$lib/stores/downloadState'; import { type DownloadStatus } from '$lib/stores/downloadState';
import { setPlaybackContext } from '$lib/stores/playbackContextStore'; import { setPlaybackContext } from '$lib/stores/playbackContextStore';
import { setFavoritesTab } from '$lib/stores/navigationStore'; import { normalizeFavoritesTabOrder } from '$lib/utils/favorites';
import type { FavoritesPreferences } from '$lib/types'; import type { FavoritesPreferences } from '$lib/types';
interface FavoriteAlbum { interface FavoriteAlbum {
@@ -77,7 +77,8 @@
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;
currentTab?: TabType; // For syncing with navigation store selectedTab?: TabType;
onTabNavigate?: (tab: TabType) => void;
} }
interface DisplayTrack { interface DisplayTrack {
@@ -123,12 +124,13 @@
onTrackRemoveDownload, onTrackRemoveDownload,
getTrackDownloadStatus, getTrackDownloadStatus,
onPlaylistSelect, onPlaylistSelect,
currentTab selectedTab,
onTabNavigate
}: 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 isInitialMount = $state(true); let preferencesLoaded = $state(false);
const tabLabels: Record<TabType, string> = { const tabLabels: Record<TabType, string> = {
tracks: 'Tracks', tracks: 'Tracks',
@@ -307,32 +309,37 @@
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);
loadFavoritesPreferences().then(() => { loadFavoritesPreferences().then(() => {
// On initial mount, sync with navigation store to load configured first tab preferencesLoaded = true;
if (isInitialMount && currentTab) { if (selectedTab) {
activeTab = currentTab; activeTab = selectedTab;
isInitialMount = false; } else {
} else if (isInitialMount) {
// Load first tab from preferences
activeTab = favoritesPreferences.tab_order[0] as TabType; activeTab = favoritesPreferences.tab_order[0] as TabType;
isInitialMount = false;
} }
loadTabIfNeeded(activeTab);
loadFavorites(activeTab);
}); });
}); });
async function loadFavoritesPreferences() { async function loadFavoritesPreferences() {
try { try {
const prefs = await invoke<FavoritesPreferences>('get_favorites_preferences'); const prefs = await invoke<FavoritesPreferences>('get_favorites_preferences');
console.log('[FavoritesView] Loaded preferences:', prefs); favoritesPreferences = {
favoritesPreferences = prefs; ...prefs,
tab_order: normalizeFavoritesTabOrder(prefs.tab_order)
};
} catch (err) { } catch (err) {
console.error('Failed to load favorites preferences:', err); console.error('Failed to load favorites preferences:', err);
favoritesPreferences = {
...favoritesPreferences,
tab_order: normalizeFavoritesTabOrder(favoritesPreferences.tab_order)
};
} }
} }
function handlePreferencesSaved(prefs: FavoritesPreferences) { function handlePreferencesSaved(prefs: FavoritesPreferences) {
favoritesPreferences = prefs; favoritesPreferences = {
...prefs,
tab_order: normalizeFavoritesTabOrder(prefs.tab_order)
};
} }
@@ -349,22 +356,10 @@
} }
}); });
// Sync activeTab when navigating back/forward (not when clicking tabs directly)
let lastUserClickedTab: TabType | null = null;
$effect(() => { $effect(() => {
// Only sync if: if (preferencesLoaded && selectedTab && selectedTab !== activeTab) {
// 1. Not initial mount activeTab = selectedTab;
// 2. currentTab exists and differs from activeTab loadTabIfNeeded(activeTab);
// 3. The change is NOT from a user click (navigation back/forward)
if (!isInitialMount && currentTab && currentTab !== activeTab && currentTab !== lastUserClickedTab) {
console.log('[FavoritesView] Tab changed via navigation (back/forward):', currentTab);
activeTab = currentTab;
loadFavorites(activeTab);
}
// Reset the flag after navigation sync
if (lastUserClickedTab) {
lastUserClickedTab = null;
} }
}); });
@@ -461,17 +456,7 @@
} }
} }
function handleTabChange(tab: TabType) { function loadTabIfNeeded(tab: TabType) {
// Mark this as a user click to prevent navigation effect from overriding
lastUserClickedTab = tab;
// Push to navigation history for back button support
setFavoritesTab(tab);
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) {
@@ -483,6 +468,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;
@@ -715,7 +709,6 @@
trackIds, trackIds,
index index
); );
console.log(`[Favorites] Context created: ${trackIds.length} tracks, starting at ${index}`);
} }
// Play track // Play track
@@ -757,7 +750,11 @@
style={favoritesPreferences.icon_background ? `background: ${favoritesPreferences.icon_background};` : ''} style={favoritesPreferences.icon_background ? `background: ${favoritesPreferences.icon_background};` : ''}
> >
{#if favoritesPreferences.custom_icon_path} {#if favoritesPreferences.custom_icon_path}
<img src="asset://localhost/{favoritesPreferences.custom_icon_path}" alt="Custom Icon" class="custom-icon-img" /> <img
src={`asset://localhost/${encodeURIComponent(favoritesPreferences.custom_icon_path)}`}
alt="Custom Icon"
class="custom-icon-img"
/>
{:else if favoritesPreferences.custom_icon_preset} {:else if favoritesPreferences.custom_icon_preset}
{#if favoritesPreferences.custom_icon_preset === 'heart'} {#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)" />
@@ -991,7 +988,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}
+64 -45
View File
@@ -6,7 +6,20 @@
* 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'; export type FavoritesTab = 'tracks' | 'albums' | 'artists' | 'playlists';
// Navigation state // Navigation state
@@ -20,8 +33,38 @@ 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;
// Selected Favorites tab (for history-aware navigation) // Last visited Favorites tab (used as default when navigating to Favorites)
let selectedFavoritesTab: FavoritesTab = 'tracks'; 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>();
@@ -46,30 +89,17 @@ export function subscribe(listener: () => void): () => void {
/** /**
* Navigate to a view * Navigate to a view
*/ */
export function navigateTo(view: ViewType, favoritesTab?: FavoritesTab): void { export function navigateTo(view: ViewType): void {
// For favorites view, allow sub-navigation by tracking tab changes
if (view === 'favorites' && favoritesTab && activeView === 'favorites' && favoritesTab !== selectedFavoritesTab) {
// Changing tabs within Favorites - push to history
viewHistory = [...viewHistory, view];
selectedFavoritesTab = favoritesTab;
notifyListeners();
return;
}
if (view !== activeView) { if (view !== activeView) {
viewHistory = [...viewHistory, view]; viewHistory = [...viewHistory, view];
forwardHistory = []; forwardHistory = [];
activeView = view; activeView = view;
// Update favorites tab if specified const tab = getFavoritesTabFromView(view);
if (view === 'favorites' && favoritesTab) { if (tab) {
selectedFavoritesTab = favoritesTab; lastFavoritesTab = tab;
} }
notifyListeners();
} else if (view === 'favorites' && favoritesTab && favoritesTab !== selectedFavoritesTab) {
// Same view but different tab - just update tab without history
selectedFavoritesTab = favoritesTab;
notifyListeners(); notifyListeners();
} }
} }
@@ -84,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;
} }
@@ -100,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;
} }
@@ -175,27 +213,10 @@ export function getSelectedLocalAlbumId(): string | null {
return selectedLocalAlbumId; return selectedLocalAlbumId;
} }
// ============ Favorites Tab Selection ============ // ============ Favorites Navigation ============
export function navigateToFavorites(tab?: FavoritesTab): void {
/** const targetTab = tab ?? lastFavoritesTab;
* Get selected Favorites tab navigateTo(favoritesViewForTab(targetTab));
*/
export function getSelectedFavoritesTab(): FavoritesTab {
return selectedFavoritesTab;
}
/**
* Set selected Favorites tab (creates history entry if already on favorites view)
*/
export function setFavoritesTab(tab: FavoritesTab): void {
if (activeView === 'favorites' && tab !== selectedFavoritesTab) {
// Push to history to allow back navigation
viewHistory = [...viewHistory, 'favorites'];
selectedFavoritesTab = tab;
notifyListeners();
} else if (activeView !== 'favorites') {
selectedFavoritesTab = tab;
}
} }
// ============ Getters ============ // ============ Getters ============
@@ -212,7 +233,6 @@ export interface NavigationState {
forwardHistory: ViewType[]; forwardHistory: ViewType[];
selectedPlaylistId: number | null; selectedPlaylistId: number | null;
selectedLocalAlbumId: string | null; selectedLocalAlbumId: string | null;
selectedFavoritesTab: FavoritesTab;
canGoBack: boolean; canGoBack: boolean;
canGoForward: boolean; canGoForward: boolean;
} }
@@ -224,7 +244,6 @@ export function getNavigationState(): NavigationState {
forwardHistory: [...forwardHistory], forwardHistory: [...forwardHistory],
selectedPlaylistId, selectedPlaylistId,
selectedLocalAlbumId, selectedLocalAlbumId,
selectedFavoritesTab,
canGoBack: viewHistory.length > 1, canGoBack: viewHistory.length > 1,
canGoForward: forwardHistory.length > 0 canGoForward: forwardHistory.length > 0
}; };
+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';
}
+26 -4
View File
@@ -71,16 +71,20 @@
// 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,
getSelectedFavoritesTab, getFavoritesTabFromView,
isFavoritesView,
type ViewType, type ViewType,
type NavigationState, type NavigationState,
type FavoritesTab type FavoritesTab
@@ -337,9 +341,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);
} }
@@ -2163,7 +2184,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}
@@ -2196,7 +2217,8 @@
onTrackRemoveDownload={handleTrackRemoveDownload} onTrackRemoveDownload={handleTrackRemoveDownload}
getTrackDownloadStatus={getTrackDownloadStatus} getTrackDownloadStatus={getTrackDownloadStatus}
onPlaylistSelect={selectPlaylist} onPlaylistSelect={selectPlaylist}
currentTab={getSelectedFavoritesTab()} selectedTab={getFavoritesTabFromView(activeView) ?? favoritesDefaultTab}
onTabNavigate={(tab) => navigateToFavorites(tab)}
/> />
{/if} {/if}
{:else if activeView === 'playlist-manager'} {:else if activeView === 'playlist-manager'}