From e5c43fbb77cfec71702f6761693f259ac6a740e9 Mon Sep 17 00:00:00 2001 From: Yuriy Panov Date: Sun, 18 Oct 2026 20:04:42 +0600 Subject: [PATCH 1/3] feat: keyboard shortcuts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Space plays or pauses, ⌘←/→ skips, ⇧←/→ seeks 10 seconds, ⌘↑/↓ sets the volume, ⌘L likes the playing track, ⌘F or / focuses search, ⌘[ or ⌥← goes back, ⌘1–5 and ⌘, open the sidebar sections and Settings, and Esc closes what's open. ⌘ is Ctrl on Windows and Linux. Keys a focused text field uses never reach the shortcuts, and letters fall back to their key position so they work on a Russian layout. Opening Search now puts the cursor in the field. Settings lists the shortcuts. Co-Authored-By: Claude Opus 5.5 --- crates/musyx/src/app.rs | 85 +++++++++++- crates/musyx/src/i18n/ru.rs | 10 ++ crates/musyx/src/main.rs | 1 + crates/musyx/src/screens/settings.rs | 17 ++- crates/musyx/src/shortcuts.rs | 194 +++++++++++++++++++++++++++ crates/musyx/src/ui/theme.rs | 11 ++ 6 files changed, 316 insertions(+), 2 deletions(-) create mode 100644 crates/musyx/src/shortcuts.rs diff --git a/crates/musyx/src/app.rs b/crates/musyx/src/app.rs index 8d70f3d..0aa0d0c 100644 --- a/crates/musyx/src/app.rs +++ b/crates/musyx/src/app.rs @@ -25,6 +25,7 @@ use crate::screens::wave::WaveScreen; use crate::screens::detail::{self, Page}; use crate::screens::{self, Loadable, sign_in}; use crate::session::{self, Restored}; +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}; @@ -138,6 +139,7 @@ pub enum Message { ClearCoverCache, CoverCacheCleared(Result<(), String>), Media(crate::media::Command), + Shortcut(Shortcut), /// A window opened; Windows media controls need its handle. WindowOpened(iced::window::Id), MediaWindow(u64), @@ -273,6 +275,9 @@ impl App { if let Session::SignedOut(sign_in) = &self.session { subs.push(sign_in.subscription().map(Message::SignIn)); } + if matches!(self.session, Session::SignedIn { .. }) { + subs.push(shortcuts::subscription().map(Message::Shortcut)); + } // 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) @@ -470,7 +475,9 @@ impl App { self.sheet = None; self.nav.go(route); let (close, _) = self.search.update(search::Msg::CloseSuggestions, None); - return Task::batch([close, self.on_enter(route)]); + // Opening Search is a request to type. + let focus = if route == Route::Search { focus_search() } else { Task::none() }; + return Task::batch([close, self.on_enter(route), focus]); } Message::AccountRefreshed(Ok(fresh)) => { if let Session::SignedIn { account, .. } = &mut self.session { @@ -550,6 +557,7 @@ impl App { }; return self.update(Message::Player(msg)); } + Message::Shortcut(shortcut) => return self.shortcut(shortcut), Message::SkipFromMenu => { self.sheet = None; return self.update(Message::Player(player::Msg::Next)); @@ -860,6 +868,40 @@ impl App { Task::none() } + fn shortcut(&mut self, shortcut: Shortcut) -> Task { + use crate::media::Command; + let to_player = Message::Player; + let msg = match shortcut { + Shortcut::TogglePlay => to_player(player::Msg::Toggle), + Shortcut::Next => to_player(player::Msg::Next), + Shortcut::Previous => to_player(player::Msg::Previous), + Shortcut::SeekForward => Message::Media(Command::SeekBy { forward: true, by: shortcuts::SEEK_STEP }), + Shortcut::SeekBack => Message::Media(Command::SeekBy { forward: false, by: shortcuts::SEEK_STEP }), + Shortcut::VolumeUp => to_player(player::Msg::SetVolume(self.player.volume + shortcuts::VOLUME_STEP)), + Shortcut::VolumeDown => to_player(player::Msg::SetVolume(self.player.volume - shortcuts::VOLUME_STEP)), + Shortcut::ToggleLike => { + let Some(track) = self.player.track().cloned() else { return Task::none() }; + let liked = self.library.liked.contains(&track.id); + Message::LikeTrack(track, !liked) + } + Shortcut::FocusSearch => return focus_search(), + Shortcut::Back if self.nav.can_go_back() => Message::Back, + Shortcut::Back => return Task::none(), + Shortcut::Dismiss => { + if self.sheet.is_some() { + self.sheet = None; + } else if self.search.suggestions().is_some() { + return self.update(Message::Search(search::Msg::CloseSuggestions)); + } else { + self.drawer = None; + } + return Task::none(); + } + Shortcut::Go(route) => Message::Navigate(route), + }; + self.update(msg) + } + /// Loads what a route shows on first visit, and retries after a failure. fn on_enter(&mut self, route: Route) -> Task { match route { @@ -1176,6 +1218,12 @@ fn trace(message: &Message) -> bool { true } +/// Puts the cursor in the search field with its text selected, so typing replaces the last query. +fn focus_search() -> Task { + use iced::widget::operation; + Task::batch([operation::focus(topbar::SEARCH_ID), operation::select_all(topbar::SEARCH_ID)]) +} + fn restore() -> Task { Task::future(session::restore()).map(Message::Restored) } @@ -1249,6 +1297,41 @@ mod tests { assert_eq!(app.player.track().unwrap().id, "b"); } + #[test] + 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 })); + let _ = app.update(Message::Shortcut(Shortcut::Dismiss)); + assert!(app.sheet.is_none()); + assert_eq!(app.drawer, Some(Panel::Queue)); + let _ = app.update(Message::Shortcut(Shortcut::Dismiss)); + assert_eq!(app.drawer, None); + } + + #[test] + fn shortcuts_drive_the_player_and_navigation() { + 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::Shortcut(Shortcut::Next)); + assert_eq!(app.player.track().unwrap().id, "b"); + + let _ = app.update(Message::Player(player::Msg::SetVolume(0.03))); + let _ = app.update(Message::Shortcut(Shortcut::VolumeDown)); + assert_eq!(app.player.volume, 0.0); + let _ = app.update(Message::Shortcut(Shortcut::VolumeUp)); + assert!((app.player.volume - shortcuts::VOLUME_STEP).abs() < f32::EPSILON); + + // Back does nothing on the first page, then returns from where ⌘2 went. + let _ = app.update(Message::Shortcut(Shortcut::Back)); + assert_eq!(app.nav.current(), Route::Home); + let _ = app.update(Message::Shortcut(Shortcut::Go(Route::Wave))); + assert_eq!(app.nav.current(), Route::Wave); + let _ = app.update(Message::Shortcut(Shortcut::Back)); + assert_eq!(app.nav.current(), Route::Home); + } + #[test] fn play_next_on_the_playing_track_says_so() { let mut app = signed_in(); diff --git a/crates/musyx/src/i18n/ru.rs b/crates/musyx/src/i18n/ru.rs index c426ec0..4c54b20 100644 --- a/crates/musyx/src/i18n/ru.rs +++ b/crates/musyx/src/i18n/ru.rs @@ -10,6 +10,16 @@ pub fn get(english: &str) -> Option<&'static str> { "Collection" => "Коллекция", "Podcasts" => "Подкасты", "Settings" => "Настройки", + "Keyboard shortcuts" => "Сочетания клавиш", + "Play or pause" => "Играть или пауза", + "Space" => "Пробел", + "Next or previous track" => "Следующий или предыдущий трек", + "Skip 10 seconds forward or back" => "Перемотать на 10 секунд вперёд или назад", + "Volume up or down" => "Громче или тише", + "Like or unlike the track playing" => "«Мне нравится» для играющего трека", + "Go back" => "Назад", + "Close a menu or panel" => "Закрыть меню или панель", + "Home, My Wave, Search, Collection, Podcasts" => "Главная, Моя волна, Поиск, Коллекция, Подкасты", "Album" => "Альбом", "Artist" => "Исполнитель", "Playlist" => "Плейлист", diff --git a/crates/musyx/src/main.rs b/crates/musyx/src/main.rs index 3ceacc9..7566414 100644 --- a/crates/musyx/src/main.rs +++ b/crates/musyx/src/main.rs @@ -10,6 +10,7 @@ mod player; mod route; mod screens; mod session; +mod shortcuts; mod store; #[cfg(feature = "snapshot")] mod snapshot; diff --git a/crates/musyx/src/screens/settings.rs b/crates/musyx/src/screens/settings.rs index f85bf30..1975519 100644 --- a/crates/musyx/src/screens/settings.rs +++ b/crates/musyx/src/screens/settings.rs @@ -1,6 +1,6 @@ //! Settings: account, streaming quality, appearance, storage. -use iced::widget::{Row, button, column, container, row}; +use iced::widget::{Column, Row, button, column, container, row, space}; use iced::{Alignment, Element, Fill}; use crate::app::Message; use crate::store::{Appearance, Locale, Quality, Settings}; @@ -42,6 +42,7 @@ pub fn view<'a>(t: &'static Tokens, settings: &Settings, account: Element<'a, Me .spacing(12) .into(), ), + section(t, tr("Keyboard shortcuts"), shortcuts(t)), line(trf("Musyx {} · unofficial Yandex Music client", &[&env!("CARGO_PKG_VERSION")]), theme::BODY, size::SMALL, t.muted), ] .spacing(28) @@ -64,3 +65,17 @@ fn chip<'a>(t: &'static Tokens, label: &'static str, on: bool, msg: Message) -> .on_press_maybe((!on).then_some(msg)) .into() } + +fn shortcuts<'a>(t: &'static Tokens) -> Element<'a, Message> { + let rows = crate::shortcuts::help().into_iter().map(|(action, keys)| { + let caps = Row::with_children(keys.into_iter().map(|k| { + container(line(k, theme::MEDIUM, size::META, t.fg)).padding([2, 8]).style(theme::kbd).into() + })) + .spacing(6); + row![line(action, theme::BODY, size::BODY, t.fg), space::horizontal(), caps] + .spacing(12) + .align_y(Alignment::Center) + .into() + }); + Column::with_children(rows).spacing(10).max_width(560).into() +} diff --git a/crates/musyx/src/shortcuts.rs b/crates/musyx/src/shortcuts.rs new file mode 100644 index 0000000..e9c41ea --- /dev/null +++ b/crates/musyx/src/shortcuts.rs @@ -0,0 +1,194 @@ +//! Keyboard shortcuts. Only keys a focused text field didn't use arrive here, so +//! Space typed into search stays a space. Letters and punctuation are read by +//! their position as a fallback, so ⌘F still works on a Russian layout. + +use std::time::Duration; + +use iced::Subscription; +use iced::keyboard::key::{Code, Named, Physical}; +use iced::keyboard::{self, Key, Modifiers}; + +use crate::i18n::tr; +use crate::route::Route; + +/// One step of the volume keys. +pub const VOLUME_STEP: f32 = 0.05; +/// How far the seek keys jump. +pub const SEEK_STEP: Duration = Duration::from_secs(10); + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Shortcut { + TogglePlay, + Next, + Previous, + SeekForward, + SeekBack, + VolumeUp, + VolumeDown, + ToggleLike, + FocusSearch, + Back, + /// Esc: closes the menu, then the search suggestions, then the drawer. + Dismiss, + Go(Route), +} + +pub fn subscription() -> Subscription { + keyboard::listen().filter_map(|event| match event { + keyboard::Event::KeyPressed { key, physical_key, modifiers, repeat, .. } => { + from_key(&key, physical_key, modifiers, repeat) + } + _ => None, + }) +} + +pub fn from_key(key: &Key, physical: Physical, mods: Modifiers, repeat: bool) -> Option { + use Shortcut as S; + let cmd = mods.command(); + // Shortcuts that Alt or the other platform's Ctrl would change into something else. + let plain = !mods.alt() && !(mods.control() && mods.logo()); + + if let Key::Named(named) = key { + let shortcut = match (named, cmd, mods.shift(), mods.alt()) { + (Named::Space, false, false, false) if !mods.control() && !mods.logo() => S::TogglePlay, + (Named::Escape, false, false, false) => S::Dismiss, + (Named::ArrowRight, true, false, false) => S::Next, + (Named::ArrowLeft, true, false, false) => S::Previous, + (Named::ArrowUp, true, false, false) => S::VolumeUp, + (Named::ArrowDown, true, false, false) => S::VolumeDown, + (Named::ArrowRight, false, true, false) => S::SeekForward, + (Named::ArrowLeft, false, true, false) => S::SeekBack, + (Named::ArrowLeft, false, false, true) => S::Back, + _ => 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); + return (!repeat || repeats).then_some(shortcut); + } + + if repeat || !plain || mods.shift() { + return None; + } + let c = latin(key, physical)?; + if !cmd { + // "/" by character, or by position where the layout puts something else there. + let slash = c == '/' || physical == Physical::Code(Code::Slash); + return (slash && !mods.control() && !mods.logo()).then_some(S::FocusSearch); + } + Some(match c { + 'f' => S::FocusSearch, + 'l' => S::ToggleLike, + '[' => S::Back, + ',' => S::Go(Route::Settings), + '1'..='5' => S::Go(Route::NAV[c as usize - '1' as usize]), + _ => return None, + }) +} + +/// The character a key stands for on a Latin layout. +fn latin(key: &Key, physical: Physical) -> Option { + if let Key::Character(s) = key { + let mut chars = s.chars(); + if let (Some(c), None) = (chars.next(), chars.next()) + && c.is_ascii() + { + return Some(c.to_ascii_lowercase()); + } + } + match physical { + Physical::Code(Code::Slash) => Some('/'), + Physical::Code(Code::BracketLeft) => Some('['), + Physical::Code(Code::Comma) => Some(','), + _ => key.to_latin(physical), + } +} + +/// The list Settings shows: what each shortcut does and the keys for it. +pub fn help() -> Vec<(&'static str, Vec)> { + let (cmd, shift, alt) = if cfg!(target_os = "macos") { ("⌘", "⇧", "⌥") } else { ("Ctrl+", "Shift+", "Alt+") }; + let with = |m: &str, k: &str| format!("{m}{k}"); + vec![ + (tr("Play or pause"), vec![tr("Space").to_owned()]), + (tr("Next or previous track"), vec![with(cmd, "→"), with(cmd, "←")]), + (tr("Skip 10 seconds forward or back"), vec![with(shift, "→"), with(shift, "←")]), + (tr("Volume up or down"), vec![with(cmd, "↑"), with(cmd, "↓")]), + (tr("Like or unlike the track playing"), vec![with(cmd, "L")]), + (tr("Search"), vec![with(cmd, "F"), "/".to_owned()]), + (tr("Go back"), vec![with(cmd, "["), with(alt, "←")]), + (tr("Close a menu or panel"), vec!["Esc".to_owned()]), + (tr("Home, My Wave, Search, Collection, Podcasts"), vec![format!("{cmd}1 … {cmd}5")]), + (tr("Settings"), vec![with(cmd, ",")]), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + use iced::keyboard::key::NativeCode; + + fn press(key: Key, code: Code, mods: Modifiers) -> Option { + from_key(&key, Physical::Code(code), mods, false) + } + + fn ch(s: &str) -> Key { + Key::Character(s.into()) + } + + #[test] + fn space_toggles_only_without_modifiers() { + assert_eq!(press(Key::Named(Named::Space), Code::Space, Modifiers::empty()), Some(Shortcut::TogglePlay)); + assert_eq!(press(Key::Named(Named::Space), Code::Space, Modifiers::COMMAND), None); + assert_eq!(press(Key::Named(Named::Space), Code::Space, Modifiers::SHIFT), None); + } + + #[test] + fn held_space_does_not_repeat_but_volume_does() { + let space = from_key(&Key::Named(Named::Space), Physical::Code(Code::Space), Modifiers::empty(), true); + assert_eq!(space, None); + let up = from_key(&Key::Named(Named::ArrowUp), Physical::Code(Code::ArrowUp), Modifiers::COMMAND, true); + assert_eq!(up, Some(Shortcut::VolumeUp)); + } + + #[test] + fn transport_and_seek_arrows() { + let arrow = |n, code, m| press(Key::Named(n), code, m); + assert_eq!(arrow(Named::ArrowRight, Code::ArrowRight, Modifiers::COMMAND), Some(Shortcut::Next)); + 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); + } + + #[test] + fn letters_follow_the_key_position_on_a_russian_layout() { + // ⌘ plus the key that types "а" in the Russian layout is ⌘F. + assert_eq!(press(ch("а"), Code::KeyF, Modifiers::COMMAND), Some(Shortcut::FocusSearch)); + assert_eq!(press(ch("д"), Code::KeyL, Modifiers::COMMAND), Some(Shortcut::ToggleLike)); + assert_eq!(press(ch("х"), Code::BracketLeft, Modifiers::COMMAND), Some(Shortcut::Back)); + assert_eq!(press(ch("."), Code::Slash, Modifiers::empty()), Some(Shortcut::FocusSearch)); + } + + #[test] + fn letters_follow_the_character_on_latin_layouts() { + // On AZERTY the key in QWERTY's F position still types "f". + assert_eq!(press(ch("f"), Code::KeyF, Modifiers::COMMAND), Some(Shortcut::FocusSearch)); + assert_eq!(press(ch("l"), Code::KeyO, Modifiers::COMMAND), Some(Shortcut::ToggleLike)); + } + + #[test] + fn number_keys_open_the_sidebar_sections() { + assert_eq!(press(ch("1"), Code::Digit1, Modifiers::COMMAND), Some(Shortcut::Go(Route::Home))); + assert_eq!(press(ch("5"), Code::Digit5, Modifiers::COMMAND), Some(Shortcut::Go(Route::Podcasts))); + assert_eq!(press(ch("6"), Code::Digit6, Modifiers::COMMAND), None); + assert_eq!(press(ch(","), Code::Comma, Modifiers::COMMAND), Some(Shortcut::Go(Route::Settings))); + } + + #[test] + fn bare_letters_and_shifted_combinations_do_nothing() { + assert_eq!(press(ch("f"), Code::KeyF, Modifiers::empty()), None); + assert_eq!(press(ch("l"), Code::KeyL, Modifiers::COMMAND | Modifiers::SHIFT), None); + assert_eq!(press(ch("l"), Code::KeyL, Modifiers::COMMAND | Modifiers::ALT), None); + let unknown = from_key(&ch("ж"), Physical::Unidentified(NativeCode::Unidentified), Modifiers::COMMAND, false); + assert_eq!(unknown, None); + } +} diff --git a/crates/musyx/src/ui/theme.rs b/crates/musyx/src/ui/theme.rs index fef3a35..4c98d54 100644 --- a/crates/musyx/src/ui/theme.rs +++ b/crates/musyx/src/ui/theme.rs @@ -188,6 +188,17 @@ pub fn badge(theme: &Theme) -> container::Style { } } +/// A key cap in the shortcut list. +pub fn kbd(theme: &Theme) -> container::Style { + let t = tokens(theme); + container::Style { + background: Some(t.raised.into()), + text_color: Some(t.fg), + border: Border { radius: radius::SMALL_COVER.into(), ..Border::default() }, + ..container::Style::default() + } +} + pub fn accent_dot(theme: &Theme) -> container::Style { container::Style { background: Some(tokens(theme).accent.into()), From ac5c8c4c8c1856b92637e44418a22ba7f8891123 Mon Sep 17 00:00:00 2001 From: Yuriy Panov Date: Sun, 18 Oct 2026 20:05:31 +0600 Subject: [PATCH 2/3] feat: context menu for tracks, albums, playlists and artists MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .../musyx/assets/icons/arrow-down-to-line.svg | 17 + .../musyx/assets/icons/arrow-up-to-line.svg | 17 + crates/musyx/assets/icons/user.svg | 16 + crates/musyx/src/app.rs | 383 +++++++++++-- crates/musyx/src/i18n/ru.rs | 11 + crates/musyx/src/player/mod.rs | 11 + crates/musyx/src/player/queue.rs | 32 ++ crates/musyx/src/screens/browse.rs | 1 + crates/musyx/src/screens/collection.rs | 5 + crates/musyx/src/shortcuts.rs | 19 +- crates/musyx/src/snapshot.rs | 52 +- crates/musyx/src/ui/icons.rs | 3 + crates/musyx/src/widgets/anchor.rs | 171 ++++++ crates/musyx/src/widgets/card.rs | 15 +- crates/musyx/src/widgets/drawer.rs | 14 +- crates/musyx/src/widgets/menu.rs | 519 ++++++++++++++++++ crates/musyx/src/widgets/mod.rs | 2 + crates/musyx/src/widgets/player_bar.rs | 27 +- crates/musyx/src/widgets/sheet.rs | 154 +----- crates/musyx/src/widgets/track_list.rs | 69 ++- crates/musyx/src/widgets/track_row.rs | 78 ++- 21 files changed, 1386 insertions(+), 230 deletions(-) create mode 100644 crates/musyx/assets/icons/arrow-down-to-line.svg create mode 100644 crates/musyx/assets/icons/arrow-up-to-line.svg create mode 100644 crates/musyx/assets/icons/user.svg create mode 100644 crates/musyx/src/widgets/anchor.rs create mode 100644 crates/musyx/src/widgets/menu.rs diff --git a/crates/musyx/assets/icons/arrow-down-to-line.svg b/crates/musyx/assets/icons/arrow-down-to-line.svg new file mode 100644 index 0000000..857cf2b --- /dev/null +++ b/crates/musyx/assets/icons/arrow-down-to-line.svg @@ -0,0 +1,17 @@ + + + + + + diff --git a/crates/musyx/assets/icons/arrow-up-to-line.svg b/crates/musyx/assets/icons/arrow-up-to-line.svg new file mode 100644 index 0000000..097179f --- /dev/null +++ b/crates/musyx/assets/icons/arrow-up-to-line.svg @@ -0,0 +1,17 @@ + + + + + + diff --git a/crates/musyx/assets/icons/user.svg b/crates/musyx/assets/icons/user.svg new file mode 100644 index 0000000..4b7a65b --- /dev/null +++ b/crates/musyx/assets/icons/user.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/crates/musyx/src/app.rs b/crates/musyx/src/app.rs index 0aa0d0c..cdcb462 100644 --- a/crates/musyx/src/app.rs +++ b/crates/musyx/src/app.rs @@ -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, + menu: Option, + /// A row of an own playlist being dragged to a new place. + drag: Option, + /// 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>>>, @@ -151,6 +157,22 @@ pub enum Message { LikeArtist(i64, bool), LikePlaylist(PlaylistId, bool), OpenSheet(Sheet), + OpenMenu(Box), + 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), + /// 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 { + 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 { + 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 { 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 { 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 { + 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"]); + } } diff --git a/crates/musyx/src/i18n/ru.rs b/crates/musyx/src/i18n/ru.rs index 4c54b20..52e832c 100644 --- a/crates/musyx/src/i18n/ru.rs +++ b/crates/musyx/src/i18n/ru.rs @@ -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" => "Переименовать плейлист", diff --git a/crates/musyx/src/player/mod.rs b/crates/musyx/src/player/mod.rs index 7653938..2bca8d1 100644 --- a/crates/musyx/src/player/mod.rs +++ b/crates/musyx/src/player/mod.rs @@ -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 }, Prefetched { track_id: String, result: Result }, /// 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 { diff --git a/crates/musyx/src/player/queue.rs b/crates/musyx/src/player/queue.rs index 5622019..97826c7 100644 --- a/crates/musyx/src/player/queue.rs +++ b/crates/musyx/src/player/queue.rs @@ -161,6 +161,23 @@ impl Queue { 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 = self.order[..=self.pos].to_vec(); @@ -184,6 +201,21 @@ mod tests { assert!(Queue::::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::>(), [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); diff --git a/crates/musyx/src/screens/browse.rs b/crates/musyx/src/screens/browse.rs index a509391..37394b9 100644 --- a/crates/musyx/src/screens/browse.rs +++ b/crates/musyx/src/screens/browse.rs @@ -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())), }) }), )); diff --git a/crates/musyx/src/screens/collection.rs b/crates/musyx/src/screens/collection.rs index cab04e7..e1f8468 100644 --- a/crates/musyx/src/screens/collection.rs +++ b/crates/musyx/src/screens/collection.rs @@ -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), diff --git a/crates/musyx/src/shortcuts.rs b/crates/musyx/src/shortcuts.rs index e9c41ea..ddcb6b9 100644 --- a/crates/musyx/src/shortcuts.rs +++ b/crates/musyx/src/shortcuts.rs @@ -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 { @@ -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] diff --git a/crates/musyx/src/snapshot.rs b/crates/musyx/src/snapshot.rs index 86598e6..722e101 100644 --- a/crates/musyx/src/snapshot.rs +++ b/crates/musyx/src/snapshot.rs @@ -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, /// `MUSYX_SNAPSHOT_DELAY` in ms before capturing (default 1500; live runs need longer). pub delay: Duration, + pub menu: Option, + 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 { 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 { + 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 { + 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(self) -> Task { Task::future(tokio::time::sleep(self.delay)) diff --git a/crates/musyx/src/ui/icons.rs b/crates/musyx/src/ui/icons.rs index bff9d03..f91c69d 100644 --- a/crates/musyx/src/ui/icons.rs +++ b/crates/musyx/src/ui/icons.rs @@ -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 { diff --git a/crates/musyx/src/widgets/anchor.rs b/crates/musyx/src/widgets/anchor.rs new file mode 100644 index 0000000..85e30c9 --- /dev/null +++ b/crates/musyx/src/widgets/anchor.rs @@ -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 Message + 'a>>, + on_press: Option Message + 'a>>, +} + +pub fn anchor<'a, Message>(content: impl Into>) -> 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 Widget for Anchor<'_, Message> { + fn tag(&self) -> tree::Tag { + tree::Tag::of::() + } + + fn state(&self) -> tree::State { + tree::State::new(State::default()) + } + + fn children(&self) -> Vec { + vec![Tree::new(&self.content)] + } + + fn diff(&self, tree: &mut Tree) { + tree.diff_children(std::slice::from_ref(&self.content)); + } + + fn size(&self) -> Size { + 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::().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> { + tree.state.downcast_mut::().offset = translation; + self.content.as_widget_mut().overlay(&mut tree.children[0], layout, renderer, viewport, translation) + } +} + +impl<'a, Message: 'a> From> 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 = ui.into_messages().collect(); + assert_eq!(messages, [Point::new(100.0, 130.0)]); + } +} diff --git a/crates/musyx/src/widgets/card.rs b/crates/musyx/src/widgets/card.rs index ee37311..4ae83bf 100644 --- a/crates/musyx/src/widgets/card.rs +++ b/crates/musyx/src/widgets/card.rs @@ -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, } 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(t: &'static Tokens, covers: &Covers, card: Card, action: Option 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. diff --git a/crates/musyx/src/widgets/drawer.rs b/crates/musyx/src/widgets/drawer.rs index 9086568..1e1f5d7 100644 --- a/crates/musyx/src/widgets/drawer.rs +++ b/crates/musyx/src/widgets/drawer.rs @@ -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, 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| { - button( + let item = |track: &Track, now: bool, msg: Option, 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, 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( diff --git a/crates/musyx/src/widgets/menu.rs b/crates/musyx/src/widgets/menu.rs new file mode 100644 index 0000000..480182b --- /dev/null +++ b/crates/musyx/src/widgets/menu.rs @@ -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, + /// The "Add to playlist" list is showing; the index is its highlighted row. + pub sub: Option>, +} + +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), + 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, 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> { + 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> { + 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 { + 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) -> Vec { + 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 { + 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]) -> impl Iterator { + groups.iter().flatten() +} + +/// The next entry in `step` direction that can be picked, wrapping around. +pub fn step(entries: &[&Entry], from: Option, down: bool) -> Option { + 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]) -> 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], 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> = 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]) -> Vec> { + 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> { + 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 = (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); + } +} diff --git a/crates/musyx/src/widgets/mod.rs b/crates/musyx/src/widgets/mod.rs index fa2d459..3bfc3ce 100644 --- a/crates/musyx/src/widgets/mod.rs +++ b/crates/musyx/src/widgets/mod.rs @@ -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; diff --git a/crates/musyx/src/widgets/player_bar.rs b/crates/musyx/src/widgets/player_bar.rs index d126be6..695c88e 100644 --- a/crates/musyx/src/widgets/player_bar.rs +++ b/crates/musyx/src/widgets/player_bar.rs @@ -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 }, diff --git a/crates/musyx/src/widgets/sheet.rs b/crates/musyx/src/widgets/sheet.rs index b075b98..b11959b 100644 --- a/crates/musyx/src/widgets/sheet.rs +++ b/crates/musyx/src/widgets/sheet.rs @@ -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 }, 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> = 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> = 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, conten .into() } -fn item<'a>(t: &'static Tokens, glyph: Icon, label: &str, msg: Option) -> 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) -> 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 { - 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 = 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:?}"); - } - } -} diff --git a/crates/musyx/src/widgets/track_list.rs b/crates/musyx/src/widgets/track_list.rs index 74b2225..f820c78 100644 --- a/crates/musyx/src/widgets/track_list.rs +++ b/crates/musyx/src/widgets/track_list.rs @@ -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(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, lang: crate::i18n::Lang, + menu: Option, + /// `(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>, playlist: Option, ) -> 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"); + } +} diff --git a/crates/musyx/src/widgets/track_row.rs b/crates/musyx/src/widgets/track_row.rs index 543bba4..700f7cb 100644 --- a/crates/musyx/src/widgets/track_row.rs +++ b/crates/musyx/src/widgets/track_row.rs @@ -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, + /// While a row is being dragged: the pointer reached this one. + pub on_drag_over: Option, } /// 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)); } From 9cbda56abc36bd06989fb6510d12b05d07d68089 Mon Sep 17 00:00:00 2001 From: Yuriy Panov Date: Sun, 18 Oct 2026 20:05:41 +0600 Subject: [PATCH 3/3] docs: describe the design system as built Rewrite DESIGN.md in the standard eight-section format around "The Late-Night Tape Deck": the same tokens, components as they ship (context menu, drag reorder, shortcuts), named rules, known contrast and token debt, and a History section listing what the build dropped from the mockup. The mockup is now marked historical; the build is the authority. Add the Impeccable sidecar (.impeccable/design.json) and the first critique snapshot. Co-Authored-By: Claude Opus 5.5 --- .../2026-10-18T09-24-01Z__crates-musyx-src.md | 163 ++++++ .impeccable/design.json | 487 +++++++++++++++++ DESIGN.md | 510 ++++++++++++++++-- README.md | 4 +- design/mockup.html | 2 + 5 files changed, 1116 insertions(+), 50 deletions(-) create mode 100644 .impeccable/critique/2026-10-18T09-24-01Z__crates-musyx-src.md create mode 100644 .impeccable/design.json diff --git a/.impeccable/critique/2026-10-18T09-24-01Z__crates-musyx-src.md b/.impeccable/critique/2026-10-18T09-24-01Z__crates-musyx-src.md new file mode 100644 index 0000000..e353a9c --- /dev/null +++ b/.impeccable/critique/2026-10-18T09-24-01Z__crates-musyx-src.md @@ -0,0 +1,163 @@ +--- +target: whole app (crates/musyx/src) +total_score: 22 +max_score: 40 +na_heuristics: +p0_count: 1 +p1_count: 2 +target_identity: "file:/Users/yp/Projects/musyx/crates/musyx/src" +timestamp: 2026-10-18T09-24-01Z +slug: crates-musyx-src +--- +Method: dual-agent (A: design review · B: detector + pixel/source evidence). The app is native iced, so the web detector ran only on design/mockup.html. B replaced the browser overlay with contrast measured from snapshot pixels, hit-target measurements and static source scans. The evidence is 21 snapshots: dark/English and light/Russian, sample data, no network. + +## Design Health Score + +| # | Heuristic | Score | Key Issue | +|---|-----------|-------|-----------| +| 1 | Visibility of System Status | 2 | Every loading state is a grey sentence. Buffering is drawn as a half-alpha pause glyph that renders as a normal one, because the SVG tint drops alpha. The playing row can't show paused. | +| 2 | Match System / Real World | 3 | Copy and Russian plurals are strong. "Tap the heart" is phone wording in a desktop app. Up to three "Go to artist" items appear without names. | +| 3 | User Control and Freedom | 2 | Dislike can't be undone, and nothing lists disliked tracks. One click replaces the queue. The queue is read-only. Esc closes nothing. | +| 4 | Consistency and Standards | 2 | The track menu opens as a centred modal, with no right-click. Space doesn't toggle playback. Play sits in a different place on list screens than on detail screens. | +| 5 | Error Prevention | 2 | The one-click Dislike sits 12px from Like. It skips the track and silently unlikes it. | +| 6 | Recognition Rather Than Recall | 2 | 16 icon-only buttons have no tooltips. Chart is missing from the nav. | +| 7 | Flexibility and Efficiency | 1 | There are no in-app shortcuts, no multi-select, no filter on Liked tracks and no drag reordering. | +| 8 | Aesthetic and Minimalist Design | 3 | The design is quiet and coherent. The hero is repeated on Home and My Wave, and "more" shows on every row. | +| 9 | Error Recovery | 3 | Every failure names the next step and offers "Try again". Failures look the same as loading text. | +| 10 | Help and Documentation | 2 | The sign-in steps and quality explanations are good. There is no shortcut list or tuning hint, and "OAuth token" appears on the first screen. | +| **Total** | | **22/40** | **Acceptable** | + +## Design Specificity Verdict + +**LLM assessment:** The structure belongs to Yandex Music; the interaction layer could belong to any player. My Wave is the hero, mood, character and language tuning is built in, Dislike sits in the player bar, Plus status and 30-second previews are explained, and "Podcasts and books" mirrors Yandex's catalogue. Aubergine with a single amber, Unbounded and the dotted wordmark make a real identity, and it holds in both themes. But the shell is the standard Spotify layout: a 232px sidebar, pill search, a three-zone player bar and a numbered table with a clock icon over durations. The "tape-deck VU needle" behind the accent appears only in DESIGN.md: nothing in the app moves like a needle. The hero is 14 generic sine lines, identical on Home and My Wave, and they hold still until My Wave plays. The build also loses most of the mockup's character: the Tune button in the hero, display-face chart ranks, the card hover play, the animated equaliser on the playing row, and the live sign-in canvas. + +**Deterministic scan:** On design/mockup.html the detector found 10 low-contrast findings, all in the light palette. Nine are `#FFF7E6` on `#A86C05` at 4.1:1, which covers primary buttons and pressed segments. One is `#2E8A55` on white at 4.3:1 ("Plus subscription"). Both carry over to the iced app, and the second is worse there: the sidebar renders on `bg`, not `panel`, so "Подписка Плюс" measures 3.83:1 in pixels. The play-fab finding is mockup-only. The scan found no false positives for the native app. Beyond what the review saw, the measurements show: +- Disabled prev/next render at full `muted`, so the 0.45 alpha is lost. +- The seek rail is 1.13:1 against the player bar, so it is invisible when idle. +- Line borders on ghost buttons and chips are 1.3–1.5:1. +- The danger button is white on `like` at 2.79:1 in dark. +- 19 hardcoded colours sit outside theme.rs, including a non-token `#4A4458`. +- 16 font sizes and 52 spacing values are off the scale. + +theme.rs matches DESIGN.md exactly, 10 of 10 tokens. + +**Visual overlays:** None. iced exposes no DOM or CDP, so nothing was injected. + +## Overall Impression + +Musyx is a well-built, disciplined player: the tokens are exact, the copy is excellent in both languages, and the OS integration is real. The weak spot is how the app reacts to input. It ignores the keyboard, routine track actions open a modal, the most destructive one-click action has no undo, and several state changes never reach the screen. The biggest opportunity is to make it behave like a desktop app: keys, right-click, focus, undo. After that, give the VU-needle idea a real form so the identity lives in the controls and not just in the colours. + +## What's Working + +1. **Token discipline and dark-mode legibility.** Every sampled pixel matched its token. Every dark-mode text pair passes: muted on bg is 6.5:1, accent_ink on accent 8.7:1, accent on bg 9.1:1. The chip, tab and ghost styles are shared by Settings, My Wave and Search. +2. **Copy and localisation craft.** + - 253 keys, none missing in Russian. + - Correct Russian plurals, genitive months and "4,1 млн"-style numbers. + - Quality options state their cost. + - Every error names the next step. "You're still signed in" on the offline screen is exactly the reassurance that moment needs. +3. **Native integration.** + - Media keys and Now Playing through souvlaki. + - A macOS menu-bar mini player that appears only when the window is minimised. + - Lazy track lists that don't rebuild on every position tick. + +## Priority Issues + +**[P0] There is no keyboard path.** +- *Why:* app.rs:265 subscribes to theme, audio, media keys and timers, and nothing else. Buttons have no focused style, so Tab reaches only text inputs. Space, Cmd/Ctrl+F and Esc do nothing. `topbar::SEARCH_ID` is defined but never focused, even when you click Search. People keep a player open for hours, and a keyboard-only user can't use it at all. +- *Fix:* add an `iced::event::listen_with` keyboard subscription, ignored while a text input has focus: + - Space: play/pause. + - Cmd/Ctrl+F or `/`: focus search. + - Esc: close the sheet, then the drawer, then suggestions. + - Cmd+←/→: previous/next track. + - Cmd+↑/↓: volume. + - Cmd+L: like. + - Cmd+[: back. + - Cmd+1–5: nav items. + + Also focus the field on `Navigate(Route::Search)`, and add a focus ring through a focusable wrapper. +- *Suggested command:* /impeccable harden + +**[P1] The track menu is a modal centred on the window.** +- *Why:* sheet.rs:40 dims the whole window for routine actions. It lists 8–13 items with one divider, repeats "Go to artist" without names, and stays open after an action. Reordering a playlist means reopening it once per position. There is no right-click, which breaks the most basic desktop convention for a list. +- *Fix:* + - Open the menu from `mouse_area::on_right_press` on rows, or from "…", as a popover at the cursor. + - Use three groups: (Play next, Add to queue) · (Like, Add to playlist…, Don't recommend) · (Go to album, Go to {artist name}). + - Close the menu on action and confirm with a toast. + - Bring back the mockup's grip column for drag reordering. +- *Suggested command:* /impeccable shape + +**[P1] Dislike fires on one click, with hidden side effects and no recovery.** +- *Why:* the unlabelled ban icon sits 12px from the heart (player_bar.rs:86). One click skips the track, removes it from Liked tracks (edit.rs:76) and shows a toast with no undo. The Disliked tab from the mockup was dropped, so nothing in the app lists dislikes. A mis-click silently loses a liked track. +- *Fix:* + - Add Undo to the toast: re-like the track and send `DislikeTrack(track, false)`. + - Add a tooltip. + - Space Dislike away from Like. + - Restore the Disliked tab in collection.rs. +- *Suggested command:* /impeccable harden + +**[P2] The light theme and the boundaries fail contrast.** The detector and the pixels agree. +- *Why:* light accent_ink on accent is 4.09:1, which covers every primary button and selected chip. Light accent as text is 3.89:1: the playing row, the current track in the drawer, the Lossless badge. ok text is 3.83:1. In both themes, the seek and volume rails are about 1.1–1.2:1 and the line borders 1.3–1.5:1. The dark danger button is 2.79:1. Genre tiles put white text on colours from the API without checking contrast. In light, the selected nav fill is about 1.1:1 against bg, so only the amber icon marks the current page. +- *Fix:* + - Light accent `#8F5B00` (5.4:1 with ink, 5.1:1 on bg). + - Light ok `#25744A`. + - Rail track at `line` or brighter. + - A dark-ink label on the danger button. + - A luminance-based text colour or a scrim on genre tiles. + - A 2–3px amber bar on the active nav row. + - Update DESIGN.md alongside theme.rs. +- *Suggested command:* /impeccable colorize (palette correction), then /impeccable audit + +**[P2] Several states never reach the screen.** +- *Why:* `svg::Style::color` ignores alpha. B measured disabled prev/next at full `muted`. The same code path should make the Loading disc look identical to Playing (player_bar.rs:116), and the idle row heart look like an enabled control (track_row.rs:97); these two weren't captured in snapshots. The playing row uses a static glyph, so pause doesn't show. Errors use the loading paragraph style. The album column is cut mid-glyph with no ellipsis ("Солнц", "любов" with the drawer open). On light/RU Home, the two-line subtitle pushes the hero title 14pt into the wave lines. +- *Fix:* + - Pass fully opaque tints that are pre-mixed with the surface instead of using `scale_alpha` on icons. + - Show buffering as a spinner or pulsing ring on the disc. + - Make the playing indicator an animated meter that freezes when paused. + - Give errors an icon and a `like` lead line. + - Add ellipsis truncation or a fade mask for the album column. + - Anchor the wave band to the hero's top, or add a scrim under the title. +- *Suggested command:* /impeccable polish + +## Persona Red Flags + +**Alex (power user)** +- No shortcuts. +- A single click plays and replaces the queue, so there is no selection or batch "Add to playlist". +- No filter or sort on a Liked list of 1,000+ tracks. +- The queue can't be edited: no remove, reorder or clear. +- Reordering a playlist takes one modal per position. +- Chart is reachable only through Home's "Show all". +- The window title doesn't show the track that is playing. + +**Sam (keyboard-only, low vision)** +- Tab reaches no button, and there is no focus indicator. +- 16 icon buttons have no tooltip. iced 0.14 exposes no accessibility tree, so screen readers get nothing; the README should say so. +- Light-theme failures at 3.8–4.1:1. +- The paused and playing states differ only by colour and a static glyph. +- Text sizes are 11.5–12.5pt for the quality badge, the plan line and the player times. + +**Jordan (first-timer)** +- Sign-in adds a "Get sign-in code" click before any code appears. +- The QR area is a white card with a grey lock, which reads as locked or broken. +- "OAuth token" appears on the first screen. +- Clicking Search opens a page titled "Browse" with no cursor in the field. +- The microphone icon means lyrics, and nothing labels it. +- First Home is a stack of "Loading…" lines next to a disabled grey play disc that could have offered "Play My Wave". + +## Minor Observations + +- **Detail pages:** Play and Shuffle sit in a separate right-aligned row with an empty left half (detail.rs:181). On your own playlist, Delete sits next to the title while Play is lower down. Put Play, Shuffle, heart and "…" together in the header, and move Rename, visibility and Delete into "…". +- **Sidebar:** DESIGN.md says it uses the `panel` fill, but it renders on `bg` (app.rs:1037). The playlist list mixes owned and liked playlists without a divider. +- **"More" on rows:** DESIGN.md says it appears on hover, but it is always visible. +- **Volume fill:** it uses `fg`, which makes it the brightest mark in the player bar and pulls attention from the amber progress bar. +- **Scroll position:** the page scrollable has no id and is never reset, so new routes may open at the old offset and Back doesn't restore position. This was not confirmed at runtime. +- **"Show all":** the links use the tab style, which reads as a tab rather than a link. +- **Collection tabs:** the counts pop in one at a time. +- **Off-scale values:** about 16 font sizes (13.5 ×6, 12, 15, 17, 11.5, 9) and 52 spacing values (16 ×9, 9 ×8, 24 ×7) are off the DESIGN.md scale. Either fold them in or record them. +- **Podcasts:** the mockup's "Continue listening" is gone, so there is no resume point for podcasts or audiobooks. + +## Questions to Consider + +- If the accent is a VU needle, why does nothing move like one? Should the seek or volume control become the needle, with a sweep and settle on each track change, and the generic sine lines retired? +- Home and My Wave show the same hero. Once My Wave is playing, should Home give that space to "Continue" content, or should My Wave simply be the home screen? +- What would Musyx feel like with desktop selection rules: click selects, double-click or Enter plays, Space toggles, right-click opens the menu? Does a one-click Dislike belong in the player bar during a session that lasts hours? diff --git a/.impeccable/design.json b/.impeccable/design.json new file mode 100644 index 0000000..74c5328 --- /dev/null +++ b/.impeccable/design.json @@ -0,0 +1,487 @@ +{ + "schemaVersion": 2, + "generatedAt": "2026-10-18T13:49:28+00:00", + "title": "Design System: Musyx", + "extensions": { + "colorMeta": { + "bg": { + "role": "neutral", + "displayName": "Aubergine Graphite", + "canonical": "#1C1A22", + "tonalRamp": [ + "#24212B", + "#3F3A4C", + "#5A546D", + "#756D8E", + "#948DA8", + "#B3AEC1", + "#D2D0DB", + "#F1F1F4" + ] + }, + "panel": { + "role": "neutral", + "displayName": "Casing Panel", + "canonical": "#23202B", + "tonalRamp": [ + "#24212C", + "#3F3A4D", + "#5A526F", + "#756B90", + "#948CAA", + "#B3AEC2", + "#D2CFDB", + "#F1F0F4" + ] + }, + "raised": { + "role": "neutral", + "displayName": "Raised Plate", + "canonical": "#2D2937", + "tonalRamp": [ + "#24212C", + "#3F3A4D", + "#5B526F", + "#766B90", + "#958CA9", + "#B4AEC2", + "#D2CFDB", + "#F1F0F4" + ] + }, + "line": { + "role": "neutral", + "displayName": "Seam", + "canonical": "#3A3546", + "tonalRamp": [ + "#24212C", + "#403A4D", + "#5B536E", + "#776C8F", + "#958DA9", + "#B4AEC2", + "#D3CFDB", + "#F2F0F4" + ] + }, + "fg": { + "role": "neutral", + "displayName": "Label White", + "canonical": "#EEEAF3", + "tonalRamp": [ + "#251C31", + "#413156", + "#5E467B", + "#7A5BA0", + "#9880B6", + "#B6A5CB", + "#D4CAE1", + "#F2EFF6" + ] + }, + "muted": { + "role": "neutral", + "displayName": "Faded Label", + "canonical": "#A39CB0", + "tonalRamp": [ + "#25222B", + "#413C4B", + "#5D566B", + "#79708C", + "#9790A6", + "#B6B0C0", + "#D4D0DA", + "#F2F1F4" + ] + }, + "accent": { + "role": "primary", + "displayName": "Indicator Amber", + "canonical": "#F0B23E", + "tonalRamp": [ + "#473006", + "#7D550A", + "#B37A0E", + "#E99E12", + "#F1B545", + "#F5CA7B", + "#F9E0B1", + "#FDF6E7" + ] + }, + "accent-ink": { + "role": "primary", + "displayName": "Amber Ink", + "canonical": "#2A1D04", + "tonalRamp": [ + "#463007", + "#7B550C", + "#B07A11", + "#E69E16", + "#EEB548", + "#F3CA7D", + "#F8E0B3", + "#FDF6E8" + ] + }, + "like": { + "role": "secondary", + "displayName": "Heart Rose", + "canonical": "#F27286", + "tonalRamp": [ + "#460610", + "#7B0B1D", + "#B11029", + "#E61536", + "#EE4862", + "#F37D8F", + "#F8B2BD", + "#FDE8EB" + ] + }, + "ok": { + "role": "secondary", + "displayName": "Signal Green", + "canonical": "#7FCB9B", + "tonalRamp": [ + "#163622", + "#27603C", + "#388956", + "#49B370", + "#71C590", + "#9AD6B0", + "#C3E7D0", + "#EDF8F1" + ] + }, + "bg-light": { + "role": "neutral", + "displayName": "Aubergine Graphite (light)", + "canonical": "#F3F1F6", + "tonalRamp": [ + "#251E2F", + "#403552", + "#5C4C76", + "#786299", + "#9685B1", + "#B5A9C7", + "#D3CCDE", + "#F2EFF5" + ] + }, + "panel-light": { + "role": "neutral", + "displayName": "Casing Panel (light)", + "canonical": "#FFFFFF", + "tonalRamp": [ + "#262626", + "#434343", + "#616161", + "#7E7E7E", + "#9B9B9B", + "#B8B8B8", + "#D5D5D5", + "#F2F2F2" + ] + }, + "raised-light": { + "role": "neutral", + "displayName": "Raised Plate (light)", + "canonical": "#EAE6F0", + "tonalRamp": [ + "#241D30", + "#403354", + "#5C4879", + "#775E9D", + "#9682B4", + "#B4A6CA", + "#D3CBE0", + "#F2EFF5" + ] + }, + "line-light": { + "role": "neutral", + "displayName": "Seam (light)", + "canonical": "#DCD6E4", + "tonalRamp": [ + "#251E2E", + "#413651", + "#5E4D74", + "#7A6498", + "#9886AF", + "#B6A9C7", + "#D4CCDE", + "#F2F0F5" + ] + }, + "fg-light": { + "role": "neutral", + "displayName": "Label White (light)", + "canonical": "#1F1B27", + "tonalRamp": [ + "#241F2D", + "#3F3750", + "#5B4F72", + "#766795", + "#9589AD", + "#B4ABC5", + "#D3CDDD", + "#F1F0F5" + ] + }, + "muted-light": { + "role": "neutral", + "displayName": "Faded Label (light)", + "canonical": "#686178", + "tonalRamp": [ + "#25222A", + "#413C4B", + "#5D566B", + "#78708B", + "#9790A5", + "#B5B0BF", + "#D3D1DA", + "#F2F1F4" + ] + }, + "accent-light": { + "role": "primary", + "displayName": "Indicator Amber (light)", + "canonical": "#A86C05", + "tonalRamp": [ + "#4A3002", + "#835404", + "#BB7906", + "#F49D07", + "#F9B43C", + "#FBCA75", + "#FDE0AE", + "#FEF5E6" + ] + }, + "accent-ink-light": { + "role": "primary", + "displayName": "Amber Ink (light)", + "canonical": "#FFF7E6", + "tonalRamp": [ + "#4C3400", + "#875C00", + "#C18300", + "#FBAB00", + "#FFBF37", + "#FFD271", + "#FFE4AB", + "#FFF7E6" + ] + }, + "like-light": { + "role": "secondary", + "displayName": "Heart Rose (light)", + "canonical": "#D2405A", + "tonalRamp": [ + "#3E0F17", + "#6D1A29", + "#9C253A", + "#CB304C", + "#D95D73", + "#E48C9C", + "#EFBBC4", + "#FAEAED" + ] + }, + "ok-light": { + "role": "secondary", + "displayName": "Signal Green (light)", + "canonical": "#2E8A55", + "tonalRamp": [ + "#133923", + "#22653E", + "#309159", + "#3FBD74", + "#69CD93", + "#94DBB3", + "#C0EAD2", + "#ECF9F1" + ] + } + }, + "typographyMeta": { + "display": { + "displayName": "Display", + "purpose": "My Wave hero, detail titles, sign-in headline, screen titles (46/40/34/30)." + }, + "wordmark": { + "displayName": "Wordmark", + "purpose": "musyx plus the amber dot." + }, + "section": { + "displayName": "Section", + "purpose": "Section headings, sheet and settings card titles." + }, + "body": { + "displayName": "Body", + "purpose": "Rows, menu entries, buttons, paragraphs." + }, + "meta": { + "displayName": "Meta", + "purpose": "Artist lines, album column, durations, help text." + }, + "small": { + "displayName": "Small", + "purpose": "Column headers, sidebar labels, player times." + } + }, + "shadows": [ + { + "name": "primary-lift", + "value": "0 4px 12px rgba(0,0,0,0.18)", + "purpose": "Primary pill buttons only." + }, + { + "name": "menu-float", + "value": "0 10px 28px rgba(0,0,0,0.30)", + "purpose": "Context menu and its submenu." + }, + { + "name": "toast-float", + "value": "0 6px 18px rgba(0,0,0,0.30)", + "purpose": "The status pill above the player bar." + }, + { + "name": "dialog-float", + "value": "0 18px 50px rgba(0,0,0,0.35)", + "purpose": "Dialogs, over a 45% black backdrop." + } + ], + "motion": [], + "breakpoints": [] + }, + "components": [ + { + "name": "Primary Button", + "kind": "button", + "refersTo": "button-primary", + "description": "The one amber action on a screen: Play, Create, Rename.", + "html": "", + "css": ".ds-btn-primary { display:inline-flex; align-items:center; gap:8px; font-family: Onest, system-ui, sans-serif; font-weight:600; font-size:14px; background:#F0B23E; color:#2A1D04; border:none; border-radius:999px; padding:10px 18px; box-shadow:0 4px 12px rgba(0,0,0,0.18); cursor:pointer; } .ds-btn-primary:hover { background:#F1BC59; } .ds-btn-primary:active { background:#D59E3B; } .ds-btn-primary:focus-visible { outline:2px solid #EEEAF3; outline-offset:2px; }" + }, + { + "name": "Ghost Button", + "kind": "button", + "refersTo": "button-ghost", + "description": "Secondary action beside Primary, e.g. Shuffle, Cancel.", + "html": "", + "css": ".ds-btn-ghost { font-family: Onest, system-ui, sans-serif; font-weight:500; font-size:14px; background:transparent; color:#EEEAF3; border:1px solid #3A3546; border-radius:999px; padding:10px 18px; cursor:pointer; } .ds-btn-ghost:hover { background:#2D2937; } .ds-btn-ghost:focus-visible { outline:2px solid #F0B23E; outline-offset:2px; }" + }, + { + "name": "Chip", + "kind": "chip", + "refersTo": "chip", + "description": "Single-choice settings: quality, appearance, language, wave tuning.", + "html": "
", + "css": ".ds-chips { display:flex; gap:6px; } .ds-chip { font-family: Onest, system-ui, sans-serif; font-weight:500; font-size:13.5px; background:transparent; color:#EEEAF3; border:1px solid #3A3546; border-radius:999px; padding:7px 13px; cursor:pointer; } .ds-chip:hover { background:#2D2937; } .ds-chip-on, .ds-chip-on:hover { background:#F0B23E; border-color:#F0B23E; color:#2A1D04; cursor:default; }" + }, + { + "name": "Search Field", + "kind": "input", + "refersTo": "search-field", + "description": "The top bar's pill search; amber border on focus.", + "html": "", + "css": ".ds-search { font-family: Onest, system-ui, sans-serif; font-size:14px; width:420px; max-width:100%; background:#23202B; color:#EEEAF3; border:1px solid #3A3546; border-radius:999px; padding:10px 16px; outline:none; } .ds-search::placeholder { color:#A39CB0; } .ds-search:focus { border-color:#F0B23E; } .ds-search::selection { background:rgba(240,178,62,0.35); }" + }, + { + "name": "Sidebar Nav Item", + "kind": "nav", + "refersTo": "nav-item-active", + "description": "Sidebar navigation; the active item is raised with an amber icon.", + "html": "", + "css": ".ds-nav { display:flex; flex-direction:column; gap:2px; width:208px; } .ds-nav-item { display:flex; align-items:center; gap:12px; font-family: Onest, system-ui, sans-serif; font-weight:500; font-size:14px; color:#A39CB0; padding:9px 10px; border-radius:8px; cursor:pointer; } .ds-nav-item:hover { background:#2D2937; color:#EEEAF3; } .ds-nav-on { background:#2D2937; color:#EEEAF3; } .ds-nav-on svg { color:#F0B23E; }" + }, + { + "name": "Track Row", + "kind": "custom", + "refersTo": "track-row", + "description": "52pt list row; click plays, right-click or … opens the menu; lit while its menu is open.", + "html": "
2Хочешь?ЗемфираПрости меня моя любовь3:45
", + "css": ".ds-row { display:flex; align-items:center; gap:12px; height:52px; padding:0 10px; border-radius:8px; font-family: Onest, system-ui, sans-serif; color:#EEEAF3; cursor:pointer; } .ds-row:hover { background:#2D2937; } .ds-row-n { width:36px; text-align:center; color:#A39CB0; font-size:13px; } .ds-row-cover { width:40px; height:40px; border-radius:6px; background:linear-gradient(135deg,#5BD08A,#2E5B3A 55%,#1C2A1F); } .ds-row-text { display:flex; flex-direction:column; flex:22; min-width:0; } .ds-row-text b { font-weight:500; font-size:14px; } .ds-row-text small, .ds-row-album { font-size:13px; color:#A39CB0; } .ds-row-album { flex:14; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } .ds-row-heart { color:#F27286; display:flex; padding:8px; } .ds-row-heart svg { fill:currentColor; } .ds-row-time { width:52px; text-align:right; font-size:13px; color:#A39CB0; } .ds-row-more { color:#A39CB0; display:flex; padding:8px; border-radius:8px; } .ds-row-more:hover { background:#3A3546; color:#EEEAF3; }" + }, + { + "name": "Context Menu", + "kind": "custom", + "refersTo": "context-menu", + "description": "Opens at the pointer or under …; grouped entries, no backdrop, every action closes it.", + "html": "


", + "css": ".ds-menu { width:280px; box-sizing:border-box; padding:6px; background:#23202B; border:1px solid #3A3546; border-radius:10px; box-shadow:0 10px 28px rgba(0,0,0,0.30); display:flex; flex-direction:column; } .ds-mi { display:flex; align-items:center; gap:12px; height:32px; padding:0 10px; font-family: Onest, system-ui, sans-serif; font-size:14px; color:#EEEAF3; background:none; border:none; border-radius:8px; text-align:left; cursor:pointer; } .ds-mi svg { color:#A39CB0; flex:none; } .ds-mi:hover, .ds-mi-on { background:#2D2937; } .ds-mi-danger, .ds-mi-danger svg { color:#F27286; } .ds-mchev { margin-left:auto; display:flex; } .ds-msep { border:none; height:1px; background:#3A3546; margin:4px; }" + }, + { + "name": "Cover Card", + "kind": "card", + "refersTo": "card", + "description": "168pt cover, title and one muted line; right-click for Play/Shuffle/collection.", + "html": "
Группа кровиКино · 1988
", + "css": ".ds-card { width:168px; padding:6px; border-radius:8px; display:flex; flex-direction:column; gap:2px; font-family: Onest, system-ui, sans-serif; color:#EEEAF3; cursor:pointer; } .ds-card:hover { background:#2D2937; } .ds-card-cover { width:168px; height:168px; border-radius:10px; margin-bottom:7px; background:linear-gradient(135deg,#E3C24F,#2E7A3A 55%,#18233A); } .ds-card b { font-weight:500; font-size:14px; } .ds-card small { font-size:13px; color:#A39CB0; }" + }, + { + "name": "Toast", + "kind": "custom", + "refersTo": "toast", + "description": "Confirms every action from menus, likes and edits.", + "html": "
Added to Liked tracks
", + "css": ".ds-toast { display:inline-block; font-family: Onest, system-ui, sans-serif; font-weight:500; font-size:14px; background:#EEEAF3; color:#1C1A22; border-radius:999px; padding:10px 18px; box-shadow:0 6px 18px rgba(0,0,0,0.30); }" + } + ], + "narrative": { + "northStar": "The Late-Night Tape Deck", + "overview": "Musyx looks like a piece of dark hardware playing in a dim room late at night. The casing is aubergine graphite. The controls are quiet and almost the same colour as the casing. Exactly one thing glows: an amber lamp that marks what is playing, what you chose and what you can press next. People leave the window open for hours, so nothing moves or competes for attention unless the music asks for it.\n\nThe layout is the familiar desktop player shell: sidebar, content, player bar, and an optional drawer. Its brand shows in the details, not the structure. There is one display face for titles and one plain face for everything else. Depth comes from three close tonal steps, not from shadows. Interactions follow desktop rules: right-click menus at the pointer, keyboard shortcuts, and drag to reorder. The My Wave hero is the one place that animates. Its amber lines drift only while My Wave is actually playing.\n\nThe theme is dark first. The light theme follows the system setting, or the choice in Settings, and keeps every role.", + "keyCharacteristics": [ + "One amber accent on an aubergine ground. Amber means \"this one, now\".", + "Three tonal surfaces (bg, panel, raised) do the layering. Shadows appear only on things that float.", + "Unbounded for titles, Onest for everything else. Icons are Lucide at 18pt.", + "Dense, scannable lists with 52pt track rows.", + "Desktop-native interaction: context menus, shortcuts, drag reorder, media keys, and a macOS menu-bar mini player." + ], + "rules": [ + { + "name": "The One Lit Lamp Rule", + "body": "Amber marks state (playing, selected, primary, focused) and nothing else. Never use it to decorate. If a screen has two amber things, they must be the same \"now\".", + "section": "colors" + }, + { + "name": "The Light-Theme Contrast Rule", + "body": "In the light theme, amber text on `bg` measures 3.9:1 and `ok` text measures 3.8:1. Both are below AA for body text. Until the light accent is darkened, keep amber text in light mode to titles of 14pt medium or larger, and never use it for small meta text.", + "section": "colors" + }, + { + "name": "The Two Faces Rule", + "body": "Unbounded appears only at display sizes and in the wordmark. Everything interactive is Onest.", + "section": "typography" + }, + { + "name": "The Float-Only Shadow Rule", + "body": "If it isn't floating above the content (menu, toast, dialog) and it isn't the primary button, it has no shadow.", + "section": "elevation" + }, + { + "name": "The No-Dim Rule", + "body": "Only dialogs dim the window. Menus, the drawer and toasts never do.", + "section": "elevation" + } + ], + "dos": [ + "**Do** take every colour from `Tokens` in `theme.rs`, and change DESIGN.md in the same commit.", + "**Do** use Lucide 0.460 icons at 18pt, tinted with the colour of the text they sit beside. New icons go in `assets/icons` with the Lucide license header.", + "**Do** put routine actions on an item in its context menu, and confirm them with a toast.", + "**Do** give every new action a keyboard path, and add it to the Settings shortcut list.", + "**Do** translate every string through `tr`/`trf` with a Russian entry in `i18n/ru.rs`. The test suite fails otherwise.", + "**Do** test new screens in both themes and both languages with the snapshot tool (`MUSYX_SNAPSHOT_*`, see `snapshot.rs`). Russian labels run about 30% longer." + ], + "donts": [ + "**Don't** use amber for decoration, borders or illustrations other than the My Wave hero.", + "**Don't** open a dialog for anything that doesn't need typing or a destructive confirmation.", + "**Don't** dim the window for menus, the drawer or toasts.", + "**Don't** fade icons with `scale_alpha`. iced's SVG tint drops alpha, so a faded icon renders at full strength. Disabled previous/next already do this. Pre-mix the colour with the surface.", + "**Don't** add hardcoded colours outside `theme.rs`. About 19 still exist (sign-in, genre tiles, dialogs) and should move into tokens when touched.", + "**Don't** add shadows to resting surfaces. Depth comes from `bg` → `panel` → `raised`." + ] + } +} diff --git a/DESIGN.md b/DESIGN.md index f6f8b18..91d2157 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1,63 +1,475 @@ -# Musyx design system +--- +name: Musyx +description: A dark-first desktop player for Yandex Music, built with iced. +colors: + bg: "#1C1A22" + panel: "#23202B" + raised: "#2D2937" + line: "#3A3546" + fg: "#EEEAF3" + muted: "#A39CB0" + accent: "#F0B23E" + accent-ink: "#2A1D04" + like: "#F27286" + ok: "#7FCB9B" + bg-light: "#F3F1F6" + panel-light: "#FFFFFF" + raised-light: "#EAE6F0" + line-light: "#DCD6E4" + fg-light: "#1F1B27" + muted-light: "#686178" + accent-light: "#A86C05" + accent-ink-light: "#FFF7E6" + like-light: "#D2405A" + ok-light: "#2E8A55" +typography: + display: + fontFamily: "Unbounded" + fontSize: "46px" + fontWeight: 600 + display-l: + fontFamily: "Unbounded" + fontSize: "40px" + fontWeight: 600 + display-m: + fontFamily: "Unbounded" + fontSize: "34px" + fontWeight: 600 + display-s: + fontFamily: "Unbounded" + fontSize: "30px" + fontWeight: 600 + wordmark: + fontFamily: "Unbounded" + fontSize: "20px" + fontWeight: 600 + section: + fontFamily: "Onest" + fontSize: "19px" + fontWeight: 600 + body: + fontFamily: "Onest" + fontSize: "14px" + fontWeight: 400 + lineHeight: 1.45 + body-medium: + fontFamily: "Onest" + fontSize: "14px" + fontWeight: 500 + meta: + fontFamily: "Onest" + fontSize: "13px" + fontWeight: 400 + small: + fontFamily: "Onest" + fontSize: "12.5px" + fontWeight: 400 +rounded: + small-cover: "6px" + control: "8px" + cover: "10px" + card: "14px" + hero: "16px" + pill: "999px" +spacing: + xs: "4px" + s: "8px" + m: "12px" + l: "18px" + xl: "22px" + gutter: "28px" + section: "34px" +components: + button-primary: + backgroundColor: "{colors.accent}" + textColor: "{colors.accent-ink}" + typography: "{typography.body-medium}" + rounded: "{rounded.pill}" + padding: "10px 18px" + button-ghost: + backgroundColor: "transparent" + textColor: "{colors.fg}" + rounded: "{rounded.pill}" + padding: "10px 18px" + button-ghost-hover: + backgroundColor: "{colors.raised}" + chip: + textColor: "{colors.fg}" + rounded: "{rounded.pill}" + padding: "7px 13px" + chip-selected: + backgroundColor: "{colors.accent}" + textColor: "{colors.accent-ink}" + icon-button: + textColor: "{colors.muted}" + rounded: "{rounded.control}" + size: "34px" + icon-button-hover: + backgroundColor: "{colors.raised}" + textColor: "{colors.fg}" + nav-item-active: + backgroundColor: "{colors.raised}" + textColor: "{colors.fg}" + rounded: "{rounded.control}" + search-field: + backgroundColor: "{colors.panel}" + textColor: "{colors.fg}" + rounded: "{rounded.pill}" + padding: "10px 16px" + width: "420px" + track-row: + textColor: "{colors.fg}" + rounded: "{rounded.control}" + height: "52px" + track-row-lit: + backgroundColor: "{colors.raised}" + context-menu: + backgroundColor: "{colors.panel}" + rounded: "{rounded.cover}" + padding: "6px" + width: "280px" + context-menu-item: + textColor: "{colors.fg}" + typography: "{typography.body}" + rounded: "{rounded.control}" + height: "32px" + card: + textColor: "{colors.fg}" + rounded: "{rounded.cover}" + width: "168px" + dialog: + backgroundColor: "{colors.panel}" + rounded: "{rounded.card}" + padding: "18px" + width: "380px" + toast: + backgroundColor: "{colors.fg}" + textColor: "{colors.bg}" + rounded: "{rounded.pill}" + padding: "10px 18px" + key-cap: + backgroundColor: "{colors.raised}" + textColor: "{colors.fg}" + typography: "{typography.meta}" + rounded: "{rounded.small-cover}" + padding: "2px 8px" +--- -The approved mockup is [`design/mockup.html`](design/mockup.html) (published at -https://claude.ai/artifact/2gmswtceJM61fcE2F5uYYM). This file records its tokens. They map -1:1 to [`crates/musyx/src/ui/theme.rs`](crates/musyx/src/ui/theme.rs), so change both together. +# Design System: Musyx -## Direction +The source of truth is the build. The tokens above map 1:1 to +[`crates/musyx/src/ui/theme.rs`](crates/musyx/src/ui/theme.rs), so change both together. Keys +without a suffix are the dark theme. The `-light` keys are the same roles in the light theme. +[`design/mockup.html`](design/mockup.html) is the original exploration (see [History](#history)). +It is no longer the authority. -The ground is aubergine graphite, with one amber accent taken from a tape deck's VU needle. -The app is dark-first, and the light theme follows the system setting. Everything stays quiet -except the My Wave hero, which is the one animated, accent-heavy surface. +## Overview -## Colour +**Creative North Star: "The Late-Night Tape Deck"** -| Token | Dark | Light | Used for | -|--------------|-----------|-----------|----------| -| `bg` | `#1C1A22` | `#F3F1F6` | Window and content background | -| `panel` | `#23202B` | `#FFFFFF` | Sidebar, player bar, drawer, cards that need separation | -| `raised` | `#2D2937` | `#EAE6F0` | Hover and selected rows, chip fills, progress track | -| `line` | `#3A3546` | `#DCD6E4` | 1px dividers and outlines | -| `fg` | `#EEEAF3` | `#1F1B27` | Primary text, the play/pause disc | -| `muted` | `#A39CB0` | `#686178` | Secondary text, idle icons | -| `accent` | `#F0B23E` | `#A86C05` | Current track, progress fill, primary buttons, active nav icon | -| `accent_ink` | `#2A1D04` | `#FFF7E6` | Text and icons on `accent` | -| `like` | `#F27286` | `#D2405A` | Filled heart, falling chart position | -| `ok` | `#7FCB9B` | `#2E8A55` | Subscription status, rising chart position | +Musyx looks like a piece of dark hardware playing in a dim room late at night. The casing is +aubergine graphite. The controls are quiet and almost the same colour as the casing. Exactly +one thing glows: an amber lamp that marks what is playing, what you chose and what you can +press next. People leave the window open for hours, so nothing moves or competes for attention +unless the music asks for it. -Covers that have no artwork yet get a placeholder made of two hues (`h1`, `h2`) derived from -the item id, painted as a diagonal gradient between them. +The layout is the familiar desktop player shell: sidebar, content, player bar, and an optional +drawer. Its brand shows in the details, not the structure. There is one display face for titles +and one plain face for everything else. Depth comes from three close tonal steps, not from +shadows. Interactions follow desktop rules: right-click menus at the pointer, keyboard shortcuts, +and drag to reorder. The My Wave hero is the one place that animates. Its amber lines drift only +while My Wave is actually playing. -## Type +The theme is dark first. The light theme follows the system setting, or the choice in Settings, +and keeps every role. -| Role | Face | Size / weight | Where | -|---------|----------------------|--------------------|-------| -| Display | Unbounded SemiBold | 46 / 40 / 34 / 30 | My Wave hero, detail page titles, sign-in headline, screen titles | -| Wordmark| Unbounded SemiBold | 20 | `musyx` + amber dot | -| Section | Onest SemiBold | 19 | Section headings ("Made for you") | -| Body | Onest Regular/Medium | 14 (rows 14, meta 13, small 12.5) | Everything else | +**Key Characteristics:** +- One amber accent on an aubergine ground. Amber means "this one, now". +- Three tonal surfaces (bg, panel, raised) do the layering. Shadows appear only on things that float. +- Unbounded for titles, Onest for everything else. Icons are Lucide at 18pt. +- Dense, scannable lists with 52pt track rows. +- Desktop-native interaction: context menus, shortcuts, drag reorder, media keys, and a macOS + menu-bar mini player. -The fonts are bundled from `crates/musyx/assets/fonts` and licensed under OFL. Durations and -counts use tabular figures. +## Colors -## Space and shape +A near-monochrome violet-grey palette with a single warm amber and two quiet status colours. -- Spacing steps: 2 · 4 · 6 · 8 · 10 · 12 · 14 · 18 · 22 · 28 · 34. Content gutter is 28, - and the gap between sections is 34. -- Radii: cover 10 · control 8 · small cover 6 · pill/round 999 · hero 16 · window cards 14. -- Shell: sidebar 232 · player bar 80 · drawer 320 · track row 52 tall. -- Icons: Lucide 0.460 (ISC), 18px and tinted via `currentColor`. The `-fill` variants are for - liked, play and pause. +### Primary +- **Indicator Amber** (`accent`): the playing track's title, the progress fill, primary buttons, + selected chips, the active nav icon, the active tab underline, the focused search border, the + wordmark dot and the My Wave hero lines. The Lossless quality badge also turns amber when Yandex + serves FLAC. +- **Amber Ink** (`accent-ink`): text and icons placed on amber. + +### Secondary +- **Heart Rose** (`like`): a filled heart, a falling chart position, destructive menu entries + ("Remove from this playlist", "Delete…") and the player's error notice line. +- **Signal Green** (`ok`): subscription status and a rising chart position. + +### Neutral +- **Aubergine Graphite** (`bg`): the window, the content area and the sidebar. +- **Casing Panel** (`panel`): the player bar, the drawer, cards that need separation, the search + field, dialogs and the context menu. +- **Raised Plate** (`raised`): hover and selected rows, lit track rows, chip hover, the slider + rail and key caps. +- **Seam** (`line`): 1px dividers, outlines on ghost buttons and chips, the menu border and the + scrollbar thumb. +- **Label White** (`fg`): primary text, the play/pause disc, the volume fill and the toast fill. +- **Faded Label** (`muted`): secondary text, idle icons, column headers and placeholders. + +Covers with no artwork yet get a placeholder: a diagonal gradient between two hues derived from +the item's id. + +### Named Rules +**The One Lit Lamp Rule.** Amber marks state (playing, selected, primary, focused) and nothing +else. Never use it to decorate. If a screen has two amber things, they must be the same "now". + +**The Light-Theme Contrast Rule.** In the light theme, amber text on `bg` measures 3.9:1 and +`ok` text measures 3.8:1. Both are below AA for body text. Until the light accent is darkened, +keep amber text in light mode to titles of 14pt medium or larger, and never use it for small +meta text. + +## Typography + +**Display Font:** Unbounded SemiBold (bundled, OFL) +**Body Font:** Onest Regular / Medium / SemiBold (bundled, OFL) + +**Character:** Unbounded's wide geometric letters give titles the look of a label on hardware. +Onest is a neutral grotesque that holds dense lists and covers Cyrillic well. + +### Hierarchy +- **Display** (600, 46 / 40 / 34 / 30): the My Wave hero, detail page titles, the sign-in + headline and screen titles ("Collection", "Settings"). +- **Wordmark** (600, 20): `musyx` followed by the amber dot. +- **Section** (Onest 600, 19): section headings ("Made for you"), sheet titles, and settings card + titles. +- **Body** (400–500, 14; 1.45 for running text): row titles (medium), menu entries (regular), + buttons (medium/semibold) and paragraphs. +- **Meta** (400, 13): artist lines, album columns, durations and help text. +- **Small** (400, 12.5): column headers, sidebar section labels and the player's times. + +### Named Rules +**The Two Faces Rule.** Unbounded appears only at display sizes and in the wordmark. Everything +interactive is Onest. + +## Layout + +The window is a fixed desktop shell. The minimum size is 960×620 and the default is 1280×800. + +- **Shell:** a 232pt sidebar, a 1px seam, then the content column, which holds the top bar and + the scrolling page. An optional 320pt drawer sits at the right edge and narrows the content + while it is open. An 80pt player bar spans the full width at the bottom. +- **Content gutter:** 28pt. Sections are 34pt apart. +- **Spacing steps:** 4 · 8 · 12 · 18 · 22 · 28 · 34 are the named tokens. Tight in-component gaps + use 2, 6, 10 and 14. About 50 one-off values (16, 9, 24 and others) predate the scale and should + move onto it when touched. +- **Lists:** track rows are 52pt tall with 2pt between rows. Cards are 168pt wide and wrap, with + 12pt between cards and 14pt between rows. +- **Overlays:** the toast floats 96pt above the bottom edge. Menus are pinned to the pointer or to + their button. Dialogs are centred in the window. + +## Elevation & Depth + +The resting UI is flat. Depth comes from tonal steps: `bg` → `panel` → `raised`, about one +lightness step apart, with `line` seams where two surfaces meet. Shadows are kept for elements +that float above the content. + +### Shadow Vocabulary +- **Primary lift** (0 4px 12px, black 18%): primary pill buttons only, so the amber action sits + slightly proud of the page. +- **Menu float** (0 10px 28px, black 30%): the context menu and its submenu. +- **Toast float** (0 6px 18px, black 30%): the status pill above the player bar. +- **Dialog float** (0 18px 50px, black 35%), over a 45% black backdrop: dialogs only. + +### Named Rules +**The Float-Only Shadow Rule.** If it isn't floating above the content (menu, toast, dialog) and +it isn't the primary button, it has no shadow. + +**The No-Dim Rule.** Only dialogs dim the window. Menus, the drawer and toasts never do. + +## Shapes + +Shapes are soft and functional. Controls are pills or gently rounded squares, and covers have +rounded corners. + +- **Pills** (999): primary, ghost and chip buttons, the search field, the toast and the + play/pause disc. +- **Controls** (8): icon buttons, nav items, track rows and menu entries. +- **Covers** (10) and **small covers** (6): album and playlist art at card and row size. Artist + covers are round. The context menu also uses the cover radius. +- **Cards** (14): settings cards, the empty-state card and dialogs. **Hero** (16): the My Wave hero. +- **Key caps** (6): the shortcut list in Settings. ## Components -- **Sidebar**: wordmark, five nav items (Home, My Wave, Search, Collection, Podcasts), a - playlist list, and an account chip with sign-out. The active item sits on a `raised` fill - and has an amber icon. -- **Player bar**: shows cover, title/artist, like and dislike on the left. The centre has - transport (shuffle, previous, play disc, next, repeat) over a progress bar with times. On - the right are a quality badge, lyrics, queue and a volume bar. -- **Track row**: index (or an equaliser when playing), cover, title/artist, album, like, - duration and a "more" button that appears on hover. The playing row is amber. -- **Cards**: a cover with a hover play button, the title, and one muted subtitle line. -- **Drawer**: Queue | Lyrics tabs, sliding in from the right over the content edge. +### Buttons +- **Primary:** an amber pill with amber-ink label, medium or semibold, padded 10×18, with the + primary lift. On hover it mixes 12% toward `fg`. When pressed it mixes 12% toward `bg`. When + disabled it is `raised` with a `muted` label. +- **Ghost:** a transparent pill with a 1px `line` outline and an `fg` label. It fills `raised` on + hover. It pairs with Primary, as in Play + Shuffle. +- **Icon button:** a 34pt square holding an 18pt icon. Idle it is `muted`. On hover the icon turns + `fg` on a `raised` fill. A toggle that is on is tinted `accent`, and a liked heart is `like`. +- **Play disc:** a 40pt `fg` circle with a `bg` glyph. When nothing is queued it becomes a + `raised` circle with a `muted` glyph. + +### Chips +- **Style:** pills padded 7×13, with a `line` outline and an `fg` label. +- **State:** a selected chip fills `accent` with an `accent-ink` label, and can't be clicked + again. Chips are used for quality, appearance, language and the My Wave mood, character and + language settings. + +### Tabs +- Text only: `muted` labels that turn `fg` on hover or when selected, with a 2pt amber underline + under the selected tab. Collection tabs are Liked tracks, Albums, Artists, Playlists and Clips. + A count appears next to a tab once its list has loaded. + +### Cards / Containers +- **Cover cards:** a 168pt cover with a medium title and a muted subtitle. A raised fill shows on + hover. Clicking opens the page. Right-click opens a menu for albums, playlists and artists: + Play, Shuffle, and add to or remove from the collection. Your own playlists get Rename… and + Delete… instead of the collection item. Clips have a heart instead of a menu. +- **Settings cards:** a `panel` fill, 1px `line`, card radius, 24pt padding, and a section title. + +### Inputs / Fields +- **Search:** a 420pt pill with a `panel` fill and a 1px `line` border that turns `accent` on + focus. Selected text is highlighted in amber at 35%. Suggestions float in a list under it. + Opening Search, ⌘F or `/` puts the cursor in it with the text selected. +- **Dialog inputs:** use the same style. + +### Navigation +- **Sidebar:** sits on `bg`, not `panel`, and is separated from the content by a seam. From top + to bottom: the wordmark, five nav items (Home, My Wave, Search, Collection, Podcasts), Playlists + with a + button, the playlist list, and an account chip with a settings gear. The active item + has a `raised` fill, an `fg` label and an amber icon. Idle items are `muted`. +- **Top bar:** a back chevron, disabled when there is no history, and the search field. + +### Player bar +- `panel` fill, 80pt tall, in three zones. +- **Left:** a 52pt cover with the title and artist, then like and dislike buttons. Right-clicking + the cover or title opens the track's menu. +- **Centre:** shuffle, previous, the play disc, next and repeat, above a 4pt seek rail with an + amber fill. The rail's handle appears only on hover or drag. Times sit on either side. +- **Right:** the quality badge, lyrics, queue, and a volume rail with an `fg` fill. + +### Track row +- 52pt tall, built as a button. Columns in order: + - a grip (your own playlists only) + - the index, or an amber `audio-lines` glyph for the playing track (static; it doesn't show + pause) + - a 40pt cover + - title and artist + - album + - the heart + - the duration + - "…" +- **Playing:** the title turns amber. +- **Unavailable:** the title is `muted` and clicking does nothing. +- Clicking plays the row and replaces the queue. +- Right-click, or "…", opens the context menu. +- A row stays lit (`raised`) while its menu is open, and while it is being dragged. +- The heart and "…" are always visible. +- **Dragging (your own playlists):** press the grip and move. The list reorders live to show + where the row will land. Drop to save, or press Esc to cancel. The wheel scrolls during a drag. + The list doesn't auto-scroll near its edges yet. + +### Context menu (signature) +- A 280pt `panel` card with a 1px `line` border, cover radius, 6pt padding and the menu float. + There is no backdrop. +- **Placement:** it opens at the pointer on right-click, or hangs under "…" with the right edges + lined up. Near a window edge it flips left or up, and it always stays 8pt inside the window. +- **Entries:** 32pt tall, with an 18pt `muted` icon and a 14pt `fg` label. The entry under the + pointer, or chosen with the arrow keys, gets a `raised` fill. Destructive entries are `like`. + Disabled entries are `muted` and skipped by the arrow keys. +- **Groups:** separated by hairlines. + - **Track menus:** play actions (Play next or Next track, Add to queue, Play similar tracks); + library actions (Liked tracks, Add to playlist ▸, Don't recommend); go-to (album, then up to + three artists by name). Your own playlists add Move to top, Move to bottom, and Remove from + this playlist. In the queue the first group is Play now, Play next and Remove from queue. + - **Card menus:** Play and Shuffle; then the collection item, or Rename… and Delete… for your + own playlists; then go-to artist for albums. +- **Add to playlist ▸:** opens a submenu beside the menu on hover, click or →. The submenu holds + New playlist… and your own playlists, and scrolls after 10 rows. +- **Closing:** every action closes the menu, and a toast confirms what happened. Clicking outside, + scrolling or Esc also closes it. ↑/↓ move, Enter picks, → and ← open and close the submenu. + +### Drawer +- 320pt on `panel`, with Queue | Lyrics tabs and a close button. +- **Queue:** shows Now playing, then Next up with a count. It lists up to 100 rows, then + "and N more". Clicking a row jumps to it. Right-click opens the queue version of the track menu. +- **Lyrics:** synced lyrics follow playback. + +### Dialogs +- 380pt `panel` card with card radius and the dialog float over a dimmed window. +- Used only when you type or confirm: New playlist, Rename playlist, and Delete playlist. +- Cancel is a ghost button. Confirm is primary, or `like` for Delete. Delete's white label on + `like` measures 2.8:1 in the dark theme, which is below AA, and is a known issue. + +### Toast +- An `fg` pill with `bg` text, 96pt above the bottom edge. It reports every action from menus, + likes and edits, and clears itself after a few seconds. + +### My Wave hero +- A 16pt-radius panel holding a canvas of 14 amber sine lines, the title, a line describing how + the wave is tuned, and Play / Pause / Resume. +- It is the same hero on Home and on My Wave, larger on My Wave. +- The lines drift only while My Wave plays. Otherwise they hold still at reduced energy. + +### Keyboard shortcuts +- Listed in Settings → Keyboard shortcuts as label + key caps. The list is capped at 560pt wide so + the caps sit near their labels. +- The shortcuts: + - Space: play/pause + - ⌘←/→: previous/next + - ⇧←/→: seek 10s + - ⌘↑/↓: volume + - ⌘L: like + - ⌘F or `/`: search + - ⌘[ or ⌥←: back + - Esc: closes a drag, menu, dialog, suggestions or the drawer, in that order + - ⌘1–5: nav sections + - ⌘,: Settings +- ⌘ is Ctrl on Windows and Linux. +- Letter shortcuts follow the key's position on non-Latin layouts. + +## Do's and Don'ts + +### Do: +- **Do** take every colour from `Tokens` in `theme.rs`, and change DESIGN.md in the same commit. +- **Do** use Lucide 0.460 icons at 18pt, tinted with the colour of the text they sit beside. New + icons go in `assets/icons` with the Lucide license header. +- **Do** put routine actions on an item in its context menu, and confirm them with a toast. +- **Do** give every new action a keyboard path, and add it to the Settings shortcut list. +- **Do** translate every string through `tr`/`trf` with a Russian entry in `i18n/ru.rs`. The test + suite fails otherwise. +- **Do** test new screens in both themes and both languages with the snapshot tool + (`MUSYX_SNAPSHOT_*`, see `snapshot.rs`). Russian labels run about 30% longer. + +### Don't: +- **Don't** use amber for decoration, borders or illustrations other than the My Wave hero. +- **Don't** open a dialog for anything that doesn't need typing or a destructive confirmation. +- **Don't** dim the window for menus, the drawer or toasts. +- **Don't** fade icons with `scale_alpha`. iced's SVG tint drops alpha, so a faded icon renders at + full strength. Disabled previous/next already do this. Pre-mix the colour with the surface. +- **Don't** add hardcoded colours outside `theme.rs`. About 19 still exist (sign-in, genre tiles, + dialogs) and should move into tokens when touched. +- **Don't** add shadows to resting surfaces. Depth comes from `bg` → `panel` → `raised`. + +## History + +`design/mockup.html` (published at https://claude.ai/artifact/2gmswtceJM61fcE2F5uYYM) was the +first approved exploration, and it set the palette, type and shell. The build kept those and +deliberately dropped or replaced these parts of it: +- the hero's Tune button and the separate My Wave copy +- the hover play button on cards +- the display-face, two-column chart ranks +- the Podcasts and Disliked collection tabs (Clips was added) +- the Continue listening shelf for podcasts +- the drag grip with an edit bar (replaced by a grip column and live drag) +- Artist wave +- the hover-only "…" +- the animated equaliser on the playing row +- the live sign-in canvas + +Treat the mockup as history. Where it and this file disagree, this file and the build win. diff --git a/README.md b/README.md index 5728a27..95c741c 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,9 @@ and it isn't affiliated with or endorsed by Yandex. - `crates/ym-api`: the Yandex Music API client, with no UI dependencies. - `crates/musyx`: the iced app (screens, widgets, player, theme). -- `design/mockup.html`: the approved design. `DESIGN.md` records its tokens. +- `DESIGN.md`: the design system as built; its tokens map 1:1 to `crates/musyx/src/ui/theme.rs`. +- `design/mockup.html`: the first design exploration, kept for history. Where it differs from + `DESIGN.md`, the build wins. ## Run diff --git a/design/mockup.html b/design/mockup.html index 288aa01..b0caf07 100644 --- a/design/mockup.html +++ b/design/mockup.html @@ -1,3 +1,5 @@ + Musyx Desktop Mockup