feat: Last.fm beta, Similar Artists, Statistics Last.fm stats, TooltipPortal, CustomSelect, Psychowave theme (v1.7.0)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Psychotoxical
2026-03-20 18:35:26 +01:00
parent 9400a5fb2b
commit 2ba7845c79
31 changed files with 1379 additions and 365 deletions
+5
View File
@@ -100,6 +100,8 @@ jobs:
- uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VITE_LASTFM_API_KEY: ${{ secrets.VITE_LASTFM_API_KEY }}
VITE_LASTFM_API_SECRET: ${{ secrets.VITE_LASTFM_API_SECRET }}
with:
releaseId: ${{ needs.create-release.outputs.release_id }}
args: ${{ matrix.settings.args }}
@@ -131,6 +133,9 @@ jobs:
run: npm install
- name: build
env:
VITE_LASTFM_API_KEY: ${{ secrets.VITE_LASTFM_API_KEY }}
VITE_LASTFM_API_SECRET: ${{ secrets.VITE_LASTFM_API_SECRET }}
run: npm run tauri:build -- --bundles deb,rpm
- name: upload Linux artifacts
+5
View File
@@ -7,6 +7,11 @@ yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
# Environment variables (API keys)
.env
.env.local
.env.*.local
# Node
node_modules
dist
+48
View File
@@ -5,6 +5,54 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.7.0] - 2026-03-20
### Added
#### Last.fm Integration *(Beta)*
- **Direct Last.fm scrobbling**: Tracks are scrobbled directly via the Last.fm API at 50% playback — no longer routed through Navidrome. Configure in Settings → Server with your Last.fm username and password.
- **Now Playing updates**: Last.fm receives the currently playing track in real time.
- **Love / Unlove**: Heart button in the Now Playing page and player bar syncs the loved state with Last.fm instantly.
- **Last.fm profile badge** in Settings → Server: shows your scrobble count and member since year once connected.
- ⚠️ **This feature is in beta.** Session management and edge cases are still being refined.
#### Similar Artists
- Artist detail pages now show a **Similar Artists** section below Top Tracks, sourced from Last.fm and filtered to artists actually present in your library. Shown as chip buttons — click to navigate directly to that artist's page.
- Requires Last.fm to be configured. Hidden when Last.fm is not connected or no library matches are found.
#### Statistics — Last.fm Stats
- New **Last.fm Stats** section on the Statistics page (requires Last.fm): top artists, albums, and tracks with proportional play-count bars.
- **Period filter**: switch between Last 7 Days, 1 Month, 3 Months, 6 Months, 12 Months, and Overall.
- **Recent Scrobbles**: last 20 scrobbled tracks with relative timestamps and a "Now Playing" badge for the currently active entry.
- **Genre Distribution removed**: replaced by the Last.fm stats sections.
#### Psychowave Theme *(Work in Progress)*
- New **Psychowave** theme: a deep purple/violet dark theme inspired by synthwave and retrowave aesthetics.
- ⚠️ **Still in active development** — colors and details will continue to be refined in upcoming releases.
#### Tooltip System — TooltipPortal
- All tooltips now use a **React portal** rendered into `document.body` at `z-index: 99999`. Replaces the previous CSS `::after` pseudo-element system.
- Fixes tooltip clipping inside `overflow: hidden` containers (player bar, queue panel, EQ).
- Fixes black OS-native tooltip boxes that appeared on native `title=` attributes — all converted to `data-tooltip`.
- Smart edge detection: tooltip flips position automatically when it would overflow the viewport.
#### Custom Select Dropdowns
- **Theme**, **Language**, and **EQ preset** selectors are now rendered as styled portal dropdowns — no more unstyled native `<select>` boxes.
- Supports option groups (EQ: Built-in Presets / Custom Presets), keyboard navigation, and click-outside-to-close.
### Changed
#### Fullscreen Player / Now Playing — Background
- **Ken Burns animation improved**: background image now has significantly more movement (±8% translate, `inset: -30%`) with a 90-second cycle — more cinematic without being distracting.
- **Color orbs removed** from both the Fullscreen Player and the Now Playing page. They caused noticeable GPU load especially on integrated graphics.
### Fixed
- **Live dropdown (Now Playing)**: Own playback was no longer reported to Navidrome after the Last.fm implementation removed the `reportNowPlaying` call. Both are now called independently on track start.
- **Sidebar: Now Playing button position when collapsed**: The button was appearing in the middle of the nav instead of just above the System section. Caused by a leftover `margin-top: auto` on the Statistics link that split the remaining flex space.
---
## [1.6.0] - 2026-03-19
> ⚠️ **Wichtiger Hinweis / Important Notice**
+1 -1
View File
@@ -182,4 +182,4 @@ The workflow is split into three jobs: `create-release` (creates the GitHub Rele
- **RandomAlbums**: No auto-refresh timer — loads once on mount, manual refresh button only. `loadingRef` guards against concurrent fetches.
- **Queue shuffle**: `shuffleQueue()` in playerStore keeps current track at index 0, Fisher-Yates shuffles the rest.
- **Tooltip z-index**: `.main-content` has `z-index: 1` so tooltips in the content area render above the queue panel (which has no z-index but appears later in DOM order). Multi-line tooltips: add `data-tooltip-wrap` attribute + use `\n` in the string; CSS rule `[data-tooltip-wrap]::after { white-space: pre-line; max-width: 220px }`.
- **Version**: 1.5.0
- **Version**: 1.7.0
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "psysonic",
"version": "1.6.0",
"version": "1.7.0",
"private": true,
"scripts": {
"dev": "vite",
+1 -1
View File
@@ -1,6 +1,6 @@
# Maintainer: stelle <stelle@psychotoxical.dev>
pkgname=psysonic
pkgver=1.6.0
pkgver=1.7.0
pkgrel=1
pkgdesc="Desktop music player for Subsonic API-compatible servers (Navidrome, Gonic, etc.)"
arch=('x86_64')
+8 -1
View File
@@ -2273,6 +2273,12 @@ version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2532096657941c2fea9c289d370a250971c689d4f143798ff67113ec042024a5"
[[package]]
name = "md5"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771"
[[package]]
name = "memchr"
version = "2.8.0"
@@ -3133,9 +3139,10 @@ dependencies = [
[[package]]
name = "psysonic"
version = "1.5.0"
version = "1.7.0"
dependencies = [
"biquad",
"md5",
"reqwest 0.12.28",
"rodio",
"serde",
+3 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "psysonic"
version = "1.6.0"
version = "1.7.0"
description = "Psysonic Desktop Music Player"
authors = []
license = ""
@@ -31,7 +31,8 @@ tauri-plugin-fs = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
rodio = { version = "0.19", default-features = false, features = ["symphonia-all"] }
reqwest = { version = "0.12", features = ["stream"] }
reqwest = { version = "0.12", features = ["stream", "json"] }
md5 = "0.7"
tokio = { version = "1", features = ["rt", "time"] }
biquad = "0.4"
tauri-plugin-window-state = "2.4.1"
+57
View File
@@ -19,6 +19,62 @@ fn exit_app(app_handle: tauri::AppHandle) {
app_handle.exit(0);
}
/// Proxy Last.fm API calls through Rust/reqwest to avoid WebView networking restrictions.
/// `params` is a list of [key, value] pairs (method must be included).
/// If `sign` is true an api_sig is computed. If `get` is true, a GET request is made.
#[tauri::command]
async fn lastfm_request(
params: Vec<[String; 2]>,
sign: bool,
get: bool,
api_key: String,
api_secret: String,
) -> Result<serde_json::Value, String> {
use std::collections::HashMap;
let mut map: HashMap<String, String> = params.into_iter().map(|[k, v]| (k, v)).collect();
map.insert("api_key".into(), api_key.clone());
if sign {
let mut keys: Vec<String> = map.keys().cloned().collect();
keys.sort();
let sig_str: String = keys.iter()
.filter(|k| k.as_str() != "format" && k.as_str() != "callback")
.map(|k| format!("{}{}", k, map[k]))
.collect::<String>();
let sig_input = format!("{}{}", sig_str, api_secret);
let digest = md5::compute(sig_input.as_bytes());
map.insert("api_sig".into(), format!("{:x}", digest));
}
map.insert("format".into(), "json".into());
let client = reqwest::Client::new();
let resp = if get {
client
.get("https://ws.audioscrobbler.com/2.0/")
.query(&map)
.header("User-Agent", "psysonic/1.6.0")
.send()
.await
} else {
client
.post("https://ws.audioscrobbler.com/2.0/")
.form(&map)
.header("User-Agent", "psysonic/1.6.0")
.send()
.await
}.map_err(|e| e.to_string())?;
let json: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?;
if let Some(err) = json.get("error") {
return Err(format!("Last.fm {} {}", err, json.get("message").and_then(|m| m.as_str()).unwrap_or("")));
}
Ok(json)
}
pub fn run() {
let (audio_engine, _audio_thread) = audio::create_engine();
@@ -128,6 +184,7 @@ pub fn run() {
audio::audio_set_eq,
audio::audio_preload,
audio::audio_set_crossfade,
lastfm_request,
])
.run(tauri::generate_context!())
.expect("error while running Psysonic");
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Psysonic",
"version": "1.6.0",
"version": "1.7.0",
"identifier": "dev.psysonic.player",
"build": {
"beforeDevCommand": "npm run dev",
+4 -1
View File
@@ -30,6 +30,7 @@ import NowPlayingPage from './pages/NowPlaying';
import FullscreenPlayer from './components/FullscreenPlayer';
import ContextMenu from './components/ContextMenu';
import DownloadFolderModal from './components/DownloadFolderModal';
import TooltipPortal from './components/TooltipPortal';
import ConnectionIndicator from './components/ConnectionIndicator';
import OfflineOverlay from './components/OfflineOverlay';
import { useConnectionStatus } from './hooks/useConnectionStatus';
@@ -143,7 +144,8 @@ function AppShell() {
<button
className="collapse-btn"
onClick={toggleQueue}
title={t('player.toggleQueue')}
data-tooltip={t('player.toggleQueue')}
data-tooltip-pos="bottom"
>
{isQueueVisible ? <PanelRightClose size={24} /> : <PanelRight size={24} />}
</button>
@@ -191,6 +193,7 @@ function AppShell() {
)}
<ContextMenu />
<DownloadFolderModal />
<TooltipPortal />
</div>
);
}
+290
View File
@@ -0,0 +1,290 @@
import { invoke } from '@tauri-apps/api/core';
const API_KEY = import.meta.env.VITE_LASTFM_API_KEY as string;
const API_SECRET = import.meta.env.VITE_LASTFM_API_SECRET as string;
export function lastfmIsConfigured(): boolean {
return Boolean(API_KEY && API_SECRET);
}
function errMsg(e: unknown): string {
if (typeof e === 'string') return e;
if (e instanceof Error) return e.message;
return String(e);
}
async function call(params: Record<string, string>, sign = false, get = false): Promise<any> {
const entries = Object.entries(params) as [string, string][];
return invoke('lastfm_request', {
params: entries,
sign,
get,
apiKey: API_KEY,
apiSecret: API_SECRET,
});
}
export async function lastfmGetToken(): Promise<string> {
try {
const data = await call({ method: 'auth.getToken' }, false, true);
return data.token as string;
} catch (e) {
throw new Error(errMsg(e));
}
}
export function lastfmAuthUrl(token: string): string {
return `https://www.last.fm/api/auth/?api_key=${API_KEY}&token=${token}`;
}
export async function lastfmGetSession(token: string): Promise<{ key: string; name: string }> {
try {
const data = await call({ method: 'auth.getSession', token }, true, false);
return { key: data.session.key as string, name: data.session.name as string };
} catch (e) {
throw new Error(errMsg(e));
}
}
export async function lastfmGetSimilarArtists(artistName: string): Promise<string[]> {
try {
const data = await call({ method: 'artist.getSimilar', artist: artistName, limit: '50' }, false, true);
const artists = data?.similarartists?.artist;
if (!artists) return [];
const arr = Array.isArray(artists) ? artists : [artists];
return arr.map((a: any) => a.name as string);
} catch {
return [];
}
}
export async function lastfmGetAllLovedTracks(
username: string,
sessionKey: string,
): Promise<Array<{ title: string; artist: string }>> {
const results: Array<{ title: string; artist: string }> = [];
let page = 1;
const limit = 200;
while (true) {
try {
const data = await call({
method: 'user.getLovedTracks',
user: username,
sk: sessionKey,
limit: String(limit),
page: String(page),
}, false, true);
const tracks = data?.lovedtracks?.track;
if (!tracks) break;
const arr = Array.isArray(tracks) ? tracks : [tracks];
for (const t of arr) {
results.push({ title: t.name, artist: t.artist?.name ?? '' });
}
const totalPages = Number(data?.lovedtracks?.['@attr']?.totalPages ?? 1);
if (page >= totalPages || page >= 10) break; // max 10 pages = 2000 tracks
page++;
} catch {
break;
}
}
return results;
}
export async function lastfmGetTrackLoved(
title: string,
artist: string,
sessionKey: string,
): Promise<boolean> {
try {
const data = await call({ method: 'track.getInfo', track: title, artist, sk: sessionKey }, false, true);
return data?.track?.userloved === '1' || data?.track?.userloved === 1;
} catch {
return false;
}
}
export async function lastfmUpdateNowPlaying(
track: { title: string; artist: string; album: string; duration: number },
sessionKey: string,
): Promise<void> {
try {
await call({
method: 'track.updateNowPlaying',
track: track.title,
artist: track.artist,
album: track.album,
duration: String(Math.round(track.duration)),
sk: sessionKey,
}, true, false);
} catch {
// best effort
}
}
export async function lastfmLoveTrack(
track: { title: string; artist: string },
sessionKey: string,
): Promise<void> {
try {
await call({ method: 'track.love', track: track.title, artist: track.artist, sk: sessionKey }, true, false);
} catch {
// best effort
}
}
export async function lastfmUnloveTrack(
track: { title: string; artist: string },
sessionKey: string,
): Promise<void> {
try {
await call({ method: 'track.unlove', track: track.title, artist: track.artist, sk: sessionKey }, true, false);
} catch {
// best effort
}
}
export interface LastfmUserInfo {
playcount: number;
registeredAt: number; // unix timestamp
}
export async function lastfmGetUserInfo(
username: string,
sessionKey: string,
): Promise<LastfmUserInfo | null> {
try {
const data = await call({ method: 'user.getInfo', user: username, sk: sessionKey }, false, true);
const u = data?.user;
if (!u) return null;
return {
playcount: Number(u.playcount),
registeredAt: Number(u.registered?.unixtime ?? 0),
};
} catch {
return null;
}
}
export interface LastfmRecentTrack {
name: string;
artist: string;
album: string;
timestamp: number | null; // null = currently playing
nowPlaying: boolean;
}
export async function lastfmGetRecentTracks(
username: string,
sessionKey: string,
limit = 20,
): Promise<LastfmRecentTrack[]> {
try {
const data = await call({ method: 'user.getRecentTracks', user: username, sk: sessionKey, limit: String(limit) }, false, true);
const items = data?.recenttracks?.track;
if (!items) return [];
const arr = Array.isArray(items) ? items : [items];
return arr.map((t: any) => ({
name: t.name,
artist: t.artist?.['#text'] ?? t.artist?.name ?? '',
album: t.album?.['#text'] ?? '',
timestamp: t.date?.uts ? Number(t.date.uts) : null,
nowPlaying: t['@attr']?.nowplaying === 'true',
}));
} catch {
return [];
}
}
export type LastfmPeriod = 'overall' | '7day' | '1month' | '3month' | '6month' | '12month';
export interface LastfmTopArtist {
name: string;
playcount: string;
}
export interface LastfmTopAlbum {
name: string;
playcount: string;
artist: string;
}
export interface LastfmTopTrack {
name: string;
playcount: string;
artist: string;
}
export async function lastfmGetTopArtists(
username: string,
sessionKey: string,
period: LastfmPeriod,
limit = 10,
): Promise<LastfmTopArtist[]> {
try {
const data = await call({ method: 'user.getTopArtists', user: username, sk: sessionKey, period, limit: String(limit) }, false, true);
const items = data?.topartists?.artist;
if (!items) return [];
const arr = Array.isArray(items) ? items : [items];
return arr.map((a: any) => ({ name: a.name, playcount: a.playcount }));
} catch {
return [];
}
}
export async function lastfmGetTopAlbums(
username: string,
sessionKey: string,
period: LastfmPeriod,
limit = 10,
): Promise<LastfmTopAlbum[]> {
try {
const data = await call({ method: 'user.getTopAlbums', user: username, sk: sessionKey, period, limit: String(limit) }, false, true);
const items = data?.topalbums?.album;
if (!items) return [];
const arr = Array.isArray(items) ? items : [items];
return arr.map((a: any) => ({ name: a.name, playcount: a.playcount, artist: a.artist?.name ?? '' }));
} catch {
return [];
}
}
export async function lastfmGetTopTracks(
username: string,
sessionKey: string,
period: LastfmPeriod,
limit = 10,
): Promise<LastfmTopTrack[]> {
try {
const data = await call({ method: 'user.getTopTracks', user: username, sk: sessionKey, period, limit: String(limit) }, false, true);
const items = data?.toptracks?.track;
if (!items) return [];
const arr = Array.isArray(items) ? items : [items];
return arr.map((t: any) => ({ name: t.name, playcount: t.playcount, artist: t.artist?.name ?? '' }));
} catch {
return [];
}
}
export async function lastfmScrobble(
track: { title: string; artist: string; album: string; duration: number },
timestamp: number,
sessionKey: string,
): Promise<void> {
try {
await call({
method: 'track.scrobble',
track: track.title,
artist: track.artist,
album: track.album,
duration: String(Math.round(track.duration)),
timestamp: String(Math.floor(timestamp / 1000)),
sk: sessionKey,
}, true, false);
} catch {
// best effort
}
}
+1 -1
View File
@@ -19,7 +19,7 @@ export default function ConnectionIndicator({ status, isLan, serverName }: Props
: t('connection.checking');
return (
<div className="connection-indicator" title={title}>
<div className="connection-indicator" data-tooltip={title} data-tooltip-pos="bottom">
<div className={`connection-led connection-led--${status}`} />
<div className="connection-meta">
<span className="connection-type">{label}</span>
+33 -2
View File
@@ -1,5 +1,6 @@
import React, { useEffect, useRef, useState } from 'react';
import { Play, ListPlus, Radio, Star, Download, ChevronRight, User, Disc3 } from 'lucide-react';
import { Play, ListPlus, Radio, Star, Download, ChevronRight, User, Disc3, Heart } from 'lucide-react';
import { lastfmLoveTrack, lastfmUnloveTrack } from '../api/lastfm';
import { usePlayerStore, Track } from '../store/playerStore';
import { SubsonicAlbum, SubsonicArtist, star, unstar, getSimilarSongs2, getTopSongs, buildDownloadUrl, getAlbum } from '../api/subsonic';
import { useNavigate } from 'react-router-dom';
@@ -20,7 +21,7 @@ function sanitizeFilename(name: string): string {
export default function ContextMenu() {
const { t } = useTranslation();
const { contextMenu, closeContextMenu, playTrack, enqueue, queue, currentTrack, removeTrack } = usePlayerStore();
const { contextMenu, closeContextMenu, playTrack, enqueue, queue, currentTrack, removeTrack, lastfmLovedCache, setLastfmLovedForSong } = usePlayerStore();
const auth = useAuthStore();
const requestDownloadFolder = useDownloadModalStore(s => s.requestFolder);
const navigate = useNavigate();
@@ -150,6 +151,21 @@ export default function ContextMenu() {
<div className="context-menu-item" onClick={() => handleAction(() => star(song.id, 'song'))}>
<Star size={14} /> {t('contextMenu.favorite')}
</div>
{auth.lastfmSessionKey && (() => {
const loveKey = `${song.title}::${song.artist}`;
const loved = lastfmLovedCache[loveKey] ?? false;
return (
<div className="context-menu-item" onClick={() => handleAction(() => {
const newLoved = !loved;
setLastfmLovedForSong(song.title, song.artist, newLoved);
if (newLoved) lastfmLoveTrack(song, auth.lastfmSessionKey);
else lastfmUnloveTrack(song, auth.lastfmSessionKey);
})}>
<Heart size={14} fill={loved ? 'currentColor' : 'none'} style={{ color: loved ? '#e31c23' : undefined }} />
{loved ? t('contextMenu.lfmUnlove') : t('contextMenu.lfmLove')}
</div>
);
})()}
</>
);
})()}
@@ -211,6 +227,21 @@ export default function ContextMenu() {
<div className="context-menu-item" onClick={() => handleAction(() => star(song.id, 'song'))}>
<Star size={14} /> {t('contextMenu.favorite')}
</div>
{auth.lastfmSessionKey && (() => {
const loveKey = `${song.title}::${song.artist}`;
const loved = lastfmLovedCache[loveKey] ?? false;
return (
<div className="context-menu-item" onClick={() => handleAction(() => {
const newLoved = !loved;
setLastfmLovedForSong(song.title, song.artist, newLoved);
if (newLoved) lastfmLoveTrack(song, auth.lastfmSessionKey);
else lastfmUnloveTrack(song, auth.lastfmSessionKey);
})}>
<Heart size={14} fill={loved ? 'currentColor' : 'none'} style={{ color: loved ? '#e31c23' : undefined }} />
{loved ? t('contextMenu.lfmUnlove') : t('contextMenu.lfmLove')}
</div>
);
})()}
<div className="context-menu-item" onClick={() => handleAction(() => startRadio(song.artist, song.artist))}>
<Radio size={14} /> {t('contextMenu.startRadio')}
</div>
+115
View File
@@ -0,0 +1,115 @@
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { ChevronDown } from 'lucide-react';
export interface SelectOption {
value: string;
label: string;
group?: string; // group label — shown as non-selectable header when it changes
disabled?: boolean;
}
interface Props {
value: string;
options: SelectOption[];
onChange: (value: string) => void;
className?: string;
style?: React.CSSProperties;
}
export default function CustomSelect({ value, options, onChange, className = '', style }: Props) {
const [open, setOpen] = useState(false);
const triggerRef = useRef<HTMLButtonElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const [dropStyle, setDropStyle] = useState<React.CSSProperties>({});
const selected = options.find(o => o.value === value);
useLayoutEffect(() => {
if (!open || !triggerRef.current) return;
const rect = triggerRef.current.getBoundingClientRect();
const MARGIN = 6;
const maxH = 240;
const spaceBelow = window.innerHeight - rect.bottom - MARGIN;
const spaceAbove = rect.top - MARGIN;
const useAbove = spaceBelow < 80 && spaceAbove > spaceBelow;
setDropStyle({
position: 'fixed',
left: rect.left,
width: rect.width,
...(useAbove
? { bottom: window.innerHeight - rect.top + MARGIN }
: { top: rect.bottom + MARGIN }),
maxHeight: Math.min(maxH, useAbove ? spaceAbove : spaceBelow),
zIndex: 99998,
});
}, [open]);
useEffect(() => {
if (!open) return;
const onDown = (e: MouseEvent) => {
if (
!triggerRef.current?.contains(e.target as Node) &&
!listRef.current?.contains(e.target as Node)
) setOpen(false);
};
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false); };
document.addEventListener('mousedown', onDown);
document.addEventListener('keydown', onKey);
return () => {
document.removeEventListener('mousedown', onDown);
document.removeEventListener('keydown', onKey);
};
}, [open]);
return (
<>
<button
ref={triggerRef}
type="button"
className={`custom-select-trigger ${className}`}
style={style}
onClick={() => setOpen(v => !v)}
aria-haspopup="listbox"
aria-expanded={open}
>
<span className="custom-select-label">{selected?.label ?? value}</span>
<ChevronDown size={14} className={`custom-select-chevron ${open ? 'open' : ''}`} />
</button>
{open && createPortal(
<div
ref={listRef}
className="custom-select-dropdown"
style={dropStyle}
role="listbox"
>
{options.reduce<React.ReactNode[]>((acc, opt, i) => {
const prevGroup = i > 0 ? options[i - 1].group : undefined;
if (opt.group && opt.group !== prevGroup) {
acc.push(
<div key={`group-${opt.group}`} className="custom-select-group-label">
{opt.group}
</div>
);
}
acc.push(
<div
key={opt.value}
className={`custom-select-option ${opt.value === value ? 'selected' : ''} ${opt.disabled ? 'disabled' : ''}`}
role="option"
aria-selected={opt.value === value}
onMouseDown={() => { if (!opt.disabled) { onChange(opt.value); setOpen(false); } }}
>
{opt.label}
</div>
);
return acc;
}, [])}
</div>,
document.body
)}
</>
);
}
+13 -17
View File
@@ -1,6 +1,7 @@
import { useState, useRef, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { Save, Trash2, RotateCcw } from 'lucide-react';
import CustomSelect from './CustomSelect';
import { useEqStore, EQ_BANDS, BUILTIN_PRESETS } from '../store/eqStore';
import { useThemeStore } from '../store/themeStore';
@@ -240,31 +241,26 @@ export default function Equalizer() {
</label>
<div className="eq-preset-row">
<select
className="input eq-preset-select"
<CustomSelect
className="eq-preset-select"
value={selectValue}
onChange={e => applyPreset(e.target.value)}
>
{activePreset === null && <option value="__custom__">{t('settings.eqPresetCustom')}</option>}
<optgroup label={t('settings.eqPresetBuiltin')}>
{BUILTIN_PRESETS.map(p => <option key={p.name} value={p.name}>{p.name}</option>)}
</optgroup>
{customPresets.length > 0 && (
<optgroup label={t('settings.eqPresetCustomGroup')}>
{customPresets.map(p => <option key={p.name} value={p.name}>{p.name}</option>)}
</optgroup>
)}
</select>
onChange={v => applyPreset(v)}
options={[
...(activePreset === null ? [{ value: '__custom__', label: t('settings.eqPresetCustom'), disabled: true }] : []),
...BUILTIN_PRESETS.map(p => ({ value: p.name, label: p.name, group: t('settings.eqPresetBuiltin') })),
...customPresets.map(p => ({ value: p.name, label: p.name, group: t('settings.eqPresetCustomGroup') })),
]}
/>
{isCustomSaved && (
<button className="eq-ctrl-btn" onClick={() => deleteCustomPreset(activePreset!)} title={t('settings.eqDeletePreset')}>
<button className="eq-ctrl-btn" onClick={() => deleteCustomPreset(activePreset!)} data-tooltip={t('settings.eqDeletePreset')}>
<Trash2 size={13} />
</button>
)}
<button className="eq-ctrl-btn" onClick={() => applyPreset('Flat')} title={t('settings.eqResetBands')}>
<button className="eq-ctrl-btn" onClick={() => applyPreset('Flat')} data-tooltip={t('settings.eqResetBands')}>
<RotateCcw size={13} />
</button>
<button className="eq-ctrl-btn" onClick={() => setShowSave(v => !v)} title={t('settings.eqSavePreset')}>
<button className="eq-ctrl-btn" onClick={() => setShowSave(v => !v)} data-tooltip={t('settings.eqSavePreset')}>
<Save size={13} />
</button>
</div>
-3
View File
@@ -193,9 +193,6 @@ export default function FullscreenPlayer({ onClose }: FullscreenPlayerProps) {
<>
<FsBg url={bgUrl} />
<div className="fs-bg-overlay" aria-hidden="true" />
<div className="fs-orb fs-orb-1" aria-hidden="true" />
<div className="fs-orb fs-orb-2" aria-hidden="true" />
<div className="fs-orb fs-orb-3" aria-hidden="true" />
</>
)}
+7
View File
@@ -0,0 +1,7 @@
export default function LastfmIcon({ size = 16 }: { size?: number }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M11.344 16.143l-.917-2.494s-1.485 1.662-3.716 1.662c-1.97 0-3.373-1.714-3.373-4.46 0-3.514 1.773-4.777 3.52-4.777 2.508 0 3.306 1.625 3.997 3.714l.918 2.88c.918 2.8 2.642 5.047 7.615 5.047 3.563 0 5.98-1.094 5.98-3.972 0-2.326-1.327-3.53-3.797-4.11l-1.836-.41c-1.27-.29-1.645-.82-1.645-1.693 0-.987.778-1.56 2.047-1.56 1.384 0 2.132.52 2.245 1.756l2.878-.347C24.883 5.116 23.3 4 20.5 4c-3.26 0-4.945 1.537-4.945 3.824 0 1.843.91 3.008 3.2 3.562l1.947.46c1.404.327 1.97.874 1.97 1.894 0 1.13-.988 1.593-2.948 1.593-2.858 0-4.052-1.497-4.742-3.634l-.943-2.887C13.22 6.162 11.73 4 7.897 4 3.847 4 1 6.61 1 11.022c0 4.235 2.617 6.638 6.19 6.638 2.566 0 4.154-1.517 4.154-1.517z"/>
</svg>
);
}
+15 -1
View File
@@ -1,9 +1,10 @@
import React, { useCallback, useMemo, useState } from 'react';
import {
Play, Pause, SkipBack, SkipForward, Volume2, VolumeX, Music,
Square, Repeat, Repeat1, Maximize2, SlidersHorizontal, X
Square, Repeat, Repeat1, Maximize2, SlidersHorizontal, X, Heart
} from 'lucide-react';
import { usePlayerStore } from '../store/playerStore';
import { useAuthStore } from '../store/authStore';
import { buildCoverArtUrl, coverArtCacheKey } from '../api/subsonic';
import CachedImage from './CachedImage';
import WaveformSeek from './WaveformSeek';
@@ -26,7 +27,9 @@ export default function PlayerBar() {
currentTrack, isPlaying, currentTime, volume,
togglePlay, next, previous, setVolume,
stop, toggleRepeat, repeatMode, toggleFullscreen,
lastfmLoved, toggleLastfmLove,
} = usePlayerStore();
const { lastfmSessionKey } = useAuthStore();
const duration = currentTrack?.duration ?? 0;
const coverSrc = useMemo(() => currentTrack?.coverArt ? buildCoverArtUrl(currentTrack.coverArt, 128) : '', [currentTrack?.coverArt]);
@@ -86,6 +89,17 @@ export default function PlayerBar() {
{currentTrack?.artist ?? '—'}
</div>
</div>
{currentTrack && lastfmSessionKey && (
<button
className="player-btn player-btn-sm player-love-btn"
onClick={toggleLastfmLove}
aria-label={lastfmLoved ? t('contextMenu.lfmUnlove') : t('contextMenu.lfmLove')}
data-tooltip={lastfmLoved ? t('contextMenu.lfmUnlove') : t('contextMenu.lfmLove')}
style={{ color: lastfmLoved ? '#e31c23' : 'var(--text-muted)', flexShrink: 0 }}
>
<Heart size={15} fill={lastfmLoved ? '#e31c23' : 'none'} />
</button>
)}
</div>
{/* Transport Controls */}
+13 -8
View File
@@ -38,7 +38,7 @@ function UpdateToast({ isCollapsed, latestVersion }: { isCollapsed: boolean; lat
if (isCollapsed) {
return (
<div className="update-toast-icon" style={{ marginTop: 'auto' }} title={`${t('sidebar.updateAvailable')}: ${latestVersion}`}>
<div className="update-toast-icon" style={{ marginTop: 'auto' }} data-tooltip={`${t('sidebar.updateAvailable')}: ${latestVersion}`} data-tooltip-pos="bottom">
<ArrowUpCircle size={20} />
</div>
);
@@ -102,7 +102,8 @@ export default function Sidebar({
<button
className="collapse-btn"
onClick={toggleCollapse}
title={isCollapsed ? t('sidebar.expand') : t('sidebar.collapse')}
data-tooltip={isCollapsed ? t('sidebar.expand') : t('sidebar.collapse')}
data-tooltip-pos="bottom"
style={{ padding: 0 }}
>
{isCollapsed ? <PanelLeft size={24} /> : <PanelLeftClose size={24} />}
@@ -119,7 +120,8 @@ export default function Sidebar({
to={item.to}
end={item.to === '/'}
className={({ isActive }) => `nav-link ${isActive ? 'active' : ''}`}
title={isCollapsed ? t(item.labelKey) : undefined}
data-tooltip={isCollapsed ? t(item.labelKey) : undefined}
data-tooltip-pos="bottom"
>
<item.icon size={isCollapsed ? 22 : 18} />
{!isCollapsed && <span>{t(item.labelKey)}</span>}
@@ -130,7 +132,8 @@ export default function Sidebar({
<NavLink
to="/now-playing"
className={({ isActive }) => `nav-link nav-link-nowplaying ${isActive ? 'active' : ''}`}
title={isCollapsed ? t('sidebar.nowPlaying') : undefined}
data-tooltip={isCollapsed ? t('sidebar.nowPlaying') : undefined}
data-tooltip-pos="bottom"
style={{ marginTop: 'auto' }}
>
<span className="nav-np-icon-wrap">
@@ -145,8 +148,8 @@ export default function Sidebar({
<NavLink
to="/statistics"
className={({ isActive }) => `nav-link ${isActive ? 'active' : ''}`}
style={isCollapsed && !latestVersion ? { marginTop: 'auto' } : undefined}
title={isCollapsed ? t('sidebar.statistics') : undefined}
data-tooltip={isCollapsed ? t('sidebar.statistics') : undefined}
data-tooltip-pos="bottom"
>
<BarChart3 size={isCollapsed ? 22 : 18} />
{!isCollapsed && <span>{t('sidebar.statistics')}</span>}
@@ -154,7 +157,8 @@ export default function Sidebar({
<NavLink
to="/help"
className={({ isActive }) => `nav-link ${isActive ? 'active' : ''}`}
title={isCollapsed ? t('sidebar.help') : undefined}
data-tooltip={isCollapsed ? t('sidebar.help') : undefined}
data-tooltip-pos="bottom"
>
<HelpCircle size={isCollapsed ? 22 : 18} />
{!isCollapsed && <span>{t('sidebar.help')}</span>}
@@ -162,7 +166,8 @@ export default function Sidebar({
<NavLink
to="/settings"
className={({ isActive }) => `nav-link ${isActive ? 'active' : ''}`}
title={isCollapsed ? t('sidebar.settings') : undefined}
data-tooltip={isCollapsed ? t('sidebar.settings') : undefined}
data-tooltip-pos="bottom"
>
<Settings size={isCollapsed ? 22 : 18} />
{!isCollapsed && <span>{t('sidebar.settings')}</span>}
+94
View File
@@ -0,0 +1,94 @@
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
interface TooltipState {
text: string;
anchorRect: DOMRect;
preferBottom: boolean;
wrap: boolean;
}
export default function TooltipPortal() {
const [tooltip, setTooltip] = useState<TooltipState | null>(null);
const boxRef = useRef<HTMLDivElement>(null);
const [style, setStyle] = useState<React.CSSProperties>({ opacity: 0 });
useEffect(() => {
const onOver = (e: MouseEvent) => {
const target = (e.target as HTMLElement).closest('[data-tooltip]') as HTMLElement | null;
if (!target) return;
const text = target.getAttribute('data-tooltip');
if (!text) return;
setTooltip({
text,
anchorRect: target.getBoundingClientRect(),
preferBottom: target.getAttribute('data-tooltip-pos') === 'bottom',
wrap: target.hasAttribute('data-tooltip-wrap'),
});
};
const onOut = (e: MouseEvent) => {
const target = (e.target as HTMLElement).closest('[data-tooltip]');
if (target) setTooltip(null);
};
document.addEventListener('mouseover', onOver);
document.addEventListener('mouseout', onOut);
return () => {
document.removeEventListener('mouseover', onOver);
document.removeEventListener('mouseout', onOut);
};
}, []);
useLayoutEffect(() => {
if (!tooltip || !boxRef.current) { setStyle({ opacity: 0 }); return; }
const box = boxRef.current.getBoundingClientRect();
const { anchorRect, preferBottom } = tooltip;
const GAP = 7;
const MARGIN = 8;
// Decide top or bottom
const spaceAbove = anchorRect.top - GAP - box.height;
const useBottom = preferBottom || spaceAbove < MARGIN;
let top = useBottom
? anchorRect.bottom + GAP
: anchorRect.top - GAP - box.height;
// Clamp vertically
top = Math.max(MARGIN, Math.min(top, window.innerHeight - box.height - MARGIN));
// Centre horizontally, clamp to viewport
let left = anchorRect.left + anchorRect.width / 2 - box.width / 2;
left = Math.max(MARGIN, Math.min(left, window.innerWidth - box.width - MARGIN));
setStyle({ opacity: 1, top, left });
}, [tooltip]);
if (!tooltip) return null;
return createPortal(
<div
ref={boxRef}
style={{
position: 'fixed',
zIndex: 99999,
background: 'var(--bg-card)',
color: 'var(--text-primary)',
border: '1px solid var(--border-subtle)',
borderRadius: 'var(--radius-sm)',
padding: '4px 8px',
fontSize: '12px',
fontWeight: 500,
boxShadow: '0 4px 12px rgba(0,0,0,0.6)',
pointerEvents: 'none',
whiteSpace: tooltip.wrap ? 'pre-line' : 'nowrap',
maxWidth: tooltip.wrap ? '220px' : undefined,
transition: 'opacity 0.15s ease',
...style,
}}
>
{tooltip.text}
</div>,
document.body
);
}
+62 -10
View File
@@ -63,6 +63,8 @@ const enTranslation = {
addToQueue: 'Add to Queue',
enqueueAlbum: 'Enqueue Album',
startRadio: 'Start Radio',
lfmLove: 'Love on Last.fm',
lfmUnlove: 'Unlove on Last.fm',
favorite: 'Favorite',
favoriteArtist: 'Favorite Artist',
favoriteAlbum: 'Favorite Album',
@@ -124,6 +126,7 @@ const enTranslation = {
albumCount_other: '{{count}} Albums',
openedInBrowser: 'Opened in browser',
featuredOn: 'Also Featured On',
similarArtists: 'Similar Artists',
},
favorites: {
title: 'Favorites',
@@ -283,11 +286,16 @@ const enTranslation = {
eqPresetName: 'Preset name…',
eqDeletePreset: 'Delete preset',
eqResetBands: 'Reset to Flat',
lfmTitle: 'Last.fm Scrobbling',
lfmDesc1: 'Psysonic supports server-side scrobbling directly via Navidrome. To link Last.fm, please log in once via the',
lfmDesc1NavidromeWebplayer: 'Navidrome Webplayer',
lfmDesc1b: 'in your browser, go to your profile, and connect your Last.fm account.',
lfmDesc2: 'Once that is done, Psysonic automatically forwards your currently playing songs to Navidrome, and they will appear on Last.fm.',
lfmTitle: 'Last.fm',
lfmConnect: 'Connect with Last.fm',
lfmConnecting: 'Waiting for authorisation…',
lfmConfirm: 'I have authorised the app',
lfmConnected: 'Connected as',
lfmDisconnect: 'Disconnect',
lfmConnectDesc: 'Connect your Last.fm account to enable scrobbling and Now Playing updates directly from Psysonic — no Navidrome configuration required.',
lfmOpenBrowser: 'A browser window will open. Authorise Psysonic on Last.fm, then click the button below.',
lfmScrobbles: '{{count}} scrobbles',
lfmMemberSince: 'Member since {{year}}',
scrobbleEnabled: 'Scrobbling enabled',
scrobbleDesc: 'Send songs to Last.fm after 50% playtime',
behavior: 'App Behavior',
@@ -440,6 +448,24 @@ const enTranslation = {
decadeAlbums_one: '{{count}} Album',
decadeAlbums_other: '{{count}} Albums',
decadeUnknown: 'Unknown',
lfmTitle: 'Last.fm Stats',
lfmTopArtists: 'Top Artists',
lfmTopAlbums: 'Top Albums',
lfmTopTracks: 'Top Tracks',
lfmPlays: '{{count}} plays',
lfmPeriodOverall: 'All Time',
lfmPeriod7day: '7 Days',
lfmPeriod1month: '1 Month',
lfmPeriod3month: '3 Months',
lfmPeriod6month: '6 Months',
lfmPeriod12month: '12 Months',
lfmNotConnected: 'Connect Last.fm in Settings to see your stats.',
lfmRecentTracks: 'Recent Scrobbles',
lfmNowPlaying: 'Now Playing',
lfmJustNow: 'just now',
lfmMinutesAgo: '{{n}}m ago',
lfmHoursAgo: '{{n}}h ago',
lfmDaysAgo: '{{n}}d ago',
},
player: {
regionLabel: 'Music Player',
@@ -527,6 +553,8 @@ const deTranslation = {
addToQueue: 'Zur Warteschlange hinzufügen',
enqueueAlbum: 'Ganzes Album einreihen',
startRadio: 'Radio starten',
lfmLove: 'Auf Last.fm liken',
lfmUnlove: 'Last.fm-Like entfernen',
favorite: 'Favorisieren',
favoriteArtist: 'Künstler favorisieren',
favoriteAlbum: 'Album favorisieren',
@@ -588,6 +616,7 @@ const deTranslation = {
albumCount_other: '{{count}} Alben',
openedInBrowser: 'Im Browser geöffnet',
featuredOn: 'Auch enthalten auf',
similarArtists: 'Ähnliche Künstler',
},
favorites: {
title: 'Favoriten',
@@ -747,11 +776,16 @@ const deTranslation = {
eqPresetName: 'Preset-Name…',
eqDeletePreset: 'Preset löschen',
eqResetBands: 'Auf Flat zurücksetzen',
lfmTitle: 'Last.fm Scrobbling',
lfmDesc1: 'Psysonic unterstützt serverseitiges Scrobbling direkt über Navidrome. Um Last.fm zu verknüpfen, logge dich bitte einmalig über den',
lfmDesc1NavidromeWebplayer: 'Navidrome Webplayer',
lfmDesc1b: 'im Browser ein, gehe auf dein Profil und verbinde deinen Last.fm Account.',
lfmDesc2: 'Sobald das erledigt ist, leitet Psysonic deine aktuell gespielten Songs automatisch an Navidrome weiter, und diese erscheinen auf Last.fm.',
lfmTitle: 'Last.fm',
lfmConnect: 'Mit Last.fm verbinden',
lfmConnecting: 'Warte auf Bestätigung…',
lfmConfirm: 'Ich habe die App autorisiert',
lfmConnected: 'Verbunden als',
lfmDisconnect: 'Trennen',
lfmConnectDesc: 'Verbinde deinen Last.fm Account, um Scrobbling und Now-Playing-Updates direkt aus Psysonic heraus zu aktivieren — keine Navidrome-Konfiguration erforderlich.',
lfmOpenBrowser: 'Es öffnet sich ein Browserfenster. Autorisiere Psysonic auf Last.fm und klicke dann unten auf den Button.',
lfmScrobbles: '{{count}} Scrobbles',
lfmMemberSince: 'Dabei seit {{year}}',
scrobbleEnabled: 'Scrobbling aktiviert',
scrobbleDesc: 'Songs nach 50% Laufzeit an Last.fm senden',
behavior: 'App-Verhalten',
@@ -904,6 +938,24 @@ const deTranslation = {
decadeAlbums_one: '{{count}} Album',
decadeAlbums_other: '{{count}} Alben',
decadeUnknown: 'Unbekannt',
lfmTitle: 'Last.fm Statistiken',
lfmTopArtists: 'Top-Künstler',
lfmTopAlbums: 'Top-Alben',
lfmTopTracks: 'Top-Titel',
lfmPlays: '{{count}} Plays',
lfmPeriodOverall: 'Gesamt',
lfmPeriod7day: '7 Tage',
lfmPeriod1month: '1 Monat',
lfmPeriod3month: '3 Monate',
lfmPeriod6month: '6 Monate',
lfmPeriod12month: '12 Monate',
lfmNotConnected: 'Verbinde Last.fm in den Einstellungen, um deine Statistiken zu sehen.',
lfmRecentTracks: 'Zuletzt gescrobbelt',
lfmNowPlaying: 'Läuft gerade',
lfmJustNow: 'gerade eben',
lfmMinutesAgo: 'vor {{n}} Min.',
lfmHoursAgo: 'vor {{n}} Std.',
lfmDaysAgo: 'vor {{n}} Tagen',
},
player: {
regionLabel: 'Musikplayer',
+58 -8
View File
@@ -7,6 +7,8 @@ import { ArrowLeft, Users, ExternalLink, Star, Play, Shuffle, Radio } from 'luci
import { open } from '@tauri-apps/plugin-shell';
import { usePlayerStore } from '../store/playerStore';
import { useTranslation } from 'react-i18next';
import { lastfmGetSimilarArtists, lastfmIsConfigured } from '../api/lastfm';
import LastfmIcon from '../components/LastfmIcon';
function formatDuration(seconds: number): string {
const m = Math.floor(seconds / 60);
@@ -31,13 +33,6 @@ function sanitizeHtml(html: string): string {
return doc.body.innerHTML;
}
function LastfmIcon({ size = 16 }: { size?: number }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M11.344 16.143l-.917-2.494s-1.485 1.662-3.716 1.662c-1.97 0-3.373-1.714-3.373-4.46 0-3.514 1.773-4.777 3.52-4.777 2.508 0 3.306 1.625 3.997 3.714l.918 2.88c.918 2.8 2.642 5.047 7.615 5.047 3.563 0 5.98-1.094 5.98-3.972 0-2.326-1.327-3.53-3.797-4.11l-1.836-.41c-1.27-.29-1.645-.82-1.645-1.693 0-.987.778-1.56 2.047-1.56 1.384 0 2.132.52 2.245 1.756l2.878-.347C24.883 5.116 23.3 4 20.5 4c-3.26 0-4.945 1.537-4.945 3.824 0 1.843.91 3.008 3.2 3.562l1.947.46c1.404.327 1.97.874 1.97 1.894 0 1.13-.988 1.593-2.948 1.593-2.858 0-4.052-1.497-4.742-3.634l-.943-2.887C13.22 6.162 11.73 4 7.897 4 3.847 4 1 6.61 1 11.022c0 4.235 2.617 6.638 6.19 6.638 2.566 0 4.154-1.517 4.154-1.517z"/>
</svg>
);
}
export default function ArtistDetail() {
const { t } = useTranslation();
@@ -52,6 +47,8 @@ export default function ArtistDetail() {
const [radioLoading, setRadioLoading] = useState(false);
const [isStarred, setIsStarred] = useState(false);
const [openedLink, setOpenedLink] = useState<string | null>(null);
const [similarArtists, setSimilarArtists] = useState<SubsonicArtist[]>([]);
const [similarLoading, setSimilarLoading] = useState(false);
const playTrack = usePlayerStore(state => state.playTrack);
const enqueue = usePlayerStore(state => state.enqueue);
@@ -107,6 +104,32 @@ export default function ArtistDetail() {
});
}, [id]);
useEffect(() => {
if (!artist || !lastfmIsConfigured()) return;
setSimilarArtists([]);
setSimilarLoading(true);
lastfmGetSimilarArtists(artist.name).then(async names => {
if (names.length === 0) { setSimilarLoading(false); return; }
const results = await Promise.all(
names.slice(0, 30).map(name =>
search(name, { artistCount: 3, albumCount: 0, songCount: 0 }).catch(() => ({ artists: [], albums: [], songs: [] }))
)
);
const seen = new Set<string>([artist.id]);
const found: SubsonicArtist[] = [];
for (let i = 0; i < results.length; i++) {
const targetName = names[i].toLowerCase();
const match = results[i].artists.find(a => a.name.toLowerCase() === targetName);
if (match && !seen.has(match.id)) {
seen.add(match.id);
found.push(match);
}
}
setSimilarArtists(found);
setSimilarLoading(false);
}).catch(() => setSimilarLoading(false));
}, [artist?.id]);
const openLink = (url: string, key: string) => {
open(url);
setOpenedLink(key);
@@ -325,8 +348,35 @@ export default function ArtistDetail() {
</>
)}
{/* Similar Artists (Last.fm) */}
{lastfmIsConfigured() && (similarLoading || similarArtists.length > 0) && (
<>
<h2 className="section-title" style={{ marginTop: '2rem', marginBottom: '1rem' }}>
{t('artistDetail.similarArtists')}
</h2>
{similarLoading ? (
<div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', color: 'var(--text-muted)', fontSize: '0.875rem' }}>
<div className="spinner" style={{ width: 16, height: 16, borderTopColor: 'currentColor' }} />
{t('artistDetail.loading')}
</div>
) : (
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem' }}>
{similarArtists.map(a => (
<button
key={a.id}
className="artist-ext-link"
onClick={() => navigate(`/artist/${a.id}`)}
>
{a.name}
</button>
))}
</div>
)}
</>
)}
{/* Albums */}
<h2 className="section-title" style={{ marginTop: (info?.biography || topSongs.length > 0) ? '2rem' : '0', marginBottom: '1rem' }}>
<h2 className="section-title" style={{ marginTop: (info?.biography || topSongs.length > 0 || lastfmIsConfigured()) ? '2rem' : '0', marginBottom: '1rem' }}>
{t('artistDetail.albumsBy', { name: artist.name })}
</h2>
+6 -9
View File
@@ -71,9 +71,6 @@ const NpBg = memo(function NpBg({ url }: { url: string }) {
style={{ backgroundImage: `url(${l.url})`, opacity: l.visible ? 1 : 0 }}
/>
))}
<div className="np-orb np-orb-1" />
<div className="np-orb np-orb-2" />
<div className="np-orb np-orb-3" />
<div className="np-bg-overlay" />
</div>
);
@@ -319,7 +316,7 @@ export default function NowPlaying() {
<button
onClick={toggleStar}
className="np-star-btn"
title={starred ? t('contextMenu.unfavorite') : t('contextMenu.favorite')}
data-tooltip={starred ? t('contextMenu.unfavorite') : t('contextMenu.favorite')}
>
<Star size={18} fill={starred ? 'var(--ctp-yellow)' : 'none'} color={starred ? 'var(--ctp-yellow)' : 'white'} />
</button>
@@ -347,16 +344,16 @@ export default function NowPlaying() {
)}
</div>
<div className="np-queue-actions">
<button onClick={() => shuffleQueue()} className="np-action-btn" title={t('queue.shuffle')} disabled={queue.length < 2}>
<button onClick={() => shuffleQueue()} className="np-action-btn" data-tooltip={t('queue.shuffle')} disabled={queue.length < 2}>
<Shuffle size={15} />
</button>
<button onClick={() => setSaveModalOpen(true)} className="np-action-btn" title={t('queue.save')} disabled={queue.length === 0}>
<button onClick={() => setSaveModalOpen(true)} className="np-action-btn" data-tooltip={t('queue.save')} disabled={queue.length === 0}>
<Save size={15} />
</button>
<button onClick={() => setLoadModalOpen(true)} className="np-action-btn" title={t('queue.load')}>
<button onClick={() => setLoadModalOpen(true)} className="np-action-btn" data-tooltip={t('queue.load')}>
<FolderOpen size={15} />
</button>
<button onClick={clearQueue} className="np-action-btn" title={t('queue.clear')} disabled={queue.length === 0}>
<button onClick={clearQueue} className="np-action-btn" data-tooltip={t('queue.clear')} disabled={queue.length === 0}>
<Trash2 size={15} />
</button>
</div>
@@ -412,7 +409,7 @@ export default function NowPlaying() {
<button
className="np-queue-remove"
onClick={e => { e.stopPropagation(); removeTrack(idx); }}
title={t('queue.remove')}
data-tooltip={t('queue.remove')}
><X size={13} /></button>
</div>
);
+132 -32
View File
@@ -1,4 +1,4 @@
import React, { useState, useMemo } from 'react';
import React, { useState, useMemo, useCallback, useEffect } from 'react';
import { version as appVersion } from '../../package.json';
import changelogRaw from '../../CHANGELOG.md?raw';
import { useNavigate } from 'react-router-dom';
@@ -7,6 +7,9 @@ import {
Palette, Server, Plus, Trash2, Eye, EyeOff, Info, ExternalLink, Shuffle, X, Play
} from 'lucide-react';
import { open as openUrl } from '@tauri-apps/plugin-shell';
import { lastfmGetToken, lastfmAuthUrl, lastfmGetSession, lastfmIsConfigured, lastfmGetUserInfo, LastfmUserInfo } from '../api/lastfm';
import LastfmIcon from '../components/LastfmIcon';
import CustomSelect from '../components/CustomSelect';
import { useAuthStore, ServerProfile } from '../store/authStore';
import { useThemeStore } from '../store/themeStore';
import { pingWithCredentials } from '../api/subsonic';
@@ -86,6 +89,57 @@ export default function Settings() {
const [connStatus, setConnStatus] = useState<Record<string, 'idle' | 'testing' | 'ok' | 'error'>>({});
const [showAddForm, setShowAddForm] = useState(false);
const [newGenre, setNewGenre] = useState('');
const [lfmState, setLfmState] = useState<'idle' | 'waiting' | 'error'>('idle');
const [lfmPendingToken, setLfmPendingToken] = useState<string | null>(null);
const [lfmError, setLfmError] = useState<string | null>(null);
const [lfmUserInfo, setLfmUserInfo] = useState<LastfmUserInfo | null>(null);
useEffect(() => {
if (!auth.lastfmSessionKey || !auth.lastfmUsername) { setLfmUserInfo(null); return; }
lastfmGetUserInfo(auth.lastfmUsername, auth.lastfmSessionKey).then(setLfmUserInfo).catch(() => {});
}, [auth.lastfmSessionKey, auth.lastfmUsername]);
const startLastfmConnect = useCallback(async () => {
setLfmError(null);
let token: string;
try {
token = await lastfmGetToken();
setLfmPendingToken(token);
setLfmState('waiting');
await openUrl(lastfmAuthUrl(token));
} catch (e: any) {
setLfmError(e.message ?? 'Unknown error');
setLfmState('error');
return;
}
// Poll every 2 s until the user authorises or we time out (2 min)
const deadline = Date.now() + 120_000;
const poll = async () => {
if (Date.now() > deadline) {
setLfmState('error');
setLfmError('Timed out — please try again.');
setLfmPendingToken(null);
return;
}
try {
const { key, name } = await lastfmGetSession(token);
auth.connectLastfm(key, name);
setLfmState('idle');
setLfmPendingToken(null);
} catch (e: any) {
// Error 14 = not yet authorised, keep polling
if (e.message?.includes('14')) {
setTimeout(poll, 2000);
} else {
setLfmState('error');
setLfmError(e.message ?? 'Unknown error');
setLfmPendingToken(null);
}
}
};
setTimeout(poll, 2000);
}, [auth]);
const testConnection = async (server: ServerProfile) => {
setConnStatus(s => ({ ...s, [server.id]: 'testing' }));
@@ -275,22 +329,36 @@ export default function Settings() {
</div>
</section>
{/* Scrobbling */}
{/* Last.fm */}
<section className="settings-section">
<div className="settings-section-header">
<Music2 size={18} />
<h2>{t('settings.lfmTitle')}</h2>
</div>
<div className="settings-card">
<div style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: '1rem', lineHeight: 1.5 }}>
<p style={{ marginBottom: '0.5rem' }}>
{t('settings.lfmDesc1')}{' '}
<strong>{t('settings.lfmDesc1NavidromeWebplayer')}</strong>
{' '}{t('settings.lfmDesc1b')}
</p>
<p>{t('settings.lfmDesc2')}</p>
{auth.lastfmSessionKey ? (
/* ── Connected state ── */
<div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', padding: '0.75rem 1rem', borderRadius: '10px', background: 'color-mix(in srgb, var(--accent) 8%, transparent)', border: '1px solid color-mix(in srgb, var(--accent) 20%, transparent)' }}>
<div style={{ flexShrink: 0, color: '#e31c23' }}><LastfmIcon size={20} /></div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontWeight: 600, fontSize: 14 }}>@{auth.lastfmUsername}</div>
{lfmUserInfo && (
<div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 2, display: 'flex', gap: '0.75rem' }}>
<span>{t('settings.lfmScrobbles', { count: lfmUserInfo.playcount.toLocaleString() })}</span>
<span>{t('settings.lfmMemberSince', { year: new Date(lfmUserInfo.registeredAt * 1000).getFullYear() })}</span>
</div>
<div className="settings-toggle-row" style={{ marginTop: '1rem' }}>
)}
</div>
<button
className="btn btn-ghost"
style={{ fontSize: 12, padding: '4px 10px', flexShrink: 0 }}
onClick={() => auth.disconnectLastfm()}
>
{t('settings.lfmDisconnect')}
</button>
</div>
<div className="settings-toggle-row">
<div>
<div style={{ fontWeight: 500 }}>{t('settings.scrobbleEnabled')}</div>
<div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{t('settings.scrobbleDesc')}</div>
@@ -301,6 +369,39 @@ export default function Settings() {
</label>
</div>
</div>
) : lfmState === 'waiting' ? (
/* ── Waiting for browser auth — auto-polling ── */
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem', fontSize: 13, color: 'var(--text-secondary)' }}>
<div className="spinner" style={{ width: 16, height: 16, borderWidth: 2 }} />
{t('settings.lfmConnecting')}
</div>
<button className="btn btn-ghost" style={{ alignSelf: 'flex-start', fontSize: 12 }}
onClick={() => { setLfmState('idle'); setLfmPendingToken(null); }}>
{t('common.cancel')}
</button>
</div>
) : (
/* ── Not connected ── */
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
<p style={{ fontSize: 13, color: 'var(--text-secondary)', lineHeight: 1.5 }}>
{t('settings.lfmConnectDesc')}
</p>
{lfmState === 'error' && (
<p style={{ fontSize: 12, color: 'var(--danger)' }}>{lfmError}</p>
)}
{lastfmIsConfigured() ? (
<button className="btn btn-primary" style={{ alignSelf: 'flex-start' }} onClick={startLastfmConnect}>
{t('settings.lfmConnect')}
</button>
) : (
<p style={{ fontSize: 12, color: 'var(--warning)' }}>
VITE_LASTFM_API_KEY / VITE_LASTFM_API_SECRET not set in build environment.
</p>
)}
</div>
)}
</div>
</section>
</>
)}
@@ -430,21 +531,21 @@ export default function Settings() {
</div>
<div className="settings-card">
<div className="form-group" style={{ maxWidth: '300px' }}>
<select
className="input"
<CustomSelect
value={theme.theme}
onChange={(e) => theme.setTheme(e.target.value as any)}
aria-label={t('settings.theme')}
>
<option value="mocha">Catppuccin Mocha</option>
<option value="macchiato">Catppuccin Macchiato</option>
<option value="frappe">Catppuccin Frappé</option>
<option value="latte">Catppuccin Latte</option>
<option value="nord">Nord · Polar Night</option>
<option value="nord-snowstorm">Nord · Snowstorm</option>
<option value="nord-frost">Nord · Frost</option>
<option value="nord-aurora">Nord · Aurora</option>
</select>
onChange={v => theme.setTheme(v as any)}
options={[
{ value: 'mocha', label: 'Catppuccin Mocha' },
{ value: 'macchiato', label: 'Catppuccin Macchiato' },
{ value: 'frappe', label: 'Catppuccin Frappé' },
{ value: 'latte', label: 'Catppuccin Latte' },
{ value: 'nord', label: 'Nord · Polar Night' },
{ value: 'nord-snowstorm', label: 'Nord · Snowstorm' },
{ value: 'nord-frost', label: 'Nord · Frost' },
{ value: 'nord-aurora', label: 'Nord · Aurora' },
{ value: 'psychowave', label: 'Psychowave' },
]}
/>
</div>
</div>
</section>
@@ -456,15 +557,14 @@ export default function Settings() {
</div>
<div className="settings-card">
<div className="form-group" style={{ maxWidth: '300px' }}>
<select
className="input"
<CustomSelect
value={i18n.language}
onChange={(e) => i18n.changeLanguage(e.target.value)}
aria-label={t('settings.language')}
>
<option value="en">{t('settings.languageEn')}</option>
<option value="de">{t('settings.languageDe')}</option>
</select>
onChange={v => i18n.changeLanguage(v)}
options={[
{ value: 'en', label: t('settings.languageEn') },
{ value: 'de', label: t('settings.languageDe') },
]}
/>
</div>
</div>
</section>
+153 -29
View File
@@ -1,34 +1,87 @@
import React, { useEffect, useState } from 'react';
import { getAlbumList, getArtists, getGenres, SubsonicAlbum, SubsonicGenre } from '../api/subsonic';
import { getAlbumList, getArtists, getGenres, SubsonicAlbum } from '../api/subsonic';
import AlbumRow from '../components/AlbumRow';
import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../store/authStore';
import { lastfmIsConfigured, lastfmGetTopArtists, lastfmGetTopAlbums, lastfmGetTopTracks, lastfmGetRecentTracks, LastfmPeriod, LastfmTopArtist, LastfmTopAlbum, LastfmTopTrack, LastfmRecentTrack } from '../api/lastfm';
function relativeTime(timestamp: number, t: (key: string, opts?: object) => string): string {
const diff = Math.floor(Date.now() / 1000) - timestamp;
if (diff < 60) return t('statistics.lfmJustNow');
if (diff < 3600) return t('statistics.lfmMinutesAgo', { n: Math.floor(diff / 60) });
if (diff < 86400) return t('statistics.lfmHoursAgo', { n: Math.floor(diff / 3600) });
return t('statistics.lfmDaysAgo', { n: Math.floor(diff / 86400) });
}
const PERIODS: { key: LastfmPeriod; label: string }[] = [
{ key: '7day', label: 'lfmPeriod7day' },
{ key: '1month', label: 'lfmPeriod1month' },
{ key: '3month', label: 'lfmPeriod3month' },
{ key: '6month', label: 'lfmPeriod6month' },
{ key: '12month', label: 'lfmPeriod12month' },
{ key: 'overall', label: 'lfmPeriodOverall' },
];
export default function Statistics() {
const { t } = useTranslation();
const { lastfmSessionKey, lastfmUsername } = useAuthStore();
const [recent, setRecent] = useState<SubsonicAlbum[]>([]);
const [frequent, setFrequent] = useState<SubsonicAlbum[]>([]);
const [highest, setHighest] = useState<SubsonicAlbum[]>([]);
const [genres, setGenres] = useState<SubsonicGenre[]>([]);
const [artistCount, setArtistCount] = useState<number | null>(null);
const [totalSongs, setTotalSongs] = useState<number | null>(null);
const [totalAlbums, setTotalAlbums] = useState<number | null>(null);
const [loading, setLoading] = useState(true);
const [lfmPeriod, setLfmPeriod] = useState<LastfmPeriod>('1month');
const [lfmTopArtists, setLfmTopArtists] = useState<LastfmTopArtist[]>([]);
const [lfmTopAlbums, setLfmTopAlbums] = useState<LastfmTopAlbum[]>([]);
const [lfmTopTracks, setLfmTopTracks] = useState<LastfmTopTrack[]>([]);
const [lfmLoading, setLfmLoading] = useState(false);
const [lfmRecentTracks, setLfmRecentTracks] = useState<LastfmRecentTrack[]>([]);
const [lfmRecentLoading, setLfmRecentLoading] = useState(false);
useEffect(() => {
Promise.all([
getAlbumList('recent', 20).catch(() => []),
getAlbumList('frequent', 12).catch(() => []),
getAlbumList('highest', 12).catch(() => []),
getGenres().catch(() => []),
getArtists().catch(() => []),
]).then(([rc, fr, hi, g, a]) => {
getGenres().catch(() => []),
]).then(([rc, fr, hi, a, g]) => {
setRecent(rc);
setFrequent(fr);
setHighest(hi);
setGenres(g.sort((a, b) => b.songCount - a.songCount).slice(0, 20));
setArtistCount(a.length);
setTotalSongs(g.reduce((acc: number, genre: any) => acc + genre.songCount, 0));
setTotalAlbums(g.reduce((acc: number, genre: any) => acc + genre.albumCount, 0));
setLoading(false);
}).catch(() => setLoading(false));
}, []);
useEffect(() => {
if (!lastfmIsConfigured() || !lastfmSessionKey || !lastfmUsername) return;
setLfmRecentLoading(true);
lastfmGetRecentTracks(lastfmUsername, lastfmSessionKey, 20)
.then(tracks => { setLfmRecentTracks(tracks); setLfmRecentLoading(false); })
.catch(() => setLfmRecentLoading(false));
}, [lastfmSessionKey, lastfmUsername]);
useEffect(() => {
if (!lastfmIsConfigured() || !lastfmSessionKey || !lastfmUsername) return;
setLfmLoading(true);
Promise.all([
lastfmGetTopArtists(lastfmUsername, lastfmSessionKey, lfmPeriod, 10),
lastfmGetTopAlbums(lastfmUsername, lastfmSessionKey, lfmPeriod, 10),
lastfmGetTopTracks(lastfmUsername, lastfmSessionKey, lfmPeriod, 10),
]).then(([artists, albums, tracks]) => {
setLfmTopArtists(artists);
setLfmTopAlbums(albums);
setLfmTopTracks(tracks);
setLfmLoading(false);
}).catch(() => setLfmLoading(false));
}, [lfmPeriod, lastfmSessionKey, lastfmUsername]);
const loadMore = async (
type: 'frequent' | 'highest',
currentList: SubsonicAlbum[],
@@ -43,15 +96,10 @@ export default function Statistics() {
}
};
const totalSongs = genres.reduce((acc, g) => acc + g.songCount, 0);
const totalAlbums = genres.reduce((acc, g) => acc + g.albumCount, 0);
const maxGenreCount = Math.max(...genres.map(g => g.songCount), 1);
const stats = [
{ label: t('statistics.statArtists'), value: artistCount },
{ label: t('statistics.statAlbums'), value: totalAlbums || null },
{ label: t('statistics.statSongs'), value: totalSongs || null },
{ label: t('statistics.statGenres'), value: genres.length || null },
{ label: t('statistics.statAlbums'), value: totalAlbums },
{ label: t('statistics.statSongs'), value: totalSongs },
];
return (
@@ -90,29 +138,105 @@ export default function Statistics() {
moreText={t('statistics.loadMore')}
/>
{genres.length > 0 && (
<section>
<h2 className="section-title">{t('statistics.genreDistribution')}</h2>
<div className="genre-chart">
{genres.map(genre => (
<div key={genre.value} className="genre-row">
<div className="genre-row-header">
<span className="genre-name">{genre.value}</span>
<span className="genre-counts">
{t('statistics.genreSongs', { count: genre.songCount })}
{' · '}
{t('statistics.genreAlbums', { count: genre.albumCount })}
{/* Last.fm Stats */}
{lastfmIsConfigured() && (
<section style={{ marginTop: '2rem' }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: '0.75rem', marginBottom: '1rem' }}>
<h2 className="section-title" style={{ margin: 0 }}>{t('statistics.lfmTitle')}</h2>
{lastfmSessionKey && (
<div style={{ display: 'flex', gap: '0.375rem', flexWrap: 'wrap' }}>
{PERIODS.map(p => (
<button
key={p.key}
className={`btn btn-sm ${lfmPeriod === p.key ? 'btn-primary' : 'btn-surface'}`}
onClick={() => setLfmPeriod(p.key)}
style={{ padding: '0.25rem 0.625rem', fontSize: '0.75rem' }}
>
{t(`statistics.${p.label}`)}
</button>
))}
</div>
)}
</div>
{!lastfmSessionKey ? (
<p style={{ color: 'var(--text-muted)', fontSize: '0.875rem' }}>{t('statistics.lfmNotConnected')}</p>
) : lfmLoading ? (
<div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', color: 'var(--text-muted)', fontSize: '0.875rem', padding: '1rem 0' }}>
<div className="spinner" style={{ width: 16, height: 16, borderTopColor: 'currentColor' }} />
</div>
) : (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: '1rem' }}>
{([
{ label: t('statistics.lfmTopArtists'), items: lfmTopArtists.map(a => ({ primary: a.name, secondary: null, playcount: a.playcount })) },
{ label: t('statistics.lfmTopAlbums'), items: lfmTopAlbums.map(a => ({ primary: a.name, secondary: a.artist, playcount: a.playcount })) },
{ label: t('statistics.lfmTopTracks'), items: lfmTopTracks.map(tr => ({ primary: tr.name, secondary: tr.artist, playcount: tr.playcount })) },
] as { label: string; items: { primary: string; secondary: string | null; playcount: string }[] }[]).map(col => {
const max = Math.max(...col.items.map(it => Number(it.playcount)), 1);
return (
<div key={col.label} style={{ background: 'var(--glass-bg)', border: '1px solid var(--glass-border)', borderRadius: '12px', padding: '1.25rem', backdropFilter: 'blur(8px)' }}>
<h3 style={{ fontSize: '0.7rem', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--accent)', marginBottom: '1rem' }}>
{col.label}
</h3>
<ol style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: '0.875rem' }}>
{col.items.map((it, i) => (
<li key={`${it.primary}-${i}`}>
<div style={{ display: 'flex', alignItems: 'baseline', gap: '0.625rem', marginBottom: '0.25rem' }}>
<span style={{ fontSize: '1.1rem', fontWeight: 800, color: i === 0 ? 'var(--accent)' : 'var(--text-muted)', opacity: i === 0 ? 1 : 0.5, lineHeight: 1, flexShrink: 0, width: '1.5rem' }}>
{i + 1}
</span>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: '0.875rem', fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.primary}</div>
{it.secondary && (
<div style={{ fontSize: '0.75rem', color: 'var(--text-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.secondary}</div>
)}
</div>
<div className="genre-bar-track">
<div
className="genre-bar-fill"
style={{ width: `${(genre.songCount / maxGenreCount) * 100}%` }}
/>
<span style={{ fontSize: '0.7rem', color: 'var(--text-muted)', flexShrink: 0 }}>{Number(it.playcount).toLocaleString()}</span>
</div>
<div style={{ height: '2px', borderRadius: '1px', background: 'var(--glass-border)', overflow: 'hidden', marginLeft: '2.125rem' }}>
<div style={{ height: '100%', width: `${(Number(it.playcount) / max) * 100}%`, background: i === 0 ? 'var(--accent)' : 'var(--text-muted)', opacity: i === 0 ? 0.8 : 0.3, borderRadius: '1px', transition: 'width 0.4s ease' }} />
</div>
</li>
))}
</ol>
</div>
);
})}
</div>
)}
</section>
)}
{/* Recent Scrobbles */}
{lastfmIsConfigured() && lastfmSessionKey && (
<section style={{ marginTop: '2rem' }}>
<h2 className="section-title" style={{ marginBottom: '1rem' }}>{t('statistics.lfmRecentTracks')}</h2>
{lfmRecentLoading ? (
<div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', color: 'var(--text-muted)', fontSize: '0.875rem' }}>
<div className="spinner" style={{ width: 16, height: 16, borderTopColor: 'currentColor' }} />
</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.375rem' }}>
{lfmRecentTracks.map((track, i) => (
<div key={`${track.name}-${i}`} style={{ display: 'flex', alignItems: 'center', gap: '1rem', padding: '0.5rem 0.75rem', borderRadius: '8px', background: track.nowPlaying ? 'color-mix(in srgb, var(--accent) 8%, transparent)' : 'transparent', border: track.nowPlaying ? '1px solid color-mix(in srgb, var(--accent) 20%, transparent)' : '1px solid transparent' }}>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
<span style={{ fontSize: '0.875rem', fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{track.name}</span>
{track.nowPlaying && (
<span style={{ fontSize: '0.65rem', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--accent)', flexShrink: 0 }}>{t('statistics.lfmNowPlaying')}</span>
)}
</div>
<div style={{ fontSize: '0.75rem', color: 'var(--text-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{track.artist}{track.album ? ` · ${track.album}` : ''}
</div>
</div>
<span style={{ fontSize: '0.7rem', color: 'var(--text-muted)', flexShrink: 0 }}>
{track.nowPlaying ? '' : track.timestamp ? relativeTime(track.timestamp, t) : ''}
</span>
</div>
))}
</div>
)}
</section>
)}
+8
View File
@@ -47,6 +47,8 @@ interface AuthState {
setConnecting: (v: boolean) => void;
setConnectionError: (e: string | null) => void;
setLastfm: (apiKey: string, apiSecret: string, sessionKey: string, username: string) => void;
connectLastfm: (sessionKey: string, username: string) => void;
disconnectLastfm: () => void;
setMinimizeToTray: (v: boolean) => void;
setScrobblingEnabled: (v: boolean) => void;
setMaxCacheMb: (v: number) => void;
@@ -126,6 +128,12 @@ export const useAuthStore = create<AuthState>()(
setLastfm: (apiKey, apiSecret, sessionKey, username) =>
set({ lastfmApiKey: apiKey, lastfmApiSecret: apiSecret, lastfmSessionKey: sessionKey, lastfmUsername: username }),
connectLastfm: (sessionKey, username) =>
set({ lastfmSessionKey: sessionKey, lastfmUsername: username }),
disconnectLastfm: () =>
set({ lastfmSessionKey: '', lastfmUsername: '' }),
setMinimizeToTray: (v) => set({ minimizeToTray: v }),
setScrobblingEnabled: (v) => set({ scrobblingEnabled: v }),
setMaxCacheMb: (v) => set({ maxCacheMb: v }),
+82 -4
View File
@@ -2,7 +2,8 @@ import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import { buildStreamUrl, getPlayQueue, savePlayQueue, SubsonicSong, reportNowPlaying, scrobbleSong } from '../api/subsonic';
import { buildStreamUrl, getPlayQueue, savePlayQueue, reportNowPlaying, SubsonicSong } from '../api/subsonic';
import { lastfmScrobble, lastfmUpdateNowPlaying, lastfmLoveTrack, lastfmUnloveTrack, lastfmGetTrackLoved, lastfmGetAllLovedTracks } from '../api/lastfm';
import { useAuthStore } from './authStore';
export interface Track {
@@ -55,6 +56,8 @@ interface PlayerState {
currentTime: number;
volume: number;
scrobbled: boolean;
lastfmLoved: boolean;
lastfmLovedCache: Record<string, boolean>;
playTrack: (track: Track, queue?: Track[]) => void;
pause: () => void;
@@ -83,6 +86,11 @@ interface PlayerState {
removeTrack: (index: number) => void;
shuffleQueue: () => void;
toggleLastfmLove: () => void;
setLastfmLoved: (v: boolean) => void;
setLastfmLovedForSong: (title: string, artist: string, v: boolean) => void;
syncLastfmLovedTracks: () => Promise<void>;
initializeFromServerQueue: () => Promise<void>;
contextMenu: {
@@ -143,11 +151,13 @@ function handleAudioProgress(current_time: number, duration: number) {
const progress = current_time / dur;
usePlayerStore.setState({ currentTime: current_time, progress, buffered: 0 });
// Scrobble at 50%
// Scrobble at 50% directly via Last.fm
if (progress >= 0.5 && !store.scrobbled) {
usePlayerStore.setState({ scrobbled: true });
const { scrobblingEnabled } = useAuthStore.getState();
if (scrobblingEnabled) scrobbleSong(track.id, Date.now());
const { scrobblingEnabled, lastfmSessionKey } = useAuthStore.getState();
if (scrobblingEnabled && lastfmSessionKey) {
lastfmScrobble(track, Date.now(), lastfmSessionKey);
}
}
// Gapless preload: buffer next track when 30s remain
@@ -205,6 +215,9 @@ export function initAudioListeners(): () => void {
listen<string>('audio:error', ({ payload }) => handleAudioError(payload)),
];
// Sync Last.fm loved tracks cache on startup.
usePlayerStore.getState().syncLastfmLovedTracks();
// Initial sync of crossfade settings to Rust audio engine on startup.
const { crossfadeEnabled, crossfadeSecs } = useAuthStore.getState();
invoke('audio_set_crossfade', { enabled: crossfadeEnabled, secs: crossfadeSecs }).catch(() => {});
@@ -237,6 +250,8 @@ export const usePlayerStore = create<PlayerState>()(
currentTime: 0,
volume: 0.8,
scrobbled: false,
lastfmLoved: false,
lastfmLovedCache: {},
isQueueVisible: true,
isFullscreenOpen: false,
repeatMode: 'off',
@@ -253,6 +268,55 @@ export const usePlayerStore = create<PlayerState>()(
setQueueVisible: (v: boolean) => set({ isQueueVisible: v }),
toggleFullscreen: () => set(state => ({ isFullscreenOpen: !state.isFullscreenOpen })),
toggleLastfmLove: () => {
const { currentTrack, lastfmLoved } = get();
const { lastfmSessionKey } = useAuthStore.getState();
if (!currentTrack || !lastfmSessionKey) return;
const newLoved = !lastfmLoved;
const cacheKey = `${currentTrack.title}::${currentTrack.artist}`;
set(s => ({ lastfmLoved: newLoved, lastfmLovedCache: { ...s.lastfmLovedCache, [cacheKey]: newLoved } }));
if (newLoved) {
lastfmLoveTrack(currentTrack, lastfmSessionKey);
} else {
lastfmUnloveTrack(currentTrack, lastfmSessionKey);
}
},
setLastfmLoved: (v) => {
const { currentTrack } = get();
if (currentTrack) {
const cacheKey = `${currentTrack.title}::${currentTrack.artist}`;
set(s => ({ lastfmLoved: v, lastfmLovedCache: { ...s.lastfmLovedCache, [cacheKey]: v } }));
} else {
set({ lastfmLoved: v });
}
},
syncLastfmLovedTracks: async () => {
const { lastfmSessionKey, lastfmUsername } = useAuthStore.getState();
if (!lastfmSessionKey || !lastfmUsername) return;
const tracks = await lastfmGetAllLovedTracks(lastfmUsername, lastfmSessionKey);
const newCache: Record<string, boolean> = {};
for (const t of tracks) newCache[`${t.title}::${t.artist}`] = true;
// Merge with existing cache (local likes take precedence)
set(s => ({ lastfmLovedCache: { ...newCache, ...s.lastfmLovedCache } }));
// Update current track's loved state if it's in the new cache
const { currentTrack } = get();
if (currentTrack) {
const loved = newCache[`${currentTrack.title}::${currentTrack.artist}`] ?? false;
set({ lastfmLoved: loved });
}
},
setLastfmLovedForSong: (title, artist, v) => {
const cacheKey = `${title}::${artist}`;
const isCurrentTrack = get().currentTrack?.title === title && get().currentTrack?.artist === artist;
set(s => ({
lastfmLovedCache: { ...s.lastfmLovedCache, [cacheKey]: v },
...(isCurrentTrack ? { lastfmLoved: v } : {}),
}));
},
toggleRepeat: () => set(state => {
const modes = ['off', 'all', 'one'] as const;
return { repeatMode: modes[(modes.indexOf(state.repeatMode) + 1) % modes.length] };
@@ -285,6 +349,7 @@ export const usePlayerStore = create<PlayerState>()(
buffered: 0,
currentTime: 0,
scrobbled: false,
lastfmLoved: false,
isPlaying: true, // optimistic — reverted on error
});
@@ -310,7 +375,19 @@ export const usePlayerStore = create<PlayerState>()(
}, 500);
});
// Report Now Playing to Navidrome (for Live/getNowPlaying) + Last.fm
reportNowPlaying(track.id);
const { scrobblingEnabled: lfmEnabled, lastfmSessionKey: lfmKey } = useAuthStore.getState();
if (lfmKey) {
if (lfmEnabled) lastfmUpdateNowPlaying(track, lfmKey);
lastfmGetTrackLoved(track.title, track.artist, lfmKey).then(loved => {
const cacheKey = `${track.title}::${track.artist}`;
usePlayerStore.setState(s => ({
lastfmLoved: loved,
lastfmLovedCache: { ...s.lastfmLovedCache, [cacheKey]: loved },
}));
});
}
syncQueueToServer(newQueue, track, 0);
},
@@ -521,6 +598,7 @@ export const usePlayerStore = create<PlayerState>()(
queue: state.queue,
queueIndex: state.queueIndex,
currentTime: state.currentTime,
lastfmLovedCache: state.lastfmLovedCache,
} as Partial<PlayerState>),
}
)
+1 -1
View File
@@ -1,7 +1,7 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
type Theme = 'mocha' | 'macchiato' | 'frappe' | 'latte' | 'nord' | 'nord-snowstorm' | 'nord-frost' | 'nord-aurora';
type Theme = 'mocha' | 'macchiato' | 'frappe' | 'latte' | 'nord' | 'nord-snowstorm' | 'nord-frost' | 'nord-aurora' | 'psychowave';
interface ThemeState {
theme: Theme;
+92 -217
View File
@@ -1716,57 +1716,6 @@
}
}
/* ── Drifting color orbs ── */
@keyframes orb-a {
0% {
transform: translate(0px, 0px) scale(1);
}
33% {
transform: translate(90px, -50px) scale(1.12);
}
66% {
transform: translate(-40px, 70px) scale(0.94);
}
100% {
transform: translate(0px, 0px) scale(1);
}
}
@keyframes orb-b {
0% {
transform: translate(0px, 0px) scale(1);
}
33% {
transform: translate(-70px, 40px) scale(1.08);
}
66% {
transform: translate(50px, -60px) scale(1.14);
}
100% {
transform: translate(0px, 0px) scale(1);
}
}
@keyframes orb-c {
0% {
transform: translate(0px, 0px) scale(1);
}
50% {
transform: translate(60px, 50px) scale(0.9);
}
100% {
transform: translate(0px, 0px) scale(1);
}
}
/* ── Cover breathing ── */
@keyframes cover-breathe {
@@ -1781,38 +1730,23 @@
}
@keyframes ken-burns {
0% {
transform: scale(1.08) translate(0%, 0%);
}
25% {
transform: scale(1.12) translate(-1.5%, 1%);
}
50% {
transform: scale(1.10) translate(1%, -1.5%);
}
75% {
transform: scale(1.13) translate(1.5%, 0.5%);
}
100% {
transform: scale(1.08) translate(0%, 0%);
}
0% { transform: scale(1.1) translate(-8%, -8%); }
25% { transform: scale(1.15) translate(8%, -8%); }
50% { transform: scale(1.1) translate(8%, 8%); }
75% { transform: scale(1.15) translate(-8%, 8%); }
100% { transform: scale(1.1) translate(-8%, -8%); }
}
/* ── Blurred background ── */
.fs-bg {
position: absolute;
inset: -15%;
inset: -30%;
background-size: cover;
background-position: top center;
background-position: center center;
filter: blur(6px) brightness(0.25) saturate(1.6);
animation: ken-burns 40s ease-in-out infinite;
transform: scale(1.2);
animation: ken-burns 90s ease-in-out infinite;
z-index: 0;
will-change: opacity;
will-change: transform;
pointer-events: none;
transition: opacity 700ms ease;
}
@@ -1825,45 +1759,6 @@
pointer-events: none;
}
/* ── Drifting color orbs ── */
.fs-orb {
position: absolute;
border-radius: 50%;
filter: blur(110px);
opacity: 0.22;
pointer-events: none;
z-index: 0;
}
.fs-orb-1 {
background: var(--ctp-mauve);
width: 700px;
height: 700px;
top: -220px;
left: -180px;
animation: orb-a 20s ease-in-out infinite;
}
.fs-orb-2 {
background: var(--ctp-blue);
width: 600px;
height: 600px;
bottom: -180px;
right: -120px;
animation: orb-b 26s ease-in-out infinite;
animation-delay: -9s;
}
.fs-orb-3 {
background: var(--ctp-lavender);
width: 480px;
height: 480px;
top: 35%;
right: 5%;
animation: orb-c 17s ease-in-out infinite;
animation-delay: -14s;
}
/* ── Close button ── */
.fs-close {
position: absolute;
@@ -2272,71 +2167,11 @@
}
/* ─ CSS Tooltips ─ */
/* Tooltips are handled by TooltipPortal (React portal) — no CSS pseudo-elements needed */
[data-tooltip] {
position: relative;
}
[data-tooltip]::before,
[data-tooltip]::after {
position: absolute;
opacity: 0;
visibility: hidden;
transition: opacity 0.2s ease, visibility 0.2s ease;
pointer-events: none;
z-index: 9999;
}
[data-tooltip]::before {
content: '';
border: 5px solid transparent;
border-top-color: var(--border-subtle);
bottom: 100%;
left: 50%;
transform: translateX(-50%);
}
/* Inner triangle for the tooltip arrow to match background */
[data-tooltip]::after {
content: attr(data-tooltip);
background: var(--bg-card);
color: var(--text-primary);
padding: var(--space-1) var(--space-2);
border-radius: var(--radius-sm);
font-size: 12px;
bottom: calc(100% + 6px);
left: 50%;
transform: translateX(-50%);
white-space: nowrap;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.6);
font-weight: 500;
border: 1px solid var(--border-subtle);
}
[data-tooltip]:hover::before,
[data-tooltip]:hover::after {
opacity: 1;
visibility: visible;
}
[data-tooltip-wrap]::after {
white-space: pre-line;
max-width: 220px;
text-align: left;
}
/* Modifiers for position */
[data-tooltip][data-tooltip-pos="bottom"]::before {
top: 100%;
bottom: auto;
border-top-color: transparent;
border-bottom-color: var(--border-subtle);
}
[data-tooltip][data-tooltip-pos="bottom"]::after {
top: calc(100% + 6px);
bottom: auto;
}
/* ─ Playlists Page ─ */
.playlist-page-header {
@@ -2479,7 +2314,7 @@
.stats-overview {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-columns: repeat(3, 1fr);
gap: var(--space-4);
}
@@ -2746,47 +2581,6 @@
background: linear-gradient(to bottom, transparent 40%, var(--bg-app) 100%);
}
/* Orbs will-change promotes each to its own compositor layer so
the blur is composited on the GPU and doesn't repaint on every frame */
.np-orb {
position: absolute;
border-radius: 50%;
filter: blur(70px);
opacity: 0.3;
pointer-events: none;
z-index: 0;
will-change: transform;
}
.np-orb-1 {
background: var(--ctp-mauve);
width: 400px;
height: 400px;
top: -120px;
left: -80px;
animation: orb-a 18s ease-in-out infinite;
}
.np-orb-2 {
background: var(--ctp-blue);
width: 320px;
height: 320px;
bottom: -80px;
right: -60px;
animation: orb-b 24s ease-in-out infinite;
animation-delay: -9s;
}
.np-orb-3 {
background: var(--ctp-lavender);
width: 260px;
height: 260px;
top: 30%;
right: 10%;
animation: orb-c 15s ease-in-out infinite;
animation-delay: -5s;
}
.np-hero-content {
position: relative;
z-index: 1;
@@ -3208,6 +3002,87 @@
min-width: 140px;
}
/* ─ Custom Select ─ */
.custom-select-trigger {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
width: 100%;
padding: 0.5rem 0.75rem;
background: var(--bg-input);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
color: var(--text-primary);
font-size: 0.875rem;
cursor: pointer;
text-align: left;
transition: border-color 0.15s, background 0.15s;
}
.custom-select-trigger:hover {
border-color: var(--accent);
background: var(--bg-hover);
}
.custom-select-trigger:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.custom-select-label {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.custom-select-chevron {
flex-shrink: 0;
color: var(--text-muted);
transition: transform 0.2s ease;
}
.custom-select-chevron.open {
transform: rotate(180deg);
}
.custom-select-dropdown {
background: var(--bg-card);
border: 1px solid var(--border-subtle);
border-radius: var(--radius-md);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
overflow-y: auto;
overscroll-behavior: contain;
}
.custom-select-option {
padding: 0.5rem 0.75rem;
font-size: 0.875rem;
color: var(--text-primary);
cursor: pointer;
transition: background 0.1s;
}
.custom-select-option:hover {
background: var(--bg-hover);
}
.custom-select-option.selected {
color: var(--accent);
font-weight: 600;
background: color-mix(in srgb, var(--accent) 8%, transparent);
}
.custom-select-option.disabled {
color: var(--text-muted);
cursor: default;
}
.custom-select-group-label {
padding: 0.375rem 0.75rem 0.25rem;
font-size: 0.7rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--text-muted);
border-top: 1px solid var(--border-subtle);
margin-top: 0.25rem;
}
.custom-select-group-label:first-child {
border-top: none;
margin-top: 0;
}
.eq-ctrl-btn {
background: var(--bg-hover);
border: 1px solid var(--border);
+55
View File
@@ -422,6 +422,61 @@
--danger: #bf616a;
}
/* ─── Psychowave — Synthwave / Retrowave ─── */
[data-theme='psychowave'] {
color-scheme: dark;
--select-arrow: url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2224%22%20height%3D%2224%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%23c9a8ff%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpolyline%20points%3D%226%209%2012%2015%2018%209%22%3E%3C%2Fpolyline%3E%3C%2Fsvg%3E");
/* ── Palette ── */
--ctp-crust: #120720;
--ctp-mantle: #160a28;
--ctp-base: #1c0b35;
--ctp-surface0: #2a1050;
--ctp-surface1: #381860;
--ctp-surface2: #4a2878;
--ctp-overlay0: #5e3d90;
--ctp-overlay1: #7b50b8;
--ctp-overlay2: #9868d8;
/* Soft lavender text */
--ctp-text: #f0e6ff;
--ctp-subtext1: #c9a8ff;
--ctp-subtext0: #a882e0;
/* Neon accents */
--ctp-mauve: #ff2d78; /* hot pink — primary accent & button gradient start */
--ctp-lavender: #bf5fff; /* electric purple — button gradient end */
--ctp-pink: #ff2d78;
--ctp-flamingo: #ff6b9d;
--ctp-rosewater: #ff8fc0;
--ctp-blue: #00d4ff; /* electric cyan */
--ctp-sapphire: #007aff;
--ctp-sky: #00bfff;
--ctp-teal: #00e5cc;
--ctp-green: #39ff14; /* neon green */
--ctp-yellow: #ffd700; /* neon gold */
--ctp-peach: #ff8c42;
--ctp-maroon: #ff4d6d;
--ctp-red: #ff2d55;
/* ── Semantic tokens ── */
--bg-app: #1c0b35;
--bg-sidebar: #160a28;
--bg-card: #2a1050;
--bg-hover: #381860;
--bg-player: #120720;
--bg-glass: rgba(28, 11, 53, 0.82);
--accent: #ff2d78;
--accent-dim: rgba(255, 45, 120, 0.15);
--accent-glow: rgba(255, 45, 120, 0.45);
--text-primary: #f0e6ff;
--text-secondary:#c9a8ff;
--text-muted: #9b72d0;
--border: #4a2878;
--border-subtle: #2a1050;
--positive: #39ff14;
--warning: #ffd700;
--danger: #ff2d55;
}
/* ─── Global Base Settings ─── */
:root {
/* Typography */