Compare commits

..
1 Commits
Author SHA1 Message Date
ab 576e802b7a Allow reordering sidebar pins and undoing removals
Build and Publish / Build and Publish Docker Image (push) Successful in 3m16s
2026-11-24 00:47:05 +02:00
16 changed files with 880 additions and 116 deletions

No files matched your search

+7
View File
@@ -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
Generated
+1 -1
View File
@@ -2062,7 +2062,7 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
[[package]]
name = "furumusic"
version = "0.15.1"
version = "0.15.2"
dependencies = [
"anyhow",
"async-stream",
+1 -1
View File
@@ -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"
+5
View File
@@ -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." , "Плейлистов пока нет.";
+23
View File
@@ -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,
+192 -39
View File
@@ -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<String>,
before_href: Option<String>,
after_href: Option<String>,
}
#[derive(Deserialize)]
struct PinMove {
href: String,
before_href: Option<String>,
}
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<Vec<serde_json::Value>, sqlx::Error> {
sqlx::query_scalar(&format!(
r#"SELECT jsonb_build_object(
@@ -48,30 +83,23 @@ async fn list(pool: &PgPool, user: i64) -> Result<Vec<serde_json::Value>, 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<bool, sqlx::Error> {
) -> Result<Outcome, sqlx::Error> {
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<bool> = 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<Outcome, sqlx::Error> {
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<Outcome, sqlx::Error> {
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<PinChange>,
change: Option<Mutation>,
) -> cot::Result<cot::response::Response> {
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<tokio::sync::OnceCell<PgPool>>, config: Arc<AppCon
}
};
let read = connect.clone();
let write = connect.clone();
Route::with_handler_and_name(
"/pins",
get(move |auth_ctx, session, db| {
@@ -167,8 +298,30 @@ pub(super) fn route(pool: Arc<tokio::sync::OnceCell<PgPool>>, config: Arc<AppCon
async move { handle(auth_ctx, session, db, pool.await?, None).await }
})
.post(move |auth_ctx, session, db, Json(body): Json<PinChange>| {
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<PinMove>| {
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",
)
+156 -42
View File
@@ -1,75 +1,189 @@
use super::*;
async fn set(pool: &PgPool, user: i64, href: &str, pinned: bool) -> Result<bool, sqlx::Error> {
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<bool, sqlx::Error> {
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<Outcome, sqlx::Error> {
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(())
}
+2
View File
@@ -0,0 +1,2 @@
-- Until explicitly arranged, pins retain their creation order after ordered pins.
ALTER TABLE furumusic__sidebar_pin ADD COLUMN position bigint
+211 -17
View File
@@ -1,16 +1,39 @@
<script>
document.addEventListener('alpine:init', () => {
let writes = Promise.resolve();
let noticeId = 0;
let errorTimer;
let cancelPointer;
const undoWindow = 10_000;
// Preserve relative positions even when several neighbours are unpinned
// and their Undo buttons are used in a different order.
function neighbors(order, href, present) {
const index = order.indexOf(href);
return {
before_href: order.slice(index + 1).find(key => present.includes(key)) ?? null,
after_href: order.slice(0, index).reverse().find(key => present.includes(key)) ?? null,
};
}
Alpine.store('pins', {
items: [], busy: false, generation: 0,
items: [], undoNotices: [], pendingWrites: 0, generation: 0, errorVisible: false,
dragHref: '', dropBeforeHref: undefined,
get busy() { return this.pendingWrites > 0; },
init() { if (!GUEST) this.reload(); },
async read() {
const response = await fetch('/api/player/pins');
if (!response.ok) throw new Error('Could not load shortcuts');
const items = await response.json();
if (!Array.isArray(items)) throw new Error('Invalid shortcut list');
return items;
},
async reload() {
if (this.busy) return;
while (this.busy) await writes;
const generation = ++this.generation;
try {
const response = await fetch('/api/player/pins');
if (!response.ok) return;
const items = await response.json();
if (generation === this.generation && Array.isArray(items)) this.items = items;
const items = await this.read();
if (generation === this.generation && !this.busy) this.items = items;
} catch {}
},
has(target) {
@@ -25,23 +48,194 @@ document.addEventListener('alpine:init', () => {
if (kind === 'playlist' && entity.id > 0) href = '#playlist/' + entity.id;
return href ? {href, title: entity.name || entity.title, cover_url: entity.image_url || entity.cover_url || null} : null;
},
async toggle(target) {
if (!target || this.busy) return;
const pinned = !this.has(target);
this.busy = true;
enqueue(action) {
++this.pendingWrites;
++this.generation;
const next = writes.then(action).finally(() => { --this.pendingWrites; });
writes = next.catch(() => {});
return next;
},
async write(method, payload, matches) {
this.errorVisible = false;
try {
const response = await fetch('/api/player/pins', { method: 'POST', headers: {'Content-Type': 'application/json'},
body: JSON.stringify({...target, pinned}) });
const response = await fetch('/api/player/pins', {method, headers: {'Content-Type': 'application/json'},
body: JSON.stringify(payload)});
if (!response.ok) throw new Error();
this.items = await response.json();
if (this.has(target) !== pinned) throw new Error();
const items = await response.json();
if (!Array.isArray(items)) throw new Error();
this.items = items;
if (!matches(items)) throw new Error();
return true;
} catch {
Alpine.store('info').open('{{ t.player_error }}', '{{ t.player_pin_failed }}');
} finally {
this.busy = false;
// A lost response can follow a successful write. A stale drop
// target can also disappear in another tab while dragging.
try {
this.items = await this.read();
if (matches(this.items)) return true;
} catch {}
this.errorVisible = true;
clearTimeout(errorTimer);
errorTimer = setTimeout(() => { this.errorVisible = false; }, 6000);
return false;
}
},
toggle(target) {
if (!target || this.busy) return;
if (this.has(target)) return this.unpin(target);
return this.enqueue(async () => {
if (await this.write('POST', {...target, pinned:true}, items => items.some(i => i.href === target.href))) {
this.undoNotices = this.undoNotices.filter(n => n.item.href !== target.href);
}
});
},
orderWithRemoved() {
const order = this.items.map(item => item.href);
for (const notice of [...this.undoNotices].reverse()) {
const href = notice.item.href;
if (order.includes(href)) continue;
const {before_href, after_href} = neighbors(notice.order, href, order);
const index = before_href ? order.indexOf(before_href) : after_href ? order.indexOf(after_href) + 1 : order.length;
order.splice(index, 0, href);
}
return order;
},
unpin(target, event) {
const keyboard = event?.detail === 0;
return this.enqueue(async () => {
const item = this.items.find(i => i.href === target.href);
if (!item) return;
const order = this.orderWithRemoved();
if (!await this.write('POST', {...item, pinned:false}, items => !items.some(i => i.href === item.href))) return;
const id = ++noticeId;
this.undoNotices.push({id, item, order, expires:Date.now() + undoWindow, restoring:false});
setTimeout(() => this.expireUndo(id), undoWindow);
if (keyboard) Alpine.nextTick(() => this.focusVisible('.pin-undo-notice[data-undo-id="' + id + '"] button'));
});
},
expireUndo(id) {
this.undoNotices = this.undoNotices.filter(n => n.id !== id || n.restoring);
},
undo(id, event) {
const notice = this.undoNotices.find(n => n.id === id);
if (!notice || notice.restoring) return;
if (Date.now() >= notice.expires) return this.expireUndo(id);
// Accept an in-time click even if another write is still in flight.
notice.restoring = true;
const keyboard = event?.detail === 0;
return this.enqueue(async () => {
const href = notice.item.href;
const anchors = neighbors(notice.order, href, this.items.map(item => item.href));
const ok = await this.write('POST', {...notice.item, pinned:true, ...anchors}, items => items.some(i => i.href === href));
notice.restoring = false;
if (ok || Date.now() >= notice.expires) this.expireUndo(id);
if (ok && keyboard) Alpine.nextTick(() => this.focusVisible('.shortcut-pin-row[data-pin-href="' + CSS.escape(href) + '"] .shortcut-unpin'));
});
},
focusVisible(selector) {
const element = Array.from(document.querySelectorAll(selector)).find(el => el.getClientRects().length && !el.closest('[inert]'));
element?.focus({preventScroll:true});
},
moveBy(item, offset, handle) {
const nav = handle?.closest('.music-nav');
return this.enqueue(async () => {
const index = this.items.findIndex(i => i.href === item.href);
const destination = index + offset;
if (index < 0 || destination < 0 || destination >= this.items.length) return;
const rest = this.items.filter(i => i.href !== item.href);
await this.move(item.href, rest[destination]?.href ?? null);
await Alpine.nextTick();
const active = document.activeElement;
if (nav?.isConnected && (active === handle || active === document.body || active?.matches('dialog'))) {
nav.querySelector('[data-pin-href="' + CSS.escape(item.href) + '"] .shortcut-pin-grip')?.focus({preventScroll:true});
}
});
},
async move(href, before) {
const matches = items => {
const index = items.findIndex(item => item.href === href);
return index >= 0 && (items[index + 1]?.href ?? null) === before;
};
if (matches(this.items)) return;
const previous = this.items;
const moved = previous.find(item => item.href === href);
const rest = previous.filter(item => item.href !== href);
const destination = before === null ? rest.length : rest.findIndex(item => item.href === before);
if (!moved || destination < 0) return;
rest.splice(destination, 0, moved);
this.items = rest;
const preview = this.items;
const saved = await this.write('PUT', {href, before_href:before}, matches);
if (!saved && this.items === preview) this.items = previous;
},
cancelDrag() { cancelPointer?.(); },
startDrag(event, item) {
if (!event.isPrimary || event.button !== 0 || this.busy || this.items.length < 2) return;
this.cancelDrag();
const handle = event.currentTarget;
const list = handle.closest('.shortcut-pin-list');
const scroller = list.closest('.mobile-drawer-body') || list.closest('.music-nav');
const pointer = event.pointerId;
const listeners = new AbortController();
const options = {signal:listeners.signal};
let x = event.clientX, y = event.clientY;
const startX = x, startY = y;
let frame = 0;
const update = () => {
frame = 0;
const bounds = list.getBoundingClientRect();
const port = scroller.getBoundingClientRect();
this.dropBeforeHref = undefined;
if (x < bounds.left || x > bounds.right || y < Math.max(bounds.top, port.top) - 8 || y > Math.min(bounds.bottom, port.bottom) + 8) return;
this.dropBeforeHref = null;
for (const row of list.querySelectorAll('[data-pin-href]')) {
if (row.dataset.pinHref === item.href) continue;
const rect = row.getBoundingClientRect();
if (y < rect.top + rect.height / 2) {
this.dropBeforeHref = row.dataset.pinHref;
break;
}
}
const lastScroll = scroller.scrollTop;
if (y < port.top + 28) scroller.scrollTop -= 8;
else if (y > port.bottom - 28) scroller.scrollTop += 8;
if (scroller.scrollTop !== lastScroll) frame = requestAnimationFrame(update);
};
const finish = (commit = false) => {
if (frame) cancelAnimationFrame(frame);
const before = this.dropBeforeHref;
const moved = !!this.dragHref && before !== undefined;
listeners.abort();
if (handle.hasPointerCapture(pointer)) handle.releasePointerCapture(pointer);
cancelPointer = null;
this.dragHref = '';
this.dropBeforeHref = undefined;
if (commit && moved) this.enqueue(() => this.move(item.href, before));
};
cancelPointer = () => finish();
handle.setPointerCapture(pointer);
handle.addEventListener('pointermove', e => {
if (e.pointerId !== pointer) return;
x = e.clientX; y = e.clientY;
if (!this.dragHref && Math.hypot(x - startX, y - startY) < 4) return;
this.dragHref = item.href;
if (!frame) frame = requestAnimationFrame(update);
}, options);
handle.addEventListener('pointerup', e => {
if (e.pointerId !== pointer) return;
if (this.dragHref) {
if (frame) cancelAnimationFrame(frame);
x = e.clientX; y = e.clientY;
update();
}
finish(true);
}, options);
handle.addEventListener('lostpointercapture', cancelPointer, options);
handle.addEventListener('pointercancel', cancelPointer, options);
window.addEventListener('blur', cancelPointer, options);
window.addEventListener('keydown', e => {
if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); finish(); }
}, {...options, capture:true});
},
});
});
</script>
+19
View File
@@ -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}
</style>
+10
View File
@@ -0,0 +1,10 @@
<div class="pin-feedback" aria-live="polite" aria-relevant="additions text" @keydown.space.stop>
<template x-for="notice in $store.pins.undoNotices" :key="notice.id">
<div class="pin-undo-notice" :data-undo-id="notice.id">
<span><span>{{ t.player_pin_removed }}</span> · <strong x-text="notice.item.title"></strong></span>
<button type="button" :disabled="notice.restoring" :aria-label="'{{ t.player_pin_undo }} · ' + notice.item.title"
@click="$store.pins.undo(notice.id, $event)">{{ t.player_pin_undo }}</button>
</div>
</template>
<div class="pin-action-error" x-show="$store.pins.errorVisible" x-cloak>{{ t.player_pin_failed }}</div>
</div>
+1
View File
@@ -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;
},
+4
View File
@@ -26,6 +26,9 @@
</div>
</div>
</aside>
<template x-if="!$store.mobile.libraryOpen">
{% include "player/pin_undo.html" %}
</template>
<template x-if="$store.mobile.libraryOpen">
<dialog class="mobile-library-backdrop" aria-label="{{ t.player_library }}"
x-init="$nextTick(() => $el.isConnected && $el.showModal())"
@@ -43,6 +46,7 @@
@click="if ($event.target.closest('a[href]') && !($event.ctrlKey || $event.metaKey || $event.shiftKey || $event.altKey)) $store.mobile.closeLibrary()">
{% include "player/sidebar_nav.html" %}
</div>
{% include "player/pin_undo.html" %}
</div>
</dialog>
</template>
+38 -14
View File
@@ -19,7 +19,7 @@
</div>
<section class="music-shortcuts"
x-data="{ get shortcuts() {
if (this.$store.pins.items.length) return this.$store.pins.items;
if (this.$store.pins.items.length || this.$store.pins.undoNotices.length) return this.$store.pins.items;
return this.$store.playlists.regularList().filter(p => p.kind === 'user' && p.is_own).slice(0, 3)
.map(p => ({ href: '#playlist/' + p.id, title: p.title, cover_url: p.cover_url, kind: 'playlist' }));
} }">
@@ -32,18 +32,42 @@
<span class="music-shortcut-title">{{ t.player_likes_playlist }}</span>
<span class="music-shortcut-count" x-text="$store.playlists.list.find(p => p.kind === 'likes')?.track_count ?? ''"></span>
</a>
<template x-for="item in shortcuts" :key="item.href">
<a class="music-shortcut" :href="item.href" :aria-current="$store.library._activeHash === item.href ? 'page' : null">
<span class="music-shortcut-art" :class="{ 'shortcut-artist': item.kind === 'artist' }">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path x-show="item.kind === 'playlist'" d="M3 6h13M3 11h9M3 16h5m8-3v7l5-3.5z"/>
<g x-show="item.kind === 'artist'"><circle cx="12" cy="8" r="3.5"/><path d="M5 20a7 7 0 0 1 14 0"/></g>
<g x-show="item.kind === 'release'"><circle cx="12" cy="12" r="8"/><circle cx="12" cy="12" r="2"/></g>
</svg>
<template x-if="item.cover_url"><img :src="item.cover_url" alt="" loading="lazy" @error="$el.hidden = true" @load="$el.hidden = false"></template>
</span>
<span class="music-shortcut-title" x-text="item.title"></span>
</a>
</template>
<h3 class="shortcut-suggestions-label" x-show="!$store.pins.items.length && shortcuts.length" x-cloak>{{ t.player_my_playlists }}</h3>
<ol class="shortcut-pin-list" :class="{ 'drop-at-end': $store.pins.dragHref && $store.pins.dropBeforeHref === null }">
<template x-for="item in shortcuts" :key="item.href">
<li class="shortcut-pin-row" :data-pin-href="$store.pins.items.length ? item.href : null"
:class="{ 'is-dragging': $store.pins.dragHref === item.href, 'is-drop-before': $store.pins.dropBeforeHref === item.href }">
<a class="music-shortcut" :href="item.href" :title="item.title" :aria-current="$store.library._activeHash === item.href ? 'page' : null">
<span class="music-shortcut-art" :class="{ 'shortcut-artist': item.kind === 'artist' }">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path x-show="item.kind === 'playlist'" d="M3 6h13M3 11h9M3 16h5m8-3v7l5-3.5z"/>
<g x-show="item.kind === 'artist'"><circle cx="12" cy="8" r="3.5"/><path d="M5 20a7 7 0 0 1 14 0"/></g>
<g x-show="item.kind === 'release'"><circle cx="12" cy="12" r="8"/><circle cx="12" cy="12" r="2"/></g>
</svg>
<template x-if="item.cover_url"><img :src="item.cover_url" alt="" loading="lazy" @error="$el.hidden = true" @load="$el.hidden = false"></template>
</span>
<span class="music-shortcut-title" x-text="item.title"></span>
</a>
<template x-if="$store.pins.items.length">
<div class="shortcut-pin-actions" @keydown.space.stop>
<button type="button" class="shortcut-pin-grip" x-show="$store.pins.items.length > 1"
:aria-label="'{{ t.player_reorder_pin }} · ' + item.title"
title="{{ t.player_reorder_hint }}" aria-description="{{ t.player_reorder_hint }}"
aria-keyshortcuts="ArrowUp ArrowDown"
@pointerdown="$store.pins.startDrag($event, item)"
@keydown.arrow-up.stop.prevent="$store.pins.moveBy(item, -1, $el)"
@keydown.arrow-down.stop.prevent="$store.pins.moveBy(item, 1, $el)">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 5h.01M15 5h.01M9 12h.01M15 12h.01M9 19h.01M15 19h.01" stroke-width="3.8"/></svg>
</button>
<button type="button" class="shortcut-unpin"
:aria-label="'{{ t.player_sidebar_unpin }} · ' + item.title" title="{{ t.player_sidebar_unpin }}"
@click.stop="$store.pins.unpin(item, $event)">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m3 3 18 18M8.3 8.3l-2.8 3-2 1.1 8.1 8.1 1.1-2 3-2.8M17.5 12.7l1.1-1.1 2.1-.7-7.6-7.6-.7 2.1-1 1M8.4 15.6 4 20"/></svg>
</button>
</div>
</template>
</li>
</template>
</ol>
</section>
</nav>
+24 -1
View File
@@ -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; }
+186 -1
View File
@@ -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();
}