mirror of
https://github.com/kilyabin/psysonic.git
synced 2026-07-22 14:35:41 +00:00
feat(playlists): integrate Navidrome smart playlist flow into playlists page
Move smart playlist creation and management into Playlists, including Navidrome-only gating, smart-name/icon presentation, and smarter refresh handling while server-side smart rules are being applied.
This commit is contained in:
@@ -565,6 +565,99 @@ async fn nd_set_user_libraries(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// GET `/api/playlist` — list playlists; pass `smart=true` to filter smart playlists.
|
||||||
|
#[tauri::command]
|
||||||
|
async fn nd_list_playlists(
|
||||||
|
server_url: String,
|
||||||
|
token: String,
|
||||||
|
smart: Option<bool>,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
let resp = nd_retry(|| {
|
||||||
|
let client = nd_http_client();
|
||||||
|
let mut req = client
|
||||||
|
.get(format!("{}/api/playlist", server_url))
|
||||||
|
.header("X-ND-Authorization", format!("Bearer {}", token));
|
||||||
|
if let Some(s) = smart {
|
||||||
|
req = req.query(&[("smart", s)]);
|
||||||
|
}
|
||||||
|
req.send()
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
if !resp.status().is_success() {
|
||||||
|
return Err(format!("HTTP {}", resp.status()));
|
||||||
|
}
|
||||||
|
resp.json::<serde_json::Value>().await.map_err(nd_err)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST `/api/playlist` — create playlist (supports smart rules payload).
|
||||||
|
#[tauri::command]
|
||||||
|
async fn nd_create_playlist(
|
||||||
|
server_url: String,
|
||||||
|
token: String,
|
||||||
|
body: serde_json::Value,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
let resp = nd_retry(|| {
|
||||||
|
nd_http_client()
|
||||||
|
.post(format!("{}/api/playlist", server_url))
|
||||||
|
.header("X-ND-Authorization", format!("Bearer {}", token))
|
||||||
|
.json(&body)
|
||||||
|
.send()
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
let status = resp.status();
|
||||||
|
let text = resp.text().await.unwrap_or_default();
|
||||||
|
if !status.is_success() {
|
||||||
|
return Err(format!("HTTP {}: {}", status, text));
|
||||||
|
}
|
||||||
|
serde_json::from_str(&text).map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// PUT `/api/playlist/{id}` — update playlist (supports smart rules payload).
|
||||||
|
#[tauri::command]
|
||||||
|
async fn nd_update_playlist(
|
||||||
|
server_url: String,
|
||||||
|
token: String,
|
||||||
|
id: String,
|
||||||
|
body: serde_json::Value,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
let resp = nd_retry(|| {
|
||||||
|
nd_http_client()
|
||||||
|
.put(format!("{}/api/playlist/{}", server_url, id))
|
||||||
|
.header("X-ND-Authorization", format!("Bearer {}", token))
|
||||||
|
.json(&body)
|
||||||
|
.send()
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
let status = resp.status();
|
||||||
|
let text = resp.text().await.unwrap_or_default();
|
||||||
|
if !status.is_success() {
|
||||||
|
return Err(format!("HTTP {}: {}", status, text));
|
||||||
|
}
|
||||||
|
Ok(serde_json::from_str(&text).unwrap_or(serde_json::Value::Null))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// DELETE `/api/playlist/{id}` — delete playlist.
|
||||||
|
#[tauri::command]
|
||||||
|
async fn nd_delete_playlist(
|
||||||
|
server_url: String,
|
||||||
|
token: String,
|
||||||
|
id: String,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let resp = nd_retry(|| {
|
||||||
|
nd_http_client()
|
||||||
|
.delete(format!("{}/api/playlist/{}", server_url, id))
|
||||||
|
.header("X-ND-Authorization", format!("Bearer {}", token))
|
||||||
|
.send()
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
let status = resp.status();
|
||||||
|
if !status.is_success() {
|
||||||
|
let text = resp.text().await.unwrap_or_default();
|
||||||
|
return Err(format!("HTTP {}: {}", status, text));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
const RADIO_PAGE_SIZE: u32 = 25;
|
const RADIO_PAGE_SIZE: u32 = 25;
|
||||||
|
|
||||||
/// Search the radio-browser.info directory (needs User-Agent header — CORS would block WebView).
|
/// Search the radio-browser.info directory (needs User-Agent header — CORS would block WebView).
|
||||||
@@ -3724,6 +3817,10 @@ pub fn run() {
|
|||||||
nd_delete_user,
|
nd_delete_user,
|
||||||
nd_list_libraries,
|
nd_list_libraries,
|
||||||
nd_set_user_libraries,
|
nd_set_user_libraries,
|
||||||
|
nd_list_playlists,
|
||||||
|
nd_create_playlist,
|
||||||
|
nd_update_playlist,
|
||||||
|
nd_delete_playlist,
|
||||||
search_radio_browser,
|
search_radio_browser,
|
||||||
get_top_radio_stations,
|
get_top_radio_stations,
|
||||||
fetch_url_bytes,
|
fetch_url_bytes,
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
import { invoke } from '@tauri-apps/api/core';
|
||||||
|
import { useAuthStore } from '../store/authStore';
|
||||||
|
import { ndLogin } from './navidromeAdmin';
|
||||||
|
|
||||||
|
export type SmartRuleOperator =
|
||||||
|
| 'is'
|
||||||
|
| 'isNot'
|
||||||
|
| 'contains'
|
||||||
|
| 'notContains'
|
||||||
|
| 'startsWith'
|
||||||
|
| 'endsWith'
|
||||||
|
| 'gt'
|
||||||
|
| 'lt'
|
||||||
|
| 'inTheRange';
|
||||||
|
|
||||||
|
export interface SmartRuleCondition {
|
||||||
|
field: string;
|
||||||
|
operator: SmartRuleOperator;
|
||||||
|
value: string | number | boolean | [number, number];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NdSmartPlaylist {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
songCount: number;
|
||||||
|
duration?: number;
|
||||||
|
rules?: Record<string, unknown>;
|
||||||
|
sync?: boolean;
|
||||||
|
updatedAt?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
let authCache: {
|
||||||
|
key: string;
|
||||||
|
token: string;
|
||||||
|
expiresAt: number;
|
||||||
|
} | null = null;
|
||||||
|
|
||||||
|
async function getNavidromeAuth(): Promise<{ serverUrl: string; token: string }> {
|
||||||
|
const s = useAuthStore.getState();
|
||||||
|
const server = s.getActiveServer();
|
||||||
|
const serverUrl = s.getBaseUrl();
|
||||||
|
if (!serverUrl || !server?.username || !server?.password) {
|
||||||
|
throw new Error('No active server credentials');
|
||||||
|
}
|
||||||
|
const key = `${serverUrl}|${server.username}|${server.password}`;
|
||||||
|
if (authCache && authCache.key === key && Date.now() < authCache.expiresAt) {
|
||||||
|
return { serverUrl, token: authCache.token };
|
||||||
|
}
|
||||||
|
const login = await ndLogin(serverUrl, server.username, server.password);
|
||||||
|
authCache = {
|
||||||
|
key,
|
||||||
|
token: login.token,
|
||||||
|
expiresAt: Date.now() + 10 * 60 * 1000,
|
||||||
|
};
|
||||||
|
return { serverUrl, token: login.token };
|
||||||
|
}
|
||||||
|
|
||||||
|
function conditionToRule(c: SmartRuleCondition): Record<string, unknown> {
|
||||||
|
return { [c.operator]: { [c.field]: c.value } };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildSmartRules(conditions: SmartRuleCondition[], opts?: { limit?: number; sort?: string }) {
|
||||||
|
const all = conditions.map(conditionToRule);
|
||||||
|
const rules: Record<string, unknown> = { all };
|
||||||
|
if (typeof opts?.limit === 'number' && opts.limit > 0) rules.limit = opts.limit;
|
||||||
|
if (opts?.sort) rules.sort = opts.sort;
|
||||||
|
return rules;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function ndListSmartPlaylists(): Promise<NdSmartPlaylist[]> {
|
||||||
|
const { serverUrl, token } = await getNavidromeAuth();
|
||||||
|
const raw = await invoke<unknown>('nd_list_playlists', { serverUrl, token, smart: true });
|
||||||
|
const list = Array.isArray(raw)
|
||||||
|
? raw
|
||||||
|
: (raw && typeof raw === 'object' && Array.isArray((raw as { items?: unknown[] }).items))
|
||||||
|
? (raw as { items: unknown[] }).items
|
||||||
|
: [];
|
||||||
|
return list.map((v) => {
|
||||||
|
const o = (v as Record<string, unknown>) ?? {};
|
||||||
|
return {
|
||||||
|
id: String(o.id ?? ''),
|
||||||
|
name: String(o.name ?? ''),
|
||||||
|
songCount: Number(o.songCount ?? 0),
|
||||||
|
duration: typeof o.duration === 'number' ? o.duration : undefined,
|
||||||
|
rules: typeof o.rules === 'object' && o.rules ? (o.rules as Record<string, unknown>) : undefined,
|
||||||
|
sync: typeof o.sync === 'boolean' ? o.sync : undefined,
|
||||||
|
updatedAt: typeof o.updatedAt === 'string' ? o.updatedAt : undefined,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function ndCreateSmartPlaylist(name: string, rules: Record<string, unknown>, sync = true): Promise<NdSmartPlaylist> {
|
||||||
|
const { serverUrl, token } = await getNavidromeAuth();
|
||||||
|
const raw = await invoke<unknown>('nd_create_playlist', {
|
||||||
|
serverUrl,
|
||||||
|
token,
|
||||||
|
body: { name, rules, sync },
|
||||||
|
});
|
||||||
|
const o = (raw as Record<string, unknown>) ?? {};
|
||||||
|
return {
|
||||||
|
id: String(o.id ?? ''),
|
||||||
|
name: String(o.name ?? name),
|
||||||
|
songCount: Number(o.songCount ?? 0),
|
||||||
|
duration: typeof o.duration === 'number' ? o.duration : undefined,
|
||||||
|
rules: typeof o.rules === 'object' && o.rules ? (o.rules as Record<string, unknown>) : undefined,
|
||||||
|
sync: typeof o.sync === 'boolean' ? o.sync : undefined,
|
||||||
|
updatedAt: typeof o.updatedAt === 'string' ? o.updatedAt : undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function ndDeletePlaylist(id: string): Promise<void> {
|
||||||
|
const { serverUrl, token } = await getNavidromeAuth();
|
||||||
|
await invoke('nd_delete_playlist', { serverUrl, token, id });
|
||||||
|
}
|
||||||
+25
-1
@@ -499,6 +499,30 @@ export async function getRandomSongs(size = 50, genre?: string, timeout = 15000)
|
|||||||
return data.randomSongs?.song ?? [];
|
return data.randomSongs?.song ?? [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface RandomSongsFilters {
|
||||||
|
size?: number;
|
||||||
|
genre?: string;
|
||||||
|
fromYear?: number;
|
||||||
|
toYear?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Extended random song fetch with server-side year/genre filtering. */
|
||||||
|
export async function getRandomSongsFiltered(
|
||||||
|
filters: RandomSongsFilters,
|
||||||
|
timeout = 15000,
|
||||||
|
): Promise<SubsonicSong[]> {
|
||||||
|
const params: Record<string, string | number> = {
|
||||||
|
size: filters.size ?? 50,
|
||||||
|
_t: Date.now(),
|
||||||
|
...libraryFilterParams(),
|
||||||
|
};
|
||||||
|
if (filters.genre) params.genre = filters.genre;
|
||||||
|
if (typeof filters.fromYear === 'number') params.fromYear = filters.fromYear;
|
||||||
|
if (typeof filters.toYear === 'number') params.toYear = filters.toYear;
|
||||||
|
const data = await api<{ randomSongs: { song: SubsonicSong[] } }>('getRandomSongs.view', params, timeout);
|
||||||
|
return data.randomSongs?.song ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
export async function getSong(id: string): Promise<SubsonicSong | null> {
|
export async function getSong(id: string): Promise<SubsonicSong | null> {
|
||||||
try {
|
try {
|
||||||
const data = await api<{ song: SubsonicSong }>('getSong.view', { id });
|
const data = await api<{ song: SubsonicSong }>('getSong.view', { id });
|
||||||
@@ -995,7 +1019,7 @@ export function buildDownloadUrl(id: string): string {
|
|||||||
|
|
||||||
// ─── Playlists ────────────────────────────────────────────────
|
// ─── Playlists ────────────────────────────────────────────────
|
||||||
export async function getPlaylists(): Promise<SubsonicPlaylist[]> {
|
export async function getPlaylists(): Promise<SubsonicPlaylist[]> {
|
||||||
const data = await api<{ playlists: { playlist: SubsonicPlaylist[] } }>('getPlaylists.view');
|
const data = await api<{ playlists: { playlist: SubsonicPlaylist[] } }>('getPlaylists.view', { _t: Date.now() });
|
||||||
return data.playlists?.playlist ?? [];
|
return data.playlists?.playlist ?? [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import { useTranslation } from 'react-i18next';
|
|||||||
import {
|
import {
|
||||||
Settings,
|
Settings,
|
||||||
PanelLeftClose, PanelLeft, AudioLines, HardDriveDownload, HardDriveUpload,
|
PanelLeftClose, PanelLeft, AudioLines, HardDriveDownload, HardDriveUpload,
|
||||||
ChevronDown, Check, Music2, X, ChevronRight, PlayCircle, Trash2,
|
ChevronDown, Check, Music2, X, ChevronRight, PlayCircle, Sparkles, Trash2,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import PsysonicLogo from './PsysonicLogo';
|
import PsysonicLogo from './PsysonicLogo';
|
||||||
import PSmallLogo from './PSmallLogo';
|
import PSmallLogo from './PSmallLogo';
|
||||||
@@ -31,6 +31,17 @@ import { useLuckyMixAvailable } from '../hooks/useLuckyMixAvailable';
|
|||||||
|
|
||||||
const SIDEBAR_NAV_LONG_PRESS_MS = 1000;
|
const SIDEBAR_NAV_LONG_PRESS_MS = 1000;
|
||||||
const SIDEBAR_NAV_LONG_PRESS_MOVE_CANCEL_PX = 10;
|
const SIDEBAR_NAV_LONG_PRESS_MOVE_CANCEL_PX = 10;
|
||||||
|
const SMART_PREFIX = 'psy-smart-';
|
||||||
|
|
||||||
|
function isSmartPlaylistName(name: string): boolean {
|
||||||
|
return (name ?? '').toLowerCase().startsWith(SMART_PREFIX);
|
||||||
|
}
|
||||||
|
|
||||||
|
function displayPlaylistName(name: string): string {
|
||||||
|
const n = name ?? '';
|
||||||
|
if (isSmartPlaylistName(n)) return n.slice(SMART_PREFIX.length);
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
function isPointerOutsideAsideSidebar(clientX: number, clientY: number): boolean {
|
function isPointerOutsideAsideSidebar(clientX: number, clientY: number): boolean {
|
||||||
const aside = document.querySelector('aside.sidebar');
|
const aside = document.querySelector('aside.sidebar');
|
||||||
@@ -569,11 +580,11 @@ export default function Sidebar({
|
|||||||
key={pl.id}
|
key={pl.id}
|
||||||
to={`/playlists/${pl.id}`}
|
to={`/playlists/${pl.id}`}
|
||||||
className={({ isActive }) => `nav-link sidebar-playlist-item ${isActive ? 'active' : ''}`}
|
className={({ isActive }) => `nav-link sidebar-playlist-item ${isActive ? 'active' : ''}`}
|
||||||
data-tooltip={isCollapsed ? pl.name : undefined}
|
data-tooltip={isCollapsed ? displayPlaylistName(pl.name) : undefined}
|
||||||
data-tooltip-pos="bottom"
|
data-tooltip-pos="bottom"
|
||||||
>
|
>
|
||||||
<PlayCircle size={12} />
|
{isSmartPlaylistName(pl.name) ? <Sparkles size={12} /> : <PlayCircle size={12} />}
|
||||||
<span>{pl.name}</span>
|
<span>{displayPlaylistName(pl.name)}</span>
|
||||||
</NavLink>
|
</NavLink>
|
||||||
))
|
))
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ export const enTranslation = {
|
|||||||
offlineLibrary: 'Offline Library',
|
offlineLibrary: 'Offline Library',
|
||||||
genres: 'Genres',
|
genres: 'Genres',
|
||||||
playlists: 'Playlists',
|
playlists: 'Playlists',
|
||||||
|
smartPlaylists: 'Smart Playlists',
|
||||||
mostPlayed: 'Most Played',
|
mostPlayed: 'Most Played',
|
||||||
radio: 'Internet Radio',
|
radio: 'Internet Radio',
|
||||||
folderBrowser: 'Folder Browser',
|
folderBrowser: 'Folder Browser',
|
||||||
@@ -1317,6 +1318,50 @@ export const enTranslation = {
|
|||||||
csvImportDownloadSuccess: 'Report downloaded successfully',
|
csvImportDownloadSuccess: 'Report downloaded successfully',
|
||||||
csvImportDownloadError: 'Failed to download report',
|
csvImportDownloadError: 'Failed to download report',
|
||||||
},
|
},
|
||||||
|
smartPlaylists: {
|
||||||
|
title: 'Smart Playlists',
|
||||||
|
empty: 'No smart playlists yet.',
|
||||||
|
sectionBasic: '1. Basic',
|
||||||
|
sectionGenres: '2. Genres',
|
||||||
|
sectionYearsAndFilters: '3. Years and filters',
|
||||||
|
genreMode: 'Genre mode',
|
||||||
|
genreModeInclude: 'Include genres',
|
||||||
|
genreModeExclude: 'Exclude genres',
|
||||||
|
genreSearchPlaceholder: 'Filter genres...',
|
||||||
|
availableGenres: 'Available',
|
||||||
|
selectedGenres: 'Selected',
|
||||||
|
yearMode: 'Year mode',
|
||||||
|
yearModeInclude: 'Include range',
|
||||||
|
yearModeExclude: 'Exclude range',
|
||||||
|
name: 'Name (without prefix)',
|
||||||
|
anyGenre: 'Any genre',
|
||||||
|
limit: 'Limit',
|
||||||
|
limitHint: 'How many tracks to include in playlist (1-{{max}}, usually 50).',
|
||||||
|
artistContains: 'Artist contains…',
|
||||||
|
albumContains: 'Album contains…',
|
||||||
|
titleContains: 'Title contains…',
|
||||||
|
minRating: 'Minimum rating',
|
||||||
|
minRatingAria: 'Minimum rating for smart playlist',
|
||||||
|
minRatingHint: '0 disables minimum threshold; 1-5 keeps tracks with rating above selected value.',
|
||||||
|
fromYear: 'From year',
|
||||||
|
toYear: 'To year',
|
||||||
|
excludeUnrated: 'Exclude unrated tracks',
|
||||||
|
compilationOnly: 'Only compilations',
|
||||||
|
create: 'New Smart Playlist',
|
||||||
|
created: 'Created {{name}}',
|
||||||
|
createFailed: 'Could not create smart playlist.',
|
||||||
|
deleted: 'Deleted {{name}}',
|
||||||
|
deleteFailed: 'Could not delete smart playlist.',
|
||||||
|
navidromeOnly: 'Smart playlists can only be created on Navidrome servers.',
|
||||||
|
loadFailed: 'Could not load smart playlists from Navidrome.',
|
||||||
|
liveBadge: 'live',
|
||||||
|
sortRandom: 'Sort: random',
|
||||||
|
sortTitleAsc: 'Sort: title A-Z',
|
||||||
|
sortTitleDesc: 'Sort: title Z-A',
|
||||||
|
sortYearDesc: 'Sort: year desc',
|
||||||
|
sortYearAsc: 'Sort: year asc',
|
||||||
|
sortPlayCountDesc: 'Sort: play count desc',
|
||||||
|
},
|
||||||
mostPlayed: {
|
mostPlayed: {
|
||||||
title: 'Most Played',
|
title: 'Most Played',
|
||||||
topArtists: 'Top Artists',
|
topArtists: 'Top Artists',
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ export const ruTranslation = {
|
|||||||
offlineLibrary: 'Офлайн-библиотека',
|
offlineLibrary: 'Офлайн-библиотека',
|
||||||
genres: 'Жанры',
|
genres: 'Жанры',
|
||||||
playlists: 'Плейлисты',
|
playlists: 'Плейлисты',
|
||||||
|
smartPlaylists: 'Смарт-плейлисты',
|
||||||
mostPlayed: 'Популярное',
|
mostPlayed: 'Популярное',
|
||||||
radio: 'Онлайн-радио',
|
radio: 'Онлайн-радио',
|
||||||
folderBrowser: 'Браузер папок',
|
folderBrowser: 'Браузер папок',
|
||||||
@@ -1381,6 +1382,50 @@ export const ruTranslation = {
|
|||||||
csvImportDownloadSuccess: 'Отчёт успешно скачан',
|
csvImportDownloadSuccess: 'Отчёт успешно скачан',
|
||||||
csvImportDownloadError: 'Не удалось скачать отчёт',
|
csvImportDownloadError: 'Не удалось скачать отчёт',
|
||||||
},
|
},
|
||||||
|
smartPlaylists: {
|
||||||
|
title: 'Смарт-плейлисты',
|
||||||
|
empty: 'Смарт-плейлистов пока нет.',
|
||||||
|
sectionBasic: '1. База',
|
||||||
|
sectionGenres: '2. Жанры',
|
||||||
|
sectionYearsAndFilters: '3. Годы и фильтры',
|
||||||
|
genreMode: 'Режим жанров',
|
||||||
|
genreModeInclude: 'Включить жанры',
|
||||||
|
genreModeExclude: 'Исключить жанры',
|
||||||
|
genreSearchPlaceholder: 'Фильтр жанров...',
|
||||||
|
availableGenres: 'Доступные',
|
||||||
|
selectedGenres: 'Выбранные',
|
||||||
|
yearMode: 'Режим годов',
|
||||||
|
yearModeInclude: 'Включить диапазон',
|
||||||
|
yearModeExclude: 'Исключить диапазон',
|
||||||
|
name: 'Название (без префикса)',
|
||||||
|
anyGenre: 'Любой жанр',
|
||||||
|
limit: 'Лимит',
|
||||||
|
limitHint: 'Сколько треков включать в плейлист (1-{{max}}, обычно 50).',
|
||||||
|
artistContains: 'Исполнитель содержит…',
|
||||||
|
albumContains: 'Альбом содержит…',
|
||||||
|
titleContains: 'Название содержит…',
|
||||||
|
minRating: 'Мин. рейтинг',
|
||||||
|
minRatingAria: 'Минимальный рейтинг для смарт-плейлиста',
|
||||||
|
minRatingHint: '0 — без минимального порога; 1-5 — оставить треки с рейтингом выше выбранного.',
|
||||||
|
fromYear: 'Год от',
|
||||||
|
toYear: 'Год до',
|
||||||
|
excludeUnrated: 'Исключить треки без рейтинга',
|
||||||
|
compilationOnly: 'Только сборники',
|
||||||
|
create: 'Создать смарт-плейлист',
|
||||||
|
created: 'Создан {{name}}',
|
||||||
|
createFailed: 'Не удалось создать смарт-плейлист.',
|
||||||
|
deleted: 'Удалён {{name}}',
|
||||||
|
deleteFailed: 'Не удалось удалить смарт-плейлист.',
|
||||||
|
navidromeOnly: 'Смарт-плейлисты можно создавать только на серверах Navidrome.',
|
||||||
|
loadFailed: 'Не удалось загрузить смарт-плейлисты из Navidrome.',
|
||||||
|
liveBadge: 'live',
|
||||||
|
sortRandom: 'Сортировка: случайно',
|
||||||
|
sortTitleAsc: 'Сортировка: название А-Я',
|
||||||
|
sortTitleDesc: 'Сортировка: название Я-А',
|
||||||
|
sortYearDesc: 'Сортировка: год по убыванию',
|
||||||
|
sortYearAsc: 'Сортировка: год по возрастанию',
|
||||||
|
sortPlayCountDesc: 'Сортировка: прослушивания по убыванию',
|
||||||
|
},
|
||||||
mostPlayed: {
|
mostPlayed: {
|
||||||
title: 'Популярное',
|
title: 'Популярное',
|
||||||
topArtists: 'Топ исполнителей',
|
topArtists: 'Топ исполнителей',
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { useEffect, useState, useRef, useCallback, useMemo } from 'react';
|
import React, { useEffect, useState, useRef, useCallback, useMemo } from 'react';
|
||||||
import { createPortal } from 'react-dom';
|
import { createPortal } from 'react-dom';
|
||||||
import { useParams, useNavigate } from 'react-router-dom';
|
import { useParams, useNavigate } from 'react-router-dom';
|
||||||
import { ChevronDown, ChevronLeft, Play, ListPlus, Trash2, Search, X, Loader2, Plus, GripVertical, Star, RefreshCw, Shuffle, Heart, HardDriveDownload, Check, Pencil, Globe, Lock, Camera, Download, FileUp, RotateCcw } from 'lucide-react';
|
import { ChevronDown, ChevronLeft, Play, ListPlus, Trash2, Search, X, Loader2, Plus, GripVertical, Star, RefreshCw, Shuffle, Heart, HardDriveDownload, Check, Pencil, Globe, Lock, Camera, Download, FileUp, RotateCcw, Sparkles } from 'lucide-react';
|
||||||
import { useTracklistColumns, type ColDef } from '../utils/useTracklistColumns';
|
import { useTracklistColumns, type ColDef } from '../utils/useTracklistColumns';
|
||||||
import { AddToPlaylistSubmenu } from '../components/ContextMenu';
|
import { AddToPlaylistSubmenu } from '../components/ContextMenu';
|
||||||
import {
|
import {
|
||||||
@@ -55,6 +55,18 @@ function totalDurationLabel(songs: SubsonicSong[]): string {
|
|||||||
return formatHumanHoursMinutes(total);
|
return formatHumanHoursMinutes(total);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const SMART_PREFIX = 'psy-smart-';
|
||||||
|
|
||||||
|
function isSmartPlaylistName(name: string): boolean {
|
||||||
|
return (name ?? '').toLowerCase().startsWith(SMART_PREFIX);
|
||||||
|
}
|
||||||
|
|
||||||
|
function displayPlaylistName(name: string): string {
|
||||||
|
const n = name ?? '';
|
||||||
|
if (isSmartPlaylistName(n)) return n.slice(SMART_PREFIX.length);
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
function codecLabel(song: SubsonicSong, showBitrate: boolean): string {
|
function codecLabel(song: SubsonicSong, showBitrate: boolean): string {
|
||||||
const parts: string[] = [];
|
const parts: string[] = [];
|
||||||
if (song.suffix) parts.push(song.suffix.toUpperCase());
|
if (song.suffix) parts.push(song.suffix.toUpperCase());
|
||||||
@@ -1146,7 +1158,10 @@ export default function PlaylistDetail() {
|
|||||||
<div className="album-detail-meta">
|
<div className="album-detail-meta">
|
||||||
<>
|
<>
|
||||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||||
<h1 className="album-detail-title" style={{ marginBottom: 0, marginTop: 6 }}>{playlist.name}</h1>
|
<h1 className="album-detail-title" style={{ marginBottom: 0, marginTop: 6, display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||||
|
{isSmartPlaylistName(playlist.name) && <Sparkles size={16} style={{ color: 'var(--text-muted)' }} />}
|
||||||
|
<span>{displayPlaylistName(playlist.name)}</span>
|
||||||
|
</h1>
|
||||||
<button
|
<button
|
||||||
className="btn btn-ghost"
|
className="btn btn-ghost"
|
||||||
onClick={() => setEditingMeta(true)}
|
onClick={() => setEditingMeta(true)}
|
||||||
|
|||||||
+427
-8
@@ -1,18 +1,84 @@
|
|||||||
import React, { useEffect, useState, useRef, useCallback } from 'react';
|
import React, { useEffect, useState, useRef, useCallback } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import { ListMusic, Play, Plus, Trash2, X, CheckSquare2, Check } from 'lucide-react';
|
import { ListMusic, Play, Plus, Trash2, CheckSquare2, Check, Clock3, Sparkles } from 'lucide-react';
|
||||||
import { getPlaylists, deletePlaylist, SubsonicPlaylist, getPlaylist, buildCoverArtUrl, coverArtCacheKey, updatePlaylist } from '../api/subsonic';
|
import { deletePlaylist, SubsonicPlaylist, getPlaylist, buildCoverArtUrl, coverArtCacheKey, updatePlaylist, getGenres, SubsonicGenre } from '../api/subsonic';
|
||||||
import { usePlayerStore, songToTrack } from '../store/playerStore';
|
import { usePlayerStore, songToTrack } from '../store/playerStore';
|
||||||
import { usePlaylistStore } from '../store/playlistStore';
|
import { usePlaylistStore } from '../store/playlistStore';
|
||||||
|
import { useAuthStore } from '../store/authStore';
|
||||||
import CachedImage from '../components/CachedImage';
|
import CachedImage from '../components/CachedImage';
|
||||||
|
import StarRating from '../components/StarRating';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { formatHumanHoursMinutes } from '../utils/formatHumanDuration';
|
import { formatHumanHoursMinutes } from '../utils/formatHumanDuration';
|
||||||
import { showToast } from '../utils/toast';
|
import { showToast } from '../utils/toast';
|
||||||
|
import { ndCreateSmartPlaylist } from '../api/navidromeSmart';
|
||||||
|
|
||||||
function formatDuration(seconds: number): string {
|
function formatDuration(seconds: number): string {
|
||||||
return formatHumanHoursMinutes(seconds);
|
return formatHumanHoursMinutes(seconds);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const SMART_PREFIX = 'psy-smart-';
|
||||||
|
const LIMIT_MAX = 500;
|
||||||
|
const YEAR_MIN = 1950;
|
||||||
|
const YEAR_MAX = new Date().getFullYear() + 1;
|
||||||
|
|
||||||
|
type GenreMode = 'include' | 'exclude';
|
||||||
|
type YearMode = 'include' | 'exclude';
|
||||||
|
|
||||||
|
type SmartFilters = {
|
||||||
|
name: string;
|
||||||
|
limit: string;
|
||||||
|
sort: string;
|
||||||
|
artistContains: string;
|
||||||
|
albumContains: string;
|
||||||
|
titleContains: string;
|
||||||
|
minRating: number;
|
||||||
|
excludeUnrated: boolean;
|
||||||
|
compilationOnly: boolean;
|
||||||
|
selectedGenres: string[];
|
||||||
|
genreMode: GenreMode;
|
||||||
|
yearFrom: number;
|
||||||
|
yearTo: number;
|
||||||
|
yearMode: YearMode;
|
||||||
|
};
|
||||||
|
|
||||||
|
type PendingSmartPlaylist = {
|
||||||
|
name: string;
|
||||||
|
id?: string;
|
||||||
|
firstSeenCoverArt?: string;
|
||||||
|
attempts: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
const defaultSmartFilters: SmartFilters = {
|
||||||
|
name: '',
|
||||||
|
limit: '50',
|
||||||
|
sort: '+random',
|
||||||
|
artistContains: '',
|
||||||
|
albumContains: '',
|
||||||
|
titleContains: '',
|
||||||
|
minRating: 0,
|
||||||
|
excludeUnrated: false,
|
||||||
|
compilationOnly: false,
|
||||||
|
selectedGenres: [],
|
||||||
|
genreMode: 'include',
|
||||||
|
yearFrom: YEAR_MIN,
|
||||||
|
yearTo: YEAR_MAX,
|
||||||
|
yearMode: 'include',
|
||||||
|
};
|
||||||
|
|
||||||
|
function clampYear(v: number): number {
|
||||||
|
return Math.max(YEAR_MIN, Math.min(YEAR_MAX, v));
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSmartPlaylistName(name: string): boolean {
|
||||||
|
return (name ?? '').toLowerCase().startsWith(SMART_PREFIX);
|
||||||
|
}
|
||||||
|
|
||||||
|
function displayPlaylistName(name: string): string {
|
||||||
|
const n = name ?? '';
|
||||||
|
if (isSmartPlaylistName(n)) return n.slice(SMART_PREFIX.length);
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
export default function Playlists() {
|
export default function Playlists() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
@@ -23,10 +89,19 @@ export default function Playlists() {
|
|||||||
const playlists = usePlaylistStore((s) => s.playlists);
|
const playlists = usePlaylistStore((s) => s.playlists);
|
||||||
const fetchPlaylists = usePlaylistStore((s) => s.fetchPlaylists);
|
const fetchPlaylists = usePlaylistStore((s) => s.fetchPlaylists);
|
||||||
const playlistsLoading = usePlaylistStore((s) => s.playlistsLoading);
|
const playlistsLoading = usePlaylistStore((s) => s.playlistsLoading);
|
||||||
|
const activeUsername = useAuthStore(s => s.getActiveServer()?.username ?? '');
|
||||||
|
const activeServerId = useAuthStore(s => s.activeServerId);
|
||||||
|
const subsonicIdentityByServer = useAuthStore(s => s.subsonicServerIdentityByServer);
|
||||||
|
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [creating, setCreating] = useState(false);
|
const [creating, setCreating] = useState(false);
|
||||||
|
const [creatingSmart, setCreatingSmart] = useState(false);
|
||||||
const [newName, setNewName] = useState('');
|
const [newName, setNewName] = useState('');
|
||||||
|
const [smartFilters, setSmartFilters] = useState<SmartFilters>(defaultSmartFilters);
|
||||||
|
const [genres, setGenres] = useState<SubsonicGenre[]>([]);
|
||||||
|
const [genreQuery, setGenreQuery] = useState('');
|
||||||
|
const [creatingSmartBusy, setCreatingSmartBusy] = useState(false);
|
||||||
|
const [pendingSmart, setPendingSmart] = useState<PendingSmartPlaylist[]>([]);
|
||||||
const [playingId, setPlayingId] = useState<string | null>(null);
|
const [playingId, setPlayingId] = useState<string | null>(null);
|
||||||
const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);
|
const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);
|
||||||
const nameInputRef = useRef<HTMLInputElement>(null);
|
const nameInputRef = useRef<HTMLInputElement>(null);
|
||||||
@@ -34,6 +109,10 @@ export default function Playlists() {
|
|||||||
// ── Multi-selection ──────────────────────────────────────────────────────
|
// ── Multi-selection ──────────────────────────────────────────────────────
|
||||||
const [selectionMode, setSelectionMode] = useState(false);
|
const [selectionMode, setSelectionMode] = useState(false);
|
||||||
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
|
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
|
||||||
|
const isNavidromeServer = Boolean(
|
||||||
|
activeServerId &&
|
||||||
|
(subsonicIdentityByServer[activeServerId]?.type ?? '').toLowerCase() === 'navidrome',
|
||||||
|
);
|
||||||
|
|
||||||
const toggleSelectionMode = () => {
|
const toggleSelectionMode = () => {
|
||||||
setSelectionMode(v => !v);
|
setSelectionMode(v => !v);
|
||||||
@@ -54,9 +133,15 @@ export default function Playlists() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const selectedPlaylists = playlists.filter(p => selectedIds.has(p.id));
|
const selectedPlaylists = playlists.filter(p => selectedIds.has(p.id));
|
||||||
|
const isPlaylistDeletable = useCallback((pl: SubsonicPlaylist) => {
|
||||||
|
if (!pl.owner) return true;
|
||||||
|
if (!activeUsername) return false;
|
||||||
|
return pl.owner === activeUsername;
|
||||||
|
}, [activeUsername]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchPlaylists().finally(() => setLoading(false));
|
fetchPlaylists().finally(() => setLoading(false));
|
||||||
|
getGenres().then(setGenres).catch(() => {});
|
||||||
}, [fetchPlaylists]);
|
}, [fetchPlaylists]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -65,6 +150,12 @@ export default function Playlists() {
|
|||||||
|
|
||||||
const createPlaylist = usePlaylistStore(s => s.createPlaylist);
|
const createPlaylist = usePlaylistStore(s => s.createPlaylist);
|
||||||
|
|
||||||
|
const availableGenres = genres
|
||||||
|
.map(g => g.value)
|
||||||
|
.filter(v => !smartFilters.selectedGenres.includes(v))
|
||||||
|
.filter(v => !genreQuery.trim() || v.toLowerCase().includes(genreQuery.trim().toLowerCase()))
|
||||||
|
.sort((a, b) => a.localeCompare(b));
|
||||||
|
|
||||||
const handleCreate = async () => {
|
const handleCreate = async () => {
|
||||||
const name = newName.trim() || t('playlists.unnamed');
|
const name = newName.trim() || t('playlists.unnamed');
|
||||||
await createPlaylist(name);
|
await createPlaylist(name);
|
||||||
@@ -74,6 +165,143 @@ export default function Playlists() {
|
|||||||
setNewName('');
|
setNewName('');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const buildSmartRulesPayload = (): Record<string, unknown> => {
|
||||||
|
const all: Record<string, unknown>[] = [];
|
||||||
|
if (smartFilters.artistContains.trim()) all.push({ contains: { artist: smartFilters.artistContains.trim() } });
|
||||||
|
if (smartFilters.albumContains.trim()) all.push({ contains: { album: smartFilters.albumContains.trim() } });
|
||||||
|
if (smartFilters.titleContains.trim()) all.push({ contains: { title: smartFilters.titleContains.trim() } });
|
||||||
|
|
||||||
|
const minRating = Number(smartFilters.minRating);
|
||||||
|
if (Number.isFinite(minRating) && minRating > 0) all.push({ gt: { rating: minRating } });
|
||||||
|
else if (smartFilters.excludeUnrated) all.push({ gt: { rating: 0 } });
|
||||||
|
if (smartFilters.compilationOnly) all.push({ is: { compilation: true } });
|
||||||
|
|
||||||
|
if (smartFilters.selectedGenres.length > 0) {
|
||||||
|
if (smartFilters.genreMode === 'include') {
|
||||||
|
all.push({ any: smartFilters.selectedGenres.map(v => ({ contains: { genre: v } })) });
|
||||||
|
} else {
|
||||||
|
for (const g of smartFilters.selectedGenres) all.push({ notContains: { genre: g } });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (smartFilters.yearMode === 'include') {
|
||||||
|
all.push({ inTheRange: { year: [smartFilters.yearFrom, smartFilters.yearTo] } });
|
||||||
|
} else {
|
||||||
|
all.push({ any: [{ lt: { year: smartFilters.yearFrom } }, { gt: { year: smartFilters.yearTo } }] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const rules: Record<string, unknown> = { all };
|
||||||
|
rules.limit = Math.max(1, Math.min(LIMIT_MAX, Number(smartFilters.limit) || 50));
|
||||||
|
rules.sort = smartFilters.sort;
|
||||||
|
return rules;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCreateSmart = async () => {
|
||||||
|
if (!isNavidromeServer) {
|
||||||
|
showToast(t('smartPlaylists.navidromeOnly'), 3500, 'error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setCreatingSmartBusy(true);
|
||||||
|
try {
|
||||||
|
const baseName = smartFilters.name.trim() || `mix-${new Date().toISOString().slice(0, 10)}`;
|
||||||
|
const rules = buildSmartRulesPayload();
|
||||||
|
await ndCreateSmartPlaylist(`${SMART_PREFIX}${baseName}`, rules, true);
|
||||||
|
await fetchPlaylists();
|
||||||
|
const createdName = `${SMART_PREFIX}${baseName}`;
|
||||||
|
setPendingSmart(prev => {
|
||||||
|
const existing = prev.find(p => p.name === createdName);
|
||||||
|
if (existing) return prev;
|
||||||
|
const created = usePlaylistStore.getState().playlists.find(p => p.name === createdName);
|
||||||
|
return [
|
||||||
|
...prev,
|
||||||
|
{
|
||||||
|
name: createdName,
|
||||||
|
id: created?.id,
|
||||||
|
firstSeenCoverArt: created?.coverArt,
|
||||||
|
attempts: 0,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
});
|
||||||
|
setCreatingSmart(false);
|
||||||
|
setSmartFilters(defaultSmartFilters);
|
||||||
|
setGenreQuery('');
|
||||||
|
showToast(t('smartPlaylists.created', { name: createdName }), 3500, 'success');
|
||||||
|
} catch {
|
||||||
|
showToast(t('smartPlaylists.createFailed'), 3500, 'error');
|
||||||
|
} finally {
|
||||||
|
setCreatingSmartBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Smart playlist rules are processed asynchronously on server.
|
||||||
|
// Poll list every 10s and keep waiting through Navidrome placeholder cover.
|
||||||
|
useEffect(() => {
|
||||||
|
if (pendingSmart.length === 0) return;
|
||||||
|
const interval = window.setInterval(async () => {
|
||||||
|
await fetchPlaylists();
|
||||||
|
const listNow = usePlaylistStore.getState().playlists;
|
||||||
|
const hydrated = pendingSmart.map(item => {
|
||||||
|
if (item.id) return item;
|
||||||
|
const found = listNow.find(p => p.name === item.name);
|
||||||
|
return found ? { ...item, id: found.id } : item;
|
||||||
|
});
|
||||||
|
// Detail endpoint tends to reflect fresh metadata earlier than list endpoint.
|
||||||
|
const ids = hydrated.map(p => p.id).filter((v): v is string => Boolean(v));
|
||||||
|
const details = await Promise.all(
|
||||||
|
ids.map(async (id) => {
|
||||||
|
try {
|
||||||
|
const { playlist } = await getPlaylist(id);
|
||||||
|
return playlist;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const freshById = new Map(
|
||||||
|
details.filter((p): p is SubsonicPlaylist => p !== null).map(p => [p.id, p]),
|
||||||
|
);
|
||||||
|
if (freshById.size > 0) {
|
||||||
|
usePlaylistStore.setState((s) => ({
|
||||||
|
playlists: s.playlists.map((p) => {
|
||||||
|
const fresh = freshById.get(p.id);
|
||||||
|
return fresh ? { ...p, ...fresh } : p;
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
const current = usePlaylistStore.getState().playlists;
|
||||||
|
setPendingSmart(() => {
|
||||||
|
const next: PendingSmartPlaylist[] = [];
|
||||||
|
for (const item of hydrated) {
|
||||||
|
const pl = item.id
|
||||||
|
? current.find(p => p.id === item.id)
|
||||||
|
: current.find(p => p.name === item.name);
|
||||||
|
if (!pl) {
|
||||||
|
next.push({ ...item, attempts: item.attempts + 1 });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const songCount = pl.songCount ?? 0;
|
||||||
|
const currentCover = pl.coverArt;
|
||||||
|
const firstCover = item.firstSeenCoverArt ?? currentCover;
|
||||||
|
const placeholderStillThere = Boolean(firstCover) && currentCover === firstCover;
|
||||||
|
// Wait until we see actual content and cover changed from the first placeholder-ish cover.
|
||||||
|
// Fallback timeout keeps UI from waiting forever on servers that never update cover id.
|
||||||
|
const hardTimeoutReached = item.attempts >= 18; // ~3 minutes (18 * 10s)
|
||||||
|
const ready = songCount > 0 && (!placeholderStillThere || hardTimeoutReached);
|
||||||
|
if (!ready) {
|
||||||
|
next.push({
|
||||||
|
...item,
|
||||||
|
id: pl.id,
|
||||||
|
firstSeenCoverArt: firstCover,
|
||||||
|
attempts: item.attempts + 1,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}, 10000);
|
||||||
|
return () => window.clearInterval(interval);
|
||||||
|
}, [pendingSmart, fetchPlaylists]);
|
||||||
|
|
||||||
const handlePlay = async (e: React.MouseEvent, pl: SubsonicPlaylist) => {
|
const handlePlay = async (e: React.MouseEvent, pl: SubsonicPlaylist) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
if (playingId === pl.id) return;
|
if (playingId === pl.id) return;
|
||||||
@@ -93,6 +321,10 @@ export default function Playlists() {
|
|||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
if (deleteConfirmId !== pl.id) {
|
if (deleteConfirmId !== pl.id) {
|
||||||
setDeleteConfirmId(pl.id);
|
setDeleteConfirmId(pl.id);
|
||||||
|
const btn = e.currentTarget as HTMLElement;
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
btn.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
|
||||||
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@@ -109,9 +341,10 @@ export default function Playlists() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleDeleteSelected = async () => {
|
const handleDeleteSelected = async () => {
|
||||||
if (selectedPlaylists.length === 0) return;
|
const deletable = selectedPlaylists.filter(isPlaylistDeletable);
|
||||||
|
if (deletable.length === 0) return;
|
||||||
let deleted = 0;
|
let deleted = 0;
|
||||||
for (const pl of selectedPlaylists) {
|
for (const pl of deletable) {
|
||||||
try {
|
try {
|
||||||
await deletePlaylist(pl.id);
|
await deletePlaylist(pl.id);
|
||||||
removeId(pl.id);
|
removeId(pl.id);
|
||||||
@@ -121,7 +354,7 @@ export default function Playlists() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
usePlaylistStore.setState((s) => ({
|
usePlaylistStore.setState((s) => ({
|
||||||
playlists: s.playlists.filter((p) => !selectedIds.has(p.id)),
|
playlists: s.playlists.filter((p) => !(selectedIds.has(p.id) && isPlaylistDeletable(p))),
|
||||||
}));
|
}));
|
||||||
clearSelection();
|
clearSelection();
|
||||||
if (deleted > 0) {
|
if (deleted > 0) {
|
||||||
@@ -169,6 +402,49 @@ export default function Playlists() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="content-body animate-fade-in">
|
<div className="content-body animate-fade-in">
|
||||||
|
<style>{`
|
||||||
|
.dual-year-range {
|
||||||
|
position: relative;
|
||||||
|
height: 34px;
|
||||||
|
}
|
||||||
|
.dual-year-range__track,
|
||||||
|
.dual-year-range__selected {
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
top: 50%;
|
||||||
|
height: 4px;
|
||||||
|
transform: translateY(-50%);
|
||||||
|
border-radius: 999px;
|
||||||
|
}
|
||||||
|
.dual-year-range__track { background: var(--border); }
|
||||||
|
.dual-year-range__selected { background: var(--accent); }
|
||||||
|
.dual-year-range input[type='range'] {
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
top: 0;
|
||||||
|
width: 100%;
|
||||||
|
height: 34px;
|
||||||
|
margin: 0;
|
||||||
|
background: transparent;
|
||||||
|
-webkit-appearance: none;
|
||||||
|
appearance: none;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
.dual-year-range input[type='range']::-webkit-slider-runnable-track { height: 4px; background: transparent; }
|
||||||
|
.dual-year-range input[type='range']::-webkit-slider-thumb {
|
||||||
|
-webkit-appearance: none;
|
||||||
|
appearance: none;
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
margin-top: -5px;
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
background: var(--bg-card);
|
||||||
|
pointer-events: auto;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
`}</style>
|
||||||
|
|
||||||
{/* ── Header row ── */}
|
{/* ── Header row ── */}
|
||||||
<div className="playlists-header">
|
<div className="playlists-header">
|
||||||
@@ -201,10 +477,15 @@ export default function Playlists() {
|
|||||||
</button>
|
</button>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<button className="btn btn-primary" onClick={() => setCreating(true)}>
|
<button className="btn btn-primary" onClick={() => { setCreatingSmart(false); setCreating(true); }}>
|
||||||
<Plus size={15} /> {t('playlists.newPlaylist')}
|
<Plus size={15} /> {t('playlists.newPlaylist')}
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{!creating && isNavidromeServer && (
|
||||||
|
<button className="btn btn-surface" onClick={() => { setCreating(false); setCreatingSmart(v => !v); }}>
|
||||||
|
<Plus size={15} /> {t('smartPlaylists.create')}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<button
|
<button
|
||||||
@@ -219,6 +500,99 @@ export default function Playlists() {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{creatingSmart && (
|
||||||
|
<div style={{ marginBottom: '1rem', border: '1px solid var(--border)', borderRadius: 'var(--radius)', padding: '0.9rem', background: 'var(--bg-card)' }}>
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
|
||||||
|
<section style={{ border: '1px solid var(--border)', borderRadius: 'var(--radius-sm)', padding: '0.75rem' }}>
|
||||||
|
<div style={{ fontSize: 13, fontWeight: 600, marginBottom: '0.65rem' }}>{t('smartPlaylists.sectionBasic')}</div>
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.65rem' }}>
|
||||||
|
<input className="input" placeholder={t('smartPlaylists.name')} value={smartFilters.name} onChange={e => setSmartFilters(v => ({ ...v, name: e.target.value }))} />
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.35rem' }}>
|
||||||
|
<input className="input" type="number" min={1} max={LIMIT_MAX} placeholder={t('smartPlaylists.limit')} value={smartFilters.limit} onChange={e => setSmartFilters(v => ({ ...v, limit: e.target.value }))} />
|
||||||
|
<span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{t('smartPlaylists.limitHint', { max: LIMIT_MAX })}</span>
|
||||||
|
</div>
|
||||||
|
<select className="input" value={smartFilters.sort} onChange={e => setSmartFilters(v => ({ ...v, sort: e.target.value }))}>
|
||||||
|
<option value="+random">{t('smartPlaylists.sortRandom')}</option>
|
||||||
|
<option value="+title">{t('smartPlaylists.sortTitleAsc')}</option>
|
||||||
|
<option value="-title">{t('smartPlaylists.sortTitleDesc')}</option>
|
||||||
|
<option value="-year">{t('smartPlaylists.sortYearDesc')}</option>
|
||||||
|
<option value="+year">{t('smartPlaylists.sortYearAsc')}</option>
|
||||||
|
<option value="-playcount">{t('smartPlaylists.sortPlayCountDesc')}</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<section style={{ border: '1px solid var(--border)', borderRadius: 'var(--radius-sm)', padding: '0.75rem' }}>
|
||||||
|
<div style={{ fontSize: 13, fontWeight: 600, marginBottom: '0.65rem' }}>{t('smartPlaylists.sectionGenres')}</div>
|
||||||
|
<div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', marginBottom: '0.75rem', flexWrap: 'wrap' }}>
|
||||||
|
<span style={{ fontSize: 13, color: 'var(--text-muted)' }}>{t('smartPlaylists.genreMode')}</span>
|
||||||
|
<button className={`btn ${smartFilters.genreMode === 'include' ? 'btn-primary' : 'btn-surface'}`} onClick={() => setSmartFilters(v => ({ ...v, genreMode: 'include' }))}>{t('smartPlaylists.genreModeInclude')}</button>
|
||||||
|
<button className={`btn ${smartFilters.genreMode === 'exclude' ? 'btn-primary' : 'btn-surface'}`} onClick={() => setSmartFilters(v => ({ ...v, genreMode: 'exclude' }))}>{t('smartPlaylists.genreModeExclude')}</button>
|
||||||
|
</div>
|
||||||
|
<input className="input" placeholder={t('smartPlaylists.genreSearchPlaceholder')} value={genreQuery} onChange={e => setGenreQuery(e.target.value)} style={{ marginBottom: '0.75rem' }} />
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
|
||||||
|
<div style={{ border: '1px solid var(--border)', borderRadius: 'var(--radius-sm)', padding: '0.5rem', minHeight: 120 }}>
|
||||||
|
<div style={{ fontSize: 12, color: 'var(--text-muted)', marginBottom: '0.5rem' }}>{t('smartPlaylists.availableGenres')}</div>
|
||||||
|
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.35rem' }}>
|
||||||
|
{availableGenres.map(g => (
|
||||||
|
<button key={g} className="btn btn-surface" style={{ fontSize: 12, padding: '2px 8px' }} onClick={() => setSmartFilters(v => ({ ...v, selectedGenres: [...v.selectedGenres, g] }))}>{g}</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div style={{ border: '1px solid var(--border)', borderRadius: 'var(--radius-sm)', padding: '0.5rem', minHeight: 120 }}>
|
||||||
|
<div style={{ fontSize: 12, color: 'var(--text-muted)', marginBottom: '0.5rem' }}>{t('smartPlaylists.selectedGenres')}</div>
|
||||||
|
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.35rem' }}>
|
||||||
|
{smartFilters.selectedGenres.map(g => (
|
||||||
|
<button key={g} className="btn btn-surface" style={{ fontSize: 12, padding: '2px 8px' }} onClick={() => setSmartFilters(v => ({ ...v, selectedGenres: v.selectedGenres.filter(x => x !== g) }))}>× {g}</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<section style={{ border: '1px solid var(--border)', borderRadius: 'var(--radius-sm)', padding: '0.75rem' }}>
|
||||||
|
<div style={{ fontSize: 13, fontWeight: 600, marginBottom: '0.65rem' }}>{t('smartPlaylists.sectionYearsAndFilters')}</div>
|
||||||
|
<div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', marginBottom: '0.75rem', flexWrap: 'wrap' }}>
|
||||||
|
<span style={{ fontSize: 13, color: 'var(--text-muted)' }}>{t('smartPlaylists.yearMode')}</span>
|
||||||
|
<button className={`btn ${smartFilters.yearMode === 'include' ? 'btn-primary' : 'btn-surface'}`} onClick={() => setSmartFilters(v => ({ ...v, yearMode: 'include' }))}>{t('smartPlaylists.yearModeInclude')}</button>
|
||||||
|
<button className={`btn ${smartFilters.yearMode === 'exclude' ? 'btn-primary' : 'btn-surface'}`} onClick={() => setSmartFilters(v => ({ ...v, yearMode: 'exclude' }))}>{t('smartPlaylists.yearModeExclude')}</button>
|
||||||
|
</div>
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--text-muted)' }}>
|
||||||
|
<span>{t('smartPlaylists.fromYear')}: {smartFilters.yearFrom}</span>
|
||||||
|
<span>{t('smartPlaylists.toYear')}: {smartFilters.yearTo}</span>
|
||||||
|
</div>
|
||||||
|
<div className="dual-year-range">
|
||||||
|
<div className="dual-year-range__track" />
|
||||||
|
<div className="dual-year-range__selected" style={{ left: `${((smartFilters.yearFrom - YEAR_MIN) / (YEAR_MAX - YEAR_MIN)) * 100}%`, right: `${100 - ((smartFilters.yearTo - YEAR_MIN) / (YEAR_MAX - YEAR_MIN)) * 100}%` }} />
|
||||||
|
<input type="range" min={YEAR_MIN} max={YEAR_MAX} value={smartFilters.yearFrom} onChange={e => setSmartFilters(v => ({ ...v, yearFrom: Math.min(clampYear(Number(e.target.value)), v.yearTo) }))} />
|
||||||
|
<input type="range" min={YEAR_MIN} max={YEAR_MAX} value={smartFilters.yearTo} onChange={e => setSmartFilters(v => ({ ...v, yearTo: Math.max(clampYear(Number(e.target.value)), v.yearFrom) }))} />
|
||||||
|
</div>
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.65rem', marginTop: '0.75rem' }}>
|
||||||
|
<input className="input" placeholder={t('smartPlaylists.artistContains')} value={smartFilters.artistContains} onChange={e => setSmartFilters(v => ({ ...v, artistContains: e.target.value }))} />
|
||||||
|
<input className="input" placeholder={t('smartPlaylists.albumContains')} value={smartFilters.albumContains} onChange={e => setSmartFilters(v => ({ ...v, albumContains: e.target.value }))} />
|
||||||
|
<input className="input" placeholder={t('smartPlaylists.titleContains')} value={smartFilters.titleContains} onChange={e => setSmartFilters(v => ({ ...v, titleContains: e.target.value }))} />
|
||||||
|
<div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{t('smartPlaylists.minRating')}: {smartFilters.minRating}★</div>
|
||||||
|
<StarRating value={smartFilters.minRating} onChange={rating => setSmartFilters(v => ({ ...v, minRating: rating }))} ariaLabel={t('smartPlaylists.minRatingAria')} />
|
||||||
|
<span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{t('smartPlaylists.minRatingHint')}</span>
|
||||||
|
</div>
|
||||||
|
<div style={{ marginTop: '0.75rem', display: 'flex', gap: '1rem', flexWrap: 'wrap' }}>
|
||||||
|
<label style={{ display: 'inline-flex', alignItems: 'center', gap: '0.5rem' }}>
|
||||||
|
<input type="checkbox" checked={smartFilters.excludeUnrated} onChange={e => setSmartFilters(v => ({ ...v, excludeUnrated: e.target.checked }))} />
|
||||||
|
{t('smartPlaylists.excludeUnrated')}
|
||||||
|
</label>
|
||||||
|
<label style={{ display: 'inline-flex', alignItems: 'center', gap: '0.5rem' }}>
|
||||||
|
<input type="checkbox" checked={smartFilters.compilationOnly} onChange={e => setSmartFilters(v => ({ ...v, compilationOnly: e.target.checked }))} />
|
||||||
|
{t('smartPlaylists.compilationOnly')}
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: '0.5rem' }}>
|
||||||
|
<button className="btn btn-surface" onClick={() => setCreatingSmart(false)}>{t('playlists.cancel')}</button>
|
||||||
|
<button className="btn btn-primary" onClick={handleCreateSmart} disabled={creatingSmartBusy}>
|
||||||
|
<Plus size={15} /> {t('smartPlaylists.create')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* ── Grid ── */}
|
{/* ── Grid ── */}
|
||||||
{playlists.length === 0 ? (
|
{playlists.length === 0 ? (
|
||||||
@@ -246,11 +620,29 @@ export default function Playlists() {
|
|||||||
}}
|
}}
|
||||||
onMouseLeave={() => { if (deleteConfirmId === pl.id) setDeleteConfirmId(null); }}
|
onMouseLeave={() => { if (deleteConfirmId === pl.id) setDeleteConfirmId(null); }}
|
||||||
style={selectionMode && selectedIds.has(pl.id) ? {
|
style={selectionMode && selectedIds.has(pl.id) ? {
|
||||||
|
position: 'relative',
|
||||||
outline: '2px solid var(--accent)',
|
outline: '2px solid var(--accent)',
|
||||||
outlineOffset: '2px',
|
outlineOffset: '2px',
|
||||||
borderRadius: 'var(--radius-md)'
|
borderRadius: 'var(--radius-md)'
|
||||||
} : {}}
|
} : { position: 'relative' }}
|
||||||
>
|
>
|
||||||
|
{!selectionMode && isPlaylistDeletable(pl) && (
|
||||||
|
<button
|
||||||
|
className="btn btn-ghost"
|
||||||
|
onClick={(e) => handleDelete(e, pl)}
|
||||||
|
style={{
|
||||||
|
position: 'absolute',
|
||||||
|
top: 8,
|
||||||
|
right: 8,
|
||||||
|
zIndex: 5,
|
||||||
|
padding: 4,
|
||||||
|
borderColor: deleteConfirmId === pl.id ? 'var(--color-danger, #e66)' : undefined,
|
||||||
|
}}
|
||||||
|
data-tooltip={deleteConfirmId === pl.id ? t('playlists.confirmDelete') : t('common.delete')}
|
||||||
|
>
|
||||||
|
<Trash2 size={14} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
{selectionMode && (
|
{selectionMode && (
|
||||||
<div className={`album-card-select-check${selectedIds.has(pl.id) ? ' album-card-select-check--on' : ''}`}>
|
<div className={`album-card-select-check${selectedIds.has(pl.id) ? ' album-card-select-check--on' : ''}`}>
|
||||||
{selectedIds.has(pl.id) && <Check size={14} strokeWidth={3} />}
|
{selectedIds.has(pl.id) && <Check size={14} strokeWidth={3} />}
|
||||||
@@ -270,6 +662,29 @@ export default function Playlists() {
|
|||||||
<ListMusic size={48} strokeWidth={1.2} />
|
<ListMusic size={48} strokeWidth={1.2} />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{pendingSmart.some(p => p.id === pl.id || p.name === pl.name) && (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
position: 'absolute',
|
||||||
|
top: 8,
|
||||||
|
left: 8,
|
||||||
|
width: 24,
|
||||||
|
height: 24,
|
||||||
|
borderRadius: 999,
|
||||||
|
background: 'rgba(0,0,0,0.45)',
|
||||||
|
border: '1px solid rgba(255,255,255,0.25)',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
color: 'white',
|
||||||
|
zIndex: 8,
|
||||||
|
pointerEvents: 'none',
|
||||||
|
}}
|
||||||
|
data-tooltip={t('common.loading')}
|
||||||
|
>
|
||||||
|
<Clock3 size={13} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Play overlay — same pattern as AlbumCard */}
|
{/* Play overlay — same pattern as AlbumCard */}
|
||||||
<div className="album-card-play-overlay">
|
<div className="album-card-play-overlay">
|
||||||
@@ -288,7 +703,10 @@ export default function Playlists() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="album-card-info">
|
<div className="album-card-info">
|
||||||
<div className="album-card-title">{pl.name}</div>
|
<div className="album-card-title" style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||||
|
{isSmartPlaylistName(pl.name) && <Sparkles size={14} style={{ color: 'var(--text-muted)', flex: '0 0 auto' }} />}
|
||||||
|
<span>{displayPlaylistName(pl.name)}</span>
|
||||||
|
</div>
|
||||||
<div className="album-card-artist">
|
<div className="album-card-artist">
|
||||||
{t('playlists.songs', { n: pl.songCount })}
|
{t('playlists.songs', { n: pl.songCount })}
|
||||||
{pl.duration > 0 && <> · {formatDuration(pl.duration)}</>}
|
{pl.duration > 0 && <> · {formatDuration(pl.duration)}</>}
|
||||||
@@ -298,6 +716,7 @@ export default function Playlists() {
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user