feat: context menu for tracks, albums, playlists and artists
Replace the centred track dialog with a menu that opens at the pointer on a right-click, or under a row's "…", without dimming the window. It flips at the window edges, groups its entries, names each artist, and opens "Add to playlist" as a submenu. Every action closes it and a toast confirms it; arrow keys, Enter and Esc work inside it. The same menu opens from the player bar, the queue drawer (with Play now and Remove from queue) and album, playlist and artist cards (Play, Shuffle, collection, or Rename/Delete for your own playlists). Playing from a card loads the page first. Rows of your own playlists get a drag handle: the list reorders live while dragging, and Esc cancels. Move to top and Move to bottom replace Move up/down. A right-click inside a scrolled list reports window coordinates: iced hands each widget its offset when it asks for overlays, before every event, and the anchor widget keeps it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e5c43fbb77
commit
ac5c8c4c8c
21 files changed
+1386
-230
No files matched your search
@@ -0,0 +1,17 @@
|
||||
<!-- @license lucide-static v0.460.0 - ISC -->
|
||||
<svg
|
||||
class="lucide lucide-arrow-down-to-line"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M12 17V3" />
|
||||
<path d="m6 11 6 6 6-6" />
|
||||
<path d="M19 21H5" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 375 B |
@@ -0,0 +1,17 @@
|
||||
<!-- @license lucide-static v0.460.0 - ISC -->
|
||||
<svg
|
||||
class="lucide lucide-arrow-up-to-line"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M5 3h14" />
|
||||
<path d="m18 13-6-6-6 6" />
|
||||
<path d="M12 7v14" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 373 B |
@@ -0,0 +1,16 @@
|
||||
<!-- @license lucide-static v0.460.0 - ISC -->
|
||||
<svg
|
||||
class="lucide lucide-user"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" />
|
||||
<circle cx="12" cy="7" r="4" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 375 B |
+350
-33
@@ -29,9 +29,10 @@ use crate::shortcuts::{self, Shortcut};
|
||||
use crate::store::{self, Appearance, Locale, Quality, Settings};
|
||||
use crate::ui::theme::{self, shell};
|
||||
use crate::widgets::drawer::{self, Panel};
|
||||
use crate::widgets::menu::{self, Menu};
|
||||
use crate::widgets::player_bar;
|
||||
use crate::widgets::sheet::{self, Sheet};
|
||||
use crate::widgets::track_list::Env;
|
||||
use crate::widgets::track_list::{Drag, Env};
|
||||
use crate::widgets::{sidebar, topbar};
|
||||
|
||||
/// Where sign-in stands. Everything but `SignedIn` takes the whole window.
|
||||
@@ -66,6 +67,11 @@ pub struct App {
|
||||
/// Albums, artists and playlists liked, and tracks disliked, by id.
|
||||
likes: LikedIds,
|
||||
sheet: Option<Sheet>,
|
||||
menu: Option<Menu>,
|
||||
/// A row of an own playlist being dragged to a new place.
|
||||
drag: Option<Drag>,
|
||||
/// Play this page's tracks once it loads ("Play" in a card's menu).
|
||||
pending_play: Option<(Route, bool)>,
|
||||
toast: Option<(String, std::time::Instant)>,
|
||||
/// Lyrics per track id, fetched while the lyrics panel is open.
|
||||
lyrics: HashMap<String, Loadable<Option<Arc<Lyrics>>>>,
|
||||
@@ -151,6 +157,22 @@ pub enum Message {
|
||||
LikeArtist(i64, bool),
|
||||
LikePlaylist(PlaylistId, bool),
|
||||
OpenSheet(Sheet),
|
||||
OpenMenu(Box<Menu>),
|
||||
CloseMenu,
|
||||
/// The pointer is over this menu entry.
|
||||
MenuHover(usize),
|
||||
MenuSubHover(usize),
|
||||
/// Show or hide the "Add to playlist" list.
|
||||
MenuSub(bool),
|
||||
/// A menu entry was chosen: close the menu, then do it.
|
||||
MenuPick(Box<Message>),
|
||||
/// Play an album, artist or playlist, loading its page first if needed.
|
||||
PlayRoute { route: Route, shuffle: bool },
|
||||
/// A drag handle in an own playlist was pressed on this row.
|
||||
DragStart { playlist: PlaylistId, track: Track, index: usize },
|
||||
/// The dragged row is over this place in the list.
|
||||
DragOver(usize),
|
||||
DragEnd,
|
||||
CloseSheet,
|
||||
SheetText(String),
|
||||
PlayNext(Track),
|
||||
@@ -195,6 +217,9 @@ impl App {
|
||||
covers: Covers::default(),
|
||||
likes: LikedIds::default(),
|
||||
sheet: None,
|
||||
menu: None,
|
||||
drag: None,
|
||||
pending_play: None,
|
||||
toast: None,
|
||||
lyrics: HashMap::new(),
|
||||
lyric_line: None,
|
||||
@@ -232,6 +257,9 @@ impl App {
|
||||
app.session = config.session();
|
||||
app.library.liked = Liked::loaded(config.sample_liked(), &Liked::NotLoaded);
|
||||
app.pages.insert(Route::Album(1), Loadable::Loaded(config.sample_album()));
|
||||
app.pages.insert(Route::Playlist(crate::snapshot::OWN_PLAYLIST), Loadable::Loaded(config.sample_playlist()));
|
||||
app.menu = config.menu();
|
||||
app.drag = config.drag();
|
||||
if let Some(route) = config.route {
|
||||
app.nav = Navigator::new(route);
|
||||
}
|
||||
@@ -278,6 +306,13 @@ impl App {
|
||||
if matches!(self.session, Session::SignedIn { .. }) {
|
||||
subs.push(shortcuts::subscription().map(Message::Shortcut));
|
||||
}
|
||||
if self.drag.is_some() {
|
||||
// The button can come up anywhere, over the list or not.
|
||||
subs.push(iced::event::listen_with(|event, _, _| match event {
|
||||
iced::Event::Mouse(iced::mouse::Event::ButtonReleased(iced::mouse::Button::Left)) => Some(Message::DragEnd),
|
||||
_ => None,
|
||||
}));
|
||||
}
|
||||
// The hero's lines drift only while My Wave plays and the hero is on screen.
|
||||
let hero_visible = matches!(self.nav.current(), Route::Home | Route::Wave);
|
||||
let wave_playing = self.player.wave_station() == Some(MY_WAVE)
|
||||
@@ -473,6 +508,7 @@ impl App {
|
||||
}
|
||||
Message::Navigate(route) => {
|
||||
self.sheet = None;
|
||||
self.menu = None;
|
||||
self.nav.go(route);
|
||||
let (close, _) = self.search.update(search::Msg::CloseSuggestions, None);
|
||||
// Opening Search is a request to type.
|
||||
@@ -599,6 +635,79 @@ impl App {
|
||||
}
|
||||
}
|
||||
Message::CloseSheet => self.sheet = None,
|
||||
Message::OpenMenu(menu) => {
|
||||
self.sheet = None;
|
||||
let (close, _) = self.search.update(search::Msg::CloseSuggestions, None);
|
||||
self.menu = Some(*menu);
|
||||
return close;
|
||||
}
|
||||
Message::CloseMenu => self.menu = None,
|
||||
Message::MenuHover(i) => {
|
||||
let submenu = self.menu_entry(i).is_some_and(|e| matches!(e.action, menu::Action::Submenu));
|
||||
if let Some(menu) = &mut self.menu {
|
||||
menu.highlight = Some(i);
|
||||
menu.sub = match (submenu, menu.sub) {
|
||||
(true, open @ Some(_)) => open,
|
||||
(true, None) => Some(None),
|
||||
(false, _) => None,
|
||||
};
|
||||
}
|
||||
}
|
||||
Message::MenuSubHover(j) => {
|
||||
if let Some(menu) = &mut self.menu {
|
||||
menu.sub = Some(Some(j));
|
||||
}
|
||||
}
|
||||
Message::MenuSub(open) => {
|
||||
if let Some(menu) = &mut self.menu {
|
||||
menu.sub = open.then_some(menu.sub.flatten());
|
||||
}
|
||||
}
|
||||
Message::MenuPick(msg) => {
|
||||
self.menu = None;
|
||||
return self.update(*msg);
|
||||
}
|
||||
Message::PlayRoute { route, shuffle } => {
|
||||
let tracks = match self.pages.get(&route) {
|
||||
Some(Loadable::Loaded(Page::Album { tracks, .. } | Page::Playlist { tracks, .. })) => tracks.clone(),
|
||||
Some(Loadable::Loaded(Page::Artist { popular, .. })) => popular.clone(),
|
||||
Some(Loadable::Loading) => {
|
||||
self.pending_play = Some((route, shuffle));
|
||||
return Task::none();
|
||||
}
|
||||
_ => {
|
||||
let Some(task) = self.client().and_then(|c| detail::load(c, route)) else { return Task::none() };
|
||||
self.pending_play = Some((route, shuffle));
|
||||
self.pages.insert(route, Loadable::Loading);
|
||||
return task;
|
||||
}
|
||||
};
|
||||
if tracks.is_empty() {
|
||||
self.toast(tr("There's nothing to play here."));
|
||||
return Task::none();
|
||||
}
|
||||
return self.update(Message::PlayTracks { tracks, start: 0, shuffle });
|
||||
}
|
||||
Message::DragStart { playlist, track, index } => {
|
||||
self.menu = None;
|
||||
self.drag = Some(Drag { playlist, track, from: index, to: index });
|
||||
}
|
||||
Message::DragOver(to) => {
|
||||
if let Some(drag) = &mut self.drag {
|
||||
drag.to = to;
|
||||
}
|
||||
}
|
||||
Message::DragEnd => {
|
||||
let Some(Drag { playlist, track, from, to }) = self.drag.take() else { return Task::none() };
|
||||
if from == to {
|
||||
return Task::none();
|
||||
}
|
||||
// Show the new order now; the refresh after the edit confirms it.
|
||||
if let Some(Loadable::Loaded(Page::Playlist { tracks, .. })) = self.pages.get_mut(&Route::Playlist(playlist)) {
|
||||
*tracks = crate::widgets::track_list::moved(tracks, from, to);
|
||||
}
|
||||
return self.update(Message::MovePlaylistTrack { id: playlist, track, from, to });
|
||||
}
|
||||
Message::SheetText(text) => {
|
||||
if let Some(Sheet::NewPlaylist { name, .. } | Sheet::Rename { name, .. }) = &mut self.sheet {
|
||||
*name = text;
|
||||
@@ -726,7 +835,18 @@ impl App {
|
||||
{
|
||||
return task;
|
||||
}
|
||||
let failed = result.is_err();
|
||||
self.pages.insert(route, Loadable::from_result(result));
|
||||
if let Some((wanted, shuffle)) = self.pending_play
|
||||
&& wanted == route
|
||||
{
|
||||
self.pending_play = None;
|
||||
if failed {
|
||||
self.toast(tr("Couldn't load the tracks. Try again."));
|
||||
return Task::none();
|
||||
}
|
||||
return self.update(Message::PlayRoute { route, shuffle });
|
||||
}
|
||||
}
|
||||
Message::LoadHome => {
|
||||
let Some(client) = self.client().cloned() else { return Task::none() };
|
||||
@@ -888,7 +1008,11 @@ impl App {
|
||||
Shortcut::Back if self.nav.can_go_back() => Message::Back,
|
||||
Shortcut::Back => return Task::none(),
|
||||
Shortcut::Dismiss => {
|
||||
if self.sheet.is_some() {
|
||||
if self.drag.is_some() {
|
||||
self.drag = None;
|
||||
} else if self.menu.is_some() {
|
||||
self.menu = None;
|
||||
} else if self.sheet.is_some() {
|
||||
self.sheet = None;
|
||||
} else if self.search.suggestions().is_some() {
|
||||
return self.update(Message::Search(search::Msg::CloseSuggestions));
|
||||
@@ -898,10 +1022,80 @@ impl App {
|
||||
return Task::none();
|
||||
}
|
||||
Shortcut::Go(route) => Message::Navigate(route),
|
||||
Shortcut::MenuUp | Shortcut::MenuDown | Shortcut::MenuIn | Shortcut::MenuOut | Shortcut::MenuEnter => {
|
||||
return self.menu_key(shortcut);
|
||||
}
|
||||
};
|
||||
self.update(msg)
|
||||
}
|
||||
|
||||
/// Arrow keys and Enter inside an open menu.
|
||||
fn menu_key(&mut self, key: Shortcut) -> Task<Message> {
|
||||
let Some(open) = &self.menu else { return Task::none() };
|
||||
let groups = menu::groups(&open.target, &self.menu_ctx(&open.target));
|
||||
let entries: Vec<&menu::Entry> = menu::flat(&groups).collect();
|
||||
let subs = match open.track() {
|
||||
Some(track) => menu::sub_entries(track, self.own_playlists()),
|
||||
None => Vec::new(),
|
||||
};
|
||||
let highlighted = open.highlight.and_then(|i| entries.get(i));
|
||||
let on_submenu = highlighted.is_some_and(|e| matches!(e.action, menu::Action::Submenu));
|
||||
let (mut highlight, mut sub) = (open.highlight, open.sub);
|
||||
let mut pick = None;
|
||||
match (key, sub) {
|
||||
(Shortcut::MenuDown | Shortcut::MenuUp, Some(Some(j))) if !subs.is_empty() => {
|
||||
let n = subs.len();
|
||||
sub = Some(Some(if key == Shortcut::MenuDown { (j + 1) % n } else { (j + n - 1) % n }));
|
||||
}
|
||||
(Shortcut::MenuDown | Shortcut::MenuUp, _) => {
|
||||
highlight = menu::step(&entries, highlight, key == Shortcut::MenuDown);
|
||||
sub = None;
|
||||
}
|
||||
(Shortcut::MenuIn, _) if on_submenu => sub = Some(Some(0)),
|
||||
(Shortcut::MenuOut, Some(_)) => sub = None,
|
||||
(Shortcut::MenuEnter, Some(Some(j))) => pick = subs.get(j).cloned(),
|
||||
(Shortcut::MenuEnter, _) if on_submenu => sub = Some(Some(0)),
|
||||
(Shortcut::MenuEnter, _) => pick = highlighted.map(|e| (*e).clone()),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(menu::Entry { action: menu::Action::Send(msg), .. }) = pick {
|
||||
return self.update(Message::MenuPick(msg));
|
||||
}
|
||||
if let Some(open) = &mut self.menu {
|
||||
open.highlight = highlight;
|
||||
open.sub = sub;
|
||||
}
|
||||
Task::none()
|
||||
}
|
||||
|
||||
fn own_playlists(&self) -> &[PlaylistSummary] {
|
||||
self.library.playlists.get().map_or(&[], |p| p.own.as_slice())
|
||||
}
|
||||
|
||||
fn menu_ctx(&self, target: &menu::Target) -> menu::Ctx<'_> {
|
||||
use menu::Target;
|
||||
let (playing, liked, disliked) = match target {
|
||||
Target::Track { track, .. } => (
|
||||
self.player.track().is_some_and(|tr| tr.id == track.id),
|
||||
self.library.liked.contains(&track.id),
|
||||
self.likes.disliked_tracks.contains(&track.id),
|
||||
),
|
||||
Target::Album(a) => (false, self.likes.albums.contains(&a.id), false),
|
||||
Target::Playlist(p) => (false, self.likes.playlists.contains(&p.id), false),
|
||||
Target::Artist(a) => (false, self.likes.artists.contains(&a.id), false),
|
||||
};
|
||||
let me = match &self.session {
|
||||
Session::SignedIn { account, .. } => account.uid,
|
||||
_ => 0,
|
||||
};
|
||||
menu::Ctx { playing, liked, disliked, own_playlists: self.own_playlists(), me }
|
||||
}
|
||||
|
||||
fn menu_entry(&self, i: usize) -> Option<menu::Entry> {
|
||||
let open = self.menu.as_ref()?;
|
||||
menu::flat(&menu::groups(&open.target, &self.menu_ctx(&open.target))).nth(i).cloned()
|
||||
}
|
||||
|
||||
/// Loads what a route shows on first visit, and retries after a failure.
|
||||
fn on_enter(&mut self, route: Route) -> Task<Message> {
|
||||
match route {
|
||||
@@ -1041,6 +1235,8 @@ impl App {
|
||||
likes: &self.likes,
|
||||
playing: self.player.track().map(|tr| tr.id.as_str()),
|
||||
me: account.uid,
|
||||
menu_track: self.menu.as_ref().and_then(Menu::track).map(|tr| tr.id.as_str()),
|
||||
drag: self.drag.as_ref(),
|
||||
};
|
||||
|
||||
let page = scrollable(screens::view(screens::Ctx {
|
||||
@@ -1106,21 +1302,10 @@ impl App {
|
||||
layers = layers.push(sheet::toast(t, text));
|
||||
}
|
||||
if let Some(open) = &self.sheet {
|
||||
let track_id = match open {
|
||||
Sheet::Track { track, .. } => Some(track.id.as_str()),
|
||||
_ => None,
|
||||
};
|
||||
let own: &[PlaylistSummary] = self.library.playlists.get().map_or(&[], |p| p.own.as_slice());
|
||||
layers = layers.push(sheet::overlay(
|
||||
t,
|
||||
open,
|
||||
sheet::Ctx {
|
||||
playing: track_id.is_some() && self.player.track().map(|tr| tr.id.as_str()) == track_id,
|
||||
liked: track_id.is_some_and(|id| self.library.liked.contains(id)),
|
||||
disliked: track_id.is_some_and(|id| self.likes.disliked_tracks.contains(id)),
|
||||
own_playlists: own,
|
||||
},
|
||||
));
|
||||
layers = layers.push(sheet::overlay(t, open));
|
||||
}
|
||||
if let Some(open) = &self.menu {
|
||||
layers = layers.push(menu::layer(t, open, self.menu_ctx(&open.target)));
|
||||
}
|
||||
layers.into()
|
||||
}
|
||||
@@ -1267,6 +1452,15 @@ mod tests {
|
||||
Track::from_json(&format!(r#"{{"id":"{id}","title":"T{id}","durationMs":100000}}"#)).unwrap()
|
||||
}
|
||||
|
||||
fn open_menu(app: &mut App, track: Track, from: menu::Source) {
|
||||
let at = menu::Anchor::Point(iced::Point::new(400.0, 200.0));
|
||||
let _ = app.update(Message::OpenMenu(Box::new(Menu::new(menu::Target::Track { track, from }, at))));
|
||||
}
|
||||
|
||||
fn pick(app: &mut App, msg: Message) {
|
||||
let _ = app.update(Message::MenuPick(Box::new(msg)));
|
||||
}
|
||||
|
||||
fn upcoming(app: &App) -> Vec<String> {
|
||||
app.player.queue().map(|q| q.upcoming().map(|(_, t)| t.id.clone()).collect()).unwrap_or_default()
|
||||
}
|
||||
@@ -1276,9 +1470,9 @@ mod tests {
|
||||
let mut app = signed_in();
|
||||
let tracks: Arc<[Track]> = vec![track("a"), track("b"), track("c")].into();
|
||||
let _ = app.update(Message::PlayTracks { tracks, start: 0, shuffle: false });
|
||||
let _ = app.update(Message::OpenSheet(Sheet::Track { track: track("n"), playlist: None, choosing: false }));
|
||||
let _ = app.update(Message::PlayNext(track("n")));
|
||||
assert!(app.sheet.is_none());
|
||||
open_menu(&mut app, track("n"), menu::Source::List { playlist: None });
|
||||
pick(&mut app, Message::PlayNext(track("n")));
|
||||
assert!(app.menu.is_none());
|
||||
assert_eq!(upcoming(&app), ["n", "b", "c"]);
|
||||
let _ = app.update(Message::Player(player::Msg::Next));
|
||||
assert_eq!(app.player.track().unwrap().id, "n");
|
||||
@@ -1289,11 +1483,11 @@ mod tests {
|
||||
let mut app = signed_in();
|
||||
let tracks: Arc<[Track]> = vec![track("a"), track("b")].into();
|
||||
let _ = app.update(Message::PlayTracks { tracks, start: 0, shuffle: false });
|
||||
let _ = app.update(Message::OpenSheet(Sheet::Track { track: track("a"), playlist: None, choosing: false }));
|
||||
open_menu(&mut app, track("a"), menu::Source::List { playlist: None });
|
||||
let messages = click_in_window(&app, "Next track");
|
||||
assert_eq!(messages, ["SkipFromMenu"]);
|
||||
let _ = app.update(Message::SkipFromMenu);
|
||||
assert!(app.sheet.is_none());
|
||||
assert_eq!(messages, ["MenuPick(SkipFromMenu)"]);
|
||||
pick(&mut app, Message::SkipFromMenu);
|
||||
assert!(app.menu.is_none());
|
||||
assert_eq!(app.player.track().unwrap().id, "b");
|
||||
}
|
||||
|
||||
@@ -1301,9 +1495,9 @@ mod tests {
|
||||
fn escape_closes_the_menu_then_the_drawer() {
|
||||
let mut app = signed_in();
|
||||
let _ = app.update(Message::ToggleDrawer(Panel::Queue));
|
||||
let _ = app.update(Message::OpenSheet(Sheet::Track { track: track("a"), playlist: None, choosing: false }));
|
||||
open_menu(&mut app, track("a"), menu::Source::List { playlist: None });
|
||||
let _ = app.update(Message::Shortcut(Shortcut::Dismiss));
|
||||
assert!(app.sheet.is_none());
|
||||
assert!(app.menu.is_none());
|
||||
assert_eq!(app.drawer, Some(Panel::Queue));
|
||||
let _ = app.update(Message::Shortcut(Shortcut::Dismiss));
|
||||
assert_eq!(app.drawer, None);
|
||||
@@ -1362,8 +1556,8 @@ mod tests {
|
||||
app.pages.insert(Route::Playlist(id), Loadable::Loaded(crate::screens::detail::Page::Playlist { info, tracks: tracks.clone() }));
|
||||
app.nav = Navigator::new(Route::Playlist(id));
|
||||
let _ = app.update(Message::PlayTracks { tracks: tracks.clone(), start: 0, shuffle: false });
|
||||
let _ = app.update(Message::OpenSheet(Sheet::Track { track: tracks[5].clone(), playlist: Some((id, 5, 30)), choosing: false }));
|
||||
for label in ["Play next", "Add to queue", "Move up"] {
|
||||
open_menu(&mut app, tracks[5].clone(), menu::Source::List { playlist: Some((id, 5, 30)) });
|
||||
for label in ["Play next", "Add to queue", "Move to top"] {
|
||||
let messages = click_in_window(&app, label);
|
||||
assert!(
|
||||
!messages.iter().any(|m| m.starts_with("PlayTracks")),
|
||||
@@ -1400,9 +1594,9 @@ mod tests {
|
||||
fn similar_tracks_replace_the_queue_and_say_so() {
|
||||
let mut app = signed_in();
|
||||
let _ = app.update(Message::PlayTracks { tracks: vec![track("a"), track("b")].into(), start: 0, shuffle: false });
|
||||
let _ = app.update(Message::OpenSheet(Sheet::Track { track: track("a"), playlist: None, choosing: false }));
|
||||
let _ = app.update(Message::PlaySimilar(track("a")));
|
||||
assert!(app.sheet.is_none());
|
||||
open_menu(&mut app, track("a"), menu::Source::List { playlist: None });
|
||||
pick(&mut app, Message::PlaySimilar(track("a")));
|
||||
assert!(app.menu.is_none());
|
||||
let _ = app.update(Message::SimilarLoaded(track("a"), Ok(vec![track("s1"), track("s2")])));
|
||||
assert_eq!(app.player.track().unwrap().id, "s1");
|
||||
assert_eq!(upcoming(&app), ["s2"]);
|
||||
@@ -1431,14 +1625,137 @@ mod tests {
|
||||
if toast {
|
||||
app.toast("Added to Liked tracks");
|
||||
}
|
||||
let _ = app.update(Message::OpenSheet(Sheet::Track { track: track("n"), playlist: None, choosing: false }));
|
||||
open_menu(&mut app, track("n"), menu::Source::List { playlist: None });
|
||||
for label in ["Play next", "Add to queue", "Add to Liked tracks"] {
|
||||
let messages = click_in_window(&app, label);
|
||||
assert!(
|
||||
messages.first().is_some_and(|m| !m.starts_with("CloseSheet")),
|
||||
messages.first().is_some_and(|m| m.starts_with("MenuPick")),
|
||||
"{label} (toast: {toast}) produced {messages:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn own_playlist(app: &mut App, n: usize) -> (PlaylistId, Arc<[Track]>) {
|
||||
let id = PlaylistId { owner: 1, kind: 1002 };
|
||||
let tracks: Arc<[Track]> = (0..n).map(|i| track(&i.to_string())).collect();
|
||||
let info = ym_api::PlaylistPage {
|
||||
playlist: ym_api::PlaylistSummary::for_tests(id, "Дорога"),
|
||||
description: None,
|
||||
tracks: Vec::new(),
|
||||
};
|
||||
app.pages.insert(Route::Playlist(id), Loadable::Loaded(crate::screens::detail::Page::Playlist { info, tracks: tracks.clone() }));
|
||||
app.nav = Navigator::new(Route::Playlist(id));
|
||||
(id, tracks)
|
||||
}
|
||||
|
||||
fn page_ids(app: &App, id: PlaylistId) -> Vec<String> {
|
||||
match app.pages.get(&Route::Playlist(id)) {
|
||||
Some(Loadable::Loaded(crate::screens::detail::Page::Playlist { tracks, .. })) => tracks.iter().map(|t| t.id.clone()).collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_a_dragged_row_shows_the_new_order_at_once() {
|
||||
let mut app = signed_in();
|
||||
let (id, tracks) = own_playlist(&mut app, 5);
|
||||
let _ = app.update(Message::DragStart { playlist: id, track: tracks[1].clone(), index: 1 });
|
||||
let _ = app.update(Message::DragOver(3));
|
||||
let _ = app.update(Message::DragEnd);
|
||||
assert!(app.drag.is_none());
|
||||
assert_eq!(page_ids(&app, id), ["0", "2", "3", "1", "4"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_cancels_a_drag_without_moving_anything() {
|
||||
let mut app = signed_in();
|
||||
let (id, tracks) = own_playlist(&mut app, 5);
|
||||
let _ = app.update(Message::DragStart { playlist: id, track: tracks[0].clone(), index: 0 });
|
||||
let _ = app.update(Message::DragOver(4));
|
||||
let _ = app.update(Message::Shortcut(Shortcut::Dismiss));
|
||||
assert!(app.drag.is_none());
|
||||
let _ = app.update(Message::DragEnd);
|
||||
assert_eq!(page_ids(&app, id), ["0", "1", "2", "3", "4"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_list_previews_the_order_while_dragging() {
|
||||
let mut app = signed_in();
|
||||
let (id, tracks) = own_playlist(&mut app, 4);
|
||||
let _ = app.update(Message::DragStart { playlist: id, track: tracks[0].clone(), index: 0 });
|
||||
let _ = app.update(Message::DragOver(2));
|
||||
// A press on a row mid-drag must not start playback.
|
||||
let messages = click_in_window(&app, "T1");
|
||||
assert!(!messages.iter().any(|m| m.starts_with("PlayTracks")), "{messages:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn play_from_a_card_waits_for_the_page_then_plays() {
|
||||
let mut app = signed_in();
|
||||
let route = Route::Album(9);
|
||||
let _ = app.update(Message::PlayRoute { route, shuffle: false });
|
||||
assert!(matches!(app.pages.get(&route), Some(Loadable::Loading)));
|
||||
assert!(app.player.track().is_none());
|
||||
let mut info = ym_api::AlbumPage::from_json(r#"{"id":9,"title":"A","volumes":[[{"id":"x","title":"X"},{"id":"y","title":"Y"}]]}"#).unwrap();
|
||||
let tracks = std::mem::take(&mut info.tracks).into();
|
||||
let _ = app.update(Message::PageLoaded(route, Ok(crate::screens::detail::Page::Album { info, tracks })));
|
||||
assert_eq!(app.player.track().unwrap().id, "x");
|
||||
assert!(app.pending_play.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn play_from_a_card_says_so_when_the_page_fails() {
|
||||
let mut app = signed_in();
|
||||
let route = Route::Playlist(PlaylistId { owner: 2, kind: 5 });
|
||||
let _ = app.update(Message::PlayRoute { route, shuffle: true });
|
||||
let _ = app.update(Message::PageLoaded(route, Err(Error::Network("offline".into()))));
|
||||
assert!(app.player.track().is_none());
|
||||
assert!(app.toast.as_ref().is_some_and(|(t, _)| t.starts_with("Couldn't load the tracks")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrow_keys_and_enter_pick_from_the_menu() {
|
||||
let mut app = signed_in();
|
||||
let tracks: Arc<[Track]> = vec![track("a"), track("b"), track("c")].into();
|
||||
let _ = app.update(Message::PlayTracks { tracks, start: 0, shuffle: false });
|
||||
open_menu(&mut app, track("c"), menu::Source::List { playlist: None });
|
||||
let _ = app.update(Message::Shortcut(Shortcut::MenuDown));
|
||||
assert_eq!(app.menu.as_ref().unwrap().highlight, Some(0));
|
||||
let _ = app.update(Message::Shortcut(Shortcut::MenuEnter));
|
||||
assert!(app.menu.is_none(), "picking closes the menu");
|
||||
assert_eq!(upcoming(&app), ["c", "b"], "Play next moved c up");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_playlist_submenu_opens_on_hover_and_with_the_right_arrow() {
|
||||
let mut app = signed_in();
|
||||
open_menu(&mut app, track("a"), menu::Source::List { playlist: None });
|
||||
// Entry 4 is "Add to playlist": the first group has three entries.
|
||||
let _ = app.update(Message::MenuHover(4));
|
||||
assert_eq!(app.menu.as_ref().unwrap().sub, Some(None));
|
||||
let _ = app.update(Message::MenuHover(3));
|
||||
assert_eq!(app.menu.as_ref().unwrap().sub, None, "moving off it closes the list");
|
||||
let _ = app.update(Message::Shortcut(Shortcut::MenuDown));
|
||||
let _ = app.update(Message::Shortcut(Shortcut::MenuIn));
|
||||
assert_eq!(app.menu.as_ref().unwrap().sub, Some(Some(0)));
|
||||
let _ = app.update(Message::Shortcut(Shortcut::MenuOut));
|
||||
assert_eq!(app.menu.as_ref().unwrap().sub, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_from_the_queue_drops_the_track() {
|
||||
let mut app = signed_in();
|
||||
let tracks: Arc<[Track]> = vec![track("a"), track("b"), track("c")].into();
|
||||
let _ = app.update(Message::PlayTracks { tracks, start: 0, shuffle: false });
|
||||
open_menu(&mut app, track("b"), menu::Source::Queue { pos: 1 });
|
||||
let messages = click_in_window(&app, "Remove from queue");
|
||||
assert!(messages.first().is_some_and(|m| m.starts_with("MenuPick(Player(Remove { pos: 1")), "{messages:?}");
|
||||
// A track queued meanwhile shifts positions; the stale one removes nothing.
|
||||
let _ = app.update(Message::PlayNext(track("n")));
|
||||
pick(&mut app, Message::Player(player::Msg::Remove { pos: 1, id: "b".into() }));
|
||||
assert_eq!(upcoming(&app), ["n", "b", "c"]);
|
||||
pick(&mut app, Message::Player(player::Msg::Remove { pos: 2, id: "b".into() }));
|
||||
assert_eq!(upcoming(&app), ["n", "c"]);
|
||||
}
|
||||
}
|
||||
@@ -309,6 +309,17 @@ pub fn get(english: &str) -> Option<&'static str> {
|
||||
"Move up" => "Переместить выше",
|
||||
"Move down" => "Переместить ниже",
|
||||
"Remove from this playlist" => "Удалить из этого плейлиста",
|
||||
"Rename…" => "Переименовать…",
|
||||
"Delete…" => "Удалить…",
|
||||
"Play now" => "Играть сейчас",
|
||||
"Remove from queue" => "Убрать из очереди",
|
||||
"Move to top" => "Переместить в начало",
|
||||
"Move to bottom" => "Переместить в конец",
|
||||
"Add to collection" => "Добавить в коллекцию",
|
||||
"Remove from collection" => "Убрать из коллекции",
|
||||
"Go to {}" => "Исполнитель: {}",
|
||||
"Couldn't load the tracks. Try again." => "Не удалось загрузить треки. Попробуйте ещё раз.",
|
||||
"There's nothing to play here." => "Здесь нечего слушать.",
|
||||
"New playlist…" => "Новый плейлист…",
|
||||
"New playlist" => "Новый плейлист",
|
||||
"Rename playlist" => "Переименовать плейлист",
|
||||
|
||||
@@ -55,6 +55,9 @@ pub enum Msg {
|
||||
SetVolume(f32),
|
||||
ToggleMute,
|
||||
JumpTo(usize),
|
||||
/// Take an upcoming track out of the queue: a position from `Queue::upcoming`
|
||||
/// and the track's id, so a queue that changed meanwhile loses nothing else.
|
||||
Remove { pos: usize, id: String },
|
||||
Fetched { generation: u64, result: Result<Audio, Error> },
|
||||
Prefetched { track_id: String, result: Result<Audio, Error> },
|
||||
/// Start a station (`type:tag`).
|
||||
@@ -321,6 +324,14 @@ impl Player {
|
||||
}
|
||||
self.send(Command::Volume(self.effective_volume()));
|
||||
}
|
||||
Msg::Remove { pos, id } => {
|
||||
if let Some(queue) = &mut self.queue
|
||||
&& queue.upcoming().any(|(p, t)| p == pos && t.id == id)
|
||||
&& queue.remove(pos)
|
||||
{
|
||||
return self.prefetch_next();
|
||||
}
|
||||
}
|
||||
Msg::JumpTo(pos) => {
|
||||
let mut effects = self.leave(false);
|
||||
if let Some(queue) = &mut self.queue {
|
||||
|
||||
@@ -161,6 +161,23 @@ impl<T> Queue<T> {
|
||||
true
|
||||
}
|
||||
|
||||
/// Takes an upcoming item out of the play order. Positions are the ones
|
||||
/// [`Queue::upcoming`] reports; the current item and anything before it stay.
|
||||
/// Returns whether something was removed.
|
||||
pub fn remove(&mut self, order_pos: usize) -> bool {
|
||||
if order_pos <= self.pos || order_pos >= self.order.len() {
|
||||
return false;
|
||||
}
|
||||
let index = self.order.remove(order_pos);
|
||||
self.items.remove(index);
|
||||
for i in &mut self.order {
|
||||
if *i > index {
|
||||
*i -= 1;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Drops everything after the current item, e.g. when a station's settings change.
|
||||
pub fn clear_upcoming(&mut self) {
|
||||
let keep: Vec<usize> = self.order[..=self.pos].to_vec();
|
||||
@@ -184,6 +201,21 @@ mod tests {
|
||||
assert!(Queue::<u8>::new(vec![], 0, false).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_takes_out_an_upcoming_item_only() {
|
||||
let mut q = q(5, 1);
|
||||
assert!(q.remove(3));
|
||||
assert_eq!(q.upcoming().map(|(_, &i)| i).collect::<Vec<_>>(), [2, 4]);
|
||||
assert!(!q.remove(1), "the current item stays");
|
||||
assert!(!q.remove(0), "played items stay");
|
||||
assert!(!q.remove(9));
|
||||
// Shuffling off again must not bring the removed item back.
|
||||
q.set_shuffle(true);
|
||||
q.set_shuffle(false);
|
||||
assert_eq!(q.len(), 4);
|
||||
assert!(!q.upcoming().any(|(_, &i)| i == 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_is_clamped() {
|
||||
assert_eq!(*q(3, 99).current(), 2);
|
||||
|
||||
@@ -105,6 +105,7 @@ pub fn home<'a>(env: Env<'a>, discover: &'a Discover, hero: Element<'a, Message>
|
||||
hues: p.playlist.hues(),
|
||||
round: false,
|
||||
on_press: Message::Navigate(Route::Playlist(p.playlist.id)),
|
||||
menu: Some(crate::widgets::menu::Target::Playlist(p.playlist.clone())),
|
||||
})
|
||||
}),
|
||||
));
|
||||
|
||||
@@ -15,6 +15,7 @@ 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::menu::Target;
|
||||
use crate::widgets::track_list::{self, Env};
|
||||
use crate::widgets::track_row::Columns;
|
||||
use crate::i18n::{tr, trf};
|
||||
@@ -277,6 +278,7 @@ pub fn album_card<'a>(t: &'static Tokens, covers: &Covers, a: &AlbumSummary) ->
|
||||
hues: a.hues(),
|
||||
round: false,
|
||||
on_press: Message::Navigate(Route::Album(a.id)),
|
||||
menu: Some(Target::Album(a.clone())),
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -292,6 +294,7 @@ pub fn artist_card<'a>(t: &'static Tokens, covers: &Covers, a: &ArtistSummary) -
|
||||
hues: a.hues(),
|
||||
round: true,
|
||||
on_press: Message::Navigate(Route::Artist(a.id)),
|
||||
menu: Some(Target::Artist(a.clone())),
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -307,6 +310,7 @@ pub fn playlist_card<'a>(t: &'static Tokens, covers: &Covers, p: &PlaylistSummar
|
||||
hues: p.hues(),
|
||||
round: false,
|
||||
on_press: Message::Navigate(Route::Playlist(p.id)),
|
||||
menu: Some(Target::Playlist(p.clone())),
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -325,6 +329,7 @@ pub fn clip_card<'a>(env: Env<'_>, c: &Clip) -> Element<'a, Message> {
|
||||
hues: c.hues(),
|
||||
round: false,
|
||||
on_press: Message::OpenClip(c.clone()),
|
||||
menu: None,
|
||||
},
|
||||
liked,
|
||||
Message::LikeClip(c.clone(), !liked),
|
||||
|
||||
@@ -31,6 +31,12 @@ pub enum Shortcut {
|
||||
/// Esc: closes the menu, then the search suggestions, then the drawer.
|
||||
Dismiss,
|
||||
Go(Route),
|
||||
/// Plain arrows and Enter move through an open menu; without one they do nothing.
|
||||
MenuUp,
|
||||
MenuDown,
|
||||
MenuIn,
|
||||
MenuOut,
|
||||
MenuEnter,
|
||||
}
|
||||
|
||||
pub fn subscription() -> Subscription<Shortcut> {
|
||||
@@ -59,10 +65,18 @@ pub fn from_key(key: &Key, physical: Physical, mods: Modifiers, repeat: bool) ->
|
||||
(Named::ArrowRight, false, true, false) => S::SeekForward,
|
||||
(Named::ArrowLeft, false, true, false) => S::SeekBack,
|
||||
(Named::ArrowLeft, false, false, true) => S::Back,
|
||||
_ if mods.is_empty() => match named {
|
||||
Named::ArrowUp => S::MenuUp,
|
||||
Named::ArrowDown => S::MenuDown,
|
||||
Named::ArrowRight => S::MenuIn,
|
||||
Named::ArrowLeft => S::MenuOut,
|
||||
Named::Enter => S::MenuEnter,
|
||||
_ => return None,
|
||||
},
|
||||
_ => return None,
|
||||
};
|
||||
// Holding a key repeats volume and seek steps; a held Space must not flicker play and pause.
|
||||
let repeats = matches!(shortcut, S::VolumeUp | S::VolumeDown | S::SeekForward | S::SeekBack);
|
||||
let repeats = matches!(shortcut, S::VolumeUp | S::VolumeDown | S::SeekForward | S::SeekBack | S::MenuUp | S::MenuDown);
|
||||
return (!repeat || repeats).then_some(shortcut);
|
||||
}
|
||||
|
||||
@@ -156,7 +170,8 @@ mod tests {
|
||||
assert_eq!(arrow(Named::ArrowLeft, Code::ArrowLeft, Modifiers::COMMAND), Some(Shortcut::Previous));
|
||||
assert_eq!(arrow(Named::ArrowRight, Code::ArrowRight, Modifiers::SHIFT), Some(Shortcut::SeekForward));
|
||||
assert_eq!(arrow(Named::ArrowLeft, Code::ArrowLeft, Modifiers::ALT), Some(Shortcut::Back));
|
||||
assert_eq!(arrow(Named::ArrowRight, Code::ArrowRight, Modifiers::empty()), None);
|
||||
assert_eq!(arrow(Named::ArrowRight, Code::ArrowRight, Modifiers::empty()), Some(Shortcut::MenuIn));
|
||||
assert_eq!(arrow(Named::ArrowDown, Code::ArrowDown, Modifiers::CTRL), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -4,6 +4,11 @@
|
||||
//! MUSYX_SNAPSHOT=home.png MUSYX_SNAPSHOT_ROUTE=wave MUSYX_SNAPSHOT_DRAWER=queue \
|
||||
//! MUSYX_SNAPSHOT_THEME=light MUSYX_SNAPSHOT_LANG=ru cargo run -p musyx --features snapshot
|
||||
//! ```
|
||||
//!
|
||||
//! `MUSYX_SNAPSHOT_MENU` opens a track menu: `row` (right-click on a row), `sub`
|
||||
//! (with the playlist list), `edge` (near the bottom-right corner) or `more`
|
||||
//! (under a row's "…"). `MUSYX_SNAPSHOT_DRAG=1` with `ROUTE=playlist` shows a
|
||||
//! row of the sample own playlist mid-drag.
|
||||
//! iced's own `window::screenshot` is used, so it needs no screen-recording permission.
|
||||
|
||||
use std::path::PathBuf;
|
||||
@@ -34,8 +39,13 @@ pub struct Config {
|
||||
pub lang: Option<Lang>,
|
||||
/// `MUSYX_SNAPSHOT_DELAY` in ms before capturing (default 1500; live runs need longer).
|
||||
pub delay: Duration,
|
||||
pub menu: Option<String>,
|
||||
pub drag: bool,
|
||||
}
|
||||
|
||||
/// The sample own playlist for `MUSYX_SNAPSHOT_ROUTE=playlist`.
|
||||
pub const OWN_PLAYLIST: ym_api::PlaylistId = ym_api::PlaylistId { owner: 1, kind: 3 };
|
||||
|
||||
impl Config {
|
||||
pub fn from_env() -> Option<Self> {
|
||||
let out = PathBuf::from(std::env::var_os("MUSYX_SNAPSHOT")?);
|
||||
@@ -50,6 +60,7 @@ impl Config {
|
||||
"podcasts" => Route::Podcasts,
|
||||
"settings" => Route::Settings,
|
||||
"album" => Route::Album(1),
|
||||
"playlist" => Route::Playlist(OWN_PLAYLIST),
|
||||
"chart" => Route::Chart,
|
||||
// `artist:41075`, for live runs.
|
||||
other => Route::Artist(other.strip_prefix("artist:")?.parse().ok()?),
|
||||
@@ -70,7 +81,9 @@ impl Config {
|
||||
let delay = var("MUSYX_SNAPSHOT_DELAY")
|
||||
.and_then(|d| d.parse().ok())
|
||||
.map_or(Duration::from_millis(if live { 8000 } else { 1500 }), Duration::from_millis);
|
||||
Some(Self { out, signed_out, route, drawer, mode, lang, live, delay })
|
||||
let menu = var("MUSYX_SNAPSHOT_MENU");
|
||||
let drag = var("MUSYX_SNAPSHOT_DRAG").is_some_and(|v| v == "1");
|
||||
Some(Self { out, signed_out, route, drawer, mode, lang, live, delay, menu, drag })
|
||||
}
|
||||
|
||||
/// A made-up account so the shell renders without a network or keychain.
|
||||
@@ -134,6 +147,43 @@ impl Config {
|
||||
crate::screens::detail::Page::Album { info, tracks }
|
||||
}
|
||||
|
||||
/// The sample liked tracks as one of the user's own playlists.
|
||||
pub fn sample_playlist(&self) -> crate::screens::detail::Page {
|
||||
let info = ym_api::PlaylistPage {
|
||||
playlist: ym_api::PlaylistSummary::for_tests(OWN_PLAYLIST, "Дорога"),
|
||||
description: None,
|
||||
tracks: Vec::new(),
|
||||
};
|
||||
crate::screens::detail::Page::Playlist { info, tracks: self.sample_liked().into() }
|
||||
}
|
||||
|
||||
/// The menu `MUSYX_SNAPSHOT_MENU` asks for, on the second sample track.
|
||||
pub fn menu(&self) -> Option<crate::widgets::menu::Menu> {
|
||||
use crate::widgets::menu::{Anchor, Menu, Source, Target};
|
||||
use iced::{Point, Rectangle, Size};
|
||||
let track = self.sample_liked().swap_remove(1);
|
||||
let playlist = (self.route == Some(Route::Playlist(OWN_PLAYLIST))).then_some((OWN_PLAYLIST, 1, 6));
|
||||
let target = Target::Track { track, from: Source::List { playlist } };
|
||||
let anchor = match self.menu.as_deref()? {
|
||||
"edge" => Anchor::Point(Point::new(1180.0, 640.0)),
|
||||
"more" => Anchor::Below(Rectangle::new(Point::new(1212.0, 289.0), Size::new(34.0, 34.0))),
|
||||
_ => Anchor::Point(Point::new(560.0, 300.0)),
|
||||
};
|
||||
let mut menu = Menu::new(target, anchor);
|
||||
menu.highlight = Some(1);
|
||||
if self.menu.as_deref() == Some("sub") {
|
||||
menu.highlight = Some(4);
|
||||
menu.sub = Some(Some(0));
|
||||
}
|
||||
Some(menu)
|
||||
}
|
||||
|
||||
/// The second sample track dragged two rows down.
|
||||
pub fn drag(&self) -> Option<crate::widgets::track_list::Drag> {
|
||||
let track = self.sample_liked().swap_remove(1);
|
||||
self.drag.then_some(crate::widgets::track_list::Drag { playlist: OWN_PLAYLIST, track, from: 1, to: 3 })
|
||||
}
|
||||
|
||||
/// Waits for fonts and the first frames, captures the window, writes the PNG, exits.
|
||||
pub fn capture<M: Send + 'static>(self) -> Task<M> {
|
||||
Task::future(tokio::time::sleep(self.delay))
|
||||
|
||||
@@ -65,6 +65,9 @@ icons! {
|
||||
Clock => "clock-3",
|
||||
Tune => "sliders-horizontal",
|
||||
Settings => "settings",
|
||||
MoveTop => "arrow-up-to-line",
|
||||
MoveBottom => "arrow-down-to-line",
|
||||
Artist => "user",
|
||||
}
|
||||
|
||||
impl Icon {
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
//! Reports where a menu should open: the pointer on a right-click, or the bounds
|
||||
//! of the wrapped control on a left-click, both in window coordinates.
|
||||
//!
|
||||
//! Inside a scrollable a widget only sees content coordinates. iced hands every
|
||||
//! widget its offset from the window when it asks for overlays, which it does
|
||||
//! before each event, so the offset is kept here and added back.
|
||||
|
||||
use iced::advanced::widget::{Operation, Tree, tree};
|
||||
use iced::advanced::{Clipboard, Layout, Shell, Widget, layout, mouse, overlay, renderer};
|
||||
use iced::{Element, Event, Length, Point, Rectangle, Renderer, Size, Theme, Vector};
|
||||
|
||||
pub struct Anchor<'a, Message> {
|
||||
content: Element<'a, Message>,
|
||||
on_right_press: Option<Box<dyn Fn(Point) -> Message + 'a>>,
|
||||
on_press: Option<Box<dyn Fn(Rectangle) -> Message + 'a>>,
|
||||
}
|
||||
|
||||
pub fn anchor<'a, Message>(content: impl Into<Element<'a, Message>>) -> Anchor<'a, Message> {
|
||||
Anchor { content: content.into(), on_right_press: None, on_press: None }
|
||||
}
|
||||
|
||||
impl<'a, Message> Anchor<'a, Message> {
|
||||
/// A right-click anywhere on the content, with the pointer's position.
|
||||
pub fn on_right_press(mut self, f: impl Fn(Point) -> Message + 'a) -> Self {
|
||||
self.on_right_press = Some(Box::new(f));
|
||||
self
|
||||
}
|
||||
|
||||
/// A left-click on the content, with its bounds. The content doesn't see the click.
|
||||
pub fn on_press(mut self, f: impl Fn(Rectangle) -> Message + 'a) -> Self {
|
||||
self.on_press = Some(Box::new(f));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
/// Content coordinates plus this give window coordinates.
|
||||
offset: Vector,
|
||||
}
|
||||
|
||||
impl<Message> Widget<Message, Theme, Renderer> for Anchor<'_, Message> {
|
||||
fn tag(&self) -> tree::Tag {
|
||||
tree::Tag::of::<State>()
|
||||
}
|
||||
|
||||
fn state(&self) -> tree::State {
|
||||
tree::State::new(State::default())
|
||||
}
|
||||
|
||||
fn children(&self) -> Vec<Tree> {
|
||||
vec![Tree::new(&self.content)]
|
||||
}
|
||||
|
||||
fn diff(&self, tree: &mut Tree) {
|
||||
tree.diff_children(std::slice::from_ref(&self.content));
|
||||
}
|
||||
|
||||
fn size(&self) -> Size<Length> {
|
||||
self.content.as_widget().size()
|
||||
}
|
||||
|
||||
fn layout(&mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits) -> layout::Node {
|
||||
self.content.as_widget_mut().layout(&mut tree.children[0], renderer, limits)
|
||||
}
|
||||
|
||||
fn operate(&mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn Operation) {
|
||||
self.content.as_widget_mut().operate(&mut tree.children[0], layout, renderer, operation);
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
tree: &mut Tree,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
let offset = tree.state.downcast_ref::<State>().offset;
|
||||
let bounds = layout.bounds();
|
||||
if let (Some(f), Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))) = (&self.on_press, event)
|
||||
&& cursor.is_over(bounds)
|
||||
{
|
||||
shell.publish(f(bounds + offset));
|
||||
shell.capture_event();
|
||||
return;
|
||||
}
|
||||
|
||||
self.content
|
||||
.as_widget_mut()
|
||||
.update(&mut tree.children[0], event, layout, cursor, renderer, clipboard, shell, viewport);
|
||||
if shell.is_event_captured() {
|
||||
return;
|
||||
}
|
||||
|
||||
if let (Some(f), Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Right))) = (&self.on_right_press, event)
|
||||
&& let Some(at) = cursor.position_over(bounds)
|
||||
{
|
||||
shell.publish(f(at + offset));
|
||||
shell.capture_event();
|
||||
}
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
tree: &Tree,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
viewport: &Rectangle,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
self.content.as_widget().mouse_interaction(&tree.children[0], layout, cursor, viewport, renderer)
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
tree: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
self.content.as_widget().draw(&tree.children[0], renderer, theme, style, layout, cursor, viewport);
|
||||
}
|
||||
|
||||
fn overlay<'b>(
|
||||
&'b mut self,
|
||||
tree: &'b mut Tree,
|
||||
layout: Layout<'b>,
|
||||
renderer: &Renderer,
|
||||
viewport: &Rectangle,
|
||||
translation: Vector,
|
||||
) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
|
||||
tree.state.downcast_mut::<State>().offset = translation;
|
||||
self.content.as_widget_mut().overlay(&mut tree.children[0], layout, renderer, viewport, translation)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message: 'a> From<Anchor<'a, Message>> for Element<'a, Message> {
|
||||
fn from(anchor: Anchor<'a, Message>) -> Self {
|
||||
Element::new(anchor)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::anchor;
|
||||
use iced::mouse::{Button, Event as Mouse, ScrollDelta};
|
||||
use iced::widget::{column, container, scrollable, space, text};
|
||||
use iced::{Element, Event, Fill, Point, Size};
|
||||
|
||||
#[test]
|
||||
fn a_right_click_inside_a_scrolled_list_reports_window_coordinates() {
|
||||
let target = anchor(container(text("target")).width(Fill).height(60)).on_right_press(|at| at);
|
||||
let page: Element<'_, Point> = scrollable(column![space().height(500), target, space().height(500)]).into();
|
||||
let mut ui = iced_test::Simulator::with_size(Default::default(), Size::new(400.0, 300.0), page);
|
||||
|
||||
ui.point_at(Point::new(100.0, 150.0));
|
||||
let _ = ui.simulate([Event::Mouse(Mouse::WheelScrolled { delta: ScrollDelta::Pixels { x: 0.0, y: -400.0 } })]);
|
||||
// "target" sits at 500..560 in the content; scrolled by 400 it shows at 100..160.
|
||||
ui.point_at(Point::new(100.0, 130.0));
|
||||
let _ = ui.simulate([Event::Mouse(Mouse::ButtonPressed(Button::Right))]);
|
||||
let messages: Vec<Point> = ui.into_messages().collect();
|
||||
assert_eq!(messages, [Point::new(100.0, 130.0)]);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ use crate::covers::{self, Covers};
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
use crate::ui::line;
|
||||
use crate::ui::theme::{self, Tokens, radius, size};
|
||||
use crate::widgets::anchor::anchor;
|
||||
use crate::widgets::menu::{Anchor, Menu, Target};
|
||||
|
||||
/// Card width; covers are square at this size.
|
||||
pub const WIDTH: f32 = 168.0;
|
||||
@@ -20,6 +22,8 @@ pub struct Card {
|
||||
/// Artists get a round cover.
|
||||
pub round: bool,
|
||||
pub on_press: Message,
|
||||
/// What a right-click's menu is for; clips have none.
|
||||
pub menu: Option<Target>,
|
||||
}
|
||||
|
||||
pub fn view<'a>(t: &'static Tokens, covers: &Covers, card: Card) -> Element<'a, Message> {
|
||||
@@ -47,7 +51,7 @@ fn build<'a>(t: &'static Tokens, covers: &Covers, card: Card, action: Option<Ele
|
||||
.spacing(2)
|
||||
.width(Fill)
|
||||
.clip(true);
|
||||
button(
|
||||
let button = button(
|
||||
column![
|
||||
covers::view(covers, card.cover, card.hues, WIDTH, corner),
|
||||
row![text].push(action).spacing(4).align_y(Alignment::Center).width(WIDTH),
|
||||
@@ -56,8 +60,13 @@ fn build<'a>(t: &'static Tokens, covers: &Covers, card: Card, action: Option<Ele
|
||||
)
|
||||
.padding(Padding::from(6))
|
||||
.style(theme::nav_item(false))
|
||||
.on_press(card.on_press)
|
||||
.into()
|
||||
.on_press(card.on_press);
|
||||
match card.menu {
|
||||
Some(target) => anchor(button)
|
||||
.on_right_press(move |at| Message::OpenMenu(Box::new(Menu::new(target.clone(), Anchor::Point(at)))))
|
||||
.into(),
|
||||
None => button.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Cards in rows that wrap to the available width.
|
||||
|
||||
@@ -13,6 +13,8 @@ use crate::player::{Msg, Player, Queue};
|
||||
use crate::screens::Loadable;
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
use crate::ui::theme::{self, Tokens, radius, shell, size};
|
||||
use crate::widgets::anchor::anchor;
|
||||
use crate::widgets::menu::{Anchor, Menu, Source, Target};
|
||||
use crate::widgets::player_bar::clock;
|
||||
use crate::ui::{line, para};
|
||||
use crate::i18n::{tr, trf};
|
||||
@@ -141,8 +143,9 @@ fn queue_list<'a>(t: &'static Tokens, queue: &'a Queue<Track>, covers: &Covers)
|
||||
let heading = |s: String| {
|
||||
container(line(s, theme::MEDIUM, size::SMALL, t.muted)).padding(Padding::default().top(14).bottom(8).left(8))
|
||||
};
|
||||
let item = |track: &Track, now: bool, msg: Option<Message>| {
|
||||
button(
|
||||
let item = |track: &Track, now: bool, msg: Option<Message>, from: Source| {
|
||||
let target = Target::Track { track: track.clone(), from };
|
||||
let row = button(
|
||||
row![
|
||||
covers::view(covers, track.cover_url(covers::SMALL), track.hues(), 40.0, radius::SMALL_COVER),
|
||||
column![
|
||||
@@ -160,18 +163,19 @@ fn queue_list<'a>(t: &'static Tokens, queue: &'a Queue<Track>, covers: &Covers)
|
||||
.width(Fill)
|
||||
.padding([6, 8])
|
||||
.style(theme::nav_item(false))
|
||||
.on_press_maybe(msg)
|
||||
.on_press_maybe(msg);
|
||||
anchor(row).on_right_press(move |at| Message::OpenMenu(Box::new(Menu::new(target.clone(), Anchor::Point(at)))))
|
||||
};
|
||||
|
||||
let remaining = queue.upcoming().count();
|
||||
let mut list = column![heading(tr("Now playing").into()), item(queue.current(), true, None)];
|
||||
let mut list = column![heading(tr("Now playing").into()), item(queue.current(), true, None, Source::PlayerBar)];
|
||||
list = list.push(heading(if remaining == 0 {
|
||||
tr("Nothing after this").into()
|
||||
} else {
|
||||
trf("Next up · {}", &[&remaining])
|
||||
}));
|
||||
for (pos, track) in queue.upcoming().take(SHOWN) {
|
||||
list = list.push(item(track, false, Some(Message::Player(Msg::JumpTo(pos)))));
|
||||
list = list.push(item(track, false, Some(Message::Player(Msg::JumpTo(pos))), Source::Queue { pos }));
|
||||
}
|
||||
if remaining > SHOWN {
|
||||
list = list.push(
|
||||
|
||||
@@ -0,0 +1,519 @@
|
||||
//! The context menu for tracks, albums, playlists and artists. It opens at the
|
||||
//! pointer on a right-click, or under the "…" button, without dimming anything.
|
||||
//! Every action closes it; a toast says what happened.
|
||||
|
||||
use iced::widget::{Column, button, container, mouse_area, opaque, pin, responsive, row, scrollable, space, stack};
|
||||
use iced::{Alignment, Element, Fill, Point, Rectangle, Size};
|
||||
use ym_api::{AlbumSummary, ArtistSummary, PlaylistId, PlaylistSummary, Track};
|
||||
|
||||
use crate::app::Message;
|
||||
use crate::i18n::{tr, trf};
|
||||
use crate::route::Route;
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
use crate::ui::line;
|
||||
use crate::ui::theme::{self, Tokens, radius, size};
|
||||
use crate::widgets::sheet::Sheet;
|
||||
|
||||
pub const WIDTH: f32 = 280.0;
|
||||
const ITEM: f32 = 32.0;
|
||||
const SEPARATOR: f32 = 9.0;
|
||||
const PAD: f32 = 6.0;
|
||||
/// Keeps the menu off the window edge.
|
||||
const MARGIN: f32 = 8.0;
|
||||
/// The playlist submenu scrolls past this many rows.
|
||||
const SUB_ROWS: usize = 10;
|
||||
/// Artist names longer than this are cut so the menu keeps its width.
|
||||
const NAME_CHARS: usize = 24;
|
||||
|
||||
/// What the menu is for.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Target {
|
||||
Track { track: Track, from: Source },
|
||||
Album(AlbumSummary),
|
||||
Playlist(PlaylistSummary),
|
||||
Artist(ArtistSummary),
|
||||
}
|
||||
|
||||
/// Where a track's menu was opened; each place adds its own actions.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Source {
|
||||
/// A track list. In one of the user's own playlists: its id, the row, its length.
|
||||
List { playlist: Option<(PlaylistId, usize, usize)> },
|
||||
PlayerBar,
|
||||
/// The queue drawer, at a position from `Queue::upcoming`.
|
||||
Queue { pos: usize },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum Anchor {
|
||||
/// Right-click: the pointer.
|
||||
Point(Point),
|
||||
/// The "…" button: the menu hangs under it, right edges lined up.
|
||||
Below(Rectangle),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Menu {
|
||||
pub target: Target,
|
||||
pub anchor: Anchor,
|
||||
/// The entry under the pointer or picked with the arrow keys, counted across groups.
|
||||
pub highlight: Option<usize>,
|
||||
/// The "Add to playlist" list is showing; the index is its highlighted row.
|
||||
pub sub: Option<Option<usize>>,
|
||||
}
|
||||
|
||||
impl Menu {
|
||||
pub fn new(target: Target, anchor: Anchor) -> Self {
|
||||
Self { target, anchor, highlight: None, sub: None }
|
||||
}
|
||||
|
||||
pub fn track(&self) -> Option<&Track> {
|
||||
match &self.target {
|
||||
Target::Track { track, .. } => Some(track),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the menu needs to know about the library for its target.
|
||||
pub struct Ctx<'a> {
|
||||
/// The target is the track playing now: "next" means skipping ahead.
|
||||
pub playing: bool,
|
||||
/// Liked track, or album/artist/playlist in the collection.
|
||||
pub liked: bool,
|
||||
pub disliked: bool,
|
||||
pub own_playlists: &'a [PlaylistSummary],
|
||||
pub me: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Action {
|
||||
Send(Box<Message>),
|
||||
Submenu,
|
||||
Disabled,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Entry {
|
||||
pub icon: Icon,
|
||||
pub label: String,
|
||||
pub action: Action,
|
||||
pub danger: bool,
|
||||
}
|
||||
|
||||
fn entry(icon: Icon, label: impl Into<String>, msg: Message) -> Entry {
|
||||
Entry { icon, label: label.into(), action: Action::Send(Box::new(msg)), danger: false }
|
||||
}
|
||||
|
||||
/// The menu's entries in groups; a thin line separates the groups.
|
||||
pub fn groups(target: &Target, ctx: &Ctx<'_>) -> Vec<Vec<Entry>> {
|
||||
let mut groups = match target {
|
||||
Target::Track { track, from } => track_groups(track, *from, ctx),
|
||||
Target::Album(a) => vec![
|
||||
play_group(Route::Album(a.id)),
|
||||
vec![collection_entry(ctx.liked, Message::LikeAlbum(a.id, !ctx.liked))],
|
||||
artist_entries(a.artists.iter().filter_map(|r| Some((r.id?, r.name.as_str())))),
|
||||
],
|
||||
Target::Playlist(p) if p.id.owner == ctx.me => vec![
|
||||
play_group(Route::Playlist(p.id)),
|
||||
vec![
|
||||
entry(Icon::Pencil, tr("Rename…"), Message::OpenSheet(Sheet::Rename { id: p.id, name: p.title.clone() })),
|
||||
Entry {
|
||||
danger: true,
|
||||
..entry(Icon::Trash, tr("Delete…"), Message::OpenSheet(Sheet::ConfirmDelete { id: p.id, title: p.title.clone() }))
|
||||
},
|
||||
],
|
||||
],
|
||||
Target::Playlist(p) => vec![
|
||||
play_group(Route::Playlist(p.id)),
|
||||
vec![collection_entry(ctx.liked, Message::LikePlaylist(p.id, !ctx.liked))],
|
||||
],
|
||||
Target::Artist(a) => vec![
|
||||
vec![entry(Icon::Play, tr("Play"), Message::PlayRoute { route: Route::Artist(a.id), shuffle: false })],
|
||||
vec![collection_entry(ctx.liked, Message::LikeArtist(a.id, !ctx.liked))],
|
||||
],
|
||||
};
|
||||
groups.retain(|g| !g.is_empty());
|
||||
groups
|
||||
}
|
||||
|
||||
fn track_groups(track: &Track, from: Source, ctx: &Ctx<'_>) -> Vec<Vec<Entry>> {
|
||||
let playable = |e: Entry| if track.available { e } else { Entry { action: Action::Disabled, ..e } };
|
||||
let queue_group = match from {
|
||||
Source::Queue { pos } => vec![
|
||||
playable(entry(Icon::Play, tr("Play now"), Message::Player(crate::player::Msg::JumpTo(pos)))),
|
||||
playable(entry(Icon::Next, tr("Play next"), Message::PlayNext(track.clone()))),
|
||||
entry(Icon::Close, tr("Remove from queue"), Message::Player(crate::player::Msg::Remove { pos, id: track.id.clone() })),
|
||||
],
|
||||
_ => vec![
|
||||
if ctx.playing {
|
||||
entry(Icon::Next, tr("Next track"), Message::SkipFromMenu)
|
||||
} else {
|
||||
playable(entry(Icon::Next, tr("Play next"), Message::PlayNext(track.clone())))
|
||||
},
|
||||
playable(entry(Icon::Queue, tr("Add to queue"), Message::AddToQueue(track.clone()))),
|
||||
entry(Icon::Wave, tr("Play similar tracks"), Message::PlaySimilar(track.clone())),
|
||||
],
|
||||
};
|
||||
let library = vec![
|
||||
entry(
|
||||
if ctx.liked { Icon::HeartFilled } else { Icon::Heart },
|
||||
if ctx.liked { tr("Remove from Liked tracks") } else { tr("Add to Liked tracks") },
|
||||
Message::LikeTrack(track.clone(), !ctx.liked),
|
||||
),
|
||||
Entry { icon: Icon::Plus, label: tr("Add to playlist").into(), action: Action::Submenu, danger: false },
|
||||
entry(
|
||||
Icon::Dislike,
|
||||
if ctx.disliked { tr("Recommend this track again") } else { tr("Don't recommend this track") },
|
||||
Message::DislikeTrack(track.clone(), !ctx.disliked),
|
||||
),
|
||||
];
|
||||
let mut go = Vec::new();
|
||||
if let Some(album) = &track.album {
|
||||
go.push(entry(Icon::Disc, tr("Go to album"), Message::Navigate(Route::Album(album.id))));
|
||||
}
|
||||
go.extend(artist_entries(track.artists.iter().filter_map(|a| Some((a.id?, a.name.as_str())))));
|
||||
|
||||
let mut groups = vec![queue_group, library, go];
|
||||
if let Source::List { playlist: Some((id, index, len)) } = from {
|
||||
let mut own = Vec::new();
|
||||
if index > 0 {
|
||||
own.push(entry(Icon::MoveTop, tr("Move to top"), Message::MovePlaylistTrack { id, track: track.clone(), from: index, to: 0 }));
|
||||
}
|
||||
if index + 1 < len {
|
||||
own.push(entry(
|
||||
Icon::MoveBottom,
|
||||
tr("Move to bottom"),
|
||||
Message::MovePlaylistTrack { id, track: track.clone(), from: index, to: len - 1 },
|
||||
));
|
||||
}
|
||||
own.push(Entry { danger: true, ..entry(Icon::Trash, tr("Remove from this playlist"), Message::RemoveFromPlaylist(id, index)) });
|
||||
groups.push(own);
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
fn play_group(route: Route) -> Vec<Entry> {
|
||||
vec![
|
||||
entry(Icon::Play, tr("Play"), Message::PlayRoute { route, shuffle: false }),
|
||||
entry(Icon::Shuffle, tr("Shuffle"), Message::PlayRoute { route, shuffle: true }),
|
||||
]
|
||||
}
|
||||
|
||||
fn collection_entry(liked: bool, msg: Message) -> Entry {
|
||||
entry(
|
||||
if liked { Icon::HeartFilled } else { Icon::Heart },
|
||||
if liked { tr("Remove from collection") } else { tr("Add to collection") },
|
||||
msg,
|
||||
)
|
||||
}
|
||||
|
||||
/// One named entry per artist, up to three.
|
||||
fn artist_entries<'n>(artists: impl Iterator<Item = (i64, &'n str)>) -> Vec<Entry> {
|
||||
artists
|
||||
.take(3)
|
||||
.map(|(id, name)| entry(Icon::Artist, trf("Go to {}", &[&shorten(name)]), Message::Navigate(Route::Artist(id))))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn shorten(name: &str) -> String {
|
||||
if name.chars().count() <= NAME_CHARS {
|
||||
return name.to_owned();
|
||||
}
|
||||
let cut: String = name.chars().take(NAME_CHARS - 1).collect();
|
||||
format!("{}…", cut.trim_end())
|
||||
}
|
||||
|
||||
/// The "Add to playlist" list: a new playlist, then the user's own.
|
||||
pub fn sub_entries(track: &Track, own: &[PlaylistSummary]) -> Vec<Entry> {
|
||||
std::iter::once(entry(Icon::Plus, tr("New playlist…"), Message::OpenSheet(Sheet::NewPlaylist { name: String::new(), add: Some(track.clone()) })))
|
||||
.chain(own.iter().map(|p| entry(Icon::Queue, p.title.clone(), Message::AddToPlaylist(p.id, track.clone()))))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Entries in order, without the groups.
|
||||
pub fn flat(groups: &[Vec<Entry>]) -> impl Iterator<Item = &Entry> {
|
||||
groups.iter().flatten()
|
||||
}
|
||||
|
||||
/// The next entry in `step` direction that can be picked, wrapping around.
|
||||
pub fn step(entries: &[&Entry], from: Option<usize>, down: bool) -> Option<usize> {
|
||||
let n = entries.len();
|
||||
if n == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut i = from.unwrap_or(if down { n - 1 } else { 0 });
|
||||
for _ in 0..n {
|
||||
i = if down { (i + 1) % n } else { (i + n - 1) % n };
|
||||
if !matches!(entries[i].action, Action::Disabled) {
|
||||
return Some(i);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
// ---- Placement ----
|
||||
|
||||
pub fn height(groups: &[Vec<Entry>]) -> f32 {
|
||||
let items: usize = groups.iter().map(Vec::len).sum();
|
||||
2.0 * PAD + items as f32 * ITEM + groups.len().saturating_sub(1) as f32 * SEPARATOR
|
||||
}
|
||||
|
||||
fn sub_height(rows: usize) -> f32 {
|
||||
2.0 * PAD + rows.min(SUB_ROWS) as f32 * ITEM
|
||||
}
|
||||
|
||||
/// Where the menu's top-left corner goes: at the anchor, flipped left or up
|
||||
/// where it would leave the window, and never past the edges.
|
||||
pub fn place(anchor: Anchor, menu: Size, window: Size) -> Point {
|
||||
let (x, y, flip_x, flip_y) = match anchor {
|
||||
Anchor::Point(p) => (p.x, p.y, p.x - menu.width, p.y - menu.height),
|
||||
Anchor::Below(r) => (r.x + r.width - menu.width, r.y + r.height + 4.0, r.x + r.width - menu.width, r.y - 4.0 - menu.height),
|
||||
};
|
||||
let x = if x + menu.width > window.width - MARGIN { flip_x } else { x };
|
||||
let y = if y + menu.height > window.height - MARGIN { flip_y } else { y };
|
||||
Point::new(clamp(x, menu.width, window.width), clamp(y, menu.height, window.height))
|
||||
}
|
||||
|
||||
/// The submenu beside the menu at `menu`, its first row level with the entry at `row_y`.
|
||||
pub fn place_sub(menu: Point, row_y: f32, sub: Size, window: Size) -> Point {
|
||||
let right = menu.x + WIDTH + 2.0;
|
||||
let x = if right + sub.width > window.width - MARGIN { menu.x - 2.0 - sub.width } else { right };
|
||||
Point::new(clamp(x, sub.width, window.width), clamp(row_y - PAD, sub.height, window.height))
|
||||
}
|
||||
|
||||
fn clamp(v: f32, len: f32, room: f32) -> f32 {
|
||||
v.min(room - MARGIN - len).max(MARGIN)
|
||||
}
|
||||
|
||||
/// Top of the entry at flat index `at`, measured from the menu's top.
|
||||
fn row_top(groups: &[Vec<Entry>], at: usize) -> f32 {
|
||||
let mut y = PAD;
|
||||
let mut i = 0;
|
||||
for (g, group) in groups.iter().enumerate() {
|
||||
if g > 0 {
|
||||
y += SEPARATOR;
|
||||
}
|
||||
for _ in group {
|
||||
if i == at {
|
||||
return y;
|
||||
}
|
||||
y += ITEM;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
y
|
||||
}
|
||||
|
||||
// ---- View ----
|
||||
|
||||
/// The whole-window layer: a catcher that closes the menu on any click or scroll
|
||||
/// outside it, and the menu (plus its submenu) pinned where it belongs.
|
||||
pub fn layer<'a>(t: &'static Tokens, menu: &'a Menu, ctx: Ctx<'a>) -> Element<'a, Message> {
|
||||
let groups = groups(&menu.target, &ctx);
|
||||
let sub = match (menu.sub, menu.track()) {
|
||||
(Some(highlight), Some(track)) => Some((sub_entries(track, ctx.own_playlists), highlight)),
|
||||
_ => None,
|
||||
};
|
||||
let sub_at = flat(&groups).position(|e| matches!(e.action, Action::Submenu));
|
||||
|
||||
responsive(move |window| {
|
||||
let size = Size::new(WIDTH, height(&groups));
|
||||
let at = place(menu.anchor, size, window);
|
||||
let catcher = mouse_area(container(space()).width(Fill).height(Fill))
|
||||
.on_press(Message::CloseMenu)
|
||||
.on_right_press(Message::CloseMenu)
|
||||
.on_scroll(|_| Message::CloseMenu);
|
||||
|
||||
let mut items: Vec<Element<'a, Message>> = Vec::new();
|
||||
let mut i = 0;
|
||||
for (g, group) in groups.iter().enumerate() {
|
||||
if g > 0 {
|
||||
items.push(separator());
|
||||
}
|
||||
for e in group {
|
||||
let open = matches!(e.action, Action::Submenu) && sub.is_some();
|
||||
items.push(item(t, e, menu.highlight == Some(i) || open, Message::MenuHover(i)));
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let mut layers = stack![catcher, pin(panel(t, Column::with_children(items).into())).position(at)];
|
||||
|
||||
if let (Some((entries, highlight)), Some(row)) = (&sub, sub_at) {
|
||||
let size = Size::new(WIDTH, sub_height(entries.len()));
|
||||
let sub_pos = place_sub(at, at.y + row_top(&groups, row), size, window);
|
||||
let rows = Column::with_children(
|
||||
entries.iter().enumerate().map(|(j, e)| item(t, e, *highlight == Some(j), Message::MenuSubHover(j))),
|
||||
);
|
||||
let list: Element<'a, Message> = if entries.len() > SUB_ROWS {
|
||||
scrollable(rows).height(SUB_ROWS as f32 * ITEM).style(theme::scroll).into()
|
||||
} else {
|
||||
rows.into()
|
||||
};
|
||||
layers = layers.push(pin(panel(t, list)).position(sub_pos));
|
||||
}
|
||||
layers.into()
|
||||
})
|
||||
.into()
|
||||
}
|
||||
|
||||
fn panel<'a>(t: &'static Tokens, content: Element<'a, Message>) -> Element<'a, Message> {
|
||||
opaque(container(content).width(WIDTH).padding(PAD).style(move |_| container::Style {
|
||||
background: Some(t.panel.into()),
|
||||
border: iced::Border { color: t.line, width: 1.0, radius: radius::COVER.into() },
|
||||
shadow: iced::Shadow {
|
||||
color: iced::Color::BLACK.scale_alpha(0.3),
|
||||
offset: iced::Vector::new(0.0, 10.0),
|
||||
blur_radius: 28.0,
|
||||
},
|
||||
..Default::default()
|
||||
}))
|
||||
}
|
||||
|
||||
fn item<'a>(t: &'static Tokens, e: &Entry, lit: bool, hover: Message) -> Element<'a, Message> {
|
||||
let disabled = matches!(e.action, Action::Disabled);
|
||||
let (glyph, label) = match (disabled, e.danger) {
|
||||
(true, _) => (t.muted, t.muted),
|
||||
(false, true) => (t.like, t.like),
|
||||
(false, false) => (t.muted, t.fg),
|
||||
};
|
||||
let mut content = row![icon(e.icon, glyph), line(e.label.clone(), theme::BODY, size::BODY, label).width(Fill)]
|
||||
.spacing(12)
|
||||
.align_y(Alignment::Center)
|
||||
.height(ITEM);
|
||||
if matches!(e.action, Action::Submenu) {
|
||||
content = content.push(icon(crate::ui::icons::Icon::Forward, t.muted));
|
||||
}
|
||||
let press = match &e.action {
|
||||
Action::Send(msg) => Some(Message::MenuPick(msg.clone())),
|
||||
Action::Submenu => Some(Message::MenuSub(true)),
|
||||
Action::Disabled => None,
|
||||
};
|
||||
let button = button(container(content).clip(true))
|
||||
.width(Fill)
|
||||
.padding([0, 10])
|
||||
.style(theme::nav_item(lit && !disabled))
|
||||
.on_press_maybe(press);
|
||||
mouse_area(button).on_enter(hover).into()
|
||||
}
|
||||
|
||||
fn separator<'a>() -> Element<'a, Message> {
|
||||
container(container(space()).width(Fill).height(1).style(theme::divider)).padding([4, 4]).into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn track(json_extra: &str) -> Track {
|
||||
Track::from_json(&format!(
|
||||
r#"{{"id":"7","title":"Хочешь?","artists":[{{"id":3,"name":"Земфира"}}],"albums":[{{"id":5,"title":"A"}}]{json_extra}}}"#
|
||||
))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn ctx() -> Ctx<'static> {
|
||||
Ctx { playing: false, liked: false, disliked: false, own_playlists: &[], me: 1 }
|
||||
}
|
||||
|
||||
fn labels(groups: &[Vec<Entry>]) -> Vec<Vec<String>> {
|
||||
groups.iter().map(|g| g.iter().map(|e| e.label.clone()).collect()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_track_in_a_list_has_three_groups_with_named_artists() {
|
||||
let groups = groups(&Target::Track { track: track(""), from: Source::List { playlist: None } }, &ctx());
|
||||
assert_eq!(
|
||||
labels(&groups),
|
||||
[
|
||||
vec!["Play next", "Add to queue", "Play similar tracks"],
|
||||
vec!["Add to Liked tracks", "Add to playlist", "Don't recommend this track"],
|
||||
vec!["Go to album", "Go to Земфира"],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn own_playlist_rows_get_moves_that_fit_their_position() {
|
||||
let id = PlaylistId { owner: 1, kind: 3 };
|
||||
let first = groups(&Target::Track { track: track(""), from: Source::List { playlist: Some((id, 0, 5)) } }, &ctx());
|
||||
assert_eq!(labels(&first)[3], ["Move to bottom", "Remove from this playlist"]);
|
||||
let last = groups(&Target::Track { track: track(""), from: Source::List { playlist: Some((id, 4, 5)) } }, &ctx());
|
||||
assert_eq!(labels(&last)[3], ["Move to top", "Remove from this playlist"]);
|
||||
assert!(last[3][1].danger);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queue_rows_can_be_played_now_or_removed() {
|
||||
let groups = groups(&Target::Track { track: track(""), from: Source::Queue { pos: 4 } }, &ctx());
|
||||
assert_eq!(labels(&groups)[0], ["Play now", "Play next", "Remove from queue"]);
|
||||
assert!(matches!(&groups[0][2].action, Action::Send(m) if matches!(&**m, Message::Player(crate::player::Msg::Remove { pos: 4, .. }))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_playing_track_offers_next_track_and_unavailable_ones_cant_be_queued() {
|
||||
let playing = Ctx { playing: true, ..ctx() };
|
||||
let groups = groups(&Target::Track { track: track(""), from: Source::PlayerBar }, &playing);
|
||||
assert_eq!(groups[0][0].label, "Next track");
|
||||
|
||||
let gone = groups_for_unavailable();
|
||||
assert!(matches!(gone[0][0].action, Action::Disabled));
|
||||
assert!(matches!(gone[0][1].action, Action::Disabled));
|
||||
assert!(matches!(gone[1][0].action, Action::Send(_)), "liking still works");
|
||||
}
|
||||
|
||||
fn groups_for_unavailable() -> Vec<Vec<Entry>> {
|
||||
groups(&Target::Track { track: track(r#","available":false"#), from: Source::List { playlist: None } }, &ctx())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_artist_names_are_shortened_and_at_most_three_listed() {
|
||||
let names: Vec<String> = (0..5).map(|i| format!(r#"{{"id":{i},"name":"Очень длинное имя исполнителя номер {i}"}}"#)).collect();
|
||||
let t = Track::from_json(&format!(r#"{{"id":"1","title":"T","artists":[{}]}}"#, names.join(","))).unwrap();
|
||||
let groups = groups(&Target::Track { track: t, from: Source::List { playlist: None } }, &ctx());
|
||||
let go = &groups[2];
|
||||
assert_eq!(go.len(), 3);
|
||||
assert!(go[0].label.ends_with('…'), "{}", go[0].label);
|
||||
assert!(go[0].label.chars().count() <= "Go to ".len() + NAME_CHARS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn own_playlist_cards_rename_and_delete_instead_of_liking() {
|
||||
let own = PlaylistSummary::for_tests(PlaylistId { owner: 1, kind: 9 }, "Дорога");
|
||||
assert_eq!(labels(&groups(&Target::Playlist(own), &ctx()))[1], ["Rename…", "Delete…"]);
|
||||
let theirs = PlaylistSummary::for_tests(PlaylistId { owner: 2, kind: 9 }, "Чужой");
|
||||
assert_eq!(labels(&groups(&Target::Playlist(theirs), &ctx()))[1], ["Add to collection"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrow_keys_skip_disabled_entries_and_wrap() {
|
||||
let gone = groups_for_unavailable();
|
||||
let entries: Vec<&Entry> = flat(&gone).collect();
|
||||
assert_eq!(step(&entries, None, true), Some(2), "the first two can't be picked");
|
||||
assert_eq!(step(&entries, Some(2), false), Some(entries.len() - 1), "up from the first wraps to the last");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_menu_flips_and_stays_inside_the_window() {
|
||||
let window = Size::new(960.0, 620.0);
|
||||
let menu = Size::new(WIDTH, 300.0);
|
||||
assert_eq!(place(Anchor::Point(Point::new(100.0, 100.0)), menu, window), Point::new(100.0, 100.0));
|
||||
// Near the right and bottom edges it opens to the left of and above the pointer.
|
||||
assert_eq!(place(Anchor::Point(Point::new(900.0, 600.0)), menu, window), Point::new(620.0, 300.0));
|
||||
// Under the "…" button, right edges line up.
|
||||
let button = Rectangle::new(Point::new(800.0, 100.0), Size::new(34.0, 34.0));
|
||||
assert_eq!(place(Anchor::Below(button), menu, window), Point::new(834.0 - WIDTH, 138.0));
|
||||
// A menu taller than the room left above and below is held inside.
|
||||
let tall = Size::new(WIDTH, 500.0);
|
||||
let at = place(Anchor::Point(Point::new(100.0, 300.0)), tall, window);
|
||||
assert!(at.y >= MARGIN && at.y + tall.height <= window.height - MARGIN + 0.5, "{at:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_submenu_opens_left_when_there_is_no_room_on_the_right() {
|
||||
let window = Size::new(960.0, 620.0);
|
||||
let sub = Size::new(WIDTH, 200.0);
|
||||
assert_eq!(place_sub(Point::new(100.0, 50.0), 90.0, sub, window).x, 100.0 + WIDTH + 2.0);
|
||||
assert_eq!(place_sub(Point::new(600.0, 50.0), 90.0, sub, window).x, 600.0 - 2.0 - WIDTH);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
pub mod anchor;
|
||||
pub mod card;
|
||||
pub mod drawer;
|
||||
pub mod menu;
|
||||
pub mod player_bar;
|
||||
pub mod sheet;
|
||||
pub mod sidebar;
|
||||
|
||||
@@ -9,7 +9,9 @@ use crate::player::{Msg, Player, Repeat, Status};
|
||||
use crate::ui::icons::{Icon, icon, sized};
|
||||
use crate::ui::line;
|
||||
use crate::ui::theme::{self, Tokens, radius, size};
|
||||
use crate::widgets::anchor::anchor;
|
||||
use crate::widgets::drawer::Panel;
|
||||
use crate::widgets::menu::{Anchor, Menu, Source, Target};
|
||||
use crate::i18n::tr;
|
||||
|
||||
fn send(msg: Msg) -> Message {
|
||||
@@ -68,14 +70,25 @@ fn now_playing<'a>(t: &'static Tokens, p: &'a Player, liked: bool, covers: &Cove
|
||||
_ => (track.artist_line(), t.muted),
|
||||
};
|
||||
|
||||
row![
|
||||
cover,
|
||||
column![
|
||||
line(track.full_title(), theme::MEDIUM, size::BODY, t.fg),
|
||||
line(sub, theme::BODY, size::META, sub_colour),
|
||||
// A right-click on the cover or the title opens the track's menu.
|
||||
let target = Target::Track { track: track.clone(), from: Source::PlayerBar };
|
||||
let about = anchor(
|
||||
row![
|
||||
cover,
|
||||
column![
|
||||
line(track.full_title(), theme::MEDIUM, size::BODY, t.fg),
|
||||
line(sub, theme::BODY, size::META, sub_colour),
|
||||
]
|
||||
.spacing(2)
|
||||
.width(Length::Shrink),
|
||||
]
|
||||
.spacing(2)
|
||||
.width(Length::Shrink),
|
||||
.spacing(12)
|
||||
.align_y(Alignment::Center),
|
||||
)
|
||||
.on_right_press(move |at| Message::OpenMenu(Box::new(Menu::new(target.clone(), Anchor::Point(at)))));
|
||||
|
||||
row![
|
||||
about,
|
||||
button(icon(
|
||||
if liked { Icon::HeartFilled } else { Icon::Heart },
|
||||
if liked { t.like } else { t.muted },
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
//! Small dialogs over the window: track actions, new/rename playlist, delete confirmation.
|
||||
//! Small dialogs over the window: new/rename playlist, delete confirmation.
|
||||
//! Track actions live in the context menu (`widgets::menu`).
|
||||
|
||||
use iced::widget::{Column, button, column, container, mouse_area, opaque, row, space, text_input};
|
||||
use iced::{Alignment, Element, Fill, Length};
|
||||
use ym_api::{PlaylistId, PlaylistSummary, Track};
|
||||
use iced::widget::{button, column, container, mouse_area, opaque, row, space, text_input};
|
||||
use iced::{Alignment, Element, Fill};
|
||||
use ym_api::{PlaylistId, Track};
|
||||
|
||||
use crate::app::Message;
|
||||
use crate::route::Route;
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
use crate::ui::theme::{self, Tokens, radius, size};
|
||||
use crate::ui::{line, para};
|
||||
@@ -13,13 +13,6 @@ use crate::i18n::{tr, trf};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Sheet {
|
||||
Track {
|
||||
track: Track,
|
||||
/// Set when opened from one of the user's own playlists: its id, the row, its length.
|
||||
playlist: Option<(PlaylistId, usize, usize)>,
|
||||
/// Showing the "Add to playlist" list instead of the actions.
|
||||
choosing: bool,
|
||||
},
|
||||
NewPlaylist { name: String, add: Option<Track> },
|
||||
Rename { id: PlaylistId, name: String },
|
||||
ConfirmDelete { id: PlaylistId, title: String },
|
||||
@@ -27,17 +20,8 @@ pub enum Sheet {
|
||||
|
||||
pub const INPUT_ID: &str = "sheet-input";
|
||||
|
||||
/// What the sheet needs to know about the library.
|
||||
pub struct Ctx<'a> {
|
||||
/// The menu is for the track playing now: "next" means skipping ahead.
|
||||
pub playing: bool,
|
||||
pub liked: bool,
|
||||
pub disliked: bool,
|
||||
pub own_playlists: &'a [PlaylistSummary],
|
||||
}
|
||||
|
||||
/// The dimmed backdrop plus the dialog; clicking the backdrop closes it.
|
||||
pub fn overlay<'a>(t: &'static Tokens, sheet: &'a Sheet, ctx: Ctx<'a>) -> Element<'a, Message> {
|
||||
pub fn overlay<'a>(t: &'static Tokens, sheet: &'a Sheet) -> Element<'a, Message> {
|
||||
let backdrop = mouse_area(
|
||||
container(space()).width(Fill).height(Fill).style(|_| container::Style {
|
||||
background: Some(iced::Color::BLACK.scale_alpha(0.45).into()),
|
||||
@@ -46,7 +30,7 @@ pub fn overlay<'a>(t: &'static Tokens, sheet: &'a Sheet, ctx: Ctx<'a>) -> Elemen
|
||||
)
|
||||
.on_press(Message::CloseSheet);
|
||||
|
||||
let card = container(body(t, sheet, ctx))
|
||||
let card = container(body(t, sheet))
|
||||
.width(380)
|
||||
.padding(18)
|
||||
.style(move |_| container::Style {
|
||||
@@ -63,80 +47,8 @@ pub fn overlay<'a>(t: &'static Tokens, sheet: &'a Sheet, ctx: Ctx<'a>) -> Elemen
|
||||
iced::widget::stack![backdrop, container(opaque(card)).center(Fill)].into()
|
||||
}
|
||||
|
||||
fn body<'a>(t: &'static Tokens, sheet: &'a Sheet, ctx: Ctx<'a>) -> Element<'a, Message> {
|
||||
fn body<'a>(t: &'static Tokens, sheet: &'a Sheet) -> Element<'a, Message> {
|
||||
match sheet {
|
||||
Sheet::Track { track, playlist, choosing: false } => {
|
||||
let mut items: Vec<Element<'a, Message>> = vec![
|
||||
if ctx.playing {
|
||||
item(t, Icon::Next, tr("Next track"), Some(Message::SkipFromMenu))
|
||||
} else {
|
||||
item(t, Icon::Next, tr("Play next"), Some(Message::PlayNext(track.clone())))
|
||||
},
|
||||
item(t, Icon::Queue, tr("Add to queue"), Some(Message::AddToQueue(track.clone()))),
|
||||
item(
|
||||
t,
|
||||
if ctx.liked { Icon::HeartFilled } else { Icon::Heart },
|
||||
if ctx.liked { tr("Remove from Liked tracks") } else { tr("Add to Liked tracks") },
|
||||
Some(Message::LikeTrack(track.clone(), !ctx.liked)),
|
||||
),
|
||||
item(
|
||||
t,
|
||||
Icon::Plus,
|
||||
tr("Add to playlist…"),
|
||||
Some(Message::OpenSheet(Sheet::Track { track: track.clone(), playlist: *playlist, choosing: true })),
|
||||
),
|
||||
item(t, Icon::Wave, tr("Play similar tracks"), Some(Message::PlaySimilar(track.clone()))),
|
||||
];
|
||||
if let Some(album) = &track.album {
|
||||
items.push(item(t, Icon::Disc, tr("Go to album"), Some(Message::Navigate(Route::Album(album.id)))));
|
||||
}
|
||||
for artist in track.artists.iter().filter(|a| a.id.is_some()).take(3) {
|
||||
items.push(item(
|
||||
t,
|
||||
Icon::Forward,
|
||||
tr("Go to artist"),
|
||||
artist.id.map(|id| Message::Navigate(Route::Artist(id))),
|
||||
));
|
||||
}
|
||||
items.push(item(
|
||||
t,
|
||||
Icon::Dislike,
|
||||
if ctx.disliked { tr("Recommend this track again") } else { tr("Don't recommend this track") },
|
||||
Some(Message::DislikeTrack(track.clone(), !ctx.disliked)),
|
||||
));
|
||||
if let Some((id, index, len)) = *playlist {
|
||||
items.push(divider());
|
||||
if index > 0 {
|
||||
items.push(item(t, Icon::Back, tr("Move up"), Some(Message::MovePlaylistTrack {
|
||||
id, track: track.clone(), from: index, to: index - 1,
|
||||
})));
|
||||
}
|
||||
if index + 1 < len {
|
||||
items.push(item(t, Icon::Forward, tr("Move down"), Some(Message::MovePlaylistTrack {
|
||||
id, track: track.clone(), from: index, to: index + 1,
|
||||
})));
|
||||
}
|
||||
items.push(item(t, Icon::Trash, tr("Remove from this playlist"), Some(Message::RemoveFromPlaylist(id, index))));
|
||||
}
|
||||
frame(t, track.full_title(), Some(track.artist_line()), Column::with_children(items).spacing(2).into())
|
||||
}
|
||||
Sheet::Track { track, choosing: true, .. } => {
|
||||
let mut items: Vec<Element<'a, Message>> = vec![item(
|
||||
t,
|
||||
Icon::Plus,
|
||||
tr("New playlist…"),
|
||||
Some(Message::OpenSheet(Sheet::NewPlaylist { name: String::new(), add: Some(track.clone()) })),
|
||||
)];
|
||||
items.extend(ctx.own_playlists.iter().map(|p| {
|
||||
item(t, Icon::Queue, &p.title, Some(Message::AddToPlaylist(p.id, track.clone())))
|
||||
}));
|
||||
frame(
|
||||
t,
|
||||
tr("Add to playlist").into(),
|
||||
Some(track.full_title()),
|
||||
iced::widget::scrollable(Column::with_children(items).spacing(2)).height(Length::Shrink).into(),
|
||||
)
|
||||
}
|
||||
Sheet::NewPlaylist { name, add } => {
|
||||
let can = !name.trim().is_empty();
|
||||
let hint = if add.is_some() { tr("The track goes in once it's created.") } else { tr("Only you can see it until you make it public.") };
|
||||
@@ -198,19 +110,6 @@ fn frame<'a>(t: &'static Tokens, title: String, subtitle: Option<String>, conten
|
||||
.into()
|
||||
}
|
||||
|
||||
fn item<'a>(t: &'static Tokens, glyph: Icon, label: &str, msg: Option<Message>) -> Element<'a, Message> {
|
||||
button(row![icon(glyph, t.muted), line(label.to_owned(), theme::MEDIUM, size::BODY, t.fg)].spacing(12).align_y(Alignment::Center))
|
||||
.width(Fill)
|
||||
.padding([9, 10])
|
||||
.style(theme::nav_item(false))
|
||||
.on_press_maybe(msg)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn divider<'a>() -> Element<'a, Message> {
|
||||
container(space()).width(Fill).height(1).style(theme::divider).into()
|
||||
}
|
||||
|
||||
fn input<'a>(placeholder: &'a str, value: &'a str, submit: Option<Message>) -> Element<'a, Message> {
|
||||
text_input(placeholder, value)
|
||||
.id(INPUT_ID)
|
||||
@@ -271,40 +170,3 @@ pub fn toast<'a>(t: &'static Tokens, text: &'a str) -> Element<'a, Message> {
|
||||
.padding(iced::Padding::default().bottom(96))
|
||||
.into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ui::theme::DARK;
|
||||
|
||||
fn track_sheet() -> Sheet {
|
||||
let track = Track::from_json(r#"{"id":"7","title":"Хочешь?","artists":[{"id":3,"name":"Земфира"}],"albums":[{"id":5,"title":"A"}]}"#).unwrap();
|
||||
Sheet::Track { track, playlist: None, choosing: false }
|
||||
}
|
||||
|
||||
fn click(label: &str) -> Vec<String> {
|
||||
let sheet = track_sheet();
|
||||
let mut ui = iced_test::simulator(overlay(&DARK, &sheet, Ctx { playing: false, liked: false, disliked: false, own_playlists: &[] }));
|
||||
ui.click(label).unwrap_or_else(|e| panic!("can't click {label}: {e:?}"));
|
||||
ui.into_messages().map(|m| format!("{m:?}").chars().take(40).collect()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_for_the_playing_track_offers_next_track() {
|
||||
let sheet = track_sheet();
|
||||
let mut ui = iced_test::simulator(overlay(&DARK, &sheet, Ctx { playing: true, liked: false, disliked: false, own_playlists: &[] }));
|
||||
assert!(ui.find("Play next").is_err());
|
||||
ui.click("Next track").expect("next track item");
|
||||
let messages: Vec<String> = ui.into_messages().map(|m| format!("{m:?}")).collect();
|
||||
assert_eq!(messages, ["SkipFromMenu"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_items_send_their_action_and_not_close() {
|
||||
for (label, expected) in [("Play next", "PlayNext("), ("Add to queue", "AddToQueue("), ("Go to album", "Navigate(Album(5))"), ("Play similar tracks", "PlaySimilar(")] {
|
||||
let messages = click(label);
|
||||
assert!(messages.first().is_some_and(|m| m.starts_with(expected)), "{label}: {messages:?}");
|
||||
assert!(!messages.iter().any(|m| m.starts_with("CloseSheet")), "{label} also closed the sheet: {messages:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use ym_api::{LikedIds, PlaylistId, Track};
|
||||
use crate::app::Message;
|
||||
use crate::covers::{self, Covers};
|
||||
use crate::screens::collection::Liked;
|
||||
use crate::widgets::sheet::Sheet;
|
||||
use crate::widgets::menu::{Source, Target};
|
||||
use crate::ui::theme::{self, Tokens, radius};
|
||||
use crate::widgets::track_row::{self, Columns};
|
||||
|
||||
@@ -24,6 +24,29 @@ pub struct Env<'a> {
|
||||
pub playing: Option<&'a str>,
|
||||
/// The signed-in user's uid, to tell their own playlists apart.
|
||||
pub me: i64,
|
||||
/// The track whose menu is open; its rows stay lit.
|
||||
pub menu_track: Option<&'a str>,
|
||||
pub drag: Option<&'a Drag>,
|
||||
}
|
||||
|
||||
/// A row of an own playlist on its way to a new place.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Drag {
|
||||
pub playlist: PlaylistId,
|
||||
pub track: Track,
|
||||
/// Where it was when picked up, and where it would land now.
|
||||
pub from: usize,
|
||||
pub to: usize,
|
||||
}
|
||||
|
||||
/// `items` with the one at `from` moved to `to`.
|
||||
pub fn moved<T: Clone>(items: &[T], from: usize, to: usize) -> Arc<[T]> {
|
||||
let mut v = items.to_vec();
|
||||
if from < v.len() {
|
||||
let item = v.remove(from);
|
||||
v.insert(to.min(v.len()), item);
|
||||
}
|
||||
v.into()
|
||||
}
|
||||
|
||||
#[derive(Hash)]
|
||||
@@ -37,6 +60,9 @@ struct Key {
|
||||
dark: bool,
|
||||
playlist: Option<PlaylistId>,
|
||||
lang: crate::i18n::Lang,
|
||||
menu: Option<String>,
|
||||
/// `(from, to)` while a row of this list is dragged.
|
||||
drag: Option<(usize, usize)>,
|
||||
}
|
||||
|
||||
pub fn view<'a>(env: Env<'a>, tracks: &Arc<[Track]>, columns: Columns) -> Element<'a, Message> {
|
||||
@@ -55,7 +81,7 @@ pub fn view_with<'a>(
|
||||
|
||||
/// One of the user's own playlists: rows get move and remove actions.
|
||||
pub fn view_own_playlist<'a>(env: Env<'a>, tracks: &Arc<[Track]>, id: PlaylistId) -> Element<'a, Message> {
|
||||
build(env, tracks, Columns::FULL, None, Some(id))
|
||||
build(env, tracks, Columns::OWN_PLAYLIST, None, Some(id))
|
||||
}
|
||||
|
||||
fn build<'a>(
|
||||
@@ -65,7 +91,8 @@ fn build<'a>(
|
||||
shifts: Option<Arc<[i32]>>,
|
||||
playlist: Option<PlaylistId>,
|
||||
) -> Element<'a, Message> {
|
||||
let Env { t, covers, liked, playing, .. } = env;
|
||||
let Env { t, covers, liked, playing, menu_track, drag, .. } = env;
|
||||
let drag = drag.filter(|d| playlist == Some(d.playlist)).map(|d| (d.from, d.to));
|
||||
let key = Key {
|
||||
list: (tracks.as_ptr() as usize, tracks.len()),
|
||||
columns,
|
||||
@@ -76,11 +103,19 @@ fn build<'a>(
|
||||
dark: t == &theme::DARK,
|
||||
playlist,
|
||||
lang: crate::i18n::lang(),
|
||||
menu: menu_track.filter(|id| tracks.iter().any(|tr| tr.id == *id)).map(str::to_owned),
|
||||
drag,
|
||||
};
|
||||
// While dragging, the list shows the order it would have if dropped now.
|
||||
let shown = match drag {
|
||||
Some((from, to)) => moved(tracks, from, to),
|
||||
None => tracks.clone(),
|
||||
};
|
||||
let tracks = tracks.clone();
|
||||
|
||||
lazy(key, move |key: &Key| {
|
||||
let rows = tracks.iter().enumerate().map(|(index, track)| {
|
||||
let rows = shown.iter().enumerate().map(|(index, track)| {
|
||||
let dragged = key.drag.is_some_and(|(_, to)| to == index);
|
||||
let cover = columns.cover.then(|| {
|
||||
covers::view(covers, track.cover_url(covers::SMALL), track.hues(), 40.0, radius::SMALL_COVER)
|
||||
});
|
||||
@@ -92,11 +127,16 @@ fn build<'a>(
|
||||
playing: key.playing.as_deref() == Some(track.id.as_str()),
|
||||
liked: liked.contains(&track.id),
|
||||
on_like: Message::LikeTrack(track.clone(), !liked.contains(&track.id)),
|
||||
on_more: Message::OpenSheet(Sheet::Track {
|
||||
menu: Target::Track {
|
||||
track: track.clone(),
|
||||
playlist: key.playlist.map(|id| (id, index, tracks.len())),
|
||||
choosing: false,
|
||||
}),
|
||||
from: Source::List { playlist: key.playlist.map(|id| (id, index, tracks.len())) },
|
||||
},
|
||||
lit: dragged || key.menu.as_deref() == Some(track.id.as_str()),
|
||||
on_grip: match (key.playlist, key.drag) {
|
||||
(Some(playlist), None) => Some(Message::DragStart { playlist, track: track.clone(), index }),
|
||||
_ => None,
|
||||
},
|
||||
on_drag_over: key.drag.map(|_| Message::DragOver(index)),
|
||||
cover,
|
||||
columns,
|
||||
shift: shifts.as_ref().and_then(|s| s.get(index).copied()).unwrap_or(0),
|
||||
@@ -108,3 +148,16 @@ fn build<'a>(
|
||||
})
|
||||
.into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::moved;
|
||||
|
||||
#[test]
|
||||
fn moving_an_item_shifts_the_ones_between() {
|
||||
assert_eq!(&*moved(&[0, 1, 2, 3, 4], 1, 3), &[0, 2, 3, 1, 4]);
|
||||
assert_eq!(&*moved(&[0, 1, 2, 3, 4], 3, 0), &[3, 0, 1, 2, 4]);
|
||||
assert_eq!(&*moved(&[0, 1, 2], 2, 2), &[0, 1, 2]);
|
||||
assert_eq!(&*moved(&[0, 1, 2], 0, 9), &[1, 2, 0], "past the end lands last");
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
//! One row in a track list: number (or a playing marker), cover, title and
|
||||
//! artists, album, like state, duration. Clicking anywhere plays it.
|
||||
//! artists, album, like state, duration. Clicking anywhere plays it; a
|
||||
//! right-click or the "…" button opens its menu.
|
||||
|
||||
use iced::widget::{button, column, container, row, space};
|
||||
use iced::{Alignment, Element, Fill, Length};
|
||||
use iced::widget::{button, column, container, mouse_area, row, space};
|
||||
use iced::{Alignment, Element, Fill, Length, mouse};
|
||||
use ym_api::Track;
|
||||
|
||||
use crate::app::Message;
|
||||
use crate::widgets::anchor::anchor;
|
||||
use crate::widgets::menu::{Anchor, Menu, Target};
|
||||
use crate::ui::icons::{Icon, icon, sized};
|
||||
use crate::ui::line;
|
||||
use crate::ui::theme::{self, Tokens, size};
|
||||
@@ -21,14 +24,19 @@ pub struct Columns {
|
||||
pub album: bool,
|
||||
/// Chart lists show how far each track moved.
|
||||
pub shift: bool,
|
||||
/// The user's own playlists: a handle to drag rows into a new order.
|
||||
pub grip: bool,
|
||||
}
|
||||
|
||||
impl Columns {
|
||||
pub const FULL: Columns = Columns { cover: true, album: true, shift: false };
|
||||
pub const ALBUM_PAGE: Columns = Columns { cover: false, album: false, shift: false };
|
||||
pub const CHART: Columns = Columns { cover: true, album: true, shift: true };
|
||||
pub const FULL: Columns = Columns { cover: true, album: true, shift: false, grip: false };
|
||||
pub const ALBUM_PAGE: Columns = Columns { cover: false, album: false, shift: false, grip: false };
|
||||
pub const CHART: Columns = Columns { cover: true, album: true, shift: true, grip: false };
|
||||
pub const OWN_PLAYLIST: Columns = Columns { grip: true, ..Columns::FULL };
|
||||
}
|
||||
|
||||
const GRIP: f32 = 20.0;
|
||||
|
||||
pub struct Row<'a> {
|
||||
pub index: usize,
|
||||
pub track: &'a Track,
|
||||
@@ -40,7 +48,14 @@ pub struct Row<'a> {
|
||||
pub shift: i32,
|
||||
pub on_press: Message,
|
||||
pub on_like: Message,
|
||||
pub on_more: Message,
|
||||
/// What the row's menu is for.
|
||||
pub menu: Target,
|
||||
/// Held lit: its menu is open, or it's the row being dragged.
|
||||
pub lit: bool,
|
||||
/// Pressing the drag handle (own playlists, when no drag is under way).
|
||||
pub on_grip: Option<Message>,
|
||||
/// While a row is being dragged: the pointer reached this one.
|
||||
pub on_drag_over: Option<Message>,
|
||||
}
|
||||
|
||||
/// Builds an owned (`'static`) row so lists can sit inside `lazy`.
|
||||
@@ -59,10 +74,16 @@ pub fn view(t: &'static Tokens, r: Row<'_>) -> Element<'static, Message> {
|
||||
(false, false) => t.fg,
|
||||
};
|
||||
|
||||
let mut content = row![container(number).width(36).center_x(36)]
|
||||
.spacing(12)
|
||||
.align_y(Alignment::Center)
|
||||
.height(HEIGHT);
|
||||
let mut content = row![].spacing(12).align_y(Alignment::Center).height(HEIGHT);
|
||||
if r.columns.grip {
|
||||
let grip = container(icon(Icon::Grip, if r.lit { t.fg } else { t.muted })).width(GRIP).center_x(GRIP);
|
||||
let grip = mouse_area(grip).interaction(mouse::Interaction::Grab);
|
||||
content = content.push(match r.on_grip {
|
||||
Some(msg) => grip.on_press(msg),
|
||||
None => grip,
|
||||
});
|
||||
}
|
||||
content = content.push(container(number).width(36).center_x(36));
|
||||
if r.columns.shift {
|
||||
content = content.push(crate::screens::browse::shift_marker(t, r.shift));
|
||||
}
|
||||
@@ -105,28 +126,35 @@ pub fn view(t: &'static Tokens, r: Row<'_>) -> Element<'static, Message> {
|
||||
.width(52)
|
||||
.align_right(52),
|
||||
)
|
||||
.push(
|
||||
button(icon(Icon::More, t.muted))
|
||||
.padding(8)
|
||||
.style(theme::icon_button(None))
|
||||
.on_press(r.on_more),
|
||||
);
|
||||
.push({
|
||||
let target = r.menu.clone();
|
||||
// The anchor takes the click and reports where the button is; `on_press`
|
||||
// only keeps the hover style, and its message is never sent.
|
||||
anchor(button(icon(Icon::More, t.muted)).padding(8).style(theme::icon_button(None)).on_press(Message::CloseMenu))
|
||||
.on_press(move |bounds| Message::OpenMenu(Box::new(Menu::new(target.clone(), Anchor::Below(bounds)))))
|
||||
});
|
||||
|
||||
button(content)
|
||||
let row = button(content)
|
||||
.width(Fill)
|
||||
.padding([0, 10])
|
||||
.style(theme::nav_item(false))
|
||||
.on_press_maybe((!unavailable).then_some(r.on_press))
|
||||
.into()
|
||||
.style(theme::nav_item(r.lit))
|
||||
.on_press_maybe((!unavailable && r.on_drag_over.is_none()).then_some(r.on_press));
|
||||
let target = r.menu;
|
||||
let row = anchor(row).on_right_press(move |at| Message::OpenMenu(Box::new(Menu::new(target.clone(), Anchor::Point(at)))));
|
||||
match r.on_drag_over {
|
||||
Some(msg) => mouse_area(row).on_enter(msg).interaction(mouse::Interaction::Grabbing).into(),
|
||||
None => row.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Column headings above a track list, aligned with [`view`].
|
||||
pub fn header(t: &'static Tokens, columns: Columns) -> Element<'static, Message> {
|
||||
let label = |s: &'static str| line(s, theme::BODY, size::SMALL, t.muted);
|
||||
let mut heads = row![container(label("#")).width(36).center_x(36)]
|
||||
.spacing(12)
|
||||
.align_y(Alignment::Center)
|
||||
.padding([0, 10]);
|
||||
let mut heads = row![].spacing(12).align_y(Alignment::Center).padding([0, 10]);
|
||||
if columns.grip {
|
||||
heads = heads.push(space().width(GRIP));
|
||||
}
|
||||
heads = heads.push(container(label("#")).width(36).center_x(36));
|
||||
if columns.shift {
|
||||
heads = heads.push(space().width(14));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user