Kotlin, Compose for TV and Media3 port of the desktop Musyx, with device-code sign-in, Home, My Wave, search, collection, detail pages, Now Playing with queue and lyrics, and settings for streaming quality, appearance, font size (small, medium, large) and language. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
409 lines
14 KiB
Rust
409 lines
14 KiB
Rust
//! Collection: liked tracks, albums, artists, playlists (own and liked) and clips.
|
|
|
|
use std::collections::HashSet;
|
|
use std::sync::Arc;
|
|
|
|
use iced::widget::{button, column, container, row, space};
|
|
use iced::{Alignment, Element, Fill};
|
|
use ym_api::{AlbumSummary, ArtistSummary, Clip, Error, LibraryPlaylists, PlaylistSummary, Track};
|
|
|
|
use super::Loadable;
|
|
use crate::app::Message;
|
|
use crate::covers::{self, Covers};
|
|
use crate::route::Route;
|
|
use crate::ui::icons::{Icon, icon};
|
|
use crate::ui::theme::{self, Tokens, size};
|
|
use crate::ui::{duration_words, line, para, tracks_word};
|
|
use crate::widgets::card::{self, Card};
|
|
use crate::widgets::track_list::{self, Env};
|
|
use crate::widgets::track_row::Columns;
|
|
use crate::i18n::{tr, trf};
|
|
|
|
/// The liked-tracks list as the app holds it. Also answers "is this track liked?".
|
|
#[derive(Debug, Default)]
|
|
pub enum Liked {
|
|
#[default]
|
|
NotLoaded,
|
|
Loading,
|
|
Loaded {
|
|
tracks: Arc<[Track]>,
|
|
ids: HashSet<String>,
|
|
/// Bumped on every reload so cached rows rebuild.
|
|
version: u64,
|
|
},
|
|
Failed(Error),
|
|
}
|
|
|
|
impl Liked {
|
|
pub fn loaded(tracks: Vec<Track>, previous: &Liked) -> Self {
|
|
let version = previous.version() + 1;
|
|
let ids = tracks.iter().map(|t| t.id.clone()).collect();
|
|
Liked::Loaded { tracks: tracks.into(), ids, version }
|
|
}
|
|
|
|
/// A copy with `track` liked (at the top, like Yandex lists it) or unliked.
|
|
/// Not loaded yet: unchanged, the next load has it.
|
|
pub fn with(&self, track: &Track, liked: bool) -> Liked {
|
|
let Liked::Loaded { tracks, ids, version } = self else {
|
|
return match self {
|
|
Liked::Failed(e) => Liked::Failed(e.clone()),
|
|
Liked::Loading => Liked::Loading,
|
|
_ => Liked::NotLoaded,
|
|
};
|
|
};
|
|
if ids.contains(&track.id) == liked {
|
|
return Liked::Loaded { tracks: tracks.clone(), ids: ids.clone(), version: *version };
|
|
}
|
|
let list: Vec<Track> = if liked {
|
|
std::iter::once(track.clone()).chain(tracks.iter().cloned()).collect()
|
|
} else {
|
|
tracks.iter().filter(|t| t.id != track.id).cloned().collect()
|
|
};
|
|
let ids = list.iter().map(|t| t.id.clone()).collect();
|
|
Liked::Loaded { tracks: list.into(), ids, version: version + 1 }
|
|
}
|
|
|
|
pub fn contains(&self, track_id: &str) -> bool {
|
|
matches!(self, Liked::Loaded { ids, .. } if ids.contains(track_id))
|
|
}
|
|
|
|
pub fn tracks(&self) -> Option<&Arc<[Track]>> {
|
|
match self {
|
|
Liked::Loaded { tracks, .. } => Some(tracks),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
pub fn version(&self) -> u64 {
|
|
match self {
|
|
Liked::Loaded { version, .. } => *version,
|
|
_ => 0,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
|
pub enum Tab {
|
|
#[default]
|
|
Tracks,
|
|
Albums,
|
|
Artists,
|
|
Playlists,
|
|
Clips,
|
|
}
|
|
|
|
impl Tab {
|
|
const ALL: [Tab; 5] = [Tab::Tracks, Tab::Albums, Tab::Artists, Tab::Playlists, Tab::Clips];
|
|
|
|
fn label(self) -> &'static str {
|
|
match self {
|
|
Tab::Tracks => tr("Liked tracks"),
|
|
Tab::Albums => tr("Albums"),
|
|
Tab::Artists => tr("Artists"),
|
|
Tab::Playlists => tr("Playlists"),
|
|
Tab::Clips => tr("Clips"),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Everything Collection shows. Parts load on first visit to their tab.
|
|
#[derive(Debug, Default)]
|
|
pub struct Library {
|
|
pub tab: Tab,
|
|
pub liked: Liked,
|
|
pub albums: Loadable<Vec<AlbumSummary>>,
|
|
pub artists: Loadable<Vec<ArtistSummary>>,
|
|
pub playlists: Loadable<LibraryPlaylists>,
|
|
pub clips: Loadable<Vec<Clip>>,
|
|
}
|
|
|
|
impl Library {
|
|
fn count(&self, tab: Tab) -> Option<usize> {
|
|
match tab {
|
|
Tab::Tracks => self.liked.tracks().map(|t| t.len()),
|
|
Tab::Albums => self.albums.get().map(Vec::len),
|
|
Tab::Artists => self.artists.get().map(Vec::len),
|
|
Tab::Playlists => self.playlists.get().map(|p| p.own.len() + p.liked.len()),
|
|
Tab::Clips => self.clips.get().map(Vec::len),
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn view<'a>(env: Env<'a>, library: &'a Library) -> Element<'a, Message> {
|
|
let t = env.t;
|
|
let tabs = row(Tab::ALL.map(|tab| tab_button(t, tab, library))).spacing(4);
|
|
|
|
let body: Element<'a, Message> = match library.tab {
|
|
Tab::Tracks => liked_tracks(env, &library.liked),
|
|
Tab::Albums => match &library.albums {
|
|
Loadable::Loaded(albums) if albums.is_empty() => {
|
|
empty(t, tr("No liked albums yet. Like an album and it lands here."))
|
|
}
|
|
Loadable::Loaded(albums) => card::grid(albums.iter().map(|a| album_card(t, env.covers, a))),
|
|
other => status(t, other.state(), tr("your albums"), Message::LoadLibrary(Tab::Albums)),
|
|
},
|
|
Tab::Artists => match &library.artists {
|
|
Loadable::Loaded(artists) if artists.is_empty() => {
|
|
empty(t, tr("No liked artists yet. Like an artist and they land here."))
|
|
}
|
|
Loadable::Loaded(artists) => card::grid(artists.iter().map(|a| artist_card(t, env.covers, a))),
|
|
other => status(t, other.state(), tr("your artists"), Message::LoadLibrary(Tab::Artists)),
|
|
},
|
|
Tab::Playlists => match &library.playlists {
|
|
Loadable::Loaded(p) if p.own.is_empty() && p.liked.is_empty() => {
|
|
empty(t, tr("No playlists yet. Playlists you make or like show up here."))
|
|
}
|
|
Loadable::Loaded(p) => {
|
|
let mut sections = column![].spacing(28);
|
|
if !p.own.is_empty() {
|
|
sections = sections.push(section(
|
|
t,
|
|
tr("Your playlists"),
|
|
p.own.iter().map(|pl| playlist_card(t, env.covers, pl)),
|
|
));
|
|
}
|
|
if !p.liked.is_empty() {
|
|
sections = sections.push(section(
|
|
t,
|
|
tr("Liked playlists"),
|
|
p.liked.iter().map(|pl| playlist_card(t, env.covers, pl)),
|
|
));
|
|
}
|
|
sections.into()
|
|
}
|
|
other => status(t, other.state(), tr("your playlists"), Message::LoadLibrary(Tab::Playlists)),
|
|
},
|
|
Tab::Clips => match &library.clips {
|
|
Loadable::Loaded(clips) if clips.is_empty() => {
|
|
empty(t, tr("No liked clips yet. Like a clip on an artist's page and it lands here."))
|
|
}
|
|
Loadable::Loaded(clips) => card::grid(clips.iter().map(|c| clip_card(env, c))),
|
|
other => status(t, other.state(), tr("your clips"), Message::LoadLibrary(Tab::Clips)),
|
|
},
|
|
};
|
|
|
|
column![line(tr("Collection"), theme::DISPLAY, size::DISPLAY_S, t.fg), tabs, body]
|
|
.spacing(24)
|
|
.width(Fill)
|
|
.into()
|
|
}
|
|
|
|
fn tab_button<'a>(t: &'static Tokens, tab: Tab, library: &Library) -> Element<'a, Message> {
|
|
let on = library.tab == tab;
|
|
let mut label = row![line(tab.label(), theme::MEDIUM, size::BODY, if on { t.fg } else { t.muted })]
|
|
.spacing(6)
|
|
.align_y(Alignment::Center);
|
|
if let Some(n) = library.count(tab) {
|
|
label = label.push(line(n.to_string(), theme::BODY, size::SMALL, t.muted));
|
|
}
|
|
button(
|
|
column![label, container(space()).width(Fill).height(2).style(theme::tab_underline(on))]
|
|
.spacing(7)
|
|
.width(iced::Shrink),
|
|
)
|
|
.padding([6, 10])
|
|
.style(theme::tab(on))
|
|
.on_press(Message::CollectionTab(tab))
|
|
.into()
|
|
}
|
|
|
|
fn liked_tracks<'a>(env: Env<'a>, liked: &'a Liked) -> Element<'a, Message> {
|
|
let t = env.t;
|
|
match liked {
|
|
Liked::NotLoaded | Liked::Loading => para(tr("Loading your liked tracks…"), size::BODY, t.muted).into(),
|
|
Liked::Failed(e) => status(t, LoadState::Failed(e), tr("your liked tracks"), Message::LoadLiked),
|
|
Liked::Loaded { tracks, .. } if tracks.is_empty() => {
|
|
empty(t, tr("No liked tracks yet. Tap the heart on any track and it lands here."))
|
|
}
|
|
Liked::Loaded { tracks, .. } => {
|
|
let total = tracks.iter().map(|t| t.duration).sum();
|
|
column![
|
|
play_bar(t, format!("{} · {}", tracks_word(tracks.len()), duration_words(total)), tracks),
|
|
track_list::view(env, tracks, Columns::FULL),
|
|
]
|
|
.spacing(22)
|
|
.into()
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Play and Shuffle buttons with a summary on the left. Shared by every page with tracks.
|
|
pub fn play_bar<'a>(t: &'static Tokens, summary: String, tracks: &Arc<[Track]>) -> Element<'a, Message> {
|
|
let has_tracks = !tracks.is_empty();
|
|
let pill = |glyph: Icon,
|
|
label: &'static str,
|
|
ink,
|
|
style: fn(&iced::Theme, button::Status) -> button::Style,
|
|
msg| {
|
|
button(
|
|
row![icon(glyph, ink), line(label, theme::SEMIBOLD, size::BODY, ink)]
|
|
.spacing(8)
|
|
.align_y(Alignment::Center),
|
|
)
|
|
.padding([10, 18])
|
|
.style(style)
|
|
.on_press_maybe(has_tracks.then_some(msg))
|
|
};
|
|
row![
|
|
container(line(summary, theme::BODY, size::META, t.muted)).width(Fill),
|
|
pill(
|
|
Icon::Play,
|
|
tr("Play"),
|
|
t.accent_ink,
|
|
theme::primary,
|
|
Message::PlayTracks { tracks: tracks.clone(), start: 0, shuffle: false },
|
|
),
|
|
pill(
|
|
Icon::Shuffle,
|
|
tr("Shuffle"),
|
|
t.fg,
|
|
theme::ghost,
|
|
Message::PlayTracks { tracks: tracks.clone(), start: 0, shuffle: true },
|
|
),
|
|
]
|
|
.spacing(10)
|
|
.align_y(Alignment::Center)
|
|
.into()
|
|
}
|
|
|
|
pub fn album_card<'a>(t: &'static Tokens, covers: &Covers, a: &AlbumSummary) -> Element<'a, Message> {
|
|
card::view(
|
|
t,
|
|
covers,
|
|
Card {
|
|
title: a.full_title(),
|
|
subtitle: a.subtitle(),
|
|
cover: a.cover_url(covers::LARGE),
|
|
hues: a.hues(),
|
|
round: false,
|
|
on_press: Message::Navigate(Route::Album(a.id)),
|
|
},
|
|
)
|
|
}
|
|
|
|
pub fn artist_card<'a>(t: &'static Tokens, covers: &Covers, a: &ArtistSummary) -> Element<'a, Message> {
|
|
card::view(
|
|
t,
|
|
covers,
|
|
Card {
|
|
title: a.name.clone(),
|
|
subtitle: a.genres.first().cloned().unwrap_or_else(|| tr("Artist").into()),
|
|
cover: a.cover_url(covers::LARGE),
|
|
hues: a.hues(),
|
|
round: true,
|
|
on_press: Message::Navigate(Route::Artist(a.id)),
|
|
},
|
|
)
|
|
}
|
|
|
|
pub fn playlist_card<'a>(t: &'static Tokens, covers: &Covers, p: &PlaylistSummary) -> Element<'a, Message> {
|
|
card::view(
|
|
t,
|
|
covers,
|
|
Card {
|
|
title: p.title.clone(),
|
|
subtitle: p.subtitle(),
|
|
cover: p.cover_url(covers::LARGE),
|
|
hues: p.hues(),
|
|
round: false,
|
|
on_press: Message::Navigate(Route::Playlist(p.id)),
|
|
},
|
|
)
|
|
}
|
|
|
|
/// A music video. It opens in the browser; the heart likes it.
|
|
pub fn clip_card<'a>(env: Env<'_>, c: &Clip) -> Element<'a, Message> {
|
|
let liked = env.likes.clips.contains(&c.id);
|
|
let length = crate::widgets::player_bar::clock(c.duration.as_secs_f32());
|
|
card::with_like(
|
|
env.t,
|
|
env.covers,
|
|
Card {
|
|
title: c.title.clone(),
|
|
subtitle: format!("{} · {length}", c.artist_line()),
|
|
cover: c.cover_url(covers::LARGE),
|
|
hues: c.hues(),
|
|
round: false,
|
|
on_press: Message::OpenClip(c.clone()),
|
|
},
|
|
liked,
|
|
Message::LikeClip(c.clone(), !liked),
|
|
)
|
|
}
|
|
|
|
pub fn section<'a>(
|
|
t: &'static Tokens,
|
|
heading: &'a str,
|
|
cards: impl IntoIterator<Item = Element<'a, Message>>,
|
|
) -> Element<'a, Message> {
|
|
column![line(heading, theme::SEMIBOLD, size::SECTION, t.fg), card::grid(cards)]
|
|
.spacing(14)
|
|
.into()
|
|
}
|
|
|
|
pub enum LoadState<'a> {
|
|
Loading,
|
|
Failed(&'a Error),
|
|
}
|
|
|
|
/// Loading text, or a failure with a retry button. `what` is the object of
|
|
/// "Loading …" and "Couldn't load …", such as "your albums".
|
|
pub fn status<'a>(t: &'static Tokens, state: LoadState<'_>, what: &str, retry: Message) -> Element<'a, Message> {
|
|
match state {
|
|
LoadState::Loading => para(trf("Loading {}…", &[&what]), size::BODY, t.muted).into(),
|
|
LoadState::Failed(e) => column![
|
|
para(
|
|
match e {
|
|
Error::Network(_) => {
|
|
trf("Couldn't load {}. Check your connection and try again.", &[&what])
|
|
}
|
|
_ => trf("Couldn't load {}. Try again in a moment.", &[&what]),
|
|
},
|
|
size::BODY,
|
|
t.muted,
|
|
),
|
|
button(line(tr("Try again"), theme::SEMIBOLD, size::BODY, t.accent_ink))
|
|
.padding([11, 18])
|
|
.style(theme::primary)
|
|
.on_press(retry),
|
|
]
|
|
.spacing(16)
|
|
.into(),
|
|
}
|
|
}
|
|
|
|
fn empty<'a>(t: &'static Tokens, text: &'static str) -> Element<'a, Message> {
|
|
para(text, size::BODY, t.muted).into()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn track(id: &str) -> Track {
|
|
Track::from_json(&format!(r#"{{"id":"{id}","title":"T"}}"#)).unwrap()
|
|
}
|
|
|
|
#[test]
|
|
fn reload_bumps_version_and_indexes_ids() {
|
|
let first = Liked::loaded(vec![track("1"), track("2")], &Liked::Loading);
|
|
assert!(first.contains("2") && !first.contains("3"));
|
|
assert_eq!(first.version(), 1);
|
|
let second = Liked::loaded(vec![track("3")], &first);
|
|
assert_eq!(second.version(), 2);
|
|
assert!(!Liked::Failed(Error::Denied).contains("1"));
|
|
}
|
|
|
|
#[test]
|
|
fn with_adds_on_top_and_removes() {
|
|
let base = Liked::loaded(vec![track("1"), track("2")], &Liked::Loading);
|
|
let added = base.with(&track("3"), true);
|
|
assert_eq!(added.tracks().unwrap()[0].id, "3");
|
|
assert!(added.version() > base.version());
|
|
let removed = added.with(&track("1"), false);
|
|
assert!(!removed.contains("1") && removed.contains("2"));
|
|
assert_eq!(removed.with(&track("2"), true).version(), removed.version(), "no-op keeps the cache");
|
|
assert!(matches!(Liked::NotLoaded.with(&track("9"), true), Liked::NotLoaded));
|
|
}
|
|
}
|