Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7b8a8f66e5 | ||
|
|
2e479d05b3 | ||
|
|
1992a8187d | ||
|
|
532ffa661a | ||
|
|
2a1f1689b4 |
@@ -161,10 +161,10 @@ jobs:
|
|||||||
|
|
||||||
- name: Set app version from tag
|
- name: Set app version from tag
|
||||||
run: |
|
run: |
|
||||||
REF="${GITHUB_REF#refs/tags/v}"
|
# On a tag build, the tag is the single source of truth for the
|
||||||
VERSION="${REF#refs/heads/}"
|
# version name. On non-tag runs keep whatever is in tauri.conf.json.
|
||||||
# On non-tag runs keep whatever is in tauri.conf.json
|
|
||||||
if echo "$GITHUB_REF" | grep -q '^refs/tags/v'; then
|
if echo "$GITHUB_REF" | grep -q '^refs/tags/v'; then
|
||||||
|
VERSION="${GITHUB_REF#refs/tags/v}"
|
||||||
echo "Setting version to $VERSION"
|
echo "Setting version to $VERSION"
|
||||||
sed -i "s/\"version\": \"[^\"]*\"/\"version\": \"$VERSION\"/" src-tauri/tauri.conf.json
|
sed -i "s/\"version\": \"[^\"]*\"/\"version\": \"$VERSION\"/" src-tauri/tauri.conf.json
|
||||||
fi
|
fi
|
||||||
@@ -173,6 +173,35 @@ jobs:
|
|||||||
- name: Initialize Android project
|
- name: Initialize Android project
|
||||||
run: bun run tauri android init
|
run: bun run tauri android init
|
||||||
|
|
||||||
|
- name: Pin a monotonic Android versionCode
|
||||||
|
run: |
|
||||||
|
# `tauri android init` autogenerates src-tauri/gen/android/app/tauri.properties
|
||||||
|
# with a versionCode derived from the semver (e.g. 0.0.15 -> 15). That
|
||||||
|
# number is (a) tiny and (b) NOT monotonic across our history: earlier
|
||||||
|
# local/dev builds shipped versionCode 1000 (from a 0.1.0 config), so a
|
||||||
|
# plain 15 would be a *downgrade* and Android would refuse the update.
|
||||||
|
#
|
||||||
|
# Derive an explicit code that is both monotonic in semver order and
|
||||||
|
# always above the 1000 floor already in the field:
|
||||||
|
# code = 1000 + major*10000 + minor*100 + patch
|
||||||
|
# e.g. 0.0.14 -> 1014, 0.0.15 -> 1015, 0.1.0 -> 1100, 1.0.0 -> 11000.
|
||||||
|
# POSIX sh only (the runner uses dash): no here-strings, no \s in sed.
|
||||||
|
PROPS="src-tauri/gen/android/app/tauri.properties"
|
||||||
|
VERSION=$(grep '"version"' src-tauri/tauri.conf.json | head -1 | sed -E 's/.*"version"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/')
|
||||||
|
MAJ=$(echo "$VERSION" | cut -d. -f1)
|
||||||
|
MIN=$(echo "$VERSION" | cut -d. -f2)
|
||||||
|
PAT=$(echo "$VERSION" | cut -d. -f3)
|
||||||
|
# Guard against a malformed/missing component so we never emit code 0.
|
||||||
|
: "${MAJ:=0}" "${MIN:=0}" "${PAT:=0}"
|
||||||
|
CODE=$(( 1000 + MAJ*10000 + MIN*100 + PAT ))
|
||||||
|
echo "version=$VERSION -> versionCode=$CODE"
|
||||||
|
if grep -q '^tauri.android.versionCode=' "$PROPS"; then
|
||||||
|
sed -i "s/^tauri.android.versionCode=.*/tauri.android.versionCode=$CODE/" "$PROPS"
|
||||||
|
else
|
||||||
|
echo "tauri.android.versionCode=$CODE" >> "$PROPS"
|
||||||
|
fi
|
||||||
|
cat "$PROPS"
|
||||||
|
|
||||||
- name: Sync custom Android sources & gradle config
|
- name: Sync custom Android sources & gradle config
|
||||||
run: ./scripts/sync-android-sources.sh
|
run: ./scripts/sync-android-sources.sh
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "jellytau",
|
"name": "jellytau",
|
||||||
"version": "0.1.0",
|
"version": "0.0.15",
|
||||||
"description": "",
|
"description": "",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"packageManager": "bun@1.3.5",
|
"packageManager": "bun@1.3.5",
|
||||||
|
|||||||
@@ -159,6 +159,20 @@ pub async fn catalog_sync_status(
|
|||||||
Ok(CatalogSyncStatus { last_synced_at })
|
Ok(CatalogSyncStatus { last_synced_at })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Control whether offline library queries reveal the full synced catalog
|
||||||
|
/// (greyed-out, non-downloaded media) or only downloaded/local media.
|
||||||
|
///
|
||||||
|
/// The frontend calls this from the "Show all server media" toggle: pass `true`
|
||||||
|
/// when online, or when offline with the toggle on; pass `false` when offline
|
||||||
|
/// with the toggle off so library pages show downloaded media only. Fixes the
|
||||||
|
/// bug where offline library pages showed every server item regardless of the
|
||||||
|
/// toggle.
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub fn set_show_server_catalog(show: bool) {
|
||||||
|
crate::repository::offline::set_include_catalog_browse(show);
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(specta::Type, Debug, Clone, serde::Serialize, serde::Deserialize)]
|
#[derive(specta::Type, Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct ResumeQueuedResult {
|
pub struct ResumeQueuedResult {
|
||||||
|
|||||||
@@ -696,6 +696,11 @@ pub async fn player_stop(
|
|||||||
let controller = player.0.lock().await;
|
let controller = player.0.lock().await;
|
||||||
controller.stop().map_err(|e| e.to_string())?;
|
controller.stop().map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
// A genuine local stop returns the manager to Idle so it no longer
|
||||||
|
// reports Local (or a stale Remote) — otherwise a later play/pause would
|
||||||
|
// route to the wrong device.
|
||||||
|
playback_mode.0.set_mode(crate::playback_mode::PlaybackMode::Idle);
|
||||||
|
|
||||||
// Handle session state based on type (local playback only)
|
// Handle session state based on type (local playback only)
|
||||||
{
|
{
|
||||||
let mut session_mgr = session.0.lock().map_err(|e| e.to_string())?;
|
let mut session_mgr = session.0.lock().map_err(|e| e.to_string())?;
|
||||||
@@ -1538,6 +1543,9 @@ pub async fn player_play_album_track(
|
|||||||
play_selection_on_remote(&controller, session_id, &media_items, start_index).await?;
|
play_selection_on_remote(&controller, session_id, &media_items, start_index).await?;
|
||||||
controller.set_queue(media_items, start_index).map_err(|e| e.to_string())?;
|
controller.set_queue(media_items, start_index).map_err(|e| e.to_string())?;
|
||||||
} else {
|
} else {
|
||||||
|
// Local playback is now authoritative (see player_play_tracks); set it
|
||||||
|
// before starting so the mode-changed event precedes the state events.
|
||||||
|
playback_mode.0.set_mode(crate::playback_mode::PlaybackMode::Local);
|
||||||
controller
|
controller
|
||||||
.play_queue(media_items, start_index)
|
.play_queue(media_items, start_index)
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
@@ -1714,6 +1722,16 @@ pub async fn player_play_tracks(
|
|||||||
.set_queue(media_items, request.start_index)
|
.set_queue(media_items, request.start_index)
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
} else {
|
} else {
|
||||||
|
// Starting local playback makes Local the authoritative mode. Without
|
||||||
|
// this, a prior Remote mode lingers in the manager and later play/pause
|
||||||
|
// commands route back to the (stopped) remote session. Set it BEFORE
|
||||||
|
// starting playback so the PlaybackModeChanged event reaches the frontend
|
||||||
|
// ahead of the state_changed events it will emit — otherwise the frontend
|
||||||
|
// (still thinking it's remote) filters those state events out. Skip during
|
||||||
|
// a transfer: transfer_to_local drives the mode itself once complete.
|
||||||
|
if !playback_mode.0.is_transferring() {
|
||||||
|
playback_mode.0.set_mode(crate::playback_mode::PlaybackMode::Local);
|
||||||
|
}
|
||||||
controller
|
controller
|
||||||
.play_queue_from(media_items, request.start_index, request.start_position)
|
.play_queue_from(media_items, request.start_index, request.start_position)
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ use log::{error, info};
|
|||||||
use log::warn;
|
use log::warn;
|
||||||
|
|
||||||
use commands::{
|
use commands::{
|
||||||
sync_full_catalog, catalog_sync_status, resume_queued_downloads,
|
sync_full_catalog, catalog_sync_status, set_show_server_catalog, resume_queued_downloads,
|
||||||
cancel_download, clear_stale_downloads, delete_album_downloads, delete_all_downloads, delete_download,
|
cancel_download, clear_stale_downloads, delete_album_downloads, delete_all_downloads, delete_download,
|
||||||
download_album, download_item, download_item_and_start, download_video, download_series, download_season,
|
download_album, download_item, download_item_and_start, download_video, download_series, download_season,
|
||||||
get_download_storage_stats, get_downloads, get_download_manager_stats, set_max_concurrent_downloads,
|
get_download_storage_stats, get_downloads, get_download_manager_stats, set_max_concurrent_downloads,
|
||||||
@@ -588,6 +588,7 @@ fn specta_builder() -> Builder<tauri::Wry> {
|
|||||||
enqueue_video_downloads,
|
enqueue_video_downloads,
|
||||||
sync_full_catalog,
|
sync_full_catalog,
|
||||||
catalog_sync_status,
|
catalog_sync_status,
|
||||||
|
set_show_server_catalog,
|
||||||
resume_queued_downloads,
|
resume_queued_downloads,
|
||||||
get_download_manager_stats,
|
get_download_manager_stats,
|
||||||
set_max_concurrent_downloads,
|
set_max_concurrent_downloads,
|
||||||
@@ -924,6 +925,9 @@ pub fn run() {
|
|||||||
player_arc.clone(),
|
player_arc.clone(),
|
||||||
);
|
);
|
||||||
let playback_mode_arc = Arc::new(playback_mode_manager);
|
let playback_mode_arc = Arc::new(playback_mode_manager);
|
||||||
|
// Broadcast mode changes so the frontend's mirror store reconciles to
|
||||||
|
// this authoritative one (prevents remote/local control desync).
|
||||||
|
playback_mode_arc.set_event_emitter(event_emitter.clone());
|
||||||
let playback_mode_wrapper = PlaybackModeManagerWrapper(playback_mode_arc.clone());
|
let playback_mode_wrapper = PlaybackModeManagerWrapper(playback_mode_arc.clone());
|
||||||
app.manage(playback_mode_wrapper);
|
app.manage(playback_mode_wrapper);
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ use tokio::sync::Mutex as TokioMutex;
|
|||||||
use tokio::time::{sleep, Duration};
|
use tokio::time::{sleep, Duration};
|
||||||
|
|
||||||
use crate::jellyfin::JellyfinClient;
|
use crate::jellyfin::JellyfinClient;
|
||||||
use crate::player::{PlayerController, QueueContext};
|
use crate::player::{PlayerController, PlayerEventEmitter, PlayerStatusEvent, QueueContext};
|
||||||
|
|
||||||
/// Playback mode - local device, remote session, or idle
|
/// Playback mode - local device, remote session, or idle
|
||||||
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
@@ -48,6 +48,9 @@ pub struct PlaybackModeManager {
|
|||||||
player_controller: Arc<TokioMutex<PlayerController>>,
|
player_controller: Arc<TokioMutex<PlayerController>>,
|
||||||
current_mode: Arc<RwLock<PlaybackMode>>,
|
current_mode: Arc<RwLock<PlaybackMode>>,
|
||||||
is_transferring: Arc<AtomicBool>,
|
is_transferring: Arc<AtomicBool>,
|
||||||
|
/// Optional emitter used to notify the frontend when the mode changes, so its
|
||||||
|
/// mirror store stays in sync with this authoritative one. `None` in tests.
|
||||||
|
event_emitter: Arc<Mutex<Option<Arc<dyn PlayerEventEmitter>>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PlaybackModeManager {
|
impl PlaybackModeManager {
|
||||||
@@ -61,19 +64,73 @@ impl PlaybackModeManager {
|
|||||||
player_controller,
|
player_controller,
|
||||||
current_mode: Arc::new(RwLock::new(PlaybackMode::Idle)),
|
current_mode: Arc::new(RwLock::new(PlaybackMode::Idle)),
|
||||||
is_transferring: Arc::new(AtomicBool::new(false)),
|
is_transferring: Arc::new(AtomicBool::new(false)),
|
||||||
|
event_emitter: Arc::new(Mutex::new(None)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Wire the event emitter so `set_mode` notifies the frontend. Called once
|
||||||
|
/// during setup; safe to leave unset (tests do), in which case mode changes
|
||||||
|
/// simply aren't broadcast.
|
||||||
|
pub fn set_event_emitter(&self, emitter: Arc<dyn PlayerEventEmitter>) {
|
||||||
|
*self.event_emitter.lock_safe() = Some(emitter);
|
||||||
|
}
|
||||||
|
|
||||||
/// Get current playback mode
|
/// Get current playback mode
|
||||||
pub fn get_mode(&self) -> PlaybackMode {
|
pub fn get_mode(&self) -> PlaybackMode {
|
||||||
self.current_mode.read_safe().clone()
|
self.current_mode.read_safe().clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set playback mode (internal use)
|
/// Set playback mode (internal use).
|
||||||
|
///
|
||||||
|
/// Broadcasts a `PlaybackModeChanged` event when the mode actually changes so
|
||||||
|
/// the frontend's mirror store reconciles to this authoritative value. The
|
||||||
|
/// write lock is released before emitting to avoid holding it across the
|
||||||
|
/// emitter call.
|
||||||
pub fn set_mode(&self, mode: PlaybackMode) {
|
pub fn set_mode(&self, mode: PlaybackMode) {
|
||||||
log::info!("[PlaybackMode] Setting mode to: {:?}", mode);
|
log::info!("[PlaybackMode] Setting mode to: {:?}", mode);
|
||||||
let mut current = self.current_mode.write_safe();
|
let changed = {
|
||||||
*current = mode;
|
let mut current = self.current_mode.write_safe();
|
||||||
|
let changed = *current != mode;
|
||||||
|
*current = mode.clone();
|
||||||
|
changed
|
||||||
|
};
|
||||||
|
|
||||||
|
if !changed {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let (mode_str, session_id) = match &mode {
|
||||||
|
PlaybackMode::Local => ("local".to_string(), None),
|
||||||
|
PlaybackMode::Idle => ("idle".to_string(), None),
|
||||||
|
PlaybackMode::Remote { session_id } => ("remote".to_string(), Some(session_id.clone())),
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(emitter) = self.event_emitter.lock_safe().as_ref() {
|
||||||
|
emitter.emit(PlayerStatusEvent::PlaybackModeChanged {
|
||||||
|
mode: mode_str,
|
||||||
|
session_id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start the Android playback service and hand it remote-volume control.
|
||||||
|
///
|
||||||
|
/// Must run on EVERY transition into remote mode, because it is what starts
|
||||||
|
/// the foreground service. Without a running service there is no media
|
||||||
|
/// notification (the lockscreen card is missing) AND system volume buttons
|
||||||
|
/// aren't intercepted for the remote session (remote volume control dead).
|
||||||
|
/// Both symptoms share this one cause, so this must not be skipped on any
|
||||||
|
/// remote-entry path (notably the empty-queue early return in
|
||||||
|
/// `transfer_to_remote_inner`). No-op / non-Android builds do nothing.
|
||||||
|
#[allow(unused_variables)]
|
||||||
|
fn enable_remote_control(&self) {
|
||||||
|
#[cfg(target_os = "android")]
|
||||||
|
{
|
||||||
|
if let Err(e) = crate::player::enable_remote_volume(50) {
|
||||||
|
log::warn!("[PlaybackMode] Failed to enable remote volume/service: {}", e);
|
||||||
|
// Non-fatal - continue; the next poll tick will retry metadata.
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check if currently transferring
|
/// Check if currently transferring
|
||||||
@@ -297,6 +354,10 @@ impl PlaybackModeManager {
|
|||||||
self.set_mode(PlaybackMode::Remote {
|
self.set_mode(PlaybackMode::Remote {
|
||||||
session_id: session_id.to_string(),
|
session_id: session_id.to_string(),
|
||||||
});
|
});
|
||||||
|
// Start the service + remote-volume control here too — otherwise this
|
||||||
|
// early return leaves remote mode with no media notification and no
|
||||||
|
// volume interception (lockscreen card missing + remote volume dead).
|
||||||
|
self.enable_remote_control();
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -552,14 +613,9 @@ impl PlaybackModeManager {
|
|||||||
session_id: session_id.to_string(),
|
session_id: session_id.to_string(),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Enable remote volume control on Android (intercepts volume buttons)
|
// Start the service + remote-volume control (intercepts volume buttons,
|
||||||
#[cfg(target_os = "android")]
|
// and starts the foreground service that renders the lockscreen card).
|
||||||
{
|
self.enable_remote_control();
|
||||||
if let Err(e) = crate::player::enable_remote_volume(50) {
|
|
||||||
log::warn!("[PlaybackMode] Failed to enable remote volume: {}", e);
|
|
||||||
// Non-fatal - continue with transfer
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
log::info!("[PlaybackMode] Successfully transferred to remote");
|
log::info!("[PlaybackMode] Successfully transferred to remote");
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -702,6 +758,84 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Capturing emitter so we can assert what `set_mode` broadcasts.
|
||||||
|
struct CapturingEmitter {
|
||||||
|
events: Mutex<Vec<PlayerStatusEvent>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PlayerEventEmitter for CapturingEmitter {
|
||||||
|
fn emit(&self, event: PlayerStatusEvent) {
|
||||||
|
self.events.lock().unwrap().push(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn manager_with_emitter() -> (PlaybackModeManager, Arc<CapturingEmitter>) {
|
||||||
|
let emitter = Arc::new(CapturingEmitter {
|
||||||
|
events: Mutex::new(Vec::new()),
|
||||||
|
});
|
||||||
|
let manager = PlaybackModeManager::new(
|
||||||
|
Arc::new(Mutex::new(None)),
|
||||||
|
Arc::new(TokioMutex::new(crate::player::PlayerController::default())),
|
||||||
|
);
|
||||||
|
manager.set_event_emitter(emitter.clone());
|
||||||
|
(manager, emitter)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// set_mode broadcasts a PlaybackModeChanged event with the right payload so
|
||||||
|
/// the frontend can reconcile its mirror store to this authoritative one.
|
||||||
|
#[test]
|
||||||
|
fn test_set_mode_emits_change_event() {
|
||||||
|
let (manager, emitter) = manager_with_emitter();
|
||||||
|
|
||||||
|
manager.set_mode(PlaybackMode::Remote {
|
||||||
|
session_id: "sess-1".to_string(),
|
||||||
|
});
|
||||||
|
manager.set_mode(PlaybackMode::Local);
|
||||||
|
manager.set_mode(PlaybackMode::Idle);
|
||||||
|
|
||||||
|
let events = emitter.events.lock().unwrap();
|
||||||
|
assert_eq!(events.len(), 3, "one event per real mode change");
|
||||||
|
|
||||||
|
match &events[0] {
|
||||||
|
PlayerStatusEvent::PlaybackModeChanged { mode, session_id } => {
|
||||||
|
assert_eq!(mode, "remote");
|
||||||
|
assert_eq!(session_id.as_deref(), Some("sess-1"));
|
||||||
|
}
|
||||||
|
other => panic!("expected PlaybackModeChanged, got {:?}", other),
|
||||||
|
}
|
||||||
|
match &events[1] {
|
||||||
|
PlayerStatusEvent::PlaybackModeChanged { mode, session_id } => {
|
||||||
|
assert_eq!(mode, "local");
|
||||||
|
assert_eq!(session_id.as_deref(), None);
|
||||||
|
}
|
||||||
|
other => panic!("expected PlaybackModeChanged, got {:?}", other),
|
||||||
|
}
|
||||||
|
match &events[2] {
|
||||||
|
PlayerStatusEvent::PlaybackModeChanged { mode, session_id } => {
|
||||||
|
assert_eq!(mode, "idle");
|
||||||
|
assert_eq!(session_id.as_deref(), None);
|
||||||
|
}
|
||||||
|
other => panic!("expected PlaybackModeChanged, got {:?}", other),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Setting the same mode twice must not re-emit — the frontend reconciler
|
||||||
|
/// (and the event channel) shouldn't be spammed on no-op transitions.
|
||||||
|
#[test]
|
||||||
|
fn test_set_mode_deduplicates_no_op() {
|
||||||
|
let (manager, emitter) = manager_with_emitter();
|
||||||
|
|
||||||
|
manager.set_mode(PlaybackMode::Local);
|
||||||
|
manager.set_mode(PlaybackMode::Local);
|
||||||
|
manager.set_mode(PlaybackMode::Local);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
emitter.events.lock().unwrap().len(),
|
||||||
|
1,
|
||||||
|
"repeated identical mode set emits only once"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/// The resume position handed to a remote session is derived from a live
|
/// The resume position handed to a remote session is derived from a live
|
||||||
/// playback position. Guards the seconds->ticks conversion and the
|
/// playback position. Guards the seconds->ticks conversion and the
|
||||||
/// at-the-start threshold (Bug: casting restarted the track from 0).
|
/// at-the-start threshold (Bug: casting restarted the track from 0).
|
||||||
|
|||||||
@@ -124,6 +124,21 @@ pub enum PlayerStatusEvent {
|
|||||||
/// All active controllable sessions from Jellyfin
|
/// All active controllable sessions from Jellyfin
|
||||||
sessions: Vec<crate::jellyfin::client::SessionInfo>,
|
sessions: Vec<crate::jellyfin::client::SessionInfo>,
|
||||||
},
|
},
|
||||||
|
/// The authoritative playback mode changed in the Rust backend.
|
||||||
|
///
|
||||||
|
/// The Rust `PlaybackModeManager` is the single source of truth for which
|
||||||
|
/// device playback commands route to (local vs a remote session). The
|
||||||
|
/// frontend keeps a mirror store for the UI; without this event that mirror
|
||||||
|
/// drifts out of sync (e.g. a mode transition happens inside a transfer or a
|
||||||
|
/// local stop that the frontend never learns about), and controls then route
|
||||||
|
/// to the wrong device — the classic "it keeps playing on the remote" bug.
|
||||||
|
/// The frontend reconciles its store to this payload whenever it fires.
|
||||||
|
PlaybackModeChanged {
|
||||||
|
/// New mode: "local", "remote", or "idle".
|
||||||
|
mode: String,
|
||||||
|
/// Session id when `mode == "remote"`, otherwise `None`.
|
||||||
|
session_id: Option<String>,
|
||||||
|
},
|
||||||
/// The user asked to disconnect from the remote session and resume locally.
|
/// The user asked to disconnect from the remote session and resume locally.
|
||||||
///
|
///
|
||||||
/// Emitted when the lockscreen Stop button is pressed while casting. The
|
/// Emitted when the lockscreen Stop button is pressed while casting. The
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
// Offline repository - queries SQLite database for cached data
|
// Offline repository - queries SQLite database for cached data
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use log::debug;
|
use log::debug;
|
||||||
@@ -7,6 +8,30 @@ use log::debug;
|
|||||||
use super::{MediaRepository, types::*};
|
use super::{MediaRepository, types::*};
|
||||||
use crate::storage::db_service::{DatabaseService, Query, QueryParam, RusqliteService};
|
use crate::storage::db_service::{DatabaseService, Query, QueryParam, RusqliteService};
|
||||||
|
|
||||||
|
/// Whether offline library queries may include catalog items that are merely
|
||||||
|
/// *browsed/synced* but not downloaded (the greyed-out "browse the whole server"
|
||||||
|
/// view). Defaults to `true` so online browsing (which reads this same cache as
|
||||||
|
/// a fast path) still sees the full catalog.
|
||||||
|
///
|
||||||
|
/// While offline, the frontend drives this from the "Show all server media"
|
||||||
|
/// toggle: OFF means library pages show only downloaded/local media, ON reveals
|
||||||
|
/// the full greyed-out catalog. See `set_include_catalog_browse` and the
|
||||||
|
/// `showServerCatalog` UI flag. Fixes the bug where offline library pages showed
|
||||||
|
/// every server item regardless of the toggle.
|
||||||
|
static INCLUDE_CATALOG_BROWSE: AtomicBool = AtomicBool::new(true);
|
||||||
|
|
||||||
|
/// Set whether offline `get_items` includes non-downloaded (synced-only) catalog
|
||||||
|
/// items. Called from the frontend: `true` when online or when the offline
|
||||||
|
/// "Show all server media" toggle is on; `false` when offline with the toggle
|
||||||
|
/// off (show downloaded/local media only).
|
||||||
|
pub fn set_include_catalog_browse(include: bool) {
|
||||||
|
INCLUDE_CATALOG_BROWSE.store(include, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn include_catalog_browse() -> bool {
|
||||||
|
INCLUDE_CATALOG_BROWSE.load(Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
pub struct OfflineRepository {
|
pub struct OfflineRepository {
|
||||||
db_service: Arc<RusqliteService>,
|
db_service: Arc<RusqliteService>,
|
||||||
server_id: String,
|
server_id: String,
|
||||||
@@ -558,7 +583,20 @@ impl MediaRepository for OfflineRepository {
|
|||||||
// Use CTE to find items that are either:
|
// Use CTE to find items that are either:
|
||||||
// 1. Playable items (Audio, Movie, Episode) with completed downloads (offline mode)
|
// 1. Playable items (Audio, Movie, Episode) with completed downloads (offline mode)
|
||||||
// 2. Container items (MusicAlbum, Series, Season) with at least one downloaded child (offline mode)
|
// 2. Container items (MusicAlbum, Series, Season) with at least one downloaded child (offline mode)
|
||||||
// 3. Cached items with recent synced_at timestamp (online mode - for fast browsing)
|
// 3. Cached items with recent synced_at timestamp (fast online browsing, or the
|
||||||
|
// offline "Show all server media" catalog view) — only when the catalog-browse
|
||||||
|
// flag is set. When offline with the toggle off, this branch is omitted so the
|
||||||
|
// page shows downloaded/local media only. See `set_include_catalog_browse`.
|
||||||
|
let catalog_branch = if include_catalog_browse() {
|
||||||
|
"UNION
|
||||||
|
|
||||||
|
-- Cached items for fast browsing (online) or the offline catalog view
|
||||||
|
SELECT DISTINCT i.id
|
||||||
|
FROM items i
|
||||||
|
WHERE i.synced_at IS NOT NULL"
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
};
|
||||||
let sql = format!(
|
let sql = format!(
|
||||||
"WITH available_items AS (
|
"WITH available_items AS (
|
||||||
-- Playable items with completed downloads
|
-- Playable items with completed downloads
|
||||||
@@ -578,12 +616,7 @@ impl MediaRepository for OfflineRepository {
|
|||||||
WHERE d.status = 'completed'
|
WHERE d.status = 'completed'
|
||||||
AND i.item_type IN ('MusicAlbum', 'Series', 'Season', 'BoxSet', 'Folder', 'CollectionFolder')
|
AND i.item_type IN ('MusicAlbum', 'Series', 'Season', 'BoxSet', 'Folder', 'CollectionFolder')
|
||||||
|
|
||||||
UNION
|
{catalog_branch}
|
||||||
|
|
||||||
-- Cached items for fast browsing (when online)
|
|
||||||
SELECT DISTINCT i.id
|
|
||||||
FROM items i
|
|
||||||
WHERE i.synced_at IS NOT NULL
|
|
||||||
)
|
)
|
||||||
SELECT i.id, i.name, i.item_type, i.server_id, i.parent_id, i.library_id, i.overview, i.genres,
|
SELECT i.id, i.name, i.item_type, i.server_id, i.parent_id, i.library_id, i.overview, i.genres,
|
||||||
i.runtime_ticks, i.production_year, i.community_rating, i.official_rating,
|
i.runtime_ticks, i.production_year, i.community_rating, i.official_rating,
|
||||||
@@ -1874,6 +1907,57 @@ mod tests {
|
|||||||
assert_eq!(tracks.items[0].id, "track-1");
|
assert_eq!(tracks.items[0].id, "track-1");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Regression: offline library pages must honor the "Show all server media"
|
||||||
|
/// toggle. With `include_catalog_browse` off, `get_items` returns only
|
||||||
|
/// downloaded media — not the whole synced catalog. With it on, the full
|
||||||
|
/// (synced-but-not-downloaded) catalog is revealed. Fixes the bug where
|
||||||
|
/// offline library pages showed every server item regardless of the toggle.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_get_items_toggle_gates_synced_catalog() {
|
||||||
|
use crate::storage::db_service::DatabaseService;
|
||||||
|
let db_service = create_test_db();
|
||||||
|
|
||||||
|
for sql in [
|
||||||
|
// Two movies in a library, both merely synced (browsed) — no download.
|
||||||
|
"INSERT INTO items (id, server_id, name, item_type, library_id, synced_at) \
|
||||||
|
VALUES ('movie-dl', 'test-server', 'Downloaded', 'Movie', 'lib-1', '2026-01-01')",
|
||||||
|
"INSERT INTO items (id, server_id, name, item_type, library_id, synced_at) \
|
||||||
|
VALUES ('movie-cat', 'test-server', 'CatalogOnly', 'Movie', 'lib-1', '2026-01-01')",
|
||||||
|
// Only the first movie is actually downloaded.
|
||||||
|
"INSERT INTO downloads (item_id, status) VALUES ('movie-dl', 'completed')",
|
||||||
|
// A library row so the library-parent EXISTS clause matches.
|
||||||
|
"INSERT INTO libraries (id, server_id, name) VALUES ('lib-1', 'test-server', 'Movies')",
|
||||||
|
] {
|
||||||
|
db_service.execute(Query::new(sql)).await.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
let repo = OfflineRepository::new(
|
||||||
|
db_service.clone(),
|
||||||
|
"test-server".to_string(),
|
||||||
|
"test-user".to_string(),
|
||||||
|
);
|
||||||
|
let opts = Some(GetItemsOptions {
|
||||||
|
include_item_types: Some(vec!["Movie".to_string()]),
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
|
||||||
|
// Toggle OFF: only the downloaded movie is returned.
|
||||||
|
set_include_catalog_browse(false);
|
||||||
|
let local_only = repo.get_items("lib-1", opts.clone()).await.unwrap();
|
||||||
|
let ids: Vec<&str> = local_only.items.iter().map(|i| i.id.as_str()).collect();
|
||||||
|
assert_eq!(ids, vec!["movie-dl"], "toggle off should show downloaded media only");
|
||||||
|
|
||||||
|
// Toggle ON: both the downloaded and the catalog-only movie are returned.
|
||||||
|
set_include_catalog_browse(true);
|
||||||
|
let full_catalog = repo.get_items("lib-1", opts).await.unwrap();
|
||||||
|
let mut ids: Vec<&str> = full_catalog.items.iter().map(|i| i.id.as_str()).collect();
|
||||||
|
ids.sort();
|
||||||
|
assert_eq!(ids, vec!["movie-cat", "movie-dl"], "toggle on should reveal the full catalog");
|
||||||
|
|
||||||
|
// Restore default for other tests sharing this process-global flag.
|
||||||
|
set_include_catalog_browse(true);
|
||||||
|
}
|
||||||
|
|
||||||
/// Regression: TV episodes link to their season/series via `season_id` /
|
/// Regression: TV episodes link to their season/series via `season_id` /
|
||||||
/// `series_id` (NOT `parent_id`, which is NULL in the cache). A downloaded
|
/// `series_id` (NOT `parent_id`, which is NULL in the cache). A downloaded
|
||||||
/// episode must make both its Season and Series available offline, and
|
/// episode must make both its Season and Series available offline, and
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "jellytau",
|
"productName": "jellytau",
|
||||||
"version": "0.1.0",
|
"version": "0.0.15",
|
||||||
"identifier": "com.dtourolle.jellytau",
|
"identifier": "com.dtourolle.jellytau",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "bun run dev",
|
"beforeDevCommand": "bun run dev",
|
||||||
|
|||||||
@@ -825,6 +825,19 @@ async syncFullCatalog(handle: string) : Promise<CatalogSyncResult> {
|
|||||||
async catalogSyncStatus() : Promise<CatalogSyncStatus> {
|
async catalogSyncStatus() : Promise<CatalogSyncStatus> {
|
||||||
return await TAURI_INVOKE("catalog_sync_status");
|
return await TAURI_INVOKE("catalog_sync_status");
|
||||||
},
|
},
|
||||||
|
/**
|
||||||
|
* Control whether offline library queries reveal the full synced catalog
|
||||||
|
* (greyed-out, non-downloaded media) or only downloaded/local media.
|
||||||
|
*
|
||||||
|
* The frontend calls this from the "Show all server media" toggle: pass `true`
|
||||||
|
* when online, or when offline with the toggle on; pass `false` when offline
|
||||||
|
* with the toggle off so library pages show downloaded media only. Fixes the
|
||||||
|
* bug where offline library pages showed every server item regardless of the
|
||||||
|
* toggle.
|
||||||
|
*/
|
||||||
|
async setShowServerCatalog(show: boolean) : Promise<void> {
|
||||||
|
await TAURI_INVOKE("set_show_server_catalog", { show });
|
||||||
|
},
|
||||||
/**
|
/**
|
||||||
* Resolve the stream URL for every download row that was queued while offline
|
* Resolve the stream URL for every download row that was queued while offline
|
||||||
* (`status = 'pending' AND stream_url IS NULL`), then pump the queue so they
|
* (`status = 'pending' AND stream_url IS NULL`), then pump the queue so they
|
||||||
@@ -2035,6 +2048,18 @@ export type PlayerStatusEvent =
|
|||||||
* Remote sessions updated (for cast/remote control UI)
|
* Remote sessions updated (for cast/remote control UI)
|
||||||
*/
|
*/
|
||||||
{ type: "sessions_updated"; sessions: SessionInfo[] } |
|
{ type: "sessions_updated"; sessions: SessionInfo[] } |
|
||||||
|
/**
|
||||||
|
* The authoritative playback mode changed in the Rust backend.
|
||||||
|
*
|
||||||
|
* The Rust `PlaybackModeManager` is the single source of truth for which
|
||||||
|
* device playback commands route to (local vs a remote session). The
|
||||||
|
* frontend keeps a mirror store for the UI; without this event that mirror
|
||||||
|
* drifts out of sync (e.g. a mode transition happens inside a transfer or a
|
||||||
|
* local stop that the frontend never learns about), and controls then route
|
||||||
|
* to the wrong device — the classic "it keeps playing on the remote" bug.
|
||||||
|
* The frontend reconciles its store to this payload whenever it fires.
|
||||||
|
*/
|
||||||
|
{ type: "playback_mode_changed"; mode: string; session_id: string | null } |
|
||||||
/**
|
/**
|
||||||
* The user asked to disconnect from the remote session and resume locally.
|
* The user asked to disconnect from the remote session and resume locally.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
<!--
|
||||||
|
BottomUi — the app's bottom UI (mini player stacked over the bottom nav).
|
||||||
|
|
||||||
|
Rendered as an IN-FLOW flex child at the bottom of a full-height flex column,
|
||||||
|
NOT a fixed overlay. This is the whole point: because it is a normal flex
|
||||||
|
sibling below the scroll container (which is `flex-1 min-h-0 overflow-y-auto`),
|
||||||
|
the scroller is physically bounded above it and can never render behind it.
|
||||||
|
|
||||||
|
This replaces the old ResizeObserver + `bottomUiHeight` + padding-reservation
|
||||||
|
scheme, which started at 0, updated async, and repeatedly regressed into the
|
||||||
|
"last row hidden behind the nav" bug. There is nothing to measure or reserve:
|
||||||
|
the browser's flex layout does it exactly, every frame.
|
||||||
|
|
||||||
|
The Android system gesture bar is cleared via `env(safe-area-inset-bottom)`.
|
||||||
|
|
||||||
|
TRACES: UR-005 | DR-009
|
||||||
|
-->
|
||||||
|
<script lang="ts">
|
||||||
|
import { goto } from "$app/navigation";
|
||||||
|
import { currentMedia, isPlaying, playbackPosition, playbackDuration } from "$lib/stores/player";
|
||||||
|
import { isShuffle, repeatMode, hasNext, hasPrevious } from "$lib/stores/queue";
|
||||||
|
import { showSleepTimerModal } from "$lib/stores/appState";
|
||||||
|
import MiniPlayer from "$lib/components/player/MiniPlayer.svelte";
|
||||||
|
import BottomNav from "$lib/components/BottomNav.svelte";
|
||||||
|
|
||||||
|
let {
|
||||||
|
showMiniPlayer = true,
|
||||||
|
showNav = true,
|
||||||
|
onExpand,
|
||||||
|
}: {
|
||||||
|
showMiniPlayer?: boolean;
|
||||||
|
showNav?: boolean;
|
||||||
|
// Where "expand mini player" goes. Defaults to the full player route.
|
||||||
|
onExpand?: () => void;
|
||||||
|
} = $props();
|
||||||
|
|
||||||
|
function expand() {
|
||||||
|
if (onExpand) return onExpand();
|
||||||
|
if ($currentMedia) goto(`/player/${$currentMedia.id}`);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<!-- flex-shrink-0 so it keeps its natural height; the scroller sibling flexes. -->
|
||||||
|
<div class="flex-shrink-0 pb-[env(safe-area-inset-bottom)] bg-[var(--color-surface)]">
|
||||||
|
{#if showMiniPlayer}
|
||||||
|
<MiniPlayer
|
||||||
|
media={$currentMedia}
|
||||||
|
isPlaying={$isPlaying}
|
||||||
|
position={$playbackPosition}
|
||||||
|
duration={$playbackDuration}
|
||||||
|
shuffle={$isShuffle}
|
||||||
|
repeat={$repeatMode}
|
||||||
|
hasNext={$hasNext}
|
||||||
|
hasPrevious={$hasPrevious}
|
||||||
|
className="flex-shrink-0"
|
||||||
|
onExpand={expand}
|
||||||
|
onSleepTimerClick={() => showSleepTimerModal.set(true)}
|
||||||
|
/>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if showNav}
|
||||||
|
<BottomNav className="flex-shrink-0" />
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
@@ -1,432 +0,0 @@
|
|||||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
|
||||||
import { render, waitFor } from "@testing-library/svelte";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Integration tests for async image loading pattern used in components
|
|
||||||
*
|
|
||||||
* Pattern:
|
|
||||||
* - Component has $state<string> imageUrl = ""
|
|
||||||
* - Component has async loadImageUrl() function
|
|
||||||
* - Component uses $effect to call loadImageUrl when dependencies change
|
|
||||||
* - For lists: uses Map<string, string> to cache URLs per item
|
|
||||||
*/
|
|
||||||
|
|
||||||
// Mock repository with getImageUrl
|
|
||||||
const createMockRepository = () => ({
|
|
||||||
getImageUrl: vi.fn(),
|
|
||||||
});
|
|
||||||
|
|
||||||
describe.skip("Async Image Loading Pattern", () => {
|
|
||||||
// Detailed async pattern tests - core functionality verified in repository-client.test.ts
|
|
||||||
let mockRepository: any;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
mockRepository = createMockRepository();
|
|
||||||
vi.clearAllMocks();
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
vi.clearAllTimers();
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("Single Image Loading", () => {
|
|
||||||
it("should load image URL asynchronously on component mount", async () => {
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
|
|
||||||
|
|
||||||
// Simulating component with async image loading
|
|
||||||
const imageUrl = await mockRepository.getImageUrl("item123", "Primary");
|
|
||||||
|
|
||||||
expect(imageUrl).toBe("https://server.com/image.jpg");
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalledWith("item123", "Primary");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should show placeholder while loading", async () => {
|
|
||||||
mockRepository.getImageUrl.mockImplementation(
|
|
||||||
() => new Promise((resolve) => setTimeout(() => resolve("https://server.com/image.jpg"), 100))
|
|
||||||
);
|
|
||||||
|
|
||||||
vi.useFakeTimers();
|
|
||||||
const promise = mockRepository.getImageUrl("item123", "Primary");
|
|
||||||
|
|
||||||
// Initially no URL
|
|
||||||
expect(promise).toBeInstanceOf(Promise);
|
|
||||||
|
|
||||||
vi.advanceTimersByTime(100);
|
|
||||||
vi.useRealTimers();
|
|
||||||
|
|
||||||
const result = await promise;
|
|
||||||
expect(result).toBe("https://server.com/image.jpg");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should reload image when item changes", async () => {
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image1.jpg");
|
|
||||||
|
|
||||||
const url1 = await mockRepository.getImageUrl("item1", "Primary");
|
|
||||||
expect(url1).toBe("https://server.com/image1.jpg");
|
|
||||||
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image2.jpg");
|
|
||||||
|
|
||||||
const url2 = await mockRepository.getImageUrl("item2", "Primary");
|
|
||||||
expect(url2).toBe("https://server.com/image2.jpg");
|
|
||||||
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should not reload image if item ID hasn't changed", async () => {
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
|
|
||||||
|
|
||||||
// First load
|
|
||||||
await mockRepository.getImageUrl("item123", "Primary");
|
|
||||||
|
|
||||||
// Would normally use $effect to track changes
|
|
||||||
// If item ID is same, should not reload (handled by component caching)
|
|
||||||
// This test documents the expected behavior
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should handle load errors gracefully", async () => {
|
|
||||||
mockRepository.getImageUrl.mockRejectedValue(new Error("Network error"));
|
|
||||||
|
|
||||||
// Component should catch error and show placeholder
|
|
||||||
try {
|
|
||||||
await mockRepository.getImageUrl("item123", "Primary");
|
|
||||||
} catch (e) {
|
|
||||||
expect(e).toBeInstanceOf(Error);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("List Image Caching (Map-based)", () => {
|
|
||||||
it("should cache URLs using Map<string, string>", () => {
|
|
||||||
// Simulating component state: imageUrls = $state<Map<string, string>>(new Map())
|
|
||||||
const imageUrls = new Map<string, string>();
|
|
||||||
|
|
||||||
// Load first item
|
|
||||||
imageUrls.set("item1", "https://server.com/image1.jpg");
|
|
||||||
expect(imageUrls.has("item1")).toBe(true);
|
|
||||||
expect(imageUrls.get("item1")).toBe("https://server.com/image1.jpg");
|
|
||||||
|
|
||||||
// Load second item
|
|
||||||
imageUrls.set("item2", "https://server.com/image2.jpg");
|
|
||||||
expect(imageUrls.size).toBe(2);
|
|
||||||
|
|
||||||
// Check cache hit
|
|
||||||
expect(imageUrls.get("item1")).toBe("https://server.com/image1.jpg");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should load images only once per item", async () => {
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
|
|
||||||
|
|
||||||
const imageUrls = new Map<string, string>();
|
|
||||||
|
|
||||||
// Simulate loading multiple items
|
|
||||||
const items = [
|
|
||||||
{ id: "item1", name: "Album 1" },
|
|
||||||
{ id: "item2", name: "Album 2" },
|
|
||||||
{ id: "item1", name: "Album 1 (again)" }, // Same ID
|
|
||||||
];
|
|
||||||
|
|
||||||
for (const item of items) {
|
|
||||||
if (!imageUrls.has(item.id)) {
|
|
||||||
const url = await mockRepository.getImageUrl(item.id, "Primary");
|
|
||||||
imageUrls.set(item.id, url);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Should only call once per unique ID
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should update single item without affecting others", async () => {
|
|
||||||
const imageUrls = new Map<string, string>();
|
|
||||||
|
|
||||||
imageUrls.set("item1", "https://server.com/image1.jpg");
|
|
||||||
imageUrls.set("item2", "https://server.com/image2.jpg");
|
|
||||||
imageUrls.set("item3", "https://server.com/image3.jpg");
|
|
||||||
|
|
||||||
// Update item2
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image2_updated.jpg");
|
|
||||||
const newUrl = await mockRepository.getImageUrl("item2", "Primary");
|
|
||||||
imageUrls.set("item2", newUrl);
|
|
||||||
|
|
||||||
// Others should remain unchanged
|
|
||||||
expect(imageUrls.get("item1")).toBe("https://server.com/image1.jpg");
|
|
||||||
expect(imageUrls.get("item2")).toBe("https://server.com/image2_updated.jpg");
|
|
||||||
expect(imageUrls.get("item3")).toBe("https://server.com/image3.jpg");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should clear cache when data changes", () => {
|
|
||||||
const imageUrls = new Map<string, string>();
|
|
||||||
|
|
||||||
imageUrls.set("item1", "https://server.com/image1.jpg");
|
|
||||||
imageUrls.set("item2", "https://server.com/image2.jpg");
|
|
||||||
|
|
||||||
// Clear cache
|
|
||||||
imageUrls.clear();
|
|
||||||
|
|
||||||
expect(imageUrls.size).toBe(0);
|
|
||||||
expect(imageUrls.has("item1")).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should support Map operations efficiently", () => {
|
|
||||||
const imageUrls = new Map<string, string>();
|
|
||||||
|
|
||||||
// Add items
|
|
||||||
for (let i = 0; i < 100; i++) {
|
|
||||||
imageUrls.set(`item${i}`, `https://server.com/image${i}.jpg`);
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(imageUrls.size).toBe(100);
|
|
||||||
|
|
||||||
// Check specific item
|
|
||||||
expect(imageUrls.has("item50")).toBe(true);
|
|
||||||
expect(imageUrls.get("item50")).toBe("https://server.com/image50.jpg");
|
|
||||||
|
|
||||||
// Iterate
|
|
||||||
let count = 0;
|
|
||||||
imageUrls.forEach(() => {
|
|
||||||
count++;
|
|
||||||
});
|
|
||||||
expect(count).toBe(100);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("Component Lifecycle ($effect integration)", () => {
|
|
||||||
it("should trigger load on prop change", async () => {
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
|
|
||||||
|
|
||||||
// Simulate $effect tracking prop changes
|
|
||||||
let effectCount = 0;
|
|
||||||
const trackingEffect = vi.fn(() => {
|
|
||||||
effectCount++;
|
|
||||||
return mockRepository.getImageUrl("item123", "Primary");
|
|
||||||
});
|
|
||||||
|
|
||||||
trackingEffect();
|
|
||||||
expect(effectCount).toBe(1);
|
|
||||||
|
|
||||||
trackingEffect();
|
|
||||||
expect(effectCount).toBe(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should skip load if conditions not met", async () => {
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
|
|
||||||
|
|
||||||
// Simulate conditional loading (e.g., if (!imageUrl && primaryImageTag))
|
|
||||||
let imageUrl = "";
|
|
||||||
const primaryImageTag = "";
|
|
||||||
|
|
||||||
if (!imageUrl && primaryImageTag) {
|
|
||||||
imageUrl = await mockRepository.getImageUrl("item123", "Primary");
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(mockRepository.getImageUrl).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should handle dependent state updates", async () => {
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
|
|
||||||
|
|
||||||
// Simulate component state changes triggering effects
|
|
||||||
const state = {
|
|
||||||
item: { id: "item1", primaryImageTag: "tag1" },
|
|
||||||
imageUrl: "",
|
|
||||||
};
|
|
||||||
|
|
||||||
const loadImage = async () => {
|
|
||||||
if (state.item.primaryImageTag) {
|
|
||||||
state.imageUrl = await mockRepository.getImageUrl(state.item.id, "Primary");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
await loadImage();
|
|
||||||
expect(state.imageUrl).toBe("https://server.com/image.jpg");
|
|
||||||
|
|
||||||
// Change item
|
|
||||||
state.item = { id: "item2", primaryImageTag: "tag2" };
|
|
||||||
state.imageUrl = "";
|
|
||||||
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image2.jpg");
|
|
||||||
await loadImage();
|
|
||||||
expect(state.imageUrl).toBe("https://server.com/image2.jpg");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("Error Handling in Async Loading", () => {
|
|
||||||
it("should set empty string on error", async () => {
|
|
||||||
mockRepository.getImageUrl.mockRejectedValue(new Error("Network error"));
|
|
||||||
|
|
||||||
let imageUrl = "";
|
|
||||||
|
|
||||||
try {
|
|
||||||
imageUrl = await mockRepository.getImageUrl("item123", "Primary");
|
|
||||||
} catch {
|
|
||||||
imageUrl = ""; // Set to empty on error
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(imageUrl).toBe("");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should allow retry after error", async () => {
|
|
||||||
mockRepository.getImageUrl
|
|
||||||
.mockRejectedValueOnce(new Error("Network error"))
|
|
||||||
.mockResolvedValueOnce("https://server.com/image.jpg");
|
|
||||||
|
|
||||||
let imageUrl = "";
|
|
||||||
|
|
||||||
// First attempt fails
|
|
||||||
try {
|
|
||||||
imageUrl = await mockRepository.getImageUrl("item123", "Primary");
|
|
||||||
} catch {
|
|
||||||
imageUrl = "";
|
|
||||||
}
|
|
||||||
|
|
||||||
// Retry succeeds
|
|
||||||
imageUrl = await mockRepository.getImageUrl("item123", "Primary");
|
|
||||||
expect(imageUrl).toBe("https://server.com/image.jpg");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should handle concurrent load requests", async () => {
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
|
|
||||||
|
|
||||||
// Simulate loading multiple images concurrently
|
|
||||||
const imageUrls = new Map<string, string>();
|
|
||||||
const items = [
|
|
||||||
{ id: "item1" },
|
|
||||||
{ id: "item2" },
|
|
||||||
{ id: "item3" },
|
|
||||||
];
|
|
||||||
|
|
||||||
const promises = items.map(item =>
|
|
||||||
mockRepository.getImageUrl(item.id, "Primary")
|
|
||||||
.then((url: string) => imageUrls.set(item.id, url))
|
|
||||||
.catch(() => imageUrls.set(item.id, ""))
|
|
||||||
);
|
|
||||||
|
|
||||||
await Promise.all(promises);
|
|
||||||
|
|
||||||
expect(imageUrls.size).toBe(3);
|
|
||||||
expect(imageUrls.has("item1")).toBe(true);
|
|
||||||
expect(imageUrls.has("item2")).toBe(true);
|
|
||||||
expect(imageUrls.has("item3")).toBe(true);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("Performance Characteristics", () => {
|
|
||||||
it("should not reload unnecessarily", async () => {
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
|
|
||||||
|
|
||||||
// Simulate $effect with dependency tracking
|
|
||||||
let dependencyValue = "same";
|
|
||||||
let previousDependency = "same";
|
|
||||||
|
|
||||||
const loadImage = async () => {
|
|
||||||
if (dependencyValue !== previousDependency) {
|
|
||||||
previousDependency = dependencyValue;
|
|
||||||
return await mockRepository.getImageUrl("item123", "Primary");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
await loadImage();
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
|
|
||||||
|
|
||||||
// No change in dependency
|
|
||||||
await loadImage();
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
|
|
||||||
|
|
||||||
// Change dependency
|
|
||||||
dependencyValue = "changed";
|
|
||||||
await loadImage();
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should handle large lists efficiently", async () => {
|
|
||||||
const imageUrls = new Map<string, string>();
|
|
||||||
let loadCount = 0;
|
|
||||||
|
|
||||||
mockRepository.getImageUrl.mockImplementation(() => {
|
|
||||||
loadCount++;
|
|
||||||
return Promise.resolve("https://server.com/image.jpg");
|
|
||||||
});
|
|
||||||
|
|
||||||
// Simulate loading 1000 items but caching URLs
|
|
||||||
const items = Array.from({ length: 1000 }, (_, i) => ({ id: `item${i % 10}` }));
|
|
||||||
|
|
||||||
for (const item of items) {
|
|
||||||
if (!imageUrls.has(item.id)) {
|
|
||||||
const url = await mockRepository.getImageUrl(item.id, "Primary");
|
|
||||||
imageUrls.set(item.id, url);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Should only load 10 unique images
|
|
||||||
expect(loadCount).toBe(10);
|
|
||||||
expect(imageUrls.size).toBe(10);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should not block rendering during async loading", () => {
|
|
||||||
mockRepository.getImageUrl.mockImplementation(
|
|
||||||
() => new Promise((resolve) =>
|
|
||||||
setTimeout(() => resolve("https://server.com/image.jpg"), 1000)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
// Async operation should not block component rendering
|
|
||||||
const renderTiming = {
|
|
||||||
startRender: Date.now(),
|
|
||||||
loadStart: null as number | null,
|
|
||||||
loadComplete: null as number | null,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Render happens immediately
|
|
||||||
renderTiming.startRender = Date.now();
|
|
||||||
|
|
||||||
// Load happens asynchronously
|
|
||||||
mockRepository.getImageUrl("item123", "Primary").then(() => {
|
|
||||||
renderTiming.loadComplete = Date.now();
|
|
||||||
});
|
|
||||||
|
|
||||||
// Render should complete before load finishes
|
|
||||||
expect(Date.now() - renderTiming.startRender).toBeLessThan(1000);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("Backend Integration", () => {
|
|
||||||
it("should call backend with correct parameters", async () => {
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image.jpg");
|
|
||||||
|
|
||||||
await mockRepository.getImageUrl("item123", "Primary", {
|
|
||||||
maxWidth: 300,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalledWith(
|
|
||||||
"item123",
|
|
||||||
"Primary",
|
|
||||||
{
|
|
||||||
maxWidth: 300,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should handle backend URL correctly", async () => {
|
|
||||||
const backendUrl = "https://server.com/Items/item123/Images/Primary?maxWidth=300&api_key=token";
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue(backendUrl);
|
|
||||||
|
|
||||||
const url = await mockRepository.getImageUrl("item123", "Primary", { maxWidth: 300 });
|
|
||||||
|
|
||||||
expect(url).toBe(backendUrl);
|
|
||||||
// Frontend never constructs URLs directly
|
|
||||||
expect(url).toContain("api_key=");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should not require URL construction in frontend", async () => {
|
|
||||||
// Frontend receives pre-constructed URL from backend
|
|
||||||
const preConstructedUrl = "https://server.com/Items/item123/Images/Primary?api_key=token";
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue(preConstructedUrl);
|
|
||||||
|
|
||||||
const url = await mockRepository.getImageUrl("item123", "Primary");
|
|
||||||
|
|
||||||
// Frontend just uses the URL
|
|
||||||
expect(url).toContain("https://");
|
|
||||||
expect(url).toContain("item123");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
import { page } from "$app/stores";
|
import { page } from "$app/stores";
|
||||||
import { truncateMiddle } from "$lib/utils/truncateMiddle";
|
import { truncateMiddle } from "$lib/utils/truncateMiddle";
|
||||||
import { goto } from "$app/navigation";
|
import { goto } from "$app/navigation";
|
||||||
import { navigateBack } from "$lib/utils/navigation";
|
import { navigateUp } from "$lib/utils/navigation";
|
||||||
import { currentLibrary } from "$lib/stores/library";
|
import { currentLibrary } from "$lib/stores/library";
|
||||||
import { auth } from "$lib/stores/auth";
|
import { auth } from "$lib/stores/auth";
|
||||||
import SearchBar from "$lib/components/common/SearchBar.svelte";
|
import SearchBar from "$lib/components/common/SearchBar.svelte";
|
||||||
@@ -138,7 +138,7 @@
|
|||||||
selectedGenre = null;
|
selectedGenre = null;
|
||||||
genreItems = [];
|
genreItems = [];
|
||||||
} else {
|
} else {
|
||||||
navigateBack(config.backPath);
|
navigateUp(config.backPath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,154 @@
|
|||||||
|
/**
|
||||||
|
* Regression test: media-list search must surface server results.
|
||||||
|
*
|
||||||
|
* `repository_search` is two-phase — `repo.search()` resolves instantly with
|
||||||
|
* cache-only (downloaded) results, and the merged cache+server union arrives
|
||||||
|
* later via a `search-event`. A consumer that ignores that event only ever
|
||||||
|
* shows downloaded content, so search "finds nothing" for un-downloaded media.
|
||||||
|
*
|
||||||
|
* This test models that two-phase backend faithfully and would fail against a
|
||||||
|
* version of GenericMediaListPage that does not subscribe to `search-event`.
|
||||||
|
*
|
||||||
|
* TRACES: UR-008
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
|
import { render, screen, fireEvent, waitFor } from "@testing-library/svelte";
|
||||||
|
import GenericMediaListPage from "./GenericMediaListPage.svelte";
|
||||||
|
import type { MediaListConfig } from "./GenericMediaListPage.svelte";
|
||||||
|
|
||||||
|
vi.mock("$app/navigation", () => ({ goto: vi.fn() }));
|
||||||
|
|
||||||
|
vi.mock("$lib/stores/library", () => ({
|
||||||
|
currentLibrary: {
|
||||||
|
subscribe: vi.fn((fn) => {
|
||||||
|
fn({ id: "lib123", name: "Music" });
|
||||||
|
return vi.fn();
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
// Consumed as a store ($viewMode) by LibraryGrid, which this page renders.
|
||||||
|
viewMode: {
|
||||||
|
subscribe: vi.fn((fn) => {
|
||||||
|
fn("grid");
|
||||||
|
return vi.fn();
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("$lib/stores/auth", () => ({
|
||||||
|
auth: { getRepository: vi.fn() },
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("$lib/composables/useServerReachabilityReload", () => ({
|
||||||
|
useServerReachabilityReload: vi.fn(() => ({ markLoaded: vi.fn() })),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Capture the `search-event` handler the component registers so the test can
|
||||||
|
// drive the deferred (server) phase manually.
|
||||||
|
let searchEventHandler: ((event: { payload: unknown }) => void) | null = null;
|
||||||
|
vi.mock("@tauri-apps/api/event", () => ({
|
||||||
|
listen: vi.fn(async (name: string, handler: (event: { payload: unknown }) => void) => {
|
||||||
|
if (name === "search-event") searchEventHandler = handler;
|
||||||
|
return () => {};
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const ALBUM_CONFIG: MediaListConfig = {
|
||||||
|
itemType: "MusicAlbum",
|
||||||
|
title: "Albums",
|
||||||
|
backPath: "/library/music",
|
||||||
|
searchPlaceholder: "Search albums...",
|
||||||
|
sortOptions: [{ key: "SortName", label: "Title" }],
|
||||||
|
defaultSort: "SortName",
|
||||||
|
displayComponent: "grid",
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("GenericMediaListPage — two-phase search", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
searchEventHandler = null;
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders server results that arrive after the cache-only phase", async () => {
|
||||||
|
// Phase 1 (synchronous) returns cache-only — empty, as it is for a user who
|
||||||
|
// has downloaded nothing. This is the exact condition that used to show
|
||||||
|
// "nothing found" even though the server has matching albums.
|
||||||
|
let capturedRequestId: number | undefined;
|
||||||
|
const search = vi.fn(async (_q: string, _opts: unknown, requestId: number) => {
|
||||||
|
capturedRequestId = requestId;
|
||||||
|
return { items: [], totalRecordCount: 0 };
|
||||||
|
});
|
||||||
|
|
||||||
|
const getItems = vi.fn().mockResolvedValue({ items: [], totalRecordCount: 0 });
|
||||||
|
vi.mocked((await import("$lib/stores/auth")).auth.getRepository).mockReturnValue({
|
||||||
|
getItems,
|
||||||
|
search,
|
||||||
|
} as any);
|
||||||
|
|
||||||
|
const { container } = render(GenericMediaListPage, { props: { config: ALBUM_CONFIG } });
|
||||||
|
|
||||||
|
// Let the initial (mount) load finish so the debounced search effect is armed.
|
||||||
|
await waitFor(() => expect(getItems).toHaveBeenCalled());
|
||||||
|
|
||||||
|
const input = container.querySelector("input") as HTMLInputElement;
|
||||||
|
fireEvent.input(input, { target: { value: "Rumours" } });
|
||||||
|
|
||||||
|
// Debounced search fires after 300ms and returns the empty cache result.
|
||||||
|
// The `search-event` listener is registered lazily as part of searching.
|
||||||
|
await waitFor(() => expect(search).toHaveBeenCalled());
|
||||||
|
await waitFor(() => expect(searchEventHandler).not.toBeNull());
|
||||||
|
// Cache-only phase: nothing to show yet (the results counter reads zero).
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByText(/0 musicalbums matching/)).toBeTruthy()
|
||||||
|
);
|
||||||
|
|
||||||
|
// Phase 2: backend emits the merged cache+server union for this request.
|
||||||
|
expect(capturedRequestId).toBeTypeOf("number");
|
||||||
|
searchEventHandler!({
|
||||||
|
payload: {
|
||||||
|
requestId: capturedRequestId,
|
||||||
|
result: {
|
||||||
|
items: [{ id: "album1", name: "Rumours", type: "MusicAlbum" }],
|
||||||
|
totalRecordCount: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// The server result must now be reflected in the list. Old code (no
|
||||||
|
// listener) never reached this state — the count stayed at zero.
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByText(/1 musicalbum matching/)).toBeTruthy()
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores a search-event whose requestId is stale", async () => {
|
||||||
|
const search = vi.fn(async () => ({ items: [], totalRecordCount: 0 }));
|
||||||
|
const getItems = vi.fn().mockResolvedValue({ items: [], totalRecordCount: 0 });
|
||||||
|
vi.mocked((await import("$lib/stores/auth")).auth.getRepository).mockReturnValue({
|
||||||
|
getItems,
|
||||||
|
search,
|
||||||
|
} as any);
|
||||||
|
|
||||||
|
const { container } = render(GenericMediaListPage, { props: { config: ALBUM_CONFIG } });
|
||||||
|
await waitFor(() => expect(getItems).toHaveBeenCalled());
|
||||||
|
|
||||||
|
const input = container.querySelector("input") as HTMLInputElement;
|
||||||
|
fireEvent.input(input, { target: { value: "Rumours" } });
|
||||||
|
await waitFor(() => expect(search).toHaveBeenCalled());
|
||||||
|
await waitFor(() => expect(searchEventHandler).not.toBeNull());
|
||||||
|
|
||||||
|
// A superseded query's late result (wrong requestId) must not render.
|
||||||
|
searchEventHandler!({
|
||||||
|
payload: {
|
||||||
|
requestId: -999,
|
||||||
|
result: {
|
||||||
|
items: [{ id: "stale", name: "Stale Album", type: "MusicAlbum" }],
|
||||||
|
totalRecordCount: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await new Promise((r) => setTimeout(r, 0));
|
||||||
|
expect(screen.queryByText("Stale Album")).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
<!-- TRACES: UR-007, UR-029, UR-030 | DR-007, DR-032, DR-033 -->
|
<!-- TRACES: UR-007, UR-029, UR-030 | DR-007, DR-032, DR-033 -->
|
||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { onMount } from "svelte";
|
import { onMount, onDestroy } from "svelte";
|
||||||
|
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
|
||||||
import { goto } from "$app/navigation";
|
import { goto } from "$app/navigation";
|
||||||
import { navigateBack } from "$lib/utils/navigation";
|
import { navigateUp } from "$lib/utils/navigation";
|
||||||
import { currentLibrary } from "$lib/stores/library";
|
import { currentLibrary } from "$lib/stores/library";
|
||||||
import { auth } from "$lib/stores/auth";
|
import { auth } from "$lib/stores/auth";
|
||||||
import { shouldShowAudioMiniPlayer } from "$lib/stores/player";
|
import { shouldShowAudioMiniPlayer } from "$lib/stores/player";
|
||||||
@@ -13,7 +14,7 @@
|
|||||||
import BackButton from "$lib/components/common/BackButton.svelte";
|
import BackButton from "$lib/components/common/BackButton.svelte";
|
||||||
import ResultsCounter from "$lib/components/common/ResultsCounter.svelte";
|
import ResultsCounter from "$lib/components/common/ResultsCounter.svelte";
|
||||||
import { useServerReachabilityReload } from "$lib/composables/useServerReachabilityReload";
|
import { useServerReachabilityReload } from "$lib/composables/useServerReachabilityReload";
|
||||||
import type { MediaItem, Library, ItemType } from "$lib/api/types";
|
import type { MediaItem, Library, ItemType, SearchResult } from "$lib/api/types";
|
||||||
import LibraryGrid from "./LibraryGrid.svelte";
|
import LibraryGrid from "./LibraryGrid.svelte";
|
||||||
import TrackList from "./TrackList.svelte";
|
import TrackList from "./TrackList.svelte";
|
||||||
import AlphabetScrollBar from "./AlphabetScrollBar.svelte";
|
import AlphabetScrollBar from "./AlphabetScrollBar.svelte";
|
||||||
@@ -54,6 +55,31 @@
|
|||||||
let searchTimeout: ReturnType<typeof setTimeout> | null = null;
|
let searchTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||||
let initialLoadDone = false;
|
let initialLoadDone = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Payload of the backend `search-event` (mirrors Rust `SearchUpdateEvent`).
|
||||||
|
* `repo.search()` resolves instantly with cache-only (downloaded) results;
|
||||||
|
* the merged cache+server union arrives later via this event.
|
||||||
|
*/
|
||||||
|
interface SearchUpdateEvent {
|
||||||
|
requestId: number;
|
||||||
|
result: SearchResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Monotonic id identifying the latest search request. The deferred
|
||||||
|
// `search-event` is only applied when its requestId still matches, so
|
||||||
|
// out-of-order / superseded server results never clobber fresher ones.
|
||||||
|
let searchRequestId = 0;
|
||||||
|
let unlistenSearch: UnlistenFn | null = null;
|
||||||
|
|
||||||
|
async function ensureSearchListener() {
|
||||||
|
if (unlistenSearch) return;
|
||||||
|
unlistenSearch = await listen<SearchUpdateEvent>("search-event", (event) => {
|
||||||
|
const { requestId, result } = event.payload;
|
||||||
|
if (requestId !== searchRequestId) return;
|
||||||
|
items = excludePodcasts(result.items);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
sortBy = config.defaultSort;
|
sortBy = config.defaultSort;
|
||||||
});
|
});
|
||||||
@@ -82,12 +108,26 @@
|
|||||||
// Use backend search if search query is provided, otherwise use getItems with sort
|
// Use backend search if search query is provided, otherwise use getItems with sort
|
||||||
// HACK: excludePodcasts drops the "Podcasts" folder stored in the music library.
|
// HACK: excludePodcasts drops the "Podcasts" folder stored in the music library.
|
||||||
if (debouncedSearchQuery.trim()) {
|
if (debouncedSearchQuery.trim()) {
|
||||||
const result = await repo.search(debouncedSearchQuery, {
|
// Phase 1: instant cache-only (downloaded) results. The merged
|
||||||
includeItemTypes: [config.itemType],
|
// cache+server union arrives later via the `search-event` listener,
|
||||||
limit: 10000,
|
// tagged with this requestId so superseded queries are ignored.
|
||||||
});
|
await ensureSearchListener();
|
||||||
items = excludePodcasts(result.items);
|
const requestId = ++searchRequestId;
|
||||||
|
const result = await repo.search(
|
||||||
|
debouncedSearchQuery,
|
||||||
|
{
|
||||||
|
includeItemTypes: [config.itemType],
|
||||||
|
limit: 10000,
|
||||||
|
},
|
||||||
|
requestId
|
||||||
|
);
|
||||||
|
// Only apply if this is still the active query.
|
||||||
|
if (requestId === searchRequestId) {
|
||||||
|
items = excludePodcasts(result.items);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
|
// Leaving search — invalidate any in-flight server results.
|
||||||
|
searchRequestId++;
|
||||||
const result = await repo.getItems($currentLibrary.id, {
|
const result = await repo.getItems($currentLibrary.id, {
|
||||||
includeItemTypes: [config.itemType],
|
includeItemTypes: [config.itemType],
|
||||||
sortBy,
|
sortBy,
|
||||||
@@ -120,6 +160,11 @@
|
|||||||
}, 300);
|
}, 300);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
onDestroy(() => {
|
||||||
|
if (unlistenSearch) unlistenSearch();
|
||||||
|
if (searchTimeout) clearTimeout(searchTimeout);
|
||||||
|
});
|
||||||
|
|
||||||
function handleSort(newSort: string) {
|
function handleSort(newSort: string) {
|
||||||
sortBy = newSort;
|
sortBy = newSort;
|
||||||
loadItems();
|
loadItems();
|
||||||
@@ -131,7 +176,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function goBack() {
|
function goBack() {
|
||||||
navigateBack(config.backPath);
|
navigateUp(config.backPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
const searchPlaceholder = $derived(config.searchPlaceholder || `Search ${config.title.toLowerCase()}...`);
|
const searchPlaceholder = $derived(config.searchPlaceholder || `Search ${config.title.toLowerCase()}...`);
|
||||||
|
|||||||
@@ -15,6 +15,13 @@ vi.mock("$lib/stores/library", () => ({
|
|||||||
return vi.fn();
|
return vi.fn();
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
|
// Consumed as a store ($viewMode) by LibraryGrid, which this page renders.
|
||||||
|
viewMode: {
|
||||||
|
subscribe: vi.fn((fn) => {
|
||||||
|
fn("grid");
|
||||||
|
return vi.fn();
|
||||||
|
}),
|
||||||
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("$lib/stores/auth", () => ({
|
vi.mock("$lib/stores/auth", () => ({
|
||||||
@@ -32,7 +39,12 @@ vi.mock("$lib/composables/useServerReachabilityReload", () => ({
|
|||||||
})),
|
})),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
describe.skip("GenericMediaListPage", () => {
|
// The component lazily subscribes to the backend `search-event` when searching.
|
||||||
|
vi.mock("@tauri-apps/api/event", () => ({
|
||||||
|
listen: vi.fn(async () => () => {}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe("GenericMediaListPage", () => {
|
||||||
// Component integration tests - core sorting/search/debouncing logic tested in backend-integration.test.ts
|
// Component integration tests - core sorting/search/debouncing logic tested in backend-integration.test.ts
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
@@ -66,6 +78,16 @@ describe.skip("GenericMediaListPage", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should load items on mount", async () => {
|
it("should load items on mount", async () => {
|
||||||
|
const mockGetItemsFn = vi.fn().mockResolvedValue({
|
||||||
|
items: [],
|
||||||
|
totalRecordCount: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
vi.mocked((await import("$lib/stores/auth")).auth.getRepository).mockReturnValue({
|
||||||
|
getItems: mockGetItemsFn,
|
||||||
|
search: vi.fn(),
|
||||||
|
} as any);
|
||||||
|
|
||||||
const config = {
|
const config = {
|
||||||
itemType: "Audio" as const,
|
itemType: "Audio" as const,
|
||||||
title: "Tracks",
|
title: "Tracks",
|
||||||
@@ -80,9 +102,7 @@ describe.skip("GenericMediaListPage", () => {
|
|||||||
props: { config },
|
props: { config },
|
||||||
});
|
});
|
||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => expect(mockGetItemsFn).toHaveBeenCalledWith("lib123", expect.anything()));
|
||||||
// loadItems should have been called
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should display sort options", () => {
|
it("should display sort options", () => {
|
||||||
@@ -111,8 +131,14 @@ describe.skip("GenericMediaListPage", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("Search Functionality", () => {
|
describe("Search Functionality", () => {
|
||||||
it("should debounce search input for 300ms", async () => {
|
it("should debounce rapid keystrokes into a single search for the final value", async () => {
|
||||||
vi.useFakeTimers();
|
const mockSearchFn = vi.fn().mockResolvedValue({ items: [], totalRecordCount: 0 });
|
||||||
|
const mockGetItemsFn = vi.fn().mockResolvedValue({ items: [], totalRecordCount: 0 });
|
||||||
|
|
||||||
|
vi.mocked((await import("$lib/stores/auth")).auth.getRepository).mockReturnValue({
|
||||||
|
getItems: mockGetItemsFn,
|
||||||
|
search: mockSearchFn,
|
||||||
|
} as any);
|
||||||
|
|
||||||
const config = {
|
const config = {
|
||||||
itemType: "Audio" as const,
|
itemType: "Audio" as const,
|
||||||
@@ -128,29 +154,33 @@ describe.skip("GenericMediaListPage", () => {
|
|||||||
props: { config },
|
props: { config },
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Let the mount load settle so the debounce effect is armed.
|
||||||
|
await waitFor(() => expect(mockGetItemsFn).toHaveBeenCalled());
|
||||||
|
|
||||||
|
// Drive the debounce window deterministically with fake timers, flushing
|
||||||
|
// the async loadItems() microtasks after the timer fires.
|
||||||
|
vi.useFakeTimers();
|
||||||
const searchInput = container.querySelector("input") as HTMLInputElement;
|
const searchInput = container.querySelector("input") as HTMLInputElement;
|
||||||
|
|
||||||
// Type into search
|
|
||||||
fireEvent.input(searchInput, { target: { value: "t" } });
|
fireEvent.input(searchInput, { target: { value: "t" } });
|
||||||
expect(searchInput.value).toBe("t");
|
await vi.advanceTimersByTimeAsync(100);
|
||||||
|
fireEvent.input(searchInput, { target: { value: "te" } });
|
||||||
// Search should not trigger immediately
|
await vi.advanceTimersByTimeAsync(100);
|
||||||
vi.advanceTimersByTime(100);
|
fireEvent.input(searchInput, { target: { value: "tes" } });
|
||||||
|
await vi.advanceTimersByTimeAsync(100);
|
||||||
// Add more characters
|
|
||||||
fireEvent.input(searchInput, { target: { value: "test" } });
|
fireEvent.input(searchInput, { target: { value: "test" } });
|
||||||
|
|
||||||
// Still shouldn't trigger (only 100ms passed total)
|
// 200ms after the final keystroke: still inside the 300ms window, so no
|
||||||
vi.advanceTimersByTime(100);
|
// search has fired despite four keystrokes.
|
||||||
|
await vi.advanceTimersByTimeAsync(200);
|
||||||
// Now advance to 300ms total - search should trigger
|
expect(mockSearchFn).not.toHaveBeenCalled();
|
||||||
vi.advanceTimersByTime(100);
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
// Search should have been debounced
|
|
||||||
});
|
|
||||||
|
|
||||||
|
// Cross the threshold: exactly one search, for the final value.
|
||||||
|
await vi.advanceTimersByTimeAsync(100);
|
||||||
vi.useRealTimers();
|
vi.useRealTimers();
|
||||||
|
|
||||||
|
expect(mockSearchFn).toHaveBeenCalledTimes(1);
|
||||||
|
expect(mockSearchFn).toHaveBeenCalledWith("test", expect.anything(), expect.any(Number));
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should use backend search when search query is provided", async () => {
|
it("should use backend search when search query is provided", async () => {
|
||||||
@@ -159,8 +189,13 @@ describe.skip("GenericMediaListPage", () => {
|
|||||||
totalRecordCount: 1,
|
totalRecordCount: 1,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const mockGetItemsFn = vi.fn().mockResolvedValue({
|
||||||
|
items: [],
|
||||||
|
totalRecordCount: 0,
|
||||||
|
});
|
||||||
|
|
||||||
const mockRepository = {
|
const mockRepository = {
|
||||||
getItems: vi.fn(),
|
getItems: mockGetItemsFn,
|
||||||
search: mockSearchFn,
|
search: mockSearchFn,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -178,25 +213,27 @@ describe.skip("GenericMediaListPage", () => {
|
|||||||
displayComponent: "tracklist" as const,
|
displayComponent: "tracklist" as const,
|
||||||
};
|
};
|
||||||
|
|
||||||
vi.useFakeTimers();
|
|
||||||
const { container } = render(GenericMediaListPage, {
|
const { container } = render(GenericMediaListPage, {
|
||||||
props: { config },
|
props: { config },
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Wait for the initial mount load so the debounced search effect is armed.
|
||||||
|
await waitFor(() => expect(mockGetItemsFn).toHaveBeenCalled());
|
||||||
|
|
||||||
const searchInput = container.querySelector("input") as HTMLInputElement;
|
const searchInput = container.querySelector("input") as HTMLInputElement;
|
||||||
fireEvent.input(searchInput, { target: { value: "test" } });
|
fireEvent.input(searchInput, { target: { value: "test" } });
|
||||||
|
|
||||||
// Advance timer to trigger debounced search
|
// search() is called as search(query, options, requestId).
|
||||||
vi.advanceTimersByTime(300);
|
|
||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
expect(mockSearchFn).toHaveBeenCalledWith("test", expect.objectContaining({
|
expect(mockSearchFn).toHaveBeenCalledWith(
|
||||||
includeItemTypes: ["Audio"],
|
"test",
|
||||||
limit: 10000,
|
expect.objectContaining({
|
||||||
}));
|
includeItemTypes: ["Audio"],
|
||||||
|
limit: 10000,
|
||||||
|
}),
|
||||||
|
expect.any(Number)
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
vi.useRealTimers();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should use getItems without search for empty query", async () => {
|
it("should use getItems without search for empty query", async () => {
|
||||||
@@ -416,15 +453,18 @@ describe.skip("GenericMediaListPage", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should include correct itemType in search request", async () => {
|
it("should include correct itemType in search request", async () => {
|
||||||
vi.useFakeTimers();
|
|
||||||
|
|
||||||
const mockSearchFn = vi.fn().mockResolvedValue({
|
const mockSearchFn = vi.fn().mockResolvedValue({
|
||||||
items: [],
|
items: [],
|
||||||
totalRecordCount: 0,
|
totalRecordCount: 0,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const mockGetItemsFn = vi.fn().mockResolvedValue({
|
||||||
|
items: [],
|
||||||
|
totalRecordCount: 0,
|
||||||
|
});
|
||||||
|
|
||||||
const mockRepository = {
|
const mockRepository = {
|
||||||
getItems: vi.fn(),
|
getItems: mockGetItemsFn,
|
||||||
search: mockSearchFn,
|
search: mockSearchFn,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -446,17 +486,20 @@ describe.skip("GenericMediaListPage", () => {
|
|||||||
props: { config },
|
props: { config },
|
||||||
});
|
});
|
||||||
|
|
||||||
|
await waitFor(() => expect(mockGetItemsFn).toHaveBeenCalled());
|
||||||
|
|
||||||
const searchInput = container.querySelector("input") as HTMLInputElement;
|
const searchInput = container.querySelector("input") as HTMLInputElement;
|
||||||
fireEvent.input(searchInput, { target: { value: "album" } });
|
fireEvent.input(searchInput, { target: { value: "album" } });
|
||||||
vi.advanceTimersByTime(300);
|
|
||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
expect(mockSearchFn).toHaveBeenCalledWith("album", expect.objectContaining({
|
expect(mockSearchFn).toHaveBeenCalledWith(
|
||||||
includeItemTypes: ["MusicAlbum"],
|
"album",
|
||||||
}));
|
expect.objectContaining({
|
||||||
|
includeItemTypes: ["MusicAlbum"],
|
||||||
|
}),
|
||||||
|
expect.any(Number)
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
vi.useRealTimers();
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -536,6 +579,7 @@ describe.skip("GenericMediaListPage", () => {
|
|||||||
|
|
||||||
it("should handle missing library gracefully", async () => {
|
it("should handle missing library gracefully", async () => {
|
||||||
const { goto } = await import("$app/navigation");
|
const { goto } = await import("$app/navigation");
|
||||||
|
vi.mocked(goto).mockClear();
|
||||||
|
|
||||||
const mockGetItemsFn = vi.fn();
|
const mockGetItemsFn = vi.fn();
|
||||||
|
|
||||||
@@ -548,14 +592,12 @@ describe.skip("GenericMediaListPage", () => {
|
|||||||
mockRepository as any
|
mockRepository as any
|
||||||
);
|
);
|
||||||
|
|
||||||
// Mock currentLibrary to return null
|
// Deliver a null current library for this test only.
|
||||||
vi.resetModules();
|
const currentLibrary = vi.mocked((await import("$lib/stores/library")).currentLibrary);
|
||||||
vi.mocked((await import("$lib/stores/library")).currentLibrary.subscribe).mockImplementation(
|
currentLibrary.subscribe.mockImplementation((fn: any) => {
|
||||||
(fn: any) => {
|
fn(null);
|
||||||
fn(null);
|
return vi.fn();
|
||||||
return vi.fn();
|
});
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
const config = {
|
const config = {
|
||||||
itemType: "Audio" as const,
|
itemType: "Audio" as const,
|
||||||
@@ -571,9 +613,15 @@ describe.skip("GenericMediaListPage", () => {
|
|||||||
props: { config },
|
props: { config },
|
||||||
});
|
});
|
||||||
|
|
||||||
// Should navigate to back path when library is missing
|
// With no current library, loadItems bails out to the back path and never
|
||||||
await waitFor(() => {
|
// queries the repository.
|
||||||
// goto would be called with config.backPath
|
await waitFor(() => expect(goto).toHaveBeenCalledWith("/library/music"));
|
||||||
|
expect(mockGetItemsFn).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
// Restore the default (non-null) library for subsequent tests.
|
||||||
|
currentLibrary.subscribe.mockImplementation((fn: any) => {
|
||||||
|
fn({ id: "lib123", name: "Music" });
|
||||||
|
return vi.fn();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,373 +0,0 @@
|
|||||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
|
||||||
import { render, screen, waitFor } from "@testing-library/svelte";
|
|
||||||
import MediaCard from "./MediaCard.svelte";
|
|
||||||
|
|
||||||
vi.mock("$lib/stores/auth", () => ({
|
|
||||||
auth: {
|
|
||||||
getRepository: vi.fn(() => ({
|
|
||||||
getImageUrl: vi.fn(),
|
|
||||||
})),
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|
||||||
describe.skip("MediaCard - Async Image Loading", () => {
|
|
||||||
// Component rendering tests skipped - core async logic tested in repository-client.test.ts
|
|
||||||
let mockRepository: any;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks();
|
|
||||||
mockRepository = {
|
|
||||||
getImageUrl: vi.fn(),
|
|
||||||
};
|
|
||||||
|
|
||||||
vi.mocked((global as any).__stores_auth?.auth?.getRepository).mockReturnValue(mockRepository);
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
vi.clearAllTimers();
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("Image Loading", () => {
|
|
||||||
it("should load image URL asynchronously", async () => {
|
|
||||||
const mockImageUrl = "https://server.com/Items/item123/Images/Primary?api_key=token";
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue(mockImageUrl);
|
|
||||||
|
|
||||||
const mediaItem = {
|
|
||||||
id: "item123",
|
|
||||||
name: "Test Album",
|
|
||||||
type: "MusicAlbum" as const,
|
|
||||||
serverId: "server-1",
|
|
||||||
primaryImageTag: "abc123",
|
|
||||||
};
|
|
||||||
|
|
||||||
const { container } = render(MediaCard, {
|
|
||||||
props: { item: mediaItem },
|
|
||||||
});
|
|
||||||
|
|
||||||
// Component should render immediately with placeholder
|
|
||||||
expect(container).toBeTruthy();
|
|
||||||
|
|
||||||
// Wait for image URL to load
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalledWith(
|
|
||||||
"item123",
|
|
||||||
"Primary",
|
|
||||||
expect.objectContaining({
|
|
||||||
maxWidth: 300,
|
|
||||||
})
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should show placeholder while image is loading", async () => {
|
|
||||||
const mockImageUrl = "https://server.com/Items/item123/Images/Primary?api_key=token";
|
|
||||||
mockRepository.getImageUrl.mockImplementation(
|
|
||||||
() => new Promise((resolve) => setTimeout(() => resolve(mockImageUrl), 100))
|
|
||||||
);
|
|
||||||
|
|
||||||
const mediaItem = {
|
|
||||||
id: "item123",
|
|
||||||
name: "Test Album",
|
|
||||||
type: "MusicAlbum" as const,
|
|
||||||
serverId: "server-1",
|
|
||||||
primaryImageTag: "abc123",
|
|
||||||
};
|
|
||||||
|
|
||||||
const { container } = render(MediaCard, {
|
|
||||||
props: { item: mediaItem },
|
|
||||||
});
|
|
||||||
|
|
||||||
// Placeholder should be visible initially
|
|
||||||
const placeholder = container.querySelector(".placeholder");
|
|
||||||
if (placeholder) {
|
|
||||||
expect(placeholder).toBeTruthy();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wait for image to load
|
|
||||||
vi.useFakeTimers();
|
|
||||||
vi.advanceTimersByTime(100);
|
|
||||||
vi.useRealTimers();
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should update image URL when item changes", async () => {
|
|
||||||
const mockImageUrl1 = "https://server.com/Items/item1/Images/Primary?api_key=token";
|
|
||||||
const mockImageUrl2 = "https://server.com/Items/item2/Images/Primary?api_key=token";
|
|
||||||
|
|
||||||
mockRepository.getImageUrl.mockResolvedValueOnce(mockImageUrl1);
|
|
||||||
|
|
||||||
const mediaItem1 = {
|
|
||||||
id: "item1",
|
|
||||||
name: "Album 1",
|
|
||||||
type: "MusicAlbum" as const,
|
|
||||||
serverId: "server-1",
|
|
||||||
primaryImageTag: "tag1",
|
|
||||||
};
|
|
||||||
|
|
||||||
const { rerender } = render(MediaCard, {
|
|
||||||
props: { item: mediaItem1 },
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalledWith("item1", "Primary", expect.any(Object));
|
|
||||||
});
|
|
||||||
|
|
||||||
// Change item
|
|
||||||
mockRepository.getImageUrl.mockResolvedValueOnce(mockImageUrl2);
|
|
||||||
|
|
||||||
const mediaItem2 = {
|
|
||||||
id: "item2",
|
|
||||||
name: "Album 2",
|
|
||||||
type: "MusicAlbum" as const,
|
|
||||||
serverId: "server-1",
|
|
||||||
primaryImageTag: "tag2",
|
|
||||||
};
|
|
||||||
|
|
||||||
await rerender({ item: mediaItem2 });
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalledWith("item2", "Primary", expect.any(Object));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should not reload image if item ID hasn't changed", async () => {
|
|
||||||
const mockImageUrl = "https://server.com/Items/item123/Images/Primary?api_key=token";
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue(mockImageUrl);
|
|
||||||
|
|
||||||
const mediaItem = {
|
|
||||||
id: "item123",
|
|
||||||
name: "Test Album",
|
|
||||||
type: "MusicAlbum" as const,
|
|
||||||
serverId: "server-1",
|
|
||||||
primaryImageTag: "abc123",
|
|
||||||
};
|
|
||||||
|
|
||||||
const { rerender } = render(MediaCard, {
|
|
||||||
props: { item: mediaItem },
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Rerender with same item
|
|
||||||
await rerender({ item: mediaItem });
|
|
||||||
|
|
||||||
// Should not call getImageUrl again
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should handle missing primary image tag gracefully", async () => {
|
|
||||||
const mediaItem = {
|
|
||||||
id: "item123",
|
|
||||||
name: "Test Album",
|
|
||||||
type: "MusicAlbum" as const,
|
|
||||||
serverId: "server-1",
|
|
||||||
// primaryImageTag is undefined
|
|
||||||
};
|
|
||||||
|
|
||||||
const { container } = render(MediaCard, {
|
|
||||||
props: { item: mediaItem },
|
|
||||||
});
|
|
||||||
|
|
||||||
// Should render without calling getImageUrl
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(mockRepository.getImageUrl).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
// Should show placeholder
|
|
||||||
expect(container).toBeTruthy();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should handle image load errors gracefully", async () => {
|
|
||||||
mockRepository.getImageUrl.mockRejectedValue(new Error("Failed to load image"));
|
|
||||||
|
|
||||||
const mediaItem = {
|
|
||||||
id: "item123",
|
|
||||||
name: "Test Album",
|
|
||||||
type: "MusicAlbum" as const,
|
|
||||||
serverId: "server-1",
|
|
||||||
primaryImageTag: "abc123",
|
|
||||||
};
|
|
||||||
|
|
||||||
const { container } = render(MediaCard, {
|
|
||||||
props: { item: mediaItem },
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
// Should still render without crashing
|
|
||||||
expect(container).toBeTruthy();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("Image Options", () => {
|
|
||||||
it("should pass correct options to getImageUrl", async () => {
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image");
|
|
||||||
|
|
||||||
const mediaItem = {
|
|
||||||
id: "item123",
|
|
||||||
name: "Test Album",
|
|
||||||
type: "MusicAlbum" as const,
|
|
||||||
serverId: "server-1",
|
|
||||||
primaryImageTag: "abc123",
|
|
||||||
};
|
|
||||||
|
|
||||||
render(MediaCard, {
|
|
||||||
props: { item: mediaItem },
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalledWith(
|
|
||||||
"item123",
|
|
||||||
"Primary",
|
|
||||||
{
|
|
||||||
maxWidth: 300,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should include tag in image options when available", async () => {
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image");
|
|
||||||
|
|
||||||
const mediaItem = {
|
|
||||||
id: "item123",
|
|
||||||
name: "Test Album",
|
|
||||||
type: "MusicAlbum" as const,
|
|
||||||
serverId: "server-1",
|
|
||||||
primaryImageTag: "tag123",
|
|
||||||
};
|
|
||||||
|
|
||||||
render(MediaCard, {
|
|
||||||
props: { item: mediaItem },
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalledWith(
|
|
||||||
"item123",
|
|
||||||
"Primary",
|
|
||||||
{
|
|
||||||
maxWidth: 300,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("Caching", () => {
|
|
||||||
it("should cache image URLs to avoid duplicate requests", async () => {
|
|
||||||
const mockImageUrl = "https://server.com/Items/item123/Images/Primary?api_key=token";
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue(mockImageUrl);
|
|
||||||
|
|
||||||
const mediaItem = {
|
|
||||||
id: "item123",
|
|
||||||
name: "Test Album",
|
|
||||||
type: "MusicAlbum" as const,
|
|
||||||
serverId: "server-1",
|
|
||||||
primaryImageTag: "abc123",
|
|
||||||
};
|
|
||||||
|
|
||||||
// Render same item multiple times
|
|
||||||
const { rerender } = render(MediaCard, {
|
|
||||||
props: { item: mediaItem },
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Rerender with same item
|
|
||||||
await rerender({ item: mediaItem });
|
|
||||||
|
|
||||||
// Should still only have called once (cached)
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should have separate cache entries for different items", async () => {
|
|
||||||
const mockImageUrl1 = "https://server.com/Items/item1/Images/Primary?api_key=token";
|
|
||||||
const mockImageUrl2 = "https://server.com/Items/item2/Images/Primary?api_key=token";
|
|
||||||
|
|
||||||
let callCount = 0;
|
|
||||||
mockRepository.getImageUrl.mockImplementation(() => {
|
|
||||||
callCount++;
|
|
||||||
return Promise.resolve(callCount === 1 ? mockImageUrl1 : mockImageUrl2);
|
|
||||||
});
|
|
||||||
|
|
||||||
const item1 = {
|
|
||||||
id: "item1",
|
|
||||||
name: "Album 1",
|
|
||||||
type: "MusicAlbum" as const,
|
|
||||||
serverId: "server-1",
|
|
||||||
primaryImageTag: "tag1",
|
|
||||||
};
|
|
||||||
|
|
||||||
const item2 = {
|
|
||||||
id: "item2",
|
|
||||||
name: "Album 2",
|
|
||||||
type: "MusicAlbum" as const,
|
|
||||||
serverId: "server-1",
|
|
||||||
primaryImageTag: "tag2",
|
|
||||||
};
|
|
||||||
|
|
||||||
const { rerender } = render(MediaCard, {
|
|
||||||
props: { item: item1 },
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
await rerender({ item: item2 });
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Change back to item 1 - should use cached value
|
|
||||||
await rerender({ item: item1 });
|
|
||||||
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalledTimes(2);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("Reactive Updates", () => {
|
|
||||||
it("should respond to property changes via $effect", async () => {
|
|
||||||
mockRepository.getImageUrl.mockResolvedValue("https://server.com/image");
|
|
||||||
|
|
||||||
const mediaItem = {
|
|
||||||
id: "item123",
|
|
||||||
name: "Test Album",
|
|
||||||
type: "MusicAlbum" as const,
|
|
||||||
serverId: "server-1",
|
|
||||||
primaryImageTag: "abc123",
|
|
||||||
};
|
|
||||||
|
|
||||||
const { rerender } = render(MediaCard, {
|
|
||||||
props: { item: mediaItem },
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
expect(mockRepository.getImageUrl).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
const previousCallCount = mockRepository.getImageUrl.mock.calls.length;
|
|
||||||
|
|
||||||
// Update a property that shouldn't trigger reload
|
|
||||||
await rerender({
|
|
||||||
item: {
|
|
||||||
...mediaItem,
|
|
||||||
name: "Updated Album Name",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
// Should not call getImageUrl again (same primaryImageTag)
|
|
||||||
expect(mockRepository.getImageUrl.mock.calls.length).toBe(previousCallCount);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -54,8 +54,9 @@ import { invoke } from "@tauri-apps/api/core";
|
|||||||
import TrackList from "./TrackList.svelte";
|
import TrackList from "./TrackList.svelte";
|
||||||
import type { MediaItem } from "$lib/api/types";
|
import type { MediaItem } from "$lib/api/types";
|
||||||
import { auth } from "$lib/stores/auth";
|
import { auth } from "$lib/stores/auth";
|
||||||
|
import { toast } from "$lib/stores/toast";
|
||||||
|
|
||||||
describe.skip("TrackList", () => {
|
describe("TrackList", () => {
|
||||||
const mockRepository = {
|
const mockRepository = {
|
||||||
getAudioStreamUrl: vi.fn(),
|
getAudioStreamUrl: vi.fn(),
|
||||||
getImageUrl: vi.fn(),
|
getImageUrl: vi.fn(),
|
||||||
@@ -118,7 +119,8 @@ describe.skip("TrackList", () => {
|
|||||||
|
|
||||||
expect(getAllByText("Song 1").length).toBeGreaterThan(0);
|
expect(getAllByText("Song 1").length).toBeGreaterThan(0);
|
||||||
expect(getAllByText("Song 2").length).toBeGreaterThan(0);
|
expect(getAllByText("Song 2").length).toBeGreaterThan(0);
|
||||||
expect(getAllByText(/Song 3 with a Very Long Name/).length).toBeGreaterThan(0);
|
// Long names are abbreviated in the middle via truncateMiddle(name, 48).
|
||||||
|
expect(getAllByText(/Song 3 with a Very Long .*Should Be Truncated/).length).toBeGreaterThan(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("shows loading skeleton when loading=true", () => {
|
it("shows loading skeleton when loading=true", () => {
|
||||||
@@ -137,10 +139,12 @@ describe.skip("TrackList", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("shows artist column by default", () => {
|
it("shows artist column by default", () => {
|
||||||
const { getByText } = render(TrackList, { props: { tracks: mockTracks } });
|
const { getByText, getAllByText } = render(TrackList, { props: { tracks: mockTracks } });
|
||||||
|
|
||||||
|
// Header only exists in the desktop table.
|
||||||
expect(getByText("Artist")).toBeTruthy();
|
expect(getByText("Artist")).toBeTruthy();
|
||||||
expect(getByText("Artist 1")).toBeTruthy();
|
// Artist name renders in both desktop and mobile views.
|
||||||
|
expect(getAllByText("Artist 1").length).toBeGreaterThan(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("hides artist column when showArtist=false", () => {
|
it("hides artist column when showArtist=false", () => {
|
||||||
@@ -153,10 +157,12 @@ describe.skip("TrackList", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("shows album column by default", () => {
|
it("shows album column by default", () => {
|
||||||
const { getByText } = render(TrackList, { props: { tracks: mockTracks } });
|
const { getByText, getAllByText } = render(TrackList, { props: { tracks: mockTracks } });
|
||||||
|
|
||||||
|
// Header only exists in the desktop table.
|
||||||
expect(getByText("Album")).toBeTruthy();
|
expect(getByText("Album")).toBeTruthy();
|
||||||
expect(getByText("Album 1")).toBeTruthy();
|
// Album name renders in both desktop and mobile views.
|
||||||
|
expect(getAllByText("Album 1").length).toBeGreaterThan(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("hides album column when showAlbum=false", () => {
|
it("hides album column when showAlbum=false", () => {
|
||||||
@@ -185,12 +191,13 @@ describe.skip("TrackList", () => {
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
// Component renders both desktop and mobile views
|
// formatDuration(undefined) renders an empty string, so the row still
|
||||||
|
// renders without crashing and the track title is present.
|
||||||
const { getAllByText } = render(TrackList, {
|
const { getAllByText } = render(TrackList, {
|
||||||
props: { tracks: tracksWithoutDuration },
|
props: { tracks: tracksWithoutDuration },
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(getAllByText("-").length).toBeGreaterThan(0);
|
expect(getAllByText("Song 1").length).toBeGreaterThan(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("handles tracks without artist", () => {
|
it("handles tracks without artist", () => {
|
||||||
@@ -198,20 +205,24 @@ describe.skip("TrackList", () => {
|
|||||||
{
|
{
|
||||||
...mockTracks[0],
|
...mockTracks[0],
|
||||||
artists: undefined,
|
artists: undefined,
|
||||||
|
artistItems: undefined,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const { getByText } = render(TrackList, {
|
// The artist fallback renders "-" in both desktop and mobile views.
|
||||||
|
const { getAllByText } = render(TrackList, {
|
||||||
props: { tracks: tracksWithoutArtist },
|
props: { tracks: tracksWithoutArtist },
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(getByText("-")).toBeTruthy();
|
expect(getAllByText("-").length).toBeGreaterThan(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("renders multiple artists joined with comma", () => {
|
it("renders multiple artists joined with comma", () => {
|
||||||
const { getByText } = render(TrackList, { props: { tracks: mockTracks } });
|
// Tracks fall back to artists.join(", ") when artistItems is absent;
|
||||||
|
// the joined string renders in both desktop and mobile views.
|
||||||
|
const { getAllByText } = render(TrackList, { props: { tracks: mockTracks } });
|
||||||
|
|
||||||
expect(getByText("Artist 3, Artist 4")).toBeTruthy();
|
expect(getAllByText("Artist 3, Artist 4").length).toBeGreaterThan(0);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -278,25 +289,8 @@ describe.skip("TrackList", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it.skip("calls getAudioStreamUrl for each track", async () => {
|
it("shows error toast when playback fails", async () => {
|
||||||
// NOTE: This test is skipped because the code was refactored to use player_play_tracks
|
const toastSpy = vi.spyOn(toast, "error").mockImplementation(() => "");
|
||||||
// which sends trackIds to the backend. The backend now handles all metadata/stream fetching.
|
|
||||||
// This test expected the old behavior where frontend called getAudioStreamUrl.
|
|
||||||
});
|
|
||||||
|
|
||||||
it.skip("includes artwork URLs in queue items", async () => {
|
|
||||||
// NOTE: This test is skipped because the code was refactored.
|
|
||||||
// Stream URLs and artwork URLs are no longer fetched by frontend.
|
|
||||||
// Backend handles all metadata and stream URL fetching via player_play_tracks.
|
|
||||||
});
|
|
||||||
|
|
||||||
it.skip("handles tracks without artwork gracefully", async () => {
|
|
||||||
// NOTE: This test is skipped because the code no longer includes artwork URLs
|
|
||||||
// in queue items sent to backend. Backend handles artwork fetching independently.
|
|
||||||
});
|
|
||||||
|
|
||||||
it("shows error alert when playback fails", async () => {
|
|
||||||
const alertSpy = vi.spyOn(window, "alert").mockImplementation(() => {});
|
|
||||||
(invoke as any).mockRejectedValue(new Error("Network error"));
|
(invoke as any).mockRejectedValue(new Error("Network error"));
|
||||||
|
|
||||||
const { container } = render(TrackList, { props: { tracks: mockTracks } });
|
const { container } = render(TrackList, { props: { tracks: mockTracks } });
|
||||||
@@ -309,16 +303,19 @@ describe.skip("TrackList", () => {
|
|||||||
await fireEvent.click(firstTrackButton!);
|
await fireEvent.click(firstTrackButton!);
|
||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
expect(alertSpy).toHaveBeenCalledWith(
|
expect(toastSpy).toHaveBeenCalledWith(
|
||||||
expect.stringContaining("Failed to play track")
|
expect.stringContaining("Failed to play track"),
|
||||||
|
expect.anything()
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
alertSpy.mockRestore();
|
toastSpy.mockRestore();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("handles auth errors gracefully", async () => {
|
it("handles auth errors gracefully", async () => {
|
||||||
const alertSpy = vi.spyOn(window, "alert").mockImplementation(() => {});
|
const toastSpy = vi.spyOn(toast, "error").mockImplementation(() => "");
|
||||||
|
// No repository → requireHandle() throws "No repository available",
|
||||||
|
// which the default handler surfaces via toast.error.
|
||||||
(auth.getRepository as any).mockReturnValue(null as any);
|
(auth.getRepository as any).mockReturnValue(null as any);
|
||||||
|
|
||||||
const { container } = render(TrackList, { props: { tracks: mockTracks } });
|
const { container } = render(TrackList, { props: { tracks: mockTracks } });
|
||||||
@@ -331,22 +328,18 @@ describe.skip("TrackList", () => {
|
|||||||
await fireEvent.click(firstTrackButton!);
|
await fireEvent.click(firstTrackButton!);
|
||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
expect(alertSpy).toHaveBeenCalledWith(
|
expect(toastSpy).toHaveBeenCalledWith(
|
||||||
expect.stringContaining("Not authenticated")
|
expect.stringContaining("Failed to play track"),
|
||||||
|
expect.anything()
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
alertSpy.mockRestore();
|
toastSpy.mockRestore();
|
||||||
|
|
||||||
// Restore mock for other tests
|
// Restore mock for other tests
|
||||||
(auth.getRepository as any).mockReturnValue(mockRepository as any);
|
(auth.getRepository as any).mockReturnValue(mockRepository as any);
|
||||||
});
|
});
|
||||||
|
|
||||||
it.skip("handles stream URL generation errors", async () => {
|
|
||||||
// NOTE: This test is skipped because stream URLs are no longer fetched by frontend.
|
|
||||||
// The code now uses player_play_tracks which sends trackIds to backend.
|
|
||||||
// Backend handles all stream URL generation, so this error path no longer exists.
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("Custom Callback Tests", () => {
|
describe("Custom Callback Tests", () => {
|
||||||
|
|||||||
@@ -16,6 +16,7 @@
|
|||||||
import { writable, type Writable } from "svelte/store";
|
import { writable, type Writable } from "svelte/store";
|
||||||
import { commands } from "$lib/api/bindings";
|
import { commands } from "$lib/api/bindings";
|
||||||
import { auth } from "$lib/stores/auth";
|
import { auth } from "$lib/stores/auth";
|
||||||
|
import { isConnected } from "$lib/stores/connectivity";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* When true (and offline), library grids reveal greyed-out versions of media
|
* When true (and offline), library grids reveal greyed-out versions of media
|
||||||
@@ -24,6 +25,32 @@ import { auth } from "$lib/stores/auth";
|
|||||||
*/
|
*/
|
||||||
export const showServerCatalog: Writable<boolean> = writable(false);
|
export const showServerCatalog: Writable<boolean> = writable(false);
|
||||||
|
|
||||||
|
// Keep the backend's offline library queries in sync with the UI toggle. The
|
||||||
|
// offline cache holds the whole synced catalog, so `get_items` would otherwise
|
||||||
|
// return every server item even offline with the toggle off. Include the
|
||||||
|
// non-downloaded catalog only when online (fast browsing reads the same cache)
|
||||||
|
// or when the "Show all server media" toggle is on.
|
||||||
|
let lastIncludeCatalog: boolean | null = null;
|
||||||
|
function pushCatalogVisibility(connected: boolean, showCatalog: boolean): void {
|
||||||
|
const include = connected || showCatalog;
|
||||||
|
if (include === lastIncludeCatalog) return;
|
||||||
|
lastIncludeCatalog = include;
|
||||||
|
commands.setShowServerCatalog(include).catch((err) => {
|
||||||
|
console.warn("[OfflineCatalog] Failed to set catalog visibility:", err);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let connectedNow = true;
|
||||||
|
let showCatalogNow = false;
|
||||||
|
isConnected.subscribe((v) => {
|
||||||
|
connectedNow = v;
|
||||||
|
pushCatalogVisibility(connectedNow, showCatalogNow);
|
||||||
|
});
|
||||||
|
showServerCatalog.subscribe((v) => {
|
||||||
|
showCatalogNow = v;
|
||||||
|
pushCatalogVisibility(connectedNow, showCatalogNow);
|
||||||
|
});
|
||||||
|
|
||||||
/** Last time a full catalog sync completed, for a UI hint. */
|
/** Last time a full catalog sync completed, for a UI hint. */
|
||||||
export const lastCatalogSync: Writable<string | null> = writable(null);
|
export const lastCatalogSync: Writable<string | null> = writable(null);
|
||||||
|
|
||||||
|
|||||||
@@ -9,10 +9,6 @@ export const isAndroid = writable(false);
|
|||||||
// Shuffle/repeat/next/previous state now lives in the event-driven queue store
|
// Shuffle/repeat/next/previous state now lives in the event-driven queue store
|
||||||
// ($lib/stores/queue), the single source of truth.
|
// ($lib/stores/queue), the single source of truth.
|
||||||
export const showSleepTimerModal = writable(false);
|
export const showSleepTimerModal = writable(false);
|
||||||
// Measured height (px) of the fixed bottom UI on Android: BottomNav stacked with
|
|
||||||
// the global mini player. Published by the root layout via ResizeObserver so the
|
|
||||||
// library list can reserve exactly that much bottom padding (no magic rem guesses).
|
|
||||||
export const bottomUiHeight = writable(0);
|
|
||||||
|
|
||||||
// Library-specific state
|
// Library-specific state
|
||||||
export const librarySearchQuery = writable("");
|
export const librarySearchQuery = writable("");
|
||||||
|
|||||||
+50
-36
@@ -139,20 +139,23 @@ function createAuthStore() {
|
|||||||
update((s) => ({ ...s, isLoading: true, error: null }));
|
update((s) => ({ ...s, isLoading: true, error: null }));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Check security status
|
// Check security status — fire-and-forget. It only sets a warning banner,
|
||||||
try {
|
// so it must not sit in front of session restore (and thus first paint).
|
||||||
const securityStatus = await commands.storageGetSecurityStatus();
|
void (async () => {
|
||||||
console.log("[Auth] Security status:", securityStatus);
|
try {
|
||||||
if (!securityStatus.usingKeyring) {
|
const securityStatus = await commands.storageGetSecurityStatus();
|
||||||
update((s) => ({
|
console.log("[Auth] Security status:", securityStatus);
|
||||||
...s,
|
if (!securityStatus.usingKeyring) {
|
||||||
securityWarning:
|
update((s) => ({
|
||||||
"Credentials are stored with reduced security (encrypted file instead of system keyring).",
|
...s,
|
||||||
}));
|
securityWarning:
|
||||||
|
"Credentials are stored with reduced security (encrypted file instead of system keyring).",
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.warn("[Auth] Failed to get security status:", error);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
})();
|
||||||
console.warn("[Auth] Failed to get security status:", error);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Initialize auth manager and get session
|
// Initialize auth manager and get session
|
||||||
console.log("[Auth] Initializing auth manager...");
|
console.log("[Auth] Initializing auth manager...");
|
||||||
@@ -162,24 +165,30 @@ function createAuthStore() {
|
|||||||
if (session) {
|
if (session) {
|
||||||
console.log("[Auth] Restoring session for user:", session.username, "on server:", session.serverUrl);
|
console.log("[Auth] Restoring session for user:", session.username, "on server:", session.serverUrl);
|
||||||
|
|
||||||
// Create RepositoryClient for cache-first access
|
// Create RepositoryClient for cache-first access. This IS required before
|
||||||
|
// we mark authenticated — the first screen (library overview) reads
|
||||||
|
// through it — so keep it awaited.
|
||||||
repository = new RepositoryClient();
|
repository = new RepositoryClient();
|
||||||
await repository.create(session.serverUrl, session.userId, session.accessToken, session.serverId);
|
await repository.create(session.serverUrl, session.userId, session.accessToken, session.serverId);
|
||||||
|
|
||||||
// Configure Jellyfin client in Rust player for automatic playback reporting
|
// Configure the Rust player for playback reporting. This is NOT needed to
|
||||||
const deviceId = await getDeviceId();
|
// render the first screen (it only matters once playback starts), so run
|
||||||
try {
|
// it fire-and-forget instead of blocking first paint on two more IPC
|
||||||
console.log("[Auth] Configuring Rust player with restored session...");
|
// round-trips (getDeviceId + playerConfigureJellyfin).
|
||||||
await commands.playerConfigureJellyfin(
|
void (async () => {
|
||||||
session.serverUrl,
|
try {
|
||||||
session.accessToken,
|
const deviceId = await getDeviceId();
|
||||||
session.userId,
|
await commands.playerConfigureJellyfin(
|
||||||
deviceId
|
session.serverUrl,
|
||||||
);
|
session.accessToken,
|
||||||
console.log("[Auth] Rust player configured for automatic playback reporting");
|
session.userId,
|
||||||
} catch (error) {
|
deviceId
|
||||||
console.error("[Auth] Failed to configure Rust player:", error);
|
);
|
||||||
}
|
console.log("[Auth] Rust player configured for automatic playback reporting");
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[Auth] Failed to configure Rust player:", error);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
// Set authenticated immediately (offline-first)
|
// Set authenticated immediately (offline-first)
|
||||||
set({
|
set({
|
||||||
@@ -211,14 +220,19 @@ function createAuthStore() {
|
|||||||
console.error("[Auth] Failed to start connectivity monitoring:", error);
|
console.error("[Auth] Failed to start connectivity monitoring:", error);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Start background session verification
|
// Start background session verification — fire-and-forget. This is
|
||||||
try {
|
// already asynchronous work (results arrive via the auth:* events wired
|
||||||
const verifyDeviceId = await getDeviceId();
|
// above), so awaiting getDeviceId + authStartVerification here only
|
||||||
await commands.authStartVerification(verifyDeviceId);
|
// delayed first paint by two IPC round-trips for no UI benefit.
|
||||||
console.log("[Auth] Background verification started");
|
void (async () => {
|
||||||
} catch (error) {
|
try {
|
||||||
console.error("[Auth] Failed to start verification:", error);
|
const verifyDeviceId = await getDeviceId();
|
||||||
}
|
await commands.authStartVerification(verifyDeviceId);
|
||||||
|
console.log("[Auth] Background verification started");
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[Auth] Failed to start verification:", error);
|
||||||
|
}
|
||||||
|
})();
|
||||||
} else {
|
} else {
|
||||||
// No stored session
|
// No stored session
|
||||||
console.log("[Auth] No active session found");
|
console.log("[Auth] No active session found");
|
||||||
|
|||||||
@@ -26,6 +26,18 @@ vi.mock("./sessions", () => ({
|
|||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
// Capture the playerStatusEvent listener so tests can drive backend
|
||||||
|
// `playback_mode_changed` events through the reconciler. The commands still flow
|
||||||
|
// to the real bindings (which call the mocked `invoke`), so the existing
|
||||||
|
// refresh/transfer tests keep exercising the true command path.
|
||||||
|
let capturedStatusListener: ((event: { payload: any }) => void) | null = null;
|
||||||
|
vi.mock("@tauri-apps/api/event", () => ({
|
||||||
|
listen: vi.fn((_name: string, cb: (event: { payload: any }) => void) => {
|
||||||
|
capturedStatusListener = cb;
|
||||||
|
return Promise.resolve(() => {});
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
// Mock auth store
|
// Mock auth store
|
||||||
const mockGetHandle = vi.fn(() => "repo-handle-1");
|
const mockGetHandle = vi.fn(() => "repo-handle-1");
|
||||||
vi.mock("./auth", () => ({
|
vi.mock("./auth", () => ({
|
||||||
@@ -42,6 +54,7 @@ describe("playbackMode store", () => {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
currentSelectedSession = null;
|
currentSelectedSession = null;
|
||||||
|
capturedStatusListener = null;
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -295,6 +308,118 @@ describe("playbackMode store", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("refresh (reconcile to Rust authoritative mode)", () => {
|
||||||
|
it("adopts the Rust mode and aligns the selected session", async () => {
|
||||||
|
const { playbackMode } = await import("./playbackMode");
|
||||||
|
|
||||||
|
// Start disagreeing with Rust: store thinks local, Rust says remote.
|
||||||
|
playbackMode.setMode("local");
|
||||||
|
mockInvoke.mockResolvedValueOnce({ type: "remote", session_id: "sess-xyz" });
|
||||||
|
|
||||||
|
await playbackMode.refresh();
|
||||||
|
|
||||||
|
const state = get(playbackMode);
|
||||||
|
expect(state.mode).toBe("remote");
|
||||||
|
expect(state.remoteSessionId).toBe("sess-xyz");
|
||||||
|
// The merged UI stores follow selectedSession, so it must be aligned too.
|
||||||
|
expect(mockSelectSession).toHaveBeenCalledWith("sess-xyz");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clears the selected session when Rust reports non-remote", async () => {
|
||||||
|
const { playbackMode } = await import("./playbackMode");
|
||||||
|
|
||||||
|
playbackMode.setMode("remote", "sess-old");
|
||||||
|
mockInvoke.mockResolvedValueOnce({ type: "idle" });
|
||||||
|
|
||||||
|
await playbackMode.refresh();
|
||||||
|
|
||||||
|
const state = get(playbackMode);
|
||||||
|
expect(state.mode).toBe("idle");
|
||||||
|
expect(state.remoteSessionId).toBeNull();
|
||||||
|
expect(mockSelectSession).toHaveBeenCalledWith(null);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("backend playback_mode_changed reconciler", () => {
|
||||||
|
// Regression: commit 2a1f168 made Rust re-broadcast PlaybackModeChanged on
|
||||||
|
// every set_mode. Local playback drives set_mode("local") from both the
|
||||||
|
// frontend and Rust, so the same mode arrives repeatedly. The reconciler
|
||||||
|
// used to run selectSession(null) on each one, deselecting the remote
|
||||||
|
// session mid-cast and tripping the disconnect watchdog — which broke the
|
||||||
|
// lockscreen card, remote volume, and (via the mode flap) local audio.
|
||||||
|
async function initListener() {
|
||||||
|
const { playbackMode } = await import("./playbackMode");
|
||||||
|
playbackMode.initializeSessionMonitoring();
|
||||||
|
expect(capturedStatusListener).not.toBeNull();
|
||||||
|
return playbackMode;
|
||||||
|
}
|
||||||
|
|
||||||
|
it("ignores a no-op remote re-broadcast (no session churn)", async () => {
|
||||||
|
currentSelectedSession = { id: "sess-1" };
|
||||||
|
const playbackMode = await initListener();
|
||||||
|
playbackMode.setMode("remote", "sess-1");
|
||||||
|
mockSelectSession.mockClear();
|
||||||
|
|
||||||
|
// Rust re-broadcasts the SAME remote mode (e.g. a position tick path).
|
||||||
|
capturedStatusListener!({
|
||||||
|
payload: { type: "playback_mode_changed", mode: "remote", session_id: "sess-1" },
|
||||||
|
});
|
||||||
|
|
||||||
|
const state = get(playbackMode);
|
||||||
|
expect(state.mode).toBe("remote");
|
||||||
|
expect(state.remoteSessionId).toBe("sess-1");
|
||||||
|
// Must NOT re-select (which would churn the watchdog) on a no-op.
|
||||||
|
expect(mockSelectSession).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("adopts a genuine remote→local change and clears the session", async () => {
|
||||||
|
currentSelectedSession = { id: "sess-1" };
|
||||||
|
const playbackMode = await initListener();
|
||||||
|
playbackMode.setMode("remote", "sess-1");
|
||||||
|
mockSelectSession.mockClear();
|
||||||
|
|
||||||
|
capturedStatusListener!({
|
||||||
|
payload: { type: "playback_mode_changed", mode: "local", session_id: null },
|
||||||
|
});
|
||||||
|
|
||||||
|
const state = get(playbackMode);
|
||||||
|
expect(state.mode).toBe("local");
|
||||||
|
expect(state.remoteSessionId).toBeNull();
|
||||||
|
expect(mockSelectSession).toHaveBeenCalledWith(null);
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("transfer reconciles to Rust on completion", () => {
|
||||||
|
it("refreshes from Rust after a successful transferToRemote", async () => {
|
||||||
|
const { playbackMode } = await import("./playbackMode");
|
||||||
|
|
||||||
|
// First call: the transfer command; second call: the finally refresh.
|
||||||
|
mockInvoke.mockResolvedValueOnce(undefined);
|
||||||
|
mockInvoke.mockResolvedValueOnce({ type: "remote", session_id: "session-456" });
|
||||||
|
|
||||||
|
await playbackMode.transferToRemote("session-456");
|
||||||
|
|
||||||
|
expect(mockInvoke).toHaveBeenCalledWith("playback_mode_get_current");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("still reconciles to Rust when transferToRemote throws mid-transfer", async () => {
|
||||||
|
const { playbackMode } = await import("./playbackMode");
|
||||||
|
|
||||||
|
// Transfer command fails, leaving the optimistic state possibly wrong.
|
||||||
|
mockInvoke.mockRejectedValueOnce(new Error("boom"));
|
||||||
|
// The finally refresh reads the true mode (Rust never left local).
|
||||||
|
mockInvoke.mockResolvedValueOnce({ type: "local" });
|
||||||
|
|
||||||
|
await expect(playbackMode.transferToRemote("session-456")).rejects.toThrow("boom");
|
||||||
|
|
||||||
|
// The reconciling read must have happened despite the throw.
|
||||||
|
expect(mockInvoke).toHaveBeenCalledWith("playback_mode_get_current");
|
||||||
|
const state = get(playbackMode);
|
||||||
|
expect(state.mode).toBe("local");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("clearError", () => {
|
describe("clearError", () => {
|
||||||
it("should clear transfer error", async () => {
|
it("should clear transfer error", async () => {
|
||||||
const { playbackMode } = await import("./playbackMode");
|
const { playbackMode } = await import("./playbackMode");
|
||||||
|
|||||||
@@ -48,12 +48,16 @@ function createPlaybackModeStore() {
|
|||||||
async function refreshMode(): Promise<void> {
|
async function refreshMode(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const rustMode = (await commands.playbackModeGetCurrent()) as RustPlaybackMode;
|
const rustMode = (await commands.playbackModeGetCurrent()) as RustPlaybackMode;
|
||||||
|
const remoteSessionId = rustMode.type === "remote" ? rustMode.session_id || null : null;
|
||||||
|
|
||||||
update((s) => ({
|
update((s) => ({
|
||||||
...s,
|
...s,
|
||||||
mode: rustMode.type,
|
mode: rustMode.type,
|
||||||
remoteSessionId: rustMode.type === "remote" ? rustMode.session_id || null : null,
|
remoteSessionId,
|
||||||
}));
|
}));
|
||||||
|
// Keep the selected session aligned so the merged UI stores follow the
|
||||||
|
// authoritative mode.
|
||||||
|
sessions.selectSession(remoteSessionId);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to get playback mode:", error);
|
console.error("Failed to get playback mode:", error);
|
||||||
}
|
}
|
||||||
@@ -135,6 +139,10 @@ function createPlaybackModeStore() {
|
|||||||
throw error;
|
throw error;
|
||||||
} finally {
|
} finally {
|
||||||
currentTransferAbort = null;
|
currentTransferAbort = null;
|
||||||
|
// Snap back to whatever the Rust manager actually settled on. If any step
|
||||||
|
// above threw mid-transfer, the optimistic update may not match reality;
|
||||||
|
// Rust is authoritative, so reconcile to it.
|
||||||
|
await refreshMode();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -263,6 +271,9 @@ function createPlaybackModeStore() {
|
|||||||
console.warn("[PlaybackMode] Failed to clear transferring flag:", e);
|
console.warn("[PlaybackMode] Failed to clear transferring flag:", e);
|
||||||
}
|
}
|
||||||
currentTransferAbort = null;
|
currentTransferAbort = null;
|
||||||
|
// Reconcile to the authoritative Rust mode in case a step above threw and
|
||||||
|
// left our optimistic state inconsistent (see transferToRemote).
|
||||||
|
await refreshMode();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -288,6 +299,48 @@ function createPlaybackModeStore() {
|
|||||||
console.error("[PlaybackMode] Lockscreen-triggered transfer failed:", e),
|
console.error("[PlaybackMode] Lockscreen-triggered transfer failed:", e),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The Rust PlaybackModeManager is the single source of truth for routing.
|
||||||
|
// Reconcile our mirror store to it whenever it changes, so the UI and the
|
||||||
|
// event filter in playerEvents.ts can't drift and start routing controls to
|
||||||
|
// the wrong device. We deliberately do NOT reconcile while a transfer is in
|
||||||
|
// flight: transfers emit intermediate mode changes (and briefly hold the
|
||||||
|
// transferring flag), and the transfer functions own the final state.
|
||||||
|
if (event.payload.type === "playback_mode_changed") {
|
||||||
|
const currentState = get({ subscribe });
|
||||||
|
if (currentState.isTransferring) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const mode = event.payload.mode as PlaybackMode;
|
||||||
|
const remoteSessionId =
|
||||||
|
mode === "remote" ? event.payload.session_id ?? null : null;
|
||||||
|
|
||||||
|
// Ignore no-op re-broadcasts. The backend re-emits on every set_mode, and
|
||||||
|
// local playback drives set_mode("local") from BOTH the frontend
|
||||||
|
// (handleStateChanged) and Rust, so the same mode arrives repeatedly. If
|
||||||
|
// we reconciled unconditionally we'd re-run selectSession(null) on each
|
||||||
|
// one, deselecting the remote session mid-cast and tripping the
|
||||||
|
// disconnect-to-idle watchdog (breaking the lockscreen card, remote
|
||||||
|
// volume, and — via the resulting mode flap — local audio).
|
||||||
|
if (
|
||||||
|
currentState.mode === mode &&
|
||||||
|
currentState.remoteSessionId === remoteSessionId
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("[PlaybackMode] Backend mode changed →", mode, remoteSessionId);
|
||||||
|
update((s) => ({ ...s, mode, remoteSessionId }));
|
||||||
|
// Keep the selected session in step so the merged UI stores follow, but
|
||||||
|
// only touch the selection when it actually differs — re-selecting the
|
||||||
|
// same id (or clearing on a non-remote emit that isn't a real change)
|
||||||
|
// would needlessly churn the session watchdog.
|
||||||
|
const selected = get(selectedSession);
|
||||||
|
if ((selected?.id ?? null) !== remoteSessionId) {
|
||||||
|
sessions.selectSession(remoteSessionId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
/**
|
||||||
|
* Tests for the app's bottom-UI (mini player + bottom nav) visibility rules.
|
||||||
|
*
|
||||||
|
* The overlap bug these guard against: on the library page the last rows were
|
||||||
|
* hidden behind the bottom nav. It was caused by rendering the bottom UI as a
|
||||||
|
* FIXED overlay and trying to reserve its (async-measured, initially-0) height
|
||||||
|
* as padding. The fix renders the bottom UI as an in-flow flex child below the
|
||||||
|
* scroller, so overlap is structurally impossible — no measurement, no padding.
|
||||||
|
*
|
||||||
|
* These pure functions only decide *whether* each piece shows on a route. The
|
||||||
|
* structural guarantee (flex sibling below the scroller) is exercised by
|
||||||
|
* running the app, not by jsdom (which has no layout engine).
|
||||||
|
*
|
||||||
|
* TRACES: UR-005 | DR-009
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import {
|
||||||
|
showBottomNav,
|
||||||
|
showGlobalMiniPlayer,
|
||||||
|
routeOwnsLayout,
|
||||||
|
showBottomUi,
|
||||||
|
} from "./layoutShell";
|
||||||
|
|
||||||
|
const authed = (pathname: string) => ({ pathname, isAuthenticated: true });
|
||||||
|
|
||||||
|
describe("showGlobalMiniPlayer", () => {
|
||||||
|
it("shows on the main library page (regression: was hidden on non-Android)", () => {
|
||||||
|
expect(showGlobalMiniPlayer({ pathname: "/library" })).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows on a deep library page", () => {
|
||||||
|
expect(showGlobalMiniPlayer({ pathname: "/library/abc123" })).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows on home, search, downloads", () => {
|
||||||
|
expect(showGlobalMiniPlayer({ pathname: "/" })).toBe(true);
|
||||||
|
expect(showGlobalMiniPlayer({ pathname: "/search" })).toBe(true);
|
||||||
|
expect(showGlobalMiniPlayer({ pathname: "/downloads" })).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("hides on the full-screen player, login, and settings", () => {
|
||||||
|
expect(showGlobalMiniPlayer({ pathname: "/player/xyz" })).toBe(false);
|
||||||
|
expect(showGlobalMiniPlayer({ pathname: "/login" })).toBe(false);
|
||||||
|
expect(showGlobalMiniPlayer({ pathname: "/settings" })).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does NOT depend on platform or on /library — one code path everywhere", () => {
|
||||||
|
// The old bug was a platform/route split that let a second mini player exist.
|
||||||
|
expect(showGlobalMiniPlayer({ pathname: "/library" })).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("showBottomNav", () => {
|
||||||
|
it("shows on authenticated content routes including library and settings", () => {
|
||||||
|
expect(showBottomNav(authed("/library"))).toBe(true);
|
||||||
|
expect(showBottomNav(authed("/"))).toBe(true);
|
||||||
|
expect(showBottomNav(authed("/settings"))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("hides when unauthenticated", () => {
|
||||||
|
expect(showBottomNav({ pathname: "/library", isAuthenticated: false })).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("hides on the full-screen player and login", () => {
|
||||||
|
expect(showBottomNav(authed("/player/xyz"))).toBe(false);
|
||||||
|
expect(showBottomNav(authed("/login"))).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("routeOwnsLayout", () => {
|
||||||
|
it("is true for library/player/login (they render their own flex column + BottomUi)", () => {
|
||||||
|
expect(routeOwnsLayout({ pathname: "/library" })).toBe(true);
|
||||||
|
expect(routeOwnsLayout({ pathname: "/library/abc" })).toBe(true);
|
||||||
|
expect(routeOwnsLayout({ pathname: "/player/x" })).toBe(true);
|
||||||
|
expect(routeOwnsLayout({ pathname: "/login" })).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is false for routes that render into the root scroller (incl. settings)", () => {
|
||||||
|
// Settings has no +layout of its own; it must flow through the root scroller
|
||||||
|
// so the root's in-flow BottomUi renders below it (otherwise settings loses
|
||||||
|
// its nav, since the fixed-overlay nav no longer exists).
|
||||||
|
expect(routeOwnsLayout({ pathname: "/" })).toBe(false);
|
||||||
|
expect(routeOwnsLayout({ pathname: "/search" })).toBe(false);
|
||||||
|
expect(routeOwnsLayout({ pathname: "/downloads" })).toBe(false);
|
||||||
|
expect(routeOwnsLayout({ pathname: "/settings" })).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("structural invariant: every route that shows bottom UI has a scroller above it", () => {
|
||||||
|
// With the in-flow model, "the bottom UI is a flex sibling below a scroller"
|
||||||
|
// must hold on every route where it shows. That scroller is provided by
|
||||||
|
// exactly one owner:
|
||||||
|
// - routeOwnsLayout === true -> the route's own column (header + main + BottomUi)
|
||||||
|
// - routeOwnsLayout === false -> the root column (scroller + BottomUi)
|
||||||
|
// The forbidden state — bottom UI shows but no owning column renders a
|
||||||
|
// scroller + BottomUi pair — cannot occur because the two branches are total.
|
||||||
|
const routes = ["/", "/search", "/downloads", "/library", "/library/abc", "/settings"];
|
||||||
|
|
||||||
|
for (const pathname of routes) {
|
||||||
|
it(`${pathname}: bottom UI shows and has a defined layout owner`, () => {
|
||||||
|
expect(showBottomUi(authed(pathname))).toBe(true);
|
||||||
|
expect(typeof routeOwnsLayout({ pathname })).toBe("boolean");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
it("library owns its layout, so it renders its own in-flow BottomUi", () => {
|
||||||
|
// Directly pins the original regression: library must render BottomUi inside
|
||||||
|
// its own column (the root gives owning routes a clipped, non-scrolling box).
|
||||||
|
expect(showBottomUi(authed("/library"))).toBe(true);
|
||||||
|
expect(routeOwnsLayout({ pathname: "/library" })).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("settings does NOT own its layout, so the root scroller + BottomUi cover it", () => {
|
||||||
|
expect(showBottomUi(authed("/settings"))).toBe(true);
|
||||||
|
expect(routeOwnsLayout({ pathname: "/settings" })).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("the full-screen player shows no bottom UI and owns its layout", () => {
|
||||||
|
expect(showBottomUi(authed("/player/x"))).toBe(false);
|
||||||
|
expect(routeOwnsLayout({ pathname: "/player/x" })).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
/**
|
||||||
|
* Pure layout-shell visibility rules for the app's bottom UI (mini player
|
||||||
|
* stacked over the bottom nav).
|
||||||
|
*
|
||||||
|
* These rules used to live as inline `$derived` booleans scattered across the
|
||||||
|
* root and library `+layout.svelte` files and diverged per platform/route.
|
||||||
|
*
|
||||||
|
* The overlap bug ("last row hidden behind the nav") is now solved
|
||||||
|
* STRUCTURALLY, not by these rules: the bottom UI is rendered as an in-flow
|
||||||
|
* flex child below the scroller (see BottomUi.svelte), so the scroller is
|
||||||
|
* physically bounded above it and can never render behind it. There is no
|
||||||
|
* measurement and no reserved padding. These functions only decide *whether*
|
||||||
|
* each piece is visible on a given route.
|
||||||
|
*
|
||||||
|
* Keeping them pure makes the visibility contract unit-testable.
|
||||||
|
*
|
||||||
|
* TRACES: UR-005 | DR-009
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface BottomUiVisibilityInput {
|
||||||
|
/** Current route pathname, e.g. `$page.url.pathname`. */
|
||||||
|
pathname: string;
|
||||||
|
/** Whether the user is authenticated. */
|
||||||
|
isAuthenticated: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The bottom nav is shown on every authenticated route except the full-screen
|
||||||
|
* player and the login route.
|
||||||
|
*/
|
||||||
|
export function showBottomNav({
|
||||||
|
pathname,
|
||||||
|
isAuthenticated,
|
||||||
|
}: BottomUiVisibilityInput): boolean {
|
||||||
|
return (
|
||||||
|
isAuthenticated &&
|
||||||
|
!pathname.startsWith("/player/") &&
|
||||||
|
!pathname.startsWith("/login")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The global (root-owned) mini player is shown on every route except the
|
||||||
|
* full-screen player, login, and settings. Crucially this is NOT gated on
|
||||||
|
* platform or on `/library` — the root owns the mini player everywhere, so the
|
||||||
|
* library route must never render its own second one.
|
||||||
|
*/
|
||||||
|
export function showGlobalMiniPlayer({ pathname }: { pathname: string }): boolean {
|
||||||
|
return (
|
||||||
|
!pathname.startsWith("/player/") &&
|
||||||
|
!pathname.startsWith("/login") &&
|
||||||
|
!pathname.startsWith("/settings")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Routes that render their own full-height flex column (header + scroller +
|
||||||
|
* their own in-flow BottomUi). The root leaves these as a plain clipped box and
|
||||||
|
* does not render its own BottomUi. Every other route renders into the root's
|
||||||
|
* scroller, with the root's in-flow BottomUi as a flex sibling below it.
|
||||||
|
*/
|
||||||
|
export function routeOwnsLayout({ pathname }: { pathname: string }): boolean {
|
||||||
|
return (
|
||||||
|
pathname.startsWith("/library") ||
|
||||||
|
pathname.startsWith("/player/") ||
|
||||||
|
pathname.startsWith("/login")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether any bottom UI is showing for this route (mini player, nav, or both).
|
||||||
|
* The bottom UI is rendered in flex flow below the scroller (see BottomUi.svelte),
|
||||||
|
* so this is purely a visibility question — there is no padding to reserve.
|
||||||
|
*/
|
||||||
|
export function showBottomUi(input: BottomUiVisibilityInput): boolean {
|
||||||
|
return showBottomNav(input) || showGlobalMiniPlayer({ pathname: input.pathname });
|
||||||
|
}
|
||||||
@@ -1,35 +1,95 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
import { navigateBack } from "./navigation";
|
|
||||||
|
|
||||||
const goto = vi.fn();
|
const goto = vi.fn();
|
||||||
|
// Capture the afterNavigate callback so tests can simulate navigations and thus
|
||||||
|
// drive the in-app depth counter that canGoBack/navigateBack rely on.
|
||||||
|
let afterNavigateCb: ((nav: { from: unknown; to: unknown; delta?: number }) => void) | null =
|
||||||
|
null;
|
||||||
vi.mock("$app/navigation", () => ({
|
vi.mock("$app/navigation", () => ({
|
||||||
goto: (...args: unknown[]) => goto(...args),
|
goto: (...args: unknown[]) => goto(...args),
|
||||||
|
afterNavigate: (cb: (nav: any) => void) => {
|
||||||
|
afterNavigateCb = cb;
|
||||||
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
describe("navigateBack", () => {
|
import {
|
||||||
|
navigateUp,
|
||||||
|
navigateBack,
|
||||||
|
canGoBack,
|
||||||
|
registerNavigationTracking,
|
||||||
|
__resetNavigationDepthForTest,
|
||||||
|
} from "./navigation";
|
||||||
|
|
||||||
|
/** Simulate a SvelteKit navigation to move the depth counter. */
|
||||||
|
function nav(opts: { from?: boolean; delta?: number }) {
|
||||||
|
afterNavigateCb?.({
|
||||||
|
from: opts.from === false ? null : {},
|
||||||
|
to: {},
|
||||||
|
delta: opts.delta,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("navigation", () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
goto.mockClear();
|
goto.mockClear();
|
||||||
|
// registerNavigationTracking is idempotent; the first call in the suite wins
|
||||||
|
// and wires afterNavigateCb. Ensure it is registered, then reset depth so
|
||||||
|
// each case starts from the entry page (module state persists otherwise).
|
||||||
|
registerNavigationTracking();
|
||||||
|
__resetNavigationDepthForTest();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("pops real history when there is in-app history to go back to", () => {
|
describe("navigateUp", () => {
|
||||||
const back = vi.fn();
|
it("always goes to the given parent path, never touching history", () => {
|
||||||
vi.spyOn(history, "back").mockImplementation(back);
|
const back = vi.fn();
|
||||||
vi.spyOn(history, "length", "get").mockReturnValue(3);
|
vi.spyOn(history, "back").mockImplementation(back);
|
||||||
|
|
||||||
navigateBack("/library");
|
navigateUp("/library/music");
|
||||||
|
|
||||||
expect(back).toHaveBeenCalledOnce();
|
expect(goto).toHaveBeenCalledWith("/library/music");
|
||||||
expect(goto).not.toHaveBeenCalled();
|
expect(back).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("falls back to the given path on a fresh deep-link (no history)", () => {
|
describe("navigateBack / canGoBack", () => {
|
||||||
const back = vi.fn();
|
it("falls back to the path when there is no in-app history yet", () => {
|
||||||
vi.spyOn(history, "back").mockImplementation(back);
|
// Fresh session: only the initial load happened (from == null), so depth
|
||||||
vi.spyOn(history, "length", "get").mockReturnValue(1);
|
// stays at 0 and there is nothing to pop.
|
||||||
|
nav({ from: false });
|
||||||
|
expect(canGoBack()).toBe(false);
|
||||||
|
|
||||||
navigateBack("/library/music");
|
const back = vi.fn();
|
||||||
|
vi.spyOn(history, "back").mockImplementation(back);
|
||||||
|
|
||||||
expect(goto).toHaveBeenCalledWith("/library/music");
|
navigateBack("/library");
|
||||||
expect(back).not.toHaveBeenCalled();
|
|
||||||
|
expect(goto).toHaveBeenCalledWith("/library");
|
||||||
|
expect(back).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("pops history after a real in-app forward navigation", () => {
|
||||||
|
nav({ from: false }); // initial load
|
||||||
|
nav({}); // navigated deeper within the app
|
||||||
|
expect(canGoBack()).toBe(true);
|
||||||
|
|
||||||
|
const back = vi.fn();
|
||||||
|
vi.spyOn(history, "back").mockImplementation(back);
|
||||||
|
|
||||||
|
navigateBack("/library");
|
||||||
|
|
||||||
|
expect(back).toHaveBeenCalledOnce();
|
||||||
|
expect(goto).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not go below zero when the user backs out to the entry page", () => {
|
||||||
|
nav({ from: false }); // load
|
||||||
|
nav({}); // forward → depth 1
|
||||||
|
nav({ delta: -1 }); // back → depth 0
|
||||||
|
nav({ delta: -1 }); // extra back (e.g. stale delta) must not underflow
|
||||||
|
expect(canGoBack()).toBe(false);
|
||||||
|
|
||||||
|
navigateBack("/library/music");
|
||||||
|
expect(goto).toHaveBeenCalledWith("/library/music");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+83
-21
@@ -1,18 +1,90 @@
|
|||||||
import { goto } from "$app/navigation";
|
import { goto, afterNavigate } from "$app/navigation";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Navigate "back" using real browser/Android history when possible, falling
|
* App navigation has two distinct affordances (per the Android guidelines):
|
||||||
* back to an explicit path otherwise.
|
|
||||||
*
|
*
|
||||||
* Hardcoded `goto(backPath)` always sends the user to a fixed screen, which
|
* - **Up** — move to the current screen's *logical parent* in the app
|
||||||
* loses track of where they actually came from (e.g. reaching the genres list
|
* hierarchy (e.g. `/library/music/albums` → `/library/music`). Deterministic,
|
||||||
* from different entry points). Preferring `history.back()` keeps the back
|
* derived from the route, and never depends on how the user got here. This is
|
||||||
* affordance consistent with the platform back gesture and the browser/Android
|
* what the in-app header arrows should do almost everywhere.
|
||||||
* hardware back button.
|
|
||||||
*
|
*
|
||||||
* We only use history when there is somewhere to go back to *within the app*.
|
* - **Back** — pop the *actual* history stack: return to wherever the user came
|
||||||
* On a fresh deep-link (history length 1, or an external referrer) we fall back
|
* from, which may be a sibling branch (a detail page reached from search vs.
|
||||||
* to `fallbackPath` so the user never gets stranded or bounced out of the app.
|
* from the library) or even outside the app. This is the hardware/gesture
|
||||||
|
* back button's job; use it in-app only where "return to origin" is genuinely
|
||||||
|
* better than Up (e.g. a detail page with many entry points).
|
||||||
|
*
|
||||||
|
* The old single `navigateBack` conflated the two: it called `history.back()`
|
||||||
|
* first and only fell back to a path. On resume-from-background the WebView can
|
||||||
|
* restore a history stack whose `length` is still > 1 but which cannot actually
|
||||||
|
* go back within the app — so `history.back()` no-ops and the user is trapped on
|
||||||
|
* the page. Splitting Up (pure `goto`) from Back (tracked in-app depth) removes
|
||||||
|
* that trap: Up can never get stuck, and Back only fires when we *know* there is
|
||||||
|
* an in-app entry to return to.
|
||||||
|
*/
|
||||||
|
|
||||||
|
// In-app navigation depth, maintained via the public `afterNavigate` hook rather
|
||||||
|
// than reading SvelteKit's internal history-state key. Starts at 0 (the entry
|
||||||
|
// page). Each forward in-app navigation increments it; a popstate (back/forward
|
||||||
|
// gesture) sets it to the delta-adjusted value. When it is > 0 we know a real
|
||||||
|
// in-app Back exists and won't strand the user — independent of the WebView's
|
||||||
|
// possibly-stale `history.length` after a background/restore.
|
||||||
|
let inAppDepth = 0;
|
||||||
|
let navHookRegistered = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register the navigation-depth tracker. Call once from the root layout's
|
||||||
|
* component init (afterNavigate must run in a component context). Safe to call
|
||||||
|
* more than once — only the first registration takes effect.
|
||||||
|
*/
|
||||||
|
export function registerNavigationTracking(): void {
|
||||||
|
if (navHookRegistered) return;
|
||||||
|
navHookRegistered = true;
|
||||||
|
|
||||||
|
afterNavigate((nav) => {
|
||||||
|
// A popstate (hardware/gesture back or forward) carries a delta; apply it so
|
||||||
|
// depth tracks the true stack position. Programmatic goto/link navigations
|
||||||
|
// have no delta and move one step deeper.
|
||||||
|
const delta = nav.delta;
|
||||||
|
if (typeof delta === "number") {
|
||||||
|
inAppDepth = Math.max(0, inAppDepth + delta);
|
||||||
|
} else if (nav.from) {
|
||||||
|
// A real forward navigation from an existing page (not the initial load).
|
||||||
|
inAppDepth += 1;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reset the tracked depth. Intended for tests only, so each case starts from a
|
||||||
|
* known baseline (module state persists across a test file otherwise).
|
||||||
|
*/
|
||||||
|
export function __resetNavigationDepthForTest(): void {
|
||||||
|
inAppDepth = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when there is at least one in-app history entry to pop. Unlike
|
||||||
|
* `history.length > 1`, this reflects navigations that happened *within this app
|
||||||
|
* session*, so a stale WebView stack after a background/restore can't fool it.
|
||||||
|
*/
|
||||||
|
export function canGoBack(): boolean {
|
||||||
|
return inAppDepth > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* **Up**: go to the given logical parent path. Always deterministic; never
|
||||||
|
* consults history, so it cannot trap the user. Prefer this for header arrows.
|
||||||
|
*/
|
||||||
|
export function navigateUp(parentPath: string): void {
|
||||||
|
goto(parentPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* **Back**: return to the previous in-app page when there is one, otherwise fall
|
||||||
|
* back to `fallbackPath` (typically the logical parent) so the user is never
|
||||||
|
* stranded. Use only where returning to the exact origin is preferable to Up
|
||||||
|
* (e.g. a detail page reachable from multiple branches).
|
||||||
*/
|
*/
|
||||||
export function navigateBack(fallbackPath: string): void {
|
export function navigateBack(fallbackPath: string): void {
|
||||||
if (canGoBack()) {
|
if (canGoBack()) {
|
||||||
@@ -21,13 +93,3 @@ export function navigateBack(fallbackPath: string): void {
|
|||||||
goto(fallbackPath);
|
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;
|
|
||||||
}
|
|
||||||
|
|||||||
+45
-90
@@ -2,7 +2,6 @@
|
|||||||
import { onMount, onDestroy } from "svelte";
|
import { onMount, onDestroy } from "svelte";
|
||||||
import { get } from "svelte/store";
|
import { get } from "svelte/store";
|
||||||
import { page } from "$app/stores";
|
import { page } from "$app/stores";
|
||||||
import { goto } from "$app/navigation";
|
|
||||||
import { platform } from "@tauri-apps/plugin-os";
|
import { platform } from "@tauri-apps/plugin-os";
|
||||||
import "../app.css";
|
import "../app.css";
|
||||||
import { auth, needsReauth, isAuthenticated } from "$lib/stores/auth";
|
import { auth, needsReauth, isAuthenticated } from "$lib/stores/auth";
|
||||||
@@ -13,68 +12,46 @@
|
|||||||
import { onReconnected as onCatalogReconnected, syncCatalog, refreshSyncStatus, showServerCatalog, lastCatalogSync } from "$lib/services/offlineCatalog";
|
import { onReconnected as onCatalogReconnected, syncCatalog, refreshSyncStatus, showServerCatalog, lastCatalogSync } from "$lib/services/offlineCatalog";
|
||||||
import { playbackMode } from "$lib/stores/playbackMode";
|
import { playbackMode } from "$lib/stores/playbackMode";
|
||||||
import { sessions } from "$lib/stores/sessions";
|
import { sessions } from "$lib/stores/sessions";
|
||||||
import { currentMedia, isPlaying, playbackPosition, playbackDuration } from "$lib/stores/player";
|
|
||||||
import ReauthModal from "$lib/components/auth/ReauthModal.svelte";
|
import ReauthModal from "$lib/components/auth/ReauthModal.svelte";
|
||||||
import Toast from "$lib/components/Toast.svelte";
|
import Toast from "$lib/components/Toast.svelte";
|
||||||
import MiniPlayer from "$lib/components/player/MiniPlayer.svelte";
|
|
||||||
import SleepTimerModal from "$lib/components/player/SleepTimerModal.svelte";
|
import SleepTimerModal from "$lib/components/player/SleepTimerModal.svelte";
|
||||||
import BottomNav from "$lib/components/BottomNav.svelte";
|
import BottomUi from "$lib/components/BottomUi.svelte";
|
||||||
import { isInitialized, pendingSyncCount, isAndroid, showSleepTimerModal, bottomUiHeight } from "$lib/stores/appState";
|
import { isInitialized, pendingSyncCount, isAndroid, showSleepTimerModal } from "$lib/stores/appState";
|
||||||
// Shuffle/repeat/next/previous come from the event-driven queue store, the
|
import {
|
||||||
// single source of truth (updated instantly on queue_changed).
|
showBottomNav as computeShowBottomNav,
|
||||||
import { isShuffle as shuffle, repeatMode as repeat, hasNext, hasPrevious } from "$lib/stores/queue";
|
showGlobalMiniPlayer as computeShowGlobalMiniPlayer,
|
||||||
|
routeOwnsLayout as computeRouteOwnsLayout,
|
||||||
|
} from "$lib/utils/layoutShell";
|
||||||
|
import { registerNavigationTracking } from "$lib/utils/navigation";
|
||||||
|
|
||||||
let { children } = $props();
|
let { children } = $props();
|
||||||
|
|
||||||
// The fixed bottom UI (mini player stacked over the bottom nav) is measured in
|
// Track in-app navigation depth so the header "back" affordance knows when a
|
||||||
// real time and its height published to `bottomUiHeight`, so pages can reserve
|
// real in-app Back exists (vs. a stale WebView stack after a background /
|
||||||
// exactly that much space instead of guessing fixed rem values.
|
// restore). Must run during component init — afterNavigate needs a component
|
||||||
let bottomUiEl = $state<HTMLElement | null>(null);
|
// context, not the async onMount callback below.
|
||||||
|
registerNavigationTracking();
|
||||||
|
|
||||||
// Route-level visibility for the fixed bottom UI (the mini player itself also
|
// Layout-shell visibility rules live in one pure, unit-tested module
|
||||||
// self-gates on playback state; when it renders nothing the in-flow slot
|
// ($lib/utils/layoutShell) so they can't drift per route/platform.
|
||||||
// collapses to 0 and the ResizeObserver shrinks the reserved padding).
|
//
|
||||||
|
// The bottom UI (mini player + nav) is rendered IN FLEX FLOW below the
|
||||||
|
// scroller — never as a fixed overlay — so the list is physically bounded
|
||||||
|
// above it and cannot render behind it. There is nothing to measure or
|
||||||
|
// reserve; the old ResizeObserver/`bottomUiHeight`/padding scheme (which
|
||||||
|
// started at 0 and kept regressing into "last row hidden behind the nav") is
|
||||||
|
// gone. See BottomUi.svelte.
|
||||||
const pathname = $derived($page.url.pathname);
|
const pathname = $derived($page.url.pathname);
|
||||||
const showBottomNav = $derived(
|
const showBottomNav = $derived(
|
||||||
$isAuthenticated && !pathname.startsWith('/player/') && !pathname.startsWith('/login')
|
computeShowBottomNav({ pathname, isAuthenticated: $isAuthenticated })
|
||||||
);
|
|
||||||
const showGlobalMiniPlayer = $derived(
|
|
||||||
!pathname.startsWith('/player/') &&
|
|
||||||
!pathname.startsWith('/login') &&
|
|
||||||
!pathname.startsWith('/settings') &&
|
|
||||||
($isAndroid || !pathname.startsWith('/library'))
|
|
||||||
);
|
);
|
||||||
|
const showGlobalMiniPlayer = $derived(computeShowGlobalMiniPlayer({ pathname }));
|
||||||
|
|
||||||
// The library and settings routes own their own full-height layout (their own
|
// Library/settings/player/login own their own full-height flex column
|
||||||
// scroll container + bottom-space reservation), so the root must leave their
|
// (header + scroller + their own in-flow BottomUi), so the root just clips
|
||||||
// wrapper as a plain non-scrolling box. Every other top-level page (search,
|
// and lets them manage layout. Every other route renders into the root's
|
||||||
// downloads, sessions, home) renders straight into the root, so the root
|
// scroller, with the root's in-flow BottomUi as a flex sibling below it.
|
||||||
// wrapper has to scroll AND reserve the fixed bottom UI's height — otherwise
|
const routeOwnsLayout = $derived(computeRouteOwnsLayout({ pathname }));
|
||||||
// the mini player / bottom nav overlay the last rows of content.
|
|
||||||
const routeOwnsLayout = $derived(
|
|
||||||
pathname.startsWith('/library') ||
|
|
||||||
pathname.startsWith('/settings') ||
|
|
||||||
pathname.startsWith('/player/') ||
|
|
||||||
pathname.startsWith('/login')
|
|
||||||
);
|
|
||||||
const showBottomUi = $derived(showBottomNav || showGlobalMiniPlayer);
|
|
||||||
|
|
||||||
$effect(() => {
|
|
||||||
const el = bottomUiEl;
|
|
||||||
if (!el) {
|
|
||||||
bottomUiHeight.set(0);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const ro = new ResizeObserver((entries) => {
|
|
||||||
bottomUiHeight.set(entries[0]?.contentRect.height ?? el.offsetHeight);
|
|
||||||
});
|
|
||||||
ro.observe(el);
|
|
||||||
bottomUiHeight.set(el.offsetHeight);
|
|
||||||
return () => {
|
|
||||||
ro.disconnect();
|
|
||||||
bottomUiHeight.set(0);
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
onMount(async () => {
|
onMount(async () => {
|
||||||
// Detect platform first (synchronously, before any await) so the global
|
// Detect platform first (synchronously, before any await) so the global
|
||||||
@@ -206,13 +183,18 @@
|
|||||||
this wrapper must scroll and reserve the fixed bottom UI's measured
|
this wrapper must scroll and reserve the fixed bottom UI's measured
|
||||||
height so the mini player / bottom nav never overlap the last rows. -->
|
height so the mini player / bottom nav never overlap the last rows. -->
|
||||||
{#if routeOwnsLayout}
|
{#if routeOwnsLayout}
|
||||||
|
<!-- These routes own their own full-height flex column (header + scroller
|
||||||
|
+ their own in-flow BottomUi), so the root just clips and steps back. -->
|
||||||
<div class="flex-1 overflow-hidden">
|
<div class="flex-1 overflow-hidden">
|
||||||
{@render children()}
|
{@render children()}
|
||||||
</div>
|
</div>
|
||||||
{:else}
|
{:else}
|
||||||
|
<!-- Scroller is flex-1/min-h-0; the in-flow BottomUi below is a flex
|
||||||
|
sibling, so the list is physically bounded above it and can never
|
||||||
|
render behind it. No measurement, no reserved padding. -->
|
||||||
<div
|
<div
|
||||||
class="flex-1 overflow-y-auto min-h-0"
|
class="flex-1 overflow-y-auto min-h-0"
|
||||||
style="padding-bottom: {showBottomUi ? `${$bottomUiHeight}px` : '0'}; overscroll-behavior: contain"
|
style="overscroll-behavior: contain"
|
||||||
>
|
>
|
||||||
{@render children()}
|
{@render children()}
|
||||||
</div>
|
</div>
|
||||||
@@ -224,44 +206,17 @@
|
|||||||
<!-- Toast notifications (global) -->
|
<!-- Toast notifications (global) -->
|
||||||
<Toast />
|
<Toast />
|
||||||
|
|
||||||
<!-- Fixed bottom UI: mini player stacked over the bottom nav, both in normal
|
<!-- Bottom UI (mini player + nav), in normal flex flow below the scroller.
|
||||||
flow inside one measured wrapper. The wrapper's height is observed and
|
Owned routes render their own BottomUi inside their own column instead. -->
|
||||||
published to `bottomUiHeight` so pages reserve exactly this much space.
|
{#if !routeOwnsLayout && (showBottomNav || showGlobalMiniPlayer)}
|
||||||
Mini player is first (visually on top, above the nav). -->
|
<BottomUi showMiniPlayer={showGlobalMiniPlayer} showNav={showBottomNav} />
|
||||||
{#if showBottomNav || showGlobalMiniPlayer}
|
|
||||||
<div bind:this={bottomUiEl} class="fixed bottom-0 left-0 right-0 z-40 flex flex-col">
|
|
||||||
{#if showGlobalMiniPlayer}
|
|
||||||
<MiniPlayer
|
|
||||||
media={$currentMedia}
|
|
||||||
isPlaying={$isPlaying}
|
|
||||||
position={$playbackPosition}
|
|
||||||
duration={$playbackDuration}
|
|
||||||
shuffle={$shuffle}
|
|
||||||
repeat={$repeat}
|
|
||||||
hasNext={$hasNext}
|
|
||||||
hasPrevious={$hasPrevious}
|
|
||||||
className="flex-shrink-0"
|
|
||||||
onExpand={() => {
|
|
||||||
// Navigate to player page when mini player is expanded
|
|
||||||
if ($currentMedia) {
|
|
||||||
goto(`/player/${$currentMedia.id}`);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onSleepTimerClick={() => showSleepTimerModal.set(true)}
|
|
||||||
/>
|
|
||||||
{/if}
|
|
||||||
|
|
||||||
{#if showBottomNav}
|
|
||||||
<BottomNav className="flex-shrink-0" />
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Sleep Timer Modal -->
|
|
||||||
<SleepTimerModal
|
|
||||||
isOpen={$showSleepTimerModal}
|
|
||||||
onClose={() => showSleepTimerModal.set(false)}
|
|
||||||
/>
|
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
|
<!-- Sleep Timer Modal (global) -->
|
||||||
|
<SleepTimerModal
|
||||||
|
isOpen={$showSleepTimerModal}
|
||||||
|
onClose={() => showSleepTimerModal.set(false)}
|
||||||
|
/>
|
||||||
{:else}
|
{:else}
|
||||||
<div class="flex items-center justify-center h-screen">
|
<div class="flex items-center justify-center h-screen">
|
||||||
<div class="w-8 h-8 border-2 border-[var(--color-jellyfin)] border-t-transparent rounded-full animate-spin"></div>
|
<div class="w-8 h-8 border-2 border-[var(--color-jellyfin)] border-t-transparent rounded-full animate-spin"></div>
|
||||||
|
|||||||
@@ -5,13 +5,9 @@
|
|||||||
import { commands } from "$lib/api/bindings";
|
import { commands } from "$lib/api/bindings";
|
||||||
import { auth, isAuthenticated, isLoading as isAuthLoading, currentUser } from "$lib/stores/auth";
|
import { auth, isAuthenticated, isLoading as isAuthLoading, currentUser } from "$lib/stores/auth";
|
||||||
import { library } from "$lib/stores/library";
|
import { library } from "$lib/stores/library";
|
||||||
import { currentMedia, isPlaying, playbackPosition, playbackDuration } from "$lib/stores/player";
|
|
||||||
import { isShuffle, repeatMode, hasNext as hasNextStore, hasPrevious as hasPreviousStore } from "$lib/stores/queue";
|
|
||||||
import { isAndroid, bottomUiHeight } from "$lib/stores/appState";
|
|
||||||
import { useScrollGuard } from "$lib/composables/useScrollGuard";
|
import { useScrollGuard } from "$lib/composables/useScrollGuard";
|
||||||
import Search from "$lib/components/Search.svelte";
|
import Search from "$lib/components/Search.svelte";
|
||||||
import MiniPlayer from "$lib/components/player/MiniPlayer.svelte";
|
import BottomUi from "$lib/components/BottomUi.svelte";
|
||||||
import AudioPlayer from "$lib/components/player/AudioPlayer.svelte";
|
|
||||||
import SleepTimerModal from "$lib/components/player/SleepTimerModal.svelte";
|
import SleepTimerModal from "$lib/components/player/SleepTimerModal.svelte";
|
||||||
|
|
||||||
// Scroll guard prevents accidental taps on library cards during/after scrolling (Android)
|
// Scroll guard prevents accidental taps on library cards during/after scrolling (Android)
|
||||||
@@ -21,19 +17,8 @@
|
|||||||
let { children } = $props();
|
let { children } = $props();
|
||||||
|
|
||||||
let searchQuery = $state("");
|
let searchQuery = $state("");
|
||||||
let showFullPlayer = $state(false);
|
|
||||||
let showOverflowMenu = $state(false);
|
let showOverflowMenu = $state(false);
|
||||||
let showSleepTimerModal = $state(false);
|
let showSleepTimerModal = $state(false);
|
||||||
// Queue status (shuffle, repeat, hasNext, hasPrevious) is event-driven via the
|
|
||||||
// queue store, which listens for queue_changed events from the backend. This
|
|
||||||
// updates instantly when toggling shuffle/repeat (no polling lag).
|
|
||||||
const shuffle = $derived($isShuffle);
|
|
||||||
const repeat = $derived($repeatMode);
|
|
||||||
const hasNext = $derived($hasNextStore);
|
|
||||||
const hasPrevious = $derived($hasPreviousStore);
|
|
||||||
// Platform comes from the shared appState store (set once in the root layout),
|
|
||||||
// so this layout and the root layout never disagree about Android — otherwise
|
|
||||||
// both can suppress their mini players and none appears. See $lib/stores/appState.
|
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
return () => {
|
return () => {
|
||||||
@@ -204,56 +189,19 @@
|
|||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<!-- Main content. The mini player is an in-flow flex sibling below this
|
<!-- Main content. The BottomUi below is an in-flow flex sibling, so this
|
||||||
scroller (not a fixed overlay), so the list can never render behind it.
|
scroller is physically bounded above it and its last row can never
|
||||||
Android keeps the global fixed bottom UI (nav + mini player), so there we
|
render behind the nav — no measurement, no reserved padding. -->
|
||||||
reserve its real measured height (`bottomUiHeight`, observed live in the
|
|
||||||
root layout) plus a little breathing room. Non-Android reserves none —
|
|
||||||
the in-flow bar below owns that space. -->
|
|
||||||
<main
|
<main
|
||||||
class="flex-1 overflow-y-auto p-4 min-h-0"
|
class="flex-1 overflow-y-auto p-4 min-h-0"
|
||||||
style="padding-bottom: {$isAndroid ? `calc(${$bottomUiHeight}px + 1rem)` : '1rem'}; overscroll-behavior: contain"
|
style="overscroll-behavior: contain"
|
||||||
onscroll={scrollGuard.onScroll}
|
onscroll={scrollGuard.onScroll}
|
||||||
>
|
>
|
||||||
{@render children()}
|
{@render children()}
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
<!-- Mini Player (only show on non-Android platforms - Android uses global mini player) -->
|
<!-- Bottom UI (mini player + nav), in-flow below the scroller. -->
|
||||||
<!-- Hide on player page since full player is already there. Rendered in
|
<BottomUi />
|
||||||
normal flex flow so it sits above the list rather than overlapping it. -->
|
|
||||||
{#if !$isAndroid && !$page.url.pathname.startsWith('/player/')}
|
|
||||||
<MiniPlayer
|
|
||||||
media={$currentMedia}
|
|
||||||
isPlaying={$isPlaying}
|
|
||||||
position={$playbackPosition}
|
|
||||||
duration={$playbackDuration}
|
|
||||||
{shuffle}
|
|
||||||
{repeat}
|
|
||||||
{hasNext}
|
|
||||||
{hasPrevious}
|
|
||||||
className="flex-shrink-0"
|
|
||||||
onExpand={() => showFullPlayer = true}
|
|
||||||
onSleepTimerClick={() => showSleepTimerModal = true}
|
|
||||||
/>
|
|
||||||
{/if}
|
|
||||||
|
|
||||||
<!-- Full Audio Player -->
|
|
||||||
{#if showFullPlayer}
|
|
||||||
<AudioPlayer
|
|
||||||
media={$currentMedia}
|
|
||||||
isPlaying={$isPlaying}
|
|
||||||
position={$playbackPosition}
|
|
||||||
duration={$playbackDuration}
|
|
||||||
{shuffle}
|
|
||||||
{repeat}
|
|
||||||
{hasNext}
|
|
||||||
{hasPrevious}
|
|
||||||
onClose={() => {
|
|
||||||
showFullPlayer = false;
|
|
||||||
window.history.back();
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
{/if}
|
|
||||||
|
|
||||||
<!-- Sleep Timer Modal -->
|
<!-- Sleep Timer Modal -->
|
||||||
<SleepTimerModal
|
<SleepTimerModal
|
||||||
|
|||||||
@@ -17,6 +17,23 @@
|
|||||||
|
|
||||||
const isMusicLibrary = $derived($currentLibrary?.collectionType === "music");
|
const isMusicLibrary = $derived($currentLibrary?.collectionType === "music");
|
||||||
|
|
||||||
|
// Music/TV/Movies libraries have their own dedicated landing pages
|
||||||
|
// (/library/music, /library/tv, /library/movies). When `currentLibrary` is one
|
||||||
|
// of those, any inline "library content" view here is a STALE leftover from
|
||||||
|
// navigating into that page — showing it makes "up"/back from that page render
|
||||||
|
// the library's item list instead of the libraries overview. Treat those types
|
||||||
|
// as "no inline content" so this page always shows the overview for them,
|
||||||
|
// whether we arrived via the header Up affordance or the hardware back button.
|
||||||
|
// Live TV / channels / other types still render their content inline here.
|
||||||
|
const currentLibraryHasDedicatedPage = $derived(
|
||||||
|
$currentLibrary?.collectionType === "music" ||
|
||||||
|
$currentLibrary?.collectionType === "tvshows" ||
|
||||||
|
$currentLibrary?.collectionType === "movies"
|
||||||
|
);
|
||||||
|
const showInlineLibraryContent = $derived(
|
||||||
|
!!$currentLibrary && !currentLibraryHasDedicatedPage
|
||||||
|
);
|
||||||
|
|
||||||
// Filter out Playlist libraries - they belong in Music sub-library
|
// Filter out Playlist libraries - they belong in Music sub-library
|
||||||
const visibleLibraries = $derived.by(() => {
|
const visibleLibraries = $derived.by(() => {
|
||||||
return $libraries.filter(lib => lib.collectionType !== "playlists");
|
return $libraries.filter(lib => lib.collectionType !== "playlists");
|
||||||
@@ -176,8 +193,8 @@
|
|||||||
onItemClick={handleItemClick}
|
onItemClick={handleItemClick}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{:else if $currentLibrary}
|
{:else if showInlineLibraryContent}
|
||||||
<!-- Library content -->
|
<!-- Library content (live TV / channels / other inline-rendered types) -->
|
||||||
<div class="space-y-6">
|
<div class="space-y-6">
|
||||||
<div class="flex items-center gap-4">
|
<div class="flex items-center gap-4">
|
||||||
<button
|
<button
|
||||||
@@ -189,7 +206,7 @@
|
|||||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
|
||||||
</svg>
|
</svg>
|
||||||
</button>
|
</button>
|
||||||
<h1 class="text-2xl font-bold text-white">{$currentLibrary.name}</h1>
|
<h1 class="text-2xl font-bold text-white">{$currentLibrary?.name}</h1>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{#if isMusicLibrary}
|
{#if isMusicLibrary}
|
||||||
|
|||||||
@@ -2,8 +2,8 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { onMount } from "svelte";
|
import { onMount } from "svelte";
|
||||||
import { goto } from "$app/navigation";
|
import { goto } from "$app/navigation";
|
||||||
import { navigateBack } from "$lib/utils/navigation";
|
import { navigateUp } from "$lib/utils/navigation";
|
||||||
import { currentLibrary } from "$lib/stores/library";
|
import { library, currentLibrary } from "$lib/stores/library";
|
||||||
import { movies } from "$lib/stores/movies";
|
import { movies } from "$lib/stores/movies";
|
||||||
import { isServerReachable } from "$lib/stores/connectivity";
|
import { isServerReachable } from "$lib/stores/connectivity";
|
||||||
import { useServerReachabilityReload } from "$lib/composables/useServerReachabilityReload";
|
import { useServerReachabilityReload } from "$lib/composables/useServerReachabilityReload";
|
||||||
@@ -86,7 +86,7 @@
|
|||||||
<div class="flex items-center justify-between px-4">
|
<div class="flex items-center justify-between px-4">
|
||||||
<h1 class="text-3xl font-bold text-white">{$currentLibrary?.name ?? "Movies"}</h1>
|
<h1 class="text-3xl font-bold text-white">{$currentLibrary?.name ?? "Movies"}</h1>
|
||||||
<button
|
<button
|
||||||
onclick={() => navigateBack("/library")}
|
onclick={() => { library.setCurrentLibrary(null); navigateUp("/library"); }}
|
||||||
class="p-2 rounded-lg hover:bg-white/10 transition-colors text-gray-400 hover:text-white"
|
class="p-2 rounded-lg hover:bg-white/10 transition-colors text-gray-400 hover:text-white"
|
||||||
title="Back to libraries"
|
title="Back to libraries"
|
||||||
aria-label="Back to libraries"
|
aria-label="Back to libraries"
|
||||||
|
|||||||
@@ -2,9 +2,9 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { onMount } from "svelte";
|
import { onMount } from "svelte";
|
||||||
import { goto } from "$app/navigation";
|
import { goto } from "$app/navigation";
|
||||||
import { navigateBack } from "$lib/utils/navigation";
|
import { navigateUp } from "$lib/utils/navigation";
|
||||||
import { auth } from "$lib/stores/auth";
|
import { auth } from "$lib/stores/auth";
|
||||||
import { currentLibrary } from "$lib/stores/library";
|
import { library, currentLibrary } from "$lib/stores/library";
|
||||||
import { music } from "$lib/stores/music";
|
import { music } from "$lib/stores/music";
|
||||||
import { isServerReachable } from "$lib/stores/connectivity";
|
import { isServerReachable } from "$lib/stores/connectivity";
|
||||||
import { useServerReachabilityReload } from "$lib/composables/useServerReachabilityReload";
|
import { useServerReachabilityReload } from "$lib/composables/useServerReachabilityReload";
|
||||||
@@ -108,7 +108,7 @@
|
|||||||
<div class="flex items-center justify-between px-4">
|
<div class="flex items-center justify-between px-4">
|
||||||
<h1 class="text-3xl font-bold text-white">Music</h1>
|
<h1 class="text-3xl font-bold text-white">Music</h1>
|
||||||
<button
|
<button
|
||||||
onclick={() => navigateBack("/library")}
|
onclick={() => { library.setCurrentLibrary(null); navigateUp("/library"); }}
|
||||||
class="p-2 rounded-lg hover:bg-white/10 transition-colors text-gray-400 hover:text-white"
|
class="p-2 rounded-lg hover:bg-white/10 transition-colors text-gray-400 hover:text-white"
|
||||||
title="Back to libraries"
|
title="Back to libraries"
|
||||||
aria-label="Back to libraries"
|
aria-label="Back to libraries"
|
||||||
|
|||||||
@@ -2,8 +2,8 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { onMount } from "svelte";
|
import { onMount } from "svelte";
|
||||||
import { goto } from "$app/navigation";
|
import { goto } from "$app/navigation";
|
||||||
import { navigateBack } from "$lib/utils/navigation";
|
import { navigateUp } from "$lib/utils/navigation";
|
||||||
import { currentLibrary } from "$lib/stores/library";
|
import { library, currentLibrary } from "$lib/stores/library";
|
||||||
import { tv } from "$lib/stores/tv";
|
import { tv } from "$lib/stores/tv";
|
||||||
import { isServerReachable } from "$lib/stores/connectivity";
|
import { isServerReachable } from "$lib/stores/connectivity";
|
||||||
import { useServerReachabilityReload } from "$lib/composables/useServerReachabilityReload";
|
import { useServerReachabilityReload } from "$lib/composables/useServerReachabilityReload";
|
||||||
@@ -93,7 +93,7 @@
|
|||||||
<div class="flex items-center justify-between px-4">
|
<div class="flex items-center justify-between px-4">
|
||||||
<h1 class="text-3xl font-bold text-white">{$currentLibrary?.name ?? "TV Shows"}</h1>
|
<h1 class="text-3xl font-bold text-white">{$currentLibrary?.name ?? "TV Shows"}</h1>
|
||||||
<button
|
<button
|
||||||
onclick={() => navigateBack("/library")}
|
onclick={() => { library.setCurrentLibrary(null); navigateUp("/library"); }}
|
||||||
class="p-2 rounded-lg hover:bg-white/10 transition-colors text-gray-400 hover:text-white"
|
class="p-2 rounded-lg hover:bg-white/10 transition-colors text-gray-400 hover:text-white"
|
||||||
title="Back to libraries"
|
title="Back to libraries"
|
||||||
aria-label="Back to libraries"
|
aria-label="Back to libraries"
|
||||||
|
|||||||
@@ -170,7 +170,7 @@
|
|||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="max-w-2xl mx-auto space-y-8 p-6 pb-24 h-full overflow-y-auto">
|
<div class="max-w-2xl mx-auto space-y-8 p-6">
|
||||||
<div>
|
<div>
|
||||||
<h1 class="text-3xl font-bold text-white mb-2">Audio Settings</h1>
|
<h1 class="text-3xl font-bold text-white mb-2">Audio Settings</h1>
|
||||||
<p class="text-gray-400">Configure playback and audio processing</p>
|
<p class="text-gray-400">Configure playback and audio processing</p>
|
||||||
|
|||||||
Reference in New Issue
Block a user