//! Every place the content area can show. Detail pages (album, artist, playlist) //! join this enum once they carry ids from the API. use crate::i18n::tr; use ym_api::PlaylistId; use crate::ui::icons::Icon; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Route { Home, Wave, Search, Collection, Podcasts, Settings, Album(i64), Artist(i64), Playlist(PlaylistId), Chart, /// Index into the app's flattened genre list. Genre(usize), } impl Route { /// Sidebar order. pub const NAV: [Route; 5] = [Route::Home, Route::Wave, Route::Search, Route::Collection, Route::Podcasts]; pub fn label(self) -> &'static str { match self { Route::Home => tr("Home"), Route::Wave => tr("My Wave"), Route::Search => tr("Search"), Route::Collection => tr("Collection"), Route::Podcasts => tr("Podcasts"), Route::Settings => tr("Settings"), Route::Album(_) => tr("Album"), Route::Artist(_) => tr("Artist"), Route::Playlist(_) => tr("Playlist"), Route::Chart => tr("Chart"), Route::Genre(_) => tr("Genre"), } } pub fn icon(self) -> Icon { match self { Route::Home => Icon::Home, Route::Wave => Icon::Wave, Route::Search => Icon::Search, Route::Collection => Icon::Library, Route::Podcasts => Icon::Podcast, Route::Settings => Icon::Settings, Route::Album(_) => Icon::Disc, Route::Artist(_) => Icon::Wave, Route::Playlist(_) => Icon::Queue, Route::Chart => Icon::Chart, Route::Genre(_) => Icon::Library, } } } /// Back-stack navigation: the sidebar pushes, the back button pops. #[derive(Debug, Clone)] pub struct Navigator { current: Route, history: Vec, } impl Navigator { const MAX_HISTORY: usize = 50; pub fn new(start: Route) -> Self { Self { current: start, history: Vec::new() } } pub fn current(&self) -> Route { self.current } pub fn can_go_back(&self) -> bool { !self.history.is_empty() } pub fn go(&mut self, route: Route) { if route == self.current { return; } if self.history.len() == Self::MAX_HISTORY { self.history.remove(0); } self.history.push(self.current); self.current = route; } pub fn back(&mut self) { if let Some(previous) = self.history.pop() { self.current = previous; } } } #[cfg(test)] mod tests { use super::*; #[test] fn back_returns_to_previous_route() { let mut nav = Navigator::new(Route::Home); nav.go(Route::Search); nav.go(Route::Collection); nav.back(); assert_eq!(nav.current(), Route::Search); nav.back(); assert_eq!(nav.current(), Route::Home); assert!(!nav.can_go_back()); nav.back(); assert_eq!(nav.current(), Route::Home); } #[test] fn revisiting_current_route_does_not_grow_history() { let mut nav = Navigator::new(Route::Home); nav.go(Route::Home); assert!(!nav.can_go_back()); } #[test] fn history_is_bounded() { let mut nav = Navigator::new(Route::Home); for i in 0..200 { nav.go(if i % 2 == 0 { Route::Search } else { Route::Home }); } assert_eq!(nav.history.len(), Navigator::MAX_HISTORY); } }