feat(ui): UI refinements — sidebar indicators, adaptive header, and interaction polish (#397)

* feat(ui): unify queue toggle handle behavior

Show the queue toggle in the header when the queue is collapsed and use a seam-aligned drag handle when it is open. Hide the seam handle while the main content is actively scrolling to reduce accidental interactions.

* feat(ui): add adaptive header search collapse behavior

Collapse header search to a magnifier when top controls get crowded and expand it as an overlay only while active. Use measured header space with hysteresis to avoid flicker and keep neighboring controls stable.

* chore(ui): remove leftover search prototype artifacts

Drop an unused icon import from live search and remove an unused header container-type rule left from an earlier layout experiment.

* feat(ui): persist sidebar and queue visibility state

Save left sidebar collapse and right queue open/closed visibility in local storage helpers so both panel modes are restored after app restart.

* feat(ui): unify player overflow menu behavior

Use a single overflow menu for click and wheel interactions, with a volume-only mode that keeps the same layout and volume controls as the full menu.

* feat(ui): add wheel seek controls to waveform

Apply 10-second wheel seek steps with trailing 1-second debounce and keep the waveform preview stable so the playhead moves smoothly during rapid scroll input.

* fix(now-playing): stabilize narrow dashboard layout

Switch now-playing responsiveness to container-based breakpoints and prevent stacked widgets from overlapping when width is constrained.

* fix(search): reduce collapse jitter and avoid header overlap

Add a short collapse-state cooldown to prevent threshold flicker and hide conflicting header controls while collapsed search expands as an overlay.

* fix(i18n): localize player overflow controls across locales

Replace hardcoded player overflow labels with translation keys and add the missing keys for all shipped locale files.

* fix(search): keep advanced control clickable in collapsed mode

Prevent focus loss on the advanced search button in collapsed overlay mode so its click handler consistently runs.

* fix(i18n): restore queue translation in offline library

Use the existing queue.appendToQueue key for the offline enqueue button tooltip and label instead of a missing key and hardcoded English text.

* fix(ui): apply overlay scrollbar to right-panel text tabs

Switch now-playing content, lyrics, and info panes to OverlayScrollArea and harden tour-item layout so long concert metadata stays within panel bounds.

* fix(ui): add unread indicator for new releases and guard sidebar drag clicks

Track unread new-release IDs per server/library scope and clear the badge when opening the New Releases page. Also prevent click-through navigation after sidebar drag release and keep related i18n/responsive sidebar-adjacent refinements in this snapshot.

* fix(ui): stabilize live dropdown layering and unread reset flow

Render the topbar Live dropdown via a portal so it consistently overlays sidebar layers. Rework new-releases unread tracking to handle library scope baselines, ignore stale refresh races, and mark items as seen after a 5-second stay on the New Releases page.

* feat(ui): add localized New badges for recently added albums

Show a theme-consistent New badge on album cards and album detail for albums created within the last 48 hours. Localize the badge label across all supported locales and centralize recency logic in a shared utility to avoid duplication.

* fix(album): prevent tracklist jump when entering multiselect

Move bulk selection actions from the tracklist body into the album toolbar next to the track filter. Keep selection controls stable in the header area so enabling multiselect no longer shifts the tracklist content downward.

* fix(tray): add playback-state badge and finalize queue handle tooltip

Show play/pause/stop icons in the Linux tray now-playing entry and persist state safely in Tauri managed state.
Also switch the queue-resize handle tooltip to the dedicated localized key across all locales.

* fix(header): prioritize search collapse before Live/Orbit labels

Make topbar compression deterministic by collapsing search first and compacting Live/Orbit labels only in sustained low-space mode.
Add sticky hysteresis-based header compact state to prevent oscillation while resizing.

* fix(ui): stabilize header compaction and show tray state icons

Prevent topbar flicker in the narrow-width range by tightening compact-mode thresholds, gating on real overflow, and removing width transitions from live search.
Also include playback state icons in tray tooltip text across platforms while preserving tooltip length limits.

* fix(tray): keep tooltip iconization Windows-only

Revert Linux tray tooltip/title fallback attempts and keep state icons only in Windows tray tooltips, while Linux continues to show playback state in the now-playing menu entry.

* fix(ui): restore queue resize response after overlay scroll interactions

Hide the queue handle while scrolling on both the main route viewport and the now-playing viewport, and clear stale thumb-drag state before starting queue resize.
Also ignore inactive/faded overlay thumbs in resizer suppression so horizontal pointer transitions no longer leave the queue seam unresponsive.

* docs(changelog): summarize ui-refinements branch features

Document the branch-level feature additions in 1.45.0 as separate changelog sections and group remaining branch-local fixes under a single polish entry.

* docs(changelog): add PR #397 references for ui-refinements

Attach PR metadata to the new 1.45.0 ui-refinement sections and the polish entry so release notes map directly to the merged branch discussion.
This commit is contained in:
cucadmuh
2026-05-01 15:42:40 +03:00
committed by GitHub
parent 2ea22635e5
commit 9ad0f8af6d
32 changed files with 1642 additions and 197 deletions
+7
View File
@@ -9,6 +9,7 @@ import { useAuthStore } from '../store/authStore';
import CachedImage from './CachedImage';
import { playAlbum } from '../utils/playAlbum';
import { useDragDrop } from '../contexts/DragDropContext';
import { isAlbumRecentlyAdded } from '../utils/albumRecency';
interface AlbumCardProps {
album: SubsonicAlbum;
@@ -32,6 +33,7 @@ function AlbumCard({ album, selected, selectionMode, onToggleSelect, showRating
});
const coverUrl = album.coverArt ? buildCoverArtUrl(album.coverArt, 300) : '';
const psyDrag = useDragDrop();
const isNewAlbum = isAlbumRecentlyAdded(album.created);
const handleClick = () => {
if (selectionMode) { onToggleSelect?.(album.id); return; }
@@ -86,6 +88,11 @@ function AlbumCard({ album, selected, selectionMode, onToggleSelect, showRating
<HardDriveDownload size={12} />
</div>
)}
{isNewAlbum && (
<div className="album-card-new-badge" aria-label={t('common.new', 'New')}>
{t('common.new', 'New')}
</div>
)}
{selectionMode && (
<div className={`album-card-select-check${selected ? ' album-card-select-check--on' : ''}`}>
{selected && <Check size={14} strokeWidth={3} />}
+6
View File
@@ -11,6 +11,7 @@ import StarRating from './StarRating';
import type { EntityRatingSupportLevel } from '../api/subsonic';
import { copyEntityShareLink } from '../utils/copyEntityShareLink';
import { showToast } from '../utils/toast';
import { isAlbumRecentlyAdded } from '../utils/albumRecency';
function formatDuration(seconds: number): string {
const h = Math.floor(seconds / 3600);
@@ -68,6 +69,7 @@ interface AlbumInfo {
genre?: string;
coverArt?: string;
recordLabel?: string;
created?: string;
}
interface AlbumHeaderProps {
@@ -131,6 +133,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 isNewAlbum = isAlbumRecentlyAdded(info.created);
const handleShareAlbum = async () => {
try {
@@ -183,6 +186,9 @@ export default function AlbumHeader({
<div className="album-detail-cover album-cover-placeholder"></div>
)}
<div className="album-detail-meta">
{isNewAlbum && (
<span className="badge album-detail-badge">{t('common.new', 'New')}</span>
)}
<h1 className="album-detail-title">{info.name}</h1>
<p className="album-detail-artist">
<button
+1 -45
View File
@@ -1,12 +1,11 @@
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Play, ChevronRight, Heart, ListPlus, X, ChevronDown, Check, RotateCcw, Square } from 'lucide-react';
import { Play, ChevronRight, Heart, ChevronDown, Check, RotateCcw, Square } from 'lucide-react';
import { useTracklistColumns, type ColDef } from '../utils/useTracklistColumns';
import { SubsonicSong } from '../api/subsonic';
import { Track, usePlayerStore, songToTrack } from '../store/playerStore';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { useDragDrop } from '../contexts/DragDropContext';
import { AddToPlaylistSubmenu } from './ContextMenu';
import { useIsMobile } from '../hooks/useIsMobile';
import StarRating from './StarRating';
import { useSelectionStore } from '../store/selectionStore';
@@ -323,8 +322,6 @@ export default function AlbumTrackList({
const allSelected = selectedCount === songs.length && songs.length > 0;
const lastSelectedIdxRef = useRef<number | null>(null);
const [showPlPicker, setShowPlPicker] = useState(false);
// ── Column state ──────────────────────────────────────────────────────────
const {
colVisible, visibleCols, gridStyle,
@@ -354,15 +351,6 @@ export default function AlbumTrackList({
return () => document.removeEventListener('mousedown', handler);
}, [inSelectMode, tracklistRef]);
useEffect(() => {
if (!showPlPicker) return;
const handler = (e: MouseEvent) => {
if (!(e.target as HTMLElement).closest('.bulk-pl-picker-wrap')) setShowPlPicker(false);
};
document.addEventListener('mousedown', handler);
return () => document.removeEventListener('mousedown', handler);
}, [showPlPicker]);
// ── Stable callbacks passed to memoised TrackRow ──────────────────────────
const onToggleSelect = useCallback((id: string, globalIdx: number, shift: boolean) => {
@@ -619,38 +607,6 @@ export default function AlbumTrackList({
}}
>
{/* ── Bulk action bar ── */}
{inSelectMode && (
<div className="bulk-action-bar">
<span className="bulk-action-count">
{t('common.bulkSelected', { count: selectedCount })}
</span>
<div className="bulk-pl-picker-wrap">
<button
className="btn btn-surface btn-sm"
onClick={() => setShowPlPicker(v => !v)}
>
<ListPlus size={14} />
{t('common.bulkAddToPlaylist')}
</button>
{showPlPicker && (
<AddToPlaylistSubmenu
songIds={[...useSelectionStore.getState().selectedIds]}
onDone={() => { setShowPlPicker(false); useSelectionStore.getState().clearAll(); }}
dropDown
/>
)}
</div>
<button
className="btn btn-ghost btn-sm"
onClick={() => useSelectionStore.getState().clearAll()}
>
<X size={13} />
{t('common.bulkClear')}
</button>
</div>
)}
{/* ── Header ── */}
<div className="tracklist-header-wrapper">
<div className="tracklist-header" style={gridStyle}>
+138 -4
View File
@@ -1,6 +1,6 @@
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { Search, Disc3, Users, Music, SlidersVertical, TextSearch } from 'lucide-react';
import { Search, Disc3, Users, Music, TextSearch } from 'lucide-react';
import { search, SearchResults, buildCoverArtUrl, coverArtCacheKey } from '../api/subsonic';
import { usePlayerStore, songToTrack } from '../store/playerStore';
import { useAuthStore } from '../store/authStore';
@@ -23,6 +23,8 @@ export default function LiveSearch() {
const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false);
const [activeIndex, setActiveIndex] = useState(-1);
const [isFocused, setIsFocused] = useState(false);
const [isCollapsed, setIsCollapsed] = useState(false);
const navigate = useNavigate();
const enqueue = usePlayerStore(state => state.enqueue);
const openContextMenu = usePlayerStore(state => state.openContextMenu);
@@ -31,6 +33,9 @@ export default function LiveSearch() {
const ctxType = usePlayerStore(state => state.contextMenu.type);
const ref = useRef<HTMLDivElement>(null);
const dropdownRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const collapsedRef = useRef(false);
const compactHeaderControlsRef = useRef(false);
const musicLibraryFilterVersion = useAuthStore(s => s.musicLibraryFilterVersion);
const doSearch = useCallback(
@@ -50,6 +55,110 @@ export default function LiveSearch() {
useEffect(() => { doSearch(query); setActiveIndex(-1); }, [query, doSearch]);
const isSearchActive = isFocused || open || query.trim().length > 0;
useEffect(() => {
const root = ref.current;
if (!root) return;
const header = root.closest('.content-header') as HTMLElement | null;
if (!header) return;
const overlayActive = isCollapsed && isSearchActive;
if (overlayActive) {
header.dataset.liveSearchOverlay = 'true';
} else {
delete header.dataset.liveSearchOverlay;
}
return () => {
delete header.dataset.liveSearchOverlay;
};
}, [isCollapsed, isSearchActive]);
useEffect(() => {
const root = ref.current;
if (!root) return;
const header = root.closest('.content-header') as HTMLElement | null;
if (!header) return;
const spacer = header.querySelector('.spacer') as HTMLElement | null;
if (!spacer) return;
const MIN_EXPANDED_WIDTH = 260;
const SPACER_RESERVE = 24;
const HYSTERESIS_PX = 20;
// Live/Orbit compact-mode is intentionally stickier than search collapse,
// otherwise both systems can feed each other and oscillate.
const HEADER_CONTROLS_COMPACT_ON_SPACER = 36;
const HEADER_CONTROLS_COMPACT_OFF_SPACER = 108;
const SWITCH_COOLDOWN_MS = 180;
const collapseThreshold = MIN_EXPANDED_WIDTH + SPACER_RESERVE;
const expandThreshold = collapseThreshold + HYSTERESIS_PX;
let lastSwitchAt = 0;
let cooldownTimer: number | null = null;
const updateCollapsed = () => {
const searchWidth = root.getBoundingClientRect().width;
const spacerWidth = spacer.getBoundingClientRect().width;
const budget = searchWidth + spacerWidth;
const headerOverflowing = header.scrollWidth - header.clientWidth > 1;
let nextCollapsed = collapsedRef.current
? budget < expandThreshold
: budget < collapseThreshold;
// Priority rule: if we are already compacting Live/Orbit labels, search
// must stay collapsed until compact mode can be released.
if (compactHeaderControlsRef.current) {
nextCollapsed = true;
}
if (nextCollapsed !== collapsedRef.current) {
const now = performance.now();
const remaining = SWITCH_COOLDOWN_MS - (now - lastSwitchAt);
if (remaining > 0) {
if (cooldownTimer == null) {
cooldownTimer = window.setTimeout(() => {
cooldownTimer = null;
updateCollapsed();
}, remaining);
}
return;
}
lastSwitchAt = now;
collapsedRef.current = nextCollapsed;
setIsCollapsed(nextCollapsed);
}
const nextCompactControls = nextCollapsed
? (
compactHeaderControlsRef.current
// Stay compact until we clearly have room and no overflow.
? (headerOverflowing || spacerWidth < HEADER_CONTROLS_COMPACT_OFF_SPACER)
// Enter compact only when both tight spacer and real overflow exist.
: (headerOverflowing && spacerWidth < HEADER_CONTROLS_COMPACT_ON_SPACER)
)
: false;
if (nextCompactControls !== compactHeaderControlsRef.current) {
compactHeaderControlsRef.current = nextCompactControls;
if (nextCompactControls) {
header.dataset.liveHeaderCompact = 'true';
} else {
delete header.dataset.liveHeaderCompact;
}
}
};
updateCollapsed();
const ro = new ResizeObserver(updateCollapsed);
ro.observe(header);
ro.observe(spacer);
ro.observe(root);
window.addEventListener('resize', updateCollapsed);
return () => {
ro.disconnect();
window.removeEventListener('resize', updateCollapsed);
delete header.dataset.liveHeaderCompact;
if (cooldownTimer != null) {
window.clearTimeout(cooldownTimer);
}
};
}, []);
// Close on click outside — but stay open while a song context menu is up.
// The CM renders a fullscreen transparent backdrop (z-index 998) above the
// dropdown, so any mousedown — including a second right-click on another
@@ -103,8 +212,23 @@ export default function LiveSearch() {
};
return (
<div className="live-search" ref={ref} role="search">
<div className="live-search-input-wrap">
<div
className="live-search"
ref={ref}
role="search"
data-collapsed={isCollapsed || undefined}
data-active={isSearchActive || undefined}
>
<div
className="live-search-input-wrap"
onMouseDown={(e) => {
if (isSearchActive) return;
if (!isCollapsed) return;
e.preventDefault();
setIsFocused(true);
requestAnimationFrame(() => inputRef.current?.focus());
}}
>
{loading ? (
<span className="live-search-icon animate-spin" style={{ opacity: 0.6 }}>
<div style={{ width: 16, height: 16, border: '2px solid var(--border)', borderTopColor: 'var(--accent)', borderRadius: '50%' }} />
@@ -113,13 +237,18 @@ export default function LiveSearch() {
<Search size={16} className="live-search-icon" />
)}
<input
ref={inputRef}
id="live-search-input"
className="input live-search-field"
type="search"
placeholder={t('search.placeholder')}
value={query}
onChange={e => setQuery(e.target.value)}
onFocus={() => results && setOpen(true)}
onFocus={() => {
setIsFocused(true);
if (results) setOpen(true);
}}
onBlur={() => setIsFocused(false)}
onKeyDown={handleKeyDown}
aria-autocomplete="list"
aria-controls="search-results"
@@ -134,6 +263,11 @@ export default function LiveSearch() {
<button
className="live-search-adv-btn"
type="button"
onMouseDown={(e) => {
// Keep focus on the search input so collapsed-overlay controls
// remain active long enough for this button click to fire.
e.preventDefault();
}}
onClick={() => navigate(query.trim() ? `/search/advanced?q=${encodeURIComponent(query.trim())}` : '/search/advanced')}
data-tooltip={t('search.advanced')}
data-tooltip-pos="bottom"
+21 -5
View File
@@ -7,6 +7,7 @@ import { useAuthStore } from '../store/authStore';
import { useTranslation } from 'react-i18next';
import type { Track } from '../store/playerStore';
import { EaseScroller, targetForFraction } from '../utils/easeScroll';
import OverlayScrollArea from './OverlayScrollArea';
interface Props {
currentTrack: Track | null;
@@ -153,11 +154,26 @@ export default function LyricsPane({ currentTrack }: Props) {
);
return (
<div
<OverlayScrollArea
className="lyrics-pane"
ref={setContainerRef}
onWheel={handleUserScroll}
onTouchMove={handleUserScroll}
viewportClassName="lyrics-pane__viewport"
viewportRef={setContainerRef}
measureDeps={[
currentTrack?.id,
loading,
notFound,
source,
useWords,
hasSynced,
staticOnly,
sidebarLyricsStyle,
plainLyrics?.length ?? 0,
syncedLines?.length ?? 0,
wordLines?.length ?? 0,
]}
railInset="panel"
viewportOnWheel={handleUserScroll}
viewportOnTouchMove={handleUserScroll}
>
{loading && <p className="lyrics-status">{t('player.lyricsLoading')}</p>}
{notFound && !loading && <p className="lyrics-status">{t('player.lyricsNotFound')}</p>}
@@ -227,7 +243,7 @@ export default function LyricsPane({ currentTrack }: Props) {
{sourceLabel && !loading && !notFound && (
<p className="lyrics-source">{sourceLabel}</p>
)}
</div>
</OverlayScrollArea>
);
}
+45 -15
View File
@@ -1,4 +1,5 @@
import React, { useState, useEffect, useRef } from 'react';
import React, { useState, useEffect, useRef, useCallback, useLayoutEffect } from 'react';
import { createPortal } from 'react-dom';
import { PlayCircle, User, Radio, RefreshCw } from 'lucide-react';
import { getNowPlaying, SubsonicNowPlaying, buildCoverArtUrl } from '../api/subsonic';
import { useAuthStore } from '../store/authStore';
@@ -15,7 +16,21 @@ export default function NowPlayingDropdown() {
const ownUsername = useAuthStore(s => s.getActiveServer()?.username ?? '');
const [loading, setLoading] = useState(false);
const [spinning, setSpinning] = useState(false);
const dropdownRef = useRef<HTMLDivElement>(null);
const triggerWrapRef = useRef<HTMLDivElement>(null);
const panelRef = useRef<HTMLDivElement>(null);
const [panelPos, setPanelPos] = useState<{ top: number; left: number }>({ top: 0, left: 0 });
const PANEL_WIDTH = 340;
const updatePanelPos = useCallback(() => {
const el = triggerWrapRef.current;
if (!el) return;
const r = el.getBoundingClientRect();
const margin = 8;
const top = r.bottom + 10;
const maxLeft = window.innerWidth - PANEL_WIDTH - margin;
const left = Math.max(margin, Math.min(r.right - PANEL_WIDTH, maxLeft));
setPanelPos({ top, left });
}, []);
const fetchNowPlaying = async () => {
setLoading(true);
@@ -46,12 +61,25 @@ export default function NowPlayingDropdown() {
return () => clearInterval(id);
}, [isOpen]);
useLayoutEffect(() => {
if (!isOpen) return;
updatePanelPos();
const onWin = () => updatePanelPos();
window.addEventListener('resize', onWin);
window.addEventListener('scroll', onWin, true);
return () => {
window.removeEventListener('resize', onWin);
window.removeEventListener('scroll', onWin, true);
};
}, [isOpen, updatePanelPos]);
// Click outside to close
useEffect(() => {
function handleClickOutside(event: MouseEvent) {
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
setIsOpen(false);
}
const target = event.target as Node;
if (triggerWrapRef.current?.contains(target)) return;
if (panelRef.current?.contains(target)) return;
setIsOpen(false);
}
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
@@ -64,16 +92,16 @@ export default function NowPlayingDropdown() {
);
return (
<div className="now-playing-dropdown" ref={dropdownRef} style={{ position: 'relative' }}>
<div className="now-playing-dropdown" ref={triggerWrapRef} style={{ position: 'relative' }}>
<button
className="btn btn-surface"
className="btn btn-surface now-playing-dropdown__trigger"
onClick={() => setIsOpen(!isOpen)}
data-tooltip={t('nowPlaying.tooltip')}
data-tooltip-pos="bottom"
style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: '0.5rem', padding: '0.5rem 1rem' }}
>
<Radio size={18} className={visible.length > 0 ? 'animate-pulse' : ''} style={{ color: visible.length > 0 ? 'var(--accent)' : 'inherit' }} />
<span>Live</span>
<span className="now-playing-dropdown__label">Live</span>
{visible.length > 0 && (
<span style={{
background: 'var(--accent)',
@@ -88,20 +116,21 @@ export default function NowPlayingDropdown() {
)}
</button>
{isOpen && (
{isOpen && createPortal(
<div
ref={panelRef}
className="glass animate-fade-in"
style={{
position: 'absolute',
top: 'calc(100% + 10px)',
right: 0,
width: '340px',
position: 'fixed',
top: panelPos.top,
left: panelPos.left,
width: `${PANEL_WIDTH}px`,
maxHeight: '400px',
overflowY: 'auto',
borderRadius: '12px',
boxShadow: 'var(--shadow-lg)',
padding: '1rem',
zIndex: 1000,
zIndex: 10050,
display: 'flex',
flexDirection: 'column',
gap: '1rem'
@@ -154,7 +183,8 @@ export default function NowPlayingDropdown() {
))}
</div>
)}
</div>
</div>,
document.body
)}
</div>
);
+20 -2
View File
@@ -7,6 +7,7 @@ import { useAuthStore } from '../store/authStore';
import { getArtistInfo, getSong, type SubsonicArtistInfo, type SubsonicSong } from '../api/subsonic';
import { fetchBandsintownEvents, type BandsintownEvent } from '../api/bandsintown';
import CachedImage from './CachedImage';
import OverlayScrollArea from './OverlayScrollArea';
const TOUR_LIMIT = 5;
const BIO_CLAMP_LINES = 4;
@@ -161,7 +162,24 @@ export default function NowPlayingInfo() {
const hiddenTourCount = Math.max(0, tourEvents.length - visibleTours.length);
return (
<div className="np-info">
<OverlayScrollArea
className="np-info"
viewportClassName="np-info__viewport"
railInset="panel"
measureDeps={[
currentTrack?.id,
artistId,
songId,
enableBandsintown,
tourLoading,
tourEvents.length,
showAllTours,
bioExpanded,
bioOverflows,
bioClean.length,
contributorRows.length,
]}
>
{/* Artist card */}
<section className="np-info-section np-info-artist">
{heroImage && heroCacheKey && (
@@ -306,6 +324,6 @@ export default function NowPlayingInfo() {
</div>
</section>
)}
</div>
</OverlayScrollArea>
);
}
+1 -1
View File
@@ -76,7 +76,7 @@ export default function OrbitStartTrigger() {
style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: '0.5rem', padding: '0.5rem 1rem' }}
>
<OrbitIcon size={18} className="orbit-start-trigger__spin" />
<span style={{ display: 'inline-flex', alignItems: 'center', height: '1.5em' }}>
<span className="orbit-start-trigger__label" style={{ display: 'inline-flex', alignItems: 'center', height: '1.5em' }}>
<OrbitWordmark height={14} />
</span>
</button>
+8
View File
@@ -22,6 +22,10 @@ export type OverlayScrollAreaProps = {
viewportRef?: React.Ref<HTMLDivElement>;
/** Optional id on the viewport (e.g. main app scroll for route pages). */
viewportId?: string;
/** Optional wheel handler on the scrollable viewport. */
viewportOnWheel?: React.WheelEventHandler<HTMLDivElement>;
/** Optional touch-move handler on the scrollable viewport. */
viewportOnTouchMove?: React.TouchEventHandler<HTMLDivElement>;
};
const RAIL_INSET_CLASS: Record<OverlayScrollRailInset, string> = {
@@ -46,6 +50,8 @@ export default function OverlayScrollArea({
viewportScrollBehaviorAuto = false,
viewportRef: viewportRefProp,
viewportId,
viewportOnWheel,
viewportOnTouchMove,
}: OverlayScrollAreaProps) {
const wrapRef = useRef<HTMLDivElement>(null);
const viewportRef = useRef<HTMLDivElement | null>(null);
@@ -121,6 +127,8 @@ export default function OverlayScrollArea({
ref={setViewportNode}
className={viewportClass}
onScroll={recompute}
onWheel={viewportOnWheel}
onTouchMove={viewportOnTouchMove}
>
{children}
</div>
+307 -61
View File
@@ -3,7 +3,7 @@ import { createPortal } from 'react-dom';
import {
Play, Pause, SkipBack, SkipForward, Volume2, VolumeX, Music,
Square, Repeat, Repeat1, Maximize2, SlidersVertical, X, Heart, Cast,
PictureInPicture2, ArrowLeftRight, Moon, Sunrise,
PictureInPicture2, ArrowLeftRight, Moon, Sunrise, Ellipsis,
} from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import { usePlayerStore } from '../store/playerStore';
@@ -108,6 +108,15 @@ export default function PlayerBar() {
const { lastfmSessionKey } = useAuthStore();
const floatingPlayerBar = useThemeStore(s => s.floatingPlayerBar);
const [floatingStyle, setFloatingStyle] = useState<React.CSSProperties>({});
const playerBarRef = useRef<HTMLElement>(null);
const [utilityOverflow, setUtilityOverflow] = useState(false);
const [utilityMenuOpen, setUtilityMenuOpen] = useState(false);
const [utilityMenuMode, setUtilityMenuMode] = useState<'full' | 'volume'>('full');
const utilityMenuRef = useRef<HTMLDivElement>(null);
const utilityBtnRef = useRef<HTMLButtonElement>(null);
const [utilityMenuStyle, setUtilityMenuStyle] = useState<React.CSSProperties>({});
const volumeWheelMenuTimerRef = useRef<number | null>(null);
const [suppressOverflowTooltip, setSuppressOverflowTooltip] = useState(false);
useEffect(() => {
if (!floatingPlayerBar) return;
@@ -141,6 +150,88 @@ export default function PlayerBar() {
};
}, [floatingPlayerBar]);
useEffect(() => {
const updateOverflow = () => {
const width = playerBarRef.current?.clientWidth ?? window.innerWidth;
const threshold = floatingPlayerBar ? 980 : 1140;
setUtilityOverflow(width < threshold);
};
updateOverflow();
const ro = typeof ResizeObserver !== 'undefined'
? new ResizeObserver(updateOverflow)
: null;
const el = playerBarRef.current;
if (ro && el) ro.observe(el);
window.addEventListener('resize', updateOverflow);
return () => {
ro?.disconnect();
window.removeEventListener('resize', updateOverflow);
};
}, [floatingPlayerBar]);
useEffect(() => {
if (!utilityOverflow) setUtilityMenuOpen(false);
if (!utilityOverflow && volumeWheelMenuTimerRef.current != null) {
window.clearTimeout(volumeWheelMenuTimerRef.current);
volumeWheelMenuTimerRef.current = null;
}
}, [utilityOverflow]);
useEffect(() => {
if (!utilityMenuOpen) return;
const onDown = (e: MouseEvent) => {
const target = e.target as Node;
if (utilityBtnRef.current?.contains(target)) return;
if (utilityMenuRef.current?.contains(target)) return;
setUtilityMenuOpen(false);
};
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') setUtilityMenuOpen(false);
};
document.addEventListener('mousedown', onDown);
document.addEventListener('keydown', onKey);
return () => {
document.removeEventListener('mousedown', onDown);
document.removeEventListener('keydown', onKey);
};
}, [utilityMenuOpen]);
useEffect(() => () => {
if (volumeWheelMenuTimerRef.current != null) {
window.clearTimeout(volumeWheelMenuTimerRef.current);
}
}, []);
useEffect(() => {
if (!utilityMenuOpen) return;
const MENU_WIDTH = 238;
const MARGIN = 8;
const updateMenuPos = () => {
const btn = utilityBtnRef.current;
if (!btn) return;
const r = btn.getBoundingClientRect();
const left = Math.min(
Math.max(r.right - MENU_WIDTH, MARGIN),
window.innerWidth - MENU_WIDTH - MARGIN,
);
setUtilityMenuStyle({
position: 'fixed',
left,
width: MENU_WIDTH,
bottom: window.innerHeight - r.top + 8,
zIndex: 10050,
});
};
updateMenuPos();
window.addEventListener('resize', updateMenuPos);
window.addEventListener('scroll', updateMenuPos, true);
return () => {
window.removeEventListener('resize', updateMenuPos);
window.removeEventListener('scroll', updateMenuPos, true);
};
}, [utilityMenuOpen]);
const { delayModalOpen, setDelayModalOpen, playPauseBind } = usePlaybackDelayPress(togglePlay);
const transportAnchorRef = useRef<HTMLDivElement>(null);
const playSlotRef = useRef<HTMLSpanElement>(null);
@@ -193,11 +284,25 @@ export default function PlayerBar() {
setVolume(parseFloat(e.target.value));
}, [setVolume]);
const handleVolumeWheel = useCallback((e: React.WheelEvent<HTMLDivElement>) => {
const handleVolumeWheel = useCallback((e: React.WheelEvent<HTMLElement>) => {
e.preventDefault();
const delta = e.deltaY > 0 ? -0.05 : 0.05;
setVolume(Math.max(0, Math.min(1, volume + delta)));
}, [volume, setVolume]);
if (utilityOverflow) {
setSuppressOverflowTooltip(true);
setUtilityMenuMode('volume');
setUtilityMenuOpen(true);
if (volumeWheelMenuTimerRef.current != null) {
window.clearTimeout(volumeWheelMenuTimerRef.current);
}
volumeWheelMenuTimerRef.current = window.setTimeout(() => {
setUtilityMenuOpen(false);
setSuppressOverflowTooltip(false);
volumeWheelMenuTimerRef.current = null;
}, 1000);
}
}, [volume, setVolume, utilityOverflow]);
const volumeStyle = {
background: `linear-gradient(to right, var(--volume-accent, var(--accent)) ${volume * 100}%, var(--ctp-surface2) ${volume * 100}%)`,
@@ -206,6 +311,7 @@ export default function PlayerBar() {
const playerBarContent = (
<>
<footer
ref={playerBarRef}
className={`player-bar ${floatingPlayerBar ? 'floating' : ''}${showPreviewMeta ? ' is-previewing' : ''}`}
style={floatingPlayerBar ? floatingStyle : undefined}
role="region"
@@ -435,65 +541,205 @@ export default function PlayerBar() {
)}
</div>
{/* EQ Button */}
<button
className={`player-btn player-btn-sm player-eq-btn ${eqOpen ? 'active' : ''}`}
onClick={() => setEqOpen(v => !v)}
aria-label="Equalizer"
data-tooltip="Equalizer"
>
<SlidersVertical size={15} />
</button>
{/* Mini Player */}
<button
className="player-btn player-btn-sm"
onClick={() => invoke('open_mini_player').catch(() => {})}
aria-label="Mini Player"
data-tooltip="Mini Player"
>
<PictureInPicture2 size={15} />
</button>
{/* Volume */}
<div className="player-volume-section">
<button
className="player-btn player-btn-sm"
onClick={() => {
if (volume === 0) {
setVolume(premuteVolumeRef.current);
} else {
premuteVolumeRef.current = volume;
setVolume(0);
}
}}
aria-label={t('player.volume')}
style={{ color: 'var(--text-muted)', flexShrink: 0 }}
>
{volume === 0 ? <VolumeX size={16} /> : <Volume2 size={16} />}
</button>
<div className="player-volume-slider-wrap" onWheel={handleVolumeWheel}>
{showVolPct && (
<span className="player-volume-pct" style={{ left: `${volume * 100}%` }}>
{Math.round(volume * 100)}%
</span>
)}
<input
type="range"
id="player-volume"
min={0}
max={1}
step={0.01}
value={volume}
onChange={handleVolume}
style={volumeStyle}
aria-label={t('player.volume')}
className="player-volume-slider"
onMouseEnter={() => setShowVolPct(true)}
onMouseLeave={() => setShowVolPct(false)}
/>
{utilityOverflow ? (
<div className="player-overflow-wrap">
<button
ref={utilityBtnRef}
className={`player-btn player-btn-sm${utilityMenuOpen ? ' active' : ''}`}
onClick={() => {
setUtilityMenuMode('full');
setUtilityMenuOpen(v => !v);
if (volumeWheelMenuTimerRef.current != null) {
window.clearTimeout(volumeWheelMenuTimerRef.current);
volumeWheelMenuTimerRef.current = null;
}
setSuppressOverflowTooltip(false);
}}
onWheel={handleVolumeWheel}
aria-label={t('player.moreOptions')}
data-tooltip={suppressOverflowTooltip ? undefined : t('player.moreOptions')}
>
<Ellipsis size={15} />
</button>
</div>
</div>
) : (
<>
{/* EQ Button */}
<button
className={`player-btn player-btn-sm player-eq-btn ${eqOpen ? 'active' : ''}`}
onClick={() => setEqOpen(v => !v)}
aria-label={t('player.equalizer')}
data-tooltip={t('player.equalizer')}
>
<SlidersVertical size={15} />
</button>
{/* Mini Player */}
<button
className="player-btn player-btn-sm"
onClick={() => invoke('open_mini_player').catch(() => {})}
aria-label={t('player.miniPlayer')}
data-tooltip={t('player.miniPlayer')}
>
<PictureInPicture2 size={15} />
</button>
{/* Volume */}
<div className="player-volume-section">
<button
className="player-btn player-btn-sm"
onClick={() => {
if (volume === 0) {
setVolume(premuteVolumeRef.current);
} else {
premuteVolumeRef.current = volume;
setVolume(0);
}
}}
aria-label={t('player.volume')}
style={{ color: 'var(--text-muted)', flexShrink: 0 }}
>
{volume === 0 ? <VolumeX size={16} /> : <Volume2 size={16} />}
</button>
<div className="player-volume-slider-wrap" onWheel={handleVolumeWheel}>
{showVolPct && (
<span className="player-volume-pct" style={{ left: `${volume * 100}%` }}>
{Math.round(volume * 100)}%
</span>
)}
<input
type="range"
id="player-volume"
min={0}
max={1}
step={0.01}
value={volume}
onChange={handleVolume}
style={volumeStyle}
aria-label={t('player.volume')}
className="player-volume-slider"
onMouseEnter={() => setShowVolPct(true)}
onMouseLeave={() => setShowVolPct(false)}
/>
</div>
</div>
</>
)}
{/* EQ Popup — rendered via portal to avoid backdrop-filter containing-block issue */}
{utilityMenuOpen && createPortal(
<div
className={`player-overflow-menu${utilityMenuMode === 'volume' ? ' player-overflow-menu--volume-only' : ''}`}
ref={utilityMenuRef}
style={utilityMenuStyle}
onWheel={handleVolumeWheel}
>
{utilityMenuMode === 'full' && (
<div className="player-overflow-menu-row">
<button
className={`player-overflow-menu-btn${eqOpen ? ' active' : ''}`}
onClick={() => {
setEqOpen(v => !v);
setUtilityMenuOpen(false);
}}
>
<SlidersVertical size={14} />
{t('player.equalizer')}
</button>
<button
className="player-overflow-menu-btn"
onClick={() => {
invoke('open_mini_player').catch(() => {});
setUtilityMenuOpen(false);
}}
>
<PictureInPicture2 size={14} />
{t('player.miniPlayer')}
</button>
</div>
)}
{utilityMenuMode === 'full' ? (
<div className="player-volume-section player-volume-section--menu">
<button
className="player-btn player-btn-sm"
onClick={() => {
if (volume === 0) {
setVolume(premuteVolumeRef.current);
} else {
premuteVolumeRef.current = volume;
setVolume(0);
}
}}
aria-label={t('player.volume')}
style={{ color: 'var(--text-muted)', flexShrink: 0 }}
>
{volume === 0 ? <VolumeX size={16} /> : <Volume2 size={16} />}
</button>
<div className="player-volume-slider-wrap" onWheel={handleVolumeWheel}>
{showVolPct && (
<span className="player-volume-pct" style={{ left: `${volume * 100}%` }}>
{Math.round(volume * 100)}%
</span>
)}
<input
type="range"
id="player-volume-overflow"
min={0}
max={1}
step={0.01}
value={volume}
onChange={handleVolume}
style={volumeStyle}
aria-label={t('player.volume')}
className="player-volume-slider"
onMouseEnter={() => setShowVolPct(true)}
onMouseLeave={() => setShowVolPct(false)}
/>
</div>
</div>
) : (
<div className="player-volume-section player-volume-section--menu">
<button
className="player-btn player-btn-sm"
onClick={() => {
if (volume === 0) {
setVolume(premuteVolumeRef.current);
} else {
premuteVolumeRef.current = volume;
setVolume(0);
}
}}
aria-label={t('player.volume')}
style={{ color: 'var(--text-muted)', flexShrink: 0 }}
>
{volume === 0 ? <VolumeX size={16} /> : <Volume2 size={16} />}
</button>
<div className="player-volume-slider-wrap player-volume-slider-wrap--menu-only" onWheel={handleVolumeWheel}>
{showVolPct && (
<span className="player-volume-pct" style={{ left: `${volume * 100}%` }}>
{Math.round(volume * 100)}%
</span>
)}
<input
type="range"
id="player-volume-overflow-wheel"
min={0}
max={1}
step={0.01}
value={volume}
onChange={handleVolume}
style={volumeStyle}
aria-label={t('player.volume')}
className="player-volume-slider"
onMouseEnter={() => setShowVolPct(true)}
onMouseLeave={() => setShowVolPct(false)}
/>
</div>
</div>
)}
</div>,
document.body
)}
{/* EQ Popup — rendered via portal to avoid backdrop-filter containing-block issue */}
{eqOpen && createPortal(
+190 -2
View File
@@ -6,7 +6,7 @@ import { useOfflineJobStore } from '../store/offlineJobStore';
import { useDeviceSyncJobStore } from '../store/deviceSyncJobStore';
import { useAuthStore } from '../store/authStore';
import { useSidebarStore, type SidebarItemConfig } from '../store/sidebarStore';
import { NavLink } from 'react-router-dom';
import { NavLink, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
Settings,
@@ -16,7 +16,7 @@ import {
import PsysonicLogo from './PsysonicLogo';
import PSmallLogo from './PSmallLogo';
import WhatsNewBanner from './WhatsNewBanner';
import { getPlaylists } from '../api/subsonic';
import { getAlbumList, getPlaylists } from '../api/subsonic';
import { usePlaylistStore } from '../store/playlistStore';
import { ALL_NAV_ITEMS } from '../config/navItems';
import OverlayScrollArea from './OverlayScrollArea';
@@ -32,6 +32,10 @@ import { useLuckyMixAvailable } from '../hooks/useLuckyMixAvailable';
const SIDEBAR_NAV_LONG_PRESS_MS = 1000;
const SIDEBAR_NAV_LONG_PRESS_MOVE_CANCEL_PX = 10;
const SMART_PREFIX = 'psy-smart-';
const NEW_RELEASES_UNREAD_STORAGE_PREFIX = 'psy_new_releases_unread_seen_v1';
const NEW_RELEASES_UNREAD_SAMPLE_SIZE = 80;
const NEW_RELEASES_UNREAD_POLL_MS = 2 * 60 * 1000;
const NEW_RELEASES_RESET_DELAY_MS = 5_000;
function isSmartPlaylistName(name: string): boolean {
return (name ?? '').toLowerCase().startsWith(SMART_PREFIX);
@@ -59,6 +63,7 @@ export default function Sidebar({
toggleCollapse?: () => void;
}) {
const { t } = useTranslation();
const location = useLocation();
const isPlaying = usePlayerStore(s => s.isPlaying);
const currentTrack = usePlayerStore(s => s.currentTrack);
const offlineJobs = useOfflineJobStore(s => s.jobs);
@@ -95,6 +100,8 @@ export default function Sidebar({
}, [playlistsRaw]);
const [dropdownRect, setDropdownRect] = useState({ top: 0, left: 0, width: 0 });
const libraryTriggerRef = useRef<HTMLButtonElement>(null);
const [sidebarViewportEl, setSidebarViewportEl] = useState<HTMLDivElement | null>(null);
const [isSidebarScrolling, setIsSidebarScrolling] = useState(false);
const showLibraryPicker = !isCollapsed && isLoggedIn && musicFolders.length > 1;
const filterId = serverId ? (musicLibraryFilterByServer[serverId] ?? 'all') : 'all';
@@ -140,6 +147,106 @@ export default function Sidebar({
const suppressNavClickRef = useRef(false);
const lastPointerDuringNavDndRef = useRef({ x: 0, y: 0 });
const [navDndTrashHint, setNavDndTrashHint] = useState<{ x: number; y: number } | null>(null);
const [newReleasesUnreadCount, setNewReleasesUnreadCount] = useState(0);
const newReleasesRefreshSeqRef = useRef(0);
const newReleasesPageEnteredAtRef = useRef<number | null>(null);
const newReleasesResetTimerRef = useRef<number | null>(null);
const newReleasesSeenStorageKey = useMemo(
() => `${NEW_RELEASES_UNREAD_STORAGE_PREFIX}:${serverId || 'no-server'}:${filterId || 'all'}`,
[serverId, filterId],
);
const newReleasesSeenAllScopeStorageKey = useMemo(
() => `${NEW_RELEASES_UNREAD_STORAGE_PREFIX}:${serverId || 'no-server'}:all`,
[serverId],
);
const readSeenNewReleaseIdsByKey = useCallback((key: string): string[] => {
try {
const raw = localStorage.getItem(key);
if (!raw) return [];
const parsed = JSON.parse(raw);
if (!Array.isArray(parsed)) return [];
return parsed.filter((id): id is string => typeof id === 'string' && id.length > 0);
} catch {
return [];
}
}, []);
const readSeenNewReleaseIds = useCallback(
() => readSeenNewReleaseIdsByKey(newReleasesSeenStorageKey),
[newReleasesSeenStorageKey, readSeenNewReleaseIdsByKey],
);
const writeSeenNewReleaseIdsByKey = useCallback((key: string, ids: string[]) => {
const normalized = Array.from(new Set(ids.filter(Boolean))).slice(0, 500);
localStorage.setItem(key, JSON.stringify(normalized));
}, []);
const writeSeenNewReleaseIds = useCallback(
(ids: string[]) => writeSeenNewReleaseIdsByKey(newReleasesSeenStorageKey, ids),
[newReleasesSeenStorageKey, writeSeenNewReleaseIdsByKey],
);
const refreshNewReleasesUnread = useCallback(async (markAsSeen = false) => {
const seq = ++newReleasesRefreshSeqRef.current;
const isCurrent = () => seq === newReleasesRefreshSeqRef.current;
if (!isLoggedIn || !serverId) {
if (isCurrent()) setNewReleasesUnreadCount(0);
return;
}
try {
const newest = await getAlbumList('newest', NEW_RELEASES_UNREAD_SAMPLE_SIZE, 0);
const newestIds = newest.map(a => a.id).filter(Boolean);
let seenIds = readSeenNewReleaseIds();
// For a concrete library scope, bootstrap from the server-wide "all libraries"
// baseline when available, so switching scope doesn't hide existing unread.
if (seenIds.length === 0 && filterId !== 'all') {
const allScopeSeen = readSeenNewReleaseIdsByKey(newReleasesSeenAllScopeStorageKey);
if (allScopeSeen.length > 0) {
seenIds = allScopeSeen;
writeSeenNewReleaseIdsByKey(newReleasesSeenStorageKey, allScopeSeen);
}
}
if (seenIds.length === 0) {
// First bootstrap for this server/scope: baseline is "already seen".
writeSeenNewReleaseIds(newestIds);
if (isCurrent()) setNewReleasesUnreadCount(0);
return;
}
if (markAsSeen) {
writeSeenNewReleaseIds([...seenIds, ...newestIds]);
// Keep server-wide baseline in sync so scope fallback never resurrects
// already-viewed items after opening the New Releases page.
const allScopeSeen = readSeenNewReleaseIdsByKey(newReleasesSeenAllScopeStorageKey);
writeSeenNewReleaseIdsByKey(newReleasesSeenAllScopeStorageKey, [...allScopeSeen, ...newestIds]);
if (isCurrent()) setNewReleasesUnreadCount(0);
return;
}
const seenSet = new Set(seenIds);
let unread = newestIds.reduce((count, id) => count + (seenSet.has(id) ? 0 : 1), 0);
if (isCurrent()) setNewReleasesUnreadCount(unread);
} catch {
// Keep previous value on transient network/API errors.
}
}, [
filterId,
isLoggedIn,
newReleasesSeenAllScopeStorageKey,
newReleasesSeenStorageKey,
readSeenNewReleaseIds,
readSeenNewReleaseIdsByKey,
serverId,
writeSeenNewReleaseIds,
writeSeenNewReleaseIdsByKey,
]);
useEffect(() => {
if (!navDnd) return;
@@ -236,6 +343,8 @@ export default function Sidebar({
const onUp = (e: PointerEvent) => {
lastPointerDuringNavDndRef.current = { x: e.clientX, y: e.clientY };
// Prevent synthetic click/navigation right after finishing a drag gesture.
suppressNavClickRef.current = true;
endDrag(true);
};
@@ -399,6 +508,70 @@ export default function Sidebar({
longPressTimersRef.current.clear();
}, []);
useEffect(() => {
if (!sidebarViewportEl) return;
let hideTimer: number | null = null;
const onScroll = () => {
setIsSidebarScrolling(true);
if (hideTimer != null) window.clearTimeout(hideTimer);
hideTimer = window.setTimeout(() => {
setIsSidebarScrolling(false);
hideTimer = null;
}, 180);
};
sidebarViewportEl.addEventListener('scroll', onScroll, { passive: true });
return () => {
sidebarViewportEl.removeEventListener('scroll', onScroll);
if (hideTimer != null) window.clearTimeout(hideTimer);
};
}, [sidebarViewportEl]);
useEffect(() => {
const onNewReleasesPage = location.pathname.startsWith('/new-releases');
if (newReleasesResetTimerRef.current != null) {
window.clearTimeout(newReleasesResetTimerRef.current);
newReleasesResetTimerRef.current = null;
}
if (onNewReleasesPage) {
if (newReleasesPageEnteredAtRef.current == null) {
newReleasesPageEnteredAtRef.current = Date.now();
}
const elapsed = Date.now() - newReleasesPageEnteredAtRef.current;
const shouldMarkAsSeen = elapsed >= NEW_RELEASES_RESET_DELAY_MS;
void refreshNewReleasesUnread(shouldMarkAsSeen);
if (!shouldMarkAsSeen) {
const remaining = NEW_RELEASES_RESET_DELAY_MS - elapsed;
newReleasesResetTimerRef.current = window.setTimeout(() => {
newReleasesResetTimerRef.current = null;
void refreshNewReleasesUnread(true);
}, remaining);
}
} else {
newReleasesPageEnteredAtRef.current = null;
void refreshNewReleasesUnread(false);
}
const timer = window.setInterval(() => {
const activeOnNewReleases = location.pathname.startsWith('/new-releases');
const enteredAt = newReleasesPageEnteredAtRef.current;
const delayedSeenReached =
activeOnNewReleases &&
enteredAt != null &&
Date.now() - enteredAt >= NEW_RELEASES_RESET_DELAY_MS;
void refreshNewReleasesUnread(delayedSeenReached);
}, NEW_RELEASES_UNREAD_POLL_MS);
return () => {
window.clearInterval(timer);
if (newReleasesResetTimerRef.current != null) {
window.clearTimeout(newReleasesResetTimerRef.current);
newReleasesResetTimerRef.current = null;
}
};
}, [location.pathname, refreshNewReleasesUnread]);
return (
<>
<aside className={`sidebar animate-slide-in ${isCollapsed ? 'collapsed' : ''}`}>
@@ -412,6 +585,10 @@ export default function Sidebar({
<button
className="collapse-btn"
onClick={toggleCollapse}
style={{
opacity: isSidebarScrolling ? 0 : 1,
pointerEvents: isSidebarScrolling ? 'none' : 'auto',
}}
data-tooltip={isCollapsed ? t('sidebar.expand') : t('sidebar.collapse')}
data-tooltip-pos="right"
>
@@ -432,6 +609,7 @@ export default function Sidebar({
<OverlayScrollArea
className="sidebar-nav-scroll"
viewportClassName="sidebar-nav-viewport"
viewportRef={setSidebarViewportEl}
railInset="panel"
measureDeps={[
isCollapsed,
@@ -601,6 +779,11 @@ export default function Sidebar({
data-tooltip-pos="bottom"
>
<item.icon size={isCollapsed ? 22 : 18} />
{item.to === '/new-releases' && newReleasesUnreadCount > 0 && (
<span className="sidebar-nav-unread-badge" aria-hidden>
{newReleasesUnreadCount > 99 ? '99+' : newReleasesUnreadCount}
</span>
)}
{!isCollapsed && <span>{t(item.labelKey)}</span>}
</NavLink>
) : (
@@ -619,6 +802,11 @@ export default function Sidebar({
>
<item.icon size={isCollapsed ? 22 : 18} />
{!isCollapsed && <span>{t(item.labelKey)}</span>}
{item.to === '/new-releases' && newReleasesUnreadCount > 0 && (
<span className="sidebar-nav-unread-badge" aria-hidden>
{newReleasesUnreadCount > 99 ? '99+' : newReleasesUnreadCount}
</span>
)}
</NavLink>
</div>
);
+7
View File
@@ -40,15 +40,22 @@ export default function TooltipPortal() {
const t = (e.target as HTMLElement).closest('[data-tooltip]');
if (t) setTooltip(null);
};
/** Wheel interactions (e.g. volume on overflow button) should suppress tooltip immediately. */
const onWheel = (e: WheelEvent) => {
const t = (e.target as HTMLElement).closest('[data-tooltip]');
if (t) setTooltip(null);
};
document.addEventListener('mouseover', onOver);
document.addEventListener('mouseout', onOut);
document.addEventListener('mousemove', onMove, { passive: true });
document.addEventListener('mousedown', onDown, true);
document.addEventListener('wheel', onWheel, { capture: true, passive: true });
return () => {
document.removeEventListener('mouseover', onOver);
document.removeEventListener('mouseout', onOut);
document.removeEventListener('mousemove', onMove);
document.removeEventListener('mousedown', onDown, true);
document.removeEventListener('wheel', onWheel, true);
};
}, []);
+59
View File
@@ -897,6 +897,8 @@ export default function WaveformSeek({ trackId }: Props) {
const SEEK_COMMIT_GUARD_MS = 900;
const SEEK_COMMIT_MIN_HOLD_MS = 320;
const SEEK_COMMIT_PROGRESS_EPS = 0.02;
const WHEEL_SEEK_STEP_SECONDS = 10;
const WHEEL_SEEK_DEBOUNCE_MS = 1000;
const canvasRef = useRef<HTMLCanvasElement>(null);
const heightsRef = useRef<Float32Array | null>(null);
const progressRef = useRef(usePlayerStore.getState().progress);
@@ -1005,6 +1007,12 @@ export default function WaveformSeek({ trackId }: Props) {
// While user drags, keep the local preview stable. External progress ticks
// during streaming/recovery would otherwise fight the cursor and flicker.
if (isDragging.current) return;
const now = Date.now();
const wheelPreviewFraction = wheelPreviewFractionRef.current;
if (wheelPreviewFraction != null) {
if (now < wheelPreviewUntilRef.current) return;
wheelPreviewFractionRef.current = null;
}
const pendingCommit = pendingCommittedSeekRef.current;
if (pendingCommit) {
const ageMs = Date.now() - pendingCommit.setAtMs;
@@ -1097,6 +1105,19 @@ export default function WaveformSeek({ trackId }: Props) {
seekRef.current = seek;
const pendingSeekRef = useRef<number | null>(null);
const pendingCommittedSeekRef = useRef<{ fraction: number; setAtMs: number } | null>(null);
const wheelSeekTimerRef = useRef<number | null>(null);
const queuedWheelSeekFractionRef = useRef<number | null>(null);
const wheelPreviewFractionRef = useRef<number | null>(null);
const wheelPreviewUntilRef = useRef(0);
useEffect(() => () => {
if (wheelSeekTimerRef.current != null) {
window.clearTimeout(wheelSeekTimerRef.current);
wheelSeekTimerRef.current = null;
}
wheelPreviewFractionRef.current = null;
wheelPreviewUntilRef.current = 0;
}, []);
// Preview a 01 fraction while dragging: draw immediately for 1:1
// responsiveness; the actual seek is committed on mouseup.
@@ -1151,6 +1172,44 @@ export default function WaveformSeek({ trackId }: Props) {
<canvas
ref={canvasRef}
style={{ width: '100%', height: '24px', cursor: trackId ? 'pointer' : 'default', display: 'block' }}
onWheel={e => {
if (!trackIdRef.current || duration <= 0 || isDragging.current) return;
e.preventDefault();
const wheelSteps = Math.max(1, Math.round(Math.abs(e.deltaY) / 100));
if (wheelSteps <= 0) return;
const now = Date.now();
const currentSeconds = progressRef.current * duration;
const deltaSeconds = (e.deltaY > 0 ? -1 : 1) * WHEEL_SEEK_STEP_SECONDS * wheelSteps;
const nextSeconds = Math.max(0, Math.min(duration, currentSeconds + deltaSeconds));
const nextFraction = Math.max(0, Math.min(1, nextSeconds / duration));
// Preventive UI update: move visual playhead immediately on every wheel event.
progressRef.current = nextFraction;
wheelPreviewFractionRef.current = nextFraction;
wheelPreviewUntilRef.current = now + WHEEL_SEEK_DEBOUNCE_MS;
const canvas = canvasRef.current;
if (canvas && !ANIMATED_STYLES.has(styleRef.current)) {
drawSeekbar(canvas, styleRef.current, heightsRef.current, nextFraction, bufferedRef.current);
}
// Trailing debounce: commit seek only after wheel activity settles.
queuedWheelSeekFractionRef.current = nextFraction;
if (wheelSeekTimerRef.current != null) {
window.clearTimeout(wheelSeekTimerRef.current);
}
wheelSeekTimerRef.current = window.setTimeout(() => {
wheelSeekTimerRef.current = null;
const queuedFraction = queuedWheelSeekFractionRef.current;
queuedWheelSeekFractionRef.current = null;
if (queuedFraction == null) return;
wheelPreviewFractionRef.current = null;
wheelPreviewUntilRef.current = 0;
pendingCommittedSeekRef.current = { fraction: queuedFraction, setAtMs: Date.now() };
seekRef.current(queuedFraction);
}, WHEEL_SEEK_DEBOUNCE_MS);
}}
onMouseDown={e => {
isDragging.current = true;
const rect = e.currentTarget.getBoundingClientRect();