diff --git a/CHANGELOG.md b/CHANGELOG.md index 5127f09..4aa91bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,13 @@ - Desktop/mobile lyrics view following playback, individual track previews, availability icons, and local version editing in the admin track editor. +## v0.15.2 — 2026-11-24 + +- Reorder pinned sidebar shortcuts by dragging or using the arrow keys. The + order is saved for the account on desktop and mobile. +- Unpin shortcuts directly from the menu. Each removal can be undone for ten + seconds to restore the shortcut to its previous position. + ## v0.15.1 — 2026-11-24 - My listening now finds local artist portraits for Cyrillic and other Unicode diff --git a/Cargo.lock b/Cargo.lock index 7695709..24e03ee 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2062,7 +2062,7 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" [[package]] name = "furumusic" -version = "0.15.1" +version = "0.15.2" dependencies = [ "anyhow", "async-stream", diff --git a/Cargo.toml b/Cargo.toml index e052d51..166d199 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "furumusic" -version = "0.15.1" +version = "0.15.2" edition = "2024" description = "Reusable web-app boilerplate: auth, OIDC/SSO, admin panel, user management, i18n, PostgreSQL" diff --git a/src/i18n/phrases.rs b/src/i18n/phrases.rs index 276239e..2bb7f0b 100644 --- a/src/i18n/phrases.rs +++ b/src/i18n/phrases.rs @@ -284,6 +284,7 @@ translations! { player_my_music: "My music" , "Моя музыка"; player_my_listening: "My listening" , "Мои прослушивания"; player_quick_access: "Quick access" , "Быстрый доступ"; + player_my_playlists: "My playlists" , "Мои плейлисты"; player_pinned: "Pinned" , "Закреплено"; player_account_menu: "Account menu" , "Меню аккаунта"; player_featured_only_artists: "Featured only" , "Только фиты"; @@ -328,6 +329,10 @@ translations! { player_new_playlist: "New Playlist" , "Новый плейлист"; player_sidebar_pin: "Pin to sidebar" , "Закрепить в меню"; player_sidebar_unpin: "Unpin from sidebar" , "Открепить из меню"; + player_reorder_pin: "Move shortcut" , "Переместить в меню"; + player_reorder_hint: "Drag or use the up and down arrows", "Перетащите или нажмите стрелку вверх или вниз"; + player_pin_removed: "Unpinned" , "Откреплено"; + player_pin_undo: "Undo" , "Отменить"; player_pin_failed: "Could not update this shortcut." , "Не удалось обновить закрепление."; player_more_actions: "More actions" , "Ещё"; player_collection_empty: "No playlists yet." , "Плейлистов пока нет."; diff --git a/src/music/mod.rs b/src/music/mod.rs index 4e6cdd5..31add36 100644 --- a/src/music/mod.rs +++ b/src/music/mod.rs @@ -2952,7 +2952,30 @@ pub mod db_migrations { const OPERATIONS: &'static [Operation] = &[Operation::custom(create_sidebar_pins).build()]; } + #[cot::db::migrations::migration_op] + async fn add_sidebar_pin_order(ctx: migrations::MigrationContext<'_>) -> cot::db::Result<()> { + ctx.db + .raw(include_str!("../player/sidebar_pin_order.sql")) + .await?; + Ok(()) + } + + #[derive(Debug, Copy, Clone)] + pub struct M0059AddSidebarPinOrder; + impl migrations::Migration for M0059AddSidebarPinOrder { + const APP_NAME: &'static str = "furumusic"; + const MIGRATION_NAME: &'static str = "m_0059_add_sidebar_pin_order"; + const DEPENDENCIES: &'static [migrations::MigrationDependency] = + &[migrations::MigrationDependency::migration( + "furumusic", + "m_0058_create_sidebar_pins", + )]; + const OPERATIONS: &'static [Operation] = + &[Operation::custom(add_sidebar_pin_order).build()]; + } + pub const MIGRATIONS: &[&SyncDynMigration] = &[ + &M0059AddSidebarPinOrder, &M0058CreateSidebarPins, &M0057CreateLyricsSearch, &M0056CreateLyrics, diff --git a/src/player/pins.rs b/src/player/pins.rs index e839f57..879facb 100644 --- a/src/player/pins.rs +++ b/src/player/pins.rs @@ -1,5 +1,5 @@ use super::*; -use sqlx::PgPool; +use sqlx::{PgConnection, PgPool}; #[derive(Deserialize)] struct PinChange { @@ -7,6 +7,32 @@ struct PinChange { pinned: bool, title: String, cover_url: Option, + before_href: Option, + after_href: Option, +} + +#[derive(Deserialize)] +struct PinMove { + href: String, + before_href: Option, +} + +enum Mutation { + Set(PinChange), + Move(PinMove), +} + +enum MissingAnchor<'a> { + Reject, + RestoreAfter(Option<&'a str>), +} + +#[derive(Debug, PartialEq)] +enum Outcome { + Applied, + Invalid, + Missing, + Stale, } enum Target { @@ -41,6 +67,15 @@ impl Target { } } +const PIN_TARGETS: &str = "FROM furumusic__sidebar_pin pin + LEFT JOIN furumusic__artist a ON a.id = pin.artist_id AND NOT a.is_hidden + LEFT JOIN furumusic__release r ON r.id = pin.release_id AND NOT r.is_hidden + LEFT JOIN furumusic__playlist p ON p.id = pin.playlist_id AND ( + p.owner_id = pin.user_id OR p.is_public OR EXISTS ( + SELECT 1 FROM furumusic__saved_playlist s WHERE s.user_id = pin.user_id AND s.playlist_id = p.id))"; +const VISIBLE: &str = "(COALESCE(a.id, r.id, p.id) IS NOT NULL OR pin.peer_title IS NOT NULL)"; +const PIN_ORDER: &str = "pin.position NULLS LAST, pin.created_at, pin.href"; + async fn list(pool: &PgPool, user: i64) -> Result, sqlx::Error> { sqlx::query_scalar(&format!( r#"SELECT jsonb_build_object( @@ -48,30 +83,23 @@ async fn list(pool: &PgPool, user: i64) -> Result, sqlx:: WHEN pin.href LIKE '#release%' THEN 'release' ELSE 'playlist' END, 'id', COALESCE(a.id, r.id, p.id), 'title', COALESCE(a.name, r.title, p.title, pin.peer_title), 'cover_url', COALESCE('/api/player/cover/' || COALESCE(a.image_file_id, r.cover_file_id, p.cover_file_id, ({})) || '/small', pin.peer_cover)) - FROM furumusic__sidebar_pin pin - LEFT JOIN furumusic__artist a ON a.id = pin.artist_id AND NOT a.is_hidden - LEFT JOIN furumusic__release r ON r.id = pin.release_id AND NOT r.is_hidden - LEFT JOIN furumusic__playlist p ON p.id = pin.playlist_id AND ( - p.owner_id = pin.user_id OR p.is_public OR EXISTS ( - SELECT 1 FROM furumusic__saved_playlist s WHERE s.user_id = pin.user_id AND s.playlist_id = p.id)) - WHERE pin.user_id = $1 AND (COALESCE(a.id, r.id, p.id) IS NOT NULL OR pin.peer_title IS NOT NULL) - ORDER BY pin.created_at, pin.href"#, include_str!("playlist_cover.sql"))) + {PIN_TARGETS} WHERE pin.user_id = $1 AND {VISIBLE} ORDER BY {PIN_ORDER}"#, include_str!("playlist_cover.sql"))) .bind(user).fetch_all(pool).await } -async fn update_pin( - pool: &PgPool, +async fn set_pin( + conn: &mut PgConnection, user: i64, target: Target, change: &PinChange, -) -> Result { +) -> Result { if !change.pinned { sqlx::query("DELETE FROM furumusic__sidebar_pin WHERE user_id = $1 AND href = $2") .bind(user) .bind(&change.href) - .execute(pool) + .execute(conn) .await?; - return Ok(true); + return Ok(Outcome::Applied); } let (artist, release, playlist, title) = match target { Target::Artist(id) => (Some(id), None, None, None), @@ -84,16 +112,120 @@ async fn update_pin( && url.len() <= 4096 && url.starts_with("/api/player/federation/catalog/artwork/") }); - let result = sqlx::query(r#"INSERT INTO furumusic__sidebar_pin (user_id, href, artist_id, release_id, playlist_id, peer_title, peer_cover) - SELECT $1, $2, $3, $4, $5, $6, $7 WHERE $6::text IS NOT NULL + let inserted: Option = sqlx::query_scalar(r#"WITH written AS ( + INSERT INTO furumusic__sidebar_pin (user_id, href, artist_id, release_id, playlist_id, peer_title, peer_cover, created_at) + SELECT $1, $2, $3, $4, $5, $6, $7, clock_timestamp() WHERE $6::text IS NOT NULL OR EXISTS (SELECT 1 FROM furumusic__artist WHERE id = $3 AND NOT is_hidden) OR EXISTS (SELECT 1 FROM furumusic__release WHERE id = $4 AND NOT is_hidden) OR EXISTS (SELECT 1 FROM furumusic__playlist p WHERE p.id = $5 AND (p.owner_id = $1 OR p.is_public OR EXISTS (SELECT 1 FROM furumusic__saved_playlist s WHERE s.user_id = $1 AND s.playlist_id = p.id))) - ON CONFLICT (user_id, href) DO UPDATE SET peer_title = EXCLUDED.peer_title, peer_cover = EXCLUDED.peer_cover"#) + ON CONFLICT (user_id, href) DO UPDATE SET peer_title = EXCLUDED.peer_title, peer_cover = EXCLUDED.peer_cover + RETURNING href) + SELECT NOT EXISTS (SELECT 1 FROM furumusic__sidebar_pin WHERE user_id = $1 AND href = $2) FROM written"#) .bind(user).bind(&change.href).bind(artist).bind(release).bind(playlist).bind(title).bind(cover) - .execute(pool).await?; - Ok(result.rows_affected() > 0) + .fetch_optional(&mut *conn).await?; + match inserted { + None => Ok(Outcome::Missing), + Some(true) if change.before_href.is_some() || change.after_href.is_some() => { + place_pin( + conn, + user, + &change.href, + change.before_href.as_deref(), + MissingAnchor::RestoreAfter(change.after_href.as_deref()), + ) + .await + } + Some(_) => Ok(Outcome::Applied), + } +} + +// A move requires its anchor to still exist. Undo may fall back to the old +// predecessor when the next pin was removed in another tab. +async fn place_pin( + conn: &mut PgConnection, + user: i64, + href: &str, + before: Option<&str>, + missing: MissingAnchor<'_>, +) -> Result { + let mut pins: Vec<(String, bool)> = sqlx::query_as(&format!( + "SELECT pin.href, {VISIBLE} {PIN_TARGETS} WHERE pin.user_id = $1 ORDER BY {PIN_ORDER}" + )) + .bind(user) + .fetch_all(&mut *conn) + .await?; + let Some(source) = pins + .iter() + .position(|(key, visible)| *visible && key == href) + else { + return Ok(Outcome::Stale); + }; + if before == Some(href) { + return Ok(Outcome::Applied); + } + let moved = pins.remove(source); + let visible_index = |href: &str| { + pins.iter() + .position(|(key, visible)| *visible && key == href) + }; + let at = if let Some(i) = before.and_then(visible_index) { + i + } else if let MissingAnchor::RestoreAfter(previous) = missing { + previous + .and_then(visible_index) + .map_or(pins.len(), |i| i + 1) + } else if before.is_none() { + pins.len() + } else { + return Ok(Outcome::Stale); + }; + if at != source { + pins.insert(at, moved); + let order: Vec<_> = pins.into_iter().map(|(key, _)| key).collect(); + sqlx::query("UPDATE furumusic__sidebar_pin p SET position = u.pos + FROM unnest($2::text[]) WITH ORDINALITY AS u(href, pos) + WHERE p.user_id = $1 AND p.href = u.href AND p.position IS DISTINCT FROM u.pos") + .bind(user).bind(order).execute(conn).await?; + } + Ok(Outcome::Applied) +} + +async fn mutate(pool: &PgPool, user: i64, action: Mutation) -> Result { + let mut tx = pool.begin().await?; + // Serialize all pin writers for this account, including when it has no pins. + sqlx::query("SELECT id FROM furumusic__user WHERE id = $1 FOR NO KEY UPDATE") + .bind(user) + .fetch_one(&mut *tx) + .await?; + let outcome = match action { + Mutation::Set(change) => { + let Some(target) = Target::parse(&change.href) else { + return Ok(Outcome::Invalid); + }; + if change.pinned + && matches!(target, Target::Peer) + && (change.title.trim().is_empty() || change.title.len() > 2048) + { + return Ok(Outcome::Invalid); + } + set_pin(&mut tx, user, target, &change).await? + } + Mutation::Move(change) => { + place_pin( + &mut tx, + user, + &change.href, + change.before_href.as_deref(), + MissingAnchor::Reject, + ) + .await? + } + }; + if outcome == Outcome::Applied { + tx.commit().await?; + } + Ok(outcome) } async fn handle( @@ -101,32 +233,30 @@ async fn handle( session: Session, db: Database, pool: PgPool, - change: Option, + change: Option, ) -> cot::Result { let Some(user) = auth::get_request_user(&auth_ctx, &session, &db).await else { return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated")); }; - if let Some(change) = change { - let Some(target) = Target::parse(&change.href) else { - return Ok(json_error( - StatusCode::BAD_REQUEST, - "invalid sidebar target", - )); - }; - if change.pinned - && matches!(target, Target::Peer) - && (change.title.trim().is_empty() || change.title.len() > 2048) - { - return Ok(json_error(StatusCode::BAD_REQUEST, "invalid title")); - } - if !update_pin(&pool, user.id, target, &change) + if let Some(action) = change { + match mutate(&pool, user.id, action) .await .map_err(|e| cot::Error::internal(e.to_string()))? { - return Ok(json_error( - StatusCode::NOT_FOUND, - "sidebar target not found", - )); + Outcome::Applied => {} + Outcome::Invalid => { + return Ok(json_error( + StatusCode::BAD_REQUEST, + "invalid sidebar target", + )); + } + Outcome::Missing => { + return Ok(json_error( + StatusCode::NOT_FOUND, + "sidebar target not found", + )); + } + Outcome::Stale => return Ok(json_error(StatusCode::CONFLICT, "sidebar pins changed")), } } let items = list(&pool, user.id) @@ -160,6 +290,7 @@ pub(super) fn route(pool: Arc>, config: Arc>, config: Arc| { + let pool = write(); + async move { + handle( + auth_ctx, + session, + db, + pool.await?, + Some(Mutation::Set(body)), + ) + .await + } + }) + .put(move |auth_ctx, session, db, Json(body): Json| { let pool = connect(); - async move { handle(auth_ctx, session, db, pool.await?, Some(body)).await } + async move { + handle( + auth_ctx, + session, + db, + pool.await?, + Some(Mutation::Move(body)), + ) + .await + } }), "player_sidebar_pins", ) diff --git a/src/player/pins_tests.rs b/src/player/pins_tests.rs index 191785f..8b87921 100644 --- a/src/player/pins_tests.rs +++ b/src/player/pins_tests.rs @@ -1,75 +1,189 @@ use super::*; -async fn set(pool: &PgPool, user: i64, href: &str, pinned: bool) -> Result { - let change = PinChange { +fn change(href: &str, pinned: bool) -> PinChange { + PinChange { href: href.into(), pinned, title: "Peer album".into(), cover_url: Some("/api/player/federation/catalog/artwork/example".into()), + before_href: None, + after_href: None, + } +} + +async fn set(pool: &PgPool, user: i64, href: &str, pinned: bool) -> Result { + Ok(mutate(pool, user, Mutation::Set(change(href, pinned))).await? == Outcome::Applied) +} + +async fn move_before( + pool: &PgPool, + user: i64, + href: &str, + before: Option<&str>, +) -> Result { + mutate( + pool, + user, + Mutation::Move(PinMove { + href: href.into(), + before_href: before.map(String::from), + }), + ) + .await +} + +async fn check_order(pool: &PgPool, expected: &[&str]) -> anyhow::Result<()> { + let items = list(pool, 3).await?; + let order: Vec<_> = items.iter().map(|p| p["href"].as_str().unwrap()).collect(); + assert_eq!(order, expected); + Ok(()) +} + +async fn exercise_order(pool: &PgPool) -> anyhow::Result<()> { + let [a, b, c, d] = [ + "#artistfed?name=a", + "#artistfed?name=b", + "#artistfed?name=c", + "#artistfed?name=d", + ]; + check_order(pool, &[a, b, c]).await?; + for _ in 0..2 { + assert_eq!(move_before(pool, 3, c, Some(a)).await?, Outcome::Applied); + check_order(pool, &[c, a, b]).await?; + } + assert!(set(pool, 3, d, true).await?); + assert_eq!(move_before(pool, 3, b, None).await?, Outcome::Applied); + check_order(pool, &[c, a, d, b]).await?; + assert!(set(pool, 3, a, false).await?); + let undo = |next: &str| { + let mut request = change(a, true); + request.before_href = Some(next.into()); + request.after_href = Some(c.into()); + Mutation::Set(request) }; - update_pin(pool, user, Target::parse(href).unwrap(), &change).await + assert_eq!(mutate(pool, 3, undo(d)).await?, Outcome::Applied); + check_order(pool, &[c, a, d, b]).await?; + assert_eq!(move_before(pool, 3, a, None).await?, Outcome::Applied); + assert_eq!(mutate(pool, 3, undo(d)).await?, Outcome::Applied); + check_order(pool, &[c, d, b, a]).await?; + assert!(set(pool, 3, a, false).await?); + assert_eq!( + mutate(pool, 3, undo("#artistfed?name=gone")).await?, + Outcome::Applied + ); + check_order(pool, &[c, a, d, b]).await?; + + let (left, right) = tokio::try_join!( + move_before(pool, 3, a, Some(c)), + move_before(pool, 3, b, Some(d)) + )?; + assert_eq!((left, right), (Outcome::Applied, Outcome::Applied)); + check_order(pool, &[a, c, b, d]).await?; + assert_eq!(move_before(pool, 2, a, None).await?, Outcome::Stale); + assert!(list(pool, 2).await?.is_empty()); + + assert!(set(pool, 3, "#playlist/32", true).await?); + sqlx::query("UPDATE furumusic__playlist SET is_public = false WHERE id=32") + .execute(pool) + .await?; + assert_eq!( + move_before(pool, 3, a, Some("#playlist/32")).await?, + Outcome::Stale + ); + assert_eq!( + move_before(pool, 3, "#playlist/32", None).await?, + Outcome::Stale + ); + check_order(pool, &[a, c, b, d]).await?; + sqlx::query("UPDATE furumusic__playlist SET is_public = true WHERE id=32") + .execute(pool) + .await?; + sqlx::query("DELETE FROM furumusic__user WHERE id=3") + .execute(pool) + .await?; + Ok(()) } #[tokio::test] #[ignore = "requires disposable PostgreSQL via FURU_STATISTICS_TEST_DATABASE_URL"] async fn sidebar_pins_respect_visibility_and_catalog_changes() -> anyhow::Result<()> { - let pool = sqlx::postgres::PgPoolOptions::new() - .max_connections(1) - .connect(&std::env::var("FURU_STATISTICS_TEST_DATABASE_URL")?) + use std::str::FromStr; + let url = std::env::var("FURU_STATISTICS_TEST_DATABASE_URL")?; + let admin = PgPool::connect(&url).await?; + let schema = format!("sidebar_pins_{}", uuid::Uuid::new_v4().simple()); + sqlx::query(&format!("CREATE SCHEMA {schema}")) + .execute(&admin) .await?; - // PostgreSQL creates the migration's table in the connection-local temporary schema. + let options = sqlx::postgres::PgConnectOptions::from_str(&url)? + .options([("search_path", schema.as_str())]); + let pool = PgPool::connect_with(options).await?; + let result = exercise_pins(&pool).await; + pool.close().await; + sqlx::query(&format!("DROP SCHEMA {schema} CASCADE")) + .execute(&admin) + .await?; + result +} + +async fn exercise_pins(pool: &PgPool) -> anyhow::Result<()> { sqlx::raw_sql(" - SET search_path TO pg_temp; - CREATE TEMP TABLE furumusic__user (id bigint PRIMARY KEY); - CREATE TEMP TABLE furumusic__artist (id bigint PRIMARY KEY, name text, is_hidden bool, image_file_id bigint); - CREATE TEMP TABLE furumusic__release (id bigint PRIMARY KEY, title text, is_hidden bool, cover_file_id bigint); - CREATE TEMP TABLE furumusic__playlist (id bigint PRIMARY KEY, title text, owner_id bigint, is_public bool, cover_file_id bigint); - CREATE TEMP TABLE furumusic__track (id bigint PRIMARY KEY, release_id bigint, is_hidden bool, cover_file_id bigint); - CREATE TEMP TABLE furumusic__playlist_track (id bigint, playlist_id bigint, track_id bigint, position int); - CREATE TEMP TABLE furumusic__saved_playlist (user_id bigint, playlist_id bigint); - INSERT INTO furumusic__user VALUES (1),(2); + CREATE TABLE furumusic__user (id bigint PRIMARY KEY); + CREATE TABLE furumusic__artist (id bigint PRIMARY KEY, name text, is_hidden bool, image_file_id bigint); + CREATE TABLE furumusic__release (id bigint PRIMARY KEY, title text, is_hidden bool, cover_file_id bigint); + CREATE TABLE furumusic__playlist (id bigint PRIMARY KEY, title text, owner_id bigint, is_public bool, cover_file_id bigint); + CREATE TABLE furumusic__track (id bigint PRIMARY KEY, release_id bigint, is_hidden bool, cover_file_id bigint); + CREATE TABLE furumusic__playlist_track (id bigint, playlist_id bigint, track_id bigint, position int); + CREATE TABLE furumusic__saved_playlist (user_id bigint, playlist_id bigint); + INSERT INTO furumusic__user VALUES (1),(2),(3); INSERT INTO furumusic__artist VALUES (10,'Artist',false,70), (11,'Hidden artist',true,NULL); INSERT INTO furumusic__release VALUES (12,'Album',false,80), (13,'Hidden album',true,81); INSERT INTO furumusic__track VALUES (20,12,true,90), (21,13,false,NULL), (22,12,false,NULL), (23,12,false,91); INSERT INTO furumusic__playlist VALUES (30,'My list',1,false,99), (31,'Someone else',2,false,NULL), (32,'Public list',2,true,NULL); INSERT INTO furumusic__playlist_track VALUES (1,32,20,1), (2,32,21,2), (3,32,22,3), (4,32,23,4); - ").execute(&pool).await?; + ").execute(pool).await?; sqlx::raw_sql(include_str!("sidebar_pins.sql")) - .execute(&pool) + .execute(pool) .await?; - assert!(set(&pool, 1, "#playlist/30", true).await?); - assert!(set(&pool, 1, "#playlist/30", true).await?); - assert_eq!(list(&pool, 1).await?.len(), 1); + sqlx::query("INSERT INTO furumusic__sidebar_pin (user_id,href,peer_title,created_at) VALUES + (3,'#artistfed?name=c','C','2026-01-02'), (3,'#artistfed?name=b','B','2026-01-01'), (3,'#artistfed?name=a','A','2026-01-01')") + .execute(pool).await?; + sqlx::raw_sql(include_str!("sidebar_pin_order.sql")) + .execute(pool) + .await?; + exercise_order(pool).await?; + assert!(set(pool, 1, "#playlist/30", true).await?); + assert!(set(pool, 1, "#playlist/30", true).await?); + assert_eq!(list(pool, 1).await?.len(), 1); assert_eq!( - list(&pool, 1).await?[0]["cover_url"], + list(pool, 1).await?[0]["cover_url"], "/api/player/cover/99/small" ); for href in ["#playlist/31", "#artist/11", "#release/13", "#artist/99"] { - assert!(!set(&pool, 1, href, true).await?, "{href}"); + assert!(!set(pool, 1, href, true).await?, "{href}"); } - assert!(set(&pool, 2, "#playlist/31", true).await?); - assert!(set(&pool, 1, "#playlist/31", false).await?); - assert_eq!(list(&pool, 2).await?.len(), 1); - assert!(set(&pool, 1, "#playlist/32", true).await?); - let public = list(&pool, 1) + assert!(set(pool, 2, "#playlist/31", true).await?); + assert!(set(pool, 1, "#playlist/31", false).await?); + assert_eq!(list(pool, 2).await?.len(), 1); + assert!(set(pool, 1, "#playlist/32", true).await?); + let public = list(pool, 1) .await? .into_iter() .find(|p| p["id"] == 32) .unwrap(); assert_eq!(public["cover_url"], "/api/player/cover/80/small"); sqlx::query("UPDATE furumusic__playlist SET is_public = false WHERE id=32") - .execute(&pool) + .execute(pool) .await?; - assert_eq!(list(&pool, 1).await?.len(), 1); + assert_eq!(list(pool, 1).await?.len(), 1); sqlx::query("INSERT INTO furumusic__saved_playlist VALUES (1,32)") - .execute(&pool) + .execute(pool) .await?; - assert_eq!(list(&pool, 1).await?.len(), 2); - assert!(set(&pool, 1, "#artist/10", true).await?); - assert!(set(&pool, 1, "#release/12", true).await?); + assert_eq!(list(pool, 1).await?.len(), 2); + assert!(set(pool, 1, "#artist/10", true).await?); + assert!(set(pool, 1, "#release/12", true).await?); let peer = "#releasefed?key=%7B%22normalized_title%22%3A%22album%22%7D"; - assert!(set(&pool, 1, peer, true).await?); - let pinned = list(&pool, 1).await?; + assert!(set(pool, 1, peer, true).await?); + let pinned = list(pool, 1).await?; assert_eq!(pinned.len(), 5); let remote = pinned.into_iter().find(|p| p["href"] == peer).unwrap(); assert_eq!(remote["title"], "Peer album"); @@ -79,16 +193,16 @@ async fn sidebar_pins_respect_visibility_and_catalog_changes() -> anyhow::Result "/api/player/federation/catalog/artwork/example" ); sqlx::raw_sql("DELETE FROM furumusic__artist WHERE id=10; DELETE FROM furumusic__release WHERE id=12; DELETE FROM furumusic__playlist WHERE id=30;") - .execute(&pool).await?; - assert_eq!(list(&pool, 1).await?.len(), 2); - assert!(set(&pool, 1, peer, false).await?); + .execute(pool).await?; + assert_eq!(list(pool, 1).await?.len(), 2); + assert!(set(pool, 1, peer, false).await?); sqlx::query("DELETE FROM furumusic__user WHERE id=1") - .execute(&pool) + .execute(pool) .await?; let remaining: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM furumusic__sidebar_pin") - .fetch_one(&pool) + .fetch_one(pool) .await?; assert_eq!(remaining, 1); - assert_eq!(list(&pool, 2).await?[0]["href"], "#playlist/31"); + assert_eq!(list(pool, 2).await?[0]["href"], "#playlist/31"); Ok(()) } diff --git a/src/player/sidebar_pin_order.sql b/src/player/sidebar_pin_order.sql new file mode 100644 index 0000000..de12b08 --- /dev/null +++ b/src/player/sidebar_pin_order.sql @@ -0,0 +1,2 @@ +-- Until explicitly arranged, pins retain their creation order after ordered pins. +ALTER TABLE furumusic__sidebar_pin ADD COLUMN position bigint diff --git a/templates/player/collection_scripts.html b/templates/player/collection_scripts.html index 7749b4c..afaec92 100644 --- a/templates/player/collection_scripts.html +++ b/templates/player/collection_scripts.html @@ -1,16 +1,39 @@ diff --git a/templates/player/collection_styles.html b/templates/player/collection_styles.html index a5f7e14..aae40ae 100644 --- a/templates/player/collection_styles.html +++ b/templates/player/collection_styles.html @@ -25,4 +25,23 @@ .collection-popup {position:absolute;right:0;top:100%;z-index:5;min-width:135px;background:var(--bg-elevated);padding:4px;border:1px solid var(--border-color);border-radius:6px;box-shadow:0 4px 14px #0005} .collection-popup button {display:block;width:100%;border:0;padding:8px 12px;text-align:left;background:transparent;color:var(--text-primary);cursor:pointer} .collection-popup button:hover,.collection-more:hover {background:var(--bg-active)} +.pin-feedback { + position:fixed; z-index:1000; left:16px; bottom:calc(var(--player-bar-space) + 12px); + display:grid; grid-template-columns:minmax(0,1fr); gap:6px; max-width:min(360px,calc(100vw - 32px)); max-height:35dvh; + overflow:auto; overscroll-behavior:contain; scrollbar-width:thin; +} +.pin-undo-notice,.pin-action-error { + display:flex; align-items:center; justify-content:space-between; gap:12px; + padding:6px 8px 6px 14px; min-width:0; min-height:40px; border:1px solid var(--border-color); + border-radius:8px; background:var(--bg-elevated); color:var(--text-primary); font-size:13px; +} +.pin-undo-notice > span {overflow:hidden; text-overflow:ellipsis; white-space:nowrap; min-width:0} +.pin-undo-notice button { + flex:none; padding:6px 10px; min-height:32px; border:0; border-radius:5px; + background:transparent; color:var(--accent); font:inherit; font-weight:600; cursor:pointer; +} +.pin-undo-notice button:hover,.pin-undo-notice button:focus-visible {background:var(--bg-active)} +.pin-undo-notice button:disabled {opacity:.6} +.mobile-library-drawer .pin-feedback {position:static; flex:0 0 auto; max-width:100%} +.mobile-library-drawer .pin-undo-notice button {min-height:44px} diff --git a/templates/player/pin_undo.html b/templates/player/pin_undo.html new file mode 100644 index 0000000..004d93b --- /dev/null +++ b/templates/player/pin_undo.html @@ -0,0 +1,10 @@ +
+ +
{{ t.player_pin_failed }}
+
diff --git a/templates/player/scripts.html b/templates/player/scripts.html index 1fdc7c5..df84075 100644 --- a/templates/player/scripts.html +++ b/templates/player/scripts.html @@ -325,6 +325,7 @@ document.addEventListener('alpine:init', () => { if (this.libraryOpen) Alpine.store('user').menuOpen = false; }, closeLibrary() { + Alpine.store('pins')?.cancelDrag(); document.querySelector('dialog.mobile-library-backdrop[open]')?.close(); this.libraryOpen = false; }, diff --git a/templates/player/shell.html b/templates/player/shell.html index 214d014..54a3c0b 100644 --- a/templates/player/shell.html +++ b/templates/player/shell.html @@ -26,6 +26,9 @@ + diff --git a/templates/player/sidebar_nav.html b/templates/player/sidebar_nav.html index c898894..d23a741 100644 --- a/templates/player/sidebar_nav.html +++ b/templates/player/sidebar_nav.html @@ -19,7 +19,7 @@
@@ -32,18 +32,42 @@ {{ t.player_likes_playlist }} - +

{{ t.player_my_playlists }}

+
    + +
diff --git a/templates/player/sidebar_styles.html b/templates/player/sidebar_styles.html index eec0cb0..ba18f39 100644 --- a/templates/player/sidebar_styles.html +++ b/templates/player/sidebar_styles.html @@ -41,7 +41,7 @@ } .music-nav a[aria-current] { background: var(--bg-active); color: var(--text-primary); } .music-nav-pages a[aria-current] svg { color: var(--accent); } -.music-nav a:focus-visible, .sidebar-account button:focus-visible, .account-action-list > :focus-visible { +.music-nav :is(a, button):focus-visible, .sidebar-account button:focus-visible, .account-action-list > :focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } @@ -69,6 +69,29 @@ .music-shortcut-art img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; } .music-shortcut-title { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; font-size: 13px; } .music-shortcut-count { margin-left: auto; font-size: 12px; color: var(--text-subdued); font-variant-numeric: tabular-nums; } +.shortcut-suggestions-label { margin: 12px 10px 3px; color: var(--text-subdued); font-size: 11px; font-weight: 600; } +.shortcut-pin-list { position: relative; list-style: none; margin: 0; padding: 0; } +.shortcut-pin-row { position: relative; display: flex; align-items: center; min-width: 0; border-radius: 7px; } +.shortcut-pin-row > a { flex: 1; } +.shortcut-pin-row[data-pin-href]:is(:hover,:focus-within) { background: var(--bg-hover); } +.shortcut-pin-row:has(> a[aria-current]) { background: var(--bg-active); } +.shortcut-pin-row.is-dragging { background: var(--bg-active); } +.shortcut-pin-row.is-dragging .shortcut-pin-grip { color: var(--accent); cursor: grabbing; } +.shortcut-pin-row.is-drop-before::before, .shortcut-pin-list.drop-at-end::after { + content: ''; position: absolute; left: 6px; right: 6px; height: 2px; + border-radius: 2px; background: var(--accent); z-index: 1; pointer-events: none; +} +.shortcut-pin-row.is-drop-before::before { top: -1px; } +.shortcut-pin-list.drop-at-end::after { bottom: -1px; } +.shortcut-pin-actions { display: flex; align-items: center; padding-right: 2px; } +.shortcut-pin-actions button { + display: grid; place-items: center; flex: none; width: 28px; height: 34px; padding: 0; + border: 0; border-radius: 5px; background: transparent; color: var(--text-subdued); cursor: pointer; +} +.shortcut-pin-actions button:is(:hover,:focus-visible) { color: var(--text-primary); background: var(--bg-active); } +.shortcut-pin-actions svg { width: 15px; height: 15px; pointer-events: none; } +.shortcut-pin-actions .shortcut-pin-grip { touch-action: none; user-select: none; cursor: grab; } +.mobile-library-drawer .shortcut-pin-actions button { width: 44px; height: 44px; } .sidebar-account { position: relative; flex: 0 0 auto; padding: 8px; border-top: 1px solid var(--border-color); } .sidebar-account-trigger { width: 100%; padding: 7px 10px; } .sidebar-account-trigger .user-avatar { width: 29px; height: 29px; flex-shrink: 0; font-size: 12px; } diff --git a/tests/browser-sidebar.cjs b/tests/browser-sidebar.cjs index 9c5b047..670e388 100644 --- a/tests/browser-sidebar.cjs +++ b/tests/browser-sidebar.cjs @@ -83,6 +83,10 @@ async function checkSidebar(browser, mobile) { const nav = page.locator(mobile ? 'dialog .music-nav' : '.sidebar-left .music-nav'); if (mobile) await menuButton.click(); await nav.getByRole('link', { name: mobile ? pin.title : owned.title }).waitFor(); + if (!mobile) { + assert.equal(await nav.locator('.shortcut-pin-grip:visible, .shortcut-unpin:visible').count(), 0, + 'automatic shortcuts cannot be moved or unpinned'); + } assert.deepEqual(await nav.locator('.music-nav-pages a').allTextContents().then(values => values.map(value => value.trim())), ['Catalog', 'My music', 'Podcasts', 'My listening']); await nav.getByRole('link', { name: /Liked songs/ }).click(); @@ -122,6 +126,185 @@ async function checkSidebar(browser, mobile) { await page.close(); } +async function dragShortcut(page, nav, source, destination, touch, cancel = false) { + const grip = nav.locator('[data-pin-href="' + source.href + '"] .shortcut-pin-grip'); + const row = nav.locator('[data-pin-href="' + destination.href + '"]'); + const handle = await grip.boundingBox(), target = await row.boundingBox(); + assert.ok(handle && target); + const x = Math.round(handle.x + handle.width / 2); + const y = Math.round(handle.y + handle.height / 2); + const end = Math.round(target.y + target.height * .8); + if (touch) { + const cdp = await page.context().newCDPSession(page); + await cdp.send('Input.dispatchTouchEvent', {type:'touchStart',touchPoints:[{x,y}]}); + for (let step = 1; step <= 8; step++) { + await cdp.send('Input.dispatchTouchEvent', {type:'touchMove',touchPoints:[{x,y:y+(end-y)*step/8}]}); + } + await cdp.send('Input.dispatchTouchEvent', {type:cancel ? 'touchCancel' : 'touchEnd', touchPoints:[]}); + await cdp.detach(); + } else { + await page.mouse.move(x,y); + await page.mouse.down(); + await page.mouse.move(x,end,{steps:8}); + if (cancel) await page.keyboard.press('Escape'); + await page.mouse.up(); + } +} + +async function checkPinActions(browser, mobile) { + const page = await browser.newPage({viewport:{width:mobile ? 375 : 1280,height:800}, hasTouch:mobile, isMobile:mobile}); + const errors = []; + page.on('pageerror', err => errors.push(err.message)); + await page.clock.install(); + const [a,b,c,d] = ['Low','Hounds of Love','Discovery · '+ 'Anniversary Edition '.repeat(7).trim(),'Kind of Blue'].map((title,index) => ( + {title,href:'#release/'+(index+101),id:index+101,kind:'release'} + )); + let stored = [a,b,c,d]; + let rejectMove = false; + let loseUnpinReply = false; + let offlineMove = false; + let offlineRead = false; + const writes = []; + await page.route('**/*', route => { + const {hostname,pathname} = new URL(route.request().url()); + if (hostname === 'sidebar.test' && pathname === '/') return route.fulfill({contentType:'text/html',body:html}); + if (hostname === 'cdn.jsdelivr.net' && pathname.includes('alpine')) return route.fulfill({contentType:'application/javascript',body:alpine}); + if (pathname === '/api/player/pins') { + const method = route.request().method(); + if (offlineMove && method === 'PUT') { + offlineMove = false; + offlineRead = true; + return route.abort('internetdisconnected'); + } + if (offlineRead && method === 'GET') { + offlineRead = false; + return route.abort('internetdisconnected'); + } + if (method === 'GET') return route.fulfill({json:stored}); + const change = route.request().postDataJSON(); + writes.push({method,...change}); + if (method === 'PUT' && rejectMove) { + stored = stored.filter(item => item.href !== c.href); + return route.fulfill({status:409,json:{error:'Order changed'}}); + } + const item = [a,b,c,d].find(item => item.href === change.href); + assert.ok(item, 'only pinned entries can be modified'); + stored = stored.filter(entry => entry.href !== item.href); + if (method === 'PUT' || change.pinned) { + const before = stored.findIndex(entry => entry.href === change.before_href); + const after = stored.findIndex(entry => entry.href === change.after_href); + stored.splice(before >= 0 ? before : after >= 0 ? after + 1 : stored.length, 0, item); + } + if (loseUnpinReply && method === 'POST' && !change.pinned) { + loseUnpinReply = false; + return route.abort('failed'); + } + return route.fulfill({json:stored}); + } + const responses = { + '/api/player/artists': {items:[],total:0,has_more:false}, + '/api/player/me': {id:1,name:'Listener'}, '/api/player/playlists':[likes,owned], + ['/api/player/releases/'+a.id]: {...a,artists:[],tracks:[]}, + }; + return route.fulfill({json:responses[pathname] || []}); + }); + const root = mobile ? 'dialog .music-shortcuts' : '.sidebar-left .music-shortcuts'; + const nav = page.locator(root); + const menuButton = page.locator('.mobile-library-btn'); + const openDrawer = async () => { + await menuButton.click(); + await page.locator('dialog:modal').waitFor(); + }; + const row = item => nav.locator('[data-pin-href="' + item.href + '"]'); + const notice = item => page.locator('.pin-undo-notice:visible').filter({hasText:item.title}); + const unpin = async item => { + await row(item).locator('.shortcut-unpin').click(); + await notice(item).getByRole('button',{name:/Undo/i}).waitFor(); + assert.ok(await notice(item).evaluate(el => + el.scrollWidth <= el.clientWidth + 1 && + el.querySelector('button').getBoundingClientRect().right <= el.closest('.pin-feedback').getBoundingClientRect().right + 1 + ), 'Undo remains fully visible for long titles'); + }; + const undo = item => notice(item).getByRole('button',{name:/Undo/i}).click(); + async function expectOrder(expected) { + const hrefs = expected.map(item => item.href); + await page.waitForFunction(({root,hrefs}) => { + const actual = Array.from(document.querySelectorAll(root+' [data-pin-href]'), el => el.dataset.pinHref); + return !Alpine.store('pins').busy && actual.length === hrefs.length && + actual.every((href,index) => href === hrefs[index]); + }, {root,hrefs}); + assert.deepEqual(stored.map(item => item.href), hrefs); + } + await page.goto('http://sidebar.test/'); + if (mobile) await openDrawer(); + await expectOrder([a,b,c,d]); + const initialHash = new URL(page.url()).hash; + await dragShortcut(page,nav,a,c,mobile,true); + await expectOrder([a,b,c,d]); + assert.equal(writes.length, 0, 'a cancelled drag leaves the order intact'); + await dragShortcut(page,nav,a,c,mobile); + await expectOrder([b,c,a,d]); + assert.equal(new URL(page.url()).hash, initialHash, 'dragging a pin cannot navigate'); + assert.deepEqual(writes.map(({method,href,before_href})=>[method,href,before_href]),[['PUT',a.href,d.href]]); + await page.reload(); + if (mobile) await openDrawer(); + await expectOrder([b,c,a,d]); + const grip = row(b).locator('.shortcut-pin-grip'); + await grip.focus(); + await page.keyboard.press('ArrowDown'); + await expectOrder([c,b,a,d]); + assert.ok(await grip.evaluate(button => document.activeElement === button), 'keyboard reordering retains focus'); + + // Remove adjacent head entries; the first undo no longer has its old next neighbour. + await unpin(c); + await unpin(b); + await expectOrder([a,d]); + if (mobile) { + await page.keyboard.press('Escape'); + await page.locator('dialog').waitFor({state:'detached'}); + } + await undo(c); + if (mobile) await openDrawer(); + await expectOrder([c,a,d]); + await undo(b); + await expectOrder([c,b,a,d]); + + loseUnpinReply = true; + await unpin(d); + await page.clock.fastForward(8000); + assert.ok(await notice(d).isVisible(), 'undo remains available before ten seconds'); + await page.clock.fastForward(2200); + await notice(d).waitFor({state:'hidden'}); + await expectOrder([c,b,a]); + if (!mobile) { + offlineMove = true; + await row(b).locator('.shortcut-pin-grip').focus(); + await Promise.all([ + page.waitForEvent('requestfailed', req => req.url().endsWith('/api/player/pins') && req.method() === 'GET'), + page.keyboard.press('ArrowUp'), + ]); + await expectOrder([c,b,a]); + await page.locator('.pin-action-error:visible').waitFor(); + rejectMove = true; + await row(b).locator('.shortcut-pin-grip').focus(); + await page.keyboard.press('ArrowUp'); + await expectOrder([b,a]); + await unpin(b); + await unpin(a); + await expectOrder([]); + assert.equal(await nav.getByRole('link',{name:owned.title}).count(), 0); + await page.clock.fastForward(10_100); + await nav.getByRole('link',{name:owned.title}).waitFor(); + assert.equal(await nav.locator('.shortcut-unpin:visible, .shortcut-pin-grip:visible').count(), 0); + } else { + await row(a).getByRole('link').tap(); + await page.waitForURL('**/'+a.href); + await page.locator('dialog').waitFor({state:'detached'}); + } + assert.deepEqual(errors, []); + await page.close(); +} + (async () => { const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}), @@ -130,7 +313,9 @@ async function checkSidebar(browser, mobile) { await checkSidebar(browser, false); await checkSidebar(browser, true); await checkCollection(browser); - console.log('Desktop and mobile navigation and account controls passed.'); + await checkPinActions(browser, false); + await checkPinActions(browser, true); + console.log('Desktop and mobile sidebar navigation, account controls, pin reordering and undo passed.'); } finally { await browser.close(); }