feat(purchases): add PurchaseDetailView UI (detail + download screen, Slint)

Slice 9/13. New ui/purchases/PurchaseDetailView.slint cloning AlbumPageView
header (224x224, unavailable TriangleAlert overlay, LONG-month purchasedOn,
quality/stats), CircleAction Play-album + Download-All, format dropdown,
count-based progress (NOT format-scoped, A.4), Add-to-Library block, disc-grouped
track table with 4-state hover download, getTrackStatus format-scoped suppression,
bare track-row quality (A.6). Wires PurchaseDetailState/PurchaseActions globals
(state.slint + app.slint bridge), AppShell purchase-detail mount, controller
load_purchase_album + apply_detail, detail-cover artwork target. 28 tests green.

Note: per-track/Play-album routing (A.1/A.2) + now-playing active-track wiring
land in Slice 10; nav history + reactive-reload in Slice 11.

cc
This commit is contained in:
vicrodh committed 2026-06-24 14:02:15 -06:00
1 parent 06dd52e5d4
commit be87fe3377
7 files changed
+1679 -8

No files matched your search

+8
View File
@@ -209,6 +209,9 @@ pub enum ArtworkTarget {
/// A thumbnail of `PurchasesState.tracks-full[index]` (artwork-target full
/// set). Dual-set by id into the rendered flat + grouped track models.
PurchaseTrack { index: usize },
/// The 224×224 header cover of the PurchaseDetailView (single image written
/// to `PurchaseDetailState.artwork`).
PurchaseDetailCover,
}
impl ArtworkTarget {
@@ -1117,6 +1120,11 @@ fn apply_artwork(
crate::purchases::set_track_artwork(window, &id, image);
}
}
ArtworkTarget::PurchaseDetailCover => {
window
.global::<crate::PurchaseDetailState>()
.set_artwork(image);
}
ArtworkTarget::LocalAlbumCard { index, gen } => {
// Drop the cover if a reload superseded the set it belongs to.
if !crate::local_library::albums_gen_current(gen) {
+266
View File
@@ -2367,6 +2367,55 @@ fn execute_track_download(
});
}
/// Open the PurchaseDetailView for `album_id`. Seeds the bound id on
/// `PurchaseDetailState`, resets the previous album's content (so an
/// album→album jump never flashes stale data), and switches the view. The
/// actual fetch is fired by the view's `changed album-id => load(id)` handler
/// (§A.3 reactive reload) — `load_purchase_detail` runs that load. The
/// conditional-mount guard in AppShell requires the non-empty id we set here.
fn navigate_purchase_detail(weak: slint::Weak<AppWindow>, album_id: &str) {
let album_id = album_id.to_string();
let _ = weak.upgrade_in_event_loop(move |w| {
purchases::reset_detail(&w);
w.global::<PurchaseDetailState>().set_album_id(album_id.into());
w.global::<NavState>().set_view(ContentView::PurchaseAlbum);
});
}
/// Fetch + apply the detail album (Svelte `loadAlbum`, §2.2.2). Sets the
/// loading shell, loads the `PurchaseAlbum` + formats via the controller, then
/// applies + spawns the header-cover artwork. On error surfaces the RAW string
/// (NOT i18n-mapped, unlike the list view — §2.2.4). Re-entrant safe: a newer
/// `album-id` change supersedes an in-flight load by reseeding the cache.
fn load_purchase_detail(
runtime: Arc<AppRuntime<SlintAdapter>>,
weak: slint::Weak<AppWindow>,
handle: tokio::runtime::Handle,
image_cache: artwork::ImageCache,
album_id: String,
) {
handle.spawn(async move {
let _ = weak.upgrade_in_event_loop(|w| {
purchases::set_detail_loading(&w);
});
match purchases::load_purchase_album(&runtime, &album_id).await {
Ok(payload) => {
let _ = weak.upgrade_in_event_loop(move |w| {
purchases::apply_detail(&w, payload);
});
let jobs = purchases::detail_artwork_jobs();
artwork::spawn_loads(jobs, weak.clone(), image_cache.clone());
}
Err(e) => {
let _ = weak.upgrade_in_event_loop(move |w| {
// RAW error (NOT i18n-mapped, §2.2.4).
purchases::set_detail_error(&w, &e);
});
}
}
});
}
/// Open Library > Favorites on `tab` and lazy-load that tab's data.
/// Switching the active tab also routes here so each tab fetches on
/// first view (Tauri's loadTabIfNeeded).
@@ -5595,6 +5644,16 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
});
}
// Open a purchase album DETAIL view (from a Purchases grid/list card).
// Seeds the bound id + switches the view; the view's `changed album-id`
// handler fires the fetch (§A.3). Slice 11 layers nav-history + persistence.
{
let weak = window.as_weak();
window.on_open_purchase_album(move |album_id| {
navigate_purchase_detail(weak.clone(), album_id.as_str());
});
}
// Open an album: record history, then load and show it.
{
let runtime = app_runtime.clone();
@@ -11216,6 +11275,213 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
});
}
// ── PurchaseDetailView actions (Slice 9 — detail surface) ───────────────
{
// load(album-id) — the reactive-reload seam (§A.3). Fired by the view's
// `changed album-id` handler + first mount. Fetches the detail album +
// formats and applies them (RAW error on failure).
let runtime = app_runtime.clone();
let weak = window.as_weak();
let handle = tokio_rt.handle().clone();
let image_cache = image_cache.clone();
window
.global::<PurchaseDetailActions>()
.on_load(move |album_id| {
load_purchase_detail(
runtime.clone(),
weak.clone(),
handle.clone(),
image_cache.clone(),
album_id.to_string(),
);
});
}
{
// open-artist(id) — reuse the global open-artist path.
let weak = window.as_weak();
window
.global::<PurchaseDetailActions>()
.on_open_artist(move |id| {
let Some(w) = weak.upgrade() else { return };
w.invoke_open_artist(id);
});
}
{
// play-album — Play-album routing (Slice 10 finalizes A.1; here it goes
// through the standard album-play media-action emitted by the shell, NOT
// a purchase command, NOT the downloaded file).
let weak = window.as_weak();
window.global::<PurchaseDetailActions>().on_play_album(move || {
let Some(w) = weak.upgrade() else { return };
let album_id = purchases::detail_album_id();
if album_id.is_empty() {
return;
}
w.invoke_media_action("album".into(), album_id.into(), "play".into());
});
}
{
// play-track(id) — per-track single-track play (Slice 10 finalizes A.2;
// standard media-action path, no queue mutation).
let weak = window.as_weak();
window
.global::<PurchaseDetailActions>()
.on_play_track(move |id| {
let Some(w) = weak.upgrade() else { return };
w.invoke_media_action("track".into(), id, "play".into());
});
}
{
// select-format(index) — update the selected format id + re-derive (a
// format change re-scopes per-track completion + the dropdown label).
let weak = window.as_weak();
window
.global::<PurchaseDetailActions>()
.on_select_format(move |index| {
let Some(w) = weak.upgrade() else { return };
purchases::select_detail_format(index.max(0) as usize);
purchases::derive_detail(&w);
});
}
{
// download-all — folder pick → startAlbumDownload (§2.2.7 'all' branch).
let runtime = app_runtime.clone();
let weak = window.as_weak();
let handle = tokio_rt.handle().clone();
window
.global::<PurchaseDetailActions>()
.on_download_all(move || {
let runtime = runtime.clone();
let weak = weak.clone();
let handle2 = handle.clone();
// Guard (Svelte §2.2.7): no album or no selected format → return.
let album_id = purchases::detail_album_id();
let Some(fmt_id) = purchases::detail_selected_format_id() else {
return;
};
let Some(fmt_label) = purchases::detail_selected_format_label() else {
return;
};
let track_ids = purchases::detail_track_ids();
if album_id.is_empty() {
return;
}
handle.spawn(async move {
let Some(dest) = purchases::pick_download_folder().await else {
return;
};
let quality_dir = purchases::quality_dir(&fmt_label);
purchases::start_album_download(
runtime,
weak.clone(),
handle2,
album_id,
track_ids,
fmt_id,
dest,
quality_dir,
);
// Project the seeded progress immediately.
let _ = weak.upgrade_in_event_loop(|w| {
purchases::refresh_detail_download(&w);
});
});
});
}
{
// download-track(id) — folder pick → startTrackDownload (§2.2.7 trackId
// branch). Single-track MERGE into the album state (§A.7).
let runtime = app_runtime.clone();
let weak = window.as_weak();
let handle = tokio_rt.handle().clone();
window
.global::<PurchaseDetailActions>()
.on_download_track(move |track_id_s| {
let Ok(track_id) = track_id_s.parse::<u64>() else { return };
let album_id = purchases::detail_album_id();
let Some(fmt_id) = purchases::detail_selected_format_id() else {
return;
};
let Some(fmt_label) = purchases::detail_selected_format_label() else {
return;
};
if album_id.is_empty() {
return;
}
let runtime = runtime.clone();
let weak = weak.clone();
let handle2 = handle.clone();
handle.spawn(async move {
let Some(dest) = purchases::pick_download_folder().await else {
return;
};
let quality_dir = purchases::quality_dir(&fmt_label);
purchases::start_track_download(
runtime,
weak.clone(),
handle2,
album_id,
track_id,
fmt_id,
dest,
quality_dir,
);
let _ = weak.upgrade_in_event_loop(|w| {
purchases::refresh_detail_download(&w);
});
});
});
}
{
// cancel-download — set the abort flag (the running track finishes; the
// rest become cancelled between tracks) + re-derive the progress.
let weak = window.as_weak();
window
.global::<PurchaseDetailActions>()
.on_cancel_download(move || {
let Some(w) = weak.upgrade() else { return };
let album_id = purchases::detail_album_id();
if album_id.is_empty() {
return;
}
purchases::cancel_album_download(&album_id);
purchases::refresh_detail_download(&w);
});
}
{
// add-to-library — the ONLY non-purchase backend write (§2.2.6). Reads
// the rewritten album-folder destination from the store, fires the
// add-folder + scan, clears the download state, then re-derives.
let weak = window.as_weak();
let handle = tokio_rt.handle().clone();
window
.global::<PurchaseDetailActions>()
.on_add_to_library(move || {
let Some(w) = weak.upgrade() else { return };
let album_id = purchases::detail_album_id();
let Some(destination) = purchases::detail_destination() else {
return;
};
if album_id.is_empty() {
return;
}
// Show the spinner; `handle_add_to_library` holds it true across
// the whole async add and clears it (plus re-derives the detail)
// on EVERY exit path — so the spinner stays visible for the real
// duration of the add (Svelte keeps `addingToLibrary` true across
// the await), and on success the cleared download state hides the
// progress + Add-to-Library blocks while on failure only the
// spinner drops. No premature next-tick clear here.
purchases::set_detail_adding_to_library(&w, true);
purchases::handle_add_to_library(
weak.clone(),
handle.clone(),
album_id,
destination,
);
});
}
// Immersive Suggestions panel actions (Checkpoint D — split-panel == 2).
{
// load(track-id) — entry + now-playing-change refresh. Reads the
+521 -5
View File
@@ -1123,9 +1123,26 @@ pub fn start_track_download(
/// per-track status changes without a refetch.
fn nudge_ui_refresh(weak: &slint::Weak<AppWindow>) {
let _ = weak.upgrade_in_event_loop(|w| {
// Only re-derive while the purchases view is the relevant surface; a
// re-derive elsewhere is harmless (it just rebuilds hidden models).
// Re-derive the PurchasesView LIST projection (per-track dl-status on the
// visible rows). A re-derive elsewhere is harmless (it rebuilds hidden
// models).
refresh_track_statuses(&w);
// ALSO re-derive the detail screen so the progress section, per-track
// 4-state, completed-count, was-cancelled, all-complete, and the
// Add-to-Library block update LIVE during/after a running download
// (matches Svelte's reactive `$derived` re-run on every store change,
// PurchaseAlbumDetailView.svelte :44-52/:203-209/:317-349/:388-461).
// Gated on the detail view being the active surface — `derive_detail`
// reads the persisted detail cache (the currently-loaded album), so a
// re-derive while another view is up would rebuild the hidden detail
// models from stale-but-irrelevant cache; gating keeps it cheap and
// correct. The four main.rs action handlers seed the detail once
// synchronously; this routes the async download-lifecycle nudges
// (execute_album_download :1032, start_track_download :1057/:1063/:1116)
// to keep it refreshed thereafter.
if w.global::<NavState>().get_view() == ContentView::PurchaseAlbum {
derive_detail(&w);
}
});
}
@@ -1152,6 +1169,16 @@ pub async fn pick_download_folder() -> Option<String> {
/// 4. fire-and-forget scan of the new folder (`scan_folder`, errors swallowed
/// — the Svelte `.catch(() => {})`).
/// On add-folder failure → error toast `purchases.addToLibraryError`.
///
/// The spinner (`adding_to_library`) is set true by the caller BEFORE this fires
/// and is held true across the whole async add (matching Svelte's `addingToLibrary`
/// staying true across the await, PurchaseAlbumDetailView.svelte :56-71). This fn
/// owns clearing it: on EVERY exit path it schedules an event-loop callback that
/// drops the spinner AND re-derives the detail — so on success the cleared download
/// state hides the progress + Add-to-Library blocks (Svelte's reactive `$derived`),
/// and on failure the spinner drops while the block stays in place. (Replaces the
/// old next-tick `upgrade_in_event_loop` in main.rs that flashed the spinner off
/// before the async add finished and re-derived against stale state.)
pub fn handle_add_to_library(
weak: slint::Weak<AppWindow>,
handle: tokio::runtime::Handle,
@@ -1160,8 +1187,22 @@ pub fn handle_add_to_library(
) {
let scan_handle = handle.clone();
handle.spawn(async move {
// Drop the spinner + re-derive the detail on the event loop. Called on
// every exit path (skip-if-remote / add-failure / success) so the
// spinner never gets stuck and the (possibly cleared) download state is
// reflected. On success the state is already cleared → the derive hides
// the progress + Add-to-Library blocks; on failure nothing was cleared →
// the block stays, only the spinner drops.
let finish = |weak: slint::Weak<AppWindow>| {
let _ = weak.upgrade_in_event_loop(|w| {
set_detail_adding_to_library(&w, false);
refresh_detail_download(&w);
});
};
// skip-if-remote: no library writes while controlling a remote renderer.
if is_controlling_remote().await {
finish(weak.clone());
return;
}
@@ -1185,8 +1226,10 @@ pub fn handle_add_to_library(
.flatten();
let Some(folder_id) = folder_id else {
// (error) add-folder failed → error toast, leave state intact.
// (error) add-folder failed → error toast, leave state intact (the
// Add-to-Library block stays); `finish` drops only the spinner.
crate::toast::error_weak(&weak, qbz_i18n::t("Couldn't add to library"));
finish(weak.clone());
return;
};
@@ -1202,6 +1245,9 @@ pub fn handle_add_to_library(
// album folder, so the files tag `source='qobuz_purchase'` (§7.8) and
// pick up the gold badge in LocalLibrary.
crate::local_library_settings::scan_folder(weak.clone(), scan_handle, folder_id);
// (5) drop the spinner + re-derive (cleared state → blocks vanish).
finish(weak.clone());
});
}
@@ -1223,8 +1269,8 @@ pub fn handle_add_to_library(
use slint::{ComponentHandle, Model, ModelRc, VecModel};
use crate::{
PurchaseAlbumGroup, PurchaseAlbumItem, PurchaseFormatItem, PurchaseTrackGroup, PurchaseTrackItem,
PurchasesState,
ContentView, NavState, PurchaseAlbumGroup, PurchaseAlbumItem, PurchaseDetailState,
PurchaseDetailTrack, PurchaseFormatItem, PurchaseTrackGroup, PurchaseTrackItem, PurchasesState,
};
/// `'all' | 'hires' | 'cd' | 'lossy'` quality filter (Svelte `QualityFilter`).
@@ -2085,6 +2131,476 @@ pub fn find_track(track_id: u64) -> Option<PurchaseTrack> {
with_ui_cache(|c| c.tracks_raw.iter().find(|t| t.id == track_id).cloned())
}
// ============================================================================
// Slice 9 — PurchaseDetailView (detail + download screen)
//
// The detail-surface chrome lives in `ui/purchases/PurchaseDetailView.slint`;
// this section is the Rust half: the load fn (mirrors Tauri command #5 via the
// shared `purchases_service::build_purchase_album`), the detail UI cache (so
// format changes + download-status nudges re-project the rows/progress without
// a refetch), and the event-loop appliers that project the cache + the
// download store → `PurchaseDetailState`.
//
// SEND BOUNDARY: load fns return PLAIN `Send` payloads (no Slint types); the
// appliers build `ModelRc`/`Image` only on the event loop.
//
// Mirrors `PurchaseAlbumDetailView.svelte` §2.2. The download state machine,
// folder picker, and the download actions are reused from Slice 7 (they live
// above and survive navigation in the process-wide store).
// ============================================================================
/// A `Send` snapshot of one purchased album for the detail view: the header
/// fields + the synthesized format options + the nested tracks. No Slint types
/// — built off the event loop, cached, then applied.
#[derive(Debug, Clone, Default)]
pub struct PurchaseDetailPayload {
pub album: PurchaseAlbum,
pub formats: Vec<PurchaseFormatOption>,
}
/// Detail UI cache: the loaded album + its formats + the currently-selected
/// format id, so a format-dropdown change or a download-status nudge can
/// re-project the rows/progress WITHOUT a refetch (the Svelte component keeps
/// these in `$state`). Survives navigation only transiently — a fresh
/// `load_purchase_album` reseeds it (and `reset_detail` clears it).
#[derive(Debug, Default)]
struct DetailCache {
album_id: String,
album: Option<PurchaseAlbum>,
formats: Vec<PurchaseFormatOption>,
/// The currently-selected format id (default `formats[0].id` after load).
selected_format_id: Option<u32>,
}
fn detail_cache() -> &'static Mutex<DetailCache> {
static CACHE: OnceLock<Mutex<DetailCache>> = OnceLock::new();
CACHE.get_or_init(|| Mutex::new(DetailCache::default()))
}
fn with_detail_cache<R>(f: impl FnOnce(&mut DetailCache) -> R) -> R {
let mut guard = detail_cache().lock().unwrap_or_else(|e| e.into_inner());
f(&mut guard)
}
/// `getSelectedFormatLabel` / `handleFormatChange` glue: set the selected
/// format id from a dropdown INDEX into the cached `formats`. Returns the
/// chosen format id (so the caller can re-derive). A no-op (returns the current
/// selection) for an out-of-range index.
pub fn select_detail_format(index: usize) -> Option<u32> {
with_detail_cache(|c| {
if let Some(fmt) = c.formats.get(index) {
c.selected_format_id = Some(fmt.id);
}
c.selected_format_id
})
}
/// The currently-selected detail format id (for the download actions:
/// `promptForFolder` reads `selectedFormatId` + `qualityFolderName`).
pub fn detail_selected_format_id() -> Option<u32> {
with_detail_cache(|c| c.selected_format_id)
}
/// The cached detail album id (the actions need it to key the download store).
pub fn detail_album_id() -> String {
with_detail_cache(|c| c.album_id.clone())
}
/// The label of the currently-selected format (for the `qualityDir`
/// derivation in the download actions; `qualityFolderName(selectedFormatId)`).
pub fn detail_selected_format_label() -> Option<String> {
with_detail_cache(|c| {
let sel = c.selected_format_id?;
c.formats
.iter()
.find(|f| f.id == sel)
.map(|f| f.label.clone())
})
}
/// The track ids of the cached detail album, in order (for `download-all` →
/// `startAlbumDownload(albumId, album.tracks.items.map(t=>t.id), ...)`).
pub fn detail_track_ids() -> Vec<u64> {
with_detail_cache(|c| {
c.album
.as_ref()
.and_then(|a| a.tracks.as_ref())
.map(|page| page.items.iter().map(|t| t.id).collect())
.unwrap_or_default()
})
}
/// The cached detail album's download destination (after the rewrite) — read
/// from the download store for the Add-to-Library handler.
pub fn detail_destination() -> Option<String> {
let album_id = detail_album_id();
album_download_state(&album_id).and_then(|s| s.destination)
}
/// Load the detail album (Svelte `loadAlbum`, §2.2.2 + command #5). Fetches the
/// full catalog `Album` (the regular `get_album` path) AND the user's purchases
/// listing (for the `downloadable`/`purchased_at` meta), reads the local
/// registry for download flags, builds the `PurchaseAlbum` via the shared
/// `build_purchase_album` service, and synthesizes the formats. Returns a
/// `Send` payload (no Slint types) or a RAW error string (the detail view shows
/// the raw error, NOT i18n-mapped — §2.2.4).
pub async fn load_purchase_album(
runtime: &Runtime,
album_id: &str,
) -> Result<PurchaseDetailPayload, String> {
let Some(client) = snapshot_client(runtime).await else {
// No session = the Svelte unauthenticated fetch rejects → raw error.
return Err("No Qobuz session".to_string());
};
// Full catalog album (the regular album path — same call command #5 uses).
let album = client
.get_album(album_id)
.await
.map_err(|e| format!("Failed to fetch album {album_id}: {e}"))?;
// The purchases listing carries the per-album `downloadable`/`purchased_at`.
let purchases = purchases_service::get_user_purchases_all(&client)
.await
.map_err(|e| format!("Failed to fetch purchases: {e}"))?;
// Registry: downloaded ids + the requested-format map (command #5's DB read).
let (downloaded_ids, format_map) = read_registry_for_detail().await;
let purchase_album =
purchases_service::build_purchase_album(&album, &purchases, &downloaded_ids, &format_map);
let formats = purchases_service::synth_formats(&album);
Ok(PurchaseDetailPayload {
album: purchase_album,
formats,
})
}
/// Read the local registry for the detail annotation: the downloaded track ids
/// (`HashSet<i64>`) + the `track_id → Vec<format_id>` map. Mirrors command #5's
/// `get_downloaded_purchase_formats` read. Empty on a DB error / no user.
async fn read_registry_for_detail() -> (HashSet<i64>, HashMap<i64, Vec<u32>>) {
let formats = get_downloaded_purchase_formats().await; // track_id(u64) → Vec<format_id(u32)>
let mut ids: HashSet<i64> = HashSet::new();
let mut map: HashMap<i64, Vec<u32>> = HashMap::new();
for (track_id, fmt_ids) in formats {
ids.insert(track_id as i64);
map.insert(track_id as i64, fmt_ids);
}
(ids, map)
}
/// Apply a freshly-loaded detail payload to `PurchaseDetailState` (event loop).
/// Seeds the cache, default-selects `formats[0]`, then projects the header +
/// the track rows via [`derive_detail`].
pub fn apply_detail(window: &AppWindow, payload: PurchaseDetailPayload) {
let selected = payload.formats.first().map(|f| f.id);
with_detail_cache(|c| {
c.album_id = payload.album.id.clone();
c.album = Some(payload.album.clone());
c.formats = payload.formats.clone();
c.selected_format_id = selected;
});
let s = window.global::<PurchaseDetailState>();
s.set_loading(false);
s.set_load_error(slint::SharedString::new());
s.set_loaded(true);
// Seed the FULL artwork-target cover model: the header cover is written by
// the artwork pipeline into `PurchaseDetailState.artwork` (single image).
// (No list/grid here — just the one 224×224 cover.)
derive_detail(window);
}
/// Re-project the detail header + format dropdown + progress + track rows from
/// the cache and the download store onto `PurchaseDetailState`. Called after a
/// load, after a format-dropdown change, and after each download-status nudge
/// (the Svelte `$derived` re-run). Runs on the event loop.
pub fn derive_detail(window: &AppWindow) {
let (album, formats, selected) = with_detail_cache(|c| {
(c.album.clone(), c.formats.clone(), c.selected_format_id)
});
let Some(album) = album else {
return;
};
let s = window.global::<PurchaseDetailState>();
// ── Header ────────────────────────────────────────────────────────────
s.set_title(album.title.clone().into());
s.set_artist(album.artist.name.clone().into());
s.set_artist_id(if album.artist.id != 0 {
album.artist.id.to_string().into()
} else {
slint::SharedString::new()
});
s.set_downloadable(album.downloadable);
// LONG-month purchased-on (§2.2.4; the detail uses the long month, unlike
// the list's short month).
s.set_purchased_on(format_purchase_date_long(album.purchased_at).into());
s.set_label_name(
album
.label
.as_ref()
.map(|l| l.name.clone())
.unwrap_or_default()
.into(),
);
s.set_genre_name(
album
.genre
.as_ref()
.map(|g| g.name.clone())
.unwrap_or_default()
.into(),
);
// Header quality (§2.2.4): `formatQuality((bit ?? 16) > 16, bit, rate)`.
let header_hires = album.maximum_bit_depth.unwrap_or(16) > 16;
s.set_quality(
format_quality(header_hires, album.maximum_bit_depth, album.maximum_sampling_rate).into(),
);
let tracks = album
.tracks
.as_ref()
.map(|p| p.items.as_slice())
.unwrap_or(&[]);
let total_tracks = tracks.len() as i32;
s.set_total_tracks(total_tracks);
let total_secs: u32 = tracks.iter().map(|t| t.duration).sum();
s.set_total_duration(format_total_duration(total_secs).into());
// ── Format dropdown ───────────────────────────────────────────────────
let labels: Vec<slint::SharedString> =
formats.iter().map(|f| f.label.clone().into()).collect();
s.set_format_labels(ModelRc::new(VecModel::from(labels)));
let format_index = selected
.and_then(|sel| formats.iter().position(|f| f.id == sel))
.unwrap_or(0) as i32;
s.set_format_index(format_index);
s.set_has_formats(!formats.is_empty());
// ── Download state (from the process-wide store) ──────────────────────
let dl_state = album_download_state(&album.id);
let statuses = dl_state
.as_ref()
.map(|st| st.track_statuses.clone())
.unwrap_or_default();
let is_downloading_all = dl_state.as_ref().map(|st| st.is_downloading_all).unwrap_or(false);
// allComplete IS format-scoped (Svelte `:388`).
let all_complete = album_all_complete_for_format(&album.id, selected);
// completedCount / wasCancelled / progress-fill are NOT format-scoped
// (§A.4) — count ALL statuses in the raw map regardless of selected format.
let completed_count = statuses
.values()
.filter(|st| **st == TrackDownloadStatus::Complete)
.count() as i32;
let any_cancelled = statuses
.values()
.any(|st| *st == TrackDownloadStatus::Cancelled);
// wasCancelled = !isDownloadingAll && !allComplete && some cancelled.
let was_cancelled = !is_downloading_all && !all_complete && any_cancelled;
let progress_percent = if total_tracks > 0 {
(completed_count as f32 / total_tracks as f32) * 100.0
} else {
0.0
};
s.set_is_downloading_all(is_downloading_all);
s.set_all_complete(all_complete);
s.set_was_cancelled(was_cancelled);
s.set_completed_count(completed_count);
s.set_progress_percent(progress_percent);
// Progress section renders iff downloadingAll || allComplete || wasCancelled.
s.set_show_progress(is_downloading_all || all_complete || was_cancelled);
// Download-all gating: disabled while downloading-all OR no selected format.
s.set_can_download_all(!is_downloading_all && selected.is_some());
// Add-to-Library block: only when allComplete (format-scoped) && a
// destination is set in the store (§2.2.4).
let destination = dl_state.as_ref().and_then(|st| st.destination.clone());
s.set_show_add_to_library(all_complete && destination.is_some());
// ── Track rows (disc-grouped) ─────────────────────────────────────────
let rows = build_detail_rows(&album, selected);
s.set_tracks(ModelRc::new(VecModel::from(rows)));
}
/// Build the disc-grouped detail track rows (§2.2.4 `groupByDisc` + §2.2.5 row).
/// Disc number = `media_number ?? 1`; multi-disc iff > 1 distinct discs. The
/// first row of each disc on a multi-disc album carries `disc_header_number =
/// disc`; otherwise 0 (single-disc → flat). Per-track status is FORMAT-SCOPED
/// (`track_status_scoped`); `is_downloaded = isDownloadedForFormat ||
/// status==Complete`; `show_download = downloadable || is_downloaded`.
fn build_detail_rows(
album: &PurchaseAlbum,
selected_format_id: Option<u32>,
) -> Vec<PurchaseDetailTrack> {
let tracks = album
.tracks
.as_ref()
.map(|p| p.items.as_slice())
.unwrap_or(&[]);
// Disc grouping: preserve item order, group by media_number ?? 1.
// `isMultiDisc` = more than one distinct disc number.
let mut distinct_discs: Vec<u32> = Vec::new();
for t in tracks {
let disc = t.media_number.unwrap_or(1);
if !distinct_discs.contains(&disc) {
distinct_discs.push(disc);
}
}
let is_multi_disc = distinct_discs.len() > 1;
let mut rows: Vec<PurchaseDetailTrack> = Vec::with_capacity(tracks.len());
let mut last_disc: Option<u32> = None;
for t in tracks {
let disc = t.media_number.unwrap_or(1);
// First row of a disc on a multi-disc album → header marker.
let disc_header = if is_multi_disc && last_disc != Some(disc) {
disc as i32
} else {
0
};
last_disc = Some(disc);
// FORMAT-SCOPED per-track status (§2.2.3): suppresses `complete` when
// viewing a different format than the one downloaded.
let scoped = track_status_scoped(&album.id, t.id, selected_format_id);
let dl_status = scoped.map(|s| s.as_str()).unwrap_or("").to_string();
// isDownloadedForFormat (server `downloaded_format_ids`) OR a store
// `complete` (§2.2.5).
let downloaded_for_format =
is_downloaded_for_format(&t.downloaded_format_ids, selected_format_id);
let is_downloaded =
downloaded_for_format || scoped == Some(TrackDownloadStatus::Complete);
// show-download (§2.2.5): album.downloadable OR already downloaded.
let show_download = album.downloadable || is_downloaded;
// Second-line performer when ≠ album artist (§2.2.5).
let show_performer =
!t.performer.name.is_empty() && t.performer.name != album.artist.name;
rows.push(PurchaseDetailTrack {
id: t.id.to_string().into(),
track_number: t.track_number as i32,
// Purchased tracks have NO version → formatTrackTitle == title.
title: t.title.clone().into(),
performer: t.performer.name.clone().into(),
show_performer,
duration: format_duration(t.duration).into(),
quality: bare_quality(t.maximum_bit_depth, t.maximum_sampling_rate).into(),
streamable: t.streamable,
dl_status: dl_status.into(),
is_downloaded,
show_download,
disc_header_number: disc_header,
});
}
rows
}
/// Artwork jobs for the detail header cover (the single 224×224 album cover).
/// Reads the cache; event-loop-free.
pub fn detail_artwork_jobs() -> Vec<crate::artwork::ArtworkJob> {
with_detail_cache(|c| {
c.album
.as_ref()
.and_then(|a| a.image.best().cloned())
.filter(|u| !u.is_empty())
.map(|url| {
vec![crate::artwork::ArtworkJob {
url,
target: crate::artwork::ArtworkTarget::PurchaseDetailCover,
}]
})
.unwrap_or_default()
})
}
/// Set loading on the detail state (before a fetch). Event loop.
pub fn set_detail_loading(window: &AppWindow) {
let s = window.global::<PurchaseDetailState>();
s.set_loading(true);
s.set_load_error(slint::SharedString::new());
s.set_loaded(false);
}
/// Surface a RAW detail error (NOT i18n-mapped, §2.2.4). Event loop.
pub fn set_detail_error(window: &AppWindow, message: &str) {
let s = window.global::<PurchaseDetailState>();
s.set_loading(false);
s.set_loaded(false);
s.set_load_error(message.into());
}
/// Set the `adding-to-library` spinner flag. Event loop.
pub fn set_detail_adding_to_library(window: &AppWindow, adding: bool) {
window
.global::<PurchaseDetailState>()
.set_adding_to_library(adding);
}
/// Reset the detail view + cache before loading a new album (an album→album
/// jump must not flash the previous album's header/tracks). Clears the cache
/// and resets the state to its loading shell. Does NOT touch the download store
/// (that survives navigation by design). Event loop.
pub fn reset_detail(window: &AppWindow) {
with_detail_cache(|c| *c = DetailCache::default());
let s = window.global::<PurchaseDetailState>();
s.set_loading(true);
s.set_loaded(false);
s.set_load_error(slint::SharedString::new());
s.set_title(slint::SharedString::new());
s.set_artist(slint::SharedString::new());
s.set_artwork(slint::Image::default());
s.set_tracks(ModelRc::new(VecModel::<PurchaseDetailTrack>::default()));
s.set_format_labels(ModelRc::new(VecModel::<slint::SharedString>::default()));
s.set_has_formats(false);
s.set_show_progress(false);
s.set_show_add_to_library(false);
}
/// Re-derive the detail download projection (progress + per-track statuses)
/// from the store. The download actions call this (via the weak window) to
/// surface live status changes without a refetch. Event loop.
pub fn refresh_detail_download(window: &AppWindow) {
derive_detail(window);
}
/// `formatTotalDuration(seconds)` (§2.2.8): `"{h}h {m}m"` when hours > 0, else
/// `"{m}m"`.
fn format_total_duration(seconds: u32) -> String {
let hrs = seconds / 3600;
let mins = (seconds % 3600) / 60;
if hrs > 0 {
format!("{hrs}h {mins}m")
} else {
format!("{mins}m")
}
}
/// `formatPurchaseDate(ts)` LONG-month variant (Svelte detail `:417`): `''`
/// when no ts; else a localized `"MMMMM D, YYYY"` (FULL month name). The list
/// view uses the SHORT-month [`format_purchase_date`]; the detail uses the long
/// month — replicate the asymmetry verbatim.
fn format_purchase_date_long(ts: Option<i64>) -> String {
let Some(ts) = ts else {
return String::new();
};
if ts <= 0 {
return String::new();
}
use chrono::TimeZone;
match chrono::Local.timestamp_opt(ts, 0) {
chrono::offset::LocalResult::Single(dt) => dt
.format_localized("%B %-d, %Y", crate::dates::current_locale())
.to_string(),
_ => String::new(),
}
}
#[cfg(test)]
mod tests {
use super::*;
+5 -1
View File
@@ -26,7 +26,7 @@ export { Theme, ThemeColors } from "foundation/semantic-colors.slint";
export { ThemeState } from "foundation/theme-state.slint";
// Re-export the state globals so the Rust layer can populate them.
export { HomeState, HomeActions, DiscoverState, DiscoverActions, SectionDescriptor, ConfigRow, DiscoverBrowseState, DiscoverBrowseActions, ForYouState, MixState, GenreFilterState, GenreFilterActions, AlbumState, ArtistState, NavState, ShellState, SessionState, SettingsState, AlbumActions, ArtistActions, ArtworkActions, NowPlayingState, QueueState, LyricsState, LyricsLineItem, SearchState, SearchActions, NetworkSidebarState, NetworkSidebarActions, MusicianState, MusicianActions, LabelState, LabelActions, AwardState, AwardActions, AwardEntry, ArtistReleasesState, ArtistReleasesActions, LocationViewState, LocationViewActions, FavoritesState, FavoritesActions, PlaylistPickerState, PlaylistPickerActions, DuplicateConfirmState, DuplicateConfirmActions, PlaylistState, PlaylistActions, SidebarState, SidebarActions, SidebarFolderPopupState, CreatePlaylistState, CreatePlaylistActions, EditPlaylistState, EditPlaylistActions, CreateFolderState, CreateFolderActions, MyQbzCreateState, MyQbzCreateActions, DragState, DragActions, PlaylistManagerState, PlaylistManagerActions, OfflineManagerState, OfflineManagerActions, BlacklistState, BlacklistActions, BlacklistedArtistItem, MyQbzState, MyQbzActions, MixtapeCardItem, MyQbzAddState, MyQbzAddActions, MyQbzAddRow, MyQbzDetailState, MyQbzDetailActions, MixtapeDetailItem, MyQbzEditState, MyQbzEditActions, MyQbzMixState, MyQbzMixActions, DiscoBuilderState, DiscoBuilderActions, DiscoGroup, DiscoCandidate, LocalLibraryState, LocalLibraryActions, LibraryFoldersState, LibFolderEditState, LibraryManageActions, LibraryScanState, LibAlbumFilterState, LocalAlbumState, LocalAlbumActions, TagEditorState, TagEditorActions, FolderEditState, FolderEditActions, ToastState, TextUtil, QconnectDevState, QconnectDevice, CastState, CastDevice, CastActions, AppearanceState, MyQbzBrandingState, EphemeralPlayChoiceState, EphemeralPlayChoiceActions, PlexSettingsState, PlexAuthActions, PlexSectionItem, ScrobbleState, ScrobbleActions, DiscordState, OfflineState, OfflineModeActions, OfflineFavoritesState, OfflineFavoritesActions, ImportLogEntry, PlaylistImportState, PlaylistImportActions, DacWizardState, DacWizardActions, DacCandidateRow, RemediationRow, DacConfigRow, InfoCreditRow, InfoCreditPair, AlbumCreditPerformer, AlbumCreditTrack, TrackInfoState, TrackInfoActions, AlbumInfoState, AlbumInfoActions, BookletState, BookletActions, SuggestionsState, SuggestionsActions, SuggestionCard, VisualizerState, ImmersiveState, ImmersiveSearchActions, ImmersiveActions, MiniPlayerState, WindowControlActions, PurchasesState, PurchasesActions, PurchaseAlbumItem, PurchaseTrackItem, PurchaseAlbumGroup, PurchaseTrackGroup, PurchaseFormatItem } from "state.slint";
export { HomeState, HomeActions, DiscoverState, DiscoverActions, SectionDescriptor, ConfigRow, DiscoverBrowseState, DiscoverBrowseActions, ForYouState, MixState, GenreFilterState, GenreFilterActions, AlbumState, ArtistState, NavState, ShellState, SessionState, SettingsState, AlbumActions, ArtistActions, ArtworkActions, NowPlayingState, QueueState, LyricsState, LyricsLineItem, SearchState, SearchActions, NetworkSidebarState, NetworkSidebarActions, MusicianState, MusicianActions, LabelState, LabelActions, AwardState, AwardActions, AwardEntry, ArtistReleasesState, ArtistReleasesActions, LocationViewState, LocationViewActions, FavoritesState, FavoritesActions, PlaylistPickerState, PlaylistPickerActions, DuplicateConfirmState, DuplicateConfirmActions, PlaylistState, PlaylistActions, SidebarState, SidebarActions, SidebarFolderPopupState, CreatePlaylistState, CreatePlaylistActions, EditPlaylistState, EditPlaylistActions, CreateFolderState, CreateFolderActions, MyQbzCreateState, MyQbzCreateActions, DragState, DragActions, PlaylistManagerState, PlaylistManagerActions, OfflineManagerState, OfflineManagerActions, BlacklistState, BlacklistActions, BlacklistedArtistItem, MyQbzState, MyQbzActions, MixtapeCardItem, MyQbzAddState, MyQbzAddActions, MyQbzAddRow, MyQbzDetailState, MyQbzDetailActions, MixtapeDetailItem, MyQbzEditState, MyQbzEditActions, MyQbzMixState, MyQbzMixActions, DiscoBuilderState, DiscoBuilderActions, DiscoGroup, DiscoCandidate, LocalLibraryState, LocalLibraryActions, LibraryFoldersState, LibFolderEditState, LibraryManageActions, LibraryScanState, LibAlbumFilterState, LocalAlbumState, LocalAlbumActions, TagEditorState, TagEditorActions, FolderEditState, FolderEditActions, ToastState, TextUtil, QconnectDevState, QconnectDevice, CastState, CastDevice, CastActions, AppearanceState, MyQbzBrandingState, EphemeralPlayChoiceState, EphemeralPlayChoiceActions, PlexSettingsState, PlexAuthActions, PlexSectionItem, ScrobbleState, ScrobbleActions, DiscordState, OfflineState, OfflineModeActions, OfflineFavoritesState, OfflineFavoritesActions, ImportLogEntry, PlaylistImportState, PlaylistImportActions, DacWizardState, DacWizardActions, DacCandidateRow, RemediationRow, DacConfigRow, InfoCreditRow, InfoCreditPair, AlbumCreditPerformer, AlbumCreditTrack, TrackInfoState, TrackInfoActions, AlbumInfoState, AlbumInfoActions, BookletState, BookletActions, SuggestionsState, SuggestionsActions, SuggestionCard, VisualizerState, ImmersiveState, ImmersiveSearchActions, ImmersiveActions, MiniPlayerState, WindowControlActions, PurchasesState, PurchasesActions, PurchaseAlbumItem, PurchaseTrackItem, PurchaseAlbumGroup, PurchaseTrackGroup, PurchaseFormatItem, PurchaseDetailState, PurchaseDetailActions, PurchaseDetailTrack } from "state.slint";
// Which top-level screen is shown. The app starts on `splash` while it
// restores a saved session, then resolves to `shell` or `login`.
@@ -63,6 +63,7 @@ export component AppWindow inherits Window {
callback open-tos();
callback open-album(string);
callback open-artist(string);
callback open-purchase-album(string);
callback media-action(string, string, string);
callback header-menu-navigate(string);
callback discover-view-all(string, string);
@@ -108,6 +109,9 @@ export component AppWindow inherits Window {
open-artist(id) => {
root.open-artist(id);
}
open-purchase-album(id) => {
root.open-purchase-album(id);
}
media-action(kind, id, action) => {
root.media-action(kind, id, action);
}
@@ -0,0 +1,763 @@
// PurchaseDetailView — the purchase detail + download screen
// (source-of-truth §2.2). 1:1 port of `PurchaseAlbumDetailView.svelte`:
// back button + loading/RAW-error states + 224×224 header (with the
// unavailable overlay) + actions row (Play-album / Download-all / format
// dropdown) + the count-based progress section + the Add-to-Library green
// block + the disc-grouped track table with the bespoke 4-state download row.
//
// All download/format math runs in Rust (crate::purchases); this file is the
// chrome and binds `PurchaseDetailState` / fires `PurchaseDetailActions`. The
// track table reproduces the Tauri bespoke detail row (BARE-quality column
// §A.6, the 4-state download control, disc grouping) rather than threading
// Purchases-only flags through the shared TrackRow — the faithful 1:1.
//
// REACTIVE RELOAD (§A.3): the root watches `PurchaseDetailState.album-id` and
// fires `PurchaseDetailActions.load(id)` on change + first mount, so navigating
// between two purchase albums RE-FETCHES instead of showing stale data. (The
// Tauri view relies on a conditional remount; a persistent Slint page must
// watch the bound id explicitly.)
import { Theme } from "../foundation/semantic-colors.slint";
import { Typography } from "../foundation/typography.slint";
import { Radius } from "../foundation/radius.slint";
import { Spacing } from "../foundation/spacing.slint";
import { QbzIcon } from "../primitives/QbzIcon.slint";
import { LoadingSpinner } from "../primitives/LoadingSpinner.slint";
import { CircleAction } from "../primitives/CircleAction.slint";
import { QbzSelect } from "../primitives/QbzSelect.slint";
import { NavButtons } from "../shell/NavButtons.slint";
import {
PurchaseDetailState,
PurchaseDetailActions,
PurchaseDetailTrack,
} from "../state.slint";
// ── One detail track row (bespoke, §2.2.5) ──────────────────────────────────
// # | title (+ 2nd-line performer) | duration | quality (BARE) | download.
// `is-downloaded` dims the row to .6 and renders the green redownload check;
// `show-download` gates the whole control (album not downloadable AND not
// downloaded → no button). The download button is hover-revealed via opacity,
// except failed/redownload which stay visible.
component DetailTrackRow inherits Rectangle {
in property <PurchaseDetailTrack> track;
in property <bool> active: false;
in property <bool> playing: false;
callback play();
callback download();
height: 48px;
border-radius: Radius.sm;
background: root.active ? Theme.alpha-10
: (row-ta.has-hover && root.track.streamable ? Theme.surface-hover : transparent);
// Downloaded rows dim to .6 (Svelte `.complete` opacity).
opacity: root.track.is-downloaded ? 0.6 : 1.0;
// Row click → play (only when streamable). Declared first so the per-cell
// download TouchArea (a child, hit-tested later) still wins.
row-ta := TouchArea {
enabled: root.track.streamable;
mouse-cursor: root.track.streamable ? pointer : default;
clicked => { root.play(); }
}
HorizontalLayout {
padding-left: 12px;
padding-right: 12px;
spacing: 12px;
// # / playing-bars / downloading-spinner.
VerticalLayout {
alignment: center;
width: 28px;
// Playing → three animated bars (the active-track indicator).
if root.active && root.playing: HorizontalLayout {
alignment: center;
spacing: 2px;
Rectangle { width: 3px; height: 12px; background: Theme.accent; border-radius: 1px; }
Rectangle { width: 3px; height: 8px; background: Theme.accent; border-radius: 1px; }
Rectangle { width: 3px; height: 14px; background: Theme.accent; border-radius: 1px; }
}
if !(root.active && root.playing) && root.track.dl-status == "downloading": LoadingSpinner {
size: 14px;
}
if !(root.active && root.playing) && root.track.dl-status != "downloading": Text {
text: root.track.track-number;
color: root.active ? Theme.accent : Theme.text-muted;
font-size: Typography.legal;
horizontal-alignment: center;
}
}
// Title (+ 2nd-line performer when ≠ album artist).
VerticalLayout {
alignment: center;
horizontal-stretch: 1;
spacing: 2px;
Text {
text: root.track.title;
color: root.active ? Theme.accent : Theme.text-primary;
font-size: Typography.body;
font-weight: Typography.medium;
overflow: elide;
}
if root.track.show-performer: Text {
text: root.track.performer;
color: Theme.text-muted;
font-size: Typography.legal;
overflow: elide;
}
}
// Duration.
VerticalLayout {
alignment: center;
width: 44px;
Text {
text: root.track.duration;
color: Theme.text-muted;
font-size: Typography.legal;
horizontal-alignment: right;
}
}
// Quality — BARE "{bit}/{rate}" (§A.6).
VerticalLayout {
alignment: center;
width: 64px;
Text {
text: root.track.quality;
color: Theme.text-secondary;
font-size: Typography.legal;
horizontal-alignment: right;
}
}
// Download control (4 states). Hidden entirely when not downloadable
// and not downloaded (§2.2.5).
VerticalLayout {
alignment: center;
width: 32px;
if root.track.show-download: dl-slot := Rectangle {
width: 30px;
height: 30px;
border-radius: 6px;
background: dl-ta.has-hover ? Theme.surface-elevated : transparent;
// Idle button hover-revealed; downloaded/failed stay visible.
opacity: (root.track.is-downloaded
|| root.track.dl-status == "failed"
|| root.track.dl-status == "downloading"
|| row-ta.has-hover) ? 1.0 : 0.0;
// 1:1 branch ORDER (Svelte col-download :432-459): `isDownloaded`
// is checked FIRST, BEFORE `status === 'downloading'`. So on a
// redownload of an already-downloaded track (is-downloaded AND
// downloading) the redownload check shows here in the download
// column — the spinner only appears in the col-number. Do NOT
// check "downloading" first (§gap).
//
// downloaded → green check (download on hover) — clickable redownload.
if root.track.is-downloaded: QbzIcon {
source: dl-ta.has-hover
? @image-url("../assets/icons/download.svg")
: @image-url("../assets/icons/check.svg");
width: 16px;
height: 16px;
x: (parent.width - self.width) / 2;
y: (parent.height - self.height) / 2;
tint: dl-ta.has-hover ? Theme.text-primary : Theme.success;
}
// else downloading → spinner, no button.
if !root.track.is-downloaded && root.track.dl-status == "downloading": LoadingSpinner {
size: 14px;
x: (parent.width - self.width) / 2;
y: (parent.height - self.height) / 2;
}
// else failed → red triangle-alert (retry).
if !root.track.is-downloaded && root.track.dl-status == "failed": QbzIcon {
source: @image-url("../assets/icons/triangle-alert.svg");
width: 16px;
height: 16px;
x: (parent.width - self.width) / 2;
y: (parent.height - self.height) / 2;
tint: Theme.danger;
}
// else idle → plain download (Svelte `else if album.downloadable`;
// `show-download` already gates the slot to downloadable for the
// not-downloaded case, so this implicitly only renders when
// downloadable).
if !root.track.is-downloaded
&& root.track.dl-status != "downloading"
&& root.track.dl-status != "failed": QbzIcon {
source: @image-url("../assets/icons/download.svg");
width: 16px;
height: 16px;
x: (parent.width - self.width) / 2;
y: (parent.height - self.height) / 2;
tint: dl-ta.has-hover ? Theme.text-primary : Theme.text-muted;
}
dl-ta := TouchArea {
// Clickable except while the spinner shows (downloading AND
// not a redownload of an owned track) — the redownload check
// IS a clickable button (Svelte's `.redownload` button), so a
// downloading owned track stays clickable here.
enabled: root.track.is-downloaded || root.track.dl-status != "downloading";
mouse-cursor: pointer;
clicked => { root.download(); }
}
}
}
}
}
export component PurchaseDetailView inherits Rectangle {
background: Theme.surface-main;
// ── REACTIVE RELOAD (§A.3) ──────────────────────────────────────────────
// Fire a fresh load whenever the bound album id changes (and on first
// mount). A persistent Slint page would otherwise show stale data when the
// id is swapped without a remount.
property <string> watched-id: PurchaseDetailState.album-id;
function maybe-load() {
if (PurchaseDetailState.album-id != "") {
PurchaseDetailActions.load(PurchaseDetailState.album-id);
}
}
init => { self.maybe-load(); }
changed watched-id => { self.maybe-load(); }
flick := Flickable {
width: parent.width;
viewport-width: self.width;
viewport-height: page.preferred-height;
page := VerticalLayout {
width: parent.width;
padding-left: 32px;
padding-right: 32px;
padding-top: 11px;
padding-bottom: 100px;
spacing: 0px;
alignment: start;
// --- History navigation (back button, always at top) -------------
HorizontalLayout {
alignment: start;
NavButtons { }
}
Rectangle { height: 22px; }
// --- Loading / RAW-error states ----------------------------------
if PurchaseDetailState.loading: Rectangle {
height: 200px;
LoadingSpinner {
size: 36px;
x: (parent.width - self.width) / 2;
y: (parent.height - self.height) / 2;
}
}
// Error is the RAW string (NOT i18n-mapped, unlike the list view).
if !PurchaseDetailState.loading && PurchaseDetailState.load-error != "": Rectangle {
height: 200px;
Text {
text: PurchaseDetailState.load-error;
color: Theme.text-secondary;
font-size: Typography.body;
horizontal-alignment: center;
vertical-alignment: center;
x: (parent.width - self.width) / 2;
y: (parent.height - self.height) / 2;
}
}
// --- Loaded content ----------------------------------------------
if !PurchaseDetailState.loading
&& PurchaseDetailState.load-error == ""
&& PurchaseDetailState.loaded: VerticalLayout {
spacing: 0px;
alignment: start;
// ── Header ────────────────────────────────────────────────
HorizontalLayout {
spacing: 32px;
// 224×224 artwork. Unavailable → hide img + TriangleAlert
// overlay (§2.2.4).
Rectangle {
width: 224px;
height: 224px;
border-radius: 12px;
background: Theme.surface-elevated;
drop-shadow-blur: 32px;
drop-shadow-color: #00000080;
drop-shadow-offset-y: 8px;
clip: true;
if PurchaseDetailState.downloadable
&& PurchaseDetailState.artwork.width > 0: Image {
width: 100%;
height: 100%;
source: PurchaseDetailState.artwork;
image-fit: cover;
}
if PurchaseDetailState.downloadable
&& PurchaseDetailState.artwork.width == 0: QbzIcon {
source: @image-url("../assets/icons/music.svg");
width: 48px;
height: 48px;
x: (parent.width - self.width) / 2;
y: (parent.height - self.height) / 2;
tint: Theme.text-muted;
}
// Unavailable overlay (TriangleAlert + label).
if !PurchaseDetailState.downloadable: Rectangle {
background: Theme.surface-elevated;
VerticalLayout {
alignment: center;
spacing: 8px;
HorizontalLayout {
alignment: center;
QbzIcon {
source: @image-url("../assets/icons/triangle-alert.svg");
width: 18px;
height: 18px;
tint: Theme.text-muted;
}
}
Text {
text: @tr("Unavailable");
color: Theme.text-muted;
font-size: Typography.legal;
horizontal-alignment: center;
}
}
}
}
// Metadata column.
VerticalLayout {
alignment: start;
padding-top: 4px;
spacing: 0px;
horizontal-stretch: 1;
Text {
text: PurchaseDetailState.title;
color: Theme.text-primary;
font-size: Typography.section;
font-weight: Typography.bold;
overflow: elide;
}
Rectangle { height: 4px; }
// Artist — Svelte renders the clickable link whenever
// `onArtistClick` is present, and +page.svelte ALWAYS
// passes it (even for artist id 0). So always a link;
// open-artist gets the (possibly empty) id verbatim.
HorizontalLayout {
alignment: start;
artist-area := TouchArea {
width: artist-text.preferred-width;
height: artist-text.preferred-height;
mouse-cursor: pointer;
clicked => {
PurchaseDetailActions.open-artist(PurchaseDetailState.artist-id);
}
artist-text := Text {
text: PurchaseDetailState.artist;
color: artist-area.has-hover
? Theme.text-primary
: Theme.text-secondary;
font-size: Typography.heading;
font-weight: Typography.bold;
}
}
}
Rectangle { height: 10px; }
// Info line: purchasedOn + LONG-month date, then
// · label · genre (each conditional).
HorizontalLayout {
alignment: start;
spacing: 0px;
if PurchaseDetailState.purchased-on != "": Text {
text: @tr("Purchased on") + " " + PurchaseDetailState.purchased-on;
color: Theme.text-muted;
font-size: Typography.legal;
vertical-alignment: center;
}
if PurchaseDetailState.label-name != "": Text {
// 1:1 quirk (§gap): the leading middot before the
// label is emitted ONLY when purchased-on is
// present (Svelte `{#if album.purchased_at} &middot; {/if}`
// before the label, :262). With no purchased_at but
// a label, Svelte renders the label with NO leading
// dot — so drop it here too.
text: (PurchaseDetailState.purchased-on != "" ? " • " : "")
+ PurchaseDetailState.label-name;
color: Theme.text-muted;
font-size: Typography.legal;
vertical-alignment: center;
}
if PurchaseDetailState.genre-name != "": Text {
// Genre ALWAYS gets a leading middot (Svelte's
// `{#if album.genre} &middot; {genre} {/if}`, :265-266
// — unconditional), even with no purchased_at and
// no label.
text: " • " + PurchaseDetailState.genre-name;
color: Theme.text-muted;
font-size: Typography.legal;
vertical-alignment: center;
}
}
Rectangle { height: 6px; }
// Quality + stats line.
HorizontalLayout {
alignment: start;
spacing: 0px;
if PurchaseDetailState.quality != "": Text {
text: PurchaseDetailState.quality;
color: Theme.accent;
font-size: Typography.legal;
font-weight: Typography.semibold;
vertical-alignment: center;
}
}
Rectangle { height: 4px; }
Text {
// "{count} tracks · {duration}". Svelte uses
// `purchases.tracksCount` with `{count}` interpolation;
// preserve the placeholder via Slint's `@tr("{} …", n)`
// so the Slice-13 catalog can back it (§8.5).
text: @tr("{} tracks", PurchaseDetailState.total-tracks)
+ " • "
+ PurchaseDetailState.total-duration;
color: Theme.text-muted;
font-size: Typography.legal;
}
// ── Actions row (only if downloadable) ────────────
if PurchaseDetailState.downloadable: VerticalLayout {
Rectangle { height: 20px; }
HorizontalLayout {
alignment: start;
spacing: 12px;
// Play-album circle.
if PurchaseDetailState.show-play: CircleAction {
icon: @image-url("../assets/icons/play-fill.svg");
primary: true;
tooltip: @tr("Play");
clicked => { PurchaseDetailActions.play-album(); }
}
// Download-all circle. `.primary` only when no
// play button. Spinner while downloading-all.
VerticalLayout {
alignment: center;
CircleAction {
icon: @image-url("../assets/icons/download.svg");
primary: !PurchaseDetailState.show-play;
loading: PurchaseDetailState.is-downloading-all;
enabled: PurchaseDetailState.can-download-all;
tooltip: @tr("Download all");
clicked => { PurchaseDetailActions.download-all(); }
}
}
// Format dropdown (only when formats exist).
if PurchaseDetailState.has-formats: VerticalLayout {
alignment: center;
QbzSelect {
options: PurchaseDetailState.format-labels;
current-index: PurchaseDetailState.format-index;
sm: true;
menu-width: 220px;
selected(i) => {
PurchaseDetailActions.select-format(i);
}
}
}
}
}
}
}
// ── Progress section (downloadingAll || allComplete ||
// wasCancelled) ──────────────────────────────────────────
if PurchaseDetailState.show-progress: VerticalLayout {
Rectangle { height: 24px; }
HorizontalLayout {
alignment: start;
spacing: 8px;
// allComplete → Check + complete.
if PurchaseDetailState.all-complete: QbzIcon {
source: @image-url("../assets/icons/check.svg");
width: 14px;
height: 14px;
tint: Theme.success;
}
if PurchaseDetailState.all-complete: Text {
text: @tr("Download complete");
color: Theme.text-secondary;
font-size: Typography.legal;
vertical-alignment: center;
}
// wasCancelled → X + "Cancelled ({completed}/{total})".
if !PurchaseDetailState.all-complete
&& PurchaseDetailState.was-cancelled: QbzIcon {
source: @image-url("../assets/icons/x.svg");
width: 14px;
height: 14px;
tint: Theme.text-muted;
}
if !PurchaseDetailState.all-complete
&& PurchaseDetailState.was-cancelled: Text {
text: @tr("Download cancelled") + " ("
+ PurchaseDetailState.completed-count + "/"
+ PurchaseDetailState.total-tracks + ")";
color: Theme.text-secondary;
font-size: Typography.legal;
vertical-alignment: center;
}
// downloading → spinner + "Downloading {current}/{total}"
// + cancel button.
if !PurchaseDetailState.all-complete
&& !PurchaseDetailState.was-cancelled: LoadingSpinner { size: 14px; }
if !PurchaseDetailState.all-complete
&& !PurchaseDetailState.was-cancelled: Text {
text: @tr("Downloading") + " "
+ PurchaseDetailState.completed-count + "/"
+ PurchaseDetailState.total-tracks;
color: Theme.text-secondary;
font-size: Typography.legal;
vertical-alignment: center;
}
if !PurchaseDetailState.all-complete
&& !PurchaseDetailState.was-cancelled: Rectangle {
width: 8px;
}
if !PurchaseDetailState.all-complete
&& !PurchaseDetailState.was-cancelled: cancel-btn := Rectangle {
height: 26px;
border-radius: 6px;
background: cancel-ta.has-hover ? Theme.surface-hover : Theme.surface-elevated;
HorizontalLayout {
padding-left: 8px;
padding-right: 10px;
spacing: 4px;
VerticalLayout {
alignment: center;
QbzIcon {
source: @image-url("../assets/icons/x.svg");
width: 12px;
height: 12px;
tint: Theme.text-secondary;
}
}
Text {
text: @tr("Cancel");
color: Theme.text-secondary;
font-size: Typography.legal;
vertical-alignment: center;
}
}
cancel-ta := TouchArea {
mouse-cursor: pointer;
clicked => { PurchaseDetailActions.cancel-download(); }
}
}
}
Rectangle { height: 8px; }
// Progress bar — fill = completedCount/totalTracks*100 (NOT
// format-scoped, §A.4); classes complete/cancelled.
Rectangle {
height: 4px;
border-radius: 2px;
background: Theme.surface-elevated;
clip: true;
Rectangle {
x: 0;
width: parent.width * (PurchaseDetailState.progress-percent / 100);
height: parent.height;
border-radius: 2px;
background: PurchaseDetailState.all-complete
? Theme.success
: (PurchaseDetailState.was-cancelled
? Theme.text-muted
: Theme.accent);
}
}
}
// ── Add-to-Library block (allComplete && destination) ─────
if PurchaseDetailState.show-add-to-library: VerticalLayout {
Rectangle { height: 20px; }
Rectangle {
height: 64px;
border-radius: 8px;
border-width: 1px;
border-color: Theme.success;
background: Theme.alpha-10;
HorizontalLayout {
padding-left: 16px;
padding-right: 16px;
spacing: 16px;
// DOM order matches Svelte `.add-to-library`
// (display:flex): [button] then [desc].
// Button (LEFT).
VerticalLayout {
alignment: center;
add-btn := Rectangle {
height: 34px;
width: 160px;
border-radius: 6px;
// Svelte `.add-to-library-btn` is
// `background: var(--success)` GREEN; hover
// is `opacity: 0.9` (no color change).
background: Theme.success;
opacity: PurchaseDetailState.adding-to-library
? 0.6
: (add-ta.has-hover ? 0.9 : 1.0);
HorizontalLayout {
alignment: center;
spacing: 6px;
VerticalLayout {
alignment: center;
if PurchaseDetailState.adding-to-library: LoadingSpinner {
size: 14px;
}
if !PurchaseDetailState.adding-to-library: QbzIcon {
source: @image-url("../assets/icons/library.svg");
width: 14px;
height: 14px;
tint: white;
}
}
Text {
text: @tr("Add to library");
color: white;
font-size: Typography.legal;
font-weight: Typography.semibold;
vertical-alignment: center;
}
}
add-ta := TouchArea {
enabled: !PurchaseDetailState.adding-to-library;
mouse-cursor: pointer;
clicked => { PurchaseDetailActions.add-to-library(); }
}
}
}
// Description (RIGHT). Single span — the "Add to
// library" label exists ONLY on the button in Svelte.
VerticalLayout {
alignment: center;
horizontal-stretch: 1;
Text {
text: @tr("Add these downloaded tracks to your local library.");
color: Theme.text-muted;
font-size: Typography.legal;
overflow: elide;
}
}
}
}
}
// ── Divider ───────────────────────────────────────────────
Rectangle { height: 24px; }
Rectangle { height: 1px; background: Theme.border-subtle; }
Rectangle { height: 12px; }
// ── Track table ───────────────────────────────────────────
VerticalLayout {
spacing: 0px;
// Header row: # | title | duration | quality | <Download>.
Rectangle {
height: 32px;
HorizontalLayout {
padding-left: 12px;
padding-right: 12px;
spacing: 12px;
Text {
text: "#";
width: 28px;
color: Theme.text-muted;
font-size: Typography.legal;
horizontal-alignment: center;
vertical-alignment: center;
}
Text {
text: @tr("Title");
horizontal-stretch: 1;
color: Theme.text-muted;
font-size: Typography.legal;
vertical-alignment: center;
}
Text {
text: @tr("Duration");
width: 44px;
color: Theme.text-muted;
font-size: Typography.legal;
horizontal-alignment: right;
vertical-alignment: center;
}
Text {
text: @tr("Quality");
width: 64px;
color: Theme.text-muted;
font-size: Typography.legal;
horizontal-alignment: right;
vertical-alignment: center;
}
VerticalLayout {
alignment: center;
width: 32px;
HorizontalLayout {
alignment: center;
QbzIcon {
source: @image-url("../assets/icons/download.svg");
width: 14px;
height: 14px;
tint: Theme.text-muted;
}
}
}
}
}
// Each row, preceded by a "Disc N" divider when the model
// marks it (multi-disc only; single-disc → header-number 0
// never fires → flat list). Mirrors groupByDisc + isMultiDisc.
for track[index] in PurchaseDetailState.tracks: VerticalLayout {
spacing: 0px;
if track.disc-header-number > 0: Rectangle {
height: 40px;
HorizontalLayout {
padding-left: 12px;
padding-right: 12px;
Text {
text: @tr("Disc") + " \{track.disc-header-number}";
color: Theme.text-muted;
font-size: Typography.legal;
font-weight: 600;
letter-spacing: 0.5px;
vertical-alignment: center;
horizontal-alignment: left;
horizontal-stretch: 1;
}
}
}
DetailTrackRow {
track: track;
active: PurchaseDetailState.active-track-id == track.id;
playing: PurchaseDetailState.playback-active
&& PurchaseDetailState.active-track-id == track.id;
play => {
PurchaseDetailActions.play-track(track.id);
}
download => {
PurchaseDetailActions.download-track(track.id);
}
}
}
}
}
}
}
}
+13 -2
View File
@@ -8,7 +8,7 @@
import { Theme } from "../foundation/semantic-colors.slint";
import { Layout } from "../foundation/layout.slint";
import { Radius } from "../foundation/radius.slint";
import { NavState, ContentView, ShellState, OfflineState, PlaylistState, ImmersiveState, SearchActions, VisualizerState } from "../state.slint";
import { NavState, ContentView, ShellState, OfflineState, PlaylistState, ImmersiveState, SearchActions, VisualizerState, PurchaseDetailState } from "../state.slint";
import { Sidebar } from "Sidebar.slint";
import { SidebarNowPlayingDock } from "SidebarNowPlayingDock.slint";
import { HeaderBar } from "HeaderBar.slint";
@@ -57,6 +57,7 @@ import { LabelPageView } from "../label/LabelPageView.slint";
import { AwardView } from "../award/AwardView.slint";
import { AwardAlbumsView } from "../award/AwardAlbumsView.slint";
import { PurchasesView } from "../purchases/PurchasesView.slint";
import { PurchaseDetailView } from "../purchases/PurchaseDetailView.slint";
import { ArtistsByLocationView } from "../location/ArtistsByLocationView.slint";
import { FavoritesView } from "../favorites/FavoritesView.slint";
import { FavoritesOfflineRail } from "../favorites/FavoritesOfflineRail.slint";
@@ -78,6 +79,7 @@ import { Cortinilla } from "../search/Cortinilla.slint";
export component AppShell inherits Rectangle {
callback open-album(string);
callback open-artist(string);
callback open-purchase-album(string);
callback media-action(string, string, string);
callback header-menu-navigate(string);
callback discover-view-all(string, string);
@@ -110,6 +112,7 @@ export component AppShell inherits Rectangle {
|| NavState.view == ContentView.award
|| NavState.view == ContentView.award-albums
|| NavState.view == ContentView.purchases
|| NavState.view == ContentView.purchase-album
|| NavState.view == ContentView.location
|| NavState.view == ContentView.mix
// Playlist: LOCAL playlists and the offline sidecar rendering of a
@@ -373,8 +376,10 @@ export component AppShell inherits Rectangle {
}
}
if NavState.view == ContentView.purchases && !OfflineState.offline: PurchasesView {
// A grid/list card click opens the purchase DETAIL view
// (Slice 11 adds nav-history + persistence on top).
open-album(id) => {
root.open-album(id);
root.open-purchase-album(id);
}
open-artist(id) => {
root.open-artist(id);
@@ -383,6 +388,12 @@ export component AppShell inherits Rectangle {
root.media-action(kind, id, action);
}
}
// Detail mounts ONLY with a non-empty selected id (ADR-010
// conditional-mount guard; the controller seeds the id before
// navigating, and the view's `changed album-id` fires the load).
if NavState.view == ContentView.purchase-album
&& !OfflineState.offline
&& PurchaseDetailState.album-id != "": PurchaseDetailView { }
if NavState.view == ContentView.playlist-manager: PlaylistManagerView { }
if NavState.view == ContentView.mixtapes: MixtapesView { }
if NavState.view == ContentView.collections: CollectionsView { }
+103
View File
@@ -4450,6 +4450,109 @@ export global PurchasesActions {
callback retry();
}
// ── Purchase detail / download view (source-of-truth §2.2) ──────────────────
// One row in the detail track table. Mirrors the bespoke Tauri detail row
// (§2.2.5): bare "{bit}/{rate}" quality (§A.6), a 4-state download control, and
// disc grouping. `disc-header-number` > 0 marks the FIRST track of a disc on a
// multi-disc album so a "Disc N" divider renders above it (the AlbumPageView
// disc-header-number mechanism); 0 otherwise (single-disc → flat).
//
// `dl-status` is the format-scoped per-track status ("" | downloading |
// complete | failed) from `track_status_scoped`. `is-downloaded` is the row's
// derived green-check state (server `downloaded_format_ids` for the selected
// format OR a store `complete`). `show-download` gates whether ANY download
// control renders (album downloadable OR already downloaded, §2.2.5).
export struct PurchaseDetailTrack {
id: string,
track-number: int,
title: string,
performer: string, // shown on a 2nd line when ≠ album artist
show-performer: bool,
duration: string, // "m:ss"
quality: string, // BARE "{bit}/{rate}" (§A.6); "" if either missing
streamable: bool,
dl-status: string, // "" | downloading | complete | failed (format-scoped)
is-downloaded: bool, // green redownload check
show-download: bool, // album.downloadable || is-downloaded
disc-header-number: int, // > 0 → "Disc N" header above this row (multi-disc)
}
export global PurchaseDetailState {
// Bound album id. The view watches this and fires `load` on change so a
// navigation between two different purchase albums RE-FETCHES (§A.3); the
// controller seeds it before navigating. Empty → nothing to render.
in-out property <string> album-id: "";
// Content state. `load-error` is the RAW error string (NOT i18n-mapped,
// unlike the list view — §2.2.4 / §8.4).
in property <bool> loading: true;
in property <string> load-error: "";
in property <bool> loaded: false;
// Header.
in property <string> title: "";
in property <string> artist: "";
in property <string> artist-id: ""; // "" → artist is plain text (no link)
in property <string> artwork-url: "";
in property <image> artwork;
in property <bool> downloadable: true; // !downloadable → header overlay + no actions
in property <string> purchased-on: ""; // LONG-month "November 6, 2025" ("" hides)
in property <string> label-name: ""; // "" hides the "· label" segment
in property <string> genre-name: ""; // "" hides the "· genre" segment
in property <string> quality: ""; // formatQuality "24bit/96kHz" | "CD Quality"
in property <int> total-tracks: 0;
in property <string> total-duration: ""; // "{h}h {m}m" | "{m}m"
// Format dropdown. `format-labels` are the backend fmt.label strings (NOT
// an i18n key); `format-index` is the currently-selected option (default 0).
in property <[string]> format-labels: [];
in property <int> format-index: 0;
in property <bool> has-formats: false;
// Download progress (source-of-truth §2.2.1 / §A.4). `all-complete` IS
// format-scoped; `completed-count` / `progress-percent` / `was-cancelled`
// are NOT (count ALL statuses regardless of selected format).
in property <bool> is-downloading-all: false;
in property <bool> all-complete: false; // format-scoped
in property <bool> was-cancelled: false; // NOT format-scoped
in property <int> completed-count: 0; // NOT format-scoped
in property <float> progress-percent: 0; // completed/total*100, NOT format-scoped
// Whether the progress section renders at all (downloadingAll || allComplete
// || wasCancelled) — precomputed in Rust to keep the .slint declarative.
in property <bool> show-progress: false;
// Add-to-Library block (only when all-complete && a destination is set).
in property <bool> show-add-to-library: false;
in property <bool> adding-to-library: false;
// Download-all circle gating: disabled while downloading-all OR no format.
in property <bool> can-download-all: false;
// Whether the Play-album circle renders (onAlbumPlay present — always true
// in Slint since play routing exists; kept as a flag for parity).
in property <bool> show-play: true;
// Active/playing track for row highlight + playing-bars.
in property <string> active-track-id: "";
in property <bool> playback-active: false;
// The disc-grouped track rows (already flattened with disc-header markers in
// Rust). The view iterates this once.
in property <[PurchaseDetailTrack]> tracks: [];
}
export global PurchaseDetailActions {
// Reactive reload: the view fires this whenever the bound `album-id`
// changes (and on first mount) so a fresh load runs (§A.3).
callback load(string /* album id */);
// Header / navigation.
callback open-artist(string /* artist id */);
callback play-album(); // Play-album circle (§A.1, routing in Slice 10)
callback play-track(string /* track id */); // per-track row play (§A.2)
// Format dropdown — a new option chosen (index into format-labels).
callback select-format(int /* index */);
// Download-all circle → folder picker → startAlbumDownload.
callback download-all();
// Per-track download → folder picker → startTrackDownload.
callback download-track(string /* track id */);
// Progress section cancel button.
callback cancel-download();
// Add-to-Library block button.
callback add-to-library();
}
// A Qobuz mix detail page (DailyQ / WeeklyQ / FavQ / TopQ), opened
// from the For You Qobuz Mixes tiles. Populated by crate::mix. Rows
// reuse the shared SearchTrackRow (with show-album), so the track