Files
musyz-mobile/reference/musyx/src/screens/browse.rs
T
yuriy.pandClaude Opus 5.5 46610d95fa 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>
2026-10-16 22:14:54 +06:00

364 lines
14 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 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());
}
}