Compare commits

...

50 Commits

Author SHA1 Message Date
Psychotoxical 76da684c8d ci: add cmake to Linux build dependencies
Required by symphonia-adapter-libopus which bundles and compiles
libopus from source via CMake.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-14 22:28:59 +02:00
Psychotoxical 795701a447 chore(release): bump version to 1.34.11
- Changelog for v1.34.11 (Opus, Device Sync, community themes, SSL fix)
- Contributors updated in Settings About (PR #181, #182, #183)
- Version bumped to 1.34.11 in package.json, tauri.conf.json, Cargo.toml

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-14 22:28:15 +02:00
Psychotoxical 0a14123a0b docs(readme): add cmake as required build prerequisite
symphonia-adapter-libopus bundles libopus and compiles it via cmake.
Without cmake installed, cargo build fails with a C compiler error.
Added install instructions for Linux, macOS, and Windows.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-14 22:04:25 +02:00
Psychotoxical 7cd03248c8 Merge pull request #183 from cucadmuh/feat/opus-support
feat(audio): Opus playback via symphonia-adapter-libopus
2026-04-14 21:58:22 +02:00
Maxim Isaev 4c6fc4d6d5 merge: integrate origin/main into feat/opus-support 2026-04-14 22:52:35 +03:00
Psychotoxical 798812d5ef customization: 8 new themes have been implemented
customization: 8 new themes have been implemented
2026-04-14 21:47:51 +02:00
Psychotoxical 9f4c7382aa feat: add 3 visual toggles (cover art background, playlist cover photo, show bitrate)
feat: add 3 visual toggles (cover art background, playlist cover photo, show bitrate)
2026-04-14 21:47:48 +02:00
Psychotoxical d34de09673 feat(device-sync): overhaul Device Sync page
- New two-panel layout with live album search (search3, 300ms debounce)
  and 10 random albums when search is empty — replaces full paginated load
- Pre-sync summary modal: shows files to add/delete, net change, available
  space; Proceed button disabled when space is insufficient
- calculate_sync_payload now filters already-synced tracks (path exists on
  device) so add_bytes/add_count reflect the true delta
- Space check accounts for pending deletions: addBytes > availableBytes + delBytes
- Separate deviceSyncJobStore for ephemeral job progress state
- Removable drive detection + auto-poll every 5 s via sysinfo
- Desired-state diff: de-selecting a synced source stages it for deletion
  instead of silently removing it
- Status badges (Synced / Pending / Deletion) with matching row highlights
- Live-Search badge () and Zufallsalben section label (⇌) in album browser
- Status summary row height aligned with search field (52 px)
- i18n: all new keys added to all 8 locales (en/de/fr/nl/nb/zh/ru/es)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-14 21:37:35 +02:00
Maxim Isaev 1ff4f1ef0f feat(audio): add Opus playback via symphonia-adapter-libopus
Wire a lazy CodecRegistry built with symphonia::default::register_enabled_codecs
plus symphonia_adapter_libopus::OpusDecoder for SizedDecoder and radio decoders.

Raise package rust-version to 1.89 to match the MSRV required by
symphonia-adapter-libopus.
2026-04-14 22:17:29 +03:00
kveld9 9a9be253e3 8 new themes have been implemented 2026-04-14 14:40:23 -03:00
kveld9 38e59d7a5e feat: add 3 visual toggles (cover art background, playlist cover photo, show bitrate) 2026-04-14 14:21:48 -03:00
Psychotoxical 915f0143f7 fix(ssl): strip trailing slash in getBaseUrl + trust OS certificate store for HTTPS streaming
Fixes two bugs reported in #178:

- getBaseUrl() now strips trailing slashes from server URLs, consistent
  with restBaseFromUrl(). A trailing slash caused double-slash stream URLs
  (//rest/stream.view) which Caddy rejects. Trailing slash also caused
  browsing to return 0 results. Fix manually ported from PR #179 by kveld9.

- reqwest now loads the OS native certificate store in addition to
  Mozilla's webpki roots (rustls-tls-native-roots feature). Fixes HTTPS
  streaming failures where the server certificate is signed by a local CA
  (e.g. Caddy internal CA) that is trusted in the system keychain but not
  in Mozilla's root store.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-14 18:16:08 +02:00
Psychotoxical e0bb02b65e Update CHANGELOG.md 2026-04-14 11:48:51 +02:00
Psychotoxical 0d5011c5be Update CHANGELOG.md 2026-04-14 11:48:01 +02:00
Psychotoxical 34d899806a Update CHANGELOG.md 2026-04-14 11:47:01 +02:00
Psychotoxical 928cdba17a Update CHANGELOG.md 2026-04-14 11:42:55 +02:00
Psychotoxical 17a5c92174 feat(device-sync): USB/SD card sync page (WIP)
Adds a new Device Sync page for transferring music from Navidrome to
USB drives or SD cards. Sidebar entry is hidden by default.

- Four new Tauri commands: sync_track_to_device, compute_sync_paths,
  list_device_dir_files, delete_device_file
- Filename template engine with cross-platform path sanitization
- 4-concurrent-worker download, live progress via device:sync:progress event
- Persistent source list (albums/playlists/artists) with checkbox deletion
- Expandable artist tree in browser panel (per-album selection)
- i18n: DE + EN complete; other locales have stub keys

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-14 00:02:13 +02:00
Psychotoxical 58f99ae846 chore: bump version to 1.34.11-dev 2026-04-13 22:25:49 +02:00
Psychotoxical ef9a620ac6 chore(aur): bump pkgver to 1.34.10 2026-04-13 22:23:55 +02:00
Psychotoxical 01f71cf50c chore(release): bump version to 1.34.10
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 22:21:07 +02:00
Psychotoxical 39966d1c65 Create FUNDING.yml 2026-04-13 22:07:56 +02:00
Psychotoxical cbf72c7eba chore(about): add cucadmuh PR #176 to contributors
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 21:54:02 +02:00
cucadmuh 4207455440 fix(audio): Linux output device selection and watcher (#176)
* fix(audio): stabilize Linux output device picker and watcher

Keep pinned ALSA/cpal device ids stable when enumeration omits the active
sink or returns an equivalent name. Stop Linux device-watcher from clearing
the pin based on missing list entries; macOS and Windows still treat repeated
absence as unplugged. Settings refresh flow calls canonicalize and refetches
the list; add i18n for the out-of-list device label.

* fix(settings): sort audio output devices by label

cpal enumeration order is arbitrary; order the dropdown by readable label
and place the current OS default device first among concrete outputs.
2026-04-13 21:48:21 +02:00
Psychotoxical 9983d13122 chore(about): add kilyabin PR #175 to contributors
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 20:48:13 +02:00
kilyabin 1b55e88cd5 fix(fullscreen-player): stop mesh blob and portrait animations in no-compositing mode (#175)
In software compositing (WEBKIT_DISABLE_COMPOSITING_MODE=1), WebKit renders
entirely on the CPU. The mesh blob animations were not covered by the
no-compositing overrides: blob-a occupies 130×130% of the viewport, so each
frame the CPU had to composite a surface larger than the screen. On high-DPI
displays (e.g. 8K) this drops the fullscreen player to ~10 FPS.

- Stop mesh blob pan animations (static gradients are preserved)
- Stop portrait drift animation (filter was already removed)
- Remove box-shadow from the seekbar played bar (its width changes on every
  playback tick; in software mode each change triggers a box-shadow repaint)
2026-04-13 20:46:56 +02:00
Psychotoxical 2326f1f94b feat(linux): AppImage bundle + force X11/XWayland on all Linux packages
- CI: add squashfs-tools dep, APPIMAGE_EXTRACT_AND_RUN=1, appimage to
  --bundles, and *.AppImage to upload glob
- main.rs: set GDK_BACKEND=x11 and WEBKIT_DISABLE_COMPOSITING_MODE=1
  on Linux before Tauri init — WebKitGTK on Wayland is unstable;
  both vars are overridable by setting them before launch

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 20:45:00 +02:00
Psychotoxical 27ea221130 chore(about): update contributors, remove feature tagline, limit changelog to 3
- Add missing contributions: cucadmuh (PR #144, #167, #173, #174),
  kveld9 (PR #168), nisarg-78 (PR #115)
- Remove aboutFeatures tag line from all 8 locales (too dynamic to maintain)
- Changelog section now shows only the 3 most recent versions

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 20:23:22 +02:00
cucadmuh 9cd4743d1c feat(settings): audio output device picker (labels, OS default, live refresh) (#173)
* feat(settings): clearer audio device labels for duplicate ALSA names

Show HDMI outputs as "Card (HDMI n)" from hdmi:DEV indices; include PCM and
optional subdevice for hw/plughw/sysdefault; label other ALSA plugins with
iface and PCM. When labels still collide, append a structured hint
(iface · card · PCM) instead of only truncating the raw device string.

* feat(settings): improve audio output device picker

Parse ALSA-style ids into clearer labels (HDMI with DEV index, PCM/subdevice
for hw/plughw/sysdefault). Disambiguate colliding labels; share stderr
suppression for Linux device enumeration.

Add audio_default_output_device_name and tag the matching list entry as the
current system output (i18n). While the Audio tab is open, refresh list and
mark on audio:device-changed and audio:device-reset without toggling the
refresh spinner. Show an error toast if listing devices fails.
2026-04-13 20:13:22 +02:00
cucadmuh e75fda168e fix(folder-browser): arrow navigation only without modifiers (#174)
Skip column/list arrow handling when any modifier is down. Detect modifiers
via nativeEvent and getModifierState (WebKit/WebView), and match arrow keys
by both key and code. On row buttons, preventDefault for plain arrows only
to avoid native focus/scroll stealing navigation. Filter field ArrowDown uses
the same modifier check.
2026-04-13 20:13:10 +02:00
Psychotoxical ec021516c7 fix(audio): device-reset false positive + stderr noise + i18n tooltip
- Device watcher requires 3 consecutive misses (~9 s) before triggering
  audio:device-reset, preventing false positives when ALSA temporarily
  hides a busy device from output_devices() enumeration
- Add stderr suppression to open_stream_for_device_and_rate (last source
  of ALSA terminal noise on Linux)
- Fix tooltip showing raw key 'common.refresh' — replaced with
  settings.audioOutputDeviceRefresh (added to all 8 locales)
- Device switch restarts track from beginning (no seek-back)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 19:00:36 +02:00
Psychotoxical 82e1b458f3 fix(audio): clean up ALSA device names for display on Linux
Raw ALSA names like "sysdefault:CARD=U192k" are replaced with
readable labels ("U192k") in the device dropdown. The underlying
value stays unchanged so rodio can still open the correct device.

Covers: sysdefault, hw, plughw, iec958, front, surround prefixes.
Names without ALSA structure (pipewire, pulse, default) are kept as-is.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 18:46:53 +02:00
Psychotoxical fc7a5815ef feat(audio): add refresh button for device list in Settings
The module-level cache prevented newly connected USB audio devices
from appearing in the dropdown. Replace with a manual refresh button
(RotateCcw icon, spins while loading) next to the dropdown.

Device enumeration now runs on every Audio tab open and on explicit
refresh. ALSA stderr noise is already suppressed by the dup2 guard,
so re-enumeration is silent.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 18:38:58 +02:00
Psychotoxical 1cf5faff21 fix(audio): suppress ALSA stderr noise during device enumeration
Device watcher (3 s loop) and audio_list_devices both called
cpal output_devices(), triggering ALSA to probe unavailable backends
(JACK, OSS, dmix) and spam stderr with error messages.

Fix: redirect fd 2 to /dev/null for the duration of each enumeration
on Unix via libc dup/dup2 + RAII guard. Also add a module-level
cache in Settings.tsx so audio_list_devices is only invoked once
per app session instead of on every Audio tab activation.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 18:30:24 +02:00
Psychotoxical 16cb4f5a6f feat(audio): audio output device selection (closes #169)
Adds the ability to choose which audio output device Psysonic plays
through — useful for USB DACs, dedicated soundcards, and multi-device setups.

Rust (audio.rs):
- open_stream_for_device_and_rate(device_name, rate): opens a named
  device by cpal name, falls back to system default if not found
- AudioEngine.selected_device: persists the chosen device across
  stream reopens so hi-res rate switches stay on the right device
- audio_list_devices: Tauri command — returns all output device names
- audio_set_device: Tauri command — switches device immediately,
  drops old sinks, emits audio:device-changed
- start_device_watcher: now handles two cases:
    1. No pinned device + system default changed → reopen on new default
    2. Pinned device disappeared (DAC unplugged) → clear selected_device,
       fall back to system default, emit audio:device-reset

Frontend:
- authStore: audioOutputDevice (string | null), persisted
- playerStore: applies stored device on cold start
- App.tsx: listens to audio:device-reset, clears authStore device
  and restarts playback on the fallback device
- Settings → Audio tab: device dropdown at top (above Hi-Res and EQ),
  uses CustomSelect (portal-based, styled), all 8 locales
- CustomSelect: added disabled prop

Note: exclusive mode (WASAPI exclusive, CoreAudio exclusive) is out
of scope for now.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 18:20:23 +02:00
Psychotoxical 9b22327bb0 fix(login): clarify that https:// URLs are accepted in server URL field (#171)
https:// was already supported by the code (startsWith('http') check) but
the placeholder text only showed bare host:port examples, giving no hint
that a full URL with protocol is valid.

- Updated serverUrlPlaceholder in login namespace (all 8 locales) to show
  https://music.example.com as the domain example
- Added settings.serverUrlPlaceholder i18n key (all 8 locales) and wired it
  into AddServerForm — previously the placeholder was a hardcoded English string

Closes #171

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 17:59:19 +02:00
Psychotoxical dba89cc4e4 fix(offline): replace blocking overlay with slim banner; add server settings link (#170)
When offline with no cached content, the full-screen OfflineOverlay blocked
all navigation including Settings, making it impossible to fix a broken
server config. Replace it with the same slim banner used in offline-cache mode.

- OfflineBanner now handles both cases: cache (existing) and no-cache (new)
- No-cache banner shows server name and a direct link to Settings → Server tab
- OfflineOverlay component is no longer used (import removed from App.tsx)
- All 8 locales: added offlineNoCacheBanner and serverSettings keys

Fixes #170

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 17:52:17 +02:00
Psychotoxical 91d4cb58b8 feat: playlist management enhancements & UX improvements (#168)
- Multi-selection for Albums, Artists, Playlists with context menu bulk-add
- Collapsible playlist section in sidebar
- Infinite scroll on Artists page (IntersectionObserver)
- Submenu flip-up on viewport overflow
- Remove from Playlist in context menu
- All 8 locales synced

Fixes applied:
- title= → data-tooltip on playlist toggle button (CLAUDE.md)
- Hardcoded Spanish aria-label → i18n (sidebar.expandPlaylists/collapsePlaylists)
- AddToPlaylistSubmenu fetches playlists on first open if store empty

Co-Authored-By: kveld9 <kveld9@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 17:37:50 +02:00
Psychotoxical 374ebce9b5 feat(keybindings): in-app modifier chords; fix seek shortcut units (#167)
feat(keybindings): in-app modifier chords; fix seek shortcut units
2026-04-13 17:35:45 +02:00
Psychotoxical 083c5f62cb fix(pr168): title→data-tooltip, i18n playlist toggle, cold-start playlist fetch
- Replace title= with data-tooltip on sidebar playlist expand button (CLAUDE.md)
- Replace hardcoded Spanish aria-label strings with i18n keys (sidebar.expandPlaylists / collapsePlaylists) across all 8 locales
- AddToPlaylistSubmenu now fetches playlists on first open if store is empty (regression fix)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 17:33:56 +02:00
kveld9 592a479c30 fixed some bugs 2026-04-12 20:43:31 -03:00
Maxim Isaev 6439200e95 feat(keybindings): in-app modifier chords; fix seek shortcut units
Persist chords as ctrl/alt/shift/super plus key code; legacy single-key
bindings still match without modifiers. Settings capture uses buildInAppBinding;
App uses matchInAppBinding and skips chords also registered as global shortcuts.
Share MODIFIER_KEY_CODES and formatBinding with global shortcut formatting.

Fix seek-forward/backward hotkeys: seek() expects 0-1 progress, not seconds.
2026-04-13 01:01:50 +03:00
kveld9 9cb1471170 chore: apply stashed changes 2026-04-12 17:55:13 -03:00
kveld9 21e26e2604 chore: remove tauri generated schemas from tracking 2026-04-12 17:54:16 -03:00
kveld9 94323e91fa fixed bugs 2026-04-12 17:53:52 -03:00
kveld9 bef6941a2b feat: add multi-selection and context menu for playlist management 2026-04-12 17:53:52 -03:00
Psychotoxical 805b6bf163 chore(gen): update Tauri schema files
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 18:44:51 +02:00
Psychotoxical fee454da5d fix(folder-browser): correct --bg-base to --bg-app in filter bar; add cucadmuh PR #165
--bg-base is undefined — sticky filter bar would have rendered transparent.
Also added PR #165 to cucadmuh's contributions in Settings About.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 18:44:40 +02:00
Psychotoxical a765bcd5d0 feat(themes): add Vision Dark & Vision Navy colorblind-safe themes (closes #166)
Purple & Gold palette (Deuteranopia / Protanopia / Tritanopia safe).
Vision Dark: near-black #0D0B12 + Gold #FFD700 (~14.7:1 WCAG AAA).
Vision Navy: deep navy #0A1628 + Gold #FFD700 (~14.5:1 WCAG AAA).
New 'Accessibility' group in ThemePicker.
Removed stale theme count from aboutFeatures across all locales.

This is an initial step toward colorblind accessibility — color variables
alone cannot cover all CVD use cases. Structural improvements (secondary
indicators, pattern/shape cues) are still needed in future iterations.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 18:44:29 +02:00
Psychotoxical 7e50c7af40 feat(folder-browser): per-column filter keyboard flow
feat(folder-browser): per-column filter keyboard flow
2026-04-12 18:41:08 +02:00
Maxim Isaev a12d6a4015 feat(folder-browser): add per-column filter and queue append hotkey flow
Add Ctrl+F filtering for the active Folder Browser column with keyboard handoff between filter and rows, and clear right-side filters when parent selection changes.

When pressing Shift+Enter on a filtered track list, append visible tracks to the queue instead of replacing the current queue.
2026-04-12 14:08:36 +03:00
60 changed files with 7148 additions and 13435 deletions
+15
View File
@@ -0,0 +1,15 @@
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: psychotoxic
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
polar: # Replace with a single Polar username
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
thanks_dev: # Replace with a single thanks.dev username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+4 -3
View File
@@ -125,7 +125,7 @@ jobs:
sudo apt-get update
sudo apt-get install -y \
libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf \
libasound2-dev
libasound2-dev squashfs-tools cmake
- name: setup node
uses: actions/setup-node@v5
@@ -148,7 +148,8 @@ jobs:
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
APPIMAGE_EXTRACT_AND_RUN: 1
run: npm run tauri:build -- --bundles deb,rpm,appimage
- name: upload Linux artifacts
env:
@@ -156,5 +157,5 @@ jobs:
run: |
VERSION=${{ needs.create-release.outputs.package_version }}
find src-tauri/target/release/bundle \
\( -name "*.deb" -o -name "*.rpm" \) \
\( -name "*.deb" -o -name "*.rpm" -o -name "*.AppImage" \) \
| xargs gh release upload "app-v${VERSION}" --clobber
+1
View File
@@ -31,6 +31,7 @@ dist-ssr
# Tauri
src-tauri/target/
src-tauri/gen/
# Documentation
CLAUDE.md
+70
View File
@@ -5,6 +5,76 @@ 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.34.11] - 2026-04-14
### Added
- **Opus audio playback** *(Issue [#180](https://github.com/Psychotoxical/psysonic/issues/180), contributed by [@cucadmuh](https://github.com/cucadmuh), PR [#183](https://github.com/Psychotoxical/psysonic/pull/183))*: Psysonic can now decode Opus audio natively via `symphonia-adapter-libopus`, which bundles and compiles libopus from source. Previously `.opus` files were sent to the server for transcoding — a workaround that never worked reliably. Native decoding is now used directly; the server is no longer involved. Note: building from source requires `cmake` to be installed (see README).
- **Device Sync — synchronise your library to USB and SD card players** *(Issue [#161](https://github.com/Psychotoxical/psysonic/issues/161), by [@Psychotoxical](https://github.com/Psychotoxical))*: A fully overhauled Device Sync page lets you copy music from your Navidrome library to any mounted USB drive or SD card. Browse albums via live search (300 ms debounce) or a random album selection. Choose a filename template (Artist/Album/Track format), pick a target folder, and review a pre-sync summary showing files to add, files to delete, and available space — including a warning if the device would run out of space after accounting for pending deletions. Already-synced files are detected and skipped automatically so incremental syncs are fast.
- **3 visual toggles** *(contributed by [@kveld9](https://github.com/kveld9), PR [#181](https://github.com/Psychotoxical/psysonic/pull/181))*: Three new toggles in Settings → Appearance:
- **Cover art background** — enables/disables the blurred album art background in Album Detail and the Hero section.
- **Playlist cover photo** — shows/hides the cover collage at the top of Playlist Detail pages.
- **Show bitrate badge** — toggles the bitrate label displayed on tracks in the queue and track lists.
- **8 community themes** *(contributed by [@kveld9](https://github.com/kveld9), PR [#182](https://github.com/Psychotoxical/psysonic/pull/182))*: A new **Community** theme group appears directly below Psysonic Themes in the Theme Picker, containing eight new themes: **AMOLED Black Pure** (pure black for OLED), **Monochrome Dark** (grayscale), **Amber Night** (warm golden amber), **Phosphor Green** (classic terminal green), **Midnight Blue** (deep blue), **Rose Dark** (pink/rose accents), **Sepia Dark** (warm cream sepia), and **Ice Blue** (cool cyan). Psysonic now ships with 75 themes across 9 groups.
### Fixed
- **HTTPS streaming failures and server URL trailing slash** *(Issue [#178](https://github.com/Psychotoxical/psysonic/issues/178), by [@Psychotoxical](https://github.com/Psychotoxical) with fix ported from PR [#179](https://github.com/Psychotoxical/psysonic/pull/179) by [@kveld9](https://github.com/kveld9))*: Two bugs that broke HTTPS server connections are now fixed. A trailing slash in the configured server URL caused double-slash stream URLs (`//rest/stream.view`) that reverse proxies like Caddy would reject, and also caused album browsing to return 0 results. Additionally, `reqwest` now loads the OS native certificate store alongside Mozilla's root store — fixing HTTPS streaming failures when the server certificate is signed by a local CA (e.g. Caddy's internal CA) that is trusted in the system keychain but not in Mozilla's bundle.
- **Server display in Settings** *(by [@Psychotoxical](https://github.com/Psychotoxical))*: The server list in Settings → Servers now shows the URL and username on separate lines instead of a single truncated `username@url` string. Protocol prefixes (`http://`, `https://`) are stripped for cleaner display. HTTPS connections show a green lock icon.
### Changed
- **Waveform seekbar — live theme updates** *(contributed by [@kveld9](https://github.com/kveld9), PR [#182](https://github.com/Psychotoxical/psysonic/pull/182))*: The canvas-based seekbar now listens for `data-theme` attribute changes via `MutationObserver` and redraws immediately with the new theme colours. Switching themes no longer requires an app restart to update the waveform.
---
*Thank you to everyone who contributed to this release:*
*[@cucadmuh](https://github.com/cucadmuh) for implementing native Opus decoding — a long-requested feature that finally makes `.opus` libraries fully playable.*
*[@kveld9](https://github.com/kveld9) for three PRs in one release: the SSL/trailing-slash fix, visual customisation toggles, and eight new community themes with a live waveform update fix.*
---
## [1.34.10] - 2026-04-13
### Added
- **AppImage bundle for Linux** + X11/XWayland enforcement on all Linux packages: CI now builds `.AppImage` in addition to `.deb` and `.rpm`. `GDK_BACKEND=x11` and `WEBKIT_DISABLE_COMPOSITING_MODE=1` are set automatically at startup on all Linux packages — WebKitGTK on Wayland is unstable. Both environment variables are still overridable by setting them before launch.
- **Audio output device selection** *(Issue [#169](https://github.com/Psychotoxical/psysonic/issues/169))*: Settings → Audio now shows a dropdown of all available output devices. The current OS default is pinned at the top with a label; a Refresh button re-enumerates silently. A device watcher detects hot-plug events and emits `audio:device-reset` after ~9 s of consecutive misses, preventing false positives on busy ALSA devices. On Linux, technical ALSA prefixes are stripped for display (`sysdefault:CARD=U192k``U192k`).
- **Vision Dark & Vision Navy — colorblind-safe themes** *(Issue [#166](https://github.com/Psychotoxical/psysonic/issues/166))*: Two new themes using a Purple & Gold palette designed to be safe for Deuteranopia, Protanopia, and Tritanopia. Vision Dark pairs near-black `#0D0B12` with Gold `#FFD700` (~14.7:1 WCAG AAA); Vision Navy uses deep navy `#0A1628` + Gold (~14.5:1 WCAG AAA). Both appear under a new **Accessibility** group in the Theme Picker. These themes are a first step toward proper colorblind support and will be revised and expanded in upcoming releases — structural improvements such as secondary indicators and pattern/shape cues are still on the roadmap.
- **Folder Browser — per-column filter & Shift+Enter queue append** *(contributed by [@cucadmuh](https://github.com/cucadmuh), PR [#165](https://github.com/Psychotoxical/psysonic/pull/165))*: Press Ctrl+F to open a filter field for the active Folder Browser column. Focus hands off cleanly between the filter input and the row list. Clearing a parent-column selection clears all right-side filters automatically. Press Shift+Enter on a filtered track list to **append** the visible tracks to the queue without replacing it.
- **Keybindings — in-app modifier chords** *(contributed by [@cucadmuh](https://github.com/cucadmuh), PR [#167](https://github.com/Psychotoxical/psysonic/pull/167))*: In-app keybindings now support Ctrl/Alt/Shift+Key chords in addition to bare keys. The settings capture flow uses `buildInAppBinding`; the runtime handler uses `matchInAppBinding` and skips any chord already claimed as a global shortcut. Bare-key bindings still match without modifiers. Additionally, the seek forward/backward shortcuts now correctly interpret the configured value as seconds — previously the value was treated as a 01 progress fraction.
- **Playlist management enhancements** *(contributed by [@kveld9](https://github.com/kveld9), PR [#168](https://github.com/Psychotoxical/psysonic/pull/168))*: Multi-select context-menu actions for Albums, Artists, and Playlists now include a bulk **Add to Playlist** submenu. The sidebar playlist section is now collapsible. The Artists page gains infinite scroll via `IntersectionObserver`. Submenus flip upward automatically when they would overflow the viewport bottom. A **Remove from Playlist** entry is now available in the Playlist Detail context menu.
### Fixed
- **Fullscreen Player — animation overhead in no-compositing mode** *(contributed by [@kilyabin](https://github.com/kilyabin), PR [#175](https://github.com/Psychotoxical/psysonic/pull/175))*: In software-rendering mode (`WEBKIT_DISABLE_COMPOSITING_MODE=1`) the mesh blob pan animations are now stopped (static gradients are preserved), the portrait drift animation is stopped, and `box-shadow` is removed from the seekbar played bar. The seekbar played bar width changes on every playback tick; triggering a full shadow repaint in software mode caused significant CPU overhead.
- **Folder Browser — arrow keys with modifier keys** *(contributed by [@cucadmuh](https://github.com/cucadmuh), PR [#174](https://github.com/Psychotoxical/psysonic/pull/174))*: Column and list arrow-key handling is now skipped when any modifier key is held, preventing conflicts with browser focus navigation and OS-level shortcuts. Modifier detection uses both `nativeEvent` and `getModifierState` for WebKit/WebView2 compatibility.
- **Audio output device — Linux stability** *(contributed by [@cucadmuh](https://github.com/cucadmuh), PR [#176](https://github.com/Psychotoxical/psysonic/pull/176))*: Pinned ALSA/cpal device IDs now stay stable when enumeration temporarily omits the active sink or returns an equivalent name. The Linux device-watcher no longer clears the pin based solely on missing list entries — only macOS and Windows treat repeated absence as "device unplugged". The Settings refresh flow calls `canonicalize` and refetches the list; an i18n label is now shown when the active device is no longer in the enumerated list.
- **Login — server URL field** *(Issue [#171](https://github.com/Psychotoxical/psysonic/issues/171))*: The placeholder text in the Add Server form was previously a hardcoded English string. It is now fully localised and clarifies that `https://` URLs are accepted.
- **Offline mode — non-blocking banner** *(Issue [#170](https://github.com/Psychotoxical/psysonic/issues/170))*: The full-screen blocking overlay shown when Psysonic starts without a cached library is replaced with a slim banner at the top of the content area. The banner includes a direct link to Server Settings so the user can fix the connection without navigating manually.
---
*Special thanks to everyone who contributed to this release:*
*[@cucadmuh](https://github.com/cucadmuh) for the significant Folder Browser improvements, the modifier-chord keybindings and and the Linux audio stability fixes — four PRs in one release cycle, remarkable.*
*[@kilyabin](https://github.com/kilyabin) for continuing to hunt down no-compositing performance issues.*
*[@kveld9](https://github.com/kveld9) for the playlist management overhaul.*
---
## [1.34.9] - 2026-04-12
### Added
+4
View File
@@ -169,6 +169,10 @@ If you want to build Psysonic from source or contribute to the project:
### Prerequisites
- [Node.js](https://nodejs.org/) (v18+)
- [Rust](https://www.rust-lang.org/) (v1.75+)
- **`cmake`** — required to compile the bundled libopus (Opus audio support). Install it before running `cargo build` or `npm run tauri:build`:
- Linux: `sudo apt install cmake` / `sudo pacman -S cmake`
- macOS: `brew install cmake`
- Windows: [cmake.org/download](https://cmake.org/download/) or `winget install cmake`
- OS-specific build dependencies for Tauri (see the [Tauri prerequisites guide](https://tauri.app/v2/guides/getting-started/prerequisites)).
### Setup
+5 -5
View File
@@ -1,12 +1,12 @@
{
"name": "psysonic",
"version": "1.34.9",
"version": "1.34.11-dev",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "psysonic",
"version": "1.34.9",
"version": "1.34.11-dev",
"dependencies": {
"@fontsource-variable/dm-sans": "^5.2.8",
"@fontsource-variable/figtree": "^5.2.10",
@@ -2278,9 +2278,9 @@
}
},
"node_modules/follow-redirects": {
"version": "1.15.11",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz",
"integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==",
"version": "1.16.0",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz",
"integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==",
"funding": [
{
"type": "individual",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "psysonic",
"version": "1.34.9",
"version": "1.34.11",
"private": true,
"scripts": {
"dev": "vite",
+1 -1
View File
@@ -1,6 +1,6 @@
# Maintainer: Psychotoxic <psychotoxic@gmx.de>
pkgname=psysonic
pkgver=1.34.9
pkgver=1.34.10
pkgrel=1
pkgdesc="Desktop music player for Subsonic API-compatible servers (Navidrome, Gonic, etc.)"
arch=('x86_64')
+186 -47
View File
@@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
version = 4
[[package]]
name = "adler2"
@@ -39,7 +39,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed7572b7ba83a31e20d1b48970ee402d2e3e0537dcfe0a3ff4d6eb7508617d43"
dependencies = [
"alsa-sys",
"bitflags 2.11.0",
"bitflags 2.11.1",
"cfg-if",
"libc",
]
@@ -327,7 +327,7 @@ version = "0.72.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"cexpr",
"clang-sys",
"itertools",
@@ -371,9 +371,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitflags"
version = "2.11.0"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af"
checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"
dependencies = [
"serde_core",
]
@@ -475,7 +475,7 @@ version = "0.18.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"cairo-sys-rs",
"glib",
"libc",
@@ -619,6 +619,15 @@ dependencies = [
"libloading 0.8.9",
]
[[package]]
name = "cmake"
version = "0.1.58"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"
dependencies = [
"cc",
]
[[package]]
name = "cocoa"
version = "0.24.1"
@@ -729,7 +738,7 @@ version = "0.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"core-foundation 0.10.1",
"core-graphics-types 0.2.0",
"foreign-types 0.5.0",
@@ -753,7 +762,7 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"core-foundation 0.10.1",
"libc",
]
@@ -1051,7 +1060,7 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"block2",
"libc",
"objc2",
@@ -1721,7 +1730,7 @@ version = "0.18.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"futures-channel",
"futures-core",
"futures-executor",
@@ -1983,14 +1992,15 @@ dependencies = [
[[package]]
name = "hyper-rustls"
version = "0.27.8"
version = "0.27.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2b52f86d1d4bc0d6b4e6826d960b1b333217e07d36b882dca570a5e1c48895b"
checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f"
dependencies = [
"http",
"hyper",
"hyper-util",
"rustls",
"rustls-native-certs",
"tokio",
"tokio-rustls",
"tower-service",
@@ -2148,7 +2158,7 @@ version = "1.16.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "965c5e6a62a241f2f673df956ea5f52c27780bc1031855890a551ed9b869e2d1"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"byteorder",
"flate2",
]
@@ -2412,7 +2422,7 @@ version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"serde",
"unicode-segmentation",
]
@@ -2467,9 +2477,9 @@ dependencies = [
[[package]]
name = "libc"
version = "0.2.184"
version = "0.2.185"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48f5d2a454e16a5ea0f4ced81bd44e4cfc7bd3a507b61887c99fd3538b28e4af"
checksum = "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f"
[[package]]
name = "libloading"
@@ -2753,7 +2763,7 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2076a31b7010b17a38c01907c45b945e8f11495ee4dd588309718901b1f7a5b7"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"jni-sys 0.3.1",
"log",
"ndk-sys 0.5.0+25.2.9519653",
@@ -2767,7 +2777,7 @@ version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"jni-sys 0.3.1",
"log",
"ndk-sys 0.6.0+11769913",
@@ -2907,7 +2917,7 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"block2",
"objc2",
"objc2-core-foundation",
@@ -2920,7 +2930,7 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"dispatch2",
"objc2",
]
@@ -2931,7 +2941,7 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"dispatch2",
"objc2",
"objc2-core-foundation",
@@ -2959,7 +2969,7 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"block2",
"libc",
"objc2",
@@ -2972,7 +2982,7 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"objc2",
"objc2-core-foundation",
]
@@ -2983,7 +2993,7 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"objc2",
"objc2-core-foundation",
"objc2-foundation",
@@ -2995,7 +3005,7 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"objc2",
"objc2-core-foundation",
"objc2-foundation",
@@ -3007,7 +3017,7 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"block2",
"objc2",
"objc2-app-kit",
@@ -3065,12 +3075,27 @@ dependencies = [
"pathdiff",
]
[[package]]
name = "openssl-probe"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
[[package]]
name = "option-ext"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
[[package]]
name = "opusic-sys"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc3280fe5b6f97ac1a35a0ac003e2fb0b92f8e4bdf2b2057e1bf9b87acca5696"
dependencies = [
"cmake",
]
[[package]]
name = "ordered-stream"
version = "0.2.0"
@@ -3405,7 +3430,7 @@ version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"crc32fast",
"fdeflate",
"flate2",
@@ -3558,12 +3583,13 @@ dependencies = [
[[package]]
name = "psysonic"
version = "1.34.9"
version = "1.34.11"
dependencies = [
"biquad",
"discord-rich-presence",
"futures-util",
"id3",
"libc",
"lofty",
"md5",
"reqwest 0.12.28",
@@ -3573,6 +3599,8 @@ dependencies = [
"serde_json",
"souvlaki",
"symphonia",
"symphonia-adapter-libopus",
"sysinfo",
"tauri",
"tauri-build",
"tauri-plugin-dialog",
@@ -3633,7 +3661,7 @@ dependencies = [
"bytes",
"getrandom 0.3.4",
"lru-slab",
"rand 0.9.3",
"rand 0.9.4",
"ring",
"rustc-hash",
"rustls",
@@ -3707,9 +3735,9 @@ dependencies = [
[[package]]
name = "rand"
version = "0.9.3"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ec095654a25171c2124e9e3393a930bddbffdc939556c914957a4c3e0a87166"
checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"
dependencies = [
"rand_chacha 0.9.0",
"rand_core 0.9.5",
@@ -3802,7 +3830,7 @@ version = "0.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
]
[[package]]
@@ -3889,6 +3917,7 @@ dependencies = [
"pin-project-lite",
"quinn",
"rustls",
"rustls-native-certs",
"rustls-pki-types",
"serde",
"serde_json",
@@ -4035,7 +4064,7 @@ version = "0.38.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"errno",
"libc",
"linux-raw-sys 0.4.15",
@@ -4048,7 +4077,7 @@ version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"errno",
"libc",
"linux-raw-sys 0.12.1",
@@ -4057,9 +4086,9 @@ dependencies = [
[[package]]
name = "rustls"
version = "0.23.37"
version = "0.23.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4"
checksum = "69f9466fb2c14ea04357e91413efb882e2a6d4a406e625449bc0a5d360d53a21"
dependencies = [
"once_cell",
"ring",
@@ -4069,6 +4098,18 @@ dependencies = [
"zeroize",
]
[[package]]
name = "rustls-native-certs"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63"
dependencies = [
"openssl-probe",
"rustls-pki-types",
"schannel",
"security-framework",
]
[[package]]
name = "rustls-pki-types"
version = "1.14.0"
@@ -4081,9 +4122,9 @@ dependencies = [
[[package]]
name = "rustls-webpki"
version = "0.103.11"
version = "0.103.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20a6af516fea4b20eccceaf166e8aa666ac996208e8a644ce3ef5aa783bc7cd4"
checksum = "8279bb85272c9f10811ae6a6c547ff594d6a7f3c6c6b02ee9726d1d0dcfcdd06"
dependencies = [
"ring",
"rustls-pki-types",
@@ -4111,6 +4152,15 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "schannel"
version = "0.1.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "schemars"
version = "0.8.22"
@@ -4168,6 +4218,29 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "security-framework"
version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
dependencies = [
"bitflags 2.11.1",
"core-foundation 0.10.1",
"core-foundation-sys",
"libc",
"security-framework-sys",
]
[[package]]
name = "security-framework-sys"
version = "2.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "selectors"
version = "0.24.0"
@@ -4192,7 +4265,7 @@ version = "0.36.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5d9c0c92a92d33f08817311cf3f2c29a3538a8240e94a6a3c622ce652d7e00c"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"cssparser 0.36.0",
"derive_more 2.1.1",
"log",
@@ -4686,6 +4759,17 @@ dependencies = [
"symphonia-metadata",
]
[[package]]
name = "symphonia-adapter-libopus"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9d17450685dda0e87467eddf3e0f9c0b2a1707fc5c3234c111f70d46c6e4494"
dependencies = [
"log",
"opusic-sys",
"symphonia-core",
]
[[package]]
name = "symphonia-bundle-flac"
version = "0.5.5"
@@ -4874,6 +4958,17 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "sysinfo"
version = "0.33.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fc858248ea01b66f19d8e8a6d55f41deaf91e9d495246fd01368d99935c6c01"
dependencies = [
"core-foundation-sys",
"libc",
"windows 0.57.0",
]
[[package]]
name = "system-deps"
version = "6.2.2"
@@ -4893,7 +4988,7 @@ version = "0.34.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9103edf55f2da3c82aea4c7fab7c4241032bfeea0e71fa557d98e00e7ce7cc20"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"block2",
"core-foundation 0.10.1",
"core-graphics 0.25.0",
@@ -5199,7 +5294,7 @@ version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73736611e14142408d15353e21e3cca2f12a3cfb523ad0ce85999b6d2ef1a704"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"log",
"serde",
"serde_json",
@@ -5388,7 +5483,7 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfe075d7053dae61ac5413a34ea7d4913b6e6207844fd726bdd858b37ff72bf5"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"cfg-if",
"libc",
"log",
@@ -5454,9 +5549,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.51.1"
version = "1.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f66bf9585cda4b724d3e78ab34b73fb2bbaba9011b9bfdf69dc836382ea13b8c"
checksum = "a91135f59b1cbf38c91e73cf3386fca9bb77915c45ce2771460c9d92f0f3d776"
dependencies = [
"bytes",
"libc",
@@ -5627,7 +5722,7 @@ version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"bytes",
"futures-util",
"http",
@@ -6058,7 +6153,7 @@ version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
dependencies = [
"bitflags 2.11.0",
"bitflags 2.11.1",
"hashbrown 0.15.5",
"indexmap 2.14.0",
"semver",
@@ -6250,6 +6345,16 @@ dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows"
version = "0.57.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12342cb4d8e3b046f3d80effd474a7a02447231330ef77d71daa6fbc40681143"
dependencies = [
"windows-core 0.57.0",
"windows-targets 0.52.6",
]
[[package]]
name = "windows"
version = "0.58.0"
@@ -6292,6 +6397,18 @@ dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-core"
version = "0.57.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2ed2439a290666cd67ecce2b0ffaad89c2a56b976b736e6ece670297897832d"
dependencies = [
"windows-implement 0.57.0",
"windows-interface 0.57.0",
"windows-result 0.1.2",
"windows-targets 0.52.6",
]
[[package]]
name = "windows-core"
version = "0.58.0"
@@ -6342,6 +6459,17 @@ dependencies = [
"windows-threading",
]
[[package]]
name = "windows-implement"
version = "0.57.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9107ddc059d5b6fbfbffdfa7a7fe3e22a226def0b2608f72e9d552763d3e1ad7"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "windows-implement"
version = "0.58.0"
@@ -6364,6 +6492,17 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "windows-interface"
version = "0.57.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29bee4b38ea3cde66011baa44dba677c432a78593e202392d1e9070cf2a7fca7"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "windows-interface"
version = "0.58.0"
@@ -6882,7 +7021,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
dependencies = [
"anyhow",
"bitflags 2.11.0",
"bitflags 2.11.1",
"indexmap 2.14.0",
"log",
"serde",
+8 -3
View File
@@ -1,13 +1,13 @@
[package]
name = "psysonic"
version = "1.34.9"
version = "1.34.11"
description = "Psysonic Desktop Music Player"
authors = []
license = ""
repository = ""
default-run = "psysonic"
edition = "2021"
rust-version = "1.77.2"
rust-version = "1.89"
[lib]
name = "psysonic_lib"
@@ -32,7 +32,7 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
rodio = { version = "0.19", default-features = false, features = ["symphonia-all"] }
symphonia = { version = "0.5", default-features = false, features = ["flac", "mp3", "pcm", "aac", "alac", "isomp4", "vorbis", "ogg", "wav", "adpcm"] }
reqwest = { version = "0.12", default-features = false, features = ["stream", "json", "multipart", "rustls-tls", "blocking"] }
reqwest = { version = "0.12", default-features = false, features = ["stream", "json", "multipart", "rustls-tls", "rustls-tls-native-roots", "blocking"] }
futures-util = "0.3"
md5 = "0.7"
tokio = { version = "1", features = ["rt", "time", "sync"] }
@@ -45,7 +45,12 @@ discord-rich-presence = "0.2"
url = "2"
thread-priority = "1"
lofty = "0.22"
sysinfo = { version = "0.33", default-features = false, features = ["disk"] }
id3 = "1.16.4"
symphonia-adapter-libopus = "0.2.7"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows = { version = "0.58", features = [
File diff suppressed because one or more lines are too long
-1
View File
@@ -1 +0,0 @@
{"default":{"identifier":"default","description":"Default capabilities for Psysonic","local":true,"windows":["main"],"permissions":["core:default","shell:default",{"identifier":"shell:allow-open","allow":[{"url":"https://**"}]},"global-shortcut:allow-register","global-shortcut:allow-unregister","store:default","store:allow-load","store:allow-set","store:allow-get","store:allow-save","dialog:default","dialog:allow-open","dialog:allow-save","fs:default","fs:allow-write-file","fs:allow-read-file","fs:allow-mkdir","fs:scope-download-recursive","fs:scope-home-recursive","window-state:allow-save-window-state","window-state:allow-restore-state","core:window:allow-set-title","core:window:allow-close","core:window:allow-minimize","core:window:allow-toggle-maximize","core:window:allow-hide","core:window:allow-show","core:window:allow-set-fullscreen","core:window:allow-is-fullscreen","core:window:allow-start-dragging","core:window:allow-create","core:webview:allow-create-webview-window","process:allow-restart"],"platforms":["linux","macOS","windows"]}}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+322 -41
View File
@@ -1,7 +1,9 @@
use std::io::{Cursor, Read, Seek, SeekFrom};
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, OnceLock};
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::time::{Duration, Instant};
#[cfg(unix)]
use libc;
use ringbuf::{HeapConsumer, HeapProducer, HeapRb};
@@ -11,7 +13,7 @@ use rodio::source::UniformSourceIterator;
use serde::Serialize;
use symphonia::core::{
audio::{AudioBufferRef, SampleBuffer, SignalSpec},
codecs::{DecoderOptions, CODEC_TYPE_NULL},
codecs::{CodecRegistry, DecoderOptions, CODEC_TYPE_NULL},
formats::{FormatOptions, FormatReader, SeekMode, SeekTo},
io::{MediaSource, MediaSourceStream, MediaSourceStreamOptions},
meta::MetadataOptions,
@@ -680,11 +682,22 @@ impl Drop for RadioLiveState {
// [features]
// fdk-aac = ["dep:symphonia-adapter-fdk-aac"]
/// Symphonias default codec set for our enabled features, plus Opus via libopus.
fn psysonic_codec_registry() -> &'static CodecRegistry {
static REGISTRY: OnceLock<CodecRegistry> = OnceLock::new();
REGISTRY.get_or_init(|| {
let mut registry = CodecRegistry::new();
symphonia::default::register_enabled_codecs(&mut registry);
registry.register_all::<symphonia_adapter_libopus::OpusDecoder>();
registry
})
}
fn try_make_radio_decoder(
params: &symphonia::core::codecs::CodecParameters,
opts: &DecoderOptions,
) -> Result<Box<dyn symphonia::core::codecs::Decoder>, symphonia::core::errors::Error> {
symphonia::default::get_codecs().make(params, opts)
psysonic_codec_registry().make(params, opts)
}
// ── Async HTTP Download Task ──────────────────────────────────────────────────
@@ -978,7 +991,7 @@ impl SizedDecoder {
.zip(track.codec_params.n_frames)
.map(|(base, frames)| base.calc_time(frames));
let mut decoder = symphonia::default::get_codecs()
let mut decoder = psysonic_codec_registry()
.make(&track.codec_params, &DecoderOptions::default())
.map_err(|e| {
eprintln!("[psysonic] codec init failed: {e}");
@@ -1448,9 +1461,11 @@ pub struct AudioEngine {
/// The rate the device was opened at on cold start — used to restore the
/// stream when Hi-Res is toggled off while a hi-res rate is active.
pub device_default_rate: u32,
/// Sends `(desired_rate, is_hi_res, reply_tx)` to the audio-stream thread to
/// re-open the output device. `is_hi_res` controls thread-priority escalation.
pub stream_reopen_tx: std::sync::mpsc::SyncSender<(u32, bool, std::sync::mpsc::SyncSender<rodio::OutputStreamHandle>)>,
/// Sends `(desired_rate, is_hi_res, device_name, reply_tx)` to the audio-stream
/// thread to re-open the output device. `device_name = None` → system default.
pub stream_reopen_tx: std::sync::mpsc::SyncSender<(u32, bool, Option<String>, std::sync::mpsc::SyncSender<rodio::OutputStreamHandle>)>,
/// User-selected output device name (None = follow system default).
pub selected_device: Arc<Mutex<Option<String>>>,
pub current: Arc<Mutex<AudioCurrent>>,
/// Monotonically incremented on each audio_play (non-chain) / audio_stop call.
pub generation: Arc<AtomicU64>,
@@ -1511,7 +1526,10 @@ impl AudioCurrent {
}
}
/// Open the system default output device at `desired_rate` Hz (0 = device default).
/// Open an output device at `desired_rate` Hz (0 = device default).
///
/// `device_name`: exact name from `audio_list_devices`. `None` → system default.
/// Falls back to the system default if the named device is not found.
///
/// Resolution order:
/// 1. Exact rate match in the device's supported config ranges.
@@ -1520,12 +1538,31 @@ impl AudioCurrent {
/// 4. System default (last resort).
///
/// Returns `(OutputStream, OutputStreamHandle, actual_sample_rate)`.
fn open_stream_for_rate(desired_rate: u32) -> (rodio::OutputStream, rodio::OutputStreamHandle, u32) {
fn open_stream_for_device_and_rate(device_name: Option<&str>, desired_rate: u32) -> (rodio::OutputStream, rodio::OutputStreamHandle, u32) {
use rodio::cpal::traits::{DeviceTrait, HostTrait};
// Suppress ALSA stderr noise while enumerating devices on Unix.
#[cfg(unix)]
let _guard = unsafe {
struct StderrGuard(i32);
impl Drop for StderrGuard {
fn drop(&mut self) { unsafe { libc::dup2(self.0, 2); libc::close(self.0); } }
}
let saved = libc::dup(2);
let devnull = libc::open(b"/dev/null\0".as_ptr() as *const libc::c_char, libc::O_WRONLY);
libc::dup2(devnull, 2);
libc::close(devnull);
StderrGuard(saved)
};
let host = rodio::cpal::default_host();
if let Some(device) = host.default_output_device() {
// Resolve the target device: named device first, fall back to system default.
let device = device_name.and_then(|name| {
host.output_devices().ok()?.find(|d| d.name().ok().as_deref() == Some(name))
}).or_else(|| host.default_output_device());
if let Some(device) = device {
if desired_rate > 0 {
if let Ok(supported) = device.supported_output_configs() {
let configs: Vec<_> = supported.collect();
@@ -1608,7 +1645,7 @@ pub fn create_engine() -> (AudioEngine, std::thread::JoinHandle<()>) {
let (init_tx, init_rx) =
std::sync::mpsc::sync_channel::<(rodio::OutputStreamHandle, u32)>(0);
let (reopen_tx, reopen_rx) =
std::sync::mpsc::sync_channel::<(u32, bool, std::sync::mpsc::SyncSender<rodio::OutputStreamHandle>)>(4);
std::sync::mpsc::sync_channel::<(u32, bool, Option<String>, std::sync::mpsc::SyncSender<rodio::OutputStreamHandle>)>(4);
let thread = std::thread::Builder::new()
.name("psysonic-audio-stream".into())
@@ -1627,11 +1664,11 @@ pub fn create_engine() -> (AudioEngine, std::thread::JoinHandle<()>) {
// Thread priority is kept at default during standard-mode playback.
// It is escalated to Max only when a Hi-Res stream reopen is requested,
// to prevent PipeWire underruns at high quantum sizes (8192 frames).
let (mut _stream, handle, rate) = open_stream_for_rate(0);
let (mut _stream, handle, rate) = open_stream_for_device_and_rate(None, 0);
init_tx.send((handle, rate)).ok();
// Keep the stream alive and handle sample-rate switch requests.
while let Ok((desired_rate, is_hi_res, reply_tx)) = reopen_rx.recv() {
// Keep the stream alive and handle sample-rate / device-switch requests.
while let Ok((desired_rate, is_hi_res, device_name, reply_tx)) = reopen_rx.recv() {
// Escalate to Max for Hi-Res reopens (large PipeWire quanta need
// real-time scheduling to avoid underruns). No escalation for
// standard mode — the thread blocks on recv() between reopens so
@@ -1657,7 +1694,7 @@ pub fn create_engine() -> (AudioEngine, std::thread::JoinHandle<()>) {
std::env::set_var("PULSE_LATENCY_MSEC", latency_ms.to_string());
}
let (new_stream, new_handle, _actual) = open_stream_for_rate(desired_rate);
let (new_stream, new_handle, _actual) = open_stream_for_device_and_rate(device_name.as_deref(), desired_rate);
_stream = new_stream;
reply_tx.send(new_handle).ok();
}
@@ -1671,6 +1708,7 @@ pub fn create_engine() -> (AudioEngine, std::thread::JoinHandle<()>) {
stream_sample_rate: Arc::new(AtomicU32::new(initial_rate)),
device_default_rate: initial_rate,
stream_reopen_tx: reopen_tx,
selected_device: Arc::new(Mutex::new(None)),
current: Arc::new(Mutex::new(AudioCurrent {
sink: None,
duration_secs: 0.0,
@@ -2018,7 +2056,8 @@ pub async fn audio_play(
let needs_switch = target_rate > 0 && target_rate != current_stream_rate;
if needs_switch {
let (reply_tx, reply_rx) = std::sync::mpsc::sync_channel::<rodio::OutputStreamHandle>(0);
if state.stream_reopen_tx.send((target_rate, hi_res_enabled, reply_tx)).is_ok() {
let dev = state.selected_device.lock().unwrap().clone();
if state.stream_reopen_tx.send((target_rate, hi_res_enabled, dev, reply_tx)).is_ok() {
match reply_rx.recv_timeout(std::time::Duration::from_secs(5)) {
Ok(new_handle) => {
*state.stream_handle.lock().unwrap() = new_handle;
@@ -2883,6 +2922,167 @@ pub async fn audio_play_radio(
Ok(())
}
/// ALSA probes noisy plugins during device queries — suppress stderr on Unix.
#[cfg(unix)]
fn with_suppressed_alsa_stderr<R>(f: impl FnOnce() -> R) -> R {
struct StderrGuard(i32);
impl Drop for StderrGuard {
fn drop(&mut self) {
unsafe { libc::dup2(self.0, 2); libc::close(self.0); }
}
}
let _guard = unsafe {
let saved = libc::dup(2);
let devnull = libc::open(b"/dev/null\0".as_ptr() as *const libc::c_char, libc::O_WRONLY);
libc::dup2(devnull, 2);
libc::close(devnull);
StderrGuard(saved)
};
f()
}
#[cfg(not(unix))]
#[inline]
fn with_suppressed_alsa_stderr<R>(f: impl FnOnce() -> R) -> R {
f()
}
fn enumerate_output_device_names() -> Vec<String> {
use rodio::cpal::traits::{DeviceTrait, HostTrait};
with_suppressed_alsa_stderr(|| {
let host = rodio::cpal::default_host();
host.output_devices()
.map(|iter| iter.filter_map(|d| d.name().ok()).collect())
.unwrap_or_default()
})
}
/// Linux ALSA-style cpal names: same physical sink can appear with different suffixes;
/// busy devices are sometimes omitted from `output_devices()` while playback works.
#[cfg(target_os = "linux")]
fn linux_alsa_sink_fingerprint(name: &str) -> Option<(String, String, u32)> {
const IFACES: &[&str] = &[
"hdmi", "hw", "plughw", "sysdefault", "iec958", "front", "dmix", "surround40",
"surround51", "surround71",
];
let colon = name.find(':')?;
let iface = name[..colon].to_ascii_lowercase();
if !IFACES.iter().any(|&i| i == iface.as_str()) {
return None;
}
let card = name.split("CARD=").nth(1)?.split(',').next()?.to_string();
let dev = name
.split("DEV=")
.nth(1)
.and_then(|s| s.split(',').next())
.and_then(|s| s.parse().ok())
.unwrap_or(0);
Some((iface, card, dev))
}
#[cfg(not(target_os = "linux"))]
#[inline]
fn linux_alsa_sink_fingerprint(_name: &str) -> Option<(String, String, u32)> {
None
}
fn output_devices_logically_same(a: &str, b: &str) -> bool {
if a == b {
return true;
}
match (
linux_alsa_sink_fingerprint(a),
linux_alsa_sink_fingerprint(b),
) {
(Some(fa), Some(fb)) => fa == fb,
_ => false,
}
}
/// True if `pinned` is the same sink as some entry (exact or Linux ALSA logical match).
fn output_enumeration_includes_pinned(available: &[String], pinned: &str) -> bool {
available
.iter()
.any(|d| output_devices_logically_same(d, pinned))
}
/// If the pinned id is missing from cpal's list but another listed id is the same
/// physical sink (e.g. suffix drift), rewrite `selected_device` to the listed form.
#[tauri::command]
pub fn audio_canonicalize_selected_device(state: State<'_, AudioEngine>) -> Option<String> {
let pinned = state.selected_device.lock().unwrap().clone()?;
if pinned.is_empty() {
return None;
}
let list = enumerate_output_device_names();
if list.iter().any(|d| d == &pinned) {
return None;
}
let canon = list
.iter()
.find(|d| output_devices_logically_same(d, &pinned))?
.clone();
*state.selected_device.lock().unwrap() = Some(canon.clone());
Some(canon)
}
/// Returns the names of all available audio output devices on the current host.
/// On Linux, ALSA probes unavailable backends (JACK, OSS, dmix) and prints errors to
/// stderr. We suppress fd 2 for the duration of enumeration to keep the terminal clean.
///
/// The user-pinned device name is appended when cpal omits it (e.g. HDMI busy while
/// streaming) so the Settings dropdown still matches `audioOutputDevice`.
#[tauri::command]
pub fn audio_list_devices(state: State<'_, AudioEngine>) -> Vec<String> {
let mut list = enumerate_output_device_names();
if let Some(ref name) = *state.selected_device.lock().unwrap() {
if !name.is_empty() && !output_enumeration_includes_pinned(&list, name) {
list.push(name.clone());
}
}
list
}
/// Device id string for the host default output (matches an entry from `audio_list_devices` when present).
#[tauri::command]
pub fn audio_default_output_device_name() -> Option<String> {
use rodio::cpal::traits::{DeviceTrait, HostTrait};
with_suppressed_alsa_stderr(|| {
let host = rodio::cpal::default_host();
host.default_output_device().and_then(|d| d.name().ok())
})
}
/// Switch the audio output device. `device_name = null` → follow system default.
/// Reopens the stream immediately; frontend must restart playback via audio:device-changed.
#[tauri::command]
pub async fn audio_set_device(
device_name: Option<String>,
state: State<'_, AudioEngine>,
app: tauri::AppHandle,
) -> Result<(), String> {
*state.selected_device.lock().unwrap() = device_name.clone();
let rate = state.stream_sample_rate.load(Ordering::Relaxed);
let (reply_tx, reply_rx) = std::sync::mpsc::sync_channel::<rodio::OutputStreamHandle>(0);
state.stream_reopen_tx
.send((rate, false, device_name, reply_tx))
.map_err(|e| e.to_string())?;
let new_handle = tauri::async_runtime::spawn_blocking(move || {
reply_rx.recv_timeout(Duration::from_secs(5)).ok()
}).await.unwrap_or(None).ok_or("device open timed out")?;
*state.stream_handle.lock().unwrap() = new_handle;
// Drop active sinks — they were bound to the old stream.
if let Some(s) = state.current.lock().unwrap().sink.take() { s.stop(); }
if let Some(s) = state.fading_out_sink.lock().unwrap().take() { s.stop(); }
app.emit("audio:device-changed", ()).map_err(|e| e.to_string())?;
Ok(())
}
#[tauri::command]
pub fn audio_set_crossfade(enabled: bool, secs: f32, state: State<'_, AudioEngine>) {
state.crossfade_enabled.store(enabled, Ordering::Relaxed);
@@ -2896,45 +3096,129 @@ pub fn audio_set_gapless(enabled: bool, state: State<'_, AudioEngine>) {
// ─── Device-change watcher ────────────────────────────────────────────────────
//
// Polls the OS default output device every 3 s. When it changes (Bluetooth
// headphones connecting, USB DAC plugging in, etc.) the stream is reopened on
// the new device and `audio:device-changed` is emitted so the frontend can
// restart playback. The old Sink is dropped here — it was bound to the
// now-closed OutputStream and can no longer produce audio on any device.
// Polls every 3 s for two conditions:
// 1. System default device changed (Bluetooth, USB DAC plug/unplug) while no
// device is pinned → reopen on new default, emit audio:device-changed.
// 2. (macOS / Windows only) User-pinned device disappeared from cpal's list →
// fall back to system default, clear selected_device, emit audio:device-reset.
// Linux: case 2 is disabled — ALSA/cpal often omit the active sink from
// enumeration while streaming, which caused false resets to system default.
pub fn start_device_watcher(engine: &AudioEngine, app: tauri::AppHandle) {
let reopen_tx = engine.stream_reopen_tx.clone();
let stream_handle = engine.stream_handle.clone();
let stream_rate = engine.stream_sample_rate.clone();
let current = engine.current.clone();
let fading_out = engine.fading_out_sink.clone();
let reopen_tx = engine.stream_reopen_tx.clone();
let stream_handle = engine.stream_handle.clone();
let stream_rate = engine.stream_sample_rate.clone();
let current = engine.current.clone();
let fading_out = engine.fading_out_sink.clone();
let selected_device = engine.selected_device.clone();
tauri::async_runtime::spawn(async move {
let mut last_name: Option<String> = tauri::async_runtime::spawn_blocking(|| {
let mut last_default: Option<String> = tauri::async_runtime::spawn_blocking(|| {
use rodio::cpal::traits::{DeviceTrait, HostTrait};
rodio::cpal::default_host()
.default_output_device()
.and_then(|d| d.name().ok())
}).await.unwrap_or(None);
// macOS/Windows: consecutive polls where a pinned device is absent from cpal's list.
#[cfg(not(target_os = "linux"))]
let mut pinned_miss_count: u32 = 0;
loop {
tokio::time::sleep(Duration::from_secs(3)).await;
let current_name: Option<String> = tauri::async_runtime::spawn_blocking(|| {
// Enumerate all available output devices and the current default.
// Suppress stderr on Unix to avoid ALSA probing noise (JACK, OSS, dmix).
let (current_default, available) = tauri::async_runtime::spawn_blocking(|| {
use rodio::cpal::traits::{DeviceTrait, HostTrait};
rodio::cpal::default_host()
.default_output_device()
.and_then(|d| d.name().ok())
}).await.unwrap_or(None);
#[cfg(unix)]
let _guard = unsafe {
struct StderrGuard(i32);
impl Drop for StderrGuard {
fn drop(&mut self) { unsafe { libc::dup2(self.0, 2); libc::close(self.0); } }
}
let saved = libc::dup(2);
let devnull = libc::open(b"/dev/null\0".as_ptr() as *const libc::c_char, libc::O_WRONLY);
libc::dup2(devnull, 2);
libc::close(devnull);
StderrGuard(saved)
};
let host = rodio::cpal::default_host();
let default = host.default_output_device().and_then(|d| d.name().ok());
let available: Vec<String> = host
.output_devices()
.map(|iter| iter.filter_map(|d| d.name().ok()).collect())
.unwrap_or_default();
(default, available)
}).await.unwrap_or((None, vec![]));
if current_name == last_name {
// Empty list almost always means a transient enumeration failure, not
// that every output device vanished. Treating it as "pinned missing"
// caused false audio:device-reset (UI jumped back to system default)
// when switching to external USB / class-compliant interfaces.
if available.is_empty() {
continue;
}
last_name = current_name.clone();
let pinned = selected_device.lock().unwrap().clone();
// Only act if there is actually a device to open.
let Some(_new_name) = current_name else { continue };
#[cfg(target_os = "linux")]
if pinned.is_some() {
// Do not infer "unplugged" from `output_devices()` when a device is pinned.
// ALSA/cpal often omit the active HDMI/USB sink from enumeration for the
// whole session — any miss counter eventually tripped audio:device-reset.
// Clearing the pin is left to the user (Settings → System Default) or
// to a future explicit error signal from the output stream.
continue;
}
// ── Case 2 (non-Linux): pinned device disappeared from enumeration ─
#[cfg(not(target_os = "linux"))]
if let Some(ref dev_name) = pinned {
if !output_enumeration_includes_pinned(&available, dev_name) {
pinned_miss_count += 1;
if pinned_miss_count < 3 {
continue;
}
eprintln!("[psysonic] device-watcher: pinned device '{dev_name}' disconnected, falling back to system default");
pinned_miss_count = 0;
*selected_device.lock().unwrap() = None;
tokio::time::sleep(Duration::from_millis(500)).await;
let rate = stream_rate.load(Ordering::Relaxed);
let reopen_tx2 = reopen_tx.clone();
let new_handle = tauri::async_runtime::spawn_blocking(move || {
let (reply_tx, reply_rx) =
std::sync::mpsc::sync_channel::<rodio::OutputStreamHandle>(0);
if reopen_tx2.send((rate, false, None, reply_tx)).is_err() {
return None;
}
reply_rx.recv_timeout(Duration::from_secs(5)).ok()
}).await.unwrap_or(None);
if let Some(handle) = new_handle {
*stream_handle.lock().unwrap() = handle;
if let Some(s) = current.lock().unwrap().sink.take() { s.stop(); }
if let Some(s) = fading_out.lock().unwrap().take() { s.stop(); }
app.emit("audio:device-reset", ()).ok();
}
last_default = current_default;
} else {
pinned_miss_count = 0;
}
continue;
}
// ── Case 1: no pinned device, system default changed ──────────────
if current_default == last_default {
continue;
}
last_default = current_default.clone();
let Some(_new_name) = current_default else { continue };
// Debounce: give the OS time to finish configuring the new device.
tokio::time::sleep(Duration::from_millis(500)).await;
@@ -2944,8 +3228,8 @@ pub fn start_device_watcher(engine: &AudioEngine, app: tauri::AppHandle) {
let new_handle = tauri::async_runtime::spawn_blocking(move || {
let (reply_tx, reply_rx) =
std::sync::mpsc::sync_channel::<rodio::OutputStreamHandle>(0);
if reopen_tx2.send((rate, false, reply_tx)).is_err() {
return None; // audio thread exited
if reopen_tx2.send((rate, false, None, reply_tx)).is_err() {
return None;
}
reply_rx.recv_timeout(Duration::from_secs(5)).ok()
}).await.unwrap_or(None);
@@ -2956,11 +3240,8 @@ pub fn start_device_watcher(engine: &AudioEngine, app: tauri::AppHandle) {
};
*stream_handle.lock().unwrap() = handle;
// Drop the old Sink — it was bound to the now-closed OutputStream.
if let Some(s) = current.lock().unwrap().sink.take() { s.stop(); }
if let Some(s) = fading_out.lock().unwrap().take() { s.stop(); }
app.emit("audio:device-changed", ()).ok();
}
});
+697
View File
@@ -1349,6 +1349,691 @@ async fn purge_hot_cache(custom_dir: Option<String>, app: tauri::AppHandle) -> R
Ok(())
}
// ─── Device Sync ─────────────────────────────────────────────────────────────
/// Information about a single mounted removable drive.
#[derive(Clone, serde::Serialize)]
struct RemovableDrive {
name: String,
mount_point: String,
available_space: u64,
total_space: u64,
file_system: String,
is_removable: bool,
}
/// Returns all currently mounted removable drives.
/// On Linux these are typically USB sticks / SD cards under /media or /run/media.
/// On macOS they appear under /Volumes. On Windows they are separate drive letters.
#[tauri::command]
fn get_removable_drives() -> Vec<RemovableDrive> {
use sysinfo::Disks;
let disks = Disks::new_with_refreshed_list();
disks
.list()
.iter()
.filter(|d| d.is_removable())
.map(|d| RemovableDrive {
name: d.name().to_string_lossy().to_string(),
mount_point: d.mount_point().to_string_lossy().to_string(),
available_space: d.available_space(),
total_space: d.total_space(),
file_system: d.file_system().to_string_lossy().to_string(),
is_removable: true,
})
.collect()
}
/// Checks whether `path` sits on top of an active mount point (i.e. not the root
/// filesystem). This prevents accidentally writing to `/media/usb` after the
/// USB drive has been unmounted — at that point the path would fall through to `/`
/// and fill the root partition.
fn is_path_on_mounted_volume(path: &std::path::Path) -> bool {
use sysinfo::Disks;
let disks = Disks::new_with_refreshed_list();
let canonical = match path.canonicalize() {
Ok(c) => c,
Err(_) => return false, // path doesn't exist or isn't accessible
};
let canonical_str = canonical.to_string_lossy();
// Find the longest mount-point prefix that matches this path.
// Exclude the root "/" (or "C:\" on Windows) so we never "match" a fallback.
let mut best_len: usize = 0;
for disk in disks.list() {
let mp = disk.mount_point().to_string_lossy().to_string();
// Skip root mount points
if mp == "/" || (mp.len() == 3 && mp.ends_with(":\\")) {
continue;
}
if canonical_str.starts_with(&mp) && mp.len() > best_len {
best_len = mp.len();
}
}
best_len > 0
}
#[derive(serde::Deserialize, Clone)]
struct TrackSyncInfo {
id: String,
url: String,
suffix: String,
artist: String,
album: String,
title: String,
#[serde(rename = "trackNumber")]
track_number: Option<u32>,
#[serde(rename = "discNumber")]
disc_number: Option<u32>,
year: Option<u32>,
}
/// Summary returned by `sync_batch_to_device` after all tracks are processed.
#[derive(Clone, serde::Serialize)]
struct SyncBatchResult {
done: u32,
skipped: u32,
failed: u32,
}
#[derive(serde::Serialize)]
struct SyncTrackResult {
path: String,
skipped: bool,
}
/// Replaces characters that are invalid in file/directory names on Windows and
/// most Unix filesystems with an underscore. Also trims leading/trailing dots
/// and spaces which cause issues on Windows.
fn sanitize_path_component(s: &str) -> String {
const INVALID: &[char] = &['/', '\\', ':', '*', '?', '"', '<', '>', '|'];
let sanitized: String = s
.chars()
.map(|c| if INVALID.contains(&c) || c.is_control() { '_' } else { c })
.collect();
sanitized.trim_matches(|c| c == '.' || c == ' ').to_string()
}
/// Evaluates `template` by substituting `{artist}`, `{album}`, `{title}`,
/// `{track_number}`, `{disc_number}`, `{year}` with sanitized values from `track`.
fn apply_device_sync_template(template: &str, track: &TrackSyncInfo) -> String {
let track_number = track.track_number
.map(|n| format!("{:02}", n))
.unwrap_or_default();
let disc_number = track.disc_number
.map(|n| n.to_string())
.unwrap_or_default();
let year = track.year
.map(|y| y.to_string())
.unwrap_or_default();
template
.replace("{artist}", &sanitize_path_component(&track.artist))
.replace("{album}", &sanitize_path_component(&track.album))
.replace("{title}", &sanitize_path_component(&track.title))
.replace("{track_number}", &track_number)
.replace("{disc_number}", &disc_number)
.replace("{year}", &year)
}
/// Downloads a single track to a USB/SD device using the configured filename template.
/// Emits `device:sync:progress` events with `{ jobId, trackId, status, path? }`.
#[tauri::command]
async fn sync_track_to_device(
track: TrackSyncInfo,
dest_dir: String,
template: String,
job_id: String,
app: tauri::AppHandle,
) -> Result<SyncTrackResult, String> {
let relative = apply_device_sync_template(&template, &track);
let file_name = format!("{}.{}", relative, track.suffix);
let dest_path = std::path::Path::new(&dest_dir).join(&file_name);
let path_str = dest_path.to_string_lossy().to_string();
if dest_path.exists() {
let _ = app.emit("device:sync:progress", serde_json::json!({
"jobId": job_id, "trackId": track.id, "status": "skipped", "path": path_str,
}));
return Ok(SyncTrackResult { path: path_str, skipped: true });
}
if let Some(parent) = dest_path.parent() {
tokio::fs::create_dir_all(parent)
.await
.map_err(|e| e.to_string())?;
}
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(300))
.build()
.map_err(|e| e.to_string())?;
let response = client.get(&track.url).send().await.map_err(|e| e.to_string())?;
if !response.status().is_success() {
let msg = format!("HTTP {}", response.status().as_u16());
let _ = app.emit("device:sync:progress", serde_json::json!({
"jobId": job_id, "trackId": track.id, "status": "error", "error": msg,
}));
return Err(msg);
}
let part_path = dest_path.with_extension(format!("{}.part", track.suffix));
if let Err(e) = stream_to_file(response, &part_path).await {
let _ = tokio::fs::remove_file(&part_path).await;
let _ = app.emit("device:sync:progress", serde_json::json!({
"jobId": job_id, "trackId": track.id, "status": "error", "error": e,
}));
return Err(e);
}
tokio::fs::rename(&part_path, &dest_path)
.await
.map_err(|e| e.to_string())?;
let _ = app.emit("device:sync:progress", serde_json::json!({
"jobId": job_id, "trackId": track.id, "status": "done", "path": path_str,
}));
Ok(SyncTrackResult { path: path_str, skipped: false })
}
/// Computes the expected file paths for a batch of tracks using the given template,
/// without downloading anything. Used by the cleanup flow to find orphans.
#[tauri::command]
fn compute_sync_paths(
tracks: Vec<TrackSyncInfo>,
dest_dir: String,
template: String,
) -> Vec<String> {
tracks.iter().map(|track| {
let relative = apply_device_sync_template(&template, track);
let file_name = format!("{}.{}", relative, track.suffix);
std::path::Path::new(&dest_dir)
.join(&file_name)
.to_string_lossy()
.to_string()
}).collect()
}
/// Lists all files (recursively) under `dir`. Returns `"VOLUME_NOT_FOUND"` if
/// the directory does not exist (e.g. USB was unplugged).
#[tauri::command]
async fn list_device_dir_files(dir: String) -> Result<Vec<String>, String> {
let root = std::path::PathBuf::from(&dir);
if !root.exists() {
return Err("VOLUME_NOT_FOUND".to_string());
}
let mut files = Vec::new();
let mut stack = vec![root];
while let Some(current) = stack.pop() {
let mut rd = match tokio::fs::read_dir(&current).await {
Ok(r) => r,
Err(_) => continue,
};
while let Ok(Some(entry)) = rd.next_entry().await {
let path = entry.path();
// Skip hidden dirs (e.g. .Trash-1000, .Ventoy, .fseventsd)
let is_hidden = path.file_name()
.and_then(|n| n.to_str())
.map(|n| n.starts_with('.'))
.unwrap_or(false);
if is_hidden { continue; }
if path.is_dir() {
stack.push(path);
} else {
files.push(path.to_string_lossy().to_string());
}
}
}
Ok(files)
}
/// Deletes a file from the device and prunes empty parent directories
/// (up to 2 levels: album folder, then artist folder).
#[tauri::command]
async fn delete_device_file(path: String) -> Result<(), String> {
let p = std::path::PathBuf::from(&path);
if p.exists() {
tokio::fs::remove_file(&p).await.map_err(|e| e.to_string())?;
prune_empty_parents(&p, 2).await;
}
Ok(())
}
/// Prune empty parent directories up to `levels` levels above `file_path`.
async fn prune_empty_parents(file_path: &std::path::Path, levels: usize) {
let mut current = file_path.parent().map(|d| d.to_path_buf());
for _ in 0..levels {
let Some(dir) = current else { break };
let is_empty = std::fs::read_dir(&dir)
.map(|mut rd| rd.next().is_none())
.unwrap_or(false);
if is_empty {
let _ = tokio::fs::remove_dir(&dir).await;
current = dir.parent().map(|d| d.to_path_buf());
} else {
break;
}
}
}
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct SubsonicAuthPayload {
base_url: String,
u: String,
t: String,
s: String,
v: String,
c: String,
f: String,
}
#[derive(serde::Deserialize)]
struct DeviceSyncSourcePayload {
#[serde(rename = "type")]
source_type: String,
id: String,
}
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct SyncDeltaResult {
add_bytes: u64,
add_count: u32,
del_bytes: u64,
del_count: u32,
available_bytes: u64,
tracks: Vec<serde_json::Value>,
}
async fn fetch_subsonic_songs(
client: &reqwest::Client,
auth: &SubsonicAuthPayload,
endpoint: &str,
id: &str,
) -> Result<Vec<serde_json::Value>, String> {
let url = format!("{}/{}", auth.base_url, endpoint);
let query = vec![
("u", auth.u.as_str()),
("t", auth.t.as_str()),
("s", auth.s.as_str()),
("v", auth.v.as_str()),
("c", auth.c.as_str()),
("f", auth.f.as_str()),
("id", id),
];
let res = client.get(&url).query(&query).send().await.map_err(|e| e.to_string())?;
let json: serde_json::Value = res.json().await.map_err(|e| e.to_string())?;
let root = json.get("subsonic-response").ok_or("No subsonic-response".to_string())?;
let songs = if endpoint == "getAlbum.view" {
root.get("album").and_then(|a| a.get("song"))
} else if endpoint == "getPlaylist.view" {
root.get("playlist").and_then(|p| p.get("entry"))
} else {
None
};
if let Some(arr) = songs.and_then(|s| s.as_array()) {
return Ok(arr.clone());
} else if let Some(obj) = songs.and_then(|s| s.as_object()) {
return Ok(vec![serde_json::Value::Object(obj.clone())]);
}
Ok(vec![])
}
#[tauri::command]
async fn calculate_sync_payload(
sources: Vec<DeviceSyncSourcePayload>,
deletion_ids: Vec<String>,
auth: SubsonicAuthPayload,
target_dir: String,
template: String,
) -> Result<SyncDeltaResult, String> {
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(30))
.build()
.map_err(|e| e.to_string())?;
let mut add_bytes = 0;
let mut add_count = 0;
let mut del_bytes = 0;
let mut del_count = 0;
let mut sync_tracks = Vec::new();
let (mut del_sources, mut add_sources) = (Vec::new(), Vec::new());
for s in sources {
if deletion_ids.contains(&s.id) {
del_sources.push(s);
} else {
add_sources.push(s);
}
}
let mut handles = Vec::new();
for source in add_sources {
let auth_clone = SubsonicAuthPayload {
base_url: auth.base_url.clone(), u: auth.u.clone(), t: auth.t.clone(), s: auth.s.clone(),
v: auth.v.clone(), c: auth.c.clone(), f: auth.f.clone(),
};
let cli = client.clone();
handles.push(tokio::spawn(async move {
let mut res_tracks = Vec::new();
if source.source_type == "album" {
if let Ok(ts) = fetch_subsonic_songs(&cli, &auth_clone, "getAlbum.view", &source.id).await { res_tracks.extend(ts); }
} else if source.source_type == "playlist" {
if let Ok(ts) = fetch_subsonic_songs(&cli, &auth_clone, "getPlaylist.view", &source.id).await { res_tracks.extend(ts); }
} else if source.source_type == "artist" {
let url = format!("{}/getArtist.view", auth_clone.base_url);
let query = vec![("u", auth_clone.u.as_str()), ("t", auth_clone.t.as_str()), ("s", auth_clone.s.as_str()), ("v", auth_clone.v.as_str()), ("c", auth_clone.c.as_str()), ("f", auth_clone.f.as_str()), ("id", &source.id)];
if let Ok(re) = cli.get(&url).query(&query).send().await {
if let Ok(js) = re.json::<serde_json::Value>().await {
if let Some(root) = js.get("subsonic-response").and_then(|r| r.get("artist")).and_then(|a| a.get("album")) {
let arr = root.as_array().map(|a| a.clone()).unwrap_or_else(|| {
root.as_object().map(|o| vec![serde_json::Value::Object(o.clone())]).unwrap_or_else(|| vec![])
});
for al in arr {
if let Some(aid) = al.get("id").and_then(|i| i.as_str()) {
if let Ok(ts) = fetch_subsonic_songs(&cli, &auth_clone, "getAlbum.view", aid).await {
res_tracks.extend(ts);
}
}
}
}
}
}
}
res_tracks
}));
}
let mut del_handles = Vec::new();
for source in del_sources {
let auth_clone = SubsonicAuthPayload {
base_url: auth.base_url.clone(), u: auth.u.clone(), t: auth.t.clone(), s: auth.s.clone(),
v: auth.v.clone(), c: auth.c.clone(), f: auth.f.clone(),
};
let cli = client.clone();
del_handles.push(tokio::spawn(async move {
let mut res_tracks = Vec::new();
if source.source_type == "album" {
if let Ok(ts) = fetch_subsonic_songs(&cli, &auth_clone, "getAlbum.view", &source.id).await { res_tracks.extend(ts); }
} else if source.source_type == "playlist" {
if let Ok(ts) = fetch_subsonic_songs(&cli, &auth_clone, "getPlaylist.view", &source.id).await { res_tracks.extend(ts); }
}
res_tracks
}));
}
let mut seen = std::collections::HashSet::new();
for handle in handles {
if let Ok(ts) = handle.await {
for track in ts {
if let Some(tid) = track.get("id").and_then(|i| i.as_str()) {
if !seen.contains(tid) {
seen.insert(tid.to_string());
// Build the expected path and skip files already present on device.
let already_exists = {
let suffix = track.get("suffix").and_then(|s| s.as_str()).unwrap_or("mp3");
let sync_info = TrackSyncInfo {
id: tid.to_string(),
url: String::new(),
suffix: suffix.to_string(),
artist: track.get("artist").and_then(|v| v.as_str()).unwrap_or("").to_string(),
album: track.get("album").and_then(|v| v.as_str()).unwrap_or("").to_string(),
title: track.get("title").and_then(|v| v.as_str()).unwrap_or("").to_string(),
track_number: track.get("track").and_then(|v| v.as_u64()).map(|n| n as u32),
disc_number: track.get("discNumber").and_then(|v| v.as_u64()).map(|n| n as u32),
year: track.get("year").and_then(|v| v.as_u64()).map(|n| n as u32),
};
let relative = apply_device_sync_template(&template, &sync_info);
let file_name = format!("{}.{}", relative, suffix);
std::path::Path::new(&target_dir).join(&file_name).exists()
};
if !already_exists {
add_count += 1;
let size = track.get("size").and_then(|s| s.as_u64()).unwrap_or_else(|| {
track.get("duration").and_then(|d| d.as_u64()).unwrap_or(0) * 320_000 / 8
});
add_bytes += size;
sync_tracks.push(track);
}
}
}
}
}
}
for handle in del_handles {
if let Ok(ts) = handle.await {
for track in ts {
del_count += 1;
let size = track.get("size").and_then(|s| s.as_u64()).unwrap_or_else(|| {
track.get("duration").and_then(|d| d.as_u64()).unwrap_or(0) * 320_000 / 8
});
del_bytes += size;
}
}
}
let mut available_bytes = 0;
for drive in get_removable_drives() {
if target_dir.starts_with(&drive.mount_point) {
available_bytes = drive.available_space;
break;
}
}
Ok(SyncDeltaResult {
add_bytes, add_count, del_bytes, del_count, available_bytes, tracks: sync_tracks,
})
}
/// Downloads a batch of tracks to a USB/SD device with controlled concurrency.
/// At most 2 parallel writes run simultaneously to prevent I/O choking on USB.
/// Emits throttled `device:sync:progress` events (max once per 500ms) and a
/// final `device:sync:complete` event with the summary.
#[tauri::command]
async fn sync_batch_to_device(
tracks: Vec<TrackSyncInfo>,
dest_dir: String,
template: String,
job_id: String,
expected_bytes: u64,
app: tauri::AppHandle,
) -> Result<SyncBatchResult, String> {
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
let dest_root = std::path::PathBuf::from(&dest_dir);
if !dest_root.exists() {
return Err("VOLUME_NOT_FOUND".to_string());
}
// Safety: verify dest_dir is on an actual mounted volume, not the root FS.
// This catches the case where a USB drive was unmounted but the empty
// mount-point directory still exists — writing there fills the root partition.
if !is_path_on_mounted_volume(&dest_root) {
return Err("NOT_MOUNTED_VOLUME".to_string());
}
// Safety: Ensure target logic hasn't exceeded physical volume capacities securely stopping dead bytes natively.
let drives = get_removable_drives();
let dest_canon = dest_root.canonicalize().unwrap_or_else(|_| dest_root.clone());
let dest_str = dest_canon.to_string_lossy();
for drive in drives {
if dest_str.starts_with(&drive.mount_point) {
// Buffer of ~10 MB padding boundary natively mapped
if expected_bytes > drive.available_space.saturating_sub(10_000_000) {
return Err(format!("NOT_ENOUGH_SPACE"));
}
break;
}
}
// Shared reqwest client — reused across all downloads.
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(300))
.build()
.map_err(|e| e.to_string())?;
// Concurrency limiter: max 2 parallel USB writes.
let semaphore = std::sync::Arc::new(tokio::sync::Semaphore::new(2));
// Counters.
let done = std::sync::Arc::new(AtomicU32::new(0));
let skipped = std::sync::Arc::new(AtomicU32::new(0));
let failed = std::sync::Arc::new(AtomicU32::new(0));
// Throttled event emission (max once per 500ms).
let last_emit = std::sync::Arc::new(Mutex::new(Instant::now()));
let total = tracks.len() as u32;
let mut handles = Vec::with_capacity(tracks.len());
for track in tracks {
let sem = semaphore.clone();
let cli = client.clone();
let app2 = app.clone();
let job = job_id.clone();
let tmpl = template.clone();
let dest = dest_dir.clone();
let d = done.clone();
let s = skipped.clone();
let f = failed.clone();
let le = last_emit.clone();
handles.push(tokio::spawn(async move {
let _permit = sem.acquire().await.expect("semaphore closed");
let relative = apply_device_sync_template(&tmpl, &track);
let file_name = format!("{}.{}", relative, track.suffix);
let dest_path = std::path::Path::new(&dest).join(&file_name);
let path_str = dest_path.to_string_lossy().to_string();
let status;
if dest_path.exists() {
s.fetch_add(1, Ordering::Relaxed);
status = "skipped";
} else {
// Ensure parent directories exist.
if let Some(parent) = dest_path.parent() {
if let Err(e) = tokio::fs::create_dir_all(parent).await {
f.fetch_add(1, Ordering::Relaxed);
let _ = app2.emit("device:sync:progress", serde_json::json!({
"jobId": job, "trackId": track.id, "status": "error",
"error": e.to_string(),
}));
return;
}
}
let response = match cli.get(&track.url).send().await {
Ok(r) if r.status().is_success() => r,
Ok(r) => {
f.fetch_add(1, Ordering::Relaxed);
let _ = app2.emit("device:sync:progress", serde_json::json!({
"jobId": job, "trackId": track.id, "status": "error",
"error": format!("HTTP {}", r.status().as_u16()),
}));
return;
}
Err(e) => {
f.fetch_add(1, Ordering::Relaxed);
let _ = app2.emit("device:sync:progress", serde_json::json!({
"jobId": job, "trackId": track.id, "status": "error",
"error": e.to_string(),
}));
return;
}
};
let part_path = dest_path.with_extension(format!("{}.part", track.suffix));
if let Err(e) = stream_to_file(response, &part_path).await {
let _ = tokio::fs::remove_file(&part_path).await;
f.fetch_add(1, Ordering::Relaxed);
let _ = app2.emit("device:sync:progress", serde_json::json!({
"jobId": job, "trackId": track.id, "status": "error",
"error": e,
}));
return;
}
if let Err(e) = tokio::fs::rename(&part_path, &dest_path).await {
let _ = tokio::fs::remove_file(&part_path).await;
f.fetch_add(1, Ordering::Relaxed);
let _ = app2.emit("device:sync:progress", serde_json::json!({
"jobId": job, "trackId": track.id, "status": "error",
"error": e.to_string(),
}));
return;
}
d.fetch_add(1, Ordering::Relaxed);
status = "done";
}
// Throttled progress event — max once per 500ms.
let should_emit = {
let mut guard = le.lock().await;
if guard.elapsed() >= Duration::from_millis(500) {
*guard = Instant::now();
true
} else {
false
}
};
if should_emit {
let _ = app2.emit("device:sync:progress", serde_json::json!({
"jobId": job, "trackId": track.id, "status": status, "path": path_str,
"done": d.load(Ordering::Relaxed),
"skipped": s.load(Ordering::Relaxed),
"failed": f.load(Ordering::Relaxed),
"total": total,
}));
}
}));
}
// Wait for all tasks to complete.
for handle in handles {
let _ = handle.await;
}
let result = SyncBatchResult {
done: done.load(Ordering::Relaxed),
skipped: skipped.load(Ordering::Relaxed),
failed: failed.load(Ordering::Relaxed),
};
// Final event so the frontend always sees 100%.
let _ = app.emit("device:sync:complete", serde_json::json!({
"jobId": job_id,
"done": result.done,
"skipped": result.skipped,
"failed": result.failed,
"total": total,
}));
Ok(result)
}
/// Deletes multiple files from the device in one call and prunes empty parent
/// directories. Returns the number of files successfully deleted.
#[tauri::command]
async fn delete_device_files(paths: Vec<String>) -> Result<u32, String> {
let mut deleted: u32 = 0;
for path in &paths {
let p = std::path::PathBuf::from(path);
if p.exists() {
if tokio::fs::remove_file(&p).await.is_ok() {
deleted += 1;
prune_empty_parents(&p, 2).await;
}
}
}
Ok(deleted)
}
/// Builds and returns a new system-tray icon with all menu items and event handlers.
/// Called from `setup()` (initial creation) and from `toggle_tray_icon` (re-creation).
fn build_tray_icon(app: &tauri::AppHandle) -> tauri::Result<TrayIcon> {
@@ -1691,6 +2376,7 @@ pub fn run() {
})
.invoke_handler(tauri::generate_handler![
greet,
calculate_sync_payload,
exit_app,
set_window_decorations,
no_compositing_mode,
@@ -1713,6 +2399,10 @@ pub fn run() {
audio::audio_play_radio,
audio::audio_set_crossfade,
audio::audio_set_gapless,
audio::audio_list_devices,
audio::audio_canonicalize_selected_device,
audio::audio_default_output_device_name,
audio::audio_set_device,
audio::audio_chain_preload,
discord::discord_update_presence,
discord::discord_clear_presence,
@@ -1734,6 +2424,13 @@ pub fn run() {
get_hot_cache_size,
delete_hot_cache_track,
purge_hot_cache,
sync_track_to_device,
sync_batch_to_device,
compute_sync_paths,
list_device_dir_files,
delete_device_file,
delete_device_files,
get_removable_drives,
toggle_tray_icon,
check_dir_accessible,
download_zip,
+11
View File
@@ -2,5 +2,16 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
// WebKitGTK on Wayland is unstable — force X11/XWayland on all Linux packages.
// Users can still override by setting these vars before launch.
#[cfg(target_os = "linux")]
unsafe {
if std::env::var("GDK_BACKEND").is_err() {
std::env::set_var("GDK_BACKEND", "x11");
}
if std::env::var("WEBKIT_DISABLE_COMPOSITING_MODE").is_err() {
std::env::set_var("WEBKIT_DISABLE_COMPOSITING_MODE", "1");
}
}
psysonic_lib::run();
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Psysonic",
"version": "1.34.9",
"version": "1.34.11",
"identifier": "dev.psysonic.player",
"build": {
"beforeDevCommand": "npm run dev",
+36 -21
View File
@@ -36,6 +36,7 @@ import Playlists from './pages/Playlists';
import PlaylistDetail from './pages/PlaylistDetail';
import InternetRadio from './pages/InternetRadio';
import FolderBrowser from './pages/FolderBrowser';
import DeviceSync from './pages/DeviceSync';
import NowPlayingPage from './pages/NowPlaying';
import FullscreenPlayer from './components/FullscreenPlayer';
import ContextMenu from './components/ContextMenu';
@@ -45,7 +46,6 @@ import { DragDropProvider } from './contexts/DragDropContext';
import TooltipPortal from './components/TooltipPortal';
import ConnectionIndicator from './components/ConnectionIndicator';
import LastfmIndicator from './components/LastfmIndicator';
import OfflineOverlay from './components/OfflineOverlay';
import OfflineBanner from './components/OfflineBanner';
import OfflineLibrary from './pages/OfflineLibrary';
import Genres from './pages/Genres';
@@ -66,7 +66,7 @@ import { useThemeStore } from './store/themeStore';
import { useThemeScheduler } from './hooks/useThemeScheduler';
import { useFontStore } from './store/fontStore';
import { useEqStore } from './store/eqStore';
import { useKeybindingsStore } from './store/keybindingsStore';
import { useKeybindingsStore, matchInAppBinding, buildInAppBinding } from './store/keybindingsStore';
import { useGlobalShortcutsStore } from './store/globalShortcutsStore';
import { useZipDownloadStore } from './store/zipDownloadStore';
import ZipDownloadOverlay from './components/ZipDownloadOverlay';
@@ -341,17 +341,10 @@ function AppShell() {
{isQueueVisible ? <PanelRightClose size={18} /> : <PanelRight size={18} />}
</button>
</header>
{connStatus === 'disconnected' && hasOfflineContent && (
<OfflineBanner onRetry={connRetry} isChecking={connRetrying} />
{connStatus === 'disconnected' && (
<OfflineBanner onRetry={connRetry} isChecking={connRetrying} showSettingsLink={!hasOfflineContent} serverName={serverName} />
)}
<div className="content-body" style={{ padding: 0, position: 'relative' }}>
{connStatus === 'disconnected' && !hasOfflineContent && (
<OfflineOverlay
serverName={serverName}
onRetry={connRetry}
isChecking={connRetrying}
/>
)}
<Routes>
<Route path="/" element={<Home />} />
<Route path="/albums" element={<Albums />} />
@@ -378,6 +371,7 @@ function AppShell() {
<Route path="/playlists/:id" element={<PlaylistDetail />} />
<Route path="/radio" element={<InternetRadio />} />
<Route path="/folders" element={<FolderBrowser />} />
<Route path="/device-sync" element={<DeviceSync />} />
</Routes>
</div>
</main>
@@ -429,13 +423,10 @@ function TauriEventBridge() {
useEffect(() => {
let unlisten: (() => void) | undefined;
listen('audio:device-changed', () => {
const { currentTrack, currentTime, isPlaying, playTrack, resetAudioPause } = usePlayerStore.getState();
const { currentTrack, isPlaying, playTrack, resetAudioPause } = usePlayerStore.getState();
if (!currentTrack) return;
if (isPlaying) {
const pos = currentTime;
const dur = currentTrack.duration || 1;
playTrack(currentTrack);
setTimeout(() => usePlayerStore.getState().seek(pos / dur), 600);
} else {
// Paused: clear warm-pause flag so the next resume uses the cold path
// (audio_play + seek) which creates a new Sink on the new device.
@@ -445,6 +436,23 @@ function TauriEventBridge() {
return () => { unlisten?.(); };
}, []);
// Pinned output device was unplugged — Rust already fell back to system default.
// Clear the stored device so the Settings dropdown resets to "System Default".
useEffect(() => {
let unlisten: (() => void) | undefined;
listen('audio:device-reset', () => {
useAuthStore.getState().setAudioOutputDevice(null);
const { currentTrack, currentTime, isPlaying, playTrack, resetAudioPause } = usePlayerStore.getState();
if (!currentTrack) return;
if (isPlaying) {
playTrack(currentTrack);
} else {
resetAudioPause();
}
}).then(u => { unlisten = u; });
return () => { unlisten?.(); };
}, []);
// Sync tray-icon visibility with the user's stored setting.
// Runs once on mount (initial sync) and again whenever the setting changes.
const showTrayIcon = useAuthStore(s => s.showTrayIcon);
@@ -457,15 +465,18 @@ function TauriEventBridge() {
const onKey = (e: KeyboardEvent) => {
const tag = (e.target as HTMLElement)?.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return;
// Global shortcuts use modifier combos — skip in-app bindings for those
// (X11 GrabModeAsync delivers the key to both the grabber and the focused WebView)
if (e.ctrlKey || e.altKey || e.metaKey) return;
const chord = buildInAppBinding(e);
if (chord) {
const registered = Object.values(useGlobalShortcutsStore.getState().shortcuts);
if (registered.includes(chord)) return;
}
const { bindings } = useKeybindingsStore.getState();
const { togglePlay, next, previous, setVolume, seek, toggleQueue, toggleFullscreen } = usePlayerStore.getState();
const action = (Object.entries(bindings) as [string, string | null][])
.find(([, code]) => code === e.code)?.[0];
.find(([, b]) => matchInAppBinding(e, b))?.[0];
if (!action) return;
e.preventDefault();
@@ -478,12 +489,16 @@ function TauriEventBridge() {
case 'volume-down': setVolume(Math.max(0, usePlayerStore.getState().volume - 0.05)); break;
case 'seek-forward': {
const s = usePlayerStore.getState();
seek(Math.min(s.currentTrack?.duration ?? 0, s.currentTime + 10));
const dur = s.currentTrack?.duration ?? 0;
if (!dur) break;
seek(Math.min(1, (s.currentTime + 10) / dur));
break;
}
case 'seek-backward': {
const s = usePlayerStore.getState();
seek(Math.max(0, s.currentTime - 10));
const dur = s.currentTrack?.duration ?? 0;
if (!dur) break;
seek(Math.max(0, (s.currentTime - 10) / dur));
break;
}
case 'toggle-queue': toggleQueue(); break;
+11 -4
View File
@@ -23,7 +23,7 @@ function getAuthParams(username: string, password: string) {
return { u: username, t: token, s: salt, v: '1.16.1', c: `psysonic/${version}`, f: 'json' };
}
function getClient() {
export function getClient() {
const { getBaseUrl, getActiveServer } = useAuthStore.getState();
const server = getActiveServer();
const baseUrl = getBaseUrl();
@@ -741,11 +741,18 @@ export async function fetchStatisticsFormatSample(): Promise<StatisticsFormatSam
}
export async function getArtists(): Promise<SubsonicArtist[]> {
const data = await api<{ artists: { index: Array<{ artist: SubsonicArtist[] }> } }>('getArtists.view', {
const data = await api<{ artists: { index: any } }>('getArtists.view', {
...libraryFilterParams(),
});
const indices = data.artists?.index ?? [];
return indices.flatMap(i => i.artist ?? []);
const rawIdx = data.artists?.index;
const indices = Array.isArray(rawIdx) ? rawIdx : (rawIdx ? [rawIdx] : []);
const artists: SubsonicArtist[] = [];
for (const idx of indices) {
const rawArt = idx.artist;
const arr = Array.isArray(rawArt) ? rawArt : (rawArt ? [rawArt] : []);
artists.push(...arr);
}
return artists;
}
export async function getArtist(id: string): Promise<{ artist: SubsonicArtist; albums: SubsonicAlbum[] }> {
+7 -2
View File
@@ -15,9 +15,10 @@ interface AlbumCardProps {
selectionMode?: boolean;
onToggleSelect?: (id: string) => void;
showRating?: boolean;
selectedAlbums?: SubsonicAlbum[];
}
function AlbumCard({ album, selected, selectionMode, onToggleSelect, showRating = false }: AlbumCardProps) {
function AlbumCard({ album, selected, selectionMode, onToggleSelect, showRating = false, selectedAlbums = [] }: AlbumCardProps) {
const navigate = useNavigate();
const openContextMenu = usePlayerStore(s => s.openContextMenu);
const serverId = useAuthStore(s => s.activeServerId ?? '');
@@ -44,7 +45,11 @@ function AlbumCard({ album, selected, selectionMode, onToggleSelect, showRating
onKeyDown={e => e.key === 'Enter' && handleClick()}
onContextMenu={(e) => {
e.preventDefault();
openContextMenu(e.clientX, e.clientY, album, 'album');
if (selectionMode && selectedAlbums.length > 0) {
openContextMenu(e.clientX, e.clientY, selectedAlbums, 'multi-album');
} else {
openContextMenu(e.clientX, e.clientY, album, 'album');
}
}}
onMouseDown={e => {
if (selectionMode || e.button !== 0) return;
+11 -7
View File
@@ -6,6 +6,7 @@ import CachedImage from './CachedImage';
import CoverLightbox from './CoverLightbox';
import { useTranslation } from 'react-i18next';
import { useIsMobile } from '../hooks/useIsMobile';
import { useThemeStore } from '../store/themeStore';
import StarRating from './StarRating';
import type { EntityRatingSupportLevel } from '../api/subsonic';
@@ -125,6 +126,7 @@ export default function AlbumHeader({
const totalDuration = songs.reduce((acc, s) => acc + s.duration, 0);
const totalSize = songs.reduce((acc, s) => acc + (s.size ?? 0), 0);
const formatLabel = [...new Set(songs.map(s => s.suffix).filter((f): f is string => !!f))].map(f => f.toUpperCase()).join(' / ');
const enableCoverArtBackground = useThemeStore(s => s.enableCoverArtBackground);
return (
<>
@@ -138,14 +140,16 @@ export default function AlbumHeader({
)}
<div className="album-detail-header">
{resolvedCoverUrl && (
<div
className="album-detail-bg"
style={{ backgroundImage: `url(${resolvedCoverUrl})` }}
aria-hidden="true"
/>
{resolvedCoverUrl && enableCoverArtBackground && (
<>
<div
className="album-detail-bg"
style={{ backgroundImage: `url(${resolvedCoverUrl})` }}
aria-hidden="true"
/>
<div className="album-detail-overlay" aria-hidden="true" />
</>
)}
<div className="album-detail-overlay" aria-hidden="true" />
<div className="album-detail-content">
<button className="btn btn-ghost album-detail-back" onClick={() => navigate(-1)}>
+7 -5
View File
@@ -10,6 +10,7 @@ import { AddToPlaylistSubmenu } from './ContextMenu';
import { useIsMobile } from '../hooks/useIsMobile';
import StarRating from './StarRating';
import { useSelectionStore } from '../store/selectionStore';
import { useThemeStore } from '../store/themeStore';
function formatDuration(seconds: number): string {
const h = Math.floor(seconds / 3600);
@@ -19,11 +20,11 @@ function formatDuration(seconds: number): string {
return `${m}:${s.toString().padStart(2, '0')}`;
}
function codecLabel(song: { suffix?: string; bitRate?: number }): string {
function codecLabel(song: { suffix?: string; bitRate?: number }, showBitrate: boolean): string {
const parts: string[] = [];
if (song.suffix) parts.push(song.suffix.toUpperCase());
if (song.bitRate) parts.push(`${song.bitRate}`);
return parts.join(' ');
if (showBitrate && song.bitRate) parts.push(`${song.bitRate} kbps`);
return parts.join(' · ');
}
// ── Column configuration ──────────────────────────────────────────────────────
@@ -108,6 +109,7 @@ const TrackRow = React.memo(function TrackRow({
}: TrackRowProps) {
const { t } = useTranslation();
const navigate = useNavigate();
const showBitrate = useThemeStore(s => s.showBitrate);
// Fine-grained: only re-renders when THIS row's selection boolean flips.
const isSelected = useSelectionStore(s => s.selectedIds.has(song.id));
const isActive = currentTrackId === song.id;
@@ -192,8 +194,8 @@ const TrackRow = React.memo(function TrackRow({
case 'format':
return (
<div key="format" className="track-meta">
{(song.suffix || song.bitRate) && (
<span className="track-codec">{codecLabel(song)}</span>
{(song.suffix || (showBitrate && song.bitRate)) && (
<span className="track-codec">{codecLabel(song, showBitrate)}</span>
)}
</div>
);
File diff suppressed because it is too large Load Diff
+4 -2
View File
@@ -15,9 +15,10 @@ interface Props {
onChange: (value: string) => void;
className?: string;
style?: React.CSSProperties;
disabled?: boolean;
}
export default function CustomSelect({ value, options, onChange, className = '', style }: Props) {
export default function CustomSelect({ value, options, onChange, className = '', style, disabled }: Props) {
const [open, setOpen] = useState(false);
const triggerRef = useRef<HTMLButtonElement>(null);
const listRef = useRef<HTMLDivElement>(null);
@@ -80,7 +81,8 @@ export default function CustomSelect({ value, options, onChange, className = '',
type="button"
className={`custom-select-trigger ${className}`}
style={style}
onClick={() => setOpen(v => !v)}
disabled={disabled}
onClick={() => { if (!disabled) setOpen(v => !v); }}
aria-haspopup="listbox"
aria-expanded={open}
>
+4 -2
View File
@@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next';
import { playAlbum } from '../utils/playAlbum';
import { useIsMobile } from '../hooks/useIsMobile';
import { useAuthStore } from '../store/authStore';
import { useThemeStore } from '../store/themeStore';
import { filterAlbumsByMixRatings, getMixMinRatingsConfigFromAuth } from '../utils/mixRatingFilter';
const INTERVAL_MS = 10000;
@@ -58,6 +59,7 @@ export default function Hero({ albums: albumsProp }: HeroProps = {}) {
const isMobile = useIsMobile();
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
const mixMinRatingFilterEnabled = useAuthStore(s => s.mixMinRatingFilterEnabled);
const enableCoverArtBackground = useThemeStore(s => s.enableCoverArtBackground);
const mixMinRatingAlbum = useAuthStore(s => s.mixMinRatingAlbum);
const mixMinRatingArtist = useAuthStore(s => s.mixMinRatingArtist);
const [albums, setAlbums] = useState<SubsonicAlbum[]>([]);
@@ -141,8 +143,8 @@ export default function Hero({ albums: albumsProp }: HeroProps = {}) {
onClick={() => navigate(`/album/${album.id}`)}
style={{ cursor: 'pointer' }}
>
<HeroBg url={stableBgUrl.current} />
<div className="hero-overlay" aria-hidden="true" />
{enableCoverArtBackground && <HeroBg url={stableBgUrl.current} />}
{enableCoverArtBackground && <div className="hero-overlay" aria-hidden="true" />}
{/* key causes re-mount → animate-fade-in triggers on each album change */}
<div className="hero-content animate-fade-in" key={album.id}>
+19 -3
View File
@@ -1,18 +1,34 @@
import React from 'react';
import { WifiOff, RefreshCw } from 'lucide-react';
import { WifiOff, RefreshCw, Settings } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
interface Props {
onRetry: () => void;
isChecking: boolean;
showSettingsLink?: boolean;
serverName?: string;
}
export default function OfflineBanner({ onRetry, isChecking }: Props) {
export default function OfflineBanner({ onRetry, isChecking, showSettingsLink, serverName }: Props) {
const { t } = useTranslation();
const navigate = useNavigate();
const message = showSettingsLink
? t('connection.offlineNoCacheBanner', { server: serverName })
: t('connection.offlineModeBanner');
return (
<div className="offline-banner">
<WifiOff size={14} />
<span>{t('connection.offlineModeBanner')}</span>
<span>{message}</span>
{showSettingsLink && (
<button
className="offline-banner-retry"
onClick={() => navigate('/settings', { state: { tab: 'server' } })}
>
<Settings size={12} />
{t('connection.serverSettings')}
</button>
)}
<button
className="offline-banner-retry"
onClick={onRetry}
+5 -5
View File
@@ -1,7 +1,8 @@
import React, { useState, useRef, useMemo } from 'react';
import { Track, usePlayerStore, songToTrack } from '../store/playerStore';
import { Play, Music, Star, X, Trash2, Save, FolderOpen, Shuffle, Infinity, Waves, MicVocal, ListMusic, Check, ListPlus, ArrowUpToLine, Radio } from 'lucide-react';
import { buildCoverArtUrl, coverArtCacheKey, getAlbum, getPlaylists, getPlaylist, createPlaylist, updatePlaylist, deletePlaylist, SubsonicPlaylist } from '../api/subsonic';
import { buildCoverArtUrl, coverArtCacheKey, getAlbum, getPlaylists, getPlaylist, updatePlaylist, deletePlaylist, SubsonicPlaylist } from '../api/subsonic';
import { usePlaylistStore } from '../store/playlistStore';
import { useCachedUrl } from './CachedImage';
import { useEffect } from 'react';
import { useTranslation } from 'react-i18next';
@@ -655,10 +656,9 @@ export default function QueuePanel() {
onClose={() => setSaveModalOpen(false)}
onSave={async (name) => {
try {
await createPlaylist(name, queue.map(t => t.id));
const playlists = await getPlaylists();
const created = playlists.find(p => p.name === name);
if (created) setActivePlaylist({ id: created.id, name: created.name });
const createPlaylist = usePlaylistStore.getState().createPlaylist;
const pl = await createPlaylist(name, queue.map(t => t.id));
if (pl) setActivePlaylist({ id: pl.id, name: pl.name });
setSaveModalOpen(false);
} catch (e) {
console.error('Failed to save playlist', e);
+103 -14
View File
@@ -1,8 +1,9 @@
import React, { useState, useRef, useLayoutEffect, useEffect, useCallback } from 'react';
import React, { useState, useRef, useLayoutEffect, useEffect, useCallback, useMemo } from 'react';
import { createPortal } from 'react-dom';
import { usePlayerStore } from '../store/playerStore';
import { useOfflineStore } from '../store/offlineStore';
import { useOfflineJobStore } from '../store/offlineJobStore';
import { useDeviceSyncJobStore } from '../store/deviceSyncJobStore';
import { useAuthStore } from '../store/authStore';
import { useSidebarStore } from '../store/sidebarStore';
import { NavLink } from 'react-router-dom';
@@ -10,10 +11,12 @@ import { useTranslation } from 'react-i18next';
import {
Disc3, Users, Music4, Radio, Settings, Heart, BarChart3,
PanelLeftClose, PanelLeft, HelpCircle, AudioLines, HardDriveDownload, Tags, ListMusic, Cast,
ChevronDown, Check, Music2, TrendingUp, FolderOpen, X, Wand2,
ChevronDown, Check, Music2, TrendingUp, FolderOpen, X, Wand2, ChevronRight, PlayCircle, HardDriveUpload,
} from 'lucide-react';
import PsysonicLogo from './PsysonicLogo';
import PSmallLogo from './PSmallLogo';
import { getPlaylists } from '../api/subsonic';
import { usePlaylistStore } from '../store/playlistStore';
// All configurable nav items — order and visibility controlled by sidebarStore.
// Exported so Settings can render the same item metadata.
@@ -28,7 +31,8 @@ export const ALL_NAV_ITEMS: Record<string, { icon: React.ElementType; labelKey:
playlists: { icon: ListMusic, labelKey: 'sidebar.playlists', to: '/playlists', section: 'library' },
mostPlayed: { icon: TrendingUp, labelKey: 'sidebar.mostPlayed', to: '/most-played', section: 'library' },
radio: { icon: Cast, labelKey: 'sidebar.radio', to: '/radio', section: 'library' },
folderBrowser: { icon: FolderOpen, labelKey: 'sidebar.folderBrowser', to: '/folders', section: 'library' },
folderBrowser: { icon: FolderOpen, labelKey: 'sidebar.folderBrowser', to: '/folders', section: 'library' },
deviceSync: { icon: HardDriveUpload, labelKey: 'sidebar.deviceSync', to: '/device-sync', section: 'library' },
statistics: { icon: BarChart3, labelKey: 'sidebar.statistics', to: '/statistics', section: 'system' },
help: { icon: HelpCircle, labelKey: 'sidebar.help', to: '/help', section: 'system' },
};
@@ -47,6 +51,12 @@ export default function Sidebar({
const offlineJobs = useOfflineJobStore(s => s.jobs);
const cancelAllDownloads = useOfflineJobStore(s => s.cancelAllDownloads);
const activeJobs = offlineJobs.filter(j => j.status === 'queued' || j.status === 'downloading');
const syncJobStatus = useDeviceSyncJobStore(s => s.status);
const syncJobDone = useDeviceSyncJobStore(s => s.done);
const syncJobSkip = useDeviceSyncJobStore(s => s.skipped);
const syncJobFail = useDeviceSyncJobStore(s => s.failed);
const syncJobTotal = useDeviceSyncJobStore(s => s.total);
const isSyncing = syncJobStatus === 'running';
const offlineAlbums = useOfflineStore(s => s.albums);
const serverId = useAuthStore(s => s.activeServerId ?? '');
const isLoggedIn = useAuthStore(s => s.isLoggedIn);
@@ -56,6 +66,14 @@ export default function Sidebar({
const hasOfflineContent = Object.values(offlineAlbums).some(a => a.serverId === serverId);
const sidebarItems = useSidebarStore(s => s.items);
const [libraryDropdownOpen, setLibraryDropdownOpen] = useState(false);
const [playlistsExpanded, setPlaylistsExpanded] = useState(false);
const playlistsRaw = usePlaylistStore(s => s.playlists);
const playlistsLoading = usePlaylistStore(s => s.playlistsLoading);
const fetchPlaylists = usePlaylistStore(s => s.fetchPlaylists);
// Sort playlists alphabetically by name
const playlists = useMemo(() => {
return [...playlistsRaw].sort((a, b) => a.name.localeCompare(b.name));
}, [playlistsRaw]);
const [dropdownRect, setDropdownRect] = useState({ top: 0, left: 0, width: 0 });
const libraryTriggerRef = useRef<HTMLButtonElement>(null);
const showLibraryPicker = !isCollapsed && isLoggedIn && musicFolders.length > 1;
@@ -113,6 +131,12 @@ export default function Sidebar({
setLibraryDropdownOpen(false);
};
// Fetch playlists when expanded
useEffect(() => {
if (!playlistsExpanded || !isLoggedIn) return;
fetchPlaylists();
}, [playlistsExpanded, isLoggedIn, fetchPlaylists]);
// Resolve ordered, visible items per section from store config
const visibleLibrary = sidebarItems
.filter(cfg => cfg.visible && ALL_NAV_ITEMS[cfg.id]?.section === 'library')
@@ -216,17 +240,69 @@ export default function Sidebar({
<span className="nav-section-label">{t('sidebar.library')}</span>
))}
{visibleLibrary.map(item => (
<NavLink
key={item.to}
to={item.to}
end={item.to === '/'}
className={({ isActive }) => `nav-link ${isActive ? 'active' : ''}`}
data-tooltip={isCollapsed ? t(item.labelKey) : undefined}
data-tooltip-pos="bottom"
>
<item.icon size={isCollapsed ? 22 : 18} />
{!isCollapsed && <span>{t(item.labelKey)}</span>}
</NavLink>
item.to === '/playlists' ? (
// Playlists item with expand button
<div key={item.to} className="sidebar-playlists-wrapper">
<div className="sidebar-playlists-header-row">
<NavLink
to={item.to}
className={({ isActive }) => `nav-link sidebar-playlists-main-link ${isActive ? 'active' : ''}`}
data-tooltip={isCollapsed ? t(item.labelKey) : undefined}
data-tooltip-pos="bottom"
>
<item.icon size={isCollapsed ? 22 : 18} />
{!isCollapsed && <span>{t(item.labelKey)}</span>}
</NavLink>
{!isCollapsed && (
<button
className={`sidebar-playlists-toggle ${playlistsExpanded ? 'expanded' : ''}`}
onClick={() => setPlaylistsExpanded(!playlistsExpanded)}
aria-expanded={playlistsExpanded}
aria-label={playlistsExpanded ? t('sidebar.collapsePlaylists') : t('sidebar.expandPlaylists')}
data-tooltip={playlistsExpanded ? t('sidebar.collapsePlaylists') : t('sidebar.expandPlaylists')}
>
<ChevronRight size={14} />
</button>
)}
</div>
{!isCollapsed && playlistsExpanded && (
<div className="sidebar-playlists-list">
{playlistsLoading ? (
<div className="sidebar-playlists-loading">
<div className="spinner" style={{ width: 14, height: 14 }} />
</div>
) : playlists.length === 0 ? (
<div className="sidebar-playlists-empty">{t('playlists.empty')}</div>
) : (
playlists.map((pl: { id: string; name: string }) => (
<NavLink
key={pl.id}
to={`/playlists/${pl.id}`}
className={({ isActive }) => `nav-link sidebar-playlist-item ${isActive ? 'active' : ''}`}
data-tooltip={isCollapsed ? pl.name : undefined}
data-tooltip-pos="bottom"
>
<PlayCircle size={12} />
<span>{pl.name}</span>
</NavLink>
))
)}
</div>
)}
</div>
) : (
<NavLink
key={item.to}
to={item.to}
end={item.to === '/'}
className={({ isActive }) => `nav-link ${isActive ? 'active' : ''}`}
data-tooltip={isCollapsed ? t(item.labelKey) : undefined}
data-tooltip-pos="bottom"
>
<item.icon size={isCollapsed ? 22 : 18} />
{!isCollapsed && <span>{t(item.labelKey)}</span>}
</NavLink>
)
))}
{/* Now Playing — fixed, always visible */}
@@ -300,6 +376,19 @@ export default function Sidebar({
</button>
</div>
)}
{isSyncing && (
<div
className={`sidebar-offline-queue sidebar-sync-queue ${isCollapsed ? 'sidebar-offline-queue--collapsed' : ''}`}
data-tooltip={isCollapsed ? t('sidebar.syncingTracks', { done: syncJobDone + syncJobSkip + syncJobFail, total: syncJobTotal }) : undefined}
data-tooltip-pos="right"
>
<HardDriveUpload size={isCollapsed ? 18 : 14} className="spin-slow" />
{!isCollapsed && (
<span>{t('sidebar.syncingTracks', { done: syncJobDone + syncJobSkip + syncJobFail, total: syncJobTotal })}</span>
)}
</div>
)}
</nav>
</aside>
);
+20
View File
@@ -93,6 +93,19 @@ export const THEME_GROUPS: { group: string; themes: ThemeDef[] }[] = [
{ id: 'vintage-tube-radio', label: 'Tube Radio', bg: '#3E2723', card: '#1E110A', accent: '#FF6F00' },
],
},
{
group: 'COMMUNITY',
themes: [
{ id: 'amber-night', label: 'Amber Night', bg: '#1a1410', card: '#201a12', accent: '#d4a96a' },
{ id: 'amoled-black-pure', label: 'AMOLED Black Pure', bg: '#000000', card: '#000000', accent: '#ffffff' },
{ id: 'ice-blue', label: 'Ice Blue', bg: '#0e1d28', card: '#132430', accent: '#7dd3e8' },
{ id: 'midnight-blue', label: 'Midnight Blue', bg: '#0d1420', card: '#111a28', accent: '#60a5fa' },
{ id: 'monochrome', label: 'Monochrome Dark', bg: '#161616', card: '#1c1c1c', accent: '#c0c0c0' },
{ id: 'phosphor-green', label: 'Phosphor Green', bg: '#0d1a0d', card: '#111f11', accent: '#4ade80' },
{ id: 'rose-dark', label: 'Rose Dark', bg: '#1a0d14', card: '#20111a', accent: '#f472b6' },
{ id: 'sepia-dark', label: 'Sepia Dark', bg: '#1e1a14', card: '#252018', accent: '#c8b89a' },
],
},
{
group: 'Mediaplayer',
themes: [
@@ -123,6 +136,13 @@ export const THEME_GROUPS: { group: string; themes: ThemeDef[] }[] = [
{ id: 'powerslave', label: 'Powerslave (inspired)', bg: '#F0DFB0', card: '#2A1808', accent: '#C8960C' },
],
},
{
group: 'Accessibility',
themes: [
{ id: 'vision-dark', label: 'Vision Dark', bg: '#0d0b12', card: '#16131e', accent: '#ffd700' },
{ id: 'vision-navy', label: 'Vision Navy', bg: '#0a1628', card: '#112038', accent: '#ffd700' },
],
},
{
group: 'Social Media',
themes: [
+11
View File
@@ -869,6 +869,17 @@ export default function WaveformSeek({ trackId }: Props) {
return () => ro.disconnect();
}, [seekbarStyle]);
// Theme change observer — redraw canvas when theme changes.
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const observer = new MutationObserver(() => {
drawSeekbar(canvas, seekbarStyle, heightsRef.current, progressRef.current, bufferedRef.current, animStateRef.current);
});
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
return () => observer.disconnect();
}, [seekbarStyle]);
const trackIdRef = useRef(trackId);
trackIdRef.current = trackId;
const seekRef = useRef(seek);
+120 -2
View File
@@ -17,6 +17,7 @@ export const deTranslation = {
expand: 'Sidebar einblenden',
collapse: 'Sidebar ausblenden',
downloadingTracks: '{{n}} Tracks werden gecacht…',
syncingTracks: 'Synchronisiere {{done}}/{{total}}…',
cancelDownload: 'Download abbrechen',
offlineLibrary: 'Offline-Bibliothek',
genres: 'Genres',
@@ -24,8 +25,11 @@ export const deTranslation = {
mostPlayed: 'Meistgehört',
radio: 'Internetradio',
folderBrowser: 'Ordner-Browser',
deviceSync: 'Gerätesync',
libraryScope: 'Bibliotheksumfang',
allLibraries: 'Alle Bibliotheken',
expandPlaylists: 'Playlists ausklappen',
collapsePlaylists: 'Playlists einklappen',
},
home: {
hero: 'Featured',
@@ -106,10 +110,14 @@ export const deTranslation = {
unfavoriteArtist: 'Künstler aus Favoriten entfernen',
unfavoriteAlbum: 'Album aus Favoriten entfernen',
removeFromQueue: 'Diesen Song entfernen',
removeFromPlaylist: 'Aus Playlist entfernen',
openAlbum: 'Album öffnen',
goToArtist: 'Zum Künstler',
download: 'Herunterladen (ZIP)',
addToPlaylist: 'Zur Playlist hinzufügen',
selectedPlaylists: '{{count}} Playlists ausgewählt',
selectedAlbums: '{{count}} Alben ausgewählt',
selectedArtists: '{{count}} Künstler ausgewählt',
songInfo: 'Song-Infos',
},
albumDetail: {
@@ -296,13 +304,18 @@ export const deTranslation = {
notFound: 'Keine Künstler gefunden.',
albumCount_one: '{{count}} Album',
albumCount_other: '{{count}} Alben',
selectionCount: '{{count}} ausgewählt',
select: 'Mehrfachauswahl',
startSelect: 'Mehrfachauswahl aktivieren',
cancelSelect: 'Abbrechen',
addToPlaylist: 'Zur Playlist hinzufügen',
},
login: {
subtitle: 'Dein Navidrome Desktop Player',
serverName: 'Server-Name (optional)',
serverNamePlaceholder: 'Mein Navidrome',
serverUrl: 'Server-URL',
serverUrlPlaceholder: '192.168.1.100:4533 oder music.example.com',
serverUrlPlaceholder: '192.168.1.100:4533 oder https://music.example.com',
username: 'Benutzername',
usernamePlaceholder: 'admin',
password: 'Passwort',
@@ -326,6 +339,7 @@ export const deTranslation = {
offlineTitle: 'Keine Serververbindung',
offlineSubtitle: '{{server}} ist nicht erreichbar. Prüfe Netzwerk oder Server.',
offlineModeBanner: 'Offline-Modus — Wiedergabe aus lokalem Cache',
offlineNoCacheBanner: 'Keine Serververbindung — {{server}} nicht erreichbar',
offlineLibraryTitle: 'Offline-Bibliothek',
offlineLibraryEmpty: 'Noch keine Alben gecacht. Online gehen, Album öffnen und "Offline verfügbar machen" klicken.',
offlineAlbumCount: '{{n}} Album',
@@ -335,6 +349,7 @@ export const deTranslation = {
offlineFilterPlaylists: 'Playlists',
offlineFilterArtists: 'Diskografien',
retry: 'Erneut versuchen',
serverSettings: 'Server-Einstellungen',
lastfmConnected: 'Last.fm verbunden als @{{user}}',
lastfmSessionInvalid: 'Session ungültig — klicken zum Neu-Verbinden',
},
@@ -401,6 +416,7 @@ export const deTranslation = {
servers: 'Server',
serverName: 'Server-Name',
serverUrl: 'Server-URL',
serverUrlPlaceholder: '192.168.1.100:4533 oder https://music.example.com',
serverUsername: 'Benutzername',
serverPassword: 'Passwort',
addServer: 'Server hinzufügen',
@@ -485,6 +501,13 @@ export const deTranslation = {
hotCacheDebounceImmediate: 'Sofort',
hotCacheDebounceSeconds: '{{n}} s',
hotCacheClearBtn: 'Hot-Cache leeren',
audioOutputDevice: 'Audio-Ausgabegerät',
audioOutputDeviceDesc: 'Wähle das Audiogerät, über das Psysonic spielt. Änderungen werden sofort übernommen und starten den aktuellen Track neu.',
audioOutputDeviceDefault: 'Systemstandard',
audioOutputDeviceRefresh: 'Geräteliste aktualisieren',
audioOutputDeviceOsDefaultNow: 'aktuelle Systemausgabe',
audioOutputDeviceListError: 'Audiogeräteliste konnte nicht geladen werden.',
audioOutputDeviceNotInCurrentList: 'nicht in der aktuellen Liste',
hiResTitle: 'Native Hi-Res-Wiedergabe',
hiResEnabled: 'Native Hi-Res-Wiedergabe aktivieren',
hiResDesc: "Standardmäßig wird auf 44,1 kHz begrenzt (maximale Stabilität). Nur aktivieren, wenn Hardware und Netzwerk zuverlässig hohe Abtastraten (88,2 kHz+) unterstützen.",
@@ -520,7 +543,6 @@ export const deTranslation = {
logout: 'Abmelden',
aboutTitle: 'Über Psysonic',
aboutDesc: 'Ein moderner Desktop-Musikplayer für Subsonic-kompatible Server (Navidrome, Gonic u. a.). Basiert auf Tauri v2 mit einer nativen Rust-Audio-Engine — schlank und schnell, aber vollgepackt mit Features: Wellenform-Seekbar, synchronisierte Lyrics, Last.fm-Integration, 10-Band-EQ, Crossfade, nahtlose Wiedergabe, Replay Gain, Genre-Browser und eine große Theme-Bibliothek.',
aboutFeatures: 'Multi-Server · Last.fm Scrobbling & Love · Vollbild Ambient Stage · Wellenform-Seek · Sync-Lyrics · 10-Band-EQ · Crossfade & Gapless · Replay Gain · Genres · 63 Themes · 5 Sprachen',
aboutLicense: 'Lizenz',
aboutLicenseText: 'GNU GPL v3 — kostenlos nutzbar, veränderbar und unter gleicher Lizenz weiterzugeben.',
aboutRepo: 'Quellcode auf GitHub',
@@ -640,6 +662,13 @@ export const deTranslation = {
themeSchedulerNightTheme: 'Nacht-Theme',
themeSchedulerNightStart: 'Nacht beginnt um',
themeSchedulerActiveHint: 'Theme-Zeitplan ist aktiv - Themes werden automatisch gewechselt.',
visualOptionsTitle: 'Visuelle Optionen',
coverArtBackground: 'Cover-Hintergrund',
coverArtBackgroundSub: 'Zeigt verschwommenes Cover als Hintergrund in Album/Playlist-Kopfzeilen',
playlistCoverPhoto: 'Playlist-Coverfoto',
playlistCoverPhotoSub: 'Zeigt Coverfoto-Raster in der Playlist-Detailansicht',
showBitrate: 'Bitrate anzeigen',
showBitrateSub: 'Audio-Bitrate in Track-Listen anzeigen',
uiScaleTitle: 'Interface-Skalierung',
uiScaleLabel: 'Zoom',
},
@@ -921,6 +950,33 @@ export const deTranslation = {
coverUpdated: 'Cover aktualisiert',
metaSaved: 'Playlist aktualisiert',
downloadZip: 'Herunterladen (ZIP)',
// Toast notifications for multi-select
addSuccess: '{{count}} Songs zu {{playlist}} hinzugefügt',
addPartial: '{{added}} hinzugefügt, {{skipped}} übersprungen (Duplikate)',
addAllSkipped: 'Alle übersprungen ({{count}} Duplikate)',
addError: 'Fehler beim Hinzufügen von Songs',
createAndAddSuccess: 'Playlist "{{playlist}}" mit {{count}} Songs erstellt',
createError: 'Fehler beim Erstellen der Playlist',
deleteSuccess: '{{count}} Playlists gelöscht',
deleteFailed: 'Fehler beim Löschen von {{name}}',
deleteSelected: 'Ausgewählte löschen',
mergeSuccess: '{{count}} Songs in {{playlist}} zusammengeführt',
mergeNoNewSongs: 'Keine neuen Songs zum Hinzufügen',
mergeError: 'Fehler beim Zusammenführen von Playlists',
mergeInto: 'Zusammenführen in',
selectionCount: '{{count}} ausgewählt',
select: 'Auswählen',
startSelect: 'Auswahl aktivieren',
cancelSelect: 'Abbrechen',
loadingAlbums: '{{count}} Alben werden aufgelöst…',
loadingArtists: '{{count}} Künstler werden aufgelöst…',
myPlaylists: 'Meine Playlists',
noOtherPlaylists: 'Keine anderen Playlists verfügbar',
addToPlaylistSuccess: '{{count}} Songs zu {{playlist}} hinzugefügt',
addToPlaylistNoNew: 'Keine neuen Songs für {{playlist}}',
addToPlaylistError: 'Fehler beim Hinzufügen zur Playlist',
removeSuccess: 'Song aus Playlist entfernt',
removeError: 'Fehler beim Entfernen aus der Playlist',
},
mostPlayed: {
title: 'Meistgehört',
@@ -974,4 +1030,66 @@ export const deTranslation = {
empty: 'Leerer Ordner',
error: 'Laden fehlgeschlagen',
},
deviceSync: {
title: 'Gerätesync',
targetFolder: 'Zielordner',
noFolderChosen: 'Kein Ordner gewählt',
selectDrive: 'Laufwerk auswählen…',
refreshDrives: 'Laufwerke aktualisieren',
noDrivesDetected: 'Keine Wechseldatenträger erkannt',
browseManual: 'Manuell durchsuchen…',
free: 'frei',
notMountedVolume: 'Ziel befindet sich nicht auf einem eingehängten Laufwerk. Das Gerät wurde möglicherweise getrennt.',
chooseFolder: 'Auswählen…',
filenameTemplate: 'Dateinamen-Vorlage',
targetDevice: 'Zielgerät',
templateHint: 'Variablen: {artist}, {album}, {title}, {track_number}, {disc_number}, {year}',
onDevice: 'Auf dem Gerät',
addSources: 'Hinzufügen…',
colName: 'Name',
colType: 'Typ',
syncResult: '{{done}} übertragen, {{skipped}} bereits aktuell ({{total}} gesamt)',
deleteFromDevice: 'Vom Gerät löschen ({{count}})',
confirmDelete: '{{count}} Eintrag/Einträge vom Gerät löschen: {{names}}?',
deleteComplete: '{{count}} Eintrag/Einträge vom Gerät entfernt.',
selectedSources: 'Ausgewählte Quellen',
noSourcesSelected: 'Keine Quellen ausgewählt. Klicke auf Einträge im Browser um sie hinzuzufügen.',
clearAll: 'Alle entfernen',
tabPlaylists: 'Wiedergabelisten',
tabAlbums: 'Alben',
tabArtists: 'Künstler',
searchPlaceholder: 'Suche…',
syncButton: 'Auf Gerät übertragen',
actionTransfer: 'Auf Gerät übertragen',
actionDelete: 'Vom Gerät löschen',
actionApplyAll: 'Änderungen synchronisieren',
templatePreview: 'Vorschau',
cancel: 'Abbrechen',
noTargetDir: 'Bitte zuerst einen Zielordner auswählen.',
noSources: 'Bitte mindestens eine Quelle auswählen.',
noTracks: 'Keine Tracks in den ausgewählten Quellen gefunden.',
fetchError: 'Fehler beim Laden der Tracks vom Server.',
syncComplete: 'Übertragung abgeschlossen.',
dismiss: 'Schließen',
colStatus: 'Status',
statusSynced: 'Synchronisiert',
statusPending: 'Ausstehend',
statusDeletion: 'Löschung',
markForDeletion: 'Zur Löschung markieren',
removeSource: 'Entfernen',
undoDeletion: 'Löschung rückgängig',
syncInBackground: 'Sync gestartet — du kannst die Seite verlassen.',
syncInProgress: '{{done}} / {{total}} Tracks…',
syncSummary: 'Sync-Zusammenfassung',
calculating: 'Payload wird berechnet…',
filesToAdd: 'Hinzuzufügende Dateien:',
filesToDelete: 'Zu löschende Dateien:',
netChange: 'Nettoänderung:',
availableSpace: 'Verfügbarer Speicher:',
spaceWarning: 'Warnung: Das Zielgerät hat nicht genug gemeldeten Speicherplatz.',
proceed: 'Sync durchführen',
notEnoughSpace: 'Nicht genug physischer Speicherplatz erkannt!',
liveSearch: 'Live',
randomAlbumsLabel: 'Zufallsalben',
},
};
+121 -2
View File
@@ -18,6 +18,7 @@ export const enTranslation = {
collapse: 'Collapse Sidebar',
downloadingTracks: 'Caching {{n}} tracks…',
syncingTracks: 'Syncing {{done}}/{{total}}…',
cancelDownload: 'Cancel download',
offlineLibrary: 'Offline Library',
genres: 'Genres',
@@ -25,8 +26,11 @@ export const enTranslation = {
mostPlayed: 'Most Played',
radio: 'Internet Radio',
folderBrowser: 'Folder Browser',
deviceSync: 'Device Sync',
libraryScope: 'Library scope',
allLibraries: 'All libraries',
expandPlaylists: 'Expand playlists',
collapsePlaylists: 'Collapse playlists',
},
home: {
hero: 'Featured',
@@ -107,10 +111,14 @@ export const enTranslation = {
unfavoriteArtist: 'Remove Artist from Favorites',
unfavoriteAlbum: 'Remove Album from Favorites',
removeFromQueue: 'Remove from Queue',
removeFromPlaylist: 'Remove from Playlist',
openAlbum: 'Open Album',
goToArtist: 'Go to Artist',
download: 'Download (ZIP)',
addToPlaylist: 'Add to Playlist',
selectedPlaylists: '{{count}} playlists selected',
selectedAlbums: '{{count}} albums selected',
selectedArtists: '{{count}} artists selected',
songInfo: 'Song Info',
},
albumDetail: {
@@ -297,13 +305,18 @@ export const enTranslation = {
notFound: 'No artists found.',
albumCount_one: '{{count}} Album',
albumCount_other: '{{count}} Albums',
selectionCount: '{{count}} selected',
select: 'Multi-select',
startSelect: 'Enable multi-select',
cancelSelect: 'Cancel',
addToPlaylist: 'Add to Playlist',
},
login: {
subtitle: 'Your Navidrome Desktop Player',
serverName: 'Server Name (optional)',
serverNamePlaceholder: 'My Navidrome',
serverUrl: 'Server URL',
serverUrlPlaceholder: '192.168.1.100:4533 or music.example.com',
serverUrlPlaceholder: '192.168.1.100:4533 or https://music.example.com',
username: 'Username',
usernamePlaceholder: 'admin',
password: 'Password',
@@ -327,6 +340,7 @@ export const enTranslation = {
offlineTitle: 'No server connection',
offlineSubtitle: 'Cannot reach {{server}}. Check your network or server.',
offlineModeBanner: 'Offline Mode — playing from local cache',
offlineNoCacheBanner: 'No server connection — cannot reach {{server}}',
offlineLibraryTitle: 'Offline Library',
offlineLibraryEmpty: 'No albums cached yet. Go online, open an album and click "Make available offline".',
offlineAlbumCount: '{{n}} album',
@@ -336,6 +350,7 @@ export const enTranslation = {
offlineFilterPlaylists: 'Playlists',
offlineFilterArtists: 'Discographies',
retry: 'Retry',
serverSettings: 'Server Settings',
lastfmConnected: 'Last.fm connected as @{{user}}',
lastfmSessionInvalid: 'Session invalid — click to re-connect',
},
@@ -403,6 +418,7 @@ export const enTranslation = {
servers: 'Servers',
serverName: 'Server Name',
serverUrl: 'Server URL',
serverUrlPlaceholder: '192.168.1.100:4533 or https://music.example.com',
serverUsername: 'Username',
serverPassword: 'Password',
addServer: 'Add Server',
@@ -487,6 +503,13 @@ export const enTranslation = {
hotCacheDebounceImmediate: 'Immediate',
hotCacheDebounceSeconds: '{{n}} s',
hotCacheClearBtn: 'Clear hot cache',
audioOutputDevice: 'Audio Output Device',
audioOutputDeviceDesc: 'Select which audio device Psysonic plays through. Changes take effect immediately and restart the current track.',
audioOutputDeviceDefault: 'System Default',
audioOutputDeviceRefresh: 'Refresh device list',
audioOutputDeviceOsDefaultNow: 'current system output',
audioOutputDeviceListError: 'Could not load the audio device list.',
audioOutputDeviceNotInCurrentList: 'not in current list',
hiResTitle: 'Native Hi-Res Playback',
hiResEnabled: 'Enable native hi-res playback',
hiResDesc: "Forces 44.1 kHz output by default for maximum stability. Enable only if your hardware and network reliably support high sample rates (88.2 kHz+).",
@@ -522,7 +545,6 @@ export const enTranslation = {
logout: 'Logout',
aboutTitle: 'About Psysonic',
aboutDesc: 'A modern desktop music player for Subsonic-compatible servers (Navidrome, Gonic, and others). Built on Tauri v2 with a native Rust audio engine — lightweight and fast, yet packed with features: waveform seekbar, synchronized lyrics, Last.fm integration, 10-band EQ, crossfade, gapless playback, Replay Gain, genre browsing, and a large library of themes.',
aboutFeatures: 'Multi-server · Last.fm scrobbling & love · Fullscreen Ambient Stage · Waveform seek · Synced lyrics · 10-band EQ · Crossfade & Gapless · Replay Gain · Genres · 63 themes · 8 languages',
aboutLicense: 'License',
aboutLicenseText: 'GNU GPL v3 — free to use, modify, and distribute under the same license.',
aboutRepo: 'Source Code on GitHub',
@@ -642,6 +664,13 @@ export const enTranslation = {
themeSchedulerNightTheme: 'Night Theme',
themeSchedulerNightStart: 'Night Starts At',
themeSchedulerActiveHint: 'Theme Scheduler is active - theme changes are managed automatically.',
visualOptionsTitle: 'Visual Options',
coverArtBackground: 'Cover Art Background',
coverArtBackgroundSub: 'Show blurred cover art as background in album/playlist headers',
playlistCoverPhoto: 'Playlist Cover Photo',
playlistCoverPhotoSub: 'Show cover photo grid in playlist detail view',
showBitrate: 'Show Bitrate',
showBitrateSub: 'Display audio bitrate in track listings',
uiScaleTitle: 'Interface Scale',
uiScaleLabel: 'Zoom',
},
@@ -923,6 +952,33 @@ export const enTranslation = {
coverUpdated: 'Cover updated',
metaSaved: 'Playlist updated',
downloadZip: 'Download (ZIP)',
// Toast notifications for multi-select
addSuccess: '{{count}} songs added to {{playlist}}',
addPartial: '{{added}} added, {{skipped}} skipped (duplicates)',
addAllSkipped: 'All skipped ({{count}} duplicates)',
addError: 'Error adding songs',
createAndAddSuccess: 'Playlist "{{playlist}}" created with {{count}} songs',
createError: 'Error creating playlist',
deleteSuccess: '{{count}} playlists deleted',
deleteFailed: 'Error deleting {{name}}',
deleteSelected: 'Delete selected',
mergeSuccess: '{{count}} songs merged into {{playlist}}',
mergeNoNewSongs: 'No new songs to add',
mergeError: 'Error merging playlists',
mergeInto: 'Merge into',
selectionCount: '{{count}} selected',
select: 'Select',
startSelect: 'Enable selection',
cancelSelect: 'Cancel',
loadingAlbums: 'Resolving {{count}} albums…',
loadingArtists: 'Resolving {{count}} artists…',
myPlaylists: 'My Playlists',
noOtherPlaylists: 'No other playlists available',
addToPlaylistSuccess: '{{count}} songs added to {{playlist}}',
addToPlaylistNoNew: 'No new songs to add to {{playlist}}',
addToPlaylistError: 'Error adding to playlist',
removeSuccess: 'Song removed from playlist',
removeError: 'Error removing song from playlist',
},
mostPlayed: {
title: 'Most Played',
@@ -976,4 +1032,67 @@ export const enTranslation = {
empty: 'Empty folder',
error: 'Failed to load',
},
deviceSync: {
title: 'Device Sync',
targetFolder: 'Target Folder',
noFolderChosen: 'No folder chosen',
selectDrive: 'Select a drive…',
refreshDrives: 'Refresh drives',
noDrivesDetected: 'No removable drives detected',
browseManual: 'Browse manually…',
free: 'free',
notMountedVolume: 'Target is not on a mounted volume. The drive may have been disconnected.',
chooseFolder: 'Choose…',
filenameTemplate: 'Filename Template',
targetDevice: 'Target Device',
templateHint: 'Variables: {artist}, {album}, {title}, {track_number}, {disc_number}, {year}',
onDevice: 'Device Manager',
addSources: 'Add…',
colName: 'Name',
colType: 'Type',
colStatus: 'Status',
syncResult: '{{done}} transferred, {{skipped}} already up to date ({{total}} total)',
deleteFromDevice: 'Mark for deletion ({{count}})',
confirmDelete: 'Delete {{count}} item(s) from the device: {{names}}?',
deleteComplete: '{{count}} item(s) removed from device.',
selectedSources: 'Selected Sources',
noSourcesSelected: 'No sources selected. Click items in the browser to add them.',
clearAll: 'Clear all',
tabPlaylists: 'Playlists',
tabAlbums: 'Albums',
tabArtists: 'Artists',
searchPlaceholder: 'Search…',
syncButton: 'Sync to Device',
actionTransfer: 'Transfer to Device',
actionDelete: 'Delete from Device',
actionApplyAll: 'Apply All Changes',
templatePreview: 'Preview',
cancel: 'Cancel',
noTargetDir: 'Please choose a target folder first.',
noSources: 'Please select at least one source.',
noTracks: 'No tracks found in the selected sources.',
fetchError: 'Failed to fetch tracks from server.',
syncComplete: 'Sync complete.',
dismiss: 'Dismiss',
statusSynced: 'Synced',
statusPending: 'Pending',
statusDeletion: 'Deletion',
markForDeletion: 'Mark for deletion',
undoDeletion: 'Undo deletion',
removeSource: 'Remove',
syncInBackground: 'Sync started in background — you can navigate away.',
syncInProgress: '{{done}} / {{total}} tracks…',
scanningDevice: 'Scanning device…',
syncSummary: 'Sync Summary',
calculating: 'Calculating required payload…',
filesToAdd: 'Files to Add:',
filesToDelete: 'Files to Delete:',
netChange: 'Net Change:',
availableSpace: 'Available Disk Space:',
spaceWarning: 'Warning: Target device does not have enough reported space.',
proceed: 'Proceed with Sync',
notEnoughSpace: 'Not enough physical disk space detected!',
liveSearch: 'Live',
randomAlbumsLabel: 'Random Albums',
},
};
+138 -2
View File
@@ -7,6 +7,7 @@ export const esTranslation = {
randomAlbums: 'Álbumes Aleatorios',
artists: 'Artistas',
randomMix: 'Mezcla Aleatoria',
randomPicker: 'Crear Mezcla',
favorites: 'Favoritos',
nowPlaying: 'Reproduciendo Ahora',
system: 'Sistema',
@@ -17,6 +18,7 @@ export const esTranslation = {
collapse: 'Colapsar Barra Lateral',
downloadingTracks: 'Descargando {{n}} pistas…',
syncingTracks: 'Sincronizando {{done}}/{{total}}…',
cancelDownload: 'Cancelar descarga',
offlineLibrary: 'Biblioteca Offline',
genres: 'Géneros',
@@ -24,8 +26,11 @@ export const esTranslation = {
mostPlayed: 'Más Reproducidos',
radio: 'Radio por Internet',
folderBrowser: 'Explorar Carpetas',
deviceSync: 'Sincronizar dispositivo',
libraryScope: 'Ámbito de biblioteca',
allLibraries: 'Todas las bibliotecas',
expandPlaylists: 'Expandir listas',
collapsePlaylists: 'Colapsar listas',
},
home: {
hero: 'Destacado',
@@ -106,10 +111,14 @@ export const esTranslation = {
unfavoriteArtist: 'Quitar Artista de Favoritos',
unfavoriteAlbum: 'Quitar Álbum de Favoritos',
removeFromQueue: 'Quitar de la Cola',
removeFromPlaylist: 'Quitar de la Playlist',
openAlbum: 'Abrir Álbum',
goToArtist: 'Ir al Artista',
download: 'Descargar (ZIP)',
addToPlaylist: 'Agregar a Lista de Reproducción',
selectedPlaylists: '{{count}} listas seleccionadas',
selectedAlbums: '{{count}} álbumes seleccionados',
selectedArtists: '{{count}} artistas seleccionados',
songInfo: 'Información de la Canción',
},
albumDetail: {
@@ -204,6 +213,13 @@ export const esTranslation = {
removeSong: 'Quitar de favoritos',
stations: 'Estaciones de Radio',
},
randomLanding: {
title: 'Crear Mezcla',
mixByTracks: 'Mezcla por Canciones',
mixByTracksDesc: 'Selección aleatoria de canciones de toda tu biblioteca',
mixByAlbums: 'Mezcla por Álbumes',
mixByAlbumsDesc: 'Álbumes aleatorios para tu próximo descubrimiento',
},
randomAlbums: {
title: 'Álbumes Aleatorios',
refresh: 'Refrescar',
@@ -276,6 +292,7 @@ export const esTranslation = {
downloadZipFailed: 'Error al descargar {{name}}',
offlineQueuing: 'Encolando {{count}} álbum(es) para offline…',
offlineFailed: 'Error al agregar {{name}} offline',
addToPlaylist: 'Agregar a Lista de Reproducción',
},
artists: {
title: 'Artistas',
@@ -289,13 +306,18 @@ export const esTranslation = {
notFound: 'No se encontraron artistas.',
albumCount_one: '{{count}} Álbum',
albumCount_other: '{{count}} Álbumes',
selectionCount: '{{count}} seleccionados',
select: 'Selección múltiple',
startSelect: 'Activar selección múltiple',
cancelSelect: 'Cancelar',
addToPlaylist: 'Agregar a Lista',
},
login: {
subtitle: 'Tu Reproductor Navidrome para Escritorio',
serverName: 'Nombre del Servidor (opcional)',
serverNamePlaceholder: 'Mi Navidrome',
serverUrl: 'URL del Servidor',
serverUrlPlaceholder: '192.168.1.100:4533 o music.example.com',
serverUrlPlaceholder: '192.168.1.100:4533 o https://music.example.com',
username: 'Usuario',
usernamePlaceholder: 'admin',
password: 'Contraseña',
@@ -319,6 +341,7 @@ export const esTranslation = {
offlineTitle: 'Sin conexión al servidor',
offlineSubtitle: 'No se puede alcanzar {{server}}. Verifica tu red o servidor.',
offlineModeBanner: 'Modo Offline — reproduciendo desde caché local',
offlineNoCacheBanner: 'Sin conexión al servidor — no se puede acceder a {{server}}',
offlineLibraryTitle: 'Biblioteca Offline',
offlineLibraryEmpty: 'No hay álbumes en caché aún. Conéctate, abre un álbum y click en "Disponible offline".',
offlineAlbumCount: '{{n}} álbum',
@@ -328,6 +351,7 @@ export const esTranslation = {
offlineFilterPlaylists: 'Listas',
offlineFilterArtists: 'Discografías',
retry: 'Reintentar',
serverSettings: 'Configuración del servidor',
lastfmConnected: 'Last.fm conectado como @{{user}}',
lastfmSessionInvalid: 'Sesión inválida — click para reconectar',
},
@@ -395,6 +419,7 @@ export const esTranslation = {
servers: 'Servidores',
serverName: 'Nombre del Servidor',
serverUrl: 'URL del Servidor',
serverUrlPlaceholder: '192.168.1.100:4533 o https://music.example.com',
serverUsername: 'Usuario',
serverPassword: 'Contraseña',
addServer: 'Agregar Servidor',
@@ -479,6 +504,13 @@ export const esTranslation = {
hotCacheDebounceImmediate: 'Inmediato',
hotCacheDebounceSeconds: '{{n}} s',
hotCacheClearBtn: 'Limpiar caché activa',
audioOutputDevice: 'Dispositivo de salida de audio',
audioOutputDeviceDesc: 'Selecciona el dispositivo de audio que usa Psysonic. Los cambios surten efecto de inmediato y reinician la pista actual.',
audioOutputDeviceDefault: 'Predeterminado del sistema',
audioOutputDeviceRefresh: 'Actualizar lista de dispositivos',
audioOutputDeviceOsDefaultNow: 'salida actual del sistema',
audioOutputDeviceListError: 'No se pudo cargar la lista de dispositivos de audio.',
audioOutputDeviceNotInCurrentList: 'no está en la lista actual',
hiResTitle: 'Reproducción Nativa Hi-Res',
hiResEnabled: 'Habilitar reproducción nativa hi-res',
hiResDesc: "Fuerza 44.1 kHz de salida por defecto para máxima estabilidad. Habilita solo si tu hardware y red soportan confiablemente altas tasas de muestreo (88.2 kHz+).",
@@ -514,7 +546,6 @@ export const esTranslation = {
logout: 'Cerrar Sesión',
aboutTitle: 'Acerca de Psysonic',
aboutDesc: 'Un reproductor de música moderno para escritorio compatible con servidores Subsonic (Navidrome, Gonic y otros). Construido en Tauri v2 con motor de audio nativo en Rust — ligero y rápido, pero lleno de características: barra de progreso tipo onda, letras sincronizadas, integración Last.fm, ecualizador de 10 bandas, crossfade, reproducción gapless, Replay Gain, navegación por géneros, y una gran biblioteca de temas.',
aboutFeatures: 'Multi-servidor · Scrobbling Last.fm y favoritos · Escenario Ambiente Pantalla Completa · Barra de progreso onda · Letras sincronizadas · Ecualizador 10 bandas · Crossfade y Gapless · Replay Gain · Géneros · 63 temas · 8 idiomas',
aboutLicense: 'Licencia',
aboutLicenseText: 'GNU GPL v3 — libre para usar, modificar y distribuir bajo la misma licencia.',
aboutRepo: 'Código Fuente en GitHub',
@@ -580,6 +611,7 @@ export const esTranslation = {
shortcutSeekForward: 'Avanzar 10s',
shortcutSeekBackward: 'Retroceder 10s',
shortcutToggleQueue: 'Alternar cola',
shortcutOpenFolderBrowser: 'Abrir {{folderBrowser}}',
shortcutFullscreenPlayer: 'Reproductor pantalla completa',
shortcutNativeFullscreen: 'Pantalla completa nativa',
playbackTitle: 'Reproducción',
@@ -609,6 +641,10 @@ export const esTranslation = {
infiniteQueue: 'Cola Infinita',
infiniteQueueDesc: 'Agregar automáticamente pistas aleatorias cuando la cola termina',
experimental: 'Experimental',
fsPlayerSection: 'Reproductor Pantalla Completa',
fsShowArtistPortrait: 'Mostrar foto del artista',
fsShowArtistPortraitDesc: 'Muestra la foto del artista (o portada del álbum) en el lado derecho del reproductor pantalla completa.',
fsPortraitDim: 'Oscurecimiento de foto',
seekbarStyle: 'Estilo de Barra de Progreso',
seekbarStyleDesc: 'Elige la apariencia de la barra de progreso del reproductor',
seekbarWaveform: 'Forma de Onda',
@@ -629,6 +665,13 @@ export const esTranslation = {
themeSchedulerNightTheme: 'Tema de Noche',
themeSchedulerNightStart: 'Comienza de Noche A las',
themeSchedulerActiveHint: 'El Programador de Temas está activo — los cambios de tema se manejan automáticamente.',
visualOptionsTitle: 'Opciones Visuales',
coverArtBackground: 'Fondo de Portada',
coverArtBackgroundSub: 'Mostrar portada desenfocada como fondo en encabezados de álbumes y listas de reproducción',
playlistCoverPhoto: 'Foto de Portada de Playlist',
playlistCoverPhotoSub: 'Mostrar cuadrícula de fotos de portada en la vista detallada de playlists',
showBitrate: 'Mostrar Bitrate',
showBitrateSub: 'Mostrar bitrate de audio en las listas de pistas',
uiScaleTitle: 'Escala de Interfaz',
uiScaleLabel: 'Zoom',
},
@@ -910,6 +953,33 @@ export const esTranslation = {
coverUpdated: 'Portada actualizada',
metaSaved: 'Lista actualizada',
downloadZip: 'Descargar (ZIP)',
// Toast notifications for multi-select
addSuccess: '{{count}} canciones agregadas a {{playlist}}',
addPartial: '{{added}} agregadas, {{skipped}} skippeadas por duplicadas',
addAllSkipped: 'Todas skippeadas ({{count}} duplicadas)',
addError: 'Error al agregar canciones',
createAndAddSuccess: 'Lista "{{playlist}}" creada con {{count}} canciones',
createError: 'Error al crear lista',
deleteSuccess: '{{count}} listas eliminadas',
deleteFailed: 'Error al eliminar {{name}}',
deleteSelected: 'Eliminar seleccionadas',
mergeSuccess: '{{count}} canciones unificadas en {{playlist}}',
mergeNoNewSongs: 'No hay canciones nuevas para agregar',
mergeError: 'Error al unificar listas',
mergeInto: 'Unificar en',
selectionCount: '{{count}} seleccionadas',
select: 'Seleccionar',
startSelect: 'Activar selección',
cancelSelect: 'Cancelar',
loadingAlbums: 'Resolviendo {{count}} álbumes…',
loadingArtists: 'Resolviendo {{count}} artistas…',
myPlaylists: 'Mis Listas',
noOtherPlaylists: 'No hay otras listas disponibles',
addToPlaylistSuccess: '{{count}} canciones agregadas a {{playlist}}',
addToPlaylistNoNew: 'No hay canciones nuevas para agregar a {{playlist}}',
addToPlaylistError: 'Error al agregar a la lista',
removeSuccess: 'Canción quitada de la playlist',
removeError: 'Error al quitar la canción de la playlist',
},
mostPlayed: {
title: 'Más Reproducidos',
@@ -963,4 +1033,70 @@ export const esTranslation = {
empty: 'Carpeta vacía',
error: 'Error al cargar',
},
deviceSync: {
title: 'Sincronizar dispositivo',
targetFolder: 'Carpeta de destino',
noFolderChosen: 'Ninguna carpeta seleccionada',
selectDrive: 'Seleccionar unidad…',
refreshDrives: 'Actualizar unidades',
noDrivesDetected: 'No se detectaron unidades extraíbles',
browseManual: 'Explorar manualmente…',
free: 'libre',
notMountedVolume: 'El destino no está en un volumen montado. La unidad puede haberse desconectado.',
chooseFolder: 'Elegir…',
filenameTemplate: 'Plantilla de nombre de archivo',
targetDevice: 'Dispositivo de destino',
templateHint: 'Variables: {artist}, {album}, {title}, {track_number}, {disc_number}, {year}',
cleanupButton: 'Eliminar archivos fuera de la selección',
cleanupNothingToDelete: 'Nada que eliminar — el dispositivo ya está sincronizado.',
confirmCleanup: '¿Eliminar {{count}} archivo(s) del dispositivo que no están en la selección actual? ¿Continuar?',
cleanupComplete: '{{count}} archivo(s) eliminado(s) del dispositivo.',
selectedSources: 'Fuentes seleccionadas',
noSourcesSelected: 'No hay fuentes seleccionadas. Haz clic en elementos del navegador para agregarlos.',
clearAll: 'Limpiar todo',
tabPlaylists: 'Listas de reproducción',
tabAlbums: 'Álbumes',
tabArtists: 'Artistas',
searchPlaceholder: 'Buscar…',
syncButton: 'Sincronizar al dispositivo',
actionTransfer: 'Transferir al dispositivo',
actionDelete: 'Eliminar del dispositivo',
actionApplyAll: 'Aplicar todos los cambios',
templatePreview: 'Vista previa',
cancel: 'Cancelar',
noTargetDir: 'Por favor, elige primero una carpeta de destino.',
noSources: 'Por favor, selecciona al menos una fuente.',
noTracks: 'No se encontraron pistas en las fuentes seleccionadas.',
fetchError: 'Error al obtener pistas del servidor.',
syncComplete: 'Sincronización completada.',
dismiss: 'Cerrar',
colName: 'Nombre',
colType: 'Tipo',
colStatus: 'Estado',
onDevice: 'Gestor de dispositivo',
addSources: 'Agregar…',
syncResult: '{{done}} transferido(s), {{skipped}} ya actualizado(s) ({{total}} total)',
deleteFromDevice: 'Marcar para eliminar ({{count}})',
confirmDelete: '¿Eliminar {{count}} elemento(s) del dispositivo: {{names}}?',
deleteComplete: '{{count}} elemento(s) eliminado(s) del dispositivo.',
statusSynced: 'Sincronizado',
statusPending: 'Pendiente',
statusDeletion: 'Eliminación',
markForDeletion: 'Marcar para eliminar',
removeSource: 'Eliminar',
undoDeletion: 'Deshacer eliminación',
syncInBackground: 'Sincronización iniciada en segundo plano — puedes navegar a otro lugar.',
syncInProgress: '{{done}} / {{total}} pistas…',
syncSummary: 'Resumen de sincronización',
calculating: 'Calculando la carga útil requerida…',
filesToAdd: 'Archivos a agregar:',
filesToDelete: 'Archivos a eliminar:',
netChange: 'Cambio neto:',
availableSpace: 'Espacio disponible en disco:',
spaceWarning: 'Advertencia: El dispositivo de destino no tiene suficiente espacio reportado.',
proceed: 'Proceder con la sincronización',
notEnoughSpace: '¡Espacio físico en disco insuficiente detectado!',
liveSearch: 'Live',
randomAlbumsLabel: 'Álbumes aleatorios',
},
};
+138 -13
View File
@@ -17,6 +17,7 @@ export const frTranslation = {
expand: 'Développer la barre latérale',
collapse: 'Réduire la barre latérale',
downloadingTracks: '{{n}} pistes en cache…',
syncingTracks: 'Synchro {{done}}/{{total}}…',
cancelDownload: 'Annuler le téléchargement',
offlineLibrary: 'Bibliothèque hors ligne',
genres: 'Genres',
@@ -24,8 +25,11 @@ export const frTranslation = {
mostPlayed: 'Les plus joués',
radio: 'Radio Internet',
folderBrowser: 'Explorateur de dossiers',
deviceSync: 'Sync appareil',
libraryScope: 'Portée de la bibliothèque',
allLibraries: 'Toutes les bibliothèques',
expandPlaylists: 'Développer les playlists',
collapsePlaylists: 'Réduire les playlists',
},
home: {
hero: 'En vedette',
@@ -106,10 +110,14 @@ export const frTranslation = {
unfavoriteArtist: 'Retirer l\'artiste des favoris',
unfavoriteAlbum: 'Retirer l\'album des favoris',
removeFromQueue: 'Retirer de la file',
removeFromPlaylist: 'Retirer de la playlist',
openAlbum: 'Ouvrir l\'album',
goToArtist: 'Aller à l\'artiste',
download: 'Télécharger (ZIP)',
addToPlaylist: 'Ajouter à la playlist',
selectedPlaylists: '{{count}} playlists sélectionnées',
selectedAlbums: '{{count}} albums sélectionnés',
selectedArtists: '{{count}} artistes sélectionnés',
songInfo: 'Infos du morceau',
},
albumDetail: {
@@ -272,17 +280,17 @@ export const frTranslation = {
yearTo: 'À',
yearFilterClear: 'Effacer le filtre année',
yearFilterLabel: 'Année',
select: 'Multi-select',
startSelect: 'Enable multi-select',
cancelSelect: 'Cancel',
selectionCount: '{{count}} selected',
downloadZips: 'Download ZIPs',
addOffline: 'Add Offline',
downloadingZip: 'Downloading {{current}}/{{total}}: {{name}}',
downloadZipDone: '{{count}} ZIP(s) downloaded',
downloadZipFailed: 'Failed to download {{name}}',
offlineQueuing: 'Queuing {{count}} album(s) for offline…',
offlineFailed: 'Failed to add {{name}} offline',
select: 'Sélection multiple',
startSelect: 'Activer la sélection multiple',
cancelSelect: 'Annuler',
selectionCount: '{{count}} sélectionnés',
downloadZips: 'Télécharger les ZIPs',
addOffline: 'Ajouter hors ligne',
downloadingZip: 'Téléchargement {{current}}/{{total}} : {{name}}',
downloadZipDone: '{{count}} ZIP(s) téléchargé(s)',
downloadZipFailed: 'Échec du téléchargement de {{name}}',
offlineQueuing: 'Mise en file d\'attente de {{count}} album(s) hors ligne…',
offlineFailed: 'Échec de l\'ajout de {{name}} hors ligne',
},
artists: {
title: 'Artistes',
@@ -296,13 +304,18 @@ export const frTranslation = {
notFound: 'Aucun artiste trouvé.',
albumCount_one: '{{count}} album',
albumCount_other: '{{count}} albums',
selectionCount: '{{count}} sélectionnés',
select: 'Sélection multiple',
startSelect: 'Activer la sélection multiple',
cancelSelect: 'Annuler',
addToPlaylist: 'Ajouter à la playlist',
},
login: {
subtitle: 'Votre lecteur de bureau Navidrome',
serverName: 'Nom du serveur (facultatif)',
serverNamePlaceholder: 'Mon Navidrome',
serverUrl: 'URL du serveur',
serverUrlPlaceholder: '192.168.1.100:4533 ou music.exemple.com',
serverUrlPlaceholder: '192.168.1.100:4533 ou https://music.exemple.com',
username: 'Nom d\'utilisateur',
usernamePlaceholder: 'admin',
password: 'Mot de passe',
@@ -326,6 +339,7 @@ export const frTranslation = {
offlineTitle: 'Pas de connexion au serveur',
offlineSubtitle: 'Impossible d\'atteindre {{server}}. Vérifiez votre réseau ou le serveur.',
offlineModeBanner: 'Mode hors ligne — lecture depuis le cache local',
offlineNoCacheBanner: 'Pas de connexion au serveur — {{server}} inaccessible',
offlineLibraryTitle: 'Bibliothèque hors ligne',
offlineLibraryEmpty: 'Aucun album en cache. Connectez-vous, ouvrez un album et cliquez sur "Rendre disponible hors ligne".',
offlineAlbumCount: '{{n}} album',
@@ -335,6 +349,7 @@ export const frTranslation = {
offlineFilterPlaylists: 'Playlists',
offlineFilterArtists: 'Discographies',
retry: 'Réessayer',
serverSettings: 'Paramètres serveur',
lastfmConnected: 'Last.fm connecté en tant que @{{user}}',
lastfmSessionInvalid: 'Session invalide — cliquez pour vous reconnecter',
},
@@ -401,6 +416,7 @@ export const frTranslation = {
servers: 'Serveurs',
serverName: 'Nom du serveur',
serverUrl: 'URL du serveur',
serverUrlPlaceholder: '192.168.1.100:4533 ou https://music.exemple.com',
serverUsername: 'Nom d\'utilisateur',
serverPassword: 'Mot de passe',
addServer: 'Ajouter un serveur',
@@ -485,6 +501,13 @@ export const frTranslation = {
hotCacheDebounceImmediate: 'Immédiat',
hotCacheDebounceSeconds: '{{n}} s',
hotCacheClearBtn: 'Vider le cache à chaud',
audioOutputDevice: 'Périphérique de sortie audio',
audioOutputDeviceDesc: 'Choisissez le périphérique audio utilisé par Psysonic. Les changements sont immédiats et relancent la piste en cours.',
audioOutputDeviceDefault: 'Défaut système',
audioOutputDeviceRefresh: 'Actualiser la liste',
audioOutputDeviceOsDefaultNow: 'sortie système actuelle',
audioOutputDeviceListError: 'Impossible de charger la liste des périphériques audio.',
audioOutputDeviceNotInCurrentList: 'absent de la liste actuelle',
hiResTitle: 'Lecture haute résolution native',
hiResEnabled: 'Activer la lecture haute résolution native',
hiResDesc: "Force une sortie à 44,1 kHz par défaut pour une stabilité maximale. N'activer que si le matériel et le réseau prennent en charge les hautes fréquences d'échantillonnage (88,2 kHz+).",
@@ -518,7 +541,6 @@ export const frTranslation = {
logout: 'Se déconnecter',
aboutTitle: 'À propos de Psysonic',
aboutDesc: 'Un lecteur de musique de bureau moderne pour les serveurs compatibles Subsonic (Navidrome, Gonic, et autres). Construit sur Tauri v2 avec un moteur audio Rust natif — léger et rapide, mais riche en fonctionnalités : barre waveform, paroles synchronisées, intégration Last.fm, égaliseur 10 bandes, crossfade, lecture sans blanc, Replay Gain, navigation par genre et une grande bibliothèque de thèmes.',
aboutFeatures: 'Multi-serveur · Scrobbling & love Last.fm · Ambient Stage plein écran · Waveform seek · Paroles synchro · EQ 10 bandes · Crossfade & Gapless · Replay Gain · Genres · 63 thèmes · 5 langues',
aboutLicense: 'Licence',
aboutLicenseText: 'GNU GPL v3 — libre d\'utilisation, de modification et de distribution sous la même licence.',
aboutRepo: 'Code source sur GitHub',
@@ -638,6 +660,13 @@ export const frTranslation = {
themeSchedulerNightTheme: 'Thème de nuit',
themeSchedulerNightStart: 'Début de la nuit',
themeSchedulerActiveHint: 'Le planificateur de thème est actif - les thèmes changent automatiquement.',
visualOptionsTitle: 'Options Visuelles',
coverArtBackground: "Fond d'Art de Poche",
coverArtBackgroundSub: "Afficher la pochette floutée comme fond dans les en-têtes d'albums et de playlists",
playlistCoverPhoto: 'Photo de Couverture de Playlist',
playlistCoverPhotoSub: 'Afficher la grille de photos de couverture dans la vue détaillée des playlists',
showBitrate: 'Afficher le Débit',
showBitrateSub: 'Afficher le débit audio dans les listes de pistes',
uiScaleTitle: "Mise à l'échelle de l'interface",
uiScaleLabel: 'Zoom',
},
@@ -919,6 +948,33 @@ export const frTranslation = {
coverUpdated: 'Pochette mise à jour',
metaSaved: 'Playlist mise à jour',
downloadZip: 'Télécharger (ZIP)',
// Toast notifications for multi-select
addSuccess: '{{count}} morceaux ajoutés à {{playlist}}',
addPartial: '{{added}} ajoutés, {{skipped}} ignorés (doublons)',
addAllSkipped: 'Tous ignorés ({{count}} doublons)',
addError: 'Erreur lors de l\'ajout des morceaux',
createAndAddSuccess: 'Playlist "{{playlist}}" créée avec {{count}} morceaux',
createError: 'Erreur lors de la création de la playlist',
deleteSuccess: '{{count}} playlists supprimées',
deleteFailed: 'Erreur lors de la suppression de {{name}}',
deleteSelected: 'Supprimer la sélection',
mergeSuccess: '{{count}} morceaux fusionnés dans {{playlist}}',
mergeNoNewSongs: 'Aucun nouveau morceau à ajouter',
mergeError: 'Erreur lors de la fusion des playlists',
mergeInto: 'Fusionner dans',
selectionCount: '{{count}} sélectionnés',
select: 'Sélectionner',
startSelect: 'Activer la sélection',
cancelSelect: 'Annuler',
loadingAlbums: 'Résolution de {{count}} albums…',
loadingArtists: 'Résolution de {{count}} artistes…',
myPlaylists: 'Mes Playlists',
noOtherPlaylists: 'Aucune autre playlist disponible',
addToPlaylistSuccess: '{{count}} morceaux ajoutés à {{playlist}}',
addToPlaylistNoNew: 'Aucun nouveau morceau pour {{playlist}}',
addToPlaylistError: 'Erreur lors de l\'ajout à la playlist',
removeSuccess: 'Morceau retiré de la playlist',
removeError: 'Erreur lors du retrait de la playlist',
},
mostPlayed: {
title: 'Les plus joués',
@@ -929,6 +985,9 @@ export const frTranslation = {
sortLeast: 'Moins joués en premier',
loadMore: 'Charger plus d\'albums',
noData: 'Aucune donnée d\'écoute. Commencez à écouter !',
noArtists: 'Tous les artistes filtrés.',
filterCompilations: 'Masquer les artistes de compilations (Various Artists, Soundtracks, etc.)',
filterCompilationsShort: 'Masquer les compilations',
},
radio: {
title: 'Radio Internet',
@@ -969,4 +1028,70 @@ export const frTranslation = {
empty: 'Dossier vide',
error: 'Échec du chargement',
},
deviceSync: {
title: 'Sync appareil',
targetFolder: 'Dossier cible',
noFolderChosen: 'Aucun dossier sélectionné',
selectDrive: 'Sélectionner un lecteur…',
refreshDrives: 'Actualiser les lecteurs',
noDrivesDetected: 'Aucun lecteur amovible détecté',
browseManual: 'Parcourir manuellement…',
free: 'libre',
notMountedVolume: 'La cible n\u0027est pas sur un volume monté. Le lecteur a peut-être été déconnecté.',
chooseFolder: 'Choisir…',
filenameTemplate: 'Modèle de nom de fichier',
targetDevice: 'Appareil cible',
templateHint: 'Variables : {artist}, {album}, {title}, {track_number}, {disc_number}, {year}',
cleanupButton: 'Supprimer les fichiers absents',
cleanupNothingToDelete: 'Rien à supprimer — l\'appareil est déjà synchronisé.',
confirmCleanup: 'Supprimer {{count}} fichier(s) de l\'appareil qui ne font pas partie de la sélection actuelle. Continuer ?',
cleanupComplete: '{{count}} fichier(s) supprimé(s) de l\'appareil.',
selectedSources: 'Sources sélectionnées',
noSourcesSelected: 'Aucune source sélectionnée. Cliquez sur des éléments dans le navigateur pour les ajouter.',
clearAll: 'Tout effacer',
tabPlaylists: 'Listes de lecture',
tabAlbums: 'Albums',
tabArtists: 'Artistes',
searchPlaceholder: 'Rechercher…',
syncButton: 'Synchroniser vers l\'appareil',
actionTransfer: 'Transférer vers l\'appareil',
actionDelete: 'Supprimer de l\'appareil',
actionApplyAll: 'Appliquer toutes les modifications',
templatePreview: 'Aperçu',
cancel: 'Annuler',
noTargetDir: 'Veuillez d\'abord choisir un dossier cible.',
noSources: 'Veuillez sélectionner au moins une source.',
noTracks: 'Aucune piste trouvée dans les sources sélectionnées.',
fetchError: 'Échec du chargement des pistes depuis le serveur.',
syncComplete: 'Synchronisation terminée.',
dismiss: 'Fermer',
colName: 'Nom',
colType: 'Type',
colStatus: 'Statut',
onDevice: 'Gestionnaire d\'appareil',
addSources: 'Ajouter…',
syncResult: '{{done}} transféré(s), {{skipped}} déjà à jour ({{total}} au total)',
deleteFromDevice: 'Marquer pour suppression ({{count}})',
confirmDelete: 'Supprimer {{count}} élément(s) du périphérique : {{names}} ?',
deleteComplete: '{{count}} élément(s) supprimé(s) du périphérique.',
statusSynced: 'Synchronisé',
statusPending: 'En attente',
statusDeletion: 'Suppression',
markForDeletion: 'Marquer pour suppression',
removeSource: 'Supprimer',
undoDeletion: 'Annuler la suppression',
syncInBackground: 'Sync démarré en arrière-plan — vous pouvez naviguer ailleurs.',
syncInProgress: '{{done}} / {{total}} pistes…',
syncSummary: 'Résumé de la synchronisation',
calculating: 'Calcul de la charge utile…',
filesToAdd: 'Fichiers à ajouter :',
filesToDelete: 'Fichiers à supprimer :',
netChange: 'Variation nette :',
availableSpace: 'Espace disque disponible :',
spaceWarning: 'Attention : L\'appareil cible ne dispose pas d\'assez d\'espace signalé.',
proceed: 'Procéder à la synchronisation',
notEnoughSpace: 'Espace disque physique insuffisant détecté !',
liveSearch: 'Live',
randomAlbumsLabel: 'Albums aléatoires',
},
};
+138 -13
View File
@@ -17,6 +17,7 @@ export const nbTranslation = {
expand: 'Utvid sidefelt',
collapse: 'Skjul sidefelt',
downloadingTracks: 'Bufre {{n}} spor…',
syncingTracks: 'Synkroniserer {{done}}/{{total}}…',
cancelDownload: 'Avbryt nedlasting',
offlineLibrary: 'Frakoblet bibliotek',
genres: 'Sjangere',
@@ -24,8 +25,11 @@ export const nbTranslation = {
mostPlayed: 'Mest spilt',
radio: 'Internettradio',
folderBrowser: 'Mappeleser',
deviceSync: 'Enhetssynk',
libraryScope: 'Biblioteksomfang',
allLibraries: 'Alle biblioteker',
expandPlaylists: 'Utvid spillelister',
collapsePlaylists: 'Skjul spillelister',
},
home: {
hero: 'Utvalgt',
@@ -106,10 +110,14 @@ export const nbTranslation = {
unfavoriteArtist: 'Fjern artist fra favoritter',
unfavoriteAlbum: 'Fjern album fra favoritter',
removeFromQueue: 'Fjern fra kø',
removeFromPlaylist: 'Fjern fra spilleliste',
openAlbum: 'Åpne album',
goToArtist: 'Gå til artist',
download: 'Last ned (ZIP)',
addToPlaylist: 'Legg til i spilleliste',
selectedPlaylists: '{{count}} spillelister valgt',
selectedAlbums: '{{count}} album valgt',
selectedArtists: '{{count}} artister valgt',
songInfo: 'Sanginfo',
},
albumDetail: {
@@ -272,17 +280,17 @@ export const nbTranslation = {
yearTo: 'Til',
yearFilterClear: 'Tøm år filteret',
yearFilterLabel: 'År',
select: 'Multi-select',
startSelect: 'Enable multi-select',
cancelSelect: 'Cancel',
selectionCount: '{{count}} selected',
downloadZips: 'Download ZIPs',
addOffline: 'Add Offline',
downloadingZip: 'Downloading {{current}}/{{total}}: {{name}}',
downloadZipDone: '{{count}} ZIP(s) downloaded',
downloadZipFailed: 'Failed to download {{name}}',
offlineQueuing: 'Queuing {{count}} album(s) for offline…',
offlineFailed: 'Failed to add {{name}} offline',
select: 'Multivalg',
startSelect: 'Aktiver multivalg',
cancelSelect: 'Avbryt',
selectionCount: '{{count}} valgt',
downloadZips: 'Last ned ZIPs',
addOffline: 'Legg til offline',
downloadingZip: 'Laster ned {{current}}/{{total}}: {{name}}',
downloadZipDone: '{{count}} ZIP(s) lastet ned',
downloadZipFailed: 'Kunne ikke laste ned {{name}}',
offlineQueuing: 'Legger {{count}} album i kø for offline…',
offlineFailed: 'Kunne ikke legge til {{name}} offline',
},
artists: {
title: 'Artister',
@@ -296,13 +304,18 @@ export const nbTranslation = {
notFound: 'Ingen artister funnet.',
albumCount_one: '{{count}} album',
albumCount_other: '{{count}} album',
selectionCount: '{{count}} valgt',
select: 'Multivalg',
startSelect: 'Aktiver multivalg',
cancelSelect: 'Avbryt',
addToPlaylist: 'Legg til i spilleliste',
},
login: {
subtitle: 'Din Navidrome-mediaspiller',
serverName: 'Tjenernavn (valgfritt)',
serverNamePlaceholder: 'Mitt mediabibliotek',
serverUrl: 'Tjener-URL',
serverUrlPlaceholder: '192.168.1.100:4533 eller feks. musikk.eksempel.com',
serverUrlPlaceholder: '192.168.1.100:4533 eller https://musikk.eksempel.com',
username: 'Brukernavn',
usernamePlaceholder: 'admin',
password: 'Passord',
@@ -326,6 +339,7 @@ export const nbTranslation = {
offlineTitle: 'Ingen tjenertilkobling',
offlineSubtitle: 'Kan ikke nå {{server}}. Sjekk nettverket eller tjeneren din.',
offlineModeBanner: 'Frakoblet modus - spiller fra lokal hurtigbuffer',
offlineNoCacheBanner: 'Ingen servertilkobling — kan ikke nå {{server}}',
offlineLibraryTitle: 'Frakoblet bibliotek',
offlineLibraryEmpty: 'Ingen album bufret ennå. Kobl deg til nettverket, åpne et album og klikk "Gjør tilgjengelig frakoblet".',
offlineAlbumCount: '{{n}} album',
@@ -335,6 +349,7 @@ export const nbTranslation = {
offlineFilterPlaylists: 'Spillelister',
offlineFilterArtists: 'Diskografier',
retry: 'Prøv igjen',
serverSettings: 'Serverinnstillinger',
lastfmConnected: 'Last.fm tilkoblet som bruker @{{user}}',
lastfmSessionInvalid: 'Sesjonen er ugyldig - klikk her for å koble til på nytt',
},
@@ -401,6 +416,7 @@ export const nbTranslation = {
servers: 'Tjenere',
serverName: 'Tjenernavn',
serverUrl: 'Tjener-URL',
serverUrlPlaceholder: '192.168.1.100:4533 eller https://musikk.eksempel.com',
serverUsername: 'Brukernavn',
serverPassword: 'Passord',
addServer: 'Legg til tjener',
@@ -486,6 +502,13 @@ export const nbTranslation = {
hotCacheDebounceImmediate: 'Umiddelbart',
hotCacheDebounceSeconds: '{{n}} sek',
hotCacheClearBtn: 'Tøm varm buffer',
audioOutputDevice: 'Lydutgangsenhet',
audioOutputDeviceDesc: 'Velg hvilken lydenhet Psysonic spiller gjennom. Endringer trer i kraft umiddelbart og starter gjeldende spor på nytt.',
audioOutputDeviceDefault: 'Systemstandard',
audioOutputDeviceRefresh: 'Oppdater enhetsliste',
audioOutputDeviceOsDefaultNow: 'gjeldende systemutgang',
audioOutputDeviceListError: 'Kunne ikke laste listen over lydenheter.',
audioOutputDeviceNotInCurrentList: 'ikke i gjeldende liste',
hiResTitle: 'Innebygd hi-res-avspilling',
hiResEnabled: 'Aktiver innebygd hi-res-avspilling',
hiResDesc: "Begrenser utdata til 44,1 kHz som standard for maksimal stabilitet. Aktiver kun hvis maskinvare og nettverk støtter høye samplingsrater (88,2 kHz+) pålitelig.",
@@ -517,7 +540,6 @@ export const nbTranslation = {
logout: 'Logg ut',
aboutTitle: 'Om Psysonic',
aboutDesc: 'En moderne musikkspiller for Subsonic-kompatible tjenere (Navidrome, Gonic og andre). Bygget på Tauri v2 med en innebygd Rust-lydmotor - lett og rask, men fullpakket med funksjoner: bølgeform-søkelinje, synkroniserte sangtekster, Last.fm-integrasjon, 10-bånds jevnstiller, crossfade, gapless-avspilling, Replay Gain, sjangerlesing og et stort bibliotek med temaer.',
aboutFeatures: 'Multi-tjener · Last.fm scrobbling og liker · Fullskjerm Ambient Stage · Bølgeformsøk · Synkroniserte tekster · 10-bånds jevnstiller · Crossfade og gapless · Replay Gain · Sjangre · 63 temaer · 6 språk',
aboutLicense: 'Lisens',
aboutLicenseText: 'GNU GPL v3 - gratis å bruke, endre og distribuere under samme lisens.',
aboutRepo: 'Kildekode på GitHub',
@@ -637,6 +659,13 @@ export const nbTranslation = {
themeSchedulerNightTheme: 'Natttema',
themeSchedulerNightStart: 'Natt starter kl.',
themeSchedulerActiveHint: 'Temaplanlegger er aktiv - temaer byttes automatisk.',
visualOptionsTitle: 'Visuelle Alternativer',
coverArtBackground: 'Cover-bakgrunn',
coverArtBackgroundSub: 'Vis uskarpt cover som bakgrunn i album/playlist-overskrifter',
playlistCoverPhoto: 'Playlist-coverfoto',
playlistCoverPhotoSub: 'Vis coverfoto-rutenett i playlist-detailedvisning',
showBitrate: 'Vis Bitrate',
showBitrateSub: 'Vis audio-bitrate i sporlister',
uiScaleTitle: 'Grensesnittskala',
uiScaleLabel: 'Zoom',
},
@@ -918,6 +947,33 @@ export const nbTranslation = {
coverUpdated: 'Omslag oppdatert',
metaSaved: 'Spillelisten er oppdatert',
downloadZip: 'Last ned (ZIP)',
// Toast notifications for multi-select
addSuccess: '{{count}} sanger lagt til i {{playlist}}',
addPartial: '{{added}} lagt til, {{skipped}} hoppet over (duplikater)',
addAllSkipped: 'Alle hoppet over ({{count}} duplikater)',
addError: 'Feil ved å legge til sanger',
createAndAddSuccess: 'Spilleliste "{{playlist}}" opprettet med {{count}} sanger',
createError: 'Feil ved oppretting av spilleliste',
deleteSuccess: '{{count}} spillelister slettet',
deleteFailed: 'Feil ved sletting av {{name}}',
deleteSelected: 'Slett valgte',
mergeSuccess: '{{count}} sanger slått sammen i {{playlist}}',
mergeNoNewSongs: 'Ingen nye sanger å legge til',
mergeError: 'Feil ved sammenslåing av spillelister',
mergeInto: 'Slå sammen i',
selectionCount: '{{count}} valgt',
select: 'Velg',
startSelect: 'Aktiver valg',
cancelSelect: 'Avbryt',
loadingAlbums: 'Løser {{count}} album…',
loadingArtists: 'Løser {{count}} artister…',
myPlaylists: 'Mine spillelister',
noOtherPlaylists: 'Ingen andre spillelister tilgjengelig',
addToPlaylistSuccess: '{{count}} sanger lagt til i {{playlist}}',
addToPlaylistNoNew: 'Ingen nye sanger for {{playlist}}',
addToPlaylistError: 'Feil ved å legge til i spilleliste',
removeSuccess: 'Sang fjernet fra spilleliste',
removeError: 'Feil ved fjerning fra spilleliste',
},
mostPlayed: {
title: 'Mest spilt',
@@ -928,6 +984,9 @@ export const nbTranslation = {
sortLeast: 'Minst spilt først',
loadMore: 'Last inn flere album',
noData: 'Ingen avspillingsdata ennå. Begynn å høre!',
noArtists: 'Alle artister filtrert bort.',
filterCompilations: 'Skjul kompilasjonsartister (Various Artists, Soundtracks, etc.)',
filterCompilationsShort: 'Skjul kompilasjoner',
},
radio: {
title: 'Internettradio',
@@ -968,4 +1027,70 @@ export const nbTranslation = {
empty: 'Tom mappe',
error: 'Kunne ikke laste',
},
deviceSync: {
title: 'Enhetssynk',
targetFolder: 'Målmappe',
noFolderChosen: 'Ingen mappe valgt',
selectDrive: 'Velg en stasjon…',
refreshDrives: 'Oppdater stasjoner',
noDrivesDetected: 'Ingen flyttbare stasjoner oppdaget',
browseManual: 'Bla manuelt…',
free: 'ledig',
notMountedVolume: 'Målet er ikke på en montert stasjon. Enheten kan ha blitt koblet fra.',
chooseFolder: 'Velg…',
filenameTemplate: 'Filnavnmal',
targetDevice: 'Målenhet',
templateHint: 'Variabler: {artist}, {album}, {title}, {track_number}, {disc_number}, {year}',
cleanupButton: 'Fjern filer som ikke er i utvalget',
cleanupNothingToDelete: 'Ingenting å fjerne — enheten er allerede synkronisert.',
confirmCleanup: 'Slette {{count}} fil(er) fra enheten som ikke er i det gjeldende utvalget. Fortsette?',
cleanupComplete: '{{count}} fil(er) fjernet fra enheten.',
selectedSources: 'Valgte kilder',
noSourcesSelected: 'Ingen kilder valgt. Klikk på elementer i nettleseren for å legge dem til.',
clearAll: 'Fjern alle',
tabPlaylists: 'Spillelister',
tabAlbums: 'Album',
tabArtists: 'Artister',
searchPlaceholder: 'Søk…',
syncButton: 'Synkroniser til enhet',
actionTransfer: 'Overfør til enhet',
actionDelete: 'Slett fra enhet',
actionApplyAll: 'Bruk alle endringer',
templatePreview: 'Forhåndsvisning',
cancel: 'Avbryt',
noTargetDir: 'Velg en målmappe først.',
noSources: 'Velg minst én kilde.',
noTracks: 'Ingen spor funnet i de valgte kildene.',
fetchError: 'Kunne ikke hente spor fra serveren.',
syncComplete: 'Synkronisering fullført.',
dismiss: 'Lukk',
colName: 'Navn',
colType: 'Type',
colStatus: 'Status',
onDevice: 'Enhetsbehandling',
addSources: 'Legg til…',
syncResult: '{{done}} overført, {{skipped}} allerede oppdatert ({{total}} totalt)',
deleteFromDevice: 'Merk for sletting ({{count}})',
confirmDelete: 'Slette {{count}} element(er) fra enheten: {{names}}?',
deleteComplete: '{{count}} element(er) fjernet fra enheten.',
statusSynced: 'Synkronisert',
statusPending: 'Venter',
statusDeletion: 'Sletting',
markForDeletion: 'Merk for sletting',
removeSource: 'Fjern',
undoDeletion: 'Angre sletting',
syncInBackground: 'Synkronisering startet i bakgrunnen — du kan navigere bort.',
syncInProgress: '{{done}} / {{total}} spor…',
syncSummary: 'Synkroniseringssammendrag',
calculating: 'Beregner nødvendig nyttelast…',
filesToAdd: 'Filer som skal legges til:',
filesToDelete: 'Filer som skal slettes:',
netChange: 'Nettoendring:',
availableSpace: 'Tilgjengelig diskplass:',
spaceWarning: 'Advarsel: Målenheten har ikke nok rapportert plass.',
proceed: 'Fortsett med synkronisering',
notEnoughSpace: 'Ikke nok fysisk diskplass oppdaget!',
liveSearch: 'Live',
randomAlbumsLabel: 'Tilfeldige album',
},
};
+135 -13
View File
@@ -17,6 +17,7 @@ export const nlTranslation = {
expand: 'Zijbalk uitklappen',
collapse: 'Zijbalk inklappen',
downloadingTracks: '{{n}} nummers worden gecached…',
syncingTracks: 'Synchroniseren {{done}}/{{total}}…',
cancelDownload: 'Download annuleren',
offlineLibrary: 'Offline bibliotheek',
genres: 'Genres',
@@ -24,8 +25,11 @@ export const nlTranslation = {
mostPlayed: 'Meest gespeeld',
radio: 'Internetradio',
folderBrowser: 'Mappenverkenner',
deviceSync: 'Apparaatsync',
libraryScope: 'Bibliotheekbereik',
allLibraries: 'Alle bibliotheken',
expandPlaylists: 'Afspeellijsten uitklappen',
collapsePlaylists: 'Afspeellijsten inklappen',
},
home: {
hero: 'Uitgelicht',
@@ -110,6 +114,9 @@ export const nlTranslation = {
goToArtist: 'Naar artiest',
download: 'Downloaden (ZIP)',
addToPlaylist: 'Toevoegen aan playlist',
selectedPlaylists: '{{count}} playlists geselecteerd',
selectedAlbums: '{{count}} albums geselecteerd',
selectedArtists: '{{count}} artiesten geselecteerd',
songInfo: 'Nummerinfo',
},
albumDetail: {
@@ -272,17 +279,17 @@ export const nlTranslation = {
yearTo: 'Tot',
yearFilterClear: 'Jaarfilter wissen',
yearFilterLabel: 'Jaar',
select: 'Multi-select',
startSelect: 'Enable multi-select',
cancelSelect: 'Cancel',
selectionCount: '{{count}} selected',
downloadZips: 'Download ZIPs',
addOffline: 'Add Offline',
downloadingZip: 'Downloading {{current}}/{{total}}: {{name}}',
downloadZipDone: '{{count}} ZIP(s) downloaded',
downloadZipFailed: 'Failed to download {{name}}',
offlineQueuing: 'Queuing {{count}} album(s) for offline…',
offlineFailed: 'Failed to add {{name}} offline',
select: 'Meervoudige selectie',
startSelect: 'Meervoudige selectie inschakelen',
cancelSelect: 'Annuleren',
selectionCount: '{{count}} geselecteerd',
downloadZips: 'ZIPs downloaden',
addOffline: 'Offline toevoegen',
downloadingZip: 'Downloaden {{current}}/{{total}}: {{name}}',
downloadZipDone: '{{count}} ZIP(s) gedownload',
downloadZipFailed: 'Downloaden van {{name}} mislukt',
offlineQueuing: '{{count}} album(s) in wachtrij voor offline…',
offlineFailed: 'Toevoegen van {{name}} offline mislukt',
},
artists: {
title: 'Artiesten',
@@ -296,13 +303,18 @@ export const nlTranslation = {
notFound: 'Geen artiesten gevonden.',
albumCount_one: '{{count}} album',
albumCount_other: '{{count}} albums',
selectionCount: '{{count}} geselecteerd',
select: 'Meervoudige selectie',
startSelect: 'Meervoudige selectie inschakelen',
cancelSelect: 'Annuleren',
addToPlaylist: 'Toevoegen aan playlist',
},
login: {
subtitle: 'Jouw Navidrome-desktopspeler',
serverName: 'Servernaam (optioneel)',
serverNamePlaceholder: 'Mijn Navidrome',
serverUrl: 'Server-URL',
serverUrlPlaceholder: '192.168.1.100:4533 of music.voorbeeld.nl',
serverUrlPlaceholder: '192.168.1.100:4533 of https://music.voorbeeld.nl',
username: 'Gebruikersnaam',
usernamePlaceholder: 'admin',
password: 'Wachtwoord',
@@ -326,6 +338,7 @@ export const nlTranslation = {
offlineTitle: 'Geen serververbinding',
offlineSubtitle: 'Kan {{server}} niet bereiken. Controleer je netwerk of server.',
offlineModeBanner: 'Offline modus — afspelen vanuit lokale cache',
offlineNoCacheBanner: 'Geen serververbinding — {{server}} niet bereikbaar',
offlineLibraryTitle: 'Offline bibliotheek',
offlineLibraryEmpty: 'Nog geen albums gecached. Ga online, open een album en klik op "Offline beschikbaar maken".',
offlineAlbumCount: '{{n}} album',
@@ -335,6 +348,7 @@ export const nlTranslation = {
offlineFilterPlaylists: 'Afspeellijsten',
offlineFilterArtists: 'Discografieën',
retry: 'Opnieuw proberen',
serverSettings: 'Serverinstellingen',
lastfmConnected: 'Last.fm verbonden als @{{user}}',
lastfmSessionInvalid: 'Sessie ongeldig — klik om opnieuw te verbinden',
},
@@ -401,6 +415,7 @@ export const nlTranslation = {
servers: 'Servers',
serverName: 'Servernaam',
serverUrl: 'Server-URL',
serverUrlPlaceholder: '192.168.1.100:4533 of https://music.voorbeeld.nl',
serverUsername: 'Gebruikersnaam',
serverPassword: 'Wachtwoord',
addServer: 'Server toevoegen',
@@ -485,6 +500,13 @@ export const nlTranslation = {
hotCacheDebounceImmediate: 'Direct',
hotCacheDebounceSeconds: '{{n}} s',
hotCacheClearBtn: 'Warme cache wissen',
audioOutputDevice: 'Audio-uitvoerapparaat',
audioOutputDeviceDesc: 'Kies via welk audioapparaat Psysonic afspeelt. Wijzigingen worden direct toegepast en starten het huidige nummer opnieuw.',
audioOutputDeviceDefault: 'Systeemstandaard',
audioOutputDeviceRefresh: 'Apparatenlijst vernieuwen',
audioOutputDeviceOsDefaultNow: 'huidige systeemuitvoer',
audioOutputDeviceListError: 'De lijst met audio-apparaten kon niet worden geladen.',
audioOutputDeviceNotInCurrentList: 'staat niet in de huidige lijst',
hiResTitle: 'Natieve hi-res-weergave',
hiResEnabled: 'Natieve hi-res-weergave inschakelen',
hiResDesc: "Beperkt de uitvoer standaard tot 44,1 kHz voor maximale stabiliteit. Alleen inschakelen als hardware en netwerk hoge samplerates (88,2 kHz+) ondersteunen.",
@@ -518,7 +540,6 @@ export const nlTranslation = {
logout: 'Uitloggen',
aboutTitle: 'Over Psysonic',
aboutDesc: 'Een moderne desktopmuziekspeeler voor Subsonic-compatibele servers (Navidrome, Gonic en anderen). Gebouwd op Tauri v2 met een native Rust audio-engine — licht en snel, maar boordevol functies: golfvorm-zoekbalk, gesynchroniseerde songteksten, Last.fm-integratie, 10-bands equalizer, crossfade, naadloos afspelen, Replay Gain, genres en een uitgebreide themabibliotheek.',
aboutFeatures: 'Multi-server · Last.fm scrobbling & love · Fullscreen Ambient Stage · Waveform seek · Syncteksten · 10-bands EQ · Crossfade & Gapless · Replay Gain · Genres · 63 thema\'s · 5 talen',
aboutLicense: 'Licentie',
aboutLicenseText: 'GNU GPL v3 — vrij te gebruiken, wijzigen en verspreiden onder dezelfde licentie.',
aboutRepo: 'Broncode op GitHub',
@@ -638,6 +659,13 @@ export const nlTranslation = {
themeSchedulerNightTheme: 'Nachtthema',
themeSchedulerNightStart: 'Nacht begint om',
themeSchedulerActiveHint: "Thema-planner is actief - thema's worden automatisch gewisseld.",
visualOptionsTitle: 'Visuele Opties',
coverArtBackground: 'Cover Achtergrond',
coverArtBackgroundSub: 'Toon vervaagde cover als achtergrond in album/playlist headers',
playlistCoverPhoto: 'Playlist Coverfoto',
playlistCoverPhotoSub: 'Toon coverfoto raster in playlist detailweergave',
showBitrate: 'Toon Bitrate',
showBitrateSub: 'Toon audio bitrate in tracklijsten',
uiScaleTitle: 'Interface schaal',
uiScaleLabel: 'Zoom',
},
@@ -919,6 +947,31 @@ export const nlTranslation = {
coverUpdated: 'Omslag bijgewerkt',
metaSaved: 'Playlist bijgewerkt',
downloadZip: 'Downloaden (ZIP)',
// Toast notifications for multi-select
addSuccess: '{{count}} nummers toegevoegd aan {{playlist}}',
addPartial: '{{added}} toegevoegd, {{skipped}} overgeslagen (duplicaten)',
addAllSkipped: 'Alles overgeslagen ({{count}} duplicaten)',
addError: 'Fout bij toevoegen van nummers',
createAndAddSuccess: 'Playlist "{{playlist}}" aangemaakt met {{count}} nummers',
createError: 'Fout bij aanmaken van playlist',
deleteSuccess: '{{count}} playlists verwijderd',
deleteFailed: 'Fout bij verwijderen van {{name}}',
deleteSelected: 'Geselecteerde verwijderen',
mergeSuccess: '{{count}} nummers samengevoegd in {{playlist}}',
mergeNoNewSongs: 'Geen nieuwe nummers om toe te voegen',
mergeError: 'Fout bij samenvoegen van playlists',
mergeInto: 'Samenvoegen in',
selectionCount: '{{count}} geselecteerd',
select: 'Selecteren',
startSelect: 'Selectie inschakelen',
cancelSelect: 'Annuleren',
loadingAlbums: '{{count}} albums oplossen…',
loadingArtists: '{{count}} artiesten oplossen…',
myPlaylists: 'Mijn playlists',
noOtherPlaylists: 'Geen andere playlists beschikbaar',
addToPlaylistSuccess: '{{count}} nummers toegevoegd aan {{playlist}}',
addToPlaylistNoNew: 'Geen nieuwe nummers voor {{playlist}}',
addToPlaylistError: 'Fout bij toevoegen aan playlist',
},
mostPlayed: {
title: 'Meest gespeeld',
@@ -929,6 +982,9 @@ export const nlTranslation = {
sortLeast: 'Minst gespeeld eerst',
loadMore: 'Meer albums laden',
noData: 'Nog geen afspeelgegevens. Begin met luisteren!',
noArtists: 'Alle artiesten gefilterd.',
filterCompilations: 'Compilatie-artiesten verbergen (Various Artists, Soundtracks, etc.)',
filterCompilationsShort: 'Compilaties verbergen',
},
radio: {
title: 'Internetradio',
@@ -969,4 +1025,70 @@ export const nlTranslation = {
empty: 'Lege map',
error: 'Laden mislukt',
},
deviceSync: {
title: 'Apparaatsync',
targetFolder: 'Doelmap',
noFolderChosen: 'Geen map gekozen',
selectDrive: 'Selecteer een schijf…',
refreshDrives: 'Schijven vernieuwen',
noDrivesDetected: 'Geen verwijderbare schijven gedetecteerd',
browseManual: 'Handmatig bladeren…',
free: 'vrij',
notMountedVolume: 'Het doel bevindt zich niet op een gekoppeld volume. De schijf is mogelijk losgekoppeld.',
chooseFolder: 'Kiezen…',
filenameTemplate: 'Bestandsnaamsjabloon',
targetDevice: 'Doelapparaat',
templateHint: 'Variabelen: {artist}, {album}, {title}, {track_number}, {disc_number}, {year}',
cleanupButton: 'Niet-geselecteerde bestanden verwijderen',
cleanupNothingToDelete: 'Niets te verwijderen — apparaat is al gesynchroniseerd.',
confirmCleanup: '{{count}} bestand(en) verwijderen van het apparaat die niet in de huidige selectie staan. Doorgaan?',
cleanupComplete: '{{count}} bestand(en) van het apparaat verwijderd.',
selectedSources: 'Geselecteerde bronnen',
noSourcesSelected: 'Geen bronnen geselecteerd. Klik op items in de browser om ze toe te voegen.',
clearAll: 'Alles wissen',
tabPlaylists: 'Afspeellijsten',
tabAlbums: 'Albums',
tabArtists: 'Artiesten',
searchPlaceholder: 'Zoeken…',
syncButton: 'Synchroniseren naar apparaat',
actionTransfer: 'Overdragen naar apparaat',
actionDelete: 'Verwijderen van apparaat',
actionApplyAll: 'Alle wijzigingen toepassen',
templatePreview: 'Voorbeeld',
cancel: 'Annuleren',
noTargetDir: 'Kies eerst een doelmap.',
noSources: 'Selecteer minimaal één bron.',
noTracks: 'Geen nummers gevonden in de geselecteerde bronnen.',
fetchError: 'Ophalen van nummers van de server mislukt.',
syncComplete: 'Synchronisatie voltooid.',
dismiss: 'Sluiten',
colName: 'Naam',
colType: 'Type',
colStatus: 'Status',
onDevice: 'Apparaatbeheer',
addSources: 'Toevoegen…',
syncResult: '{{done}} overgedragen, {{skipped}} al up-to-date ({{total}} totaal)',
deleteFromDevice: 'Markeren voor verwijdering ({{count}})',
confirmDelete: '{{count}} item(s) van het apparaat verwijderen: {{names}}?',
deleteComplete: '{{count}} item(s) van het apparaat verwijderd.',
statusSynced: 'Gesynchroniseerd',
statusPending: 'In behandeling',
statusDeletion: 'Verwijdering',
markForDeletion: 'Markeren voor verwijdering',
removeSource: 'Verwijderen',
undoDeletion: 'Verwijdering ongedaan maken',
syncInBackground: 'Sync gestart op achtergrond — u kunt navigeren.',
syncInProgress: '{{done}} / {{total}} nummers…',
syncSummary: 'Synchronisatieoverzicht',
calculating: 'Vereiste payload berekenen…',
filesToAdd: 'Te toevoegen bestanden:',
filesToDelete: 'Te verwijderen bestanden:',
netChange: 'Nettoverandering:',
availableSpace: 'Beschikbare schijfruimte:',
spaceWarning: 'Waarschuwing: Het doelapparaat heeft niet genoeg gerapporteerde ruimte.',
proceed: 'Doorgaan met synchronisatie',
notEnoughSpace: 'Onvoldoende fysieke schijfruimte gedetecteerd!',
liveSearch: 'Live',
randomAlbumsLabel: 'Willekeurige albums',
},
};
+139 -15
View File
@@ -18,6 +18,7 @@ export const ruTranslation = {
expand: 'Развернуть боковую панель',
collapse: 'Свернуть боковую панель',
downloadingTracks: 'Кэширование {{n}} треков…',
syncingTracks: 'Синхронизация {{done}}/{{total}}…',
cancelDownload: 'Отменить загрузку',
offlineLibrary: 'Офлайн-библиотека',
genres: 'Жанры',
@@ -25,8 +26,11 @@ export const ruTranslation = {
mostPlayed: 'Популярное',
radio: 'Онлайн-радио',
folderBrowser: 'Браузер папок',
deviceSync: 'Синхронизация устройства',
libraryScope: 'Область медиатеки',
allLibraries: 'Все библиотеки',
expandPlaylists: 'Развернуть плейлисты',
collapsePlaylists: 'Свернуть плейлисты',
},
home: {
hero: 'Подборка',
@@ -107,10 +111,14 @@ export const ruTranslation = {
unfavoriteArtist: 'Убрать исполнителя из избранного',
unfavoriteAlbum: 'Убрать альбом из избранного',
removeFromQueue: 'Убрать из очереди',
removeFromPlaylist: 'Убрать из плейлиста',
openAlbum: 'Открыть альбом',
goToArtist: 'К исполнителю',
download: 'Скачать (ZIP)',
addToPlaylist: 'В плейлист',
selectedPlaylists: '{{count}} плейлистов выбрано',
selectedAlbums: '{{count}} альбомов выбрано',
selectedArtists: '{{count}} исполнителей выбрано',
songInfo: 'Сведения о треке',
},
albumDetail: {
@@ -281,17 +289,17 @@ export const ruTranslation = {
yearTo: 'По',
yearFilterClear: 'Сбросить год',
yearFilterLabel: 'Год',
select: 'Multi-select',
startSelect: 'Enable multi-select',
cancelSelect: 'Cancel',
selectionCount: '{{count}} selected',
downloadZips: 'Download ZIPs',
addOffline: 'Add Offline',
downloadingZip: 'Downloading {{current}}/{{total}}: {{name}}',
downloadZipDone: '{{count}} ZIP(s) downloaded',
downloadZipFailed: 'Failed to download {{name}}',
offlineQueuing: 'Queuing {{count}} album(s) for offline…',
offlineFailed: 'Failed to add {{name}} offline',
select: 'Множественный выбор',
startSelect: 'Включить множественный выбор',
cancelSelect: 'Отмена',
selectionCount: '{{count}} выбрано',
downloadZips: 'Скачать ZIP-архивы',
addOffline: 'Добавить офлайн',
downloadingZip: 'Загрузка {{current}}/{{total}}: {{name}}',
downloadZipDone: '{{count}} ZIP-архив(ов) загружено',
downloadZipFailed: 'Не удалось скачать {{name}}',
offlineQueuing: 'Добавление {{count}} альбом(ов) в офлайн…',
offlineFailed: 'Не удалось добавить {{name}} офлайн',
},
artists: {
title: 'Исполнители',
@@ -307,13 +315,18 @@ export const ruTranslation = {
albumCount_few: '{{count}} альбома',
albumCount_many: '{{count}} альбомов',
albumCount_other: '{{count}} альбомов',
selectionCount: '{{count}} выбрано',
select: 'Множественный выбор',
startSelect: 'Включить множественный выбор',
cancelSelect: 'Отмена',
addToPlaylist: 'В плейлист',
},
login: {
subtitle: 'Десктопный клиент для Navidrome',
serverName: 'Название сервера (необязательно)',
serverNamePlaceholder: 'Мой Navidrome',
serverUrl: 'Адрес сервера',
serverUrlPlaceholder: '192.168.1.100:4533 или music.example.com',
serverUrlPlaceholder: '192.168.1.100:4533 или https://music.example.com',
username: 'Логин',
usernamePlaceholder: 'admin',
password: 'Пароль',
@@ -337,6 +350,7 @@ export const ruTranslation = {
offlineTitle: 'Нет связи с сервером',
offlineSubtitle: 'Сервер {{server}} недоступен. Проверьте сеть и адрес.',
offlineModeBanner: 'Офлайн — воспроизведение из локального кэша',
offlineNoCacheBanner: 'Нет соединения с сервером — {{server}} недоступен',
offlineLibraryTitle: 'Офлайн-библиотека',
offlineLibraryEmpty:
'Пока ничего не сохранено. Подключитесь к сети, откройте альбом и нажмите «Сохранить офлайн».',
@@ -349,6 +363,7 @@ export const ruTranslation = {
offlineFilterPlaylists: 'Плейлисты',
offlineFilterArtists: 'Дискографии',
retry: 'Повторить',
serverSettings: 'Настройки сервера',
lastfmConnected: 'Last.fm: @{{user}}',
lastfmSessionInvalid: 'Сессия недействительна — подключите снова',
},
@@ -416,6 +431,7 @@ export const ruTranslation = {
servers: 'Серверы',
serverName: 'Название',
serverUrl: 'Адрес',
serverUrlPlaceholder: '192.168.1.100:4533 или https://music.example.com',
serverUsername: 'Логин',
serverPassword: 'Пароль',
addServer: 'Добавить сервер',
@@ -502,6 +518,13 @@ export const ruTranslation = {
hotCacheDebounceImmediate: 'Сразу',
hotCacheDebounceSeconds: '{{n}} с',
hotCacheClearBtn: 'Очистить горячий кэш',
audioOutputDevice: 'Устройство вывода звука',
audioOutputDeviceDesc: 'Выберите аудиоустройство для воспроизведения. Изменения применяются немедленно и перезапускают текущий трек.',
audioOutputDeviceDefault: 'Системное по умолчанию',
audioOutputDeviceRefresh: 'Обновить список устройств',
audioOutputDeviceOsDefaultNow: 'текущий системный вывод',
audioOutputDeviceListError: 'Не удалось загрузить список аудиоустройств.',
audioOutputDeviceNotInCurrentList: 'нет в текущем списке',
hiResTitle: 'Нативное воспроизведение Hi-Res',
hiResEnabled: 'Включить нативное Hi-Res воспроизведение',
hiResDesc: "По умолчанию вывод ограничен до 44,1 кГц для максимальной стабильности. Включайте только если оборудование и сеть надёжно поддерживают высокие частоты (88,2 кГц+).",
@@ -542,8 +565,6 @@ export const ruTranslation = {
aboutTitle: 'О Psysonic',
aboutDesc:
'Современный десктопный плеер для серверов с протоколом Subsonic (Navidrome, Gonic и др.). На Tauri v2 и нативном аудиодвижке на Rust — лёгкий и быстрый: волновая шкала, синхронные тексты, Last.fm, 10-полосный EQ, кроссфейд, воспроизведение без пауз, Replay Gain, жанры и много тем оформления.',
aboutFeatures:
'Несколько серверов · Last.fm · полноэкранный режим · волна · тексты · 10 полос EQ · кроссфейд и воспроизведение без пауз · Replay Gain · жанры · десятки тем · несколько языков',
aboutLicense: 'Лицензия',
aboutLicenseText: 'GNU GPL v3 — свободное использование и изменение на тех же условиях.',
aboutRepo: 'Исходный код на GitHub',
@@ -666,6 +687,13 @@ export const ruTranslation = {
themeSchedulerNightTheme: 'Ночная тема',
themeSchedulerNightStart: 'Ночь начинается в',
themeSchedulerActiveHint: 'Расписание тем активно - темы переключаются автоматически.',
visualOptionsTitle: 'Визуальные Настройки',
coverArtBackground: 'Фон Обложки',
coverArtBackgroundSub: 'Показывать размытую обложку как фон в заголовках альбомов и плейлистов',
playlistCoverPhoto: 'Обложка Плейлиста',
playlistCoverPhotoSub: 'Показывать сетку обложек в детальном виде плейлиста',
showBitrate: 'Показывать Битрейт',
showBitrateSub: 'Отображать битрейт аудио в списках треков',
uiScaleTitle: 'Масштаб интерфейса',
uiScaleLabel: 'Масштаб',
},
@@ -978,6 +1006,33 @@ export const ruTranslation = {
coverUpdated: 'Обложка обновлена',
metaSaved: 'Плейлист сохранён',
downloadZip: 'Скачать (ZIP)',
// Toast notifications for multi-select
addSuccess: '{{count}} треков добавлено в {{playlist}}',
addPartial: '{{added}} добавлено, {{skipped}} пропущено (дубликаты)',
addAllSkipped: 'Все пропущены ({{count}} дубликатов)',
addError: 'Ошибка при добавлении треков',
createAndAddSuccess: 'Плейлист "{{playlist}}" создан с {{count}} треками',
createError: 'Ошибка при создании плейлиста',
deleteSuccess: '{{count}} плейлистов удалено',
deleteFailed: 'Ошибка при удалении {{name}}',
deleteSelected: 'Удалить выбранные',
mergeSuccess: '{{count}} треков объединено в {{playlist}}',
mergeNoNewSongs: 'Нет новых треков для добавления',
mergeError: 'Ошибка при объединении плейлистов',
mergeInto: 'Объединить в',
selectionCount: '{{count}} выбрано',
select: 'Выбрать',
startSelect: 'Включить выбор',
cancelSelect: 'Отмена',
loadingAlbums: 'Загрузка {{count}} альбомов…',
loadingArtists: 'Загрузка {{count}} исполнителей…',
myPlaylists: 'Мои плейлисты',
noOtherPlaylists: 'Нет других доступных плейлистов',
addToPlaylistSuccess: '{{count}} треков добавлено в {{playlist}}',
addToPlaylistNoNew: 'Нет новых треков для {{playlist}}',
addToPlaylistError: 'Ошибка при добавлении в плейлист',
removeSuccess: 'Трек убран из плейлиста',
removeError: 'Ошибка при удалении из плейлиста',
},
mostPlayed: {
title: 'Популярное',
@@ -987,7 +1042,10 @@ export const ruTranslation = {
sortMost: 'Сначала популярные',
sortLeast: 'Сначала малоизвестные',
loadMore: 'Загрузить больше альбомов',
noData: 'Нет данных о прослушиваниях. Начните слушать!',
noData: 'Пока нет данных о прослушивании. Начните слушать!',
noArtists: 'Все исполнители отфильтрованы.',
filterCompilations: 'Скрыть исполнителей сборников (Various Artists, Soundtracks и др.)',
filterCompilationsShort: 'Скрыть сборники',
},
radio: {
title: 'Онлайн-радио',
@@ -1028,4 +1086,70 @@ export const ruTranslation = {
empty: 'Папка пуста',
error: 'Ошибка загрузки',
},
deviceSync: {
title: 'Синхронизация устройства',
targetFolder: 'Папка назначения',
noFolderChosen: 'Папка не выбрана',
selectDrive: 'Выберите диск…',
refreshDrives: 'Обновить диски',
noDrivesDetected: 'Съёмные диски не обнаружены',
browseManual: 'Обзор вручную…',
free: 'свободно',
notMountedVolume: 'Цель не находится на смонтированном томе. Диск мог быть отключён.',
chooseFolder: 'Выбрать…',
filenameTemplate: 'Шаблон имени файла',
targetDevice: 'Целевое устройство',
templateHint: 'Переменные: {artist}, {album}, {title}, {track_number}, {disc_number}, {year}',
cleanupButton: 'Удалить файлы вне выборки',
cleanupNothingToDelete: 'Нечего удалять — устройство уже синхронизировано.',
confirmCleanup: 'Удалить {{count}} файл(ов) с устройства, не входящих в текущую выборку. Продолжить?',
cleanupComplete: '{{count}} файл(ов) удалено с устройства.',
selectedSources: 'Выбранные источники',
noSourcesSelected: 'Источники не выбраны. Нажмите на элементы в браузере, чтобы добавить их.',
clearAll: 'Очистить всё',
tabPlaylists: 'Плейлисты',
tabAlbums: 'Альбомы',
tabArtists: 'Исполнители',
searchPlaceholder: 'Поиск…',
syncButton: 'Синхронизировать на устройство',
actionTransfer: 'Перенести на устройство',
actionDelete: 'Удалить с устройства',
actionApplyAll: 'Применить все изменения',
templatePreview: 'Предпросмотр',
cancel: 'Отмена',
noTargetDir: 'Сначала выберите папку назначения.',
noSources: 'Выберите хотя бы один источник.',
noTracks: 'В выбранных источниках не найдено треков.',
fetchError: 'Ошибка загрузки треков с сервера.',
syncComplete: 'Синхронизация завершена.',
dismiss: 'Закрыть',
colName: 'Название',
colType: 'Тип',
colStatus: 'Статус',
onDevice: 'Управление устройством',
addSources: 'Добавить…',
syncResult: '{{done}} перенесено, {{skipped}} уже актуально ({{total}} всего)',
deleteFromDevice: 'Пометить для удаления ({{count}})',
confirmDelete: 'Удалить {{count}} запись(ей) с устройства: {{names}}?',
deleteComplete: '{{count}} запись(ей) удалено с устройства.',
statusSynced: 'Синхронизировано',
statusPending: 'Ожидает',
statusDeletion: 'Удаление',
markForDeletion: 'Пометить для удаления',
removeSource: 'Удалить',
undoDeletion: 'Отменить удаление',
syncInBackground: 'Синхронизация запущена в фоне — можно перейти в другой раздел.',
syncInProgress: '{{done}} / {{total}} треков…',
syncSummary: 'Сводка синхронизации',
calculating: 'Вычисление необходимых данных…',
filesToAdd: 'Файлы для добавления:',
filesToDelete: 'Файлы для удаления:',
netChange: 'Чистое изменение:',
availableSpace: 'Доступное место на диске:',
spaceWarning: 'Предупреждение: на целевом устройстве недостаточно сообщаемого места.',
proceed: 'Продолжить синхронизацию',
notEnoughSpace: 'Обнаружено недостаточно физического места на диске!',
liveSearch: 'Live',
randomAlbumsLabel: 'Случайные альбомы',
},
};
+136 -14
View File
@@ -17,6 +17,7 @@ export const zhTranslation = {
expand: '展开侧边栏',
collapse: '收起侧边栏',
downloadingTracks: '正在缓存 {{n}} 首歌曲…',
syncingTracks: '同步中 {{done}}/{{total}}…',
cancelDownload: '取消下载',
offlineLibrary: '离线音乐库',
genres: '流派',
@@ -24,8 +25,11 @@ export const zhTranslation = {
mostPlayed: '最常播放',
radio: '网络电台',
folderBrowser: '文件夹浏览器',
deviceSync: '设备同步',
libraryScope: '资料库范围',
allLibraries: '所有资料库',
expandPlaylists: '展开播放列表',
collapsePlaylists: '收起播放列表',
},
home: {
hero: '精选',
@@ -110,6 +114,9 @@ export const zhTranslation = {
goToArtist: '前往艺术家',
download: '下载 (ZIP)',
addToPlaylist: '添加到播放列表',
selectedPlaylists: '已选择 {{count}} 个播放列表',
selectedAlbums: '已选择 {{count}} 个专辑',
selectedArtists: '已选择 {{count}} 个艺术家',
songInfo: '歌曲信息',
},
albumDetail: {
@@ -272,17 +279,17 @@ export const zhTranslation = {
yearTo: '到',
yearFilterClear: '清除年份筛选',
yearFilterLabel: '年份',
select: 'Multi-select',
startSelect: 'Enable multi-select',
cancelSelect: 'Cancel',
selectionCount: '{{count}} selected',
downloadZips: 'Download ZIPs',
addOffline: 'Add Offline',
downloadingZip: 'Downloading {{current}}/{{total}}: {{name}}',
downloadZipDone: '{{count}} ZIP(s) downloaded',
downloadZipFailed: 'Failed to download {{name}}',
offlineQueuing: 'Queuing {{count}} album(s) for offline…',
offlineFailed: 'Failed to add {{name}} offline',
select: '多选',
startSelect: '启用多选',
cancelSelect: '取消',
selectionCount: '{{count}} 已选择',
downloadZips: '下载 ZIP',
addOffline: '添加离线',
downloadingZip: '正在下载 {{current}}/{{total}}: {{name}}',
downloadZipDone: '已下载 {{count}} ZIP',
downloadZipFailed: '下载 {{name}} 失败',
offlineQueuing: '正在将 {{count}} 张专辑加入离线队列…',
offlineFailed: '添加 {{name}} 离线失败',
},
artists: {
title: '艺术家',
@@ -296,13 +303,18 @@ export const zhTranslation = {
notFound: '未找到艺术家。',
albumCount_one: '{{count}} 张专辑',
albumCount_other: '{{count}} 张专辑',
selectionCount: '{{count}} 已选择',
select: '多选',
startSelect: '启用多选',
cancelSelect: '取消',
addToPlaylist: '添加到播放列表',
},
login: {
subtitle: '您的 Navidrome 桌面播放器',
serverName: '服务器名称(可选)',
serverNamePlaceholder: '我的 Navidrome',
serverUrl: '服务器地址',
serverUrlPlaceholder: '192.168.1.100:4533 或 music.example.com',
serverUrlPlaceholder: '192.168.1.100:4533 或 https://music.example.com',
username: '用户名',
usernamePlaceholder: 'admin',
password: '密码',
@@ -326,11 +338,13 @@ export const zhTranslation = {
offlineTitle: '无服务器连接',
offlineSubtitle: '无法连接到 {{server}}。请检查您的网络或服务器。',
offlineModeBanner: '离线模式 — 正在从本地缓存播放',
offlineNoCacheBanner: '无服务器连接 — 无法访问 {{server}}',
offlineLibraryTitle: '离线音乐库',
offlineLibraryEmpty: '尚未缓存任何专辑。请联网,打开专辑并点击"设为离线可用"。',
offlineAlbumCount_one: '{{n}} 张专辑',
offlineAlbumCount_plural: '{{n}} 张专辑',
retry: '重试',
serverSettings: '服务器设置',
lastfmConnected: 'Last.fm 已连接为 @{{user}}',
lastfmSessionInvalid: '会话无效 — 点击重新连接',
},
@@ -397,6 +411,7 @@ export const zhTranslation = {
servers: '服务器',
serverName: '服务器名称',
serverUrl: '服务器地址',
serverUrlPlaceholder: '192.168.1.100:4533 或 https://music.example.com',
serverUsername: '用户名',
serverPassword: '密码',
addServer: '添加服务器',
@@ -481,6 +496,13 @@ export const zhTranslation = {
hotCacheDebounceImmediate: '立即',
hotCacheDebounceSeconds: '{{n}} 秒',
hotCacheClearBtn: '清空热缓存',
audioOutputDevice: '音频输出设备',
audioOutputDeviceDesc: '选择 Psysonic 播放音频的设备。更改立即生效并重新开始当前曲目。',
audioOutputDeviceDefault: '系统默认',
audioOutputDeviceRefresh: '刷新设备列表',
audioOutputDeviceOsDefaultNow: '当前系统输出',
audioOutputDeviceListError: '无法加载音频设备列表。',
audioOutputDeviceNotInCurrentList: '不在当前列表中',
hiResTitle: '原生高清晰度播放',
hiResEnabled: '启用原生高清晰度播放',
hiResDesc: "默认强制 44.1 kHz 输出以获得最大稳定性。仅在硬件和网络可靠支持高采样率(88.2 kHz+)时启用。",
@@ -514,7 +536,6 @@ export const zhTranslation = {
logout: '退出登录',
aboutTitle: '关于 Psysonic',
aboutDesc: '适用于 Subsonic 兼容服务器(Navidrome、Gonic 等)的现代桌面音乐播放器。基于 Tauri v2 和原生 Rust 音频引擎构建——轻量快速,功能丰富:波形进度条、同步歌词、Last.fm 集成、10 段均衡器、交叉淡入淡出、无缝播放、响度增益、流派浏览以及大量精美主题。',
aboutFeatures: '多服务器 · Last.fm 记录 & 喜爱 · 全屏环境舞台 · 波形跳转 · 同步歌词 · 10 段 EQ · 交叉淡入淡出 & 无缝播放 · 响度增益 · 流派 · 63 个主题 · 5 种语言',
aboutLicense: '许可证',
aboutLicenseText: 'GNU GPL v3 — 在相同许可证下可自由使用、修改和分发。',
aboutRepo: 'GitHub 上的源代码',
@@ -634,6 +655,13 @@ export const zhTranslation = {
themeSchedulerNightTheme: '夜晚主题',
themeSchedulerNightStart: '夜晚开始时间',
themeSchedulerActiveHint: '主题定时器已启用 - 主题将自动切换。',
visualOptionsTitle: '视觉选项',
coverArtBackground: '封面背景',
coverArtBackgroundSub: '在专辑/播放列表标题中显示模糊的封面作为背景',
playlistCoverPhoto: '播放列表封面照片',
playlistCoverPhotoSub: '在播放列表详细视图中显示封面照片网格',
showBitrate: '显示比特率',
showBitrateSub: '在曲目列表中显示音频比特率',
uiScaleTitle: '界面缩放',
uiScaleLabel: '缩放',
},
@@ -915,6 +943,31 @@ export const zhTranslation = {
coverUpdated: '封面已更新',
metaSaved: '播放列表已更新',
downloadZip: '下载 (ZIP)',
// Toast notifications for multi-select
addSuccess: '{{count}} 首歌曲已添加到 {{playlist}}',
addPartial: '{{added}} 首已添加,{{skipped}} 首跳过(重复)',
addAllSkipped: '全部跳过({{count}} 首重复)',
addError: '添加歌曲时出错',
createAndAddSuccess: '播放列表 "{{playlist}}" 已创建,包含 {{count}} 首歌曲',
createError: '创建播放列表时出错',
deleteSuccess: '{{count}} 个播放列表已删除',
deleteFailed: '删除 {{name}} 时出错',
deleteSelected: '删除所选',
mergeSuccess: '{{count}} 首歌曲已合并到 {{playlist}}',
mergeNoNewSongs: '没有新歌曲可添加',
mergeError: '合并播放列表时出错',
mergeInto: '合并到',
selectionCount: '{{count}} 已选择',
select: '选择',
startSelect: '启用选择',
cancelSelect: '取消',
loadingAlbums: '正在解析 {{count}} 张专辑…',
loadingArtists: '正在解析 {{count}} 位艺术家…',
myPlaylists: '我的播放列表',
noOtherPlaylists: '没有其他可用播放列表',
addToPlaylistSuccess: '{{count}} 首歌曲已添加到 {{playlist}}',
addToPlaylistNoNew: '{{playlist}} 没有新歌曲',
addToPlaylistError: '添加到播放列表时出错',
},
mostPlayed: {
title: '最常播放',
@@ -924,7 +977,10 @@ export const zhTranslation = {
sortMost: '最多播放在前',
sortLeast: '最少播放在前',
loadMore: '加载更多专辑',
noData: '暂无播放数据开始听吧!',
noData: '暂无播放数据开始听吧!',
noArtists: '所有艺术家已过滤。',
filterCompilations: '隐藏合辑艺术家(Various Artists、原声带等)',
filterCompilationsShort: '隐藏合辑',
},
radio: {
title: '网络电台',
@@ -965,4 +1021,70 @@ export const zhTranslation = {
empty: '空文件夹',
error: '加载失败',
},
deviceSync: {
title: '设备同步',
targetFolder: '目标文件夹',
noFolderChosen: '未选择文件夹',
selectDrive: '选择驱动器…',
refreshDrives: '刷新驱动器',
noDrivesDetected: '未检测到可移动驱动器',
browseManual: '手动浏览…',
free: '可用',
notMountedVolume: '目标不在已挂载的卷上。驱动器可能已断开。',
chooseFolder: '选择…',
filenameTemplate: '文件名模板',
targetDevice: '目标设备',
templateHint: '变量:{artist}、{album}、{title}、{track_number}、{disc_number}、{year}',
cleanupButton: '删除不在选择范围内的文件',
cleanupNothingToDelete: '无需删除 — 设备已同步。',
confirmCleanup: '将从设备中删除 {{count}} 个不在当前选择范围内的文件。继续?',
cleanupComplete: '已从设备中删除 {{count}} 个文件。',
selectedSources: '已选来源',
noSourcesSelected: '未选择来源。点击浏览器中的项目以添加。',
clearAll: '全部清除',
tabPlaylists: '播放列表',
tabAlbums: '专辑',
tabArtists: '艺术家',
searchPlaceholder: '搜索…',
syncButton: '同步到设备',
actionTransfer: '传输到设备',
actionDelete: '从设备删除',
actionApplyAll: '应用所有更改',
templatePreview: '预览',
cancel: '取消',
noTargetDir: '请先选择目标文件夹。',
noSources: '请至少选择一个来源。',
noTracks: '所选来源中未找到曲目。',
fetchError: '从服务器加载曲目失败。',
syncComplete: '同步完成。',
dismiss: '关闭',
colName: '名称',
colType: '类型',
colStatus: '状态',
onDevice: '设备管理器',
addSources: '添加…',
syncResult: '已传输 {{done}}{{skipped}} 已是最新(共 {{total}}',
deleteFromDevice: '标记为删除({{count}}',
confirmDelete: '从设备删除 {{count}} 个项目:{{names}}',
deleteComplete: '已从设备删除 {{count}} 个项目。',
statusSynced: '已同步',
statusPending: '待处理',
statusDeletion: '删除中',
markForDeletion: '标记为删除',
removeSource: '移除',
undoDeletion: '撤销删除',
syncInBackground: '同步已在后台启动 — 您可以离开此页面。',
syncInProgress: '{{done}} / {{total}} 首曲目…',
syncSummary: '同步摘要',
calculating: '正在计算所需数据…',
filesToAdd: '要添加的文件:',
filesToDelete: '要删除的文件:',
netChange: '净变化:',
availableSpace: '可用磁盘空间:',
spaceWarning: '警告:目标设备的可用空间不足。',
proceed: '继续同步',
notEnoughSpace: '检测到物理磁盘空间不足!',
liveSearch: '实时',
randomAlbumsLabel: '随机专辑',
},
};
+4 -1
View File
@@ -6,11 +6,12 @@ import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../store/authStore';
import { useOfflineStore } from '../store/offlineStore';
import { useDownloadModalStore } from '../store/downloadModalStore';
import { usePlayerStore } from '../store/playerStore';
import { invoke } from '@tauri-apps/api/core';
import { join } from '@tauri-apps/api/path';
import { showToast } from '../utils/toast';
import { useZipDownloadStore } from '../store/zipDownloadStore';
import { X, CheckSquare2, Download, HardDriveDownload } from 'lucide-react';
import { X, CheckSquare2, Download, HardDriveDownload, ListMusic } from 'lucide-react';
type SortType = 'alphabeticalByName' | 'alphabeticalByArtist';
@@ -68,6 +69,7 @@ export default function Albums() {
};
const selectedAlbums = albums.filter(a => selectedIds.has(a.id));
const openContextMenu = usePlayerStore(state => state.openContextMenu);
const handleDownloadZips = async () => {
if (selectedAlbums.length === 0) return;
@@ -284,6 +286,7 @@ export default function Albums() {
selectionMode={selectionMode}
selected={selectedIds.has(a.id)}
onToggleSelect={toggleSelect}
selectedAlbums={selectedAlbums}
/>
))}
</div>
+131 -42
View File
@@ -1,7 +1,7 @@
import React, { useEffect, useState, useCallback } from 'react';
import React, { useEffect, useState, useCallback, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { getArtists, SubsonicArtist, buildCoverArtUrl, coverArtCacheKey } from '../api/subsonic';
import { LayoutGrid, List, Images, ChevronDown } from 'lucide-react';
import { LayoutGrid, List, Images, CheckSquare2, ListMusic, Check } from 'lucide-react';
import { usePlayerStore } from '../store/playerStore';
import { useAuthStore } from '../store/authStore';
import CachedImage from '../components/CachedImage';
@@ -81,25 +81,55 @@ export default function Artists() {
const [letterFilter, setLetterFilter] = useState(ALL_SENTINEL);
const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
const [visibleCount, setVisibleCount] = useState(50);
const showArtistImages = useAuthStore(s => s.showArtistImages);
const PAGE_SIZE = showArtistImages ? 50 : 100; // Menor con imágenes para reducir I/O
const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);
const [loadingMore, setLoadingMore] = useState(false);
const observerTarget = useRef<HTMLDivElement>(null);
const navigate = useNavigate();
const openContextMenu = usePlayerStore(state => state.openContextMenu);
const showArtistImages = useAuthStore(s => s.showArtistImages);
const setShowArtistImages = useAuthStore(s => s.setShowArtistImages);
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
// ── Multi-selection ──────────────────────────────────────────────────────
const [selectionMode, setSelectionMode] = useState(false);
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const toggleSelectionMode = () => {
setSelectionMode(v => !v);
setSelectedIds(new Set());
};
const toggleSelect = useCallback((id: string) => {
setSelectedIds(prev => {
const next = new Set(prev);
if (next.has(id)) next.delete(id); else next.add(id);
return next;
});
}, []);
const clearSelection = () => {
setSelectionMode(false);
setSelectedIds(new Set());
};
const selectedArtists = artists.filter(a => selectedIds.has(a.id));
useEffect(() => {
getArtists().then(data => { setArtists(data); setLoading(false); }).catch(() => setLoading(false));
}, [musicLibraryFilterVersion]);
const loadMore = useCallback(() => {
setVisibleCount(prev => prev + 50);
}, []);
if (loadingMore) return;
setLoadingMore(true);
setVisibleCount(prev => prev + PAGE_SIZE);
setTimeout(() => setLoadingMore(false), 100);
}, [loadingMore, PAGE_SIZE]);
// Reset infinite scroll when filters change
// Reset infinite scroll when filters or image setting change
useEffect(() => {
setVisibleCount(50);
}, [filter, letterFilter, viewMode]);
setVisibleCount(PAGE_SIZE);
}, [filter, letterFilter, viewMode, PAGE_SIZE]);
// Filter pipeline
let filtered = artists;
@@ -120,6 +150,16 @@ export default function Artists() {
const visible = filtered.slice(0, visibleCount);
const hasMore = visibleCount < filtered.length;
// Intersection Observer for infinite scroll (after hasMore declaration)
useEffect(() => {
const observer = new IntersectionObserver(
entries => { if (entries[0].isIntersecting) loadMore(); },
{ rootMargin: '200px' }
);
if (observerTarget.current) observer.observe(observerTarget.current);
return () => observer.disconnect();
}, [loadMore, hasMore]);
// Group by first letter (for list view)
const groups: Record<string, SubsonicArtist[]> = {};
visible.forEach(a => {
@@ -134,7 +174,11 @@ export default function Artists() {
<div className="content-body animate-fade-in">
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '1.5rem', flexWrap: 'wrap', gap: '1rem' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
<h1 className="page-title" style={{ marginBottom: 0 }}>{t('artists.title')}</h1>
<h1 className="page-title" style={{ marginBottom: 0 }}>
{selectionMode && selectedIds.size > 0
? t('artists.selectionCount', { count: selectedIds.size })
: t('artists.title')}
</h1>
<input
className="input"
style={{ maxWidth: 220 }}
@@ -146,30 +190,43 @@ export default function Artists() {
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
{!(selectionMode && selectedIds.size > 0) && (<>
<button
className={`btn btn-surface`}
onClick={() => setShowArtistImages(!showArtistImages)}
style={showArtistImages ? { background: 'var(--accent)', color: 'var(--ctp-crust)', padding: '0.5rem' } : { padding: '0.5rem' }}
data-tooltip={showArtistImages ? t('artists.imagesOn') : t('artists.imagesOff')}
data-tooltip-wrap
>
<Images size={20} />
</button>
<button
className={`btn btn-surface ${viewMode === 'grid' ? 'btn-sort-active' : ''}`}
onClick={() => setViewMode('grid')}
style={viewMode === 'grid' ? { background: 'var(--accent)', color: 'var(--ctp-crust)', padding: '0.5rem' } : { padding: '0.5rem' }}
data-tooltip={t('artists.gridView')}
>
<LayoutGrid size={20} />
</button>
<button
className={`btn btn-surface ${viewMode === 'list' ? 'btn-sort-active' : ''}`}
onClick={() => setViewMode('list')}
style={viewMode === 'list' ? { background: 'var(--accent)', color: 'var(--ctp-crust)', padding: '0.5rem' } : { padding: '0.5rem' }}
data-tooltip={t('artists.listView')}
>
<List size={20} />
</button>
</>
)}
<button
className={`btn btn-surface`}
onClick={() => setShowArtistImages(!showArtistImages)}
style={showArtistImages ? { background: 'var(--accent)', color: 'var(--ctp-crust)', padding: '0.5rem' } : { padding: '0.5rem' }}
data-tooltip={showArtistImages ? t('artists.imagesOn') : t('artists.imagesOff')}
data-tooltip-wrap
className={`btn btn-surface${selectionMode ? ' btn-sort-active' : ''}`}
onClick={toggleSelectionMode}
data-tooltip={selectionMode ? t('artists.cancelSelect') : t('artists.startSelect')}
data-tooltip-pos="bottom"
style={selectionMode ? { background: 'var(--accent)', color: 'var(--ctp-crust)' } : {}}
>
<Images size={20} />
</button>
<button
className={`btn btn-surface ${viewMode === 'grid' ? 'btn-sort-active' : ''}`}
onClick={() => setViewMode('grid')}
style={viewMode === 'grid' ? { background: 'var(--accent)', color: 'var(--ctp-crust)', padding: '0.5rem' } : { padding: '0.5rem' }}
data-tooltip={t('artists.gridView')}
>
<LayoutGrid size={20} />
</button>
<button
className={`btn btn-surface ${viewMode === 'list' ? 'btn-sort-active' : ''}`}
onClick={() => setViewMode('list')}
style={viewMode === 'list' ? { background: 'var(--accent)', color: 'var(--ctp-crust)', padding: '0.5rem' } : { padding: '0.5rem' }}
data-tooltip={t('artists.listView')}
>
<List size={20} />
<CheckSquare2 size={15} />
{selectionMode ? t('artists.cancelSelect') : t('artists.select')}
</button>
</div>
</div>
@@ -193,13 +250,33 @@ export default function Artists() {
{visible.map(artist => (
<div
key={artist.id}
className="artist-card"
onClick={() => navigate(`/artist/${artist.id}`)}
className={`artist-card${selectionMode && selectedIds.has(artist.id) ? ' selected' : ''}${selectionMode ? ' artist-card--selectable' : ''}`}
onClick={() => {
if (selectionMode) {
toggleSelect(artist.id);
} else {
navigate(`/artist/${artist.id}`);
}
}}
onContextMenu={(e) => {
e.preventDefault();
openContextMenu(e.clientX, e.clientY, artist, 'artist');
if (selectionMode && selectedIds.size > 0) {
openContextMenu(e.clientX, e.clientY, selectedArtists, 'multi-artist');
} else {
openContextMenu(e.clientX, e.clientY, artist, 'artist');
}
}}
style={selectionMode && selectedIds.has(artist.id) ? {
outline: '2px solid var(--accent)',
outlineOffset: '2px',
borderRadius: 'var(--radius-md)'
} : {}}
>
{selectionMode && (
<div className={`artist-card-select-check${selectedIds.has(artist.id) ? ' artist-card-select-check--on' : ''}`}>
{selectedIds.has(artist.id) && <Check size={14} strokeWidth={3} />}
</div>
)}
<ArtistCardAvatar artist={artist} showImages={showArtistImages} />
<div style={{ textAlign: 'center' }}>
<div className="artist-card-name">{artist.name}</div>
@@ -221,13 +298,27 @@ export default function Artists() {
{groups[letter].map(artist => (
<button
key={artist.id}
className="artist-row"
onClick={() => navigate(`/artist/${artist.id}`)}
className={`artist-row${selectionMode && selectedIds.has(artist.id) ? ' selected' : ''}`}
onClick={() => {
if (selectionMode) {
toggleSelect(artist.id);
} else {
navigate(`/artist/${artist.id}`);
}
}}
onContextMenu={(e) => {
e.preventDefault();
openContextMenu(e.clientX, e.clientY, artist, 'artist');
if (selectionMode && selectedIds.size > 0) {
openContextMenu(e.clientX, e.clientY, selectedArtists, 'multi-artist');
} else {
openContextMenu(e.clientX, e.clientY, artist, 'artist');
}
}}
id={`artist-${artist.id}`}
style={selectionMode && selectedIds.has(artist.id) ? {
background: 'var(--accent-dim)',
color: 'var(--accent)'
} : {}}
>
<ArtistRowAvatar artist={artist} showImages={showArtistImages} />
<div style={{ textAlign: 'left' }}>
@@ -245,10 +336,8 @@ export default function Artists() {
)}
{!loading && hasMore && (
<div style={{ marginTop: 32, marginBottom: '2rem', display: 'flex', justifyContent: 'center' }}>
<button className="btn btn-primary" onClick={loadMore}>
<ChevronDown size={16} /> {t('artists.loadMore')}
</button>
<div ref={observerTarget} style={{ height: '20px', margin: '2rem 0', display: 'flex', justifyContent: 'center' }}>
{loadingMore && <div className="spinner" style={{ width: 20, height: 20 }} />}
</div>
)}
+911
View File
@@ -0,0 +1,911 @@
import React, { useEffect, useState, useRef, useCallback, useMemo } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import { open as openDialog } from '@tauri-apps/plugin-dialog';
import {
HardDriveUpload, FolderOpen, Loader2,
ListMusic, Disc3, Users, CheckCircle2, AlertCircle, Clock,
ChevronRight, ChevronDown, Trash2, Undo2, Search, Usb, RefreshCw, Shuffle, Zap,
} from 'lucide-react';
import CustomSelect from '../components/CustomSelect';
import { useTranslation } from 'react-i18next';
import { useDeviceSyncStore, DeviceSyncSource } from '../store/deviceSyncStore';
import { useDeviceSyncJobStore } from '../store/deviceSyncJobStore';
import {
getPlaylists, getAlbumList, getArtists, getAlbum, getPlaylist, getArtist,
buildDownloadUrl, search as searchSubsonic,
SubsonicSong, SubsonicAlbum, SubsonicPlaylist, SubsonicArtist,
} from '../api/subsonic';
import { showToast } from '../utils/toast';
type SourceTab = 'playlists' | 'albums' | 'artists';
// ─── helpers ─────────────────────────────────────────────────────────────────
function uuid(): string { return crypto.randomUUID(); }
async function fetchTracksForSource(source: DeviceSyncSource): Promise<SubsonicSong[]> {
if (source.type === 'playlist') { const { songs } = await getPlaylist(source.id); return songs; }
if (source.type === 'album') { const { songs } = await getAlbum(source.id); return songs; }
const { albums } = await getArtist(source.id);
const all: SubsonicSong[] = [];
for (const album of albums) { const { songs } = await getAlbum(album.id); all.push(...songs); }
return all;
}
function trackToSyncInfo(track: SubsonicSong, url: string) {
return {
id: track.id, url,
suffix: track.suffix ?? 'mp3',
artist: track.artist ?? '',
album: track.album ?? '',
title: track.title ?? '',
trackNumber: track.track,
discNumber: track.discNumber,
year: track.year,
};
}
type SyncStatus = 'synced' | 'pending' | 'deletion';
interface RemovableDrive {
name: string;
mount_point: string;
available_space: number;
total_space: number;
file_system: string;
is_removable: boolean;
}
function formatBytes(bytes: number): string {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${(bytes / Math.pow(k, i)).toFixed(1)} ${sizes[i]}`;
}
// ─── component ───────────────────────────────────────────────────────────────
export default function DeviceSync() {
const { t } = useTranslation();
const targetDir = useDeviceSyncStore(s => s.targetDir);
const filenameTemplate = useDeviceSyncStore(s => s.filenameTemplate);
const sources = useDeviceSyncStore(s => s.sources);
const checkedIds = useDeviceSyncStore(s => s.checkedIds);
const pendingDeletion = useDeviceSyncStore(s => s.pendingDeletion);
const deviceFilePaths = useDeviceSyncStore(s => s.deviceFilePaths);
const scanning = useDeviceSyncStore(s => s.scanning);
const {
setTargetDir, setFilenameTemplate, addSource, removeSource,
clearSources, toggleChecked, setCheckedIds, markForDeletion,
unmarkDeletion, removeSources, setDeviceFilePaths, setScanning,
} = useDeviceSyncStore.getState();
const jobStatus = useDeviceSyncJobStore(s => s.status);
const jobDone = useDeviceSyncJobStore(s => s.done);
const jobSkip = useDeviceSyncJobStore(s => s.skipped);
const jobFail = useDeviceSyncJobStore(s => s.failed);
const jobTotal = useDeviceSyncJobStore(s => s.total);
const [activeTab, setActiveTab] = useState<SourceTab>('albums');
const [search, setSearch] = useState('');
const [playlists, setPlaylists] = useState<SubsonicPlaylist[]>([]);
const [randomAlbums, setRandomAlbums] = useState<SubsonicAlbum[]>([]);
const [albumSearchResults, setAlbumSearchResults] = useState<SubsonicAlbum[]>([]);
const [albumSearchLoading, setAlbumSearchLoading] = useState(false);
const [artists, setArtists] = useState<SubsonicArtist[]>([]);
const [loadingBrowser, setLoadingBrowser] = useState(false);
const [expandedArtistIds, setExpandedArtistIds] = useState<Set<string>>(new Set());
const [artistAlbumsMap, setArtistAlbumsMap] = useState<Map<string, SubsonicAlbum[]>>(new Map());
const [loadingArtistIds, setLoadingArtistIds] = useState<Set<string>>(new Set());
// Map source IDs → computed device paths (for status derivation)
const [sourcePathsMap, setSourcePathsMap] = useState<Map<string, string[]>>(new Map());
// ─── Removable drive detection ──────────────────────────────────────────
const [drives, setDrives] = useState<RemovableDrive[]>([]);
const [drivesLoading, setDrivesLoading] = useState(false);
const [preSyncOpen, setPreSyncOpen] = useState(false);
const [preSyncLoading, setPreSyncLoading] = useState(false);
const [syncDelta, setSyncDelta] = useState({ addBytes: 0, addCount: 0, delBytes: 0, delCount: 0, availableBytes: 0, tracks: [] as SubsonicSong[] });
const refreshDrives = useCallback(async () => {
setDrivesLoading(true);
try {
const result = await invoke<RemovableDrive[]>('get_removable_drives');
setDrives(result);
} catch {
setDrives([]);
} finally {
setDrivesLoading(false);
}
}, []);
// Fetch drives on mount, then poll every 5 seconds
useEffect(() => {
refreshDrives();
const interval = setInterval(refreshDrives, 5000);
return () => clearInterval(interval);
}, [refreshDrives]);
// Detect if the current targetDir is on a detected removable drive
const activeDrive = useMemo(() => {
if (!targetDir) return null;
return drives.find(d => targetDir.startsWith(d.mount_point)) ?? null;
}, [targetDir, drives]);
const driveDetected = activeDrive !== null;
const isRunning = jobStatus === 'running';
// ─── Device scan on mount ───────────────────────────────────────────────
const scanDevice = useCallback(async () => {
if (!targetDir || sources.length === 0) {
setDeviceFilePaths([]);
return;
}
setScanning(true);
try {
const files = await invoke<string[]>('list_device_dir_files', { dir: targetDir });
setDeviceFilePaths(files);
} catch {
setDeviceFilePaths([]);
} finally {
setScanning(false);
}
}, [targetDir, sources.length]);
// Scan device on mount and when targetDir changes
useEffect(() => { scanDevice(); }, [scanDevice]);
// Compute expected paths for each source (for status comparison)
useEffect(() => {
if (!targetDir || sources.length === 0) {
setSourcePathsMap(new Map());
return;
}
let cancelled = false;
(async () => {
const map = new Map<string, string[]>();
await Promise.all(sources.map(async source => {
if (cancelled) return;
try {
const tracks = await fetchTracksForSource(source);
const paths = await invoke<string[]>('compute_sync_paths', {
tracks: tracks.map(t => trackToSyncInfo(t, '')),
destDir: targetDir,
template: filenameTemplate,
});
map.set(source.id, paths);
} catch {
map.set(source.id, []);
}
}));
if (!cancelled) setSourcePathsMap(map);
})();
return () => { cancelled = true; };
}, [targetDir, filenameTemplate, sources]);
// Derive sync status per source
const sourceStatuses = useMemo(() => {
const deviceSet = new Set(deviceFilePaths);
const statuses = new Map<string, SyncStatus>();
for (const source of sources) {
if (pendingDeletion.includes(source.id)) {
statuses.set(source.id, 'deletion');
} else {
const paths = sourcePathsMap.get(source.id) ?? [];
const allSynced = paths.length > 0 && paths.every(p => deviceSet.has(p));
statuses.set(source.id, allSynced ? 'synced' : 'pending');
}
}
return statuses;
}, [sources, pendingDeletion, sourcePathsMap, deviceFilePaths]);
// ─── Desired State / Diff Logic ─────────────────────────────────────────
const handleToggleSource = useCallback((source: DeviceSyncSource) => {
const isSelected = sources.some(s => s.id === source.id);
const isPendingDeletion = pendingDeletion.includes(source.id);
const isActuallySelected = isSelected && !isPendingDeletion;
if (isActuallySelected) {
// User initiated a DE-SELECTION. Diff check against target device
const isSynced = sourceStatuses.get(source.id) === 'synced';
const pathsOnDisk = sourcePathsMap.get(source.id)?.filter(p => deviceFilePaths.includes(p)).length || 0;
if (pathsOnDisk > 0 || isSynced) {
// Source currently has physical footprint. Stage for deletion.
markForDeletion([source.id]);
} else {
// Zero physical footprint. Strip safely.
removeSource(source.id);
}
} else {
// User initiated a SELECTION.
if (isPendingDeletion) {
unmarkDeletion(source.id); // Cancel queued red/strikethrough state
} else if (!isSelected) {
addSource(source); // Trigger clean pending install state
}
}
}, [sources, pendingDeletion, sourceStatuses, sourcePathsMap, deviceFilePaths, markForDeletion, removeSource, unmarkDeletion, addSource]);
// ─── Listen for background sync events ──────────────────────────────────
useEffect(() => {
const jobStore = useDeviceSyncJobStore.getState;
const unlistenProgress = listen<{
jobId: string; done: number; skipped: number; failed: number; total: number;
}>('device:sync:progress', ({ payload }) => {
const current = jobStore();
if (current.jobId && payload.jobId === current.jobId) {
useDeviceSyncJobStore.getState().updateProgress(
payload.done, payload.skipped, payload.failed
);
}
});
const unlistenComplete = listen<{
jobId: string; done: number; skipped: number; failed: number; total: number;
}>('device:sync:complete', ({ payload }) => {
const current = jobStore();
if (current.jobId && payload.jobId === current.jobId) {
useDeviceSyncJobStore.getState().complete(
payload.done, payload.skipped, payload.failed
);
showToast(
t('deviceSync.syncResult', {
done: payload.done, skipped: payload.skipped, total: payload.total
}),
5000, 'info'
);
// Re-scan the device after sync completes
scanDevice();
}
});
return () => {
unlistenProgress.then(f => f());
unlistenComplete.then(f => f());
};
}, [t, scanDevice]);
// Load browser data when tab switches
useEffect(() => {
setSearch('');
if (activeTab === 'playlists' && playlists.length === 0) loadPlaylists();
if (activeTab === 'albums' && randomAlbums.length === 0) loadRandomAlbums();
if (activeTab === 'artists' && artists.length === 0) loadArtists();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeTab]);
// Live album search with 300ms debounce
useEffect(() => {
if (activeTab !== 'albums') return;
const q = search.trim();
if (!q) { setAlbumSearchResults([]); return; }
setAlbumSearchLoading(true);
const timer = setTimeout(async () => {
try {
const { albums } = await searchSubsonic(q, { albumCount: 20, artistCount: 0, songCount: 0 });
setAlbumSearchResults(albums);
} catch {
setAlbumSearchResults([]);
} finally {
setAlbumSearchLoading(false);
}
}, 300);
return () => { clearTimeout(timer); setAlbumSearchLoading(false); };
}, [search, activeTab]);
const loadPlaylists = useCallback(async () => {
setLoadingBrowser(true);
try { setPlaylists(await getPlaylists()); } catch { /* ignore */ }
finally { setLoadingBrowser(false); }
}, []);
const loadRandomAlbums = useCallback(async () => {
setLoadingBrowser(true);
try { setRandomAlbums(await getAlbumList('random', 10)); } catch { /* ignore */ }
finally { setLoadingBrowser(false); }
}, []);
const loadArtists = useCallback(async () => {
setLoadingBrowser(true);
try { setArtists(await getArtists()); } catch { /* ignore */ }
finally { setLoadingBrowser(false); }
}, []);
const toggleArtistExpand = useCallback(async (artistId: string) => {
setExpandedArtistIds(prev => {
const next = new Set(prev);
if (next.has(artistId)) { next.delete(artistId); return next; }
next.add(artistId);
return next;
});
if (!artistAlbumsMap.has(artistId)) {
setLoadingArtistIds(prev => new Set(prev).add(artistId));
try {
const { albums } = await getArtist(artistId);
setArtistAlbumsMap(prev => new Map(prev).set(artistId, albums));
} finally {
setLoadingArtistIds(prev => { const n = new Set(prev); n.delete(artistId); return n; });
}
}
}, [artistAlbumsMap]);
const q = search.toLowerCase();
const filteredPlaylists = useMemo(() => playlists.filter(p => p.name.toLowerCase().includes(q)), [playlists, q]);
const filteredArtists = useMemo(() => artists.filter(a => a.name.toLowerCase().includes(q)), [artists, q]);
const handleChooseFolder = async () => {
const sel = await openDialog({ directory: true, multiple: false, title: t('deviceSync.chooseFolder') });
if (sel) {
setTargetDir(sel as string);
// Trigger a device scan after folder change
setTimeout(() => scanDevice(), 100);
}
};
// ─── Sync (non-blocking) ────────────────────────────────────────────────
const promptSyncSummary = async () => {
if (!targetDir) { showToast(t('deviceSync.noTargetDir'), 3000, 'error'); return; }
if (sources.length === 0){ showToast(t('deviceSync.noSources'), 3000, 'error'); return; }
setPreSyncLoading(true);
setPreSyncOpen(true);
try {
const { getClient } = await import('../api/subsonic');
const { baseUrl, params } = getClient();
const payload = await invoke<{
addBytes: number; addCount: number; delBytes: number; delCount: number; availableBytes: number; tracks: SubsonicSong[];
}>('calculate_sync_payload', {
sources,
deletionIds: pendingDeletion,
auth: { baseUrl, ...params },
targetDir,
template: filenameTemplate,
});
setSyncDelta(payload);
} catch {
showToast(t('deviceSync.fetchError'), 3000, 'error');
setPreSyncOpen(false);
} finally {
setPreSyncLoading(false);
}
};
const handleSyncExecution = async () => {
setPreSyncOpen(false);
// 1. Handle pending deletions first
const deletionSources = sources.filter(s => pendingDeletion.includes(s.id));
if (deletionSources.length > 0) {
try {
const allPaths: string[] = [];
const trackArrays = await Promise.all(deletionSources.map(s => fetchTracksForSource(s)));
const deletionTracks = trackArrays.flat();
const paths = await invoke<string[]>('compute_sync_paths', {
tracks: deletionTracks.map(t => trackToSyncInfo(t, '')),
destDir: targetDir,
template: filenameTemplate,
});
allPaths.push(...paths);
await invoke<number>('delete_device_files', { paths: allPaths });
removeSources(deletionSources.map(s => s.id));
showToast(
t('deviceSync.deleteComplete', { count: deletionSources.length }),
3000, 'info'
);
} catch {
showToast(t('deviceSync.fetchError'), 3000, 'error');
}
}
const allTracks = syncDelta.tracks;
if (allTracks.length === 0) {
scanDevice();
return;
}
const jobId = uuid();
useDeviceSyncJobStore.getState().startSync(jobId, allTracks.length);
showToast(t('deviceSync.syncInBackground'), 3000, 'info');
invoke('sync_batch_to_device', {
tracks: allTracks.map(track => trackToSyncInfo(track, buildDownloadUrl(track.id))),
destDir: targetDir,
template: filenameTemplate,
jobId,
expectedBytes: syncDelta.addBytes,
}).catch((err: string) => {
useDeviceSyncJobStore.getState().complete(0, 0, allTracks.length);
if (err.includes('NOT_ENOUGH_SPACE')) {
showToast(t('deviceSync.notEnoughSpace'), 5000, 'error');
} else if (err === 'NOT_MOUNTED_VOLUME') {
showToast(t('deviceSync.notMountedVolume'), 5000, 'error');
} else {
showToast(t('deviceSync.fetchError'), 3000, 'error');
}
});
};
// ─── Actions ────────────────────────────────────────────────────────────
const handleMarkCheckedForDeletion = () => {
if (checkedIds.length === 0) return;
markForDeletion(checkedIds);
};
const allChecked = sources.length > 0 && sources.every(s => checkedIds.includes(s.id));
const toggleAll = () => setCheckedIds(allChecked ? [] : sources.map(s => s.id));
const pendingCount = Array.from(sourceStatuses.values()).filter(s => s === 'pending').length;
const syncedCount = Array.from(sourceStatuses.values()).filter(s => s === 'synced').length;
const deletionCount = pendingDeletion.length;
// ─── Dynamic action button label ────────────────────────────────────────
const actionButtonLabel = useMemo(() => {
if (deletionCount > 0 && pendingCount === 0) return t('deviceSync.actionDelete');
if (pendingCount > 0 && deletionCount === 0) return t('deviceSync.actionTransfer');
if (pendingCount > 0 && deletionCount > 0) return t('deviceSync.actionApplyAll');
return t('deviceSync.syncButton'); // both zero — button will be disabled
}, [pendingCount, deletionCount, t]);
const actionButtonDisabled =
!targetDir ||
sources.length === 0 ||
isRunning ||
(!driveDetected && !!targetDir) ||
(pendingCount === 0 && deletionCount === 0);
// ─── Template preview (dummy track) ─────────────────────────────────────
const PREVIEW_TRACK = {
artist: 'Volker Pispers',
album: '...Bis Neulich 2007',
title: 'Kapitalismus',
track_number: '01',
disc_number: '1',
year: '2007',
} as const;
const templatePreviewText = useMemo(() => {
try {
const result = filenameTemplate
.replace(/\{artist\}/g, PREVIEW_TRACK.artist)
.replace(/\{album\}/g, PREVIEW_TRACK.album)
.replace(/\{title\}/g, PREVIEW_TRACK.title)
.replace(/\{track_number\}/g, PREVIEW_TRACK.track_number)
.replace(/\{disc_number\}/g, PREVIEW_TRACK.disc_number)
.replace(/\{year\}/g, PREVIEW_TRACK.year);
return `${result}.mp3`;
} catch {
return '';
}
}, [filenameTemplate]);
const tabs: { key: SourceTab; icon: React.ReactNode; label: string }[] = [
{ key: 'playlists', icon: <ListMusic size={14} />, label: t('deviceSync.tabPlaylists') },
{ key: 'albums', icon: <Disc3 size={14} />, label: t('deviceSync.tabAlbums') },
{ key: 'artists', icon: <Users size={14} />, label: t('deviceSync.tabArtists') },
];
return (
<div className="device-sync-page">
{/* ── Header ── */}
<div className="device-sync-header">
<div className="device-sync-header-title">
<HardDriveUpload size={20} />
<h1>{t('deviceSync.title')}</h1>
</div>
<div className="device-sync-config-row">
{/* ── Left: Template ── */}
<div className="device-sync-template-section">
<span className="device-sync-label-inline">{t('deviceSync.filenameTemplate')}</span>
<div className="device-sync-template-input-wrap">
<input
className="input device-sync-template-input"
value={filenameTemplate}
onChange={e => setFilenameTemplate(e.target.value)}
spellCheck={false}
data-tooltip={t('deviceSync.templateHint')}
data-tooltip-pos="bottom"
/>
{templatePreviewText && (
<span className="device-sync-template-preview">
{t('deviceSync.templatePreview')}: {templatePreviewText}
</span>
)}
</div>
</div>
{/* ── Right: Drive config ── */}
<div className="device-sync-target-section">
<span className="device-sync-label-inline">{t('deviceSync.targetDevice')}</span>
<div className="device-sync-header-config">
<div className="device-sync-drive-layout">
{/* Row 1: Controls */}
<div className="device-sync-drive-controls">
{/* Fallback manual folder picker & Refresh */}
<button className="btn btn-ghost" onClick={handleChooseFolder} data-tooltip={t('deviceSync.browseManual')}>
<FolderOpen size={18} />
</button>
<button
className="btn btn-ghost device-sync-refresh-btn"
onClick={refreshDrives}
disabled={drivesLoading}
data-tooltip={t('deviceSync.refreshDrives')}
>
<RefreshCw size={18} className={drivesLoading ? 'spin' : ''} />
</button>
{/* Dropdown element */}
{drives.length > 0 ? (
<>
<Usb size={18} className="device-sync-drive-icon" />
<CustomSelect
className="input device-sync-drive-select"
value={targetDir ?? ''}
onChange={v => {
setTargetDir(v);
if (v) {
setTimeout(() => scanDevice(), 100);
}
}}
options={[
{ value: '', label: t('deviceSync.selectDrive') },
...drives.map(d => ({ value: d.mount_point, label: d.name || d.mount_point }))
]}
/>
</>
) : (
<span className="device-sync-no-drives">
<AlertCircle size={18} />
{t('deviceSync.noDrivesDetected')}
</span>
)}
</div>
{/* Row 2: Metadata */}
{activeDrive && (
<div className="device-sync-drive-meta">
{formatBytes(activeDrive.available_space)} {t('deviceSync.free')} / {formatBytes(activeDrive.total_space)} &bull; {activeDrive.file_system}
</div>
)}
</div>
</div>
</div>
</div>
</div>
{/* ── Main ── */}
<div className="device-sync-main">
{/* ── Browser (left) ── */}
<div className="device-sync-browser">
<div className="device-sync-tabs">
{tabs.map(tab => (
<button
key={tab.key}
className={`device-sync-tab${activeTab === tab.key ? ' active' : ''}`}
onClick={() => setActiveTab(tab.key)}
>
{tab.icon}{tab.label}
</button>
))}
</div>
<div className="device-sync-search-wrap">
<input
className="input"
placeholder={t('deviceSync.searchPlaceholder')}
value={search}
onChange={e => setSearch(e.target.value)}
/>
{activeTab === 'albums' && (
<span className="device-sync-live-badge">
<Zap size={10} />{t('deviceSync.liveSearch')}
</span>
)}
</div>
<div className="device-sync-list">
{(loadingBrowser || albumSearchLoading) && (
<div className="device-sync-loading"><Loader2 size={16} className="spin" /></div>
)}
{activeTab === 'albums' && !search.trim() && !loadingBrowser && randomAlbums.length > 0 && (
<div className="device-sync-section-label">
<Shuffle size={11} />{t('deviceSync.randomAlbumsLabel')}
</div>
)}
{activeTab === 'playlists' && filteredPlaylists.map(pl => (
<BrowserRow key={pl.id} name={pl.name} meta={`${pl.songCount} tracks`}
selected={sources.some(s => s.id === pl.id) && !pendingDeletion.includes(pl.id)}
onToggle={() => handleToggleSource({ type: 'playlist', id: pl.id, name: pl.name })} />
))}
{activeTab === 'albums' && (search.trim() ? albumSearchResults : randomAlbums).map(al => (
<BrowserRow key={al.id} name={al.name} meta={al.artist}
selected={sources.some(s => s.id === al.id) && !pendingDeletion.includes(al.id)}
onToggle={() => handleToggleSource({ type: 'album', id: al.id, name: al.name })} />
))}
{activeTab === 'artists' && filteredArtists.map(ar => (
<React.Fragment key={ar.id}>
<div className="device-sync-artist-row">
<button
className="device-sync-expand-btn"
onClick={() => toggleArtistExpand(ar.id)}
>
{loadingArtistIds.has(ar.id)
? <Loader2 size={13} className="spin" />
: expandedArtistIds.has(ar.id)
? <ChevronDown size={13} />
: <ChevronRight size={13} />}
</button>
<span className="device-sync-row-name">{ar.name}</span>
{ar.albumCount != null &&
<span className="device-sync-row-meta">{ar.albumCount} Albums</span>}
</div>
{expandedArtistIds.has(ar.id) && artistAlbumsMap.has(ar.id) &&
artistAlbumsMap.get(ar.id)!.map(al => (
<BrowserRow key={al.id} name={al.name} meta={al.year?.toString()}
selected={sources.some(s => s.id === al.id) && !pendingDeletion.includes(al.id)}
indent
onToggle={() => handleToggleSource({ type: 'album', id: al.id, name: al.name })} />
))
}
</React.Fragment>
))}
</div>
</div>
{/* ── Device Manager (right) ── */}
<div className="device-sync-device-panel">
<div className="device-sync-panel-header">
<span className="device-sync-panel-title">
{t('deviceSync.onDevice')}
{scanning && <Loader2 size={12} className="spin" style={{ marginLeft: 6 }} />}
</span>
<div className="device-sync-panel-actions">
{/* Sync button */}
<button
className="btn btn-surface"
onClick={promptSyncSummary}
disabled={actionButtonDisabled}
>
{isRunning
? <><Loader2 size={13} className="spin" /> {jobDone + jobSkip + jobFail}/{jobTotal}</>
: <>
{deletionCount > 0 && pendingCount === 0
? <Trash2 size={13} />
: <HardDriveUpload size={13} />}
{actionButtonLabel}
</>
}
</button>
{/* Mark for deletion */}
{checkedIds.length > 0 && !isRunning && (
<button
className="btn btn-danger"
onClick={handleMarkCheckedForDeletion}
>
<Trash2 size={13} />
{t('deviceSync.deleteFromDevice', { count: checkedIds.length })}
</button>
)}
</div>
</div>
{/* Status summary badges */}
{sources.length > 0 && (
<div className="device-sync-status-summary">
{syncedCount > 0 && (
<span className="device-sync-badge synced">
<CheckCircle2 size={11} /> {syncedCount} {t('deviceSync.statusSynced')}
</span>
)}
{pendingCount > 0 && (
<span className="device-sync-badge pending">
<Clock size={11} /> {pendingCount} {t('deviceSync.statusPending')}
</span>
)}
{deletionCount > 0 && (
<span className="device-sync-badge deletion">
<Trash2 size={11} /> {deletionCount} {t('deviceSync.statusDeletion')}
</span>
)}
</div>
)}
{sources.length === 0 ? (
<p className="device-sync-empty">{t('deviceSync.noSourcesSelected')}</p>
) : (
<>
<div className="device-sync-list-header">
<label className="device-sync-check-label">
<input type="checkbox" checked={allChecked} onChange={toggleAll} />
</label>
<span className="device-sync-list-col-name">{t('deviceSync.colName')}</span>
<span className="device-sync-list-col-type">{t('deviceSync.colType')}</span>
<span className="device-sync-list-col-status">{t('deviceSync.colStatus')}</span>
<span className="device-sync-list-col-actions" />
</div>
<div className="device-sync-device-list">
{sources.map(s => {
const status = sourceStatuses.get(s.id) ?? 'pending';
return (
<label
key={s.id}
className={`device-sync-device-row ${status}${checkedIds.includes(s.id) ? ' checked' : ''}`}
>
<input
type="checkbox"
checked={checkedIds.includes(s.id)}
onChange={() => toggleChecked(s.id)}
disabled={status === 'deletion'}
/>
<span className="device-sync-row-name">{s.name}</span>
<span className="device-sync-source-type">{s.type}</span>
<span className={`device-sync-status-icon ${status}`}>
{status === 'synced' && <CheckCircle2 size={13} />}
{status === 'pending' && <Clock size={13} />}
{status === 'deletion' && <Trash2 size={13} />}
</span>
<span className="device-sync-row-actions">
{status === 'synced' && (
<button
className="device-sync-action-btn danger"
onClick={e => { e.preventDefault(); markForDeletion([s.id]); }}
data-tooltip={t('deviceSync.markForDeletion')}
>
<Trash2 size={12} />
</button>
)}
{status === 'pending' && (
<button
className="device-sync-action-btn muted"
onClick={e => { e.preventDefault(); handleToggleSource(s); }}
data-tooltip={t('deviceSync.removeSource')}
>
<Trash2 size={12} />
</button>
)}
{status === 'deletion' && (
<button
className="device-sync-action-btn undo"
onClick={e => { e.preventDefault(); unmarkDeletion(s.id); }}
data-tooltip={t('deviceSync.undoDeletion')}
>
<Undo2 size={12} />
</button>
)}
</span>
</label>
);
})}
</div>
</>
)}
{/* Background sync progress (non-blocking) */}
{jobStatus === 'running' && (
<div className="device-sync-bg-progress">
<div className="device-sync-bg-progress-bar-wrap">
<div
className="device-sync-bg-progress-bar"
style={{ width: jobTotal > 0
? `${((jobDone + jobSkip + jobFail) / jobTotal) * 100}%`
: '0%' }}
/>
</div>
<span className="device-sync-bg-progress-text">
<Loader2 size={12} className="spin" />
{t('deviceSync.syncInProgress', { done: jobDone + jobSkip, total: jobTotal })}
{jobFail > 0 && <span className="device-sync-stat-error"><AlertCircle size={11} /> {jobFail}</span>}
</span>
</div>
)}
{jobStatus === 'done' && (
<div className="device-sync-bg-progress done">
<span className="device-sync-bg-progress-text">
<CheckCircle2 size={12} className="color-success" />
{t('deviceSync.syncResult', { done: jobDone, skipped: jobSkip, total: jobTotal })}
</span>
<button className="btn btn-ghost" onClick={() => useDeviceSyncJobStore.getState().reset()}>
{t('deviceSync.dismiss')}
</button>
</div>
)}
</div>
</div>
{/* Pre-Sync Summary Modal */}
{preSyncOpen && (
<div className="modal-overlay">
<div className="modal-content device-sync-modal">
<h2 className="modal-title">{t('deviceSync.syncSummary')}</h2>
{preSyncLoading ? (
<div className="device-sync-loading-modal" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', margin: '20px' }}>
<Loader2 size={32} className="spin" />
<p style={{ marginTop: '10px' }}>{t('deviceSync.calculating')}</p>
</div>
) : (
<div className="device-sync-summary-stats" style={{ display: 'flex', flexDirection: 'column', gap: '8px', margin: '10px 0' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0' }}>
<span>{t('deviceSync.filesToAdd')}</span>
<span className="color-success">+{syncDelta.addCount} ({(syncDelta.addBytes / 1_048_576).toFixed(1)} MB)</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0' }}>
<span>{t('deviceSync.filesToDelete')}</span>
<span className="color-error">-{syncDelta.delCount} ({(syncDelta.delBytes / 1_048_576).toFixed(1)} MB)</span>
</div>
<hr style={{ border: 'none', borderTop: '1px solid var(--border)', margin: '10px 0' }} />
<div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 'bold' }}>
<span>{t('deviceSync.netChange')}</span>
<span>{((syncDelta.addBytes - syncDelta.delBytes) / 1_048_576).toFixed(1)} MB</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 'bold', color: syncDelta.addBytes > syncDelta.availableBytes + syncDelta.delBytes ? 'var(--danger)' : 'inherit', marginTop: '10px' }}>
<span>{t('deviceSync.availableSpace')}</span>
<span>{(syncDelta.availableBytes / 1_048_576).toFixed(1)} MB</span>
</div>
{syncDelta.addBytes > syncDelta.availableBytes + syncDelta.delBytes && (
<div className="sync-warning error" style={{ background: 'color-mix(in srgb, var(--danger) 15%, transparent)', padding: '10px', borderRadius: 'var(--radius-md)', marginTop: '15px', display: 'flex', gap: '10px', color: 'var(--danger)', alignItems: 'flex-start' }}>
<AlertCircle size={16} style={{ flexShrink: 0, marginTop: '2px' }} />
<span>{t('deviceSync.spaceWarning')}</span>
</div>
)}
</div>
)}
{!preSyncLoading && (
<div className="modal-actions" style={{ display: 'flex', justifyContent: 'flex-end', gap: '10px', marginTop: '25px' }}>
<button className="btn btn-ghost" onClick={() => setPreSyncOpen(false)}>
{t('deviceSync.cancel')}
</button>
<button
className="btn btn-primary"
onClick={handleSyncExecution}
disabled={syncDelta.addBytes > syncDelta.availableBytes + syncDelta.delBytes}
>
{t('deviceSync.proceed')}
</button>
</div>
)}
</div>
</div>
)}
</div>
);
}
// ─── BrowserRow ──────────────────────────────────────────────────────────────
function BrowserRow({ name, meta, selected, onToggle, indent }: {
name: string; meta?: string; selected: boolean; onToggle: () => void; indent?: boolean;
}) {
return (
<button className={`device-sync-browser-row${selected ? ' selected' : ''}${indent ? ' indent' : ''}`} onClick={onToggle}>
<span className="device-sync-row-check">
{selected ? <CheckCircle2 size={14} /> : <span className="device-sync-row-circle" />}
</span>
<span className="device-sync-row-name">{name}</span>
{meta && <span className="device-sync-row-meta">{meta}</span>}
</button>
);
}
+208 -33
View File
@@ -66,12 +66,44 @@ function entryToTrack(e: SubsonicDirectoryEntry): Track {
};
}
function isFolderBrowserArrowKey(e: React.KeyboardEvent): boolean {
return (
e.key === 'ArrowUp' ||
e.key === 'ArrowDown' ||
e.key === 'ArrowLeft' ||
e.key === 'ArrowRight' ||
e.code === 'ArrowUp' ||
e.code === 'ArrowDown' ||
e.code === 'ArrowLeft' ||
e.code === 'ArrowRight'
);
}
/** Modifiers from native event + getModifierState (WebKit/WebView can miss flags on the synthetic event). */
function folderBrowserHasKeyModifiers(e: React.KeyboardEvent): boolean {
const n = e.nativeEvent;
if (n.ctrlKey || n.altKey || n.shiftKey || n.metaKey) return true;
if (typeof n.getModifierState === 'function') {
return (
n.getModifierState('Control') ||
n.getModifierState('Alt') ||
n.getModifierState('Shift') ||
n.getModifierState('Meta') ||
n.getModifierState('OS')
);
}
return false;
}
export default function FolderBrowser() {
const { t } = useTranslation();
const [columns, setColumns] = useState<Column[]>([]);
const [columnFilters, setColumnFilters] = useState<Record<number, string>>({});
const [filterFocusCol, setFilterFocusCol] = useState<number | null>(null);
const [keyboardNavActive, setKeyboardNavActive] = useState(false);
const [playingPathIds, setPlayingPathIds] = useState<string[]>(persistedPlayingPathIds);
const wrapperRef = useRef<HTMLDivElement>(null);
const filterInputRefs = useRef<Record<number, HTMLInputElement | null>>({});
const pendingNavColRef = useRef<number | null>(null);
const autoResolvedTrackRef = useRef<string | null>(null);
const prevTrackIdRef = useRef<string | null>(null);
@@ -83,6 +115,7 @@ export default function FolderBrowser() {
const currentTrack = usePlayerStore(s => s.currentTrack);
const isPlaying = usePlayerStore(s => s.isPlaying);
const playTrack = usePlayerStore(s => s.playTrack);
const enqueue = usePlayerStore(s => s.enqueue);
const openContextMenu = usePlayerStore(s => s.openContextMenu);
const isContextMenuOpen = usePlayerStore(s => s.contextMenu.isOpen);
@@ -179,6 +212,20 @@ export default function FolderBrowser() {
return () => window.removeEventListener('mousemove', onMouseMove);
}, [keyboardNavActive]);
useEffect(() => {
setColumnFilters(prev => {
const next: Record<number, string> = {};
let changed = false;
Object.entries(prev).forEach(([k, v]) => {
const idx = Number(k);
if (idx < columns.length) next[idx] = v;
else changed = true;
});
return changed ? next : prev;
});
setFilterFocusCol(prev => (prev !== null && prev >= columns.length ? null : prev));
}, [columns.length]);
useEffect(() => {
if (!isContextMenuOpen) setContextAnchorPos(null);
}, [isContextMenuOpen]);
@@ -218,18 +265,31 @@ export default function FolderBrowser() {
persistedPlayingPathIds = playingPathIds;
}, [playingPathIds]);
const preferredRowIndex = useCallback((col: Column): number => {
if (col.items.length === 0) return -1;
if (col.selectedId) {
const selectedIdx = col.items.findIndex(it => it.id === col.selectedId);
const filteredItemsByCol = useMemo(() => {
return columns.map((col, colIndex) => {
const query = (columnFilters[colIndex] ?? '').trim().toLowerCase();
if (!query) return col.items;
return col.items.filter(item => {
const haystack = `${item.title} ${item.artist ?? ''} ${item.album ?? ''}`.toLowerCase();
return haystack.includes(query);
});
});
}, [columns, columnFilters]);
const preferredRowIndex = useCallback((colIndex: number): number => {
const items = filteredItemsByCol[colIndex] ?? [];
if (items.length === 0) return -1;
const selectedId = columns[colIndex]?.selectedId;
if (selectedId) {
const selectedIdx = items.findIndex(it => it.id === selectedId);
if (selectedIdx >= 0) return selectedIdx;
}
return 0;
}, []);
}, [filteredItemsByCol, columns]);
const fallbackNavPos = useCallback((cols: Column[]): NavPos | null => {
for (let c = 0; c < cols.length; c++) {
const rowIndex = preferredRowIndex(cols[c]);
const rowIndex = preferredRowIndex(c);
if (rowIndex >= 0) return { colIndex: c, rowIndex };
}
return null;
@@ -239,15 +299,17 @@ export default function FolderBrowser() {
if (pendingNavColRef.current !== null) {
const targetColIndex = pendingNavColRef.current;
const targetCol = columns[targetColIndex];
if (targetCol && targetCol.items.length > 0 && !targetCol.loading && !targetCol.error) {
const rowIndex = preferredRowIndex(targetCol);
const targetItem = targetCol.items[rowIndex];
const targetItems = filteredItemsByCol[targetColIndex] ?? [];
if (targetCol && targetItems.length > 0 && !targetCol.loading && !targetCol.error) {
const rowIndex = preferredRowIndex(targetColIndex);
const safeRowIndex = Math.min(Math.max(0, rowIndex), targetItems.length - 1);
const targetItem = targetItems[safeRowIndex];
setColumns(prev =>
prev.map((c, i) => (i === targetColIndex ? { ...c, selectedId: targetItem.id } : c)),
);
setKeyboardPos({
colIndex: targetColIndex,
rowIndex,
rowIndex: safeRowIndex,
});
pendingNavColRef.current = null;
return;
@@ -258,15 +320,31 @@ export default function FolderBrowser() {
if (!prev) return fallbackNavPos(columns);
if (prev.colIndex >= columns.length) return fallbackNavPos(columns);
const col = columns[prev.colIndex];
if (col.loading || col.error || col.items.length === 0) return fallbackNavPos(columns);
if (prev.rowIndex >= col.items.length) {
return { colIndex: prev.colIndex, rowIndex: col.items.length - 1 };
const visibleItems = filteredItemsByCol[prev.colIndex] ?? [];
if (col.loading || col.error || visibleItems.length === 0) return fallbackNavPos(columns);
if (prev.rowIndex >= visibleItems.length) {
return { colIndex: prev.colIndex, rowIndex: visibleItems.length - 1 };
}
return prev;
});
}, [columns, fallbackNavPos, preferredRowIndex]);
}, [columns, fallbackNavPos, preferredRowIndex, filteredItemsByCol]);
const clearFiltersRightOf = useCallback((colIndex: number) => {
setColumnFilters(prev => {
const next: Record<number, string> = {};
let changed = false;
Object.entries(prev).forEach(([k, v]) => {
const idx = Number(k);
if (idx <= colIndex) next[idx] = v;
else changed = true;
});
return changed ? next : prev;
});
setFilterFocusCol(prev => (prev !== null && prev > colIndex ? null : prev));
}, []);
const handleDirClick = useCallback((colIndex: number, item: SubsonicDirectoryEntry) => {
clearFiltersRightOf(colIndex);
const nextKind: ColumnKind = colIndex === 0 ? 'indexes' : 'directory';
setColumns(prev => [
...prev.slice(0, colIndex + 1).map((c, i) =>
@@ -305,7 +383,7 @@ export default function FolderBrowser() {
return next;
});
});
}, []);
}, [clearFiltersRightOf]);
const handleFileClick = useCallback(
(colIndex: number, item: SubsonicDirectoryEntry) => {
@@ -317,18 +395,22 @@ export default function FolderBrowser() {
item.id,
];
setPlayingPathIds(path);
const col = columns[colIndex];
const queue = col.items.filter(it => !it.isDir).map(entryToTrack);
const visibleItems = filteredItemsByCol[colIndex] ?? columns[colIndex]?.items ?? [];
const queue = visibleItems.filter(it => !it.isDir).map(entryToTrack);
playTrack(entryToTrack(item), queue.length > 0 ? queue : [entryToTrack(item)]);
},
[columns, playTrack],
[columns, filteredItemsByCol, playTrack],
);
const setSelectedInColumn = useCallback((colIndex: number, itemId: string) => {
setColumns(prev =>
prev.map((c, i) => (i === colIndex ? { ...c, selectedId: itemId } : c)),
);
}, []);
setColumns(prev => {
const prevSelectedId = prev[colIndex]?.selectedId ?? null;
if (prevSelectedId !== itemId) {
clearFiltersRightOf(colIndex);
}
return prev.map((c, i) => (i === colIndex ? { ...c, selectedId: itemId } : c));
});
}, [clearFiltersRightOf]);
const clearSelectedInColumn = useCallback((colIndex: number) => {
setColumns(prev =>
@@ -336,6 +418,7 @@ export default function FolderBrowser() {
);
}, []);
const handleActivate = useCallback((colIndex: number, item: SubsonicDirectoryEntry) => {
if (item.isDir) {
handleDirClick(colIndex, item);
@@ -376,14 +459,34 @@ export default function FolderBrowser() {
const onColumnsKeyDown = useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {
if (isContextMenuOpen) return;
const target = e.target as HTMLElement;
const inFilterInput =
target instanceof HTMLInputElement && target.dataset.folderFilterInput === 'true';
if (inFilterInput) return;
const key = e.key;
if (e.ctrlKey && e.code === 'KeyF') {
e.preventDefault();
const current = keyboardPos ?? fallbackNavPos(columns);
if (!current) return;
const colIndex = current.colIndex;
setFilterFocusCol(colIndex);
requestAnimationFrame(() => {
const input = filterInputRefs.current[colIndex];
if (!input) return;
input.focus();
input.select();
});
return;
}
if (isFolderBrowserArrowKey(e) && folderBrowserHasKeyModifiers(e)) return;
if (!['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Enter'].includes(key)) return;
setKeyboardNavActive(true);
const current = keyboardPos ?? fallbackNavPos(columns);
if (!current) return;
const col = columns[current.colIndex];
const item = col?.items[current.rowIndex];
const visibleItems = filteredItemsByCol[current.colIndex] ?? [];
const item = visibleItems[current.rowIndex];
if (!col || !item) return;
e.preventDefault();
@@ -403,17 +506,28 @@ export default function FolderBrowser() {
if (key === 'ArrowUp') {
if (current.rowIndex > 0) {
const nextRowIndex = current.rowIndex - 1;
const nextItem = col.items[nextRowIndex];
const nextItem = visibleItems[nextRowIndex];
setKeyboardPos({ colIndex: current.colIndex, rowIndex: nextRowIndex });
if (nextItem.isDir) handleDirClick(current.colIndex, nextItem);
else setSelectedInColumn(current.colIndex, nextItem.id);
} else if (
current.rowIndex === 0 &&
(filterFocusCol === current.colIndex || !!columnFilters[current.colIndex])
) {
setFilterFocusCol(current.colIndex);
requestAnimationFrame(() => {
const input = filterInputRefs.current[current.colIndex];
if (!input) return;
input.focus();
input.select();
});
}
return;
}
if (key === 'ArrowDown') {
if (current.rowIndex < col.items.length - 1) {
if (current.rowIndex < visibleItems.length - 1) {
const nextRowIndex = current.rowIndex + 1;
const nextItem = col.items[nextRowIndex];
const nextItem = visibleItems[nextRowIndex];
setKeyboardPos({ colIndex: current.colIndex, rowIndex: nextRowIndex });
if (nextItem.isDir) handleDirClick(current.colIndex, nextItem);
else setSelectedInColumn(current.colIndex, nextItem.id);
@@ -424,7 +538,8 @@ export default function FolderBrowser() {
if (current.colIndex > 0) {
clearSelectedInColumn(current.colIndex);
const nextColIndex = current.colIndex - 1;
const rowIndex = preferredRowIndex(columns[nextColIndex]);
clearFiltersRightOf(nextColIndex);
const rowIndex = preferredRowIndex(nextColIndex);
if (rowIndex >= 0) setKeyboardPos({ colIndex: nextColIndex, rowIndex });
}
return;
@@ -432,9 +547,10 @@ export default function FolderBrowser() {
if (key === 'ArrowRight') {
const nextColIndex = current.colIndex + 1;
if (nextColIndex < columns.length) {
const rowIndex = preferredRowIndex(columns[nextColIndex]);
const nextVisibleItems = filteredItemsByCol[nextColIndex] ?? [];
const rowIndex = Math.min(preferredRowIndex(nextColIndex), nextVisibleItems.length - 1);
if (rowIndex >= 0) {
const nextItem = columns[nextColIndex].items[rowIndex];
const nextItem = nextVisibleItems[rowIndex];
setSelectedInColumn(nextColIndex, nextItem.id);
setKeyboardPos({ colIndex: nextColIndex, rowIndex });
return;
@@ -444,9 +560,16 @@ export default function FolderBrowser() {
return;
}
if (key === 'Enter') {
if (e.shiftKey && !item.isDir) {
const toAppend = (filteredItemsByCol[current.colIndex] ?? [])
.filter(it => !it.isDir)
.map(entryToTrack);
if (toAppend.length > 0) enqueue(toAppend);
return;
}
handleActivate(current.colIndex, item);
}
}, [keyboardPos, fallbackNavPos, columns, preferredRowIndex, handleActivate, handleDirClick, setSelectedInColumn, clearSelectedInColumn, openContextMenuForEntry, isContextMenuOpen]);
}, [keyboardPos, fallbackNavPos, columns, preferredRowIndex, handleActivate, handleDirClick, setSelectedInColumn, clearSelectedInColumn, openContextMenuForEntry, isContextMenuOpen, filteredItemsByCol, filterFocusCol, columnFilters, enqueue, clearFiltersRightOf]);
const onRowContextMenu = useCallback(
(e: React.MouseEvent, colIndex: number, rowIndex: number, col: Column, item: SubsonicDirectoryEntry) => {
@@ -602,6 +725,55 @@ export default function FolderBrowser() {
className={`folder-col${isColumnCompact(col, colIndex) ? ' folder-col--compact' : ''}`}
data-folder-col-index={colIndex}
>
{(filterFocusCol === colIndex || !!columnFilters[colIndex]) && (
<div className="folder-col-filter">
<input
ref={el => { filterInputRefs.current[colIndex] = el; }}
data-folder-filter-input="true"
className="folder-col-filter-input"
value={columnFilters[colIndex] ?? ''}
placeholder={t('playlists.searchPlaceholder')}
onFocus={() => setFilterFocusCol(colIndex)}
onBlur={() => {
if (!(columnFilters[colIndex] ?? '').trim()) {
setFilterFocusCol(prev => (prev === colIndex ? null : prev));
}
}}
onKeyDown={e => {
if (e.key === 'Escape') {
e.preventDefault();
e.stopPropagation();
setColumnFilters(prev => ({ ...prev, [colIndex]: '' }));
setFilterFocusCol(null);
requestAnimationFrame(() => wrapperRef.current?.focus({ preventScroll: true }));
return;
}
if (e.key === 'ArrowDown' && !folderBrowserHasKeyModifiers(e)) {
e.preventDefault();
e.stopPropagation();
const rowIndex = preferredRowIndex(colIndex);
if (rowIndex >= 0) {
const nextItem = (filteredItemsByCol[colIndex] ?? [])[rowIndex];
if (nextItem) {
if (nextItem.isDir) handleDirClick(colIndex, nextItem);
else setSelectedInColumn(colIndex, nextItem.id);
}
setKeyboardPos({ colIndex, rowIndex });
requestAnimationFrame(() => wrapperRef.current?.focus({ preventScroll: true }));
}
}
}}
onChange={e => {
const value = e.target.value;
setColumnFilters(prev => ({ ...prev, [colIndex]: value }));
setKeyboardPos(prev => {
if (!prev || prev.colIndex !== colIndex) return prev;
return { colIndex, rowIndex: 0 };
});
}}
/>
</div>
)}
{col.loading ? (
<div className="folder-col-status">
<div className="spinner" style={{ width: 20, height: 20 }} />
@@ -610,12 +782,11 @@ export default function FolderBrowser() {
<div className="folder-col-status folder-col-error">
{t('folderBrowser.error')}
</div>
) : col.items.length === 0 ? (
) : (filteredItemsByCol[colIndex]?.length ?? 0) === 0 ? (
<div className="folder-col-status">{t('folderBrowser.empty')}</div>
) : (
col.items.map(item => {
(filteredItemsByCol[colIndex] ?? []).map((item, rowIndex) => {
const isSelected = col.selectedId === item.id;
const rowIndex = col.items.findIndex(it => it.id === item.id);
const isContextRow =
contextAnchorPos?.colIndex === colIndex && contextAnchorPos.rowIndex === rowIndex;
const isKeyboardRow =
@@ -636,6 +807,10 @@ export default function FolderBrowser() {
if (item.isDir) handleDirClick(colIndex, item);
else handleFileClick(colIndex, item);
}}
onKeyDown={e => {
if (!isFolderBrowserArrowKey(e) || folderBrowserHasKeyModifiers(e)) return;
e.preventDefault();
}}
onContextMenu={e => {
setKeyboardPos({ colIndex, rowIndex });
onRowContextMenu(e, colIndex, rowIndex, col, item);
+4 -1
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useState, useCallback, useRef } from 'react';
import { CheckSquare2, Download, HardDriveDownload } from 'lucide-react';
import { CheckSquare2, Download, HardDriveDownload, ListMusic } from 'lucide-react';
import AlbumCard from '../components/AlbumCard';
import GenreFilterBar from '../components/GenreFilterBar';
import { getAlbumList, getAlbumsByGenre, getAlbum, SubsonicAlbum, buildDownloadUrl } from '../api/subsonic';
@@ -7,6 +7,7 @@ import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../store/authStore';
import { useOfflineStore } from '../store/offlineStore';
import { useDownloadModalStore } from '../store/downloadModalStore';
import { usePlayerStore } from '../store/playerStore';
import { invoke } from '@tauri-apps/api/core';
import { join } from '@tauri-apps/api/path';
import { showToast } from '../utils/toast';
@@ -50,6 +51,7 @@ export default function NewReleases() {
}, []);
const clearSelection = () => { setSelectionMode(false); setSelectedIds(new Set()); };
const selectedAlbums = albums.filter(a => selectedIds.has(a.id));
const openContextMenu = usePlayerStore(state => state.openContextMenu);
const handleDownloadZips = async () => {
if (selectedAlbums.length === 0) return;
@@ -183,6 +185,7 @@ export default function NewReleases() {
selectionMode={selectionMode}
selected={selectedIds.has(a.id)}
onToggleSelect={toggleSelect}
selectedAlbums={selectedAlbums}
/>
))}
</div>
+49 -32
View File
@@ -14,6 +14,7 @@ import { usePlaylistStore } from '../store/playlistStore';
import { useOfflineStore } from '../store/offlineStore';
import { useOfflineJobStore } from '../store/offlineJobStore';
import { useAuthStore } from '../store/authStore';
import { useThemeStore } from '../store/themeStore';
import { useDownloadModalStore } from '../store/downloadModalStore';
import { invoke } from '@tauri-apps/api/core';
import { join } from '@tauri-apps/api/path';
@@ -45,10 +46,10 @@ function totalDurationLabel(songs: SubsonicSong[]): string {
return formatHumanHoursMinutes(total);
}
function codecLabel(song: SubsonicSong): string {
function codecLabel(song: SubsonicSong, showBitrate: boolean): string {
const parts: string[] = [];
if (song.suffix) parts.push(song.suffix.toUpperCase());
if (song.bitRate) parts.push(`${song.bitRate} kbps`);
if (showBitrate && song.bitRate) parts.push(`${song.bitRate} kbps`);
return parts.join(' · ');
}
@@ -57,6 +58,7 @@ const PL_COLUMNS: readonly ColDef[] = [
{ key: 'num', i18nKey: null, minWidth: 60, defaultWidth: 60, required: true },
{ key: 'title', i18nKey: 'trackTitle', minWidth: 150, defaultWidth: 0, required: true, flex: true },
{ key: 'artist', i18nKey: 'trackArtist', minWidth: 80, defaultWidth: 180, required: false },
{ key: 'album', i18nKey: 'trackAlbum', minWidth: 80, defaultWidth: 180, required: false },
{ key: 'favorite', i18nKey: 'trackFavorite', minWidth: 50, defaultWidth: 70, required: false },
{ key: 'rating', i18nKey: 'trackRating', minWidth: 80, defaultWidth: 120, required: false },
{ key: 'duration', i18nKey: 'trackDuration', minWidth: 72, defaultWidth: 92, required: false },
@@ -106,6 +108,10 @@ export default function PlaylistDetail() {
const setDownloadFolder = useAuthStore(s => s.setDownloadFolder);
const requestDownloadFolder = useDownloadModalStore(s => s.requestFolder);
const enableCoverArtBackground = useThemeStore(s => s.enableCoverArtBackground);
const enablePlaylistCoverPhoto = useThemeStore(s => s.enablePlaylistCoverPhoto);
const showBitrate = useThemeStore(s => s.showBitrate);
const [playlist, setPlaylist] = useState<SubsonicPlaylist | null>(null);
const [songs, setSongs] = useState<SubsonicSong[]>([]);
const [loading, setLoading] = useState(true);
@@ -233,6 +239,8 @@ export default function PlaylistDetail() {
}, [contextMenuOpen]);
// ── Load ─────────────────────────────────────────────────────
const lastModified = usePlaylistStore(s => (id ? s.lastModified[id] : undefined));
useEffect(() => {
if (!id) return;
setLoading(true);
@@ -252,7 +260,7 @@ export default function PlaylistDetail() {
})
.catch(() => {})
.finally(() => setLoading(false));
}, [id]);
}, [id, lastModified]);
// ── Suggestions ───────────────────────────────────────────────
const loadSuggestions = useCallback(async (currentSongs: SubsonicSong[]) => {
@@ -537,10 +545,12 @@ export default function PlaylistDetail() {
{/* ── Hero ── */}
<div className="album-detail-header">
{resolvedBgUrl && (
<div className="album-detail-bg" style={{ backgroundImage: `url(${resolvedBgUrl})` }} aria-hidden="true" />
{resolvedBgUrl && enableCoverArtBackground && (
<>
<div className="album-detail-bg" style={{ backgroundImage: `url(${resolvedBgUrl})` }} aria-hidden="true" />
<div className="album-detail-overlay" aria-hidden="true" />
</>
)}
<div className="album-detail-overlay" aria-hidden="true" />
<div className="album-detail-content">
<button className="btn btn-ghost album-detail-back" onClick={() => navigate('/playlists')}>
@@ -549,31 +559,33 @@ export default function PlaylistDetail() {
<div className="album-detail-hero">
{/* Cover — click to open edit modal */}
<div
className="playlist-hero-cover"
onClick={() => setEditingMeta(true)}
>
{customCoverId && customCoverFetchUrl && customCoverCacheKey ? (
<CachedImage
src={customCoverFetchUrl}
cacheKey={customCoverCacheKey}
alt=""
className="playlist-cover-grid"
style={{ objectFit: 'cover', display: 'block' }}
/>
) : (
<div className="playlist-cover-grid">
{coverQuadUrls.map((entry, i) =>
entry
? <CachedImage key={i} className="playlist-cover-cell" src={entry.src} cacheKey={entry.cacheKey} alt="" />
: <div key={i} className="playlist-cover-cell playlist-cover-cell--empty" />
)}
{enablePlaylistCoverPhoto && (
<div
className="playlist-hero-cover"
onClick={() => setEditingMeta(true)}
>
{customCoverId && customCoverFetchUrl && customCoverCacheKey ? (
<CachedImage
src={customCoverFetchUrl}
cacheKey={customCoverCacheKey}
alt=""
className="playlist-cover-grid"
style={{ objectFit: 'cover', display: 'block' }}
/>
) : (
<div className="playlist-cover-grid">
{coverQuadUrls.map((entry, i) =>
entry
? <CachedImage key={i} className="playlist-cover-cell" src={entry.src} cacheKey={entry.cacheKey} alt="" />
: <div key={i} className="playlist-cover-cell playlist-cover-cell--empty" />
)}
</div>
)}
<div className="playlist-hero-cover-overlay">
<Camera size={28} />
</div>
)}
<div className="playlist-hero-cover-overlay">
<Camera size={28} />
</div>
</div>
)}
<div className="album-detail-meta">
<span className="badge album-detail-badge">{t('playlists.titleBadge')}</span>
@@ -1018,7 +1030,7 @@ export default function PlaylistDetail() {
onContextMenu={e => {
e.preventDefault();
setContextMenuSongId(song.id);
openContextMenu(e.clientX, e.clientY, songToTrack(song), 'album-song');
openContextMenu(e.clientX, e.clientY, songToTrack(song), 'album-song', undefined, id, realIdx);
}}
>
{visibleCols.map(colDef => {
@@ -1040,6 +1052,11 @@ export default function PlaylistDetail() {
<span className={`track-artist${song.artistId ? ' track-artist-link' : ''}`} style={{ cursor: song.artistId ? 'pointer' : 'default' }} onClick={e => { if (song.artistId) { e.stopPropagation(); navigate(`/artist/${song.artistId}`); } }}>{song.artist}</span>
</div>
);
case 'album': return (
<div key="album" className="track-artist-cell">
<span className={`track-artist${song.albumId ? ' track-artist-link' : ''}`} style={{ cursor: song.albumId ? 'pointer' : 'default' }} onClick={e => { if (song.albumId) { e.stopPropagation(); navigate(`/album/${song.albumId}`); } }}>{song.album}</span>
</div>
);
case 'favorite': return (
<div key="favorite" className="track-star-cell">
<button className="btn btn-ghost track-star-btn" onClick={e => handleToggleStar(song, e)} style={{ color: (song.id in starredOverrides ? starredOverrides[song.id] : starredSongs.has(song.id)) ? 'var(--color-star-active, var(--accent))' : 'var(--color-star-inactive, var(--text-muted))' }}>
@@ -1051,7 +1068,7 @@ export default function PlaylistDetail() {
case 'duration': return <div key="duration" className="track-duration">{formatDuration(song.duration ?? 0)}</div>;
case 'format': return (
<div key="format" className="track-meta">
{(song.suffix || song.bitRate) && <span className="track-codec">{codecLabel(song)}</span>}
{(song.suffix || (showBitrate && song.bitRate)) && <span className="track-codec">{codecLabel(song, showBitrate)}</span>}
</div>
);
case 'delete': return (
@@ -1140,7 +1157,7 @@ export default function PlaylistDetail() {
case 'duration': return <div key="duration" className="track-duration">{formatDuration(song.duration ?? 0)}</div>;
case 'format': return (
<div key="format" className="track-meta">
{(song.suffix || song.bitRate) && <span className="track-codec">{codecLabel(song)}</span>}
{(song.suffix || (showBitrate && song.bitRate)) && <span className="track-codec">{codecLabel(song, showBitrate)}</span>}
</div>
);
case 'delete': return (
+165 -52
View File
@@ -1,12 +1,13 @@
import React, { useEffect, useState, useRef } from 'react';
import React, { useEffect, useState, useRef, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { ListMusic, Play, Plus, Trash2, X } from 'lucide-react';
import { getPlaylists, createPlaylist, deletePlaylist, SubsonicPlaylist, getPlaylist, buildCoverArtUrl, coverArtCacheKey } from '../api/subsonic';
import { ListMusic, Play, Plus, Trash2, X, CheckSquare2, Check } from 'lucide-react';
import { getPlaylists, deletePlaylist, SubsonicPlaylist, getPlaylist, buildCoverArtUrl, coverArtCacheKey, updatePlaylist } from '../api/subsonic';
import { usePlayerStore, songToTrack } from '../store/playerStore';
import { usePlaylistStore } from '../store/playlistStore';
import CachedImage from '../components/CachedImage';
import { useTranslation } from 'react-i18next';
import { formatHumanHoursMinutes } from '../utils/formatHumanDuration';
import { showToast } from '../utils/toast';
function formatDuration(seconds: number): string {
return formatHumanHoursMinutes(seconds);
@@ -16,10 +17,13 @@ export default function Playlists() {
const { t } = useTranslation();
const navigate = useNavigate();
const playTrack = usePlayerStore(s => s.playTrack);
const openContextMenu = usePlayerStore(s => s.openContextMenu);
const touchPlaylist = usePlaylistStore((s) => s.touchPlaylist);
const removeId = usePlaylistStore((s) => s.removeId);
const playlists = usePlaylistStore((s) => s.playlists);
const fetchPlaylists = usePlaylistStore((s) => s.fetchPlaylists);
const playlistsLoading = usePlaylistStore((s) => s.playlistsLoading);
const [playlists, setPlaylists] = useState<SubsonicPlaylist[]>([]);
const [loading, setLoading] = useState(true);
const [creating, setCreating] = useState(false);
const [newName, setNewName] = useState('');
@@ -27,24 +31,45 @@ export default function Playlists() {
const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);
const nameInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
getPlaylists()
.then(setPlaylists)
.catch(() => {})
.finally(() => setLoading(false));
// ── Multi-selection ──────────────────────────────────────────────────────
const [selectionMode, setSelectionMode] = useState(false);
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const toggleSelectionMode = () => {
setSelectionMode(v => !v);
setSelectedIds(new Set());
};
const toggleSelect = useCallback((id: string) => {
setSelectedIds(prev => {
const next = new Set(prev);
if (next.has(id)) next.delete(id); else next.add(id);
return next;
});
}, []);
const clearSelection = () => {
setSelectionMode(false);
setSelectedIds(new Set());
};
const selectedPlaylists = playlists.filter(p => selectedIds.has(p.id));
useEffect(() => {
fetchPlaylists().finally(() => setLoading(false));
}, [fetchPlaylists]);
useEffect(() => {
if (creating) nameInputRef.current?.focus();
}, [creating]);
const createPlaylist = usePlaylistStore(s => s.createPlaylist);
const handleCreate = async () => {
const name = newName.trim() || t('playlists.unnamed');
try {
await createPlaylist(name);
const updated = await getPlaylists();
setPlaylists(updated);
} catch {}
await createPlaylist(name);
// Refresh playlists from API to get the new one
await fetchPlaylists();
setCreating(false);
setNewName('');
};
@@ -73,11 +98,67 @@ export default function Playlists() {
try {
await deletePlaylist(pl.id);
removeId(pl.id);
setPlaylists((prev) => prev.filter((p) => p.id !== pl.id));
} catch {}
usePlaylistStore.setState((s) => ({
playlists: s.playlists.filter((p) => p.id !== pl.id),
}));
showToast(t('playlists.deleteSuccess', { count: 1 }), 3000, 'info');
} catch {
showToast(t('playlists.deleteFailed', { name: pl.name }), 3000, 'error');
}
setDeleteConfirmId(null);
};
const handleDeleteSelected = async () => {
if (selectedPlaylists.length === 0) return;
let deleted = 0;
for (const pl of selectedPlaylists) {
try {
await deletePlaylist(pl.id);
removeId(pl.id);
deleted++;
} catch {
showToast(t('playlists.deleteFailed', { name: pl.name }), 3000, 'error');
}
}
usePlaylistStore.setState((s) => ({
playlists: s.playlists.filter((p) => !selectedIds.has(p.id)),
}));
clearSelection();
if (deleted > 0) {
showToast(t('playlists.deleteSuccess', { count: deleted }), 3000, 'info');
}
};
const handleMergeSelected = async (targetPlaylist: SubsonicPlaylist) => {
if (selectedPlaylists.length === 0) return;
try {
const { songs: targetSongs } = await getPlaylist(targetPlaylist.id);
const targetIds = new Set(targetSongs.map(s => s.id));
let totalAdded = 0;
for (const pl of selectedPlaylists) {
if (pl.id === targetPlaylist.id) continue;
const { songs } = await getPlaylist(pl.id);
const newSongs = songs.filter(s => !targetIds.has(s.id));
if (newSongs.length > 0) {
newSongs.forEach(s => targetIds.add(s.id));
totalAdded += newSongs.length;
}
}
if (totalAdded > 0) {
await updatePlaylist(targetPlaylist.id, Array.from(targetIds));
touchPlaylist(targetPlaylist.id);
showToast(t('playlists.mergeSuccess', { count: totalAdded, playlist: targetPlaylist.name }), 3000, 'info');
} else {
showToast(t('playlists.mergeNoNewSongs'), 3000, 'info');
}
clearSelection();
} catch {
showToast(t('playlists.mergeError'), 4000, 'error');
}
};
if (loading) {
return (
<div className="content-body" style={{ display: 'flex', justifyContent: 'center', padding: '4rem' }}>
@@ -91,34 +172,51 @@ export default function Playlists() {
{/* ── Header row ── */}
<div className="playlists-header">
<h1 className="page-title" style={{ marginBottom: 0 }}>{t('playlists.title')}</h1>
<h1 className="page-title" style={{ marginBottom: 0 }}>
{selectionMode && selectedIds.size > 0
? t('playlists.selectionCount', { count: selectedIds.size })
: t('playlists.title')}
</h1>
<div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
{creating ? (
<>
<input
ref={nameInputRef}
className="input"
style={{ width: 220 }}
placeholder={t('playlists.createName')}
value={newName}
onChange={(e) => setNewName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') handleCreate();
if (e.key === 'Escape') { setCreating(false); setNewName(''); }
}}
/>
<button className="btn btn-primary" onClick={handleCreate}>
{t('playlists.create')}
</button>
<button className="btn btn-surface" onClick={() => { setCreating(false); setNewName(''); }}>
{t('playlists.cancel')}
</button>
{!(selectionMode && selectedIds.size > 0) && (<>
{creating ? (
<>
<input
ref={nameInputRef}
className="input"
style={{ width: 220 }}
placeholder={t('playlists.createName')}
value={newName}
onChange={(e) => setNewName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') handleCreate();
if (e.key === 'Escape') { setCreating(false); setNewName(''); }
}}
/>
<button className="btn btn-primary" onClick={handleCreate}>
{t('playlists.create')}
</button>
<button className="btn btn-surface" onClick={() => { setCreating(false); setNewName(''); }}>
{t('playlists.cancel')}
</button>
</>
) : (
<button className="btn btn-primary" onClick={() => setCreating(true)}>
<Plus size={15} /> {t('playlists.newPlaylist')}
</button>
)}
</>
) : (
<button className="btn btn-primary" onClick={() => setCreating(true)}>
<Plus size={15} /> {t('playlists.newPlaylist')}
</button>
)}
<button
className={`btn btn-surface${selectionMode ? ' btn-sort-active' : ''}`}
onClick={toggleSelectionMode}
data-tooltip={selectionMode ? t('playlists.cancelSelect') : t('playlists.startSelect')}
data-tooltip-pos="bottom"
style={selectionMode ? { background: 'var(--accent)', color: 'var(--ctp-crust)' } : {}}
>
<CheckSquare2 size={15} />
{selectionMode ? t('playlists.cancelSelect') : t('playlists.select')}
</button>
</div>
</div>
@@ -130,10 +228,34 @@ export default function Playlists() {
{playlists.map((pl) => (
<div
key={pl.id}
className="album-card"
onClick={() => navigate(`/playlists/${pl.id}`)}
className={`album-card${selectionMode && selectedIds.has(pl.id) ? ' selected' : ''}`}
onClick={() => {
if (selectionMode) {
toggleSelect(pl.id);
} else {
navigate(`/playlists/${pl.id}`);
}
}}
onContextMenu={(e) => {
e.preventDefault();
if (selectionMode && selectedIds.size > 0) {
openContextMenu(e.clientX, e.clientY, selectedPlaylists, 'multi-playlist');
} else {
openContextMenu(e.clientX, e.clientY, pl, 'playlist');
}
}}
onMouseLeave={() => { if (deleteConfirmId === pl.id) setDeleteConfirmId(null); }}
style={selectionMode && selectedIds.has(pl.id) ? {
outline: '2px solid var(--accent)',
outlineOffset: '2px',
borderRadius: 'var(--radius-md)'
} : {}}
>
{selectionMode && (
<div className={`album-card-select-check${selectedIds.has(pl.id) ? ' album-card-select-check--on' : ''}`}>
{selectedIds.has(pl.id) && <Check size={14} strokeWidth={3} />}
</div>
)}
{/* Cover area — server collage or fallback icon */}
<div className="album-card-cover">
{pl.coverArt ? (
@@ -163,15 +285,6 @@ export default function Playlists() {
</button>
</div>
{/* Delete button — top-right corner */}
<button
className={`playlist-card-delete ${deleteConfirmId === pl.id ? 'playlist-card-delete--confirm' : ''}`}
onClick={(e) => handleDelete(e, pl)}
data-tooltip={deleteConfirmId === pl.id ? t('playlists.confirmDelete') : t('playlists.deletePlaylist')}
data-tooltip-pos="bottom"
>
{deleteConfirmId === pl.id ? <Trash2 size={12} /> : <X size={12} />}
</button>
</div>
<div className="album-card-info">
+3 -1
View File
@@ -8,6 +8,7 @@ import ArtistRow from '../components/ArtistRow';
import { useTranslation } from 'react-i18next';
import { useDragDrop } from '../contexts/DragDropContext';
import { useAuthStore } from '../store/authStore';
import { useThemeStore } from '../store/themeStore';
function formatDuration(s: number) {
return `${Math.floor(s / 60)}:${(s % 60).toString().padStart(2, '0')}`;
@@ -23,6 +24,7 @@ export default function SearchResults() {
const currentTrack = usePlayerStore(s => s.currentTrack);
const psyDrag = useDragDrop();
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
const showBitrate = useThemeStore(s => s.showBitrate);
useEffect(() => {
if (!query.trim()) { setResults(null); return; }
@@ -116,7 +118,7 @@ export default function SearchResults() {
<div className="track-artist-cell"><span className="track-artist" title={song.artist}>{song.artist}</span></div>
<div className="track-artist-cell"><span className="track-artist" title={song.album}>{song.album}</span></div>
<span className="track-codec" style={{ alignSelf: 'center' }}>
{[song.suffix?.toUpperCase(), song.bitRate ? `${song.bitRate} kbps` : ''].filter(Boolean).join(' · ')}
{[song.suffix?.toUpperCase(), showBitrate && song.bitRate ? `${song.bitRate} kbps` : ''].filter(Boolean).join(' · ')}
</span>
<span className="track-duration" style={{ textAlign: 'right' }}>
{formatDuration(song.duration)}
+333 -40
View File
@@ -5,12 +5,13 @@ import { useNavigate, useLocation } from 'react-router-dom';
import {
Wifi, WifiOff, Globe, Music2, Sliders, LogOut, CheckCircle2, FolderOpen,
Palette, Server, Plus, Trash2, Eye, EyeOff, Info, ExternalLink, Shuffle, X, Play, Type, Keyboard, ChevronDown,
GripVertical, PanelLeft, RotateCcw, LayoutGrid, AppWindow, HardDrive, Upload, Download, Waves, Star, Clock, ZoomIn, Sparkles, AlertTriangle, Maximize2
GripVertical, PanelLeft, RotateCcw, LayoutGrid, AppWindow, HardDrive, Upload, Download, Waves, Star, Clock, ZoomIn, Sparkles, AlertTriangle, Maximize2, AudioLines, User, Lock
} from 'lucide-react';
import i18n from '../i18n';
import { exportBackup, importBackup } from '../utils/backup';
import { showToast } from '../utils/toast';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import { open as openUrl } from '@tauri-apps/plugin-shell';
import { getImageCacheSize, clearImageCache } from '../utils/imageCache';
import { useOfflineStore } from '../store/offlineStore';
@@ -25,7 +26,7 @@ import { SeekbarPreview } from '../components/WaveformSeek';
import { IS_LINUX } from '../utils/platform';
import { useThemeStore } from '../store/themeStore';
import { useFontStore, FontId } from '../store/fontStore';
import { useKeybindingsStore, KeyAction, formatKeyCode, DEFAULT_BINDINGS } from '../store/keybindingsStore';
import { useKeybindingsStore, KeyAction, formatBinding, buildInAppBinding } from '../store/keybindingsStore';
import { useGlobalShortcutsStore, GlobalAction, buildGlobalShortcut, formatGlobalShortcut } from '../store/globalShortcutsStore';
import { useSidebarStore, DEFAULT_SIDEBAR_ITEMS, SidebarItemConfig } from '../store/sidebarStore';
import { useHomeStore, HomeSectionId } from '../store/homeStore';
@@ -73,6 +74,7 @@ const CONTRIBUTORS = [
'Click-to-seek in synced lyrics (PR #38)',
'Volume scroll wheel on volume slider (PR #38)',
'Lyrics line visual states: active / completed / upcoming (PR #38)',
'Queue auto-scroll to keep upcoming tracks in view; fixed re-renders from currentTime in QueuePanel (PR #115)',
],
},
{
@@ -106,6 +108,13 @@ const CONTRIBUTORS = [
'Hot playback cache — eviction budgeting, grace period, and live Audio settings readout (PR #153)',
'Folder Browser: keyboard navigation, context menus, now-playing path emphasis, and adaptive column layout (PR #158)',
'Infinite queue: artist-driven candidates via Top Songs + Similar Songs with random fallback (PR #163)',
'Folder Browser: per-column filter with keyboard flow and Shift+Enter queue append (PR #165)',
'Keybindings: modifier + key chords for in-app shortcuts; fixed seek ±10s units (PR #167)',
'Statistics: genre insights scoped to music library, cached Subsonic fetches, localized duration formatting (PR #144)',
'Audio output device picker: clearer ALSA labels, duplicate disambiguation, system-default mark, live refresh (PR #173)',
'Folder Browser: arrow navigation blocked when modifier keys are held (PR #174)',
'Linux audio output device picker: stable watcher (disable false enumeration-miss resets), canonicalize ALSA name drift, ghost entry for unlisted device (PR #176)',
'Opus audio playback via symphonia-adapter-libopus with bundled libopus (PR #183)',
],
},
{
@@ -120,6 +129,7 @@ const CONTRIBUTORS = [
'Russian translation refinements (PR #148)',
'Merge Random Mix & Albums into a single Build a Mix hub (PR #155)',
'Fullscreen player: software-rendering performance fixes + portrait toggle & dimming setting (PR #156)',
'Fullscreen player: stop mesh blob and portrait animations in no-compositing mode; remove seekbar box-shadow repaint (PR #175)',
],
},
{
@@ -128,6 +138,9 @@ const CONTRIBUTORS = [
contributions: [
'Spanish (es) translation — 964 strings (PR #159)',
'Column-header sorting for albums & playlists (PR #160)',
'Multi-select for albums, artists & playlists with bulk "Add to Playlist"; collapsible sidebar playlist section; infinite scroll on Artists page; "Remove from Playlist" in context menu (PR #168)',
'3 visual toggles: cover art background, playlist cover photo, show bitrate badge (PR #181)',
'8 community themes (AMOLED Black, Monochrome Dark, Amber Night, Phosphor Green, Midnight Blue, Rose Dark, Sepia Dark, Ice Blue) + waveform live theme update (PR #182)',
],
},
{
@@ -167,7 +180,7 @@ function AddServerForm({ onSave, onCancel }: { onSave: (data: Omit<ServerProfile
</div>
<div className="form-group" style={{ marginBottom: '0.75rem' }}>
<label style={{ fontSize: 13 }}>{t('settings.serverUrl')}</label>
<input className="input" type="text" value={form.url} onChange={update('url')} placeholder="192.168.1.100:4533" autoComplete="off" />
<input className="input" type="text" value={form.url} onChange={update('url')} placeholder={t('settings.serverUrlPlaceholder')} autoComplete="off" />
</div>
<div className="form-row" style={{ marginBottom: '0.75rem' }}>
<div className="form-group">
@@ -220,6 +233,125 @@ function snapHotCacheMb(v: number): number {
return Math.round((x - 32) / 32) * 32 + 32;
}
/** Makes raw ALSA device names more readable on Linux.
* Values are kept as-is (rodio needs the ALSA name); only the displayed label is cleaned.
* e.g. "sysdefault:CARD=U192k" "U192k"
* "hw:CARD=U192k,DEV=0" "U192k (hw · PCM 0)"
* "hdmi:CARD=NVidia,DEV=1" "NVidia (HDMI · DEV 1)" (same DEV as in ALSA string)
* "iec958:CARD=PCH,DEV=0" "PCH (S/PDIF)"
* Names without ALSA prefix (pipewire, pulse, default) are returned unchanged. */
function formatAudioDeviceLabel(name: string): string {
const cardMatch = name.match(/CARD=([^,]+)/);
if (!cardMatch) return name;
const card = cardMatch[1];
const devM = name.match(/DEV=(\d+)/);
const devNum = devM ? parseInt(devM[1], 10) : null;
const subM = name.match(/SUBDEV=(\d+)/);
const subNum = subM ? parseInt(subM[1], 10) : null;
if (name.startsWith('iec958:')) return `${card} (S/PDIF)`;
if (name.startsWith('hdmi:')) {
const d = devNum !== null ? devNum : 0;
return `${card} (HDMI · DEV ${d})`;
}
if (name.startsWith('sysdefault:')) {
if (devNum !== null && devNum > 0) return `${card} (default · PCM ${devNum})`;
return card;
}
if (name.startsWith('plughw:')) {
if (devNum !== null) {
const sub = subNum !== null ? ` · sub ${subNum}` : '';
return `${card} (plug · PCM ${devNum}${sub})`;
}
return card;
}
if (name.startsWith('hw:')) {
if (devNum !== null) {
const sub = subNum !== null ? ` · sub ${subNum}` : '';
return `${card} (hw · PCM ${devNum}${sub})`;
}
return `${card} (hw)`;
}
if (name.startsWith('front:')) return `${card} (Front)`;
if (name.startsWith('surround')) return `${card} (${name.split(':')[0]})`;
// Other ALSA iface:card,dev — show plugin + PCM so identical cards differ
const iface = name.split(':')[0];
if (iface && !['default', 'pulse', 'pipewire'].includes(iface)) {
if (devNum !== null) return `${card} (${iface} · PCM ${devNum})`;
return `${card} (${iface})`;
}
return card;
}
/** Readable tail when two devices still share the same label (rare after formatAudioDeviceLabel). */
function audioDeviceDuplicateHint(raw: string): string {
const cardM = raw.match(/CARD=([^,]+)/);
const devM = raw.match(/DEV=(\d+)/);
const subM = raw.match(/SUBDEV=(\d+)/);
const iface = raw.split(':')[0] || '';
const parts: string[] = [];
if (iface) parts.push(iface);
if (cardM) parts.push(cardM[1]);
if (devM) parts.push(`PCM ${devM[1]}`);
if (subM) parts.push(`sub ${subM[1]}`);
if (parts.length > 1) return parts.join(' · ');
return raw.length > 56 ? `${raw.slice(-53)}` : raw;
}
/** When several devices share the same display label, append a disambiguator. */
function disambiguatedAudioDeviceLabel(raw: string, baseLabel: string, duplicateBase: boolean): string {
if (!duplicateBase) return baseLabel;
return `${baseLabel} · ${audioDeviceDuplicateHint(raw)}`;
}
/** cpal order is arbitrary; sort by readable label, current OS default first. */
function sortAudioDeviceIds(devices: string[], osDefaultDeviceId: string | null): string[] {
return [...devices].sort((a, b) => {
const aDef = osDefaultDeviceId && a === osDefaultDeviceId;
const bDef = osDefaultDeviceId && b === osDefaultDeviceId;
if (aDef !== bDef) return aDef ? -1 : 1;
const la = formatAudioDeviceLabel(a);
const lb = formatAudioDeviceLabel(b);
const byLabel = la.localeCompare(lb, undefined, { sensitivity: 'base' });
if (byLabel !== 0) return byLabel;
return a.localeCompare(b);
});
}
function buildAudioDeviceSelectOptions(
devices: string[],
defaultLabel: string,
osDefaultDeviceId: string | null,
osDefaultMark: string,
pinnedDevice: string | null,
notInListSuffix: string,
): { value: string; label: string }[] {
const baseLabels = devices.map(formatAudioDeviceLabel);
const countByBase = new Map<string, number>();
for (const b of baseLabels) countByBase.set(b, (countByBase.get(b) ?? 0) + 1);
const pinned = pinnedDevice?.trim() || null;
const pinnedNotListed = !!(pinned && !devices.includes(pinned));
const ghost: { value: string; label: string }[] = pinnedNotListed
? (() => {
const base = formatAudioDeviceLabel(pinned);
let label = `${base} · ${notInListSuffix}`;
if (osDefaultDeviceId && pinned === osDefaultDeviceId) label = `${label} · ${osDefaultMark}`;
return [{ value: pinned, label }];
})()
: [];
return [
{ value: '', label: defaultLabel },
...ghost,
...devices.map((d, i) => {
const base = baseLabels[i];
const dup = (countByBase.get(base) ?? 0) > 1;
let label = disambiguatedAudioDeviceLabel(d, base, dup);
if (osDefaultDeviceId && d === osDefaultDeviceId) label = `${label} · ${osDefaultMark}`;
return { value: d, label };
}),
];
}
export default function Settings() {
const auth = useAuthStore();
const theme = useThemeStore();
@@ -259,6 +391,10 @@ export default function Settings() {
const [imageCacheBytes, setImageCacheBytes] = useState<number | null>(null);
const [offlineCacheBytes, setOfflineCacheBytes] = useState<number | null>(null);
const [hotCacheBytes, setHotCacheBytes] = useState<number | null>(null);
const [audioDevices, setAudioDevices] = useState<string[]>([]);
const [osDefaultAudioDeviceId, setOsDefaultAudioDeviceId] = useState<string | null>(null);
const [deviceSwitching, setDeviceSwitching] = useState(false);
const [devicesLoading, setDevicesLoading] = useState(false);
const [showClearConfirm, setShowClearConfirm] = useState(false);
const [clearing, setClearing] = useState(false);
const [contributorsOpen, setContributorsOpen] = useState(false);
@@ -275,6 +411,65 @@ export default function Settings() {
invoke<number>('get_hot_cache_size', { customDir: auth.hotCacheDownloadDir || null }).then(setHotCacheBytes).catch(() => setHotCacheBytes(0));
}, [activeTab, auth.offlineDownloadDir, auth.hotCacheDownloadDir]);
const refreshAudioDevices = useCallback((opts?: { silent?: boolean }) => {
const silent = !!opts?.silent;
if (!silent) setDevicesLoading(true);
const listP = invoke<string[]>('audio_list_devices').catch((e) => {
console.error(e);
showToast(t('settings.audioOutputDeviceListError'), 5000, 'error');
return [] as string[];
});
const defP = invoke<string | null>('audio_default_output_device_name').catch(() => null);
Promise.all([listP, defP])
.then(async ([devices, osDefault]) => {
let canon: string | null = null;
try {
canon = await invoke<string | null>('audio_canonicalize_selected_device');
if (canon) useAuthStore.getState().setAudioOutputDevice(canon);
} catch {
/* ignore */
}
const finalList = canon
? await invoke<string[]>('audio_list_devices').catch(() => devices)
: devices;
const defId = osDefault ?? null;
setAudioDevices(sortAudioDeviceIds(finalList, defId));
setOsDefaultAudioDeviceId(defId);
})
.finally(() => {
if (!silent) setDevicesLoading(false);
});
}, [t]);
// Load available audio output devices when Audio tab opens.
useEffect(() => {
if (activeTab !== 'audio') return;
refreshAudioDevices();
}, [activeTab, refreshAudioDevices]);
// Keep device list + "current system output" mark in sync when the backend reopens the stream.
useEffect(() => {
if (activeTab !== 'audio') return;
let cancelled = false;
const unlisteners: Array<() => void> = [];
(async () => {
for (const ev of ['audio:device-changed', 'audio:device-reset'] as const) {
const u = await listen(ev, () => {
if (!cancelled) refreshAudioDevices({ silent: true });
});
if (cancelled) {
u();
return;
}
unlisteners.push(u);
}
})();
return () => {
cancelled = true;
for (const u of unlisteners) u();
};
}, [activeTab, refreshAudioDevices]);
/** Live disk usage for hot cache while Audio settings are open (interval + refresh when index changes). */
useEffect(() => {
if (activeTab !== 'audio') return;
@@ -489,6 +684,76 @@ export default function Settings() {
{/* ── Audio ────────────────────────────────────────────────────────────── */}
{activeTab === 'audio' && (
<>
{/* Audio Output Device */}
<section className="settings-section">
<div className="settings-section-header">
<AudioLines size={18} />
<h2>{t('settings.audioOutputDevice')}</h2>
</div>
<div className="settings-card">
<div style={{ fontSize: 12, color: 'var(--text-muted)', marginBottom: '0.75rem' }}>
{t('settings.audioOutputDeviceDesc')}
</div>
<div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
<CustomSelect
style={{ flex: 1 }}
value={auth.audioOutputDevice ?? ''}
disabled={deviceSwitching || devicesLoading}
onChange={async (val) => {
const device = val || null;
setDeviceSwitching(true);
try {
await invoke('audio_set_device', { deviceName: device });
auth.setAudioOutputDevice(device);
} catch { /* device open failed — don't persist */ }
setDeviceSwitching(false);
}}
options={buildAudioDeviceSelectOptions(
audioDevices,
t('settings.audioOutputDeviceDefault'),
osDefaultAudioDeviceId,
t('settings.audioOutputDeviceOsDefaultNow'),
auth.audioOutputDevice,
t('settings.audioOutputDeviceNotInCurrentList'),
)}
/>
<button
className="icon-btn"
onClick={() => refreshAudioDevices()}
disabled={devicesLoading || deviceSwitching}
data-tooltip={t('settings.audioOutputDeviceRefresh')}
>
<RotateCcw size={15} className={devicesLoading ? 'spin' : ''} />
</button>
</div>
</div>
</section>
{/* Native Hi-Res Playback */}
<section className="settings-section">
<div className="settings-section-header">
<Waves size={18} />
<h2>{t('settings.hiResTitle')}</h2>
</div>
<div className="settings-card">
<div className="settings-toggle-row">
<div>
<div style={{ fontWeight: 500 }}>{t('settings.hiResEnabled')}</div>
<div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{t('settings.hiResDesc')}</div>
</div>
<label className="toggle-switch" aria-label={t('settings.hiResEnabled')}>
<input
type="checkbox"
checked={auth.enableHiRes}
onChange={e => auth.setEnableHiRes(e.target.checked)}
id="hires-enabled-toggle"
/>
<span className="toggle-track" />
</label>
</div>
</div>
</section>
{/* Equalizer */}
<section className="settings-section">
<div className="settings-section-header">
@@ -809,31 +1074,6 @@ export default function Settings() {
</div>
</section>
{/* Native Hi-Res Playback */}
<section className="settings-section">
<div className="settings-section-header">
<Waves size={18} />
<h2>{t('settings.hiResTitle')}</h2>
</div>
<div className="settings-card">
<div className="settings-toggle-row">
<div>
<div style={{ fontWeight: 500 }}>{t('settings.hiResEnabled')}</div>
<div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{t('settings.hiResDesc')}</div>
</div>
<label className="toggle-switch" aria-label={t('settings.hiResEnabled')}>
<input
type="checkbox"
checked={auth.enableHiRes}
onChange={e => auth.setEnableHiRes(e.target.checked)}
id="hires-enabled-toggle"
/>
<span className="toggle-track" />
</label>
</div>
</div>
</section>
</>
)}
@@ -1375,6 +1615,47 @@ export default function Settings() {
</div>
</section>
<section className="settings-section">
<div className="settings-section-header">
<Palette size={18} />
<h2>{t('settings.visualOptionsTitle')}</h2>
</div>
<div className="settings-card">
<div className="settings-toggle-row">
<div>
<div style={{ fontWeight: 500 }}>{t('settings.coverArtBackground')}</div>
<div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{t('settings.coverArtBackgroundSub')}</div>
</div>
<label className="toggle-switch">
<input type="checkbox" checked={theme.enableCoverArtBackground} onChange={e => theme.setEnableCoverArtBackground(e.target.checked)} />
<span className="toggle-track" />
</label>
</div>
<div className="settings-section-divider" />
<div className="settings-toggle-row">
<div>
<div style={{ fontWeight: 500 }}>{t('settings.playlistCoverPhoto')}</div>
<div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{t('settings.playlistCoverPhotoSub')}</div>
</div>
<label className="toggle-switch">
<input type="checkbox" checked={theme.enablePlaylistCoverPhoto} onChange={e => theme.setEnablePlaylistCoverPhoto(e.target.checked)} />
<span className="toggle-track" />
</label>
</div>
<div className="settings-section-divider" />
<div className="settings-toggle-row">
<div>
<div style={{ fontWeight: 500 }}>{t('settings.showBitrate')}</div>
<div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{t('settings.showBitrateSub')}</div>
</div>
<label className="toggle-switch">
<input type="checkbox" checked={theme.showBitrate} onChange={e => theme.setShowBitrate(e.target.checked)} />
<span className="toggle-track" />
</label>
</div>
</div>
</section>
<section className="settings-section">
<div className="settings-section-header">
<ZoomIn size={18} />
@@ -1576,13 +1857,17 @@ export default function Settings() {
const handler = (e: KeyboardEvent) => {
e.preventDefault();
e.stopPropagation();
if (e.code !== 'Escape') {
// unbind any existing action with this key first
const existing = (Object.entries(kb.bindings) as [KeyAction, string | null][])
.find(([, c]) => c === e.code)?.[0];
if (existing && existing !== action) kb.setBinding(existing, null);
kb.setBinding(action, e.code);
if (e.code === 'Escape') {
setListeningFor(null);
window.removeEventListener('keydown', handler, true);
return;
}
const chord = buildInAppBinding(e);
if (!chord) return;
const existing = (Object.entries(kb.bindings) as [KeyAction, string | null][])
.find(([, c]) => c === chord)?.[0];
if (existing && existing !== action) kb.setBinding(existing, null);
kb.setBinding(action, chord);
setListeningFor(null);
window.removeEventListener('keydown', handler, true);
};
@@ -1598,7 +1883,7 @@ export default function Settings() {
cursor: 'pointer',
}}
>
{isListening ? t('settings.shortcutListening') : bound ? formatKeyCode(bound) : t('settings.shortcutUnbound')}
{isListening ? t('settings.shortcutListening') : bound ? formatBinding(bound) : t('settings.shortcutUnbound')}
</button>
{bound && !isListening && (
<button
@@ -1741,7 +2026,18 @@ export default function Settings() {
</span>
)}
</div>
<div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{srv.username}@{srv.url}</div>
<div style={{ fontSize: 12, color: 'var(--text-muted)', display: 'flex', alignItems: 'center', gap: 4, overflow: 'hidden' }}>
{srv.url.startsWith('https://') && (
<Lock size={11} style={{ color: 'var(--positive)', flexShrink: 0 }} />
)}
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{srv.url.replace(/^https?:\/\//, '')}
</span>
</div>
<div style={{ fontSize: 12, color: 'var(--text-muted)', display: 'flex', alignItems: 'center', gap: 4, marginTop: 1 }}>
<User size={11} />
{srv.username}
</div>
</div>
<div style={{ display: 'flex', gap: '6px', flexShrink: 0, alignItems: 'center' }}>
{status === 'ok' && <CheckCircle2 size={16} style={{ color: 'var(--positive)' }} />}
@@ -1961,9 +2257,6 @@ export default function Settings() {
<p style={{ fontSize: 13, color: 'var(--text-secondary)', lineHeight: 1.6, margin: '1rem 0 0.5rem' }}>
{t('settings.aboutDesc')}
</p>
<p style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.6, margin: '0.5rem 0' }}>
{t('settings.aboutFeatures')}
</p>
<div className="divider" style={{ margin: '1rem 0' }} />
@@ -2525,7 +2818,7 @@ function ChangelogSection() {
</label>
</div>
<div className="changelog-list">
{versions.map(({ version, date, body }) => (
{versions.slice(0, 3).map(({ version, date, body }) => (
<details key={version} className="changelog-entry" open={version === appVersion}>
<summary className="changelog-summary">
<span className="changelog-version">v{version}</span>
+7 -1
View File
@@ -77,6 +77,8 @@ interface AuthState {
/** Alpha: native hi-res sample rate output (disabled = safe 44.1 kHz mode) */
enableHiRes: boolean;
/** Selected audio output device name. null = system default. */
audioOutputDevice: string | null;
/** Alpha: ephemeral queue prefetch cache on disk */
hotCacheEnabled: boolean;
@@ -197,6 +199,7 @@ interface AuthState {
setLastSeenChangelogVersion: (v: string) => void;
setSeekbarStyle: (v: SeekbarStyle) => void;
setEnableHiRes: (v: boolean) => void;
setAudioOutputDevice: (v: string | null) => void;
setHotCacheEnabled: (v: boolean) => void;
setHotCacheMaxMb: (v: number) => void;
setHotCacheDebounceSec: (v: number) => void;
@@ -289,6 +292,7 @@ export const useAuthStore = create<AuthState>()(
lastSeenChangelogVersion: '',
seekbarStyle: 'waveform',
enableHiRes: false,
audioOutputDevice: null,
hotCacheEnabled: false,
hotCacheMaxMb: 256,
hotCacheDebounceSec: 30,
@@ -410,6 +414,7 @@ export const useAuthStore = create<AuthState>()(
setSeekbarStyle: (v) => set({ seekbarStyle: v }),
setEnableHiRes: (v) => set({ enableHiRes: v }),
setAudioOutputDevice: (v) => set({ audioOutputDevice: v }),
setHotCacheEnabled: (v) => set({ hotCacheEnabled: v }),
setHotCacheMaxMb: (v) => set({ hotCacheMaxMb: v }),
setHotCacheDebounceSec: (v) => set({ hotCacheDebounceSec: v }),
@@ -541,7 +546,8 @@ export const useAuthStore = create<AuthState>()(
const s = get();
const server = s.servers.find(srv => srv.id === s.activeServerId);
if (!server?.url) return '';
return server.url.startsWith('http') ? server.url : `http://${server.url}`;
const base = server.url.startsWith('http') ? server.url : `http://${server.url}`;
return base.replace(/\/$/, '');
},
getActiveServer: () => {
+36
View File
@@ -0,0 +1,36 @@
import { create } from 'zustand';
export interface DeviceSyncJobState {
jobId: string | null;
total: number;
done: number;
skipped: number;
failed: number;
status: 'idle' | 'running' | 'done' | 'cancelled';
startSync: (jobId: string, total: number) => void;
updateProgress: (done: number, skipped: number, failed: number) => void;
complete: (done: number, skipped: number, failed: number) => void;
reset: () => void;
}
export const useDeviceSyncJobStore = create<DeviceSyncJobState>()((set) => ({
jobId: null,
total: 0,
done: 0,
skipped: 0,
failed: 0,
status: 'idle',
startSync: (jobId, total) =>
set({ jobId, total, done: 0, skipped: 0, failed: 0, status: 'running' }),
updateProgress: (done, skipped, failed) =>
set({ done, skipped, failed }),
complete: (done, skipped, failed) =>
set({ done, skipped, failed, status: 'done' }),
reset: () =>
set({ jobId: null, total: 0, done: 0, skipped: 0, failed: 0, status: 'idle' }),
}));
+105
View File
@@ -0,0 +1,105 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
export interface DeviceSyncSource {
type: 'album' | 'playlist' | 'artist';
id: string;
name: string;
}
interface DeviceSyncState {
targetDir: string | null;
filenameTemplate: string;
sources: DeviceSyncSource[]; // persistent device content list
checkedIds: string[]; // currently checked for bulk actions (not persisted)
pendingDeletion: string[]; // source IDs marked for deletion (not persisted)
deviceFilePaths: string[]; // actual file paths found on the device (not persisted)
scanning: boolean; // true while scanning the device
setTargetDir: (dir: string | null) => void;
setFilenameTemplate: (t: string) => void;
addSource: (source: DeviceSyncSource) => void;
removeSource: (id: string) => void;
clearSources: () => void;
toggleChecked: (id: string) => void;
setCheckedIds: (ids: string[]) => void;
markForDeletion: (ids: string[]) => void;
unmarkDeletion: (id: string) => void;
clearPendingDeletion: () => void;
removeSources: (ids: string[]) => void;
setDeviceFilePaths: (paths: string[]) => void;
setScanning: (v: boolean) => void;
}
export const useDeviceSyncStore = create<DeviceSyncState>()(
persist(
(set) => ({
targetDir: null,
filenameTemplate: '{artist}/{album}/{track_number} - {title}',
sources: [],
checkedIds: [],
pendingDeletion: [],
deviceFilePaths: [],
scanning: false,
setTargetDir: (dir) => set({ targetDir: dir }),
setFilenameTemplate: (t) => set({ filenameTemplate: t }),
addSource: (source) =>
set((s) => ({
sources: s.sources.some((x) => x.id === source.id)
? s.sources
: [...s.sources, source],
})),
removeSource: (id) =>
set((s) => ({
sources: s.sources.filter((x) => x.id !== id),
checkedIds: s.checkedIds.filter((x) => x !== id),
pendingDeletion: s.pendingDeletion.filter((x) => x !== id),
})),
clearSources: () => set({ sources: [], checkedIds: [], pendingDeletion: [] }),
toggleChecked: (id) =>
set((s) => ({
checkedIds: s.checkedIds.includes(id)
? s.checkedIds.filter((x) => x !== id)
: [...s.checkedIds, id],
})),
setCheckedIds: (ids) => set({ checkedIds: ids }),
markForDeletion: (ids) =>
set((s) => ({
pendingDeletion: [...new Set([...s.pendingDeletion, ...ids])],
checkedIds: s.checkedIds.filter((x) => !ids.includes(x)),
})),
unmarkDeletion: (id) =>
set((s) => ({
pendingDeletion: s.pendingDeletion.filter((x) => x !== id),
})),
clearPendingDeletion: () => set({ pendingDeletion: [] }),
removeSources: (ids) =>
set((s) => ({
sources: s.sources.filter((x) => !ids.includes(x.id)),
checkedIds: s.checkedIds.filter((x) => !ids.includes(x)),
pendingDeletion: s.pendingDeletion.filter((x) => !ids.includes(x)),
})),
setDeviceFilePaths: (paths) => set({ deviceFilePaths: paths }),
setScanning: (v) => set({ scanning: v }),
}),
{
name: 'psysonic_device_sync',
partialize: (s) => ({
targetDir: s.targetDir,
filenameTemplate: s.filenameTemplate,
sources: s.sources,
}),
}
)
);
+3 -14
View File
@@ -1,18 +1,13 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { invoke } from '@tauri-apps/api/core';
import { formatKeyCode } from './keybindingsStore';
import { MODIFIER_KEY_CODES, formatBinding } from './keybindingsStore';
export type GlobalAction = 'play-pause' | 'next' | 'prev' | 'volume-up' | 'volume-down';
const MODIFIER_CODES = [
'ControlLeft', 'ControlRight', 'AltLeft', 'AltRight',
'ShiftLeft', 'ShiftRight', 'MetaLeft', 'MetaRight', 'OSLeft', 'OSRight',
];
/** Build a Tauri-compatible shortcut string from a KeyboardEvent, or null if invalid. */
export function buildGlobalShortcut(e: KeyboardEvent): string | null {
if (MODIFIER_CODES.includes(e.code)) return null;
if ((MODIFIER_KEY_CODES as readonly string[]).includes(e.code)) return null;
// Require at least Ctrl, Alt, or Meta — Shift alone is too invasive
if (!e.ctrlKey && !e.altKey && !e.metaKey) return null;
@@ -27,13 +22,7 @@ export function buildGlobalShortcut(e: KeyboardEvent): string | null {
/** Human-readable label for a stored shortcut string, e.g. "ctrl+alt+ArrowRight" → "Ctrl+Alt+→". */
export function formatGlobalShortcut(shortcut: string): string {
return shortcut.split('+').map(part => {
if (part === 'ctrl') return 'Ctrl';
if (part === 'alt') return 'Alt';
if (part === 'shift') return 'Shift';
if (part === 'super' || part === 'meta') return 'Super';
return formatKeyCode(part);
}).join('+');
return formatBinding(shortcut);
}
// Module-level guard — prevents double-registration from React StrictMode's
+55 -4
View File
@@ -14,7 +14,13 @@ export type KeyAction =
| 'fullscreen-player'
| 'native-fullscreen';
// key = action, value = e.code string (e.g. 'Space', 'KeyN', 'F11') or null for unbound
/** Physical keys only — ignore for binding capture */
export const MODIFIER_KEY_CODES = [
'ControlLeft', 'ControlRight', 'AltLeft', 'AltRight',
'ShiftLeft', 'ShiftRight', 'MetaLeft', 'MetaRight', 'OSLeft', 'OSRight',
] as const;
// key = action, value = plain e.code ("Space", "KeyN") or chord "ctrl+shift+KeyN", null = unbound
export type Bindings = Record<KeyAction, string | null>;
export const DEFAULT_BINDINGS: Bindings = {
@@ -33,16 +39,49 @@ export const DEFAULT_BINDINGS: Bindings = {
interface KeybindingsState {
bindings: Bindings;
setBinding: (action: KeyAction, code: string | null) => void;
setBinding: (action: KeyAction, binding: string | null) => void;
resetToDefaults: () => void;
}
/** Build persisted binding from a keydown: single key or modifier+key chord. */
export function buildInAppBinding(e: KeyboardEvent): string | null {
if ((MODIFIER_KEY_CODES as readonly string[]).includes(e.code)) return null;
if (!e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey) return e.code;
const mods: string[] = [];
if (e.ctrlKey) mods.push('ctrl');
if (e.altKey) mods.push('alt');
if (e.shiftKey) mods.push('shift');
if (e.metaKey) mods.push('super');
return [...mods, e.code].join('+');
}
/** True if the event matches a stored binding (legacy plain codes = no modifiers). */
export function matchInAppBinding(e: KeyboardEvent, binding: string | null): boolean {
if (!binding) return false;
if (!binding.includes('+')) {
return (
e.code === binding &&
!e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey
);
}
const parts = binding.split('+');
const code = parts[parts.length - 1];
if (e.code !== code) return false;
const mods = new Set(parts.slice(0, -1));
return (
e.ctrlKey === mods.has('ctrl') &&
e.altKey === mods.has('alt') &&
e.shiftKey === mods.has('shift') &&
e.metaKey === mods.has('super')
);
}
export const useKeybindingsStore = create<KeybindingsState>()(
persist(
(set) => ({
bindings: { ...DEFAULT_BINDINGS },
setBinding: (action, code) =>
set(s => ({ bindings: { ...s.bindings, [action]: code } })),
setBinding: (action, binding) =>
set(s => ({ bindings: { ...s.bindings, [action]: binding } })),
resetToDefaults: () => set({ bindings: { ...DEFAULT_BINDINGS } }),
}),
{ name: 'psysonic_keybindings' }
@@ -80,3 +119,15 @@ export function formatKeyCode(code: string): string {
if (code === 'Slash') return '/';
return code;
}
/** Label for settings UI: plain key or chord (same string shape as global shortcuts). */
export function formatBinding(binding: string): string {
if (!binding.includes('+')) return formatKeyCode(binding);
return binding.split('+').map(part => {
if (part === 'ctrl') return 'Ctrl';
if (part === 'alt') return 'Alt';
if (part === 'shift') return 'Shift';
if (part === 'super' || part === 'meta') return 'Super';
return formatKeyCode(part);
}).join('+');
}
+10 -5
View File
@@ -174,10 +174,12 @@ interface PlayerState {
x: number;
y: number;
item: any;
type: 'song' | 'album' | 'artist' | 'queue-item' | 'album-song' | null;
type: 'song' | 'album' | 'artist' | 'queue-item' | 'album-song' | 'playlist' | 'multi-album' | 'multi-artist' | 'multi-playlist' | null;
queueIndex?: number;
playlistId?: string;
playlistSongIndex?: number;
};
openContextMenu: (x: number, y: number, item: any, type: 'song' | 'album' | 'artist' | 'queue-item' | 'album-song', queueIndex?: number) => void;
openContextMenu: (x: number, y: number, item: any, type: 'song' | 'album' | 'artist' | 'queue-item' | 'album-song' | 'playlist' | 'multi-album' | 'multi-artist' | 'multi-playlist', queueIndex?: number, playlistId?: string, playlistSongIndex?: number) => void;
closeContextMenu: () => void;
songInfoModal: { isOpen: boolean; songId: string | null };
@@ -573,9 +575,12 @@ export function initAudioListeners(): () => void {
usePlayerStore.getState().syncLastfmLovedTracks();
// Initial sync of audio settings to Rust engine on startup.
const { crossfadeEnabled, crossfadeSecs, gaplessEnabled } = useAuthStore.getState();
const { crossfadeEnabled, crossfadeSecs, gaplessEnabled, audioOutputDevice } = useAuthStore.getState();
invoke('audio_set_crossfade', { enabled: crossfadeEnabled, secs: crossfadeSecs }).catch(() => {});
invoke('audio_set_gapless', { enabled: gaplessEnabled }).catch(() => {});
if (audioOutputDevice) {
invoke('audio_set_device', { deviceName: audioOutputDevice }).catch(() => {});
}
// Keep audio settings in sync whenever auth store changes.
const unsubAuth = useAuthStore.subscribe((state) => {
@@ -729,8 +734,8 @@ export const usePlayerStore = create<PlayerState>()(
repeatMode: 'off',
contextMenu: { isOpen: false, x: 0, y: 0, item: null, type: null },
openContextMenu: (x, y, item, type, queueIndex) => set({
contextMenu: { isOpen: true, x, y, item, type, queueIndex },
openContextMenu: (x, y, item, type, queueIndex, playlistId, playlistSongIndex) => set({
contextMenu: { isOpen: true, x, y, item, type, queueIndex, playlistId, playlistSongIndex },
}),
closeContextMenu: () => set(state => ({
contextMenu: { ...state.contextMenu, isOpen: false },
+38 -1
View File
@@ -1,22 +1,59 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { getPlaylists, createPlaylist as apiCreatePlaylist, SubsonicPlaylist } from '../api/subsonic';
interface PlaylistStore {
recentIds: string[];
playlists: SubsonicPlaylist[];
playlistsLoading: boolean;
lastModified: Record<string, number>;
touchPlaylist: (id: string) => void;
removeId: (id: string) => void;
fetchPlaylists: () => Promise<void>;
createPlaylist: (name: string, songIds?: string[]) => Promise<SubsonicPlaylist | null>;
addPlaylist: (playlist: SubsonicPlaylist) => void;
}
export const usePlaylistStore = create<PlaylistStore>()(
persist(
(set) => ({
(set, get) => ({
recentIds: [],
playlists: [],
playlistsLoading: false,
lastModified: {},
touchPlaylist: (id) =>
set((s) => ({
recentIds: [id, ...s.recentIds.filter((x) => x !== id)].slice(0, 50),
lastModified: { ...s.lastModified, [id]: Date.now() },
})),
removeId: (id) =>
set((s) => ({ recentIds: s.recentIds.filter((x) => x !== id) })),
fetchPlaylists: async () => {
set({ playlistsLoading: true });
try {
const playlists = await getPlaylists();
set({ playlists, playlistsLoading: false });
} catch {
set({ playlistsLoading: false });
}
},
createPlaylist: async (name: string, songIds?: string[]) => {
try {
const playlist = await apiCreatePlaylist(name, songIds);
set((s) => ({
playlists: [...s.playlists, playlist],
recentIds: [playlist.id, ...s.recentIds.filter((x) => x !== playlist.id)].slice(0, 50),
}));
return playlist;
} catch {
return null;
}
},
addPlaylist: (playlist) => {
set((s) => ({
playlists: [...s.playlists, playlist],
}));
},
}),
{ name: 'psysonic_playlists_recent' }
)
+1
View File
@@ -20,6 +20,7 @@ export const DEFAULT_SIDEBAR_ITEMS: SidebarItemConfig[] = [
{ id: 'mostPlayed', visible: true },
{ id: 'radio', visible: true },
{ id: 'folderBrowser', visible: false },
{ id: 'deviceSync', visible: false },
{ id: 'statistics', visible: true },
{ id: 'help', visible: true },
];
+13 -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' | 'psychowave' | 'wnamp' | 'poison' | 'nucleo' | 'muma-jukebox' | 'winmedplayer' | 'p-dvd' | 'vintage-tube-radio' | 'neon-drift' | 'aero-glass' | 'luna-teal' | 'w98' | 'cupertino-light' | 'cupertino-dark' | 'gruvbox-dark-hard' | 'gruvbox-dark-medium' | 'gruvbox-dark-soft' | 'gruvbox-light-hard' | 'gruvbox-light-medium' | 'gruvbox-light-soft' | 'spotless' | 'dzr0' | 'cupertino-beats' | 'lambda-17' | 'gw1' | 'grand-theft-audio' | 'v-tactical' | 'nightcity-2077' | 'middle-earth' | 'morpheus' | 'stark-hud' | 'blade' | 'heisenberg' | 'ice-and-fire' | 'doh-matic' | 't-800' | 'dune' | 'tetrastack' | 'the-book' | 'readit' | 'insta' | 'hill-valley-85' | 'turtle-power' | 'w3-1' | 'aqua-quartz' | 'spider-tech' | 'dos' | 'unix' | 'jayfin' | 'horde' | 'alliance' | 'w11' | 'w10' | 'north-park' | 'dark-side-of-the-moon' | 'powerslave' | 'nightfox' | 'dayfox' | 'dawnfox' | 'duskfox' | 'nordfox' | 'terafox' | 'carbonfox' | 'dracula';
type Theme = 'mocha' | 'macchiato' | 'frappe' | 'latte' | 'nord' | 'nord-snowstorm' | 'nord-frost' | 'nord-aurora' | 'psychowave' | 'wnamp' | 'poison' | 'nucleo' | 'muma-jukebox' | 'winmedplayer' | 'p-dvd' | 'vintage-tube-radio' | 'neon-drift' | 'aero-glass' | 'luna-teal' | 'w98' | 'cupertino-light' | 'cupertino-dark' | 'gruvbox-dark-hard' | 'gruvbox-dark-medium' | 'gruvbox-dark-soft' | 'gruvbox-light-hard' | 'gruvbox-light-medium' | 'gruvbox-light-soft' | 'spotless' | 'dzr0' | 'cupertino-beats' | 'lambda-17' | 'gw1' | 'grand-theft-audio' | 'v-tactical' | 'nightcity-2077' | 'middle-earth' | 'morpheus' | 'stark-hud' | 'blade' | 'heisenberg' | 'ice-and-fire' | 'doh-matic' | 't-800' | 'dune' | 'tetrastack' | 'the-book' | 'readit' | 'insta' | 'hill-valley-85' | 'turtle-power' | 'w3-1' | 'aqua-quartz' | 'spider-tech' | 'dos' | 'unix' | 'jayfin' | 'horde' | 'alliance' | 'w11' | 'w10' | 'north-park' | 'dark-side-of-the-moon' | 'powerslave' | 'nightfox' | 'dayfox' | 'dawnfox' | 'duskfox' | 'nordfox' | 'terafox' | 'carbonfox' | 'dracula' | 'vision-dark' | 'vision-navy';
interface ThemeState {
theme: Theme;
@@ -16,6 +16,12 @@ interface ThemeState {
setTimeDayStart: (v: string) => void;
timeNightStart: string;
setTimeNightStart: (v: string) => void;
enableCoverArtBackground: boolean;
setEnableCoverArtBackground: (v: boolean) => void;
enablePlaylistCoverPhoto: boolean;
setEnablePlaylistCoverPhoto: (v: boolean) => void;
showBitrate: boolean;
setShowBitrate: (v: boolean) => void;
}
export function getScheduledTheme(state: Pick<ThemeState, 'enableThemeScheduler' | 'theme' | 'themeDay' | 'themeNight' | 'timeDayStart' | 'timeNightStart'>): string {
@@ -47,6 +53,12 @@ export const useThemeStore = create<ThemeState>()(
setTimeDayStart: (v) => set({ timeDayStart: v }),
timeNightStart: '19:00',
setTimeNightStart: (v) => set({ timeNightStart: v }),
enableCoverArtBackground: true,
setEnableCoverArtBackground: (v) => set({ enableCoverArtBackground: v }),
enablePlaylistCoverPhoto: true,
setEnablePlaylistCoverPhoto: (v) => set({ enablePlaylistCoverPhoto: v }),
showBitrate: true,
setShowBitrate: (v) => set({ showBitrate: v }),
}),
{
name: 'psysonic_theme',
+713 -1
View File
@@ -198,6 +198,7 @@
/* ─ Album Card ─ */
.album-card {
position: relative;
cursor: pointer;
background: var(--bg-card);
border-radius: var(--radius-lg);
@@ -519,6 +520,33 @@
color: var(--ctp-crust);
}
/* ─── Artist Card Selection Checkbox ─── */
.artist-card {
position: relative;
}
.artist-card-select-check {
position: absolute;
top: 6px;
left: 6px;
width: 20px;
height: 20px;
border-radius: var(--radius-sm);
border: 2px solid var(--border-subtle);
background: var(--bg-elevated);
display: flex;
align-items: center;
justify-content: center;
z-index: 10;
pointer-events: none;
}
.artist-card-select-check--on {
background: var(--accent);
border-color: var(--accent);
color: var(--ctp-crust);
}
/* ── Albums selection bar (portal) ── */
.albums-selection-bar {
position: fixed;
@@ -3498,10 +3526,11 @@ html.no-compositing .fs-close {
background: rgba(0, 0, 0, 0.45);
}
/* Portrait: remove CSS filter (drop-shadow) and will-change */
/* Portrait: remove CSS filter (drop-shadow), will-change and drift animation */
html.no-compositing .fs-portrait {
filter: none;
will-change: auto;
animation: none;
}
/* Portrait wrap: replace mask-image fade with a pseudo-element overlay gradient.
@@ -3535,6 +3564,20 @@ html.no-compositing .fs-lyrics-rail {
will-change: auto;
}
/* Mesh blobs: stop animations in software mode each frame composites surfaces
larger than the screen (blob-a is 130 × 130 % of the viewport); on high-DPI
displays this saturates the CPU and drops the player to ~10 FPS.
Static gradients are preserved; only the slow pan animation is removed. */
html.no-compositing .fs-mesh-blob {
animation: none;
}
/* Seekbar played bar: remove box-shadow its width changes on every playback
tick; in software rendering each change triggers a box-shadow repaint. */
html.no-compositing .fs-seekbar-played {
box-shadow: none;
}
/* Chat */
.chat-popup {
position: absolute;
@@ -3685,6 +3728,7 @@ html.no-compositing .fs-lyrics-rail {
backdrop-filter: blur(16px);
color: var(--text-primary);
font-size: 13px;
outline: none;
}
.context-menu-item {
@@ -7268,6 +7312,35 @@ html.no-compositing .fs-lyrics-rail {
text-align: center;
}
.folder-col-filter {
position: sticky;
top: 0;
z-index: 2;
padding: 0.35rem 0.45rem;
background: color-mix(in srgb, var(--bg-app) 92%, transparent);
border-bottom: 1px solid var(--border-subtle);
}
.folder-col-filter-input {
width: 100%;
padding: 0.35rem 0.5rem;
border-radius: var(--radius-sm);
border: 1px solid var(--border-subtle);
background: var(--bg-card);
color: var(--text-primary);
font-size: 0.78rem;
}
.folder-col-filter-input:focus {
outline: none;
border-color: color-mix(in srgb, var(--accent) 70%, var(--border-subtle));
box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 20%, transparent);
}
.folder-col.folder-col--compact .folder-col-filter {
display: none;
}
.folder-col-error {
color: var(--danger, #f38ba8);
}
@@ -7485,3 +7558,642 @@ html.no-compositing .fs-lyrics-rail {
0% { transform: translateX(-100%); }
100% { transform: translateX(350%); }
}
/* ─── Device Sync ─────────────────────────────────────────────────────────── */
.device-sync-page {
display: flex;
flex-direction: column;
height: 100%;
padding: 24px 28px;
overflow: hidden;
}
/* ── Header ── */
.device-sync-header {
display: flex;
flex-direction: column;
gap: 16px;
margin-bottom: 20px;
flex-shrink: 0;
}
.device-sync-header-title {
display: flex;
align-items: center;
gap: 10px;
color: var(--text-primary);
}
.device-sync-header-title h1 {
font-size: 1.3rem;
font-weight: 600;
margin: 0;
}
/* ── Config Row (Template + Drive Layout) ── */
.device-sync-config-row {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: flex-start;
gap: 30px;
min-height: 0;
width: 100%;
}
.device-sync-template-section {
display: flex;
flex-direction: column;
gap: 6px;
flex: 1;
max-width: 600px;
}
.device-sync-target-section {
display: flex;
flex-direction: column;
gap: 6px;
align-items: flex-end; /* Flush right alignment */
flex: 1; /* allow block expansion */
}
.device-sync-folder-path {
max-width: 260px;
font-size: 0.8rem;
color: var(--text-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
padding: 5px 8px;
background: var(--bg-input);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
}
/* ── Drive layout ── */
.device-sync-drive-layout {
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 4px;
}
.device-sync-drive-controls {
display: flex;
align-items: center;
gap: 8px;
}
.device-sync-drive-meta {
font-size: 0.75rem;
color: var(--text-muted);
text-align: right;
padding-right: 2px;
}
.device-sync-drive-icon {
color: var(--accent);
flex-shrink: 0;
}
.device-sync-drive-select {
min-width: 200px;
max-width: 320px;
font-size: 0.95rem;
height: 40px;
padding: 0 10px;
line-height: normal;
display: flex;
align-items: center;
justify-content: space-between;
text-align: left;
cursor: pointer;
}
.device-sync-drive-controls .btn-ghost {
height: 40px;
width: 40px;
padding: 0 !important;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.device-sync-no-drives {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 0.78rem;
color: var(--warning, #f59e0b);
padding: 5px 10px;
background: color-mix(in srgb, var(--warning, #f59e0b) 10%, transparent);
border-radius: var(--radius-sm);
}
.device-sync-label-inline {
font-size: 0.8rem;
font-weight: 500;
color: var(--text-secondary);
white-space: nowrap;
}
.device-sync-template-input-wrap {
display: flex;
flex-direction: column;
gap: 4px;
position: relative;
}
.device-sync-template-input {
width: 100%;
font-family: monospace;
font-size: 0.95rem;
height: 40px;
padding: 0 10px;
line-height: normal;
}
.device-sync-template-preview {
font-size: 0.72rem;
color: var(--text-muted);
font-family: monospace;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
padding-left: 2px;
opacity: 0.75;
position: absolute;
top: 100%;
left: 0;
margin-top: 4px;
}
/* ── Main area (device panel + browser) ── */
.device-sync-main {
display: flex;
flex: 1;
min-height: 0;
gap: 1px;
background: var(--border);
border: 1px solid var(--border);
border-radius: var(--radius);
overflow: hidden;
}
/* ── Device panel ── */
.device-sync-device-panel {
display: flex;
flex-direction: column;
flex: 1;
min-width: 0;
background: var(--bg-card);
overflow: hidden;
}
.device-sync-panel-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 14px;
height: 52px;
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.device-sync-panel-title {
font-size: 0.85rem;
font-weight: 600;
color: var(--text-primary);
}
.device-sync-panel-actions {
display: flex;
align-items: center;
gap: 6px;
}
.device-sync-add-btn {
display: flex;
align-items: center;
gap: 5px;
}
.device-sync-empty {
font-size: 0.82rem;
color: var(--text-secondary);
padding: 20px 14px;
margin: 0;
}
/* ── Device list ── */
.device-sync-list-header {
display: flex;
align-items: center;
gap: 8px;
height: 52px;
padding: 0 14px;
background: var(--bg-secondary);
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.device-sync-check-label {
display: flex;
align-items: center;
flex-shrink: 0;
cursor: pointer;
}
.device-sync-list-col-name {
flex: 1;
font-size: 0.75rem;
font-weight: 600;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.04em;
}
.device-sync-list-col-type {
width: 70px;
font-size: 0.75rem;
font-weight: 600;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.04em;
flex-shrink: 0;
}
.device-sync-device-list {
flex: 1;
overflow-y: auto;
}
.device-sync-device-row {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 14px;
cursor: pointer;
transition: background 0.1s;
border-bottom: 1px solid var(--border);
font-size: 0.85rem;
color: var(--text-primary);
}
.device-sync-device-row:last-child { border-bottom: none; }
.device-sync-source-row:hover {
background: var(--bg-hover);
}
.device-sync-source-row.deletion, .device-sync-row.deletion {
text-decoration: line-through;
opacity: 0.5;
}
.device-sync-row-name {
flex: 1;
}
.device-sync-device-row.checked { background: var(--accent-dim); }
.device-sync-source-type {
width: 70px;
font-size: 0.7rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--accent);
flex-shrink: 0;
}
/* ── Status summary badges ── */
.device-sync-status-summary {
display: flex;
align-items: center;
gap: 8px;
height: 52px;
padding: 0 14px;
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.device-sync-badge {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 3px 8px;
border-radius: 12px;
font-size: 0.7rem;
font-weight: 600;
letter-spacing: 0.02em;
}
.device-sync-badge.synced {
background: color-mix(in srgb, var(--success, #4ade80) 15%, transparent);
color: var(--success, #4ade80);
}
.device-sync-badge.pending {
background: color-mix(in srgb, var(--warning, #f59e0b) 15%, transparent);
color: var(--warning, #f59e0b);
}
.device-sync-badge.deletion {
background: color-mix(in srgb, var(--danger, #f38ba8) 15%, transparent);
color: var(--danger, #f38ba8);
}
/* ── Status column ── */
.device-sync-list-col-status {
width: 50px;
font-size: 0.75rem;
font-weight: 600;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.04em;
flex-shrink: 0;
text-align: center;
}
.device-sync-list-col-actions {
width: 32px;
flex-shrink: 0;
}
/* ── Status icons per row ── */
.device-sync-status-icon {
width: 50px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.device-sync-status-icon.synced { color: var(--success, #4ade80); }
.device-sync-status-icon.pending { color: var(--warning, #f59e0b); }
.device-sync-status-icon.deletion { color: var(--danger, #f38ba8); }
/* ── Per-row action buttons ── */
.device-sync-row-actions {
width: 32px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.device-sync-action-btn {
display: flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
border: none;
background: transparent;
border-radius: var(--radius-sm);
cursor: pointer;
transition: background 0.15s, color 0.15s, transform 0.1s;
opacity: 0;
}
.device-sync-device-row:hover .device-sync-action-btn {
opacity: 1;
}
.device-sync-action-btn.danger {
color: var(--danger, #f38ba8);
}
.device-sync-action-btn.danger:hover {
background: color-mix(in srgb, var(--danger, #f38ba8) 15%, transparent);
transform: scale(1.1);
}
.device-sync-action-btn.muted {
color: var(--text-muted);
}
.device-sync-action-btn.muted:hover {
background: var(--bg-hover);
color: var(--text-primary);
transform: scale(1.1);
}
.device-sync-action-btn.undo {
color: var(--accent);
opacity: 1;
}
.device-sync-action-btn.undo:hover {
background: color-mix(in srgb, var(--accent) 15%, transparent);
transform: scale(1.1);
}
/* ── Row status variants ── */
.device-sync-device-row.synced {}
.device-sync-device-row.pending {}
.device-sync-device-row.deletion {
opacity: 0.55;
}
.device-sync-device-row.deletion .device-sync-row-name {
text-decoration: line-through;
text-decoration-color: var(--danger, #f38ba8);
}
/* ── Background sync progress (non-blocking) ── */
.device-sync-bg-progress {
display: flex;
flex-direction: column;
gap: 6px;
padding: 10px 14px;
border-top: 1px solid var(--border);
flex-shrink: 0;
background: color-mix(in srgb, var(--accent) 4%, transparent);
}
.device-sync-bg-progress.done {
flex-direction: row;
align-items: center;
justify-content: space-between;
background: color-mix(in srgb, var(--success, #4ade80) 4%, transparent);
}
.device-sync-bg-progress-bar-wrap {
height: 3px;
background: var(--bg-input);
border-radius: 2px;
overflow: hidden;
}
.device-sync-bg-progress-bar {
height: 100%;
background: var(--accent);
border-radius: 2px;
transition: width 0.3s ease;
}
.device-sync-bg-progress-text {
display: flex;
align-items: center;
gap: 6px;
font-size: 0.78rem;
color: var(--text-secondary);
}
.device-sync-stat-error { color: var(--danger); display: flex; align-items: center; gap: 3px; }
.color-success { color: var(--success, #4ade80); }
/* ── Browser panel ── */
.device-sync-browser {
display: flex;
flex-direction: column;
flex: 1;
background: var(--bg-card);
overflow: hidden;
}
.device-sync-tabs {
display: flex;
height: 52px;
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.device-sync-tab {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
padding: 0 8px;
font-size: 0.8rem;
font-weight: 500;
color: var(--text-secondary);
background: transparent;
border: none;
cursor: pointer;
transition: color 0.15s, background 0.15s;
}
.device-sync-tab:hover { color: var(--text-primary); background: var(--bg-hover); }
.device-sync-tab.active { color: var(--accent); border-bottom: 2px solid var(--accent); }
.device-sync-search-wrap {
display: flex;
align-items: center;
height: 52px;
padding: 0 10px;
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.device-sync-search-wrap .input {
flex: 1;
}
.device-sync-live-badge {
display: flex;
align-items: center;
gap: 3px;
flex-shrink: 0;
margin-left: 8px;
padding: 2px 7px;
border-radius: 999px;
font-size: 0.68rem;
font-weight: 600;
letter-spacing: 0.03em;
color: var(--accent);
background: var(--accent-dim);
white-space: nowrap;
}
.device-sync-section-label {
display: flex;
align-items: center;
gap: 5px;
padding: 6px 10px 4px;
font-size: 0.7rem;
font-weight: 600;
letter-spacing: 0.05em;
text-transform: uppercase;
color: var(--text-muted);
}
.device-sync-list {
flex: 1;
overflow-y: auto;
}
.device-sync-loading {
display: flex;
justify-content: center;
padding: 24px;
color: var(--text-secondary);
}
.device-sync-browser-row {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 8px 12px;
text-align: left;
background: transparent;
border: none;
cursor: pointer;
transition: background 0.12s;
color: var(--text-primary);
}
.device-sync-browser-row:hover { background: var(--bg-hover); }
.device-sync-browser-row.selected { background: var(--accent-dim); }
.device-sync-browser-row.indent { padding-left: 36px; background: var(--bg-secondary); }
.device-sync-browser-row.indent:hover { background: var(--bg-hover); }
.device-sync-browser-row.indent.selected { background: var(--accent-dim); }
.device-sync-artist-row {
display: flex;
align-items: center;
gap: 6px;
padding: 8px 12px;
font-size: 0.85rem;
color: var(--text-primary);
border-bottom: 1px solid var(--border);
}
.device-sync-expand-btn {
display: flex;
align-items: center;
background: transparent;
border: none;
cursor: pointer;
color: var(--text-secondary);
padding: 2px;
flex-shrink: 0;
transition: color 0.12s;
}
.device-sync-expand-btn:hover { color: var(--text-primary); }
.device-sync-row-check { color: var(--accent); display: flex; flex-shrink: 0; }
.device-sync-row-circle {
width: 15px;
height: 15px;
border-radius: 50%;
border: 1.5px solid var(--border);
display: block;
}
.device-sync-row-name { flex: 1; font-size: 0.85rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.device-sync-row-meta { font-size: 0.75rem; color: var(--text-secondary); flex-shrink: 0; }
+147
View File
@@ -912,6 +912,13 @@
background: color-mix(in srgb, var(--accent) 20%, transparent);
}
/* ─── Sidebar device-sync queue ─── */
.sidebar-sync-queue {
background: color-mix(in srgb, var(--success, #4ade80) 10%, var(--bg-sidebar));
border-color: color-mix(in srgb, var(--success, #4ade80) 25%, transparent);
color: var(--success, #4ade80);
}
@keyframes spin-slow {
to { transform: rotate(360deg); }
}
@@ -2306,3 +2313,143 @@
color: inherit;
opacity: 0.7;
}
/* ─── Sidebar Expandable Playlists Section ─── */
.sidebar-playlists-wrapper {
display: flex;
flex-direction: column;
}
.sidebar-playlists-header-row {
display: flex;
align-items: center;
gap: var(--space-1);
padding-right: var(--space-2);
}
.sidebar-playlists-main-link {
flex: 1;
min-width: 0;
}
.sidebar-playlists-toggle {
display: flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
padding: 0;
border-radius: var(--radius-md);
background: transparent;
border: none;
color: var(--text-muted);
cursor: pointer;
transition: all var(--transition-fast);
flex-shrink: 0;
}
.sidebar-playlists-toggle:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.sidebar-playlists-toggle.expanded {
transform: rotate(90deg);
color: var(--accent);
}
.sidebar-playlists-section {
display: flex;
flex-direction: column;
}
.sidebar-playlists-header {
display: flex;
align-items: center;
gap: var(--space-3);
width: 100%;
padding: var(--space-2) var(--space-3);
border-radius: var(--radius-md);
color: var(--text-secondary);
font-size: 14px;
font-weight: 500;
transition: background var(--transition-fast), color var(--transition-fast);
cursor: pointer;
background: transparent;
border: none;
text-align: left;
}
.sidebar-playlists-header:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.sidebar-playlists-header.active {
background: var(--accent-dim);
color: var(--accent);
}
.sidebar-playlists-chevron {
margin-left: auto;
transition: transform 0.2s ease;
flex-shrink: 0;
}
.sidebar-playlists-chevron.expanded {
transform: rotate(90deg);
}
.sidebar-playlists-list {
display: flex;
flex-direction: column;
padding-left: var(--space-4);
padding-top: var(--space-1);
padding-bottom: var(--space-1);
gap: var(--space-1);
}
.sidebar-playlist-item {
display: flex;
align-items: center;
gap: var(--space-2);
padding: var(--space-1) var(--space-2);
border-radius: var(--radius-md);
color: var(--text-secondary);
font-size: 13px;
font-weight: 400;
transition: background var(--transition-fast), color var(--transition-fast);
overflow: hidden;
}
.sidebar-playlist-item span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
min-width: 0;
}
.sidebar-playlist-item:hover {
background: var(--bg-hover);
color: var(--text-primary);
}
.sidebar-playlist-item.active {
background: var(--accent-dim);
color: var(--accent);
}
.sidebar-playlists-loading {
display: flex;
align-items: center;
justify-content: center;
padding: var(--space-2);
}
.sidebar-playlists-empty {
padding: var(--space-2);
font-size: 12px;
color: var(--text-muted);
font-style: italic;
}
+644
View File
@@ -14317,3 +14317,647 @@ input[type="range"]:hover::-webkit-slider-thumb {
--warning: #ffb86c;
--danger: #ff5555;
}
/* ─── Vision Dark — Purple & Gold, colorblind-safe (Deuteranopia / Protanopia / Tritanopia) ─── */
/* Gold #FFD700 on #0D0B12 → contrast ~14.7:1 (WCAG AAA) */
[data-theme='vision-dark'] {
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%23C8C4D4%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");
--ctp-crust: #030210;
--ctp-mantle: #06050e;
--ctp-base: #0d0b12;
--ctp-surface0: #16131e;
--ctp-surface1: #201c2c;
--ctp-surface2: #2c2838;
--ctp-overlay0: #544e6a;
--ctp-overlay1: #6e6886;
--ctp-overlay2: #8a84a0;
--ctp-text: #f2eef8;
--ctp-subtext1: #c8c4d4;
--ctp-subtext0: #9c98aa;
--ctp-mauve: #8b5cf6; /* Purple — secondary accent */
--ctp-lavender: #a07af8;
--ctp-blue: #60a5fa;
--ctp-sapphire: #38bdf8;
--ctp-sky: #38bdf8;
--ctp-teal: #2dd4bf;
--ctp-green: #009e73; /* Okabe-Ito Bluish Green */
--ctp-yellow: #ffd700; /* Gold */
--ctp-peach: #e69f00;
--ctp-maroon: #d55e00; /* Okabe-Ito Vermillion — danger */
--ctp-red: #d55e00;
--ctp-flamingo: #f472b6;
--ctp-pink: #e879f9;
--ctp-rosewater: #f0abfc;
--bg-app: #0d0b12;
--bg-sidebar: #08060e;
--bg-card: #16131e;
--bg-hover: #201c2c;
--bg-player: #050310;
--bg-glass: rgba(13, 11, 18, 0.84);
--accent: #ffd700;
--accent-dim: rgba(255, 215, 0, 0.14);
--accent-glow: rgba(255, 215, 0, 0.36);
--text-primary: #f2eef8;
--text-secondary: #c8c4d4;
--text-muted: #7e7a8e;
--border: #201c2c;
--border-subtle: #16131e;
--positive: #009e73;
--warning: #e69f00;
--danger: #d55e00;
--volume-accent: #ffd700;
}
/* ─── Vision Navy — Purple & Gold, colorblind-safe (Deuteranopia / Protanopia / Tritanopia) ─── */
/* Gold #FFD700 on #0A1628 → contrast ~14.5:1 (WCAG AAA) */
[data-theme='vision-navy'] {
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%23C0C8D8%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");
--ctp-crust: #030a14;
--ctp-mantle: #060e1c;
--ctp-base: #0a1628;
--ctp-surface0: #112038;
--ctp-surface1: #1a2e48;
--ctp-surface2: #243c58;
--ctp-overlay0: #486480;
--ctp-overlay1: #607a98;
--ctp-overlay2: #7890ae;
--ctp-text: #eef2f8;
--ctp-subtext1: #c0c8d8;
--ctp-subtext0: #8898ae;
--ctp-mauve: #8b5cf6; /* Purple — secondary accent */
--ctp-lavender: #a07af8;
--ctp-blue: #3b82f6;
--ctp-sapphire: #38bdf8;
--ctp-sky: #7dd3fc;
--ctp-teal: #2dd4bf;
--ctp-green: #009e73; /* Okabe-Ito Bluish Green */
--ctp-yellow: #ffd700; /* Gold */
--ctp-peach: #e69f00;
--ctp-maroon: #d55e00; /* Okabe-Ito Vermillion */
--ctp-red: #d55e00;
--ctp-flamingo: #f472b6;
--ctp-pink: #e879f9;
--ctp-rosewater: #f0abfc;
--bg-app: #0a1628;
--bg-sidebar: #060e1c;
--bg-card: #112038;
--bg-hover: #1a2e48;
--bg-player: #040c18;
--bg-glass: rgba(10, 22, 40, 0.84);
--accent: #ffd700;
--accent-dim: rgba(255, 215, 0, 0.14);
--accent-glow: rgba(255, 215, 0, 0.36);
--text-primary: #eef2f8;
--text-secondary: #c0c8d8;
--text-muted: #607080;
--border: #1a2e48;
--border-subtle: #112038;
--positive: #009e73;
--warning: #e69f00;
--danger: #d55e00;
--volume-accent: #ffd700;
}
/* ─── COMMUNITY THEMES ─── */
/* ─── AMOLED Black Pure ─── */
[data-theme='amoled-black-pure'] {
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%23ffffff%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");
/* Backgrounds — absolute black everywhere */
--ctp-crust: #000000;
--ctp-mantle: #000000;
--ctp-base: #000000;
--ctp-surface0: #000000;
--ctp-surface1: #050505;
--ctp-surface2: #0a0a0a;
/* Overlays / muted text — raised for contrast */
--ctp-overlay0: #555555;
--ctp-overlay1: #707070;
--ctp-overlay2: #8a8a8a;
/* Text */
--ctp-text: #ffffff;
--ctp-subtext1: #e0e0e0;
--ctp-subtext0: #bbbbbb;
/* Accent — pure white */
--ctp-teal: #ffffff;
--ctp-sky: #ffffff;
--ctp-sapphire: #e0e0e0;
--ctp-blue: #cccccc;
--ctp-lavender: #ffffff;
--ctp-mauve: #e0e0e0;
--ctp-pink: #cccccc;
--ctp-flamingo: #ffffff;
--ctp-rosewater: #e0e0e0;
/* Semantic */
--ctp-red: #f87171;
--ctp-maroon: #fb923c;
--ctp-peach: #fb923c;
--ctp-yellow: #fbbf24;
--ctp-green: #4ade80;
/* UI tokens — all black */
--bg-app: #000000;
--bg-sidebar: #000000;
--bg-card: #000000;
--bg-hover: #0a0a0a;
--bg-player: #000000;
--bg-glass: rgba(0, 0, 0, 0.95);
--accent: #ffffff;
--accent-dim: rgba(255, 255, 255, 0.07);
--accent-glow: rgba(255, 255, 255, 0.15);
--text-primary: #ffffff;
--text-secondary: #b0b0b0;
--text-muted: #777777;
--border: #141414;
--border-subtle: #0a0a0a;
--border-dropdown: #1f1f1f;
--shadow-dropdown: rgba(0, 0, 0, 0.98);
--positive: #4ade80;
--warning: #fbbf24;
--danger: #f87171;
}
/* ─── Monochrome Dark ─── */
[data-theme='monochrome'] {
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%23c0c0c0%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");
/* Backgrounds — deep grayscale */
--ctp-crust: #0d0d0d;
--ctp-mantle: #111111;
--ctp-base: #161616;
--ctp-surface0: #1c1c1c;
--ctp-surface1: #232323;
--ctp-surface2: #2a2a2a;
/* Overlays — medium grays with good contrast */
--ctp-overlay0: #555555;
--ctp-overlay1: #6e6e6e;
--ctp-overlay2: #888888;
/* Text */
--ctp-text: #e8e8e8;
--ctp-subtext1: #c0c0c0;
--ctp-subtext0: #999999;
/* Accent — silver / light gray */
--ctp-teal: #c0c0c0;
--ctp-sky: #c0c0c0;
--ctp-sapphire: #aaaaaa;
--ctp-blue: #999999;
--ctp-lavender: #c0c0c0;
--ctp-mauve: #aaaaaa;
--ctp-pink: #999999;
--ctp-flamingo: #c0c0c0;
--ctp-rosewater: #aaaaaa;
/* Semantic — desaturated for monochrome */
--ctp-red: #cc6666;
--ctp-maroon: #bb7744;
--ctp-peach: #bb7744;
--ctp-yellow: #bbaa55;
--ctp-green: #77aa77;
/* UI tokens */
--bg-app: #161616;
--bg-sidebar: #111111;
--bg-card: #1c1c1c;
--bg-hover: #232323;
--bg-player: #111111;
--bg-glass: rgba(22, 22, 22, 0.95);
--accent: #c0c0c0;
--accent-dim: rgba(192, 192, 192, 0.07);
--accent-glow: rgba(192, 192, 192, 0.12);
--text-primary: #e8e8e8;
--text-secondary: #b0b0b0;
--text-muted: #777777;
--border: #282828;
--border-subtle: #1f1f1f;
--border-dropdown: #303030;
--shadow-dropdown: rgba(0, 0, 0, 0.85);
--positive: #77aa77;
--warning: #bbaa55;
--danger: #cc6666;
}
/* ─── Amber Night ─── */
[data-theme='amber-night'] {
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%23d4a96a%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");
/* Backgrounds */
--ctp-crust: #0a0804;
--ctp-mantle: #0f0c07;
--ctp-base: #1a1410;
--ctp-surface0: #201a12;
--ctp-surface1: #2a2318;
--ctp-surface2: #332b1e;
/* Overlays */
--ctp-overlay0: #5a4a30;
--ctp-overlay1: #7a6540;
--ctp-overlay2: #9a8055;
/* Text */
--ctp-text: #f0e0c8;
--ctp-subtext1: #d4b88a;
--ctp-subtext0: #b09060;
/* Golden amber accent */
--ctp-teal: #d4a96a;
--ctp-sky: #d4a96a;
--ctp-sapphire: #c49055;
--ctp-blue: #b07840;
--ctp-lavender: #d4a96a;
--ctp-mauve: #c49055;
--ctp-pink: #b07840;
--ctp-flamingo: #d4a96a;
--ctp-rosewater: #c49055;
/* Semantic */
--ctp-red: #e07060;
--ctp-maroon: #d08050;
--ctp-peach: #d08050;
--ctp-yellow: #d4a96a;
--ctp-green: #80b870;
/* UI tokens */
--bg-app: #1a1410;
--bg-sidebar: #0f0c07;
--bg-card: #201a12;
--bg-hover: #2a2318;
--bg-player: #0f0c07;
--bg-glass: rgba(26, 20, 16, 0.95);
--accent: #d4a96a;
--accent-dim: rgba(212, 169, 106, 0.08);
--accent-glow: rgba(212, 169, 106, 0.15);
--text-primary: #f0e0c8;
--text-secondary: #b09060;
--text-muted: #7a6040;
--border: #2a2318;
--border-subtle: #201a12;
--border-dropdown: #332b1e;
--shadow-dropdown: rgba(0, 0, 0, 0.90);
--positive: #80b870;
--warning: #d4a96a;
--danger: #e07060;
}
/* ─── Phosphor Green ─── */
[data-theme='phosphor-green'] {
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%234ade80%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");
/* Backgrounds */
--ctp-crust: #050e05;
--ctp-mantle: #070f07;
--ctp-base: #0d1a0d;
--ctp-surface0: #111f11;
--ctp-surface1: #162616;
--ctp-surface2: #1c2e1c;
/* Overlays */
--ctp-overlay0: #2d5a2d;
--ctp-overlay1: #3d7a3d;
--ctp-overlay2: #4d9a4d;
/* Text */
--ctp-text: #d0f0d0;
--ctp-subtext1: #a0d0a0;
--ctp-subtext0: #70aa70;
/* Phosphor green accent */
--ctp-teal: #4ade80;
--ctp-sky: #4ade80;
--ctp-sapphire: #38c070;
--ctp-blue: #2aa060;
--ctp-lavender: #4ade80;
--ctp-mauve: #38c070;
--ctp-pink: #2aa060;
--ctp-flamingo: #4ade80;
--ctp-rosewater: #38c070;
/* Semantic */
--ctp-red: #e06060;
--ctp-maroon: #c07840;
--ctp-peach: #c07840;
--ctp-yellow: #b0b050;
--ctp-green: #4ade80;
/* UI tokens */
--bg-app: #0d1a0d;
--bg-sidebar: #070f07;
--bg-card: #111f11;
--bg-hover: #162616;
--bg-player: #070f07;
--bg-glass: rgba(13, 26, 13, 0.95);
--accent: #4ade80;
--accent-dim: rgba(74, 222, 128, 0.07);
--accent-glow: rgba(74, 222, 128, 0.14);
--text-primary: #d0f0d0;
--text-secondary: #70aa70;
--text-muted: #3d6a3d;
--border: #1c2e1c;
--border-subtle: #111f11;
--border-dropdown: #223022;
--shadow-dropdown: rgba(0, 0, 0, 0.88);
--positive: #4ade80;
--warning: #b0b050;
--danger: #e06060;
}
/* ─── Midnight Blue ─── */
[data-theme='midnight-blue'] {
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%2360a5fa%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");
/* Backgrounds */
--ctp-crust: #07090f;
--ctp-mantle: #090c14;
--ctp-base: #0d1420;
--ctp-surface0: #111a28;
--ctp-surface1: #162030;
--ctp-surface2: #1c2838;
/* Overlays */
--ctp-overlay0: #2a3d5a;
--ctp-overlay1: #3a507a;
--ctp-overlay2: #4a659a;
/* Text */
--ctp-text: #ccd8f0;
--ctp-subtext1: #9ab0d8;
--ctp-subtext0: #6888b0;
/* Light blue accent */
--ctp-teal: #60a5fa;
--ctp-sky: #60a5fa;
--ctp-sapphire: #4a90e8;
--ctp-blue: #3878d0;
--ctp-lavender: #60a5fa;
--ctp-mauve: #4a90e8;
--ctp-pink: #3878d0;
--ctp-flamingo: #60a5fa;
--ctp-rosewater: #4a90e8;
/* Semantic */
--ctp-red: #e07070;
--ctp-maroon: #d09050;
--ctp-peach: #d09050;
--ctp-yellow: #c8b850;
--ctp-green: #60c880;
/* UI tokens */
--bg-app: #0d1420;
--bg-sidebar: #090c14;
--bg-card: #111a28;
--bg-hover: #162030;
--bg-player: #090c14;
--bg-glass: rgba(13, 20, 32, 0.95);
--accent: #60a5fa;
--accent-dim: rgba(96, 165, 250, 0.07);
--accent-glow: rgba(96, 165, 250, 0.14);
--text-primary: #ccd8f0;
--text-secondary: #6888b0;
--text-muted: #3a5070;
--border: #1c2838;
--border-subtle: #111a28;
--border-dropdown: #223040;
--shadow-dropdown: rgba(0, 0, 0, 0.90);
--positive: #60c880;
--warning: #c8b850;
--danger: #e07070;
}
/* ─── Rose Dark ─── */
[data-theme='rose-dark'] {
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%23f472b6%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");
/* Backgrounds */
--ctp-crust: #0e080b;
--ctp-mantle: #120a0e;
--ctp-base: #1a0d14;
--ctp-surface0: #20111a;
--ctp-surface1: #281520;
--ctp-surface2: #301a27;
/* Overlays */
--ctp-overlay0: #5a2a40;
--ctp-overlay1: #7a3a58;
--ctp-overlay2: #9a5070;
/* Text */
--ctp-text: #f0d0e0;
--ctp-subtext1: #d8a0c0;
--ctp-subtext0: #b07090;
/* Pink accent */
--ctp-teal: #f472b6;
--ctp-sky: #f472b6;
--ctp-sapphire: #e055a0;
--ctp-blue: #c8408a;
--ctp-lavender: #f472b6;
--ctp-mauve: #e055a0;
--ctp-pink: #c8408a;
--ctp-flamingo: #f472b6;
--ctp-rosewater: #e055a0;
/* Semantic */
--ctp-red: #e06070;
--ctp-maroon: #d07850;
--ctp-peach: #d07850;
--ctp-yellow: #c8a850;
--ctp-green: #70b880;
/* UI tokens */
--bg-app: #1a0d14;
--bg-sidebar: #120a0e;
--bg-card: #20111a;
--bg-hover: #281520;
--bg-player: #120a0e;
--bg-glass: rgba(26, 13, 20, 0.95);
--accent: #f472b6;
--accent-dim: rgba(244, 114, 182, 0.07);
--accent-glow: rgba(244, 114, 182, 0.14);
--text-primary: #f0d0e0;
--text-secondary: #b07090;
--text-muted: #704858;
--border: #281520;
--border-subtle: #20111a;
--border-dropdown: #341a28;
--shadow-dropdown: rgba(0, 0, 0, 0.90);
--positive: #70b880;
--warning: #c8a850;
--danger: #e06070;
}
/* ─── Sepia Dark ─── */
[data-theme='sepia-dark'] {
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%23c8b89a%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");
/* Backgrounds */
--ctp-crust: #0e0c09;
--ctp-mantle: #13100c;
--ctp-base: #1e1a14;
--ctp-surface0: #252018;
--ctp-surface1: #2e281e;
--ctp-surface2: #373025;
/* Overlays */
--ctp-overlay0: #605545;
--ctp-overlay1: #806e5a;
--ctp-overlay2: #9a8870;
/* Text */
--ctp-text: #ede0cc;
--ctp-subtext1: #d0c0a8;
--ctp-subtext0: #b0a080;
/* Cream accent */
--ctp-teal: #c8b89a;
--ctp-sky: #c8b89a;
--ctp-sapphire: #b8a080;
--ctp-blue: #a08868;
--ctp-lavender: #c8b89a;
--ctp-mauve: #b8a080;
--ctp-pink: #a08868;
--ctp-flamingo: #c8b89a;
--ctp-rosewater: #b8a080;
/* Semantic */
--ctp-red: #c87060;
--ctp-maroon: #c08050;
--ctp-peach: #c08050;
--ctp-yellow: #b8a050;
--ctp-green: #80a870;
/* UI tokens */
--bg-app: #1e1a14;
--bg-sidebar: #13100c;
--bg-card: #252018;
--bg-hover: #2e281e;
--bg-player: #13100c;
--bg-glass: rgba(30, 26, 20, 0.95);
--accent: #c8b89a;
--accent-dim: rgba(200, 184, 154, 0.07);
--accent-glow: rgba(200, 184, 154, 0.13);
--text-primary: #ede0cc;
--text-secondary: #b0a080;
--text-muted: #706050;
--border: #2e281e;
--border-subtle: #252018;
--border-dropdown: #3a3025;
--shadow-dropdown: rgba(0, 0, 0, 0.88);
--positive: #80a870;
--warning: #b8a050;
--danger: #c87060;
}
/* ─── Ice Blue ─── */
[data-theme='ice-blue'] {
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%237dd3e8%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");
/* Backgrounds */
--ctp-crust: #07101a;
--ctp-mantle: #09141e;
--ctp-base: #0e1d28;
--ctp-surface0: #132430;
--ctp-surface1: #192c3a;
--ctp-surface2: #203444;
/* Overlays */
--ctp-overlay0: #2a4a5a;
--ctp-overlay1: #3a6070;
--ctp-overlay2: #4a788a;
/* Text */
--ctp-text: #cce8f0;
--ctp-subtext1: #9accd8;
--ctp-subtext0: #68a8b8;
/* Icy cyan accent */
--ctp-teal: #7dd3e8;
--ctp-sky: #7dd3e8;
--ctp-sapphire: #60bcd5;
--ctp-blue: #48a8c0;
--ctp-lavender: #7dd3e8;
--ctp-mauve: #60bcd5;
--ctp-pink: #48a8c0;
--ctp-flamingo: #7dd3e8;
--ctp-rosewater: #60bcd5;
/* Semantic */
--ctp-red: #e07878;
--ctp-maroon: #d09858;
--ctp-peach: #d09858;
--ctp-yellow: #c8c060;
--ctp-green: #60c898;
/* UI tokens */
--bg-app: #0e1d28;
--bg-sidebar: #09141e;
--bg-card: #132430;
--bg-hover: #192c3a;
--bg-player: #09141e;
--bg-glass: rgba(14, 29, 40, 0.95);
--accent: #7dd3e8;
--accent-dim: rgba(125, 211, 232, 0.07);
--accent-glow: rgba(125, 211, 232, 0.14);
--text-primary: #cce8f0;
--text-secondary: #68a8b8;
--text-muted: #3a6878;
--border: #192c3a;
--border-subtle: #132430;
--border-dropdown: #223844;
--shadow-dropdown: rgba(0, 0, 0, 0.90);
--positive: #60c898;
--warning: #c8c060;
--danger: #e07878;
}