feat(library): genre sliders, artist links, and navigation utils
- music landing: diverse per-genre album sliders (online counts / offline wide-probe fallback) and home-screen library shortcuts - add ArtistLinks component and shared navigation/genreDiversity utils - player/playback-mode refinements across Rust and frontend
This commit is contained in:
+79
-2
@@ -1276,6 +1276,11 @@ async convertPercentToVolume(percent: number) : Promise<number> {
|
||||
/** user-defined events **/
|
||||
|
||||
|
||||
export const events = __makeEvents__<{
|
||||
playerStatusEvent: PlayerStatusEvent
|
||||
}>({
|
||||
playerStatusEvent: "player-status-event"
|
||||
})
|
||||
|
||||
/** user-defined constants **/
|
||||
|
||||
@@ -1471,7 +1476,13 @@ export type DownloadsResponse = { downloads: DownloadInfo[]; stats: DownloadStat
|
||||
/**
|
||||
* Genre
|
||||
*/
|
||||
export type Genre = { id: string; name: string }
|
||||
export type Genre = { id: string; name: string;
|
||||
/**
|
||||
* Number of albums tagged with this genre, when the backend can supply it
|
||||
* (online only). Lets the frontend rank/pick genres without probing each
|
||||
* one. `None` when unknown (e.g. offline).
|
||||
*/
|
||||
albumCount: number | null }
|
||||
/**
|
||||
* Request to get an image URL (with caching)
|
||||
*/
|
||||
@@ -1610,7 +1621,12 @@ export type PlayTracksContext = { type: "playlist"; playlistId: string; playlist
|
||||
/**
|
||||
* Request to play tracks by ID (backend fetches metadata)
|
||||
*/
|
||||
export type PlayTracksRequest = { trackIds: string[]; startIndex: number; shuffle: boolean; context: PlayTracksContext }
|
||||
export type PlayTracksRequest = { trackIds: string[]; startIndex: number; shuffle: boolean; context: PlayTracksContext;
|
||||
/**
|
||||
* Position (seconds) to resume the starting track from. Used when taking
|
||||
* over playback from a remote session so we don't restart from 0.
|
||||
*/
|
||||
startPosition?: number | null }
|
||||
/**
|
||||
* Playback information
|
||||
*/
|
||||
@@ -1791,6 +1807,67 @@ mergedIsPlaying: boolean;
|
||||
* Volume from either local player or remote session (0-1 normalized)
|
||||
*/
|
||||
mergedVolume: number }
|
||||
/**
|
||||
* Events emitted by the player backend to the frontend via Tauri events.
|
||||
*
|
||||
* These are distinct from `PlayerEvent` in state.rs, which handles internal
|
||||
* state machine transitions.
|
||||
*
|
||||
* TRACES: UR-005, UR-019, UR-023, UR-026 | DR-001, DR-028, DR-047
|
||||
*/
|
||||
export type PlayerStatusEvent =
|
||||
/**
|
||||
* Playback position updated (emitted periodically during playback)
|
||||
*/
|
||||
{ type: "position_update"; position: number; duration: number } |
|
||||
/**
|
||||
* Player state changed
|
||||
*/
|
||||
{ type: "state_changed"; state: string; media_id: string | null } |
|
||||
/**
|
||||
* Media has finished loading and is ready to play
|
||||
*/
|
||||
{ type: "media_loaded"; duration: number } |
|
||||
/**
|
||||
* Playback has ended naturally (reached end of media)
|
||||
*/
|
||||
{ type: "playback_ended" } |
|
||||
/**
|
||||
* Buffering state changed
|
||||
*/
|
||||
{ type: "buffering"; percent: number } |
|
||||
/**
|
||||
* An error occurred during playback
|
||||
*/
|
||||
{ type: "error"; message: string; recoverable: boolean } |
|
||||
/**
|
||||
* Volume changed
|
||||
*/
|
||||
{ type: "volume_changed"; volume: number; muted: boolean } |
|
||||
/**
|
||||
* Sleep timer state changed
|
||||
*/
|
||||
{ type: "sleep_timer_changed"; mode: SleepTimerMode; remaining_seconds: number } |
|
||||
/**
|
||||
* Show next episode popup with countdown
|
||||
*/
|
||||
{ type: "show_next_episode_popup"; current_episode: MediaItem; next_episode: MediaItem; countdown_seconds: number; auto_advance: boolean } |
|
||||
/**
|
||||
* Countdown tick (emitted every second during autoplay countdown)
|
||||
*/
|
||||
{ type: "countdown_tick"; remaining_seconds: number } |
|
||||
/**
|
||||
* Queue changed (items added, removed, reordered, or playback mode changed)
|
||||
*/
|
||||
{ type: "queue_changed"; items: PlayerMediaItem[]; current_index: number | null; shuffle: boolean; repeat: RepeatMode; has_next: boolean; has_previous: boolean } |
|
||||
/**
|
||||
* Media session changed (activity context changed: Audio/Movie/TvShow/Idle)
|
||||
*/
|
||||
{ type: "session_changed"; session: MediaSessionType } |
|
||||
/**
|
||||
* Remote sessions updated (for cast/remote control UI)
|
||||
*/
|
||||
{ type: "sessions_updated"; sessions: SessionInfo[] }
|
||||
/**
|
||||
* Result of creating a playlist
|
||||
*
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
// and adds frontend-only unions/helpers that have no backend equivalent.
|
||||
|
||||
export type {
|
||||
ArtistItem,
|
||||
AuthResult,
|
||||
Genre,
|
||||
GetItemsOptions,
|
||||
|
||||
@@ -26,17 +26,28 @@
|
||||
|
||||
let { availableLetters, onJump, bottomGap = "5rem" }: Props = $props();
|
||||
|
||||
// The strip stretches to fill the height of its scroll container (the page's
|
||||
// <main>, which sits below the sticky header) from the sticky top offset down
|
||||
// to the bottom gap reserved for the nav / mini-player bars. We measure the
|
||||
// container's visible height live so it stays correct regardless of header
|
||||
// size, platform, or window resizes.
|
||||
// The strip stretches from where it sits down to just above the bottom nav /
|
||||
// mini-player bars. Those bars are pinned to the bottom of the screen, so the
|
||||
// hard floor is `window.innerHeight - bottomGap`. We measure the strip's own
|
||||
// top against that floor (clamped to non-negative) and update on scroll/resize
|
||||
// so it never slides under the bars regardless of header or platform.
|
||||
let container = $state<HTMLDivElement | null>(null);
|
||||
let viewportHeight = $state(0);
|
||||
let stripHeight = $state(0);
|
||||
|
||||
function measure() {
|
||||
const scroller = container?.closest("main") ?? document.documentElement;
|
||||
viewportHeight = scroller.clientHeight;
|
||||
if (!container) return;
|
||||
const top = container.getBoundingClientRect().top;
|
||||
const floor = window.innerHeight - remToPx(bottomGap);
|
||||
stripHeight = Math.max(0, floor - top);
|
||||
}
|
||||
|
||||
function remToPx(len: string): number {
|
||||
const n = parseFloat(len);
|
||||
if (len.trim().endsWith("rem")) {
|
||||
const root = parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
|
||||
return n * root;
|
||||
}
|
||||
return n; // assume px otherwise
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
@@ -44,13 +55,21 @@
|
||||
const scroller = container?.closest("main");
|
||||
const ro = new ResizeObserver(measure);
|
||||
if (scroller) ro.observe(scroller);
|
||||
scroller?.addEventListener("scroll", measure, { passive: true });
|
||||
window.addEventListener("resize", measure);
|
||||
return () => {
|
||||
ro.disconnect();
|
||||
scroller?.removeEventListener("scroll", measure);
|
||||
window.removeEventListener("resize", measure);
|
||||
};
|
||||
});
|
||||
|
||||
// Recompute when the reserved bottom gap changes (mini-player shows/hides).
|
||||
$effect(() => {
|
||||
bottomGap;
|
||||
measure();
|
||||
});
|
||||
|
||||
const letters = $derived([HASH, ...ALPHABET]);
|
||||
let activeLetter = $state<string | null>(null);
|
||||
|
||||
@@ -99,7 +118,7 @@
|
||||
<div
|
||||
bind:this={container}
|
||||
class="flex flex-col items-center justify-between select-none touch-none py-1"
|
||||
style="height: calc({viewportHeight}px - 1.5rem - {bottomGap})"
|
||||
style="height: {stripHeight}px"
|
||||
onpointerdown={handlePointerDown}
|
||||
onpointermove={handlePointerMove}
|
||||
role="navigation"
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
<script lang="ts">
|
||||
import { goto } from "$app/navigation";
|
||||
import type { ArtistItem } from "$lib/api/types";
|
||||
|
||||
/**
|
||||
* Renders a comma-separated list of artist names. When the artists carry
|
||||
* ids (artistItems) each name links to that artist's detail page; otherwise
|
||||
* it falls back to plain text from the names-only `artists` array.
|
||||
*
|
||||
* Consolidates the artist-linking markup used on the player and detail
|
||||
* screens so every surface behaves the same way.
|
||||
*/
|
||||
interface Props {
|
||||
artistItems?: ArtistItem[] | null;
|
||||
artists?: string[] | null;
|
||||
/** Tailwind classes for the link colour/state. */
|
||||
linkClass?: string;
|
||||
/** Tailwind classes for the non-linkable fallback text. */
|
||||
textClass?: string;
|
||||
/** Called before navigating (e.g. to close a full-screen player). */
|
||||
onNavigate?: () => void;
|
||||
}
|
||||
|
||||
let {
|
||||
artistItems = null,
|
||||
artists = null,
|
||||
linkClass = "text-[var(--color-jellyfin)] hover:underline",
|
||||
textClass = "text-gray-400",
|
||||
onNavigate,
|
||||
}: Props = $props();
|
||||
|
||||
const linkable = $derived(
|
||||
(artistItems ?? []).filter((a) => a.id && a.id.trim() !== "")
|
||||
);
|
||||
|
||||
function handleClick(artistId: string, e: MouseEvent) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onNavigate?.();
|
||||
goto(`/library/${artistId}`);
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if linkable.length > 0}
|
||||
<span class="inline-flex flex-wrap items-baseline gap-1">
|
||||
{#each linkable as artist, i (artist.id)}
|
||||
<button onclick={(e) => handleClick(artist.id, e)} class={linkClass}>
|
||||
{artist.name}
|
||||
</button>{#if i < linkable.length - 1}<span class={textClass}>,</span>{/if}
|
||||
{/each}
|
||||
</span>
|
||||
{:else if artists && artists.length > 0}
|
||||
<span class={textClass}>{artists.join(", ")}</span>
|
||||
{/if}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent } from "@testing-library/svelte";
|
||||
import ArtistLinks from "./ArtistLinks.svelte";
|
||||
|
||||
const goto = vi.fn();
|
||||
vi.mock("$app/navigation", () => ({
|
||||
goto: (...args: unknown[]) => goto(...args),
|
||||
}));
|
||||
|
||||
describe("ArtistLinks", () => {
|
||||
beforeEach(() => goto.mockClear());
|
||||
|
||||
it("renders a clickable link per artist that navigates to its detail page", async () => {
|
||||
render(ArtistLinks, {
|
||||
artistItems: [
|
||||
{ id: "a1", name: "Radiohead" },
|
||||
{ id: "a2", name: "Thom Yorke" },
|
||||
],
|
||||
});
|
||||
|
||||
const link = screen.getByRole("button", { name: "Radiohead" });
|
||||
await fireEvent.click(link);
|
||||
|
||||
expect(goto).toHaveBeenCalledWith("/library/a1");
|
||||
expect(screen.getByRole("button", { name: "Thom Yorke" })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("falls back to plain text when only names (no ids) are available", () => {
|
||||
render(ArtistLinks, { artists: ["Unknown Artist"] });
|
||||
|
||||
expect(screen.queryByRole("button")).toBeNull();
|
||||
expect(screen.getByText("Unknown Artist")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("ignores artistItems with blank ids and uses the names fallback", () => {
|
||||
render(ArtistLinks, {
|
||||
artistItems: [{ id: " ", name: "No Id Artist" }],
|
||||
artists: ["No Id Artist"],
|
||||
});
|
||||
|
||||
expect(screen.queryByRole("button")).toBeNull();
|
||||
expect(screen.getByText("No Id Artist")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("calls onNavigate before navigating (e.g. to close a player)", async () => {
|
||||
const onNavigate = vi.fn();
|
||||
render(ArtistLinks, {
|
||||
artistItems: [{ id: "a1", name: "Radiohead" }],
|
||||
onNavigate,
|
||||
});
|
||||
|
||||
await fireEvent.click(screen.getByRole("button", { name: "Radiohead" }));
|
||||
|
||||
expect(onNavigate).toHaveBeenCalledOnce();
|
||||
expect(goto).toHaveBeenCalledWith("/library/a1");
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
import { goto } from "$app/navigation";
|
||||
import { navigateBack } from "$lib/utils/navigation";
|
||||
import { currentLibrary } from "$lib/stores/library";
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import SearchBar from "$lib/components/common/SearchBar.svelte";
|
||||
@@ -125,7 +126,7 @@
|
||||
selectedGenre = null;
|
||||
genreItems = [];
|
||||
} else {
|
||||
goto(config.backPath);
|
||||
navigateBack(config.backPath);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
import { goto } from "$app/navigation";
|
||||
import { navigateBack } from "$lib/utils/navigation";
|
||||
import { currentLibrary } from "$lib/stores/library";
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import { shouldShowAudioMiniPlayer } from "$lib/stores/player";
|
||||
@@ -130,7 +131,7 @@
|
||||
}
|
||||
|
||||
function goBack() {
|
||||
goto(config.backPath);
|
||||
navigateBack(config.backPath);
|
||||
}
|
||||
|
||||
const searchPlaceholder = $derived(config.searchPlaceholder || `Search ${config.title.toLowerCase()}...`);
|
||||
|
||||
@@ -43,6 +43,18 @@
|
||||
let videoElement: HTMLVideoElement | null = $state(null);
|
||||
let isPlaying = $state(false);
|
||||
let currentTime = $state(0);
|
||||
// Guards against onEnded() firing more than once per loaded stream. For
|
||||
// transcoded HLS, both the native `ended` event and the "fatal network error
|
||||
// near end of stream" recovery path can fire for the same playback, which
|
||||
// would otherwise call playerOnPlaybackEnded twice (e.g. decrementing the
|
||||
// sleep-timer episode counter twice). Reset when the stream URL changes.
|
||||
let endedFired = $state(false);
|
||||
|
||||
function notifyEnded() {
|
||||
if (endedFired) return;
|
||||
endedFired = true;
|
||||
onEnded?.();
|
||||
}
|
||||
let isFullscreen = $state(false);
|
||||
let showControls = $state(true);
|
||||
let showSleepTimerModal = $state(false);
|
||||
@@ -188,6 +200,7 @@
|
||||
seekOffset = 0;
|
||||
isMediaReady = false; // Reset to loading state when stream URL changes
|
||||
hasPerformedInitialSeek = false; // Reset so new video can seek to initial position
|
||||
endedFired = false; // New stream loaded - allow onEnded to fire again
|
||||
}
|
||||
});
|
||||
|
||||
@@ -285,9 +298,7 @@
|
||||
if (isNearEnd) {
|
||||
// Near end of stream - treat as natural end, don't restart
|
||||
console.log('[VideoPlayer] Fatal network error near end of stream - treating as ended');
|
||||
if (onEnded) {
|
||||
onEnded();
|
||||
}
|
||||
notifyEnded();
|
||||
} else if (hlsFatalRecoveryAttempts <= 3) {
|
||||
console.error('[VideoPlayer] Fatal network error, trying to recover (attempt', hlsFatalRecoveryAttempts, ')');
|
||||
hls!.startLoad();
|
||||
@@ -762,9 +773,7 @@
|
||||
onReportStop(currentTime, reportMediaId);
|
||||
}
|
||||
// Notify parent that video has ended (for next episode popup)
|
||||
if (onEnded) {
|
||||
onEnded();
|
||||
}
|
||||
notifyEnded();
|
||||
}
|
||||
|
||||
async function togglePlayPause() {
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
* TRACES: UR-005, UR-019, UR-023, UR-026 | DR-001, DR-028, DR-047
|
||||
*/
|
||||
|
||||
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import { type UnlistenFn } from "@tauri-apps/api/event";
|
||||
import { commands, events, type PlayerStatusEvent, type SleepTimerMode } from "$lib/api/bindings";
|
||||
import { player, playbackPosition } from "$lib/stores/player";
|
||||
import { queue, currentQueueItem } from "$lib/stores/queue";
|
||||
import { playbackMode } from "$lib/stores/playbackMode";
|
||||
@@ -20,33 +20,9 @@ import { preloadUpcomingTracks } from "$lib/services/preload";
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
import { get } from "svelte/store";
|
||||
|
||||
/**
|
||||
* Event types emitted by the player backend.
|
||||
* Must match PlayerStatusEvent in src-tauri/src/player/events.rs
|
||||
*
|
||||
* TRACES: UR-005, UR-019, UR-023, UR-026 | DR-001, DR-028, DR-047
|
||||
*/
|
||||
export type PlayerStatusEvent =
|
||||
| { type: "position_update"; position: number; duration: number }
|
||||
| { type: "state_changed"; state: string; media_id: string | null }
|
||||
| { type: "media_loaded"; duration: number }
|
||||
| { type: "playback_ended" }
|
||||
| { type: "buffering"; percent: number }
|
||||
| { type: "error"; message: string; recoverable: boolean }
|
||||
| { type: "volume_changed"; volume: number; muted: boolean }
|
||||
| { type: "sleep_timer_changed"; mode: SleepTimerMode; remaining_seconds: number }
|
||||
| { type: "show_next_episode_popup"; current_episode: MediaItem; next_episode: MediaItem; countdown_seconds: number; auto_advance: boolean }
|
||||
| { type: "countdown_tick"; remaining_seconds: number };
|
||||
|
||||
// Sleep timer mode type
|
||||
export type SleepTimerMode =
|
||||
| { kind: "off" }
|
||||
| { kind: "time"; endTime: number }
|
||||
| { kind: "endOfTrack" }
|
||||
| { kind: "episodes"; remaining: number };
|
||||
|
||||
/** Event name for player status events from backend */
|
||||
const PLAYER_EVENT_NAME = "player-event";
|
||||
// PlayerStatusEvent and SleepTimerMode are generated by tauri-specta and
|
||||
// imported from $lib/api/bindings — they are the authoritative shapes emitted
|
||||
// by src-tauri/src/player/events.rs.
|
||||
|
||||
let unlistenFn: UnlistenFn | null = null;
|
||||
let isInitialized = false;
|
||||
@@ -62,12 +38,9 @@ export async function initPlayerEvents(): Promise<void> {
|
||||
}
|
||||
|
||||
try {
|
||||
unlistenFn = await listen<PlayerStatusEvent>(
|
||||
PLAYER_EVENT_NAME,
|
||||
(event) => {
|
||||
handlePlayerEvent(event.payload);
|
||||
}
|
||||
);
|
||||
unlistenFn = await events.playerStatusEvent.listen((event) => {
|
||||
handlePlayerEvent(event.payload);
|
||||
});
|
||||
isInitialized = true;
|
||||
console.log("Player event listener initialized");
|
||||
} catch (e) {
|
||||
@@ -152,6 +125,10 @@ function handlePlayerEvent(event: PlayerStatusEvent): void {
|
||||
case "countdown_tick":
|
||||
handleCountdownTick(event.remaining_seconds);
|
||||
break;
|
||||
|
||||
// queue_changed is handled by the queue store's own listener
|
||||
// ($lib/stores/queue), which is the single source of truth for
|
||||
// shuffle/repeat/next/previous. No action needed here.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,8 +181,6 @@ async function handleStateChanged(state: string, _mediaId: string | null): Promi
|
||||
player.setLoading(currentItem);
|
||||
}
|
||||
|
||||
// Update queue status on state change
|
||||
await updateQueueStatus();
|
||||
break;
|
||||
|
||||
case "idle":
|
||||
@@ -218,31 +193,10 @@ async function handleStateChanged(state: string, _mediaId: string | null): Promi
|
||||
playbackMode.setMode("idle");
|
||||
}
|
||||
|
||||
// Update queue status on state change
|
||||
await updateQueueStatus();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update queue status from backend.
|
||||
* Called on state changes instead of polling.
|
||||
*/
|
||||
async function updateQueueStatus(): Promise<void> {
|
||||
try {
|
||||
const queueStatus = await commands.playerGetQueue();
|
||||
|
||||
// Import appState stores dynamically to avoid circular imports
|
||||
const { hasNext, hasPrevious, shuffle, repeat } = await import("$lib/stores/appState");
|
||||
hasNext.set(queueStatus.hasNext);
|
||||
hasPrevious.set(queueStatus.hasPrevious);
|
||||
shuffle.set(queueStatus.shuffle);
|
||||
repeat.set(queueStatus.repeat as "off" | "all" | "one");
|
||||
} catch (e) {
|
||||
console.error("[playerEvents] Failed to update queue status:", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle media loaded event.
|
||||
*/
|
||||
|
||||
@@ -6,10 +6,8 @@ import { writable } from 'svelte/store';
|
||||
export const isInitialized = writable(false);
|
||||
export const pendingSyncCount = writable(0);
|
||||
export const isAndroid = writable(false);
|
||||
export const shuffle = writable(false);
|
||||
export const repeat = writable<'off' | 'all' | 'one'>('off');
|
||||
export const hasNext = writable(false);
|
||||
export const hasPrevious = writable(false);
|
||||
// Shuffle/repeat/next/previous state now lives in the event-driven queue store
|
||||
// ($lib/stores/queue), the single source of truth.
|
||||
export const showSleepTimerModal = writable(false);
|
||||
|
||||
// Library-specific state
|
||||
|
||||
+91
-1
@@ -2,9 +2,17 @@
|
||||
// Powers the focused music landing: hero + horizontal sliders.
|
||||
// TRACES: UR-007, UR-034 | DR-007, DR-038, DR-039
|
||||
import { writable, derived } from "svelte/store";
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
import type { MediaItem, Genre } from "$lib/api/types";
|
||||
import { auth } from "./auth";
|
||||
import { excludePodcasts } from "$lib/utils/podcastFilter";
|
||||
import { selectDiverseGenres, sampleAcross } from "$lib/utils/genreDiversity";
|
||||
|
||||
/** A single "by genre" row: the genre name plus the albums in it. */
|
||||
export interface GenreRow {
|
||||
id: string;
|
||||
name: string;
|
||||
items: MediaItem[];
|
||||
}
|
||||
|
||||
interface MusicState {
|
||||
// Albums grouped from recently played tracks (backend handles grouping).
|
||||
@@ -15,6 +23,8 @@ interface MusicState {
|
||||
playlists: MediaItem[];
|
||||
// Albums the user has played but hasn't returned to in a while.
|
||||
rediscover: MediaItem[];
|
||||
// One slider per genre (top genres by album count).
|
||||
genreRows: GenreRow[];
|
||||
// Mix of recently played + rediscover, used for the hero banner.
|
||||
heroItems: MediaItem[];
|
||||
isLoading: boolean;
|
||||
@@ -22,6 +32,11 @@ interface MusicState {
|
||||
}
|
||||
|
||||
const SECTION_LIMIT = 16;
|
||||
// How many genre sliders to show, and how many genres to probe to find them.
|
||||
const MAX_GENRE_ROWS = 8;
|
||||
// Probe a wide pool so the diverse-selection step has genres from across the
|
||||
// whole (alphabetical) list to choose between, not just the first handful.
|
||||
const MAX_GENRES_PROBED = 40;
|
||||
|
||||
function createMusicStore() {
|
||||
const initialState: MusicState = {
|
||||
@@ -29,6 +44,7 @@ function createMusicStore() {
|
||||
newlyAdded: [],
|
||||
playlists: [],
|
||||
rediscover: [],
|
||||
genreRows: [],
|
||||
heroItems: [],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
@@ -110,6 +126,10 @@ function createMusicStore() {
|
||||
heroItems,
|
||||
isLoading: false,
|
||||
}));
|
||||
|
||||
// Genre rows are secondary — load them after the main sections paint so
|
||||
// the page isn't blocked on N per-genre queries.
|
||||
loadGenreRows(libraryId);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to load music sections";
|
||||
update(s => ({ ...s, isLoading: false, error: message }));
|
||||
@@ -117,6 +137,76 @@ function createMusicStore() {
|
||||
}
|
||||
}
|
||||
|
||||
/** Fetch up to SECTION_LIMIT albums for one genre as a slider row. */
|
||||
async function loadGenreRow(libraryId: string, genre: Genre): Promise<GenreRow> {
|
||||
const repo = auth.getRepository();
|
||||
try {
|
||||
const result = await repo.getItems(libraryId, {
|
||||
includeItemTypes: ["MusicAlbum"],
|
||||
genres: [genre.name],
|
||||
sortBy: "SortName",
|
||||
sortOrder: "Ascending",
|
||||
recursive: true,
|
||||
limit: SECTION_LIMIT,
|
||||
});
|
||||
// HACK: drop the "Podcasts" folder that lives in the music library.
|
||||
return { id: genre.id, name: genre.name, items: excludePodcasts(result.items) };
|
||||
} catch (e) {
|
||||
console.warn(`Failed to load genre row "${genre.name}":`, e);
|
||||
return { id: genre.id, name: genre.name, items: [] };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build one slider per genre, showing albums in each. We pick a *diverse* set
|
||||
* rather than just the most populous — otherwise a cluster of near-synonyms
|
||||
* ("Rock", "Hard Rock", "Classic Rock", ...) crowds out musically distinct
|
||||
* genres. See selectDiverseGenres. Album genres rarely carry community
|
||||
* ratings, so we order each row by name.
|
||||
*
|
||||
* When the backend reports per-genre album counts (online), we rank and pick
|
||||
* before fetching, so we only query albums for the genres we'll actually
|
||||
* show. When counts are missing (offline), we fall back to probing a wide
|
||||
* pool, dropping empties, then ranking by what came back.
|
||||
*/
|
||||
async function loadGenreRows(libraryId: string) {
|
||||
try {
|
||||
const repo = auth.getRepository();
|
||||
const genres = await repo.getGenres(libraryId);
|
||||
if (genres.length === 0) return;
|
||||
|
||||
const hasCounts = genres.some(g => g.albumCount != null);
|
||||
|
||||
let genreRows: GenreRow[];
|
||||
if (hasCounts) {
|
||||
// Rank by reported count, pick a diverse subset, then fetch only those.
|
||||
const ranked = [...genres].sort(
|
||||
(a, b) => (b.albumCount ?? 0) - (a.albumCount ?? 0)
|
||||
);
|
||||
const chosen = selectDiverseGenres(ranked, MAX_GENRE_ROWS);
|
||||
genreRows = (await Promise.all(chosen.map(g => loadGenreRow(libraryId, g)))).filter(
|
||||
row => row.items.length > 0
|
||||
);
|
||||
} else {
|
||||
// No counts (offline, or a server that ignores Fields=ItemCounts).
|
||||
// The genre list is alphabetical, so probing the first N would only
|
||||
// ever surface A-genres. Sample at an even stride across the whole
|
||||
// list instead, so the probe pool spans A→Z; then drop empties, rank
|
||||
// by what came back, and pick a diverse subset.
|
||||
const probed = sampleAcross(genres, MAX_GENRES_PROBED);
|
||||
const rows = await Promise.all(probed.map(g => loadGenreRow(libraryId, g)));
|
||||
const populated = rows
|
||||
.filter(row => row.items.length > 0)
|
||||
.sort((a, b) => b.items.length - a.items.length);
|
||||
genreRows = selectDiverseGenres(populated, MAX_GENRE_ROWS);
|
||||
}
|
||||
|
||||
update(s => ({ ...s, genreRows }));
|
||||
} catch (e) {
|
||||
console.warn("Failed to load music genre rows:", e);
|
||||
}
|
||||
}
|
||||
|
||||
function reset() {
|
||||
set(initialState);
|
||||
}
|
||||
|
||||
@@ -9,26 +9,31 @@ vi.mock("@tauri-apps/api/core", () => ({
|
||||
invoke: (...args: unknown[]) => mockInvoke(...args),
|
||||
}));
|
||||
|
||||
// Mock the sessions store
|
||||
// Mock the sessions store. `selectedSession` is read via svelte's `get()`, which
|
||||
// calls subscribe and synchronously receives the current value; tests set
|
||||
// `currentSelectedSession` to control what the store yields.
|
||||
const mockSelectSession = vi.fn();
|
||||
let currentSelectedSession: unknown = null;
|
||||
vi.mock("./sessions", () => ({
|
||||
sessions: {
|
||||
selectSession: (...args: unknown[]) => mockSelectSession(...args),
|
||||
},
|
||||
selectedSession: {
|
||||
subscribe: vi.fn((callback: (value: null) => void) => {
|
||||
callback(null);
|
||||
subscribe: vi.fn((callback: (value: unknown) => void) => {
|
||||
callback(currentSelectedSession);
|
||||
return () => {};
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock auth store
|
||||
const mockGetHandle = vi.fn(() => "repo-handle-1");
|
||||
vi.mock("./auth", () => ({
|
||||
auth: {
|
||||
getRepository: vi.fn(() => ({
|
||||
getPlaybackInfo: vi.fn().mockResolvedValue({ streamUrl: "http://test.com/stream" }),
|
||||
getImageUrl: vi.fn().mockReturnValue("http://test.com/image"),
|
||||
getHandle: () => mockGetHandle(),
|
||||
})),
|
||||
},
|
||||
}));
|
||||
@@ -36,6 +41,7 @@ vi.mock("./auth", () => ({
|
||||
describe("playbackMode store", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
currentSelectedSession = null;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -204,6 +210,90 @@ describe("playbackMode store", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("transferToLocal", () => {
|
||||
// 50,000,000 ticks = 5 seconds (10M ticks per second).
|
||||
const REMOTE_POSITION_TICKS = 50_000_000;
|
||||
const REMOTE_POSITION_SECONDS = 5;
|
||||
|
||||
function setRemoteSessionPlaying() {
|
||||
currentSelectedSession = {
|
||||
id: "session-123",
|
||||
nowPlayingItem: { id: "item-abc", name: "Test Track", runTimeTicks: 1_800_000_000 },
|
||||
playState: { positionTicks: REMOTE_POSITION_TICKS },
|
||||
};
|
||||
}
|
||||
|
||||
it("resumes local playback at the remote position, not from 0", async () => {
|
||||
const { playbackMode } = await import("./playbackMode");
|
||||
|
||||
playbackMode.setMode("remote", "session-123");
|
||||
setRemoteSessionPlaying();
|
||||
mockInvoke.mockResolvedValue(undefined);
|
||||
|
||||
await playbackMode.transferToLocal();
|
||||
|
||||
// Bug 2 guard: the resume position must be passed to play_tracks so the
|
||||
// backend seeks at load time. Restarting from 0 means startPosition is missing.
|
||||
const playTracksCall = mockInvoke.mock.calls.find((c) => c[0] === "player_play_tracks");
|
||||
expect(playTracksCall).toBeDefined();
|
||||
expect(playTracksCall![1]).toMatchObject({
|
||||
repositoryHandle: "repo-handle-1",
|
||||
request: {
|
||||
trackIds: ["item-abc"],
|
||||
startIndex: 0,
|
||||
startPosition: REMOTE_POSITION_SECONDS,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("does not issue a separate player_seek (no start-at-0-then-jump race)", async () => {
|
||||
const { playbackMode } = await import("./playbackMode");
|
||||
|
||||
playbackMode.setMode("remote", "session-123");
|
||||
setRemoteSessionPlaying();
|
||||
mockInvoke.mockResolvedValue(undefined);
|
||||
|
||||
await playbackMode.transferToLocal();
|
||||
|
||||
const seekCall = mockInvoke.mock.calls.find((c) => c[0] === "player_seek");
|
||||
expect(seekCall).toBeUndefined();
|
||||
});
|
||||
|
||||
it("tells Rust to stop the remote session with the current item and position", async () => {
|
||||
const { playbackMode } = await import("./playbackMode");
|
||||
|
||||
playbackMode.setMode("remote", "session-123");
|
||||
setRemoteSessionPlaying();
|
||||
mockInvoke.mockResolvedValue(undefined);
|
||||
|
||||
await playbackMode.transferToLocal();
|
||||
|
||||
expect(mockInvoke).toHaveBeenCalledWith("playback_mode_transfer_to_local", {
|
||||
currentItemId: "item-abc",
|
||||
positionTicks: REMOTE_POSITION_TICKS,
|
||||
});
|
||||
|
||||
const state = get(playbackMode);
|
||||
expect(state.mode).toBe("local");
|
||||
expect(state.remoteSessionId).toBeNull();
|
||||
expect(state.isTransferring).toBe(false);
|
||||
});
|
||||
|
||||
it("switches to local without playing media when remote has nothing playing", async () => {
|
||||
const { playbackMode } = await import("./playbackMode");
|
||||
|
||||
playbackMode.setMode("remote", "session-123");
|
||||
currentSelectedSession = { id: "session-123", nowPlayingItem: null, playState: null };
|
||||
|
||||
await playbackMode.transferToLocal();
|
||||
|
||||
expect(mockInvoke).not.toHaveBeenCalledWith("player_play_tracks", expect.anything());
|
||||
const state = get(playbackMode);
|
||||
expect(state.mode).toBe("local");
|
||||
expect(state.remoteSessionId).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("clearError", () => {
|
||||
it("should clear transfer error", async () => {
|
||||
const { playbackMode } = await import("./playbackMode");
|
||||
|
||||
@@ -192,10 +192,14 @@ function createPlaybackModeStore() {
|
||||
// Use player_play_tracks - backend fetches all metadata from single ID
|
||||
const repositoryHandle = repository.getHandle();
|
||||
|
||||
// Pass the resume position so the backend seeks at load time. Doing the
|
||||
// seek here (rather than a delayed playerSeek) avoids the race where the
|
||||
// media isn't loaded yet and the seek is lost, restarting from 0.
|
||||
await commands.playerPlayTracks(repositoryHandle, {
|
||||
trackIds: [itemId],
|
||||
startIndex: 0,
|
||||
shuffle: false,
|
||||
startPosition: positionSeconds,
|
||||
context: {
|
||||
type: "search",
|
||||
searchQuery: "",
|
||||
@@ -204,16 +208,6 @@ function createPlaybackModeStore() {
|
||||
|
||||
if (aborted) return;
|
||||
|
||||
// Wait briefly for media to load
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
|
||||
// Seek to position if not at the very start
|
||||
if (positionSeconds > 0.5) {
|
||||
await commands.playerSeek(positionSeconds);
|
||||
}
|
||||
|
||||
if (aborted) return;
|
||||
|
||||
// Let Rust handle stopping remote playback
|
||||
await commands.playbackModeTransferToLocal(itemId, positionTicks);
|
||||
|
||||
|
||||
@@ -7,8 +7,7 @@
|
||||
// TRACES: UR-005, UR-015 | DR-005, DR-020
|
||||
|
||||
import { writable, derived, get } from "svelte/store";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import { commands, events } from "$lib/api/bindings";
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
import { auth } from "$lib/stores/auth";
|
||||
|
||||
@@ -51,12 +50,12 @@ function createQueueStore() {
|
||||
// Initial sync from backend
|
||||
await syncFromRust();
|
||||
|
||||
// Listen for queue changed events
|
||||
unlisten = await listen<QueueChangedEvent>("player-event", (event) => {
|
||||
if ((event.payload as any).type === "queue_changed") {
|
||||
const queueEvent = event.payload as any;
|
||||
// Listen for queue changed events (generated tauri-specta event)
|
||||
unlisten = await events.playerStatusEvent.listen((event) => {
|
||||
if (event.payload.type === "queue_changed") {
|
||||
const queueEvent = event.payload;
|
||||
set({
|
||||
items: queueEvent.items,
|
||||
items: queueEvent.items as unknown as MediaItem[],
|
||||
currentIndex: queueEvent.current_index,
|
||||
shuffle: queueEvent.shuffle,
|
||||
repeat: queueEvent.repeat,
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
// TRACES: UR-010 | DR-037
|
||||
|
||||
import { writable, derived } from "svelte/store";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { commands } from "$lib/api/bindings";
|
||||
import { commands, events } from "$lib/api/bindings";
|
||||
import type { Session } from "$lib/api/types";
|
||||
|
||||
interface SessionsState {
|
||||
@@ -14,11 +13,6 @@ interface SessionsState {
|
||||
lastUpdated: Date | null;
|
||||
}
|
||||
|
||||
interface PlayerStatusEvent {
|
||||
type: string;
|
||||
sessions?: Session[];
|
||||
}
|
||||
|
||||
function createSessionsStore() {
|
||||
const initialState: SessionsState = {
|
||||
sessions: [],
|
||||
@@ -30,16 +24,17 @@ function createSessionsStore() {
|
||||
|
||||
const { subscribe, update } = writable<SessionsState>(initialState);
|
||||
|
||||
// Listen for session updates from Rust backend
|
||||
listen<PlayerStatusEvent>("player-event", (event) => {
|
||||
if (event.payload.type === "sessions_updated" && event.payload.sessions) {
|
||||
console.log(`[Sessions] Received ${event.payload.sessions.length} sessions from backend`);
|
||||
event.payload.sessions.forEach((s, i) => {
|
||||
// Listen for session updates from Rust backend (generated tauri-specta event)
|
||||
events.playerStatusEvent.listen((event) => {
|
||||
if (event.payload.type === "sessions_updated") {
|
||||
const sessions = event.payload.sessions as unknown as Session[];
|
||||
console.log(`[Sessions] Received ${sessions.length} sessions from backend`);
|
||||
sessions.forEach((s, i) => {
|
||||
console.log(`[Sessions] Session ${i}: id=${s.id}, device=${s.deviceName}, supportsRemoteControl=${s.supportsRemoteControl}`);
|
||||
});
|
||||
update((s) => ({
|
||||
...s,
|
||||
sessions: event.payload.sessions!,
|
||||
sessions,
|
||||
lastUpdated: new Date(),
|
||||
error: null,
|
||||
}));
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { selectDiverseGenres, sampleAcross } from "./genreDiversity";
|
||||
|
||||
const g = (...names: string[]) => names.map(name => ({ name }));
|
||||
|
||||
describe("sampleAcross", () => {
|
||||
it("returns input unchanged when at or under the count", () => {
|
||||
expect(sampleAcross([1, 2, 3], 5)).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it("spreads the sample across the whole list rather than taking a prefix", () => {
|
||||
// 26 letters, want ~7: a prefix would be A–G; striding spans A→Z.
|
||||
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
|
||||
const picked = sampleAcross(letters, 7);
|
||||
expect(picked[0]).toBe("A");
|
||||
// Reaches deep into the alphabet, not stuck near the front.
|
||||
expect(picked[picked.length - 1] >= "S").toBe(true);
|
||||
expect(picked.length).toBeLessThanOrEqual(7);
|
||||
});
|
||||
|
||||
it("never exceeds the requested count", () => {
|
||||
const items = Array.from({ length: 100 }, (_, i) => i);
|
||||
expect(sampleAcross(items, 8).length).toBeLessThanOrEqual(8);
|
||||
});
|
||||
});
|
||||
|
||||
describe("selectDiverseGenres", () => {
|
||||
it("returns input unchanged when at or under the limit", () => {
|
||||
const input = g("Rock", "Jazz");
|
||||
expect(selectDiverseGenres(input, 5)).toEqual(input);
|
||||
});
|
||||
|
||||
it("seeds with the most populous genre (first in input)", () => {
|
||||
const out = selectDiverseGenres(g("Rock", "Jazz", "Hip Hop"), 1);
|
||||
expect(out.map(x => x.name)).toEqual(["Rock"]);
|
||||
});
|
||||
|
||||
it("spreads the family instead of stacking near-synonyms", () => {
|
||||
// Count ranking puts all the Rock variants first; a naive top-N would
|
||||
// return four flavours of Rock. Diversity should pull in distinct genres.
|
||||
const input = g(
|
||||
"Rock",
|
||||
"Hard Rock",
|
||||
"Classic Rock",
|
||||
"Pop Rock",
|
||||
"Jazz",
|
||||
"Hip Hop",
|
||||
"Classical"
|
||||
);
|
||||
const names = selectDiverseGenres(input, 4).map(x => x.name);
|
||||
|
||||
expect(names[0]).toBe("Rock"); // seeded by count
|
||||
expect(names).toContain("Jazz");
|
||||
expect(names).toContain("Hip Hop");
|
||||
expect(names).toContain("Classical");
|
||||
// Only the seed represents the Rock cluster.
|
||||
expect(names.filter(n => n.includes("Rock"))).toEqual(["Rock"]);
|
||||
});
|
||||
|
||||
it("preserves count order as the tie-breaker among equally-distinct genres", () => {
|
||||
// All four are mutually distinct (no shared tokens), so every pick after
|
||||
// the seed is a distance tie and should follow input (count) order.
|
||||
const input = g("Rock", "Jazz", "Blues", "Folk");
|
||||
expect(selectDiverseGenres(input, 3).map(x => x.name)).toEqual([
|
||||
"Rock",
|
||||
"Jazz",
|
||||
"Blues",
|
||||
]);
|
||||
});
|
||||
|
||||
it("is case- and separator-insensitive when comparing", () => {
|
||||
const input = g("Hip Hop", "hip-hop", "Reggae");
|
||||
// "Hip Hop" and "hip-hop" share all tokens → the second is redundant.
|
||||
expect(selectDiverseGenres(input, 2).map(x => x.name)).toEqual([
|
||||
"Hip Hop",
|
||||
"Reggae",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
// Selecting a *diverse* set of genres for the music landing page.
|
||||
//
|
||||
// The naive approach ("keep the genres with the most albums") tends to surface
|
||||
// a cluster of near-synonyms — "Rock", "Hard Rock", "Classic Rock", "Pop Rock"
|
||||
// — because big umbrella genres and their sub-genres are all populous. The
|
||||
// result reads as one genre repeated, not a tour of the library.
|
||||
//
|
||||
// Instead we pick greedily for *spread*: start from the most populous genre,
|
||||
// then repeatedly add whichever remaining genre is least similar to everything
|
||||
// already chosen (a max-min / farthest-point selection). Similarity is word-
|
||||
// token overlap (Jaccard), so "Hard Rock" stays close to "Rock" but far from
|
||||
// "Jazz" or "Hip Hop". Count still acts as a gentle tie-breaker so we don't
|
||||
// promote a one-album novelty genre over a healthy distinct one.
|
||||
|
||||
/** Anything with a name and a relative weight (album count) we can rank by. */
|
||||
export interface DiversityCandidate {
|
||||
name: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sample up to `count` items at an even stride across `items`. Genre lists come
|
||||
* back alphabetical, so taking the first N would only ever surface A-genres;
|
||||
* striding spreads the sample A→Z. Always includes the first item.
|
||||
*/
|
||||
export function sampleAcross<T>(items: T[], count: number): T[] {
|
||||
if (items.length <= count) return items.slice();
|
||||
const stride = Math.max(1, Math.floor(items.length / count));
|
||||
return items.filter((_, i) => i % stride === 0).slice(0, count);
|
||||
}
|
||||
|
||||
/** Split a genre name into a set of lowercased word tokens. */
|
||||
function tokenize(name: string): Set<string> {
|
||||
return new Set(
|
||||
name
|
||||
.toLowerCase()
|
||||
.split(/[^a-z0-9]+/)
|
||||
.filter(Boolean)
|
||||
);
|
||||
}
|
||||
|
||||
/** Jaccard similarity of two token sets: |A∩B| / |A∪B|, in [0, 1]. */
|
||||
function jaccard(a: Set<string>, b: Set<string>): number {
|
||||
if (a.size === 0 && b.size === 0) return 1;
|
||||
let intersection = 0;
|
||||
for (const t of a) if (b.has(t)) intersection++;
|
||||
const union = a.size + b.size - intersection;
|
||||
return union === 0 ? 0 : intersection / union;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick up to `limit` genres that are textually distinct from one another,
|
||||
* preferring more populous genres. Input order is treated as the count ranking
|
||||
* (most albums first); ties in distance fall back to that order.
|
||||
*/
|
||||
export function selectDiverseGenres<T extends DiversityCandidate>(
|
||||
candidates: T[],
|
||||
limit: number
|
||||
): T[] {
|
||||
if (candidates.length <= limit) return candidates.slice();
|
||||
|
||||
const tokens = candidates.map(c => tokenize(c.name));
|
||||
const chosen: number[] = [];
|
||||
const remaining = new Set(candidates.map((_, i) => i));
|
||||
|
||||
// Seed with the most populous genre (candidates[0]).
|
||||
chosen.push(0);
|
||||
remaining.delete(0);
|
||||
|
||||
while (chosen.length < limit && remaining.size > 0) {
|
||||
let best = -1;
|
||||
// The best candidate is the one *least* similar to its most-similar chosen
|
||||
// member. We track that max-similarity and minimise it: a genre is only
|
||||
// "diverse" if it resembles *nothing* already chosen, so looking at the
|
||||
// single nearest neighbour (as plain farthest-point does) isn't enough —
|
||||
// "Hard Rock" must stay close to "Rock" even after unrelated "Jazz" is in.
|
||||
let bestMaxSim = Infinity;
|
||||
for (const i of remaining) {
|
||||
let maxSim = 0;
|
||||
for (const c of chosen) {
|
||||
const sim = jaccard(tokens[i], tokens[c]);
|
||||
if (sim > maxSim) maxSim = sim;
|
||||
}
|
||||
// Lower max-similarity wins; on a tie keep the earlier (more populous)
|
||||
// one, guaranteed because `remaining` iterates in insertion order.
|
||||
if (maxSim < bestMaxSim) {
|
||||
bestMaxSim = maxSim;
|
||||
best = i;
|
||||
}
|
||||
}
|
||||
chosen.push(best);
|
||||
remaining.delete(best);
|
||||
}
|
||||
|
||||
return chosen.map(i => candidates[i]);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { navigateBack } from "./navigation";
|
||||
|
||||
const goto = vi.fn();
|
||||
vi.mock("$app/navigation", () => ({
|
||||
goto: (...args: unknown[]) => goto(...args),
|
||||
}));
|
||||
|
||||
describe("navigateBack", () => {
|
||||
beforeEach(() => {
|
||||
goto.mockClear();
|
||||
});
|
||||
|
||||
it("pops real history when there is in-app history to go back to", () => {
|
||||
const back = vi.fn();
|
||||
vi.spyOn(history, "back").mockImplementation(back);
|
||||
vi.spyOn(history, "length", "get").mockReturnValue(3);
|
||||
|
||||
navigateBack("/library");
|
||||
|
||||
expect(back).toHaveBeenCalledOnce();
|
||||
expect(goto).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("falls back to the given path on a fresh deep-link (no history)", () => {
|
||||
const back = vi.fn();
|
||||
vi.spyOn(history, "back").mockImplementation(back);
|
||||
vi.spyOn(history, "length", "get").mockReturnValue(1);
|
||||
|
||||
navigateBack("/library/music");
|
||||
|
||||
expect(goto).toHaveBeenCalledWith("/library/music");
|
||||
expect(back).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { goto } from "$app/navigation";
|
||||
|
||||
/**
|
||||
* Navigate "back" using real browser/Android history when possible, falling
|
||||
* back to an explicit path otherwise.
|
||||
*
|
||||
* Hardcoded `goto(backPath)` always sends the user to a fixed screen, which
|
||||
* loses track of where they actually came from (e.g. reaching the genres list
|
||||
* from different entry points). Preferring `history.back()` keeps the back
|
||||
* affordance consistent with the platform back gesture and the browser/Android
|
||||
* hardware back button.
|
||||
*
|
||||
* We only use history when there is somewhere to go back to *within the app*.
|
||||
* On a fresh deep-link (history length 1, or an external referrer) we fall back
|
||||
* to `fallbackPath` so the user never gets stranded or bounced out of the app.
|
||||
*/
|
||||
export function navigateBack(fallbackPath: string): void {
|
||||
if (canGoBack()) {
|
||||
history.back();
|
||||
} else {
|
||||
goto(fallbackPath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True when there is in-app history to pop. `history.length > 1` means the user
|
||||
* navigated here from another page in this session rather than landing here
|
||||
* directly (deep link, refresh, or first load).
|
||||
*/
|
||||
function canGoBack(): boolean {
|
||||
if (typeof history === "undefined") return false;
|
||||
return history.length > 1;
|
||||
}
|
||||
Reference in New Issue
Block a user