Musyx Mobile: Android TV player for Yandex Music

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>
This commit is contained in:
yuriy.pandClaude Opus 5.5 committed 2026-10-16 22:14:54 +06:00
commit 46610d95fa
217 files changed
+26144

No files matched your search

+363
View File
@@ -0,0 +1,363 @@
//! Discovery: Home, the chart, genres and podcasts.
use std::sync::Arc;
use iced::widget::{Row, button, column, container, row};
use iced::{Alignment, Color, Element, Fill};
use ym_api::{AlbumKind, AlbumSummary, ChartEntry, Genre, Home, PlaylistSummary, Track};
use super::Loadable;
use super::collection::{LoadState, album_card, play_bar, playlist_card, section, status};
use crate::app::Message;
use crate::covers;
use crate::route::Route;
use crate::ui::theme::{self, Tokens, radius, size};
use crate::ui::{line, para};
use crate::widgets::card::{self, Card};
use crate::widgets::track_list::{self, Env};
use crate::widgets::track_row::Columns;
use crate::i18n::{tr, trf};
/// Chart rows shown on Home before "Show all".
const HOME_CHART: usize = 10;
/// Cards per Home row.
const HOME_CARDS: usize = 12;
/// Tracks in Home's "Recently played".
pub const RECENT: usize = 10;
/// Home data with the chart split out as a playable list.
#[derive(Debug)]
pub struct HomeData {
pub home: Home,
pub chart: Arc<[Track]>,
pub shifts: Arc<[i32]>,
/// The first rows of the chart for Home, built once so the cached list stays valid.
top: Arc<[Track]>,
top_shifts: Arc<[i32]>,
}
impl HomeData {
pub fn new(mut home: Home) -> Self {
let entries = std::mem::take(&mut home.chart);
let (chart, shifts): (Vec<Track>, Vec<i32>) =
entries.into_iter().map(|ChartEntry { track, shift, .. }| (track, shift)).unzip();
let top = chart.iter().take(HOME_CHART).cloned().collect();
let top_shifts = shifts.iter().take(HOME_CHART).copied().collect();
Self { home, chart: chart.into(), shifts: shifts.into(), top, top_shifts }
}
}
/// Everything the discovery screens show. Each part loads on first visit.
#[derive(Debug, Default)]
pub struct Discover {
pub home: Loadable<HomeData>,
/// Top-level genres followed by their sub-genres, so a `Route::Genre` index finds either.
pub genres: Loadable<Vec<Genre>>,
pub podcasts: Loadable<Vec<AlbumSummary>>,
/// The last tracks played on any device. Reloaded on every visit to Home.
pub recent: Loadable<Arc<[Track]>>,
}
/// Top-level genres first, then every sub-genre, each once.
pub fn flatten(genres: Vec<Genre>) -> Vec<Genre> {
let mut flat: Vec<Genre> = genres.clone();
for g in genres {
for sub in g.sub_genres {
if !flat.iter().any(|f| f.id == sub.id) {
flat.push(sub);
}
}
}
flat
}
pub fn home<'a>(env: Env<'a>, discover: &'a Discover, hero: Element<'a, Message>) -> Element<'a, Message> {
let t = env.t;
let covers = env.covers;
let mut page = column![hero].spacing(34);
// Only worth a section when it has something; a failure stays in the log.
if let Loadable::Loaded(recent) = &discover.recent
&& !recent.is_empty()
{
page = page.push(
column![
line(tr("Recently played"), theme::SEMIBOLD, size::SECTION, t.fg),
track_list::view(env, recent, Columns::FULL),
]
.spacing(14)
.width(Fill),
);
}
match &discover.home {
Loadable::Loaded(data) => {
let h = &data.home;
if !h.personal.is_empty() {
page = page.push(section(
t,
tr("Made for you"),
h.personal.iter().map(|p| {
card::view(t, covers, Card {
title: p.playlist.title.clone(),
subtitle: p.description.clone().unwrap_or_else(|| p.playlist.subtitle()),
cover: p.playlist.cover_url(covers::LARGE),
hues: p.playlist.hues(),
round: false,
on_press: Message::Navigate(Route::Playlist(p.playlist.id)),
})
}),
));
}
if !data.chart.is_empty() {
page = page.push(
column![
row![
line(tr("Chart"), theme::SEMIBOLD, size::SECTION, t.fg).width(Fill),
button(line(trf("Show all {}", &[&data.chart.len()]), theme::MEDIUM, size::META, t.muted))
.padding(0)
.style(theme::tab(false))
.on_press(Message::Navigate(Route::Chart)),
]
.align_y(Alignment::Center),
track_list::view_with(env, &data.top, Columns::CHART, Some(data.top_shifts.clone())),
]
.spacing(14),
);
}
if !h.new_releases.is_empty() {
page = page.push(section(
t,
tr("New releases"),
h.new_releases.iter().take(HOME_CARDS).map(|a| album_card(t, covers, a)),
));
}
if !h.new_playlists.is_empty() {
page = page.push(section(
t,
tr("New playlists"),
h.new_playlists.iter().take(HOME_CARDS).map(|p| playlist_card(t, covers, p)),
));
}
}
Loadable::Failed(e) => page = page.push(status(t, LoadState::Failed(e), tr("your home page"), Message::LoadHome)),
_ => page = page.push(para(tr("Loading your picks…"), size::BODY, t.muted)),
}
page.push(genres_section(env, &discover.genres)).into()
}
pub fn chart<'a>(env: Env<'a>, discover: &'a Discover) -> Element<'a, Message> {
let t = env.t;
let body: Element<'a, Message> = match &discover.home {
Loadable::Loaded(data) if !data.chart.is_empty() => column![
play_bar(t, tr("The most played tracks on Yandex Music today").into(), &data.chart),
track_list::view_with(env, &data.chart, Columns::CHART, Some(data.shifts.clone())),
]
.spacing(22)
.into(),
Loadable::Loaded(_) => para(tr("The chart is empty right now."), size::BODY, t.muted).into(),
Loadable::Failed(e) => status(t, LoadState::Failed(e), tr("the chart"), Message::LoadHome),
_ => para(tr("Loading the chart…"), size::BODY, t.muted).into(),
};
column![line(tr("Chart"), theme::DISPLAY, size::DISPLAY_S, t.fg), body].spacing(24).into()
}
pub fn genres_section<'a>(env: Env<'a>, genres: &'a Loadable<Vec<Genre>>) -> Element<'a, Message> {
let t = env.t;
let body: Element<'a, Message> = match genres {
// Sub-genres are reached from their parent's page.
Loadable::Loaded(list) => {
let top = list.iter().enumerate().filter(|(_, g)| !is_sub_genre(list, g));
Row::with_children(top.map(|(i, g)| genre_tile(t, i, g))).spacing(12).wrap().vertical_spacing(12).into()
}
Loadable::Failed(e) => status(t, LoadState::Failed(e), tr("genres"), Message::LoadGenres),
_ => para(tr("Loading genres…"), size::BODY, t.muted).into(),
};
column![line(tr("Genres"), theme::SEMIBOLD, size::SECTION, t.fg), body].spacing(14).into()
}
fn is_sub_genre(all: &[Genre], g: &Genre) -> bool {
all.iter().any(|parent| parent.sub_genres.iter().any(|s| s.id == g.id))
}
fn genre_tile<'a>(t: &'static Tokens, index: usize, g: &Genre) -> Element<'a, Message> {
let tint = g.color.as_deref().and_then(parse_hex).unwrap_or(t.raised);
button(
// Long names ("Nature Sounds and City Noise") wrap to a second line.
container(
iced::widget::text(g.title.clone())
.font(theme::SEMIBOLD)
.size(size::BODY)
.line_height(1.2)
.color(Color::WHITE),
)
.padding([0, 16])
.align_y(iced::alignment::Vertical::Center)
.height(72)
.width(card::WIDTH)
.clip(true),
)
.padding(0)
.style(move |_, status| {
let lift = matches!(status, button::Status::Hovered | button::Status::Pressed);
button::Style {
background: Some(iced::Background::Gradient(
iced::gradient::Linear::new(std::f32::consts::FRAC_PI_4 * 3.0)
.add_stop(0.0, if lift { theme::mix(tint, Color::WHITE, 0.12) } else { tint })
.add_stop(1.0, theme::mix(tint, Color::BLACK, 0.45))
.into(),
)),
text_color: Color::WHITE,
border: iced::Border { radius: radius::COVER.into(), ..Default::default() },
..Default::default()
}
})
.on_press(Message::Navigate(Route::Genre(index)))
.into()
}
/// `#rrggbb` → colour.
pub fn parse_hex(s: &str) -> Option<Color> {
let h = s.strip_prefix('#')?;
if h.len() != 6 {
return None;
}
let n = u32::from_str_radix(h, 16).ok()?;
Some(Color::from_rgb8((n >> 16) as u8, (n >> 8) as u8, n as u8))
}
pub fn genre<'a>(
env: Env<'a>,
genres: &'a [Genre],
index: usize,
playlists: &'a Loadable<Vec<PlaylistSummary>>,
) -> Element<'a, Message> {
let t = env.t;
let Some(g) = genres.get(index) else {
return para(tr("This genre isn't available any more."), size::BODY, t.muted).into();
};
let radio = button(
row![
crate::ui::icons::icon(crate::ui::icons::Icon::Wave, t.accent_ink),
line(tr("Play radio"), theme::SEMIBOLD, size::BODY, t.accent_ink),
]
.spacing(8)
.align_y(Alignment::Center),
)
.padding([10, 18])
.style(theme::primary)
.on_press(Message::PlayWave(format!("genre:{}", g.id)));
let mut page = column![
row![line(g.title.clone(), theme::DISPLAY, size::DISPLAY_S, t.fg).width(Fill), radio]
.align_y(Alignment::Center)
]
.spacing(24);
let subs: Vec<Element<'a, Message>> = g
.sub_genres
.iter()
.filter_map(|s| genres.iter().position(|f| f.id == s.id).map(|i| (i, s)))
.map(|(i, s)| {
button(line(s.title.clone(), theme::MEDIUM, size::META, t.fg))
.padding([7, 13])
.style(theme::ghost)
.on_press(Message::Navigate(Route::Genre(i)))
.into()
})
.collect();
if !subs.is_empty() {
page = page.push(Row::with_children(subs).spacing(6).wrap().vertical_spacing(6));
}
let body: Element<'a, Message> = match playlists {
Loadable::Loaded(list) if list.is_empty() => {
para(tr("No playlists in this genre yet."), size::BODY, t.muted).into()
}
Loadable::Loaded(list) => section(t, tr("Playlists"), list.iter().map(|p| playlist_card(t, env.covers, p))),
Loadable::Failed(e) => status(t, LoadState::Failed(e), tr("the playlists"), Message::Navigate(Route::Genre(index))),
_ => para(tr("Loading playlists…"), size::BODY, t.muted).into(),
};
page.push(body).into()
}
pub fn podcasts<'a>(
env: Env<'a>,
discover: &'a Discover,
liked: &'a Loadable<Vec<AlbumSummary>>,
) -> Element<'a, Message> {
let t = env.t;
let covers = env.covers;
let mut page = column![line(tr("Podcasts and books"), theme::DISPLAY, size::DISPLAY_S, t.fg)].spacing(34);
if let Loadable::Loaded(albums) = liked {
let mine: Vec<&AlbumSummary> =
albums.iter().filter(|a| matches!(a.kind, AlbumKind::Podcast | AlbumKind::Audiobook)).collect();
if !mine.is_empty() {
page = page.push(section(t, tr("Yours"), mine.into_iter().map(|a| album_card(t, covers, a))));
}
}
page.push(match &discover.podcasts {
Loadable::Loaded(list) => section(t, tr("Featured"), list.iter().map(|a| album_card(t, covers, a))),
Loadable::Failed(e) => status(t, LoadState::Failed(e), tr("podcasts"), Message::LoadPodcasts),
_ => para(tr("Loading podcasts…"), size::BODY, t.muted).into(),
})
.into()
}
/// The arrow beside a chart position.
pub fn shift_marker(t: &'static Tokens, shift: i32) -> Element<'static, Message> {
let (glyph, colour) = match shift {
s if s > 0 => ("▲", t.ok),
s if s < 0 => ("▼", t.like),
_ => ("–", t.muted),
};
container(line(glyph, theme::DISPLAY, 9.0, colour)).width(14).center_x(14).into()
}
#[cfg(test)]
mod tests {
use super::*;
fn genre(id: &str, subs: &[&str]) -> Genre {
Genre {
id: id.into(),
title: id.into(),
color: None,
sub_genres: subs.iter().map(|s| genre(s, &[])).collect(),
}
}
#[test]
fn flatten_appends_each_sub_genre_once() {
let flat = flatten(vec![genre("rock", &["punk", "metal"]), genre("metal", &["doom"]), genre("pop", &["punk"])]);
let ids: Vec<&str> = flat.iter().map(|g| g.id.as_str()).collect();
assert_eq!(ids, ["rock", "metal", "pop", "punk", "doom"]);
assert!(is_sub_genre(&flat, &flat[3]));
assert!(!is_sub_genre(&flat, &flat[0]));
}
#[test]
fn hex_colours() {
assert_eq!(parse_hex("#ff8000"), Some(Color::from_rgb8(255, 128, 0)));
assert_eq!(parse_hex("ff8000"), None);
assert_eq!(parse_hex("#fff"), None);
}
#[test]
fn home_data_splits_chart() {
let track = |id: &str| Track::from_json(&format!(r#"{{"id":"{id}"}}"#)).unwrap();
let home = Home {
chart: vec![
ChartEntry { position: 1, shift: 2, track: track("a") },
ChartEntry { position: 2, shift: -1, track: track("b") },
],
..Default::default()
};
let data = HomeData::new(home);
assert_eq!(data.chart.len(), 2);
assert_eq!(&*data.shifts, &[2, -1]);
assert!(data.home.chart.is_empty());
}
}
+408
View File
@@ -0,0 +1,408 @@
//! 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));
}
}
+280
View File
@@ -0,0 +1,280 @@
//! Album, artist and playlist pages: a cover header, then tracks and cards.
use std::sync::Arc;
use iced::widget::{Row, button, column, container, row, text};
use iced::{Alignment, Element, Fill, Task};
use ym_api::{AlbumPage, ArtistPage, ArtistRef, Error, PlaylistPage, Track, YmClient};
use super::Loadable;
use super::collection::{LoadState, album_card, artist_card, clip_card, play_bar, section, status};
use crate::app::Message;
use crate::covers;
use crate::route::Route;
use crate::ui::theme::{self, size};
use crate::ui::{counted, duration_words, line, para, tracks_word};
use crate::widgets::track_list::{self, Env};
use crate::widgets::sheet::Sheet;
use crate::widgets::track_row::Columns;
use crate::ui::icons::{Icon, icon};
use crate::i18n::{tr, trf};
/// A loaded page. Tracks are split out as `Arc<[Track]>` so playing them shares the list.
#[derive(Debug, Clone)]
pub enum Page {
Album { info: AlbumPage, tracks: Arc<[Track]> },
Artist { info: ArtistPage, popular: Arc<[Track]> },
Playlist { info: PlaylistPage, tracks: Arc<[Track]> },
}
/// Fetches whatever `route` shows. Non-detail routes load nothing.
pub fn load(client: &YmClient, route: Route) -> Option<Task<Message>> {
let client = client.clone();
let task = match route {
Route::Album(id) => Task::future(async move {
client.album(id).await.map(|mut info| {
let tracks = std::mem::take(&mut info.tracks).into();
Page::Album { info, tracks }
})
}),
Route::Artist(id) => Task::future(async move {
client.artist(id).await.map(|mut info| {
let popular = std::mem::take(&mut info.popular).into();
Page::Artist { info, popular }
})
}),
Route::Playlist(id) => Task::future(async move {
client.playlist(id).await.map(|mut info| {
let tracks = std::mem::take(&mut info.tracks).into();
Page::Playlist { info, tracks }
})
}),
_ => return None,
};
Some(task.map(move |result| Message::PageLoaded(route, result)))
}
pub fn view<'a>(env: Env<'a>, route: Route, page: &'a Loadable<Page>) -> Element<'a, Message> {
let t = env.t;
let what = match route {
Route::Album(_) => What { loading: tr("Loading the album…"), gone: tr("This album isn't available on Yandex Music any more."), retry: tr("the album") },
Route::Artist(_) => What { loading: tr("Loading the artist…"), gone: tr("This artist isn't available on Yandex Music any more."), retry: tr("the artist") },
_ => What { loading: tr("Loading the playlist…"), gone: tr("This playlist isn't available on Yandex Music any more."), retry: tr("the playlist") },
};
match page {
Loadable::Loaded(Page::Album { info, tracks }) => album(env, info, tracks),
Loadable::Loaded(Page::Artist { info, popular }) => artist(env, info, popular),
Loadable::Loaded(Page::Playlist { info, tracks }) => playlist(env, info, tracks),
Loadable::Failed(e) => not_found_or_retry(env, e, what, route),
Loadable::NotLoaded | Loadable::Loading => {
para(what.loading, size::BODY, t.muted).into()
}
}
}
/// How the page talks about what it's loading.
struct What {
loading: &'static str,
gone: &'static str,
retry: &'static str,
}
fn not_found_or_retry<'a>(env: Env<'a>, e: &'a Error, what: What, route: Route) -> Element<'a, Message> {
if let Error::Api(m) = e
&& m.contains("not found")
{
return para(what.gone, size::BODY, env.t.muted).into();
}
status(env.t, LoadState::Failed(e), what.retry, Message::Navigate(route))
}
struct Head<'a> {
cover: Option<String>,
hues: (f32, f32),
round: bool,
kind: String,
title: String,
by: Option<Element<'a, Message>>,
meta: String,
actions: Vec<Element<'a, Message>>,
}
fn head<'a>(env: Env<'a>, h: Head<'a>) -> Element<'a, Message> {
let t = env.t;
let size_px = 200.0;
let corner = if h.round { size_px / 2.0 } else { theme::radius::COVER };
row![
covers::view(env.covers, h.cover, h.hues, size_px, corner),
column![
line(h.kind, theme::BODY, size::META, t.muted),
text(h.title).font(theme::DISPLAY).size(size::DISPLAY_L).line_height(1.08).color(t.fg),
]
.push(h.by)
.push(line(h.meta, theme::BODY, size::META, t.muted))
.push((!h.actions.is_empty()).then(|| Row::with_children(h.actions).spacing(8).align_y(Alignment::Center)))
.spacing(8)
.width(Fill),
]
.spacing(28)
.align_y(Alignment::End)
.into()
}
/// A round heart that adds or removes something from the collection.
fn like_button<'a>(t: &'static theme::Tokens, liked: bool, msg: Message) -> Element<'a, Message> {
button(icon(if liked { Icon::HeartFilled } else { Icon::Heart }, if liked { t.like } else { t.fg }))
.padding(10)
.style(theme::ghost)
.on_press(msg)
.into()
}
fn pill<'a>(t: &'static theme::Tokens, glyph: Icon, label: &'a str, msg: Message) -> Element<'a, Message> {
button(row![icon(glyph, t.fg), line(label, theme::MEDIUM, size::META, t.fg)].spacing(6).align_y(Alignment::Center))
.padding([8, 14])
.style(theme::ghost)
.on_press(msg)
.into()
}
/// Artist names as links to their pages.
fn artist_links<'a>(env: Env<'a>, artists: &[ArtistRef]) -> Element<'a, Message> {
let t = env.t;
Row::with_children(artists.iter().map(|a| {
let label = line(a.name.clone(), theme::MEDIUM, size::BODY, t.fg);
match a.id {
Some(id) => button(label)
.padding(0)
.style(theme::tab(true))
.on_press(Message::Navigate(Route::Artist(id)))
.into(),
None => label.into(),
}
}))
.spacing(12)
.into()
}
fn album<'a>(env: Env<'a>, info: &'a AlbumPage, tracks: &'a Arc<[Track]>) -> Element<'a, Message> {
let a = &info.album;
let kind = match a.year {
Some(year) => format!("{} · {year}", tr(a.kind.label())),
None => tr(a.kind.label()).to_owned(),
};
// `info.tracks` was moved into `tracks`, so measure the list itself.
let length = format!("{} · {}", tracks_word(tracks.len()), duration_words(tracks.iter().map(|tr| tr.duration).sum()));
let meta = match &info.label {
Some(label) => format!("{length} · {label}"),
None => length,
};
column![
head(env, Head {
cover: a.cover_url(covers::LARGE),
hues: a.hues(),
round: false,
kind,
title: a.full_title(),
by: Some(artist_links(env, &a.artists)),
meta,
actions: vec![like_button(env.t, env.likes.albums.contains(&a.id), Message::LikeAlbum(a.id, !env.likes.albums.contains(&a.id)))],
}),
play_bar(env.t, String::new(), tracks),
track_list::view(env, tracks, Columns::ALBUM_PAGE),
]
.spacing(28)
.into()
}
fn artist<'a>(env: Env<'a>, info: &'a ArtistPage, popular: &'a Arc<[Track]>) -> Element<'a, Message> {
let t = env.t;
let a = &info.artist;
let kind = if a.genres.is_empty() { tr("Artist").to_owned() } else { trf("Artist · {}", &[&a.genres.join(", ")]) };
let meta = info
.monthly_listeners
.map(|n| counted(n, ["listener a month", "listeners a month"], ["слушатель в месяц", "слушателя в месяц", "слушателей в месяц"]))
.or_else(|| a.likes.map(|n| counted(n, ["like", "likes"], ["лайк", "лайка", "лайков"])))
.unwrap_or_default();
let mut page = column![
head(env, Head {
cover: a.cover_url(covers::LARGE),
hues: a.hues(),
round: true,
kind,
title: a.name.clone(),
by: None,
meta,
actions: vec![like_button(t, env.likes.artists.contains(&a.id), Message::LikeArtist(a.id, !env.likes.artists.contains(&a.id)))],
}),
]
.spacing(34);
if !popular.is_empty() {
page = page.push(
column![
line(tr("Popular tracks"), theme::SEMIBOLD, size::SECTION, t.fg),
play_bar(t, String::new(), popular),
track_list::view(env, popular, Columns::FULL),
]
.spacing(14),
);
}
if !info.albums.is_empty() {
page = page.push(section(t, tr("Albums"), info.albums.iter().map(|al| album_card(t, env.covers, al))));
}
if !info.also_albums.is_empty() {
page = page.push(section(t, tr("Appears on"), info.also_albums.iter().map(|al| album_card(t, env.covers, al))));
}
if !info.clips.is_empty() {
page = page.push(section(t, tr("Clips"), info.clips.iter().map(|c| clip_card(env, c))));
}
if !info.similar.is_empty() {
page = page.push(section(t, tr("Similar artists"), info.similar.iter().map(|ar| artist_card(t, env.covers, ar))));
}
page.into()
}
fn playlist<'a>(env: Env<'a>, info: &'a PlaylistPage, tracks: &'a Arc<[Track]>) -> Element<'a, Message> {
let t = env.t;
let p = &info.playlist;
let own = p.id.owner == env.me;
let total = tracks.iter().map(|tr| tr.duration).sum();
let mut page = column![
head(env, Head {
cover: p.cover_url(covers::LARGE),
hues: p.hues(),
round: false,
kind: trf("Playlist · {}", &[&if p.public { tr("Public") } else { tr("Private") }]),
title: p.title.clone(),
by: Some(line(p.owner_name.clone(), theme::MEDIUM, size::BODY, t.fg).into()),
meta: format!("{} · {}", tracks_word(tracks.len()), duration_words(total)),
actions: if own {
vec![
pill(t, Icon::Pencil, tr("Rename"), Message::OpenSheet(Sheet::Rename { id: p.id, name: p.title.clone() })),
pill(
t,
if p.public { Icon::Lock } else { Icon::Globe },
if p.public { tr("Make private") } else { tr("Make public") },
Message::SetPlaylistPublic(p.id, !p.public),
),
pill(t, Icon::Trash, tr("Delete"), Message::OpenSheet(Sheet::ConfirmDelete { id: p.id, title: p.title.clone() })),
]
} else {
vec![like_button(t, env.likes.playlists.contains(&p.id), Message::LikePlaylist(p.id, !env.likes.playlists.contains(&p.id)))]
},
}),
]
.spacing(28);
if let Some(description) = &info.description {
page = page.push(container(para(description.clone(), size::BODY, t.muted)).max_width(640));
}
if tracks.is_empty() {
return page.push(para(tr("This playlist is empty."), size::BODY, t.muted)).into();
}
let list = if own {
track_list::view_own_playlist(env, tracks, p.id)
} else {
track_list::view(env, tracks, Columns::FULL)
};
page.push(play_bar(t, String::new(), tracks)).push(list).into()
}
+239
View File
@@ -0,0 +1,239 @@
//! Content for each route, plus the full-window screens shown outside a session.
pub mod browse;
pub mod collection;
pub mod detail;
pub mod search;
pub mod settings;
pub mod sign_in;
pub mod wave;
use iced::widget::{Column, button, column, container, row, space};
use iced::{Alignment, Element, Fill, Padding};
use std::collections::HashMap;
use ym_api::{Account, Error, PlaylistSummary};
use crate::app::Message;
use crate::route::Route;
use crate::ui::icons::{Icon, icon};
use crate::ui::theme::{self, Tokens, size, space as sp};
use crate::ui::{line, para};
use crate::widgets::sidebar;
use crate::widgets::track_list::Env;
use crate::i18n::{tr, trf};
/// Something fetched from the API: not asked for yet, on its way, here, or failed.
#[derive(Debug, Default)]
pub enum Loadable<T> {
#[default]
NotLoaded,
Loading,
Loaded(T),
Failed(Error),
}
impl<T> Loadable<T> {
pub fn get(&self) -> Option<&T> {
match self {
Loadable::Loaded(v) => Some(v),
_ => None,
}
}
/// Not loaded yet, or failed: worth (re)requesting.
pub fn needs_load(&self) -> bool {
matches!(self, Loadable::NotLoaded | Loadable::Failed(_))
}
pub fn state(&self) -> collection::LoadState<'_> {
match self {
Loadable::Failed(e) => collection::LoadState::Failed(e),
_ => collection::LoadState::Loading,
}
}
pub fn from_result(result: Result<T, Error>) -> Self {
match result {
Ok(v) => Loadable::Loaded(v),
Err(e) => Loadable::Failed(e),
}
}
}
/// Everything a routed screen may need from app state.
pub struct Ctx<'a> {
pub env: Env<'a>,
pub route: Route,
pub search: &'a search::Search,
pub me: &'a Account,
pub library: &'a collection::Library,
pub pages: &'a HashMap<Route, Loadable<detail::Page>>,
pub discover: &'a browse::Discover,
pub genre_playlists: &'a HashMap<usize, Loadable<Vec<PlaylistSummary>>>,
pub player: &'a crate::player::Player,
pub wave: &'a wave::WaveScreen,
pub wave_phase: f32,
pub settings: &'a crate::store::Settings,
}
pub fn view<'a>(ctx: Ctx<'a>) -> Element<'a, Message> {
let Ctx { env, route, search, me, library, pages, discover, genre_playlists, player, wave, wave_phase, settings } = ctx;
let t = env.t;
let content: Column<'a, Message> = match route {
Route::Home => {
column![browse::home(env, discover, wave::hero(t, player, wave_phase, wave.shown(), false))]
}
Route::Wave => column![wave::view(
t,
env.covers,
wave,
wave::hero(t, player, wave_phase, wave.shown(), true),
)],
Route::Search => column![search::view(env, search, browse::genres_section(env, &discover.genres))],
Route::Chart => column![browse::chart(env, discover)],
Route::Genre(i) => column![browse::genre(
env,
discover.genres.get().map_or(&[][..], Vec::as_slice),
i,
genre_playlists.get(&i).unwrap_or(&Loadable::Loading),
)],
Route::Collection => column![collection::view(env, library)],
Route::Album(_) | Route::Artist(_) | Route::Playlist(_) => {
column![detail::view(env, route, pages.get(&route).unwrap_or(&Loadable::Loading))]
}
Route::Podcasts => column![browse::podcasts(env, discover, &library.albums)],
Route::Settings => column![settings::view(t, settings, account_card(t, me))],
};
content
.spacing(sp::SECTION)
.padding(Padding::default().top(6).bottom(40).left(sp::GUTTER).right(sp::GUTTER))
.width(Fill)
.into()
}
fn account_card<'a>(t: &'static Tokens, me: &'a Account) -> Element<'a, Message> {
let avatar = container(line(me.initial().to_string(), theme::SEMIBOLD, 22.0, iced::Color::from_rgb8(0x1C, 0x1A, 0x22)))
.center(56)
.style(theme::avatar);
let plan = match (me.has_plus, me.subscription_end.as_deref().and_then(human_date)) {
(true, Some(end)) => trf("Yandex Plus until {}", &[&end]),
(true, None) => tr("Yandex Plus").to_owned(),
(false, _) => tr("No Plus subscription. Tracks play as 30-second previews.").to_owned(),
};
container(
row![
avatar,
column![
line(&me.name, theme::SEMIBOLD, size::SECTION, t.fg),
line(&me.login, theme::BODY, size::BODY, t.muted),
line(plan, theme::MEDIUM, size::META, if me.has_plus { t.ok } else { t.muted }),
]
.spacing(4)
.width(Fill),
button(
row![icon(Icon::LogOut, t.fg), line(tr("Sign out"), theme::MEDIUM, size::BODY, t.fg)]
.spacing(8)
.align_y(Alignment::Center),
)
.padding([9, 16])
.style(theme::ghost)
.on_press(Message::SignOut),
]
.spacing(18)
.align_y(Alignment::Center),
)
.padding(24)
.width(Fill)
.style(theme::card)
.into()
}
/// `2027-01-05T00:00:00+03:00` → `5 January 2027` (`5 января 2027`).
pub fn human_date(iso: &str) -> Option<String> {
const MONTHS: [&str; 12] = [
"January", "February", "March", "April", "May", "June", "July", "August", "September",
"October", "November", "December",
];
// Genitive, as Russian dates need.
const MONTHS_RU: [&str; 12] = [
"января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября",
"октября", "ноября", "декабря",
];
let months = match crate::i18n::lang() {
crate::i18n::Lang::En => MONTHS,
crate::i18n::Lang::Ru => MONTHS_RU,
};
let date = iso.get(..10)?;
let mut parts = date.split('-');
let (y, m, d) = (parts.next()?, parts.next()?, parts.next()?);
let month = months.get(m.parse::<usize>().ok()?.checked_sub(1)?)?;
let day: u32 = d.parse().ok()?;
y.parse::<u32>().ok()?;
Some(format!("{day} {month} {y}"))
}
/// Full-window holding screen while the stored session is checked or a new one connects.
pub fn connecting<'a>(t: &'static Tokens, label: &'a str) -> Element<'a, Message> {
container(
column![
sidebar::wordmark(t),
line(label, theme::BODY, size::BODY, t.muted),
]
.spacing(14)
.align_x(Alignment::Center),
)
.center(Fill)
.into()
}
/// Full-window screen when stored credentials exist but Yandex can't be reached.
pub fn unreachable<'a>(t: &'static Tokens) -> Element<'a, Message> {
container(
column![
sidebar::wordmark(t),
line(tr("Can't reach Yandex Music"), theme::DISPLAY, size::DISPLAY_S, t.fg),
container(para(
tr("You're still signed in. Check your internet connection, then try again."),
15.0,
t.muted,
))
.max_width(440),
row![
button(line(tr("Try again"), theme::SEMIBOLD, size::BODY, t.accent_ink))
.padding([11, 18])
.style(theme::primary)
.on_press(Message::Restore),
button(line(tr("Sign out"), theme::MEDIUM, size::BODY, t.fg))
.padding([11, 18])
.style(theme::ghost)
.on_press(Message::SignOut),
]
.spacing(10),
space().height(40),
]
.spacing(18)
.align_x(Alignment::Center),
)
.center(Fill)
.into()
}
#[cfg(test)]
mod tests {
use super::human_date;
#[test]
fn dates_read_naturally() {
assert_eq!(human_date("2027-01-05T00:00:00+03:00").as_deref(), Some("5 January 2027"));
assert_eq!(human_date("2026-12-31").as_deref(), Some("31 December 2026"));
assert_eq!(human_date("2026-13-01"), None);
crate::i18n::set(crate::i18n::Lang::Ru);
assert_eq!(human_date("2027-01-05T00:00:00+03:00").as_deref(), Some("5 января 2027"));
crate::i18n::set(crate::i18n::Lang::En);
assert_eq!(human_date("soon"), None);
}
}
+467
View File
@@ -0,0 +1,467 @@
//! Search: suggestions while typing, results by kind, more pages on request.
//! With no query it shows genres to browse.
use std::sync::Arc;
use std::time::Duration;
use iced::widget::{button, column, container, row};
use iced::{Alignment, Element, Fill, Task};
use ym_api::{BestMatch, Error, SearchKind, SearchResults, Track, YmClient};
use super::collection::{
LoadState, album_card, artist_card, play_bar, playlist_card, section, status,
};
use super::Loadable;
use crate::app::Message;
use crate::covers;
use crate::route::Route;
use crate::ui::icons::{Icon, icon};
use crate::ui::theme::{self, radius, size};
use crate::ui::{compact, line, para};
use crate::widgets::card;
use crate::widgets::track_list::{self, Env};
use crate::widgets::track_row::Columns;
use crate::i18n::{tr, trf};
/// Wait this long after the last keystroke before asking for suggestions.
const DEBOUNCE: Duration = Duration::from_millis(250);
/// Tracks shown in the "All" tab before "Show all".
const ALL_TAB_TRACKS: usize = 5;
#[derive(Debug, Clone)]
pub enum Msg {
Changed(String),
/// The debounce timer for this text ran out.
Settled(String),
Suggestions(String, Result<Vec<String>, Error>),
Pick(String),
Submit,
CloseSuggestions,
Tab(SearchKind),
Loaded { query: String, kind: SearchKind, page: u32, result: Box<Result<SearchResults, Error>> },
More,
}
/// Results for one query and kind, with the tracks as a playable list.
#[derive(Debug)]
pub struct Results {
pub data: SearchResults,
pub tracks: Arc<[Track]>,
/// The first few tracks for the "All" tab, built once so the cached list stays valid.
top: Arc<[Track]>,
pub page: u32,
loading_more: bool,
}
#[derive(Debug, Default)]
pub struct Search {
pub text: String,
/// The query the results are for; `text` may have moved on since.
query: String,
kind: SearchKind,
results: Loadable<Results>,
suggestions: Vec<String>,
show_suggestions: bool,
}
/// What the app should do after a search message besides running the task.
pub enum After {
Nothing,
ShowResults,
}
impl Search {
pub fn suggestions(&self) -> Option<&[String]> {
(self.show_suggestions && !self.suggestions.is_empty()).then_some(&self.suggestions)
}
pub fn update(&mut self, msg: Msg, client: Option<&YmClient>) -> (Task<Message>, After) {
match msg {
Msg::Changed(text) => {
self.text = text.clone();
self.show_suggestions = !text.trim().is_empty();
if text.trim().is_empty() {
self.suggestions.clear();
return (Task::none(), After::Nothing);
}
let task = Task::future(async move {
tokio::time::sleep(DEBOUNCE).await;
text
})
.map(|t| Message::Search(Msg::Settled(t)));
return (task, After::Nothing);
}
Msg::Settled(text) => {
// Only the last keystroke's timer asks.
if text != self.text {
return (Task::none(), After::Nothing);
}
let Some(client) = client.cloned() else { return (Task::none(), After::Nothing) };
let part = text.clone();
let task = Task::future(async move { client.suggest(&part).await })
.map(move |r| Message::Search(Msg::Suggestions(text.clone(), r)));
return (task, After::Nothing);
}
Msg::Suggestions(text, Ok(list)) if text == self.text => self.suggestions = list,
Msg::Suggestions(_, Err(e)) => eprintln!("suggest: {e}"),
Msg::Suggestions(..) => {}
Msg::Pick(text) => {
self.text = text;
return self.update(Msg::Submit, client);
}
Msg::Submit => {
self.show_suggestions = false;
let query = self.text.trim().to_owned();
if query.is_empty() {
return (Task::none(), After::ShowResults);
}
if query != self.query || self.results.needs_load() {
self.query = query;
return (self.fetch(client, 0), After::ShowResults);
}
return (Task::none(), After::ShowResults);
}
Msg::CloseSuggestions => self.show_suggestions = false,
Msg::Tab(kind) => {
if kind != self.kind {
self.kind = kind;
if !self.query.is_empty() {
return (self.fetch(client, 0), After::Nothing);
}
}
}
Msg::Loaded { query, kind, page, result } => {
if query != self.query || kind != self.kind {
return (Task::none(), After::Nothing);
}
match (*result, &mut self.results) {
(Ok(more), Loadable::Loaded(current)) if page > 0 => {
current.data.tracks.extend(more.tracks);
current.data.albums.extend(more.albums);
current.data.artists.extend(more.artists);
current.data.playlists.extend(more.playlists);
current.data.podcasts.extend(more.podcasts);
current.tracks = current.data.tracks.clone().into();
current.top = top_of(&current.tracks);
current.page = page;
current.loading_more = false;
}
(Ok(data), _) => {
let tracks: Arc<[Track]> = data.tracks.clone().into();
let top = top_of(&tracks);
self.results = Loadable::Loaded(Results { data, tracks, top, page, loading_more: false });
}
(Err(e), Loadable::Loaded(current)) if page > 0 => {
eprintln!("search more: {e}");
current.loading_more = false;
}
(Err(e), _) => {
eprintln!("search: {e}");
self.results = Loadable::Failed(e);
}
}
}
Msg::More => {
if let Loadable::Loaded(current) = &mut self.results
&& !current.loading_more
{
current.loading_more = true;
let next = current.page + 1;
return (self.fetch(client, next), After::Nothing);
}
}
}
(Task::none(), After::Nothing)
}
fn fetch(&mut self, client: Option<&YmClient>, page: u32) -> Task<Message> {
let Some(client) = client.cloned() else { return Task::none() };
if page == 0 {
self.results = Loadable::Loading;
}
let (query, kind) = (self.query.clone(), self.kind);
Task::future(async move {
let result = client.search(&query, kind, page).await;
Msg::Loaded { query, kind, page, result: Box::new(result) }
})
.map(Message::Search)
}
fn has_more(&self, r: &Results) -> bool {
let Some(total) = r.data.totals.get(self.kind) else { return false };
let shown = match self.kind {
SearchKind::All => return false,
SearchKind::Tracks => r.data.tracks.len(),
SearchKind::Albums => r.data.albums.len(),
SearchKind::Artists => r.data.artists.len(),
SearchKind::Playlists => r.data.playlists.len(),
SearchKind::Podcasts => r.data.podcasts.len(),
};
(shown as u32) < total
}
}
pub fn view<'a>(env: Env<'a>, search: &'a Search, browse: Element<'a, Message>) -> Element<'a, Message> {
let t = env.t;
if search.query.is_empty() {
return column![line(tr("Browse"), theme::DISPLAY, size::DISPLAY_S, t.fg), browse].spacing(24).into();
}
let tabs = row(SearchKind::ALL.map(|kind| {
let on = kind == search.kind;
let total = search.results.get().and_then(|r| r.data.totals.get(kind)).filter(|n| *n > 0);
let mut label = row![line(kind.label(), theme::MEDIUM, size::BODY, if on { t.fg } else { t.muted })]
.spacing(6)
.align_y(Alignment::Center);
if let Some(n) = total {
label = label.push(line(compact(i64::from(n)), theme::BODY, size::SMALL, t.muted));
}
button(
column![
label,
container(iced::widget::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::Search(Msg::Tab(kind)))
.into()
}))
.spacing(4);
let title = line(trf("Results for “{}”", &[&search.query]), theme::DISPLAY, size::DISPLAY_S, t.fg);
let body: Element<'a, Message> = match &search.results {
Loadable::Loaded(r) if r.data.is_empty() => para(
trf("Nothing found for “{}”. Check the spelling or try fewer words.", &[&search.query]),
size::BODY,
t.muted,
)
.into(),
Loadable::Loaded(r) => results(env, search, r),
Loadable::Failed(e) => status(t, LoadState::Failed(e), tr("the results"), Message::Search(Msg::Submit)),
_ => para(tr("Searching…"), size::BODY, t.muted).into(),
};
let mut page = column![title].spacing(24);
if let Some(corrected) = search.results.get().and_then(|r| r.data.corrected.as_ref()) {
page = page.push(line(trf("Showing results for “{}”", &[corrected]), theme::BODY, size::META, t.muted));
}
page.push(tabs).push(body).into()
}
fn results<'a>(env: Env<'a>, search: &'a Search, r: &'a Results) -> Element<'a, Message> {
let t = env.t;
let covers = env.covers;
let d = &r.data;
let more = search.has_more(r).then(|| {
button(line(if r.loading_more { tr("Loading…") } else { tr("Show more") }, theme::MEDIUM, size::BODY, t.fg))
.padding([10, 18])
.style(theme::ghost)
.on_press_maybe((!r.loading_more).then_some(Message::Search(Msg::More)))
});
let body: Element<'a, Message> = match search.kind {
SearchKind::All => {
let mut all = column![].spacing(34);
if let Some(best) = &d.best {
all = all.push(best_card(env, best));
}
if !r.tracks.is_empty() {
all = all.push(
column![
row![
line(tr("Tracks"), theme::SEMIBOLD, size::SECTION, t.fg).width(Fill),
button(line(tr("Show all"), theme::MEDIUM, size::META, t.muted))
.padding(0)
.style(theme::tab(false))
.on_press(Message::Search(Msg::Tab(SearchKind::Tracks))),
],
track_list::view(env, &r.top, Columns::FULL),
]
.spacing(14),
);
}
if !d.artists.is_empty() {
all = all.push(section(t, tr("Artists"), d.artists.iter().take(6).map(|a| artist_card(t, covers, a))));
}
if !d.albums.is_empty() {
all = all.push(section(t, tr("Albums"), d.albums.iter().take(6).map(|a| album_card(t, covers, a))));
}
if !d.playlists.is_empty() {
all = all.push(section(t, tr("Playlists"), d.playlists.iter().take(6).map(|p| playlist_card(t, covers, p))));
}
if !d.podcasts.is_empty() {
all = all.push(section(t, tr("Podcasts"), d.podcasts.iter().take(6).map(|a| album_card(t, covers, a))));
}
all.into()
}
SearchKind::Tracks => column![
play_bar(t, String::new(), &r.tracks),
track_list::view(env, &r.tracks, Columns::FULL),
]
.spacing(18)
.into(),
SearchKind::Albums => card::grid(d.albums.iter().map(|a| album_card(t, covers, a))),
SearchKind::Artists => card::grid(d.artists.iter().map(|a| artist_card(t, covers, a))),
SearchKind::Playlists => card::grid(d.playlists.iter().map(|p| playlist_card(t, covers, p))),
SearchKind::Podcasts => card::grid(d.podcasts.iter().map(|a| album_card(t, covers, a))),
};
column![body].push(more).spacing(22).into()
}
/// The top result as a wide card: cover, name, kind, and the action it implies.
fn best_card<'a>(env: Env<'a>, best: &'a BestMatch) -> Element<'a, Message> {
let t = env.t;
let (cover, hues, round, title, kind, action) = match best {
BestMatch::Artist(a) => (
a.cover_url(covers::LARGE), a.hues(), true, a.name.clone(), tr("Artist").to_owned(),
Message::Navigate(Route::Artist(a.id)),
),
BestMatch::Album(a) => (
a.cover_url(covers::LARGE), a.hues(), false, a.full_title(), format!("{} · {}", a.kind.label(), a.artist_line()),
Message::Navigate(Route::Album(a.id)),
),
BestMatch::Playlist(p) => (
p.cover_url(covers::LARGE), p.hues(), false, p.title.clone(), trf("Playlist · {}", &[&p.owner_name]),
Message::Navigate(Route::Playlist(p.id)),
),
BestMatch::Track(tr) => (
tr.cover_url(covers::LARGE), tr.hues(), false, tr.full_title(), trf("Track · {}", &[&tr.artist_line()]),
Message::PlayTracks { tracks: Arc::from(vec![tr.clone()]), start: 0, shuffle: false },
),
};
let size_px = 108.0;
let corner = if round { size_px / 2.0 } else { radius::COVER };
let glyph = if matches!(best, BestMatch::Track(_)) { Icon::Play } else { Icon::Forward };
button(
row![
covers::view(env.covers, cover, hues, size_px, corner),
column![
line(tr("Top result"), theme::MEDIUM, size::SMALL, t.muted),
line(title, theme::DISPLAY, 24.0, t.fg),
line(kind, theme::BODY, size::META, t.muted),
]
.spacing(6)
.width(Fill),
container(icon(glyph, t.accent_ink))
.center(44)
.style(move |_| container::Style {
background: Some(t.accent.into()),
border: iced::Border { radius: radius::PILL.into(), ..Default::default() },
..Default::default()
})
.padding(0),
]
.spacing(20)
.align_y(Alignment::Center),
)
.padding(18)
.width(Fill)
.style(move |th, status| {
let mut s = theme::nav_item(false)(th, status);
if s.background.is_none() {
s.background = Some(t.panel.into());
}
s.border = iced::Border { color: t.line, width: 1.0, radius: radius::CARD.into() };
s
})
.on_press(action)
.into()
}
fn top_of(tracks: &[Track]) -> Arc<[Track]> {
tracks.iter().take(ALL_TAB_TRACKS).cloned().collect()
}
/// The suggestion list floating under the search field.
pub fn suggestions<'a>(t: &'static theme::Tokens, list: &'a [String]) -> Element<'a, Message> {
let items = list.iter().take(8).map(|s| {
button(
row![icon(Icon::Search, t.muted), line(s.clone(), theme::BODY, size::BODY, t.fg)]
.spacing(10)
.align_y(Alignment::Center),
)
.width(Fill)
.padding([8, 12])
.style(theme::nav_item(false))
.on_press(Message::Search(Msg::Pick(s.clone())))
.into()
});
container(column(items).spacing(2))
.padding(6)
.width(420)
.style(move |_| container::Style {
background: Some(t.panel.into()),
border: iced::Border { color: t.line, width: 1.0, radius: 12.0.into() },
shadow: iced::Shadow {
color: iced::Color::BLACK.scale_alpha(0.3),
offset: iced::Vector::new(0.0, 12.0),
blur_radius: 30.0,
},
..Default::default()
})
.into()
}
#[cfg(test)]
mod tests {
use super::*;
fn loaded(page: u32, titles: &[&str], total: u32) -> Msg {
let tracks = titles
.iter()
.enumerate()
.map(|(i, t)| Track::from_json(&format!(r#"{{"id":"{}{i}","title":"{t}"}}"#, page)).unwrap())
.collect();
let mut data = SearchResults { tracks, ..Default::default() };
data.totals.tracks = total;
Msg::Loaded { query: "q".into(), kind: SearchKind::Tracks, page, result: Box::new(Ok(data)) }
}
fn searched() -> Search {
let mut s = Search::default();
let _ = s.update(Msg::Changed("q".into()), None);
let _ = s.update(Msg::Submit, None);
let _ = s.update(Msg::Tab(SearchKind::Tracks), None);
s
}
#[test]
fn stale_suggestions_and_results_are_dropped() {
let mut s = Search::default();
let _ = s.update(Msg::Changed("зем".into()), None);
let _ = s.update(Msg::Changed("земф".into()), None);
let _ = s.update(Msg::Suggestions("зем".into(), Ok(vec!["old".into()])), None);
assert!(s.suggestions().is_none());
let _ = s.update(Msg::Suggestions("земф".into(), Ok(vec!["земфира".into()])), None);
assert_eq!(s.suggestions().unwrap(), ["земфира".to_owned()]);
let _ = s.update(Msg::Submit, None);
assert!(s.suggestions().is_none(), "submitting hides suggestions");
}
#[test]
fn more_pages_append() {
let mut s = searched();
let _ = s.update(loaded(0, &["a", "b"], 4), None);
let Loadable::Loaded(r) = &s.results else { panic!() };
assert!(s.has_more(r));
let _ = s.update(Msg::More, None);
let _ = s.update(loaded(1, &["c", "d"], 4), None);
let Loadable::Loaded(r) = &s.results else { panic!() };
assert_eq!(r.tracks.len(), 4);
assert!(!s.has_more(r));
}
#[test]
fn results_for_another_tab_are_ignored() {
let mut s = searched();
let mut msg = loaded(0, &["a"], 1);
if let Msg::Loaded { kind, .. } = &mut msg {
*kind = SearchKind::Albums;
}
let _ = s.update(msg, None);
assert!(s.results.get().is_none());
}
}
+66
View File
@@ -0,0 +1,66 @@
//! Settings: account, streaming quality, appearance, storage.
use iced::widget::{Row, button, column, container, row};
use iced::{Alignment, Element, Fill};
use crate::app::Message;
use crate::store::{Appearance, Locale, Quality, Settings};
use crate::ui::icons::{Icon, icon};
use crate::ui::theme::{self, Tokens, size};
use crate::ui::{line, para};
use crate::i18n::{tr, trf};
pub fn view<'a>(t: &'static Tokens, settings: &Settings, account: Element<'a, Message>) -> Element<'a, Message> {
let quality = Row::with_children(Quality::ALL.map(|q| chip(t, q.label(), q == settings.quality, Message::SetQuality(q))))
.spacing(6);
let appearance =
Row::with_children(Appearance::ALL.map(|a| chip(t, a.label(), a == settings.appearance, Message::SetAppearance(a))))
.spacing(6);
let language =
Row::with_children(Locale::ALL.map(|l| chip(t, l.label(), l == settings.language, Message::SetLanguage(l))))
.spacing(6);
column![
line(tr("Settings"), theme::DISPLAY, size::DISPLAY_S, t.fg),
account,
section(t, tr("Streaming quality"), column![quality, para(settings.quality.detail(), size::META, t.muted)].spacing(10).into()),
section(t, tr("Appearance"), appearance.into()),
section(t, tr("Language"), language.into()),
section(
t,
tr("Storage"),
column![
para(
tr("Covers are kept on disk so pages open instantly next time. Clearing them frees the space; they download again as you browse."),
size::META,
t.muted,
),
button(row![icon(Icon::Trash, t.fg), line(tr("Clear cover cache"), theme::MEDIUM, size::BODY, t.fg)].spacing(8).align_y(Alignment::Center))
.padding([9, 16])
.style(theme::ghost)
.on_press(Message::ClearCoverCache),
]
.spacing(12)
.into(),
),
line(trf("Musyx {} · unofficial Yandex Music client", &[&env!("CARGO_PKG_VERSION")]), theme::BODY, size::SMALL, t.muted),
]
.spacing(28)
.width(Fill)
.into()
}
fn section<'a>(t: &'static Tokens, title: &'a str, body: Element<'a, Message>) -> Element<'a, Message> {
container(column![line(title, theme::SEMIBOLD, size::SECTION, t.fg), body].spacing(14))
.padding(24)
.width(Fill)
.style(theme::card)
.into()
}
fn chip<'a>(t: &'static Tokens, label: &'static str, on: bool, msg: Message) -> Element<'a, Message> {
button(line(label, theme::MEDIUM, 13.5, if on { t.accent_ink } else { t.fg }))
.padding([7, 13])
.style(theme::chip(on))
.on_press_maybe((!on).then_some(msg))
.into()
}
+496
View File
@@ -0,0 +1,496 @@
//! Device-code sign-in: get a code, the user confirms it on Yandex's page
//! (or scans the QR), we poll until a token arrives. A pasted token is the
//! fallback for people who already have one.
use std::time::{Duration, Instant};
use iced::widget::{button, column, container, qr_code, row, space, text_input};
use iced::{Alignment, Element, Fill, Length, Padding, Subscription, Task};
use ym_api::Error;
use ym_api::auth::{Auth, Credentials, DeviceCode, Poll};
use crate::ui::icons::{Icon, icon};
use crate::ui::theme::{self, Tokens, radius, size};
use crate::ui::{line, para};
use crate::widgets::sidebar;
use crate::i18n::{tr, trf};
#[derive(Debug, Clone)]
pub enum Msg {
GetCode,
CodeReady(Result<DeviceCode, Error>),
Tick(Instant),
Polled(Result<Poll, Error>),
CopyCode,
OpenPage,
ToggleToken,
TokenChanged(String),
UseToken,
Cancel,
}
enum Stage {
Idle,
Requesting,
Waiting(Box<Waiting>),
}
struct Waiting {
code: DeviceCode,
qr: Option<qr_code::Data>,
started: Instant,
now: Instant,
next_poll: Instant,
polling: bool,
copied_at: Option<Instant>,
}
impl Waiting {
fn remaining(&self) -> Duration {
self.code.expires_in.saturating_sub(self.now.duration_since(self.started))
}
}
pub struct SignIn {
stage: Stage,
error: Option<String>,
token_open: bool,
token: String,
}
impl Default for SignIn {
fn default() -> Self {
Self { stage: Stage::Idle, error: None, token_open: false, token: String::new() }
}
}
/// What the app should do after a sign-in message.
pub enum Outcome {
Continue(Task<Msg>),
/// Credentials from Yandex (or pasted); the app saves them and connects.
Granted(Credentials),
}
impl SignIn {
/// Shown after a pasted token turned out to be invalid.
pub fn rejected_token() -> Self {
Self {
error: Some(tr("Yandex didn't accept that token. Check it and paste it again.").into()),
token_open: true,
..Self::default()
}
}
/// Shown when connecting with fresh credentials failed.
pub fn with_error(error: &Error) -> Self {
Self { error: Some(describe(error).into()), ..Self::default() }
}
pub fn update(&mut self, msg: Msg) -> Outcome {
match msg {
Msg::GetCode => {
self.error = None;
self.stage = Stage::Requesting;
return Outcome::Continue(Task::future(async {
match Auth::new() {
Ok(auth) => auth.request_code().await,
Err(e) => Err(e),
}
}).map(Msg::CodeReady));
}
Msg::CodeReady(Ok(code)) => {
let now = Instant::now();
let qr = qr_code::Data::new(code.verification_url.as_bytes()).ok();
self.stage = Stage::Waiting(Box::new(Waiting {
next_poll: now + code.interval,
code,
qr,
started: now,
now,
polling: false,
copied_at: None,
}));
}
Msg::CodeReady(Err(e)) => self.fail(&e),
Msg::Tick(now) => {
let Stage::Waiting(w) = &mut self.stage else {
return Outcome::Continue(Task::none());
};
w.now = now;
if w.remaining().is_zero() {
self.fail(&Error::CodeExpired);
} else if !w.polling && now >= w.next_poll {
w.polling = true;
let code = w.code.clone();
return Outcome::Continue(
Task::future(async move {
match Auth::new() {
Ok(auth) => auth.poll(&code).await,
Err(e) => Err(e),
}
})
.map(Msg::Polled),
);
}
}
Msg::Polled(result) => {
let Stage::Waiting(w) = &mut self.stage else {
return Outcome::Continue(Task::none());
};
w.polling = false;
match result {
Ok(Poll::Pending) => w.next_poll = Instant::now() + w.code.interval,
// A dropped poll isn't fatal: try again next interval.
Err(e) if e.is_retryable() => w.next_poll = Instant::now() + w.code.interval,
Ok(Poll::Granted(credentials)) => {
self.stage = Stage::Idle;
return Outcome::Granted(credentials);
}
Err(e) => self.fail(&e),
}
}
Msg::CopyCode => {
if let Stage::Waiting(w) = &mut self.stage {
w.copied_at = Some(w.now);
return Outcome::Continue(iced::clipboard::write(w.code.user_code.clone()));
}
}
Msg::OpenPage => {
if let Stage::Waiting(w) = &self.stage
&& open::that_detached(&w.code.verification_url).is_err()
{
self.error = Some(trf("Couldn't open your browser. Go to {} yourself.", &[&w.code.verification_url]));
}
}
Msg::ToggleToken => self.token_open = !self.token_open,
Msg::TokenChanged(token) => self.token = token,
Msg::UseToken => {
let credentials = Credentials::from_token(&self.token);
if !credentials.access_token.is_empty() {
self.token.clear();
self.stage = Stage::Idle;
return Outcome::Granted(credentials);
}
}
Msg::Cancel => {
self.stage = Stage::Idle;
self.error = None;
}
}
Outcome::Continue(Task::none())
}
fn fail(&mut self, error: &Error) {
self.stage = Stage::Idle;
self.error = Some(describe(error).into());
}
/// Ticks once a second while a code is on screen: drives the countdown and polling.
pub fn subscription(&self) -> Subscription<Msg> {
match self.stage {
Stage::Waiting(_) => iced::time::every(Duration::from_secs(1)).map(Msg::Tick),
_ => Subscription::none(),
}
}
pub fn view<'a>(&'a self, t: &'static Tokens) -> Element<'a, Msg> {
let left = column![
sidebar::wordmark(t),
container(
iced::widget::text(tr("Sign in with your Yandex account"))
.font(theme::DISPLAY)
.size(size::DISPLAY_M)
.line_height(1.12)
.color(t.fg),
)
.max_width(520),
container(para(
tr("Musyx plays your Yandex Music library, My Wave and playlists. You confirm sign-in on Yandex's own page, so your password never passes through this app."),
15.0,
t.muted,
))
.max_width(500),
self.body(t),
self.token_fallback(t),
space().height(Fill),
container(para(
tr("Musyx is an unofficial client and isn't affiliated with Yandex. Your sign-in token is kept in the system keychain."),
size::SMALL,
t.muted,
))
.max_width(520),
]
.spacing(26)
.padding(Padding::from([44, 56]))
.width(Length::FillPortion(21))
.clip(true)
.height(Fill);
let right = container(self.qr_card(t))
.center(Fill)
.width(Length::FillPortion(20))
.style(move |th| {
let mut s = theme::panel(th);
s.background = Some(iced::Background::Gradient(
iced::gradient::Linear::new(0.4)
.add_stop(0.0, t.panel)
.add_stop(1.0, theme::mix(t.panel, t.accent, 0.14))
.into(),
));
s
});
row![left, container(space()).width(1).height(Fill).style(theme::divider), right]
.height(Fill)
.into()
}
fn body<'a>(&'a self, t: &'static Tokens) -> Element<'a, Msg> {
let error = self.error.as_deref().map(|e| {
container(para(e, size::BODY, t.like)).max_width(500)
});
let content: Element<'a, Msg> = match &self.stage {
Stage::Idle => column![
primary(t, tr("Get sign-in code"), Some(Msg::GetCode)),
]
.into(),
Stage::Requesting => column![primary(t, tr("Getting a code…"), None)].into(),
Stage::Waiting(w) => self.steps(t, w),
};
column![content].push(error).spacing(16).into()
}
fn steps<'a>(&'a self, t: &'static Tokens, w: &'a Waiting) -> Element<'a, Msg> {
let host = w
.code
.verification_url
.trim_start_matches("https://")
.trim_start_matches("http://")
.trim_end_matches('/')
.to_owned();
let copied = w.copied_at.is_some_and(|at| w.now.duration_since(at) < Duration::from_secs(2));
let code_box = row![
container(line(spaced(&w.code.user_code), theme::DISPLAY, 30.0, t.fg))
.padding([14, 18])
.style(theme::card),
ghost(t, Icon::Copy, if copied { tr("Copied") } else { tr("Copy code") }, Msg::CopyCode),
]
.spacing(14)
.align_y(Alignment::Center);
let remaining = w.remaining().as_secs();
let status = row![
container(space()).width(9).height(9).style(theme::accent_dot),
line(
trf("Waiting for confirmation · code expires in {}", &[&format!("{}:{:02}", remaining / 60, remaining % 60)]),
theme::BODY,
13.5,
t.muted,
),
space().width(12),
button(line(tr("Cancel"), theme::MEDIUM, 13.5, t.muted))
.padding(0)
.style(theme::tab(false))
.on_press(Msg::Cancel),
]
.spacing(10)
.align_y(Alignment::Center);
column![
step(t, 1, column![
line(trf("Open {}", &[&host]), theme::MEDIUM, size::BODY, t.fg),
para(tr("On this computer or your phone. You can also scan the QR code."), 13.5, t.muted),
ghost(t, Icon::Globe, tr("Open in browser"), Msg::OpenPage),
].spacing(6)),
step(t, 2, column![
line(tr("Enter this code"), theme::MEDIUM, size::BODY, t.fg),
code_box,
].spacing(10)),
step(t, 3, column![
line(tr("Come back here"), theme::MEDIUM, size::BODY, t.fg),
para(tr("Musyx signs you in as soon as you allow access."), 13.5, t.muted),
].spacing(4)),
status,
]
.spacing(20)
.into()
}
fn token_fallback<'a>(&'a self, t: &'static Tokens) -> Element<'a, Msg> {
let toggle = button(line(
if self.token_open { tr("Hide token sign-in") } else { tr("Sign in with an existing token instead") },
theme::BODY,
13.5,
t.muted,
))
.padding(0)
.style(theme::tab(false))
.on_press(Msg::ToggleToken);
if !self.token_open {
return toggle.into();
}
let can_submit = !self.token.trim().is_empty();
column![
toggle,
row![
text_input(tr("Paste OAuth token"), &self.token)
.id("token")
.secure(true)
.on_input(Msg::TokenChanged)
.on_submit_maybe(can_submit.then_some(Msg::UseToken))
.padding([10, 14])
.width(320)
.style(theme::search_field),
button(line(tr("Sign in"), theme::MEDIUM, size::BODY, t.fg))
.padding([10, 18])
.style(theme::ghost)
.on_press_maybe(can_submit.then_some(Msg::UseToken)),
]
.spacing(8)
.align_y(Alignment::Center),
]
.spacing(10)
.into()
}
fn qr_card<'a>(&'a self, t: &'static Tokens) -> Element<'a, Msg> {
let qr = match &self.stage {
Stage::Waiting(w) => w.qr.as_ref(),
_ => None,
};
let (code, caption): (Element<'a, Msg>, &str) = match qr {
Some(data) => (
qr_code(data)
.total_size(200)
.style(|_| qr_code::Style {
cell: iced::Color::from_rgb8(0x1C, 0x1A, 0x22),
background: iced::Color::WHITE,
})
.into(),
tr("Scan to open the sign-in page"),
),
None => (
container(icon(Icon::Lock, iced::Color::from_rgb8(0x68, 0x61, 0x78)))
.center(200)
.into(),
tr("A QR code appears with your sign-in code"),
),
};
container(
column![
code,
line(caption, theme::BODY, size::SMALL, iced::Color::from_rgb8(0x4A, 0x44, 0x58)),
]
.spacing(10)
.align_x(Alignment::Center),
)
.padding(18)
.style(move |_| iced::widget::container::Style {
background: Some(iced::Color::WHITE.into()),
border: iced::Border { radius: radius::HERO.into(), ..Default::default() },
shadow: iced::Shadow {
color: iced::Color::BLACK.scale_alpha(if t == &theme::DARK { 0.45 } else { 0.14 }),
offset: iced::Vector::new(0.0, 18.0),
blur_radius: 50.0,
},
..Default::default()
})
.into()
}
}
/// The user's next step for each failure. Never shows the raw error.
fn describe(error: &Error) -> &'static str {
match error {
Error::CodeExpired => tr("The code expired before it was confirmed. Get a new code to try again."),
Error::Denied => tr("Access was declined on Yandex's page. Get a new code if that was a mistake."),
Error::Network(_) => tr("Can't reach Yandex. Check your connection and try again."),
Error::Unauthorized(_) => tr("Yandex didn't accept the sign-in. Get a new code to try again."),
Error::Api(_) => tr("Yandex sent an unexpected answer. Try again in a moment."),
}
}
/// `ABCD1234` → `ABCD 1234` for easier reading; codes that already have separators stay as they are.
fn spaced(code: &str) -> String {
if code.len() == 8 && code.chars().all(|c| c.is_ascii_alphanumeric()) {
format!("{} {}", &code[..4], &code[4..])
} else {
code.to_owned()
}
}
fn step<'a>(t: &'static Tokens, n: u8, content: impl Into<Element<'a, Msg>>) -> Element<'a, Msg> {
let badge = container(line(n.to_string(), theme::SEMIBOLD, size::BODY, t.muted))
.center(30)
.style(move |_| iced::widget::container::Style {
border: iced::Border { color: t.line, width: 1.0, radius: radius::PILL.into() },
..Default::default()
});
row![badge, container(content).padding(Padding::default().top(4))]
.spacing(14)
.into()
}
fn primary<'a>(t: &'static Tokens, label: &'a str, msg: Option<Msg>) -> Element<'a, Msg> {
let ink = if msg.is_some() { t.accent_ink } else { t.muted };
button(line(label, theme::SEMIBOLD, size::BODY, ink))
.padding([11, 18])
.style(theme::primary)
.on_press_maybe(msg)
.into()
}
fn ghost<'a>(t: &'static Tokens, glyph: Icon, label: &'a str, msg: Msg) -> Element<'a, Msg> {
button(
row![icon(glyph, t.fg), line(label, theme::MEDIUM, size::BODY, t.fg)]
.spacing(8)
.align_y(Alignment::Center),
)
.padding([9, 16])
.style(theme::ghost)
.on_press(msg)
.into()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn codes_are_split_for_reading() {
assert_eq!(spaced("QX7K29PM"), "QX7K 29PM");
assert_eq!(spaced("QX7-K29"), "QX7-K29");
assert_eq!(spaced("1234567"), "1234567");
}
#[test]
fn pasted_token_is_trimmed_and_granted() {
let mut s = SignIn::default();
let _ = s.update(Msg::TokenChanged(" y0_token \n".into()));
match s.update(Msg::UseToken) {
Outcome::Granted(c) => assert_eq!(c.access_token, "y0_token"),
Outcome::Continue(_) => panic!("expected credentials"),
}
assert!(s.token.is_empty(), "token must not linger in UI state");
}
#[test]
fn blank_token_is_ignored() {
let mut s = SignIn::default();
let _ = s.update(Msg::TokenChanged(" ".into()));
assert!(matches!(s.update(Msg::UseToken), Outcome::Continue(_)));
}
#[test]
fn failures_leave_an_actionable_message() {
let mut s = SignIn::default();
let _ = s.update(Msg::CodeReady(Err(Error::Network("dns".into()))));
assert!(matches!(s.stage, Stage::Idle));
assert!(s.error.as_deref().unwrap().contains("connection"));
}
}
+228
View File
@@ -0,0 +1,228 @@
//! My Wave: the animated hero, station settings and other stations.
use iced::widget::canvas::{self, Frame, Geometry, Path, Stroke};
use iced::widget::{Row, button, canvas as canvas_widget, column, container, row, stack};
use iced::{Alignment, Color, Element, Fill, Length, Padding, Point, Rectangle, Renderer, Theme, mouse};
use ym_api::{Character, Language, MY_WAVE, Mood, Station, WaveSettings};
use super::Loadable;
use super::collection::{LoadState, status};
use crate::app::Message;
use crate::covers::{self, Covers};
use crate::player::{self, Player, Status};
use crate::ui::icons::{Icon, icon};
use crate::ui::theme::{self, Tokens, radius, size};
use crate::ui::{line, para};
use crate::widgets::card;
use crate::i18n::{tr, trf};
/// Everything the My Wave screen shows.
#[derive(Debug, Default)]
pub struct WaveScreen {
pub settings: Loadable<WaveSettings>,
pub stations: Loadable<Vec<Station>>,
/// Settings picked but not yet confirmed by Yandex.
pub saving: Option<WaveSettings>,
}
impl WaveScreen {
/// The settings to show: the pending choice while saving.
pub fn shown(&self) -> Option<WaveSettings> {
self.saving.or_else(|| self.settings.get().copied())
}
}
/// Lines drifting across the hero. Moves only while a station plays.
struct WaveArt {
phase: f32,
energy: f32,
color: Color,
}
impl canvas::Program<Message> for WaveArt {
type State = ();
fn draw(&self, _: &(), renderer: &Renderer, _: &Theme, bounds: Rectangle, _: mouse::Cursor) -> Vec<Geometry> {
let mut frame = Frame::new(renderer, bounds.size());
let (w, h) = (bounds.width, bounds.height);
const LINES: usize = 14;
for k in 0..LINES {
let kf = k as f32;
let base = h * (0.22 + kf * 0.028);
let amp = h * (0.05 + kf * 0.006) * self.energy;
let freq = 1.6 + kf * 0.09;
let ph = self.phase * (0.35 + kf * 0.02) + kf * 0.5;
let path = Path::new(|b| {
let steps = (w / 6.0).ceil() as usize;
for i in 0..=steps {
let x = i as f32 * 6.0;
let u = x / w;
let y = base
+ (u * std::f32::consts::PI * freq + ph).sin() * amp
+ (u * std::f32::consts::PI * 4.2 - ph * 0.7).sin() * amp * 0.35;
if i == 0 { b.move_to(Point::new(x, y)) } else { b.line_to(Point::new(x, y)) }
}
});
let alpha = 0.08 + (kf / LINES as f32) * 0.55;
frame.stroke(&path, Stroke::default().with_color(self.color.scale_alpha(alpha)).with_width(1.0 + kf * 0.08));
}
vec![frame.into_geometry()]
}
}
/// Whether My Wave itself is what's playing.
fn my_wave_state(p: &Player) -> Option<Status> {
(p.wave_station() == Some(MY_WAVE)).then(|| p.status())
}
/// The My Wave hero, on Home (`big = false`) and the My Wave screen.
pub fn hero<'a>(
t: &'static Tokens,
player: &Player,
phase: f32,
settings: Option<WaveSettings>,
big: bool,
) -> Element<'a, Message> {
let state = my_wave_state(player);
let playing = state == Some(Status::Playing);
let art = canvas_widget(WaveArt { phase, energy: if playing { 1.0 } else { 0.45 }, color: t.accent })
.width(Fill)
.height(Fill);
let blurb = match settings {
Some(s) if s != WaveSettings::default() => trf(
"Tuned to: {} mood, {} tracks, {} language.",
&[
&tr(s.mood.label()).to_lowercase(),
&tr(s.character.label()).to_lowercase(),
&tr(s.language.label()).to_lowercase(),
],
),
_ => tr("An endless stream picked from what you play, like and skip.").to_owned(),
};
let (label, glyph, msg) = match state {
Some(Status::Playing | Status::Loading) => (tr("Pause"), Icon::Pause, Message::Player(player::Msg::Toggle)),
Some(_) => (tr("Resume"), Icon::Play, Message::Player(player::Msg::Toggle)),
None => (tr("Play My Wave"), Icon::Play, Message::PlayWave(MY_WAVE.to_owned())),
};
let content = row![
column![
line(tr("My Wave"), theme::DISPLAY, if big { size::DISPLAY_XL } else { size::DISPLAY_M }, t.fg),
container(para(blurb, size::BODY, t.muted)).max_width(420),
]
.spacing(6)
.width(Fill),
button(row![icon(glyph, t.accent_ink), line(label, theme::SEMIBOLD, size::BODY, t.accent_ink)].spacing(8).align_y(Alignment::Center))
.padding([11, 18])
.style(theme::primary)
.on_press(msg),
]
.spacing(28)
.align_y(Alignment::End);
let height = if big { 340.0 } else { 260.0 };
container(stack![
art,
container(content).padding(Padding::from([26, 28])).height(Fill).align_y(iced::alignment::Vertical::Bottom),
])
.height(height)
.width(Fill)
.clip(true)
.style(move |th| {
let mut s = theme::card(th);
s.border.radius = radius::HERO.into();
s.background = Some(iced::Background::Gradient(
iced::gradient::Linear::new(0.0)
.add_stop(0.0, t.panel)
.add_stop(1.0, theme::mix(t.panel, t.accent, 0.10))
.into(),
));
s
})
.into()
}
pub fn view<'a>(
t: &'static Tokens,
covers: &Covers,
screen: &'a WaveScreen,
hero: Element<'a, Message>,
) -> Element<'a, Message> {
let settings: Element<'a, Message> = match (&screen.settings, screen.shown()) {
(_, Some(s)) => {
let saving = screen.saving.is_some();
row![
setting(t, tr("Mood"), Mood::ALL.map(|m| (tr(m.label()), m == s.mood, WaveSettings { mood: m, ..s })), saving),
setting(t, tr("Character"), Character::ALL.map(|c| (tr(c.label()), c == s.character, WaveSettings { character: c, ..s })), saving),
setting(t, tr("Language"), Language::ALL.map(|l| (tr(l.label()), l == s.language, WaveSettings { language: l, ..s })), saving),
]
.spacing(28)
.wrap()
.vertical_spacing(18)
.into()
}
(Loadable::Failed(e), None) => status(t, LoadState::Failed(e), tr("your station settings"), Message::LoadWave),
_ => para(tr("Loading your settings…"), size::BODY, t.muted).into(),
};
let stations: Element<'a, Message> = match &screen.stations {
Loadable::Loaded(list) => {
let others: Vec<&Station> = list.iter().filter(|s| s.id != MY_WAVE).collect();
if others.is_empty() {
para(tr("No other stations suggested right now."), size::BODY, t.muted).into()
} else {
Row::with_children(others.into_iter().map(|s| station_tile(t, covers, s)))
.spacing(12)
.wrap()
.vertical_spacing(14)
.into()
}
}
Loadable::Failed(e) => status(t, LoadState::Failed(e), tr("stations"), Message::LoadWave),
_ => para(tr("Loading stations…"), size::BODY, t.muted).into(),
};
column![
hero,
settings,
column![line(tr("Stations"), theme::SEMIBOLD, size::SECTION, t.fg), stations].spacing(14),
]
.spacing(34)
.into()
}
fn setting<'a, const N: usize>(
t: &'static Tokens,
title: &'a str,
options: [(&'static str, bool, WaveSettings); N],
saving: bool,
) -> Element<'a, Message> {
let chips = options.map(|(label, on, next)| {
button(line(label, theme::MEDIUM, 13.5, if on { t.accent_ink } else { t.fg }))
.padding([7, 13])
.style(theme::chip(on))
.on_press_maybe((!on && !saving).then_some(Message::SetWaveSettings(next)))
.into()
});
column![line(title, theme::MEDIUM, size::BODY, t.muted), Row::with_children(chips).spacing(6)]
.spacing(10)
.into()
}
fn station_tile<'a>(t: &'static Tokens, covers: &Covers, s: &Station) -> Element<'a, Message> {
let tint = s.color.as_deref().and_then(super::browse::parse_hex).unwrap_or(t.raised);
let art = container(covers::view(covers, s.icon_url(200), (0.0, 0.0), 96.0, 0.0))
.center(card::WIDTH)
.style(move |_| container::Style {
background: Some(tint.into()),
border: iced::Border { radius: radius::COVER.into(), ..Default::default() },
..Default::default()
});
button(column![art, line(s.name.clone(), theme::MEDIUM, size::BODY, t.fg)].spacing(9).width(Length::Fixed(card::WIDTH)))
.padding(6)
.style(theme::nav_item(false))
.on_press(Message::PlayWave(s.id.clone()))
.into()
}