Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
576e802b7a | ||
|
|
8324f256c6 |
No files matched your search
@@ -10,6 +10,20 @@
|
||||
- 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
|
||||
credits, including older catalog entries with different sort keys.
|
||||
- A failed listening thumbnail falls back to the original image. A refreshed
|
||||
ranking row can display new artwork after an earlier image failed.
|
||||
|
||||
## v0.15.0 — 2026-11-23
|
||||
|
||||
- Desktop and mobile navigation now includes a personal music collection,
|
||||
|
||||
Generated
+1
-1
@@ -2062,7 +2062,7 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
|
||||
|
||||
[[package]]
|
||||
name = "furumusic"
|
||||
version = "0.15.0"
|
||||
version = "0.15.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-stream",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "furumusic"
|
||||
version = "0.15.0"
|
||||
version = "0.15.2"
|
||||
edition = "2024"
|
||||
description = "Reusable web-app boilerplate: auth, OIDC/SSO, admin panel, user management, i18n, PostgreSQL"
|
||||
|
||||
|
||||
@@ -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." , "Плейлистов пока нет.";
|
||||
|
||||
@@ -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,
|
||||
|
||||
+82
-14
@@ -139,25 +139,37 @@ const SUMMARY: &str = "
|
||||
'daily', COALESCE((SELECT jsonb_agg(to_jsonb(daily) ORDER BY day) FROM daily), '[]'))
|
||||
FROM events";
|
||||
|
||||
const TOP_ARTISTS: &str = "
|
||||
// Fold credits with the same Unicode rules on every database, including C-locale
|
||||
// installations. Return the key to the column's collation for the name_sort index.
|
||||
const TOP_ARTISTS: &str = r#"
|
||||
, top AS (
|
||||
SELECT lower(name) AS key, MIN(name) AS title, COUNT(*) AS plays
|
||||
SELECT key, MIN(name) AS title, COUNT(*) AS plays
|
||||
FROM events CROSS JOIN LATERAL (
|
||||
SELECT DISTINCT ON (lower(trim(n))) trim(n) AS name
|
||||
SELECT DISTINCT ON (key)
|
||||
lower(normalize(trim(n), NFKC) COLLATE furumusic_unicode) COLLATE "default" AS key,
|
||||
trim(n) AS name
|
||||
FROM jsonb_array_elements_text(COALESCE(metadata_json->'artist_names', '[]') ||
|
||||
COALESCE(metadata_json->'featured_artist_names', '[]')) n
|
||||
WHERE trim(n) <> '' ORDER BY lower(trim(n)), trim(n)
|
||||
WHERE trim(n) <> '' ORDER BY key, name
|
||||
) credit
|
||||
GROUP BY lower(name) ORDER BY plays DESC, key LIMIT 5
|
||||
GROUP BY key ORDER BY plays DESC, key LIMIT 5
|
||||
), visible AS NOT MATERIALIZED (
|
||||
SELECT id, name_sort, image_file_id,
|
||||
lower(normalize(trim(name), NFKC) COLLATE furumusic_unicode) COLLATE "default" AS display_key
|
||||
FROM furumusic__artist WHERE NOT is_hidden
|
||||
)
|
||||
SELECT COALESCE(jsonb_agg(to_jsonb(item) ORDER BY plays DESC, title), '[]') FROM (
|
||||
SELECT COALESCE(a.name, top.title) AS title, top.plays, a.id AS artist_id,
|
||||
CASE WHEN a.image_file_id IS NOT NULL THEN '/api/player/cover/' || a.image_file_id || '/small' END AS cover_url
|
||||
FROM top LEFT JOIN LATERAL (
|
||||
SELECT id, name, image_file_id FROM furumusic__artist WHERE name_sort = top.key
|
||||
AND NOT is_hidden ORDER BY id LIMIT 1
|
||||
) a ON true
|
||||
) item";
|
||||
FROM top LEFT JOIN furumusic__artist a ON a.id = COALESCE(
|
||||
(SELECT id FROM visible WHERE name_sort = top.key AND display_key = top.key
|
||||
AND image_file_id IS NOT NULL ORDER BY id LIMIT 1),
|
||||
-- Older imports can have a different sort key. Prefer the actual
|
||||
-- display name and choose the visible copy with a photo on ties.
|
||||
(SELECT id FROM visible WHERE display_key = top.key OR name_sort = top.key
|
||||
ORDER BY (display_key = top.key) DESC, (image_file_id IS NOT NULL) DESC, id LIMIT 1)
|
||||
)
|
||||
) item"#;
|
||||
|
||||
const TRACK_ROWS: &str = "
|
||||
SELECT COALESCE(jsonb_agg(to_jsonb(item) ORDER BY plays DESC, content_id), '[]') FROM (
|
||||
@@ -284,14 +296,20 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires disposable PostgreSQL via FURU_STATISTICS_TEST_DATABASE_URL"]
|
||||
async fn personal_listening_filters_events_and_resolves_playable_editions() -> anyhow::Result<()>
|
||||
{
|
||||
async fn catalog_fixture() -> anyhow::Result<PgPool> {
|
||||
let pool = sqlx::postgres::PgPoolOptions::new()
|
||||
.max_connections(1)
|
||||
.connect(&std::env::var("FURU_STATISTICS_TEST_DATABASE_URL")?)
|
||||
.await?;
|
||||
// Collation names do not resolve through pg_temp. Use an isolated schema
|
||||
// with the deployment's ICU collation, rolled back with the fixture.
|
||||
let schema = format!("listening_{}", uuid::Uuid::new_v4().simple());
|
||||
sqlx::raw_sql(&format!(
|
||||
"BEGIN; CREATE SCHEMA {schema}; SET LOCAL search_path TO {schema}, public;
|
||||
CREATE COLLATION furumusic_unicode (provider=icu, locale='und', deterministic=true);"
|
||||
))
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
sqlx::raw_sql(include_str!("../../tests/statistics_fixture.sql"))
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
@@ -309,6 +327,55 @@ mod tests {
|
||||
INSERT INTO furumusic__media_file (id,sha256_hash) VALUES (51,'sha'),(61,'new-sha');
|
||||
INSERT INTO furumusic__federation_content_id_cache VALUES (51,'sha','content-one'),(61,'old-sha','content-two');
|
||||
").execute(&pool).await?;
|
||||
Ok(pool)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires disposable PostgreSQL via FURU_STATISTICS_TEST_DATABASE_URL"]
|
||||
async fn personal_artist_ranking_resolves_unicode_portraits() -> anyhow::Result<()> {
|
||||
let pool = catalog_fixture().await?;
|
||||
sqlx::raw_sql(r#"
|
||||
INSERT INTO furumusic__artist (id,name,name_sort,image_file_id,is_hidden) VALUES
|
||||
(20,'Ногу Свело!','ногу свело!',101,true),
|
||||
(21,'Ногу Свело!','ногу свело!',NULL,false),
|
||||
(22,'Ногу Свело!','ногу свело',102,false),
|
||||
(23,'Олег Лёгкий','олег лёгкий',103,false),
|
||||
(24,'Саша Скул','саша скул',104,false),
|
||||
(25,'Hidden','hidden',105,true);
|
||||
INSERT INTO furumusic__listen_event (user_id,listen_id,started_at_ms,qualified,metadata_json) VALUES
|
||||
(4,'one',1,true,'{"artist_names":["НОГУ СВЕЛО!","Олег Лёгкий","Саша Скул","Hidden"],"featured_artist_names":[" Ногу Свело! "]}'),
|
||||
(4,'two',2,true,'{"artist_names":["ногу свело!","Олег Ле\u0308гкии\u0306"],"featured_artist_names":["ОЛЕГ ЛЁГКИЙ"]}');
|
||||
"#).execute(&pool).await?;
|
||||
let data = overview(&pool, 4, (0, 3), "UTC", &Ranking::Artists).await?;
|
||||
let artists = data["ranking"].as_array().unwrap();
|
||||
assert_eq!(artists.len(), 4);
|
||||
for (title, id, image, plays) in [
|
||||
("Ногу Свело!", 22, 102, 2),
|
||||
("Олег Лёгкий", 23, 103, 2),
|
||||
("Саша Скул", 24, 104, 1),
|
||||
] {
|
||||
let artist = artists.iter().find(|item| item["title"] == title).unwrap();
|
||||
assert_eq!(artist["artist_id"], id);
|
||||
assert_eq!(
|
||||
artist["cover_url"],
|
||||
format!("/api/player/cover/{image}/small")
|
||||
);
|
||||
assert_eq!(artist["plays"], plays);
|
||||
}
|
||||
let hidden = artists
|
||||
.iter()
|
||||
.find(|item| item["title"] == "Hidden")
|
||||
.unwrap();
|
||||
assert!(hidden["artist_id"].is_null() && hidden["cover_url"].is_null());
|
||||
sqlx::query("ROLLBACK").execute(&pool).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires disposable PostgreSQL via FURU_STATISTICS_TEST_DATABASE_URL"]
|
||||
async fn personal_listening_filters_events_and_resolves_playable_editions() -> anyhow::Result<()>
|
||||
{
|
||||
let pool = catalog_fixture().await?;
|
||||
let all = (0, i64::MAX);
|
||||
let data = overview(&pool, 1, all, "UTC", &Ranking::Artists).await?;
|
||||
assert_eq!(data["plays"], 31);
|
||||
@@ -352,6 +419,7 @@ mod tests {
|
||||
let empty = overview(&pool, 3, all, "UTC", &Ranking::Releases).await?;
|
||||
assert_eq!(empty["plays"], 0);
|
||||
assert_eq!(empty["ranking"], json!([]));
|
||||
sqlx::query("ROLLBACK").execute(&pool).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+192
-39
@@ -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
@@ -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(())
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Until explicitly arranged, pins retain their creation order after ordered pins.
|
||||
ALTER TABLE furumusic__sidebar_pin ADD COLUMN position bigint
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -74,7 +74,8 @@
|
||||
<li><span class="listening-rank-no" aria-hidden="true" x-text="index+1"></span>
|
||||
<div class="listening-rank-art" :class="{round:listens.kind === 'artists'}">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="7"/><circle cx="12" cy="12" r="2"/></svg>
|
||||
<template x-if="item.cover_url"><img :src="item.cover_url" alt="" loading="lazy" @error="$el.hidden=true"></template>
|
||||
<template x-if="item.cover_url"><img :src="item.cover_url" alt="" loading="lazy"
|
||||
@error="listens.coverFailed($el)" @load="$el.removeAttribute('data-unavailable')"></template>
|
||||
</div>
|
||||
<div class="listening-entry-info">
|
||||
<template x-if="listens.kind === 'tracks'">
|
||||
@@ -106,7 +107,8 @@
|
||||
<time :datetime="new Date(item.started_at_ms).toISOString()" x-text="listens.clock(item.started_at_ms)"></time>
|
||||
<button class="listening-play-art" @click="listens.play(item)"
|
||||
:aria-label="listens.text('play') + ' ' + item.title">
|
||||
<template x-if="item.cover_url"><img :src="item.cover_url" alt="" loading="lazy" @error="$el.hidden=true"></template>
|
||||
<template x-if="item.cover_url"><img :src="item.cover_url" alt="" loading="lazy"
|
||||
@error="listens.coverFailed($el)" @load="$el.removeAttribute('data-unavailable')"></template>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" :class="{placeholder: !item.cover_url}"><path d="M8 5v14l11-7z"/></svg>
|
||||
</button>
|
||||
<div class="listening-entry-info">
|
||||
|
||||
@@ -36,6 +36,13 @@ document.addEventListener('alpine:init', () => {
|
||||
number(value) { return numbers.format(value || 0); },
|
||||
date(day) { return dates.format(localDate(day)); },
|
||||
clock(ms) { return times.format(new Date(ms)); },
|
||||
coverFailed(image) {
|
||||
image.setAttribute('data-unavailable', '');
|
||||
const path = image.getAttribute('src') || '';
|
||||
if (/^\/api\/player\/cover\/\d+\/small$/.test(path)) {
|
||||
image.src = path.slice(0, -'/small'.length);
|
||||
}
|
||||
},
|
||||
duration(seconds) {
|
||||
const minutes = Math.floor(Number(seconds || 0) / 60);
|
||||
if (minutes < 1 && seconds > 0) return Math.floor(seconds) + ' ' + this.text('second');
|
||||
|
||||
@@ -39,10 +39,11 @@
|
||||
.listening-rank-art, .listening-play-art { position: relative; display: grid; place-items: center; border: 0; border-radius: 4px; overflow: hidden; aspect-ratio: 1; background: var(--bg-elevated); }
|
||||
.listening-rank-art.round { border-radius: 50%; }
|
||||
.listening-rank-art img, .listening-play-art img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
|
||||
.my-listening img[data-unavailable] { opacity: 0; }
|
||||
.listening-rank-art svg { width: 70%; fill: none; stroke: var(--text-subdued); stroke-width: 1.5; }
|
||||
.listening-play-art svg { width: 56%; position: relative; fill: white; opacity: 0; }
|
||||
.listening-play-art :is(svg.placeholder,img[hidden] + svg), .listening-play-art:hover svg, .listening-play-art:focus-visible svg { opacity: 1; }
|
||||
.listening-play-art:hover img, .listening-play-art:focus-visible img { opacity: .5; }
|
||||
.listening-play-art :is(svg.placeholder,img[data-unavailable] + svg), .listening-play-art:hover svg, .listening-play-art:focus-visible svg { opacity: 1; }
|
||||
.listening-play-art:hover img:not([data-unavailable]), .listening-play-art:focus-visible img:not([data-unavailable]) { opacity: .5; }
|
||||
.listening-entry-info { min-width: 0; }
|
||||
.listening-entry-title, .listening-entry-info small, .listening-event-detail small { display: block; max-width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.my-listening .listening-entry-title { padding: 2px 0; color: var(--text-primary); font-size: 14px; font-weight: 500; text-align: left; background: none; border: 0; text-decoration: none; }
|
||||
|
||||
@@ -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>
|
||||
@@ -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;
|
||||
},
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
@@ -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; }
|
||||
|
||||
@@ -18,6 +18,8 @@ async function run(browser, width, locale) {
|
||||
page.setDefaultTimeout(6000);
|
||||
const errors = [];
|
||||
const queries = [];
|
||||
const coverRequests = [];
|
||||
let artistCover = '/api/player/cover/10/small';
|
||||
let fail = false;
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.route('**/*', async route => {
|
||||
@@ -29,12 +31,20 @@ async function run(browser, width, locale) {
|
||||
if (url.hostname === 'cdn.jsdelivr.net' && url.pathname.includes('alpine')) {
|
||||
return route.fulfill({contentType:'application/javascript', body: alpine});
|
||||
}
|
||||
if (url.pathname.startsWith('/api/player/cover/')) {
|
||||
coverRequests.push(url.pathname);
|
||||
if (url.pathname === '/api/player/cover/11' || url.pathname === '/api/player/cover/12/small') {
|
||||
return route.fulfill({contentType:'image/svg+xml', body:'<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><circle cx="5" cy="5" r="5"/></svg>'});
|
||||
}
|
||||
return route.fulfill({status:404});
|
||||
}
|
||||
if (url.pathname === '/api/player/listening') {
|
||||
const query = Object.fromEntries(url.searchParams);
|
||||
queries.push(query);
|
||||
if (fail) return route.fulfill({status:503,json:{}});
|
||||
if (query.view === 'overview') {
|
||||
return send({plays:5, tracks:1, listened_seconds:900, ranking:[overview[query.kind]],
|
||||
const item = query.kind === 'artists' ? {...overview.artists, cover_url:artistCover} : overview[query.kind];
|
||||
return send({plays:5, tracks:1, listened_seconds:900, ranking:[item],
|
||||
daily:[{day:query.to,plays:5,listened_seconds:900}]});
|
||||
}
|
||||
const selected = query.from !== 'all';
|
||||
@@ -56,6 +66,22 @@ async function run(browser, width, locale) {
|
||||
assert.equal(await content.locator('h1').innerText(), locale === 'ru' ? 'Мои прослушивания' : 'My listening');
|
||||
assert.equal(await content.locator('.listening-day').count(), 30);
|
||||
assert.equal(await content.getByRole('link',{name:'Singer',exact:true}).getAttribute('href'), '#artist/8');
|
||||
const portrait = content.locator('.listening-rank-art img');
|
||||
await portrait.scrollIntoViewIfNeeded();
|
||||
await page.waitForFunction(() => {
|
||||
const image = document.querySelector('.listening-rank-art img');
|
||||
return image?.getAttribute('src') === '/api/player/cover/10' && image.complete && !image.naturalWidth && getComputedStyle(image).opacity === '0';
|
||||
});
|
||||
assert.deepEqual(coverRequests, ['/api/player/cover/10/small','/api/player/cover/10']);
|
||||
for (const [id, suffix] of [[11, ''], [12, '/small']]) {
|
||||
artistCover = '/api/player/cover/'+id+'/small';
|
||||
await page.evaluate(() => Alpine.store('listening').load());
|
||||
await page.waitForFunction(path => {
|
||||
const image = document.querySelector('.listening-rank-art img');
|
||||
return image?.getAttribute('src') === path && image.naturalWidth && getComputedStyle(image).opacity === '1';
|
||||
}, '/api/player/cover/'+id+suffix);
|
||||
}
|
||||
assert.deepEqual(coverRequests.slice(2), ['/api/player/cover/11/small','/api/player/cover/11','/api/player/cover/12/small']);
|
||||
await content.locator('select').selectOption('7');
|
||||
await page.waitForFunction(() => document.querySelectorAll('.listening-day').length === 7);
|
||||
assert.equal(queries.at(-1).tz, 'Europe/Madrid');
|
||||
|
||||
+186
-1
@@ -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();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user