mirror of
https://github.com/kilyabin/psysonic.git
synced 2026-07-21 22:15:40 +00:00
fix(cover): Windows thumbnails, tier fallback, PNG decode, coverArt id (#878)
* fix(cover): tier fallback for sparse surfaces and Windows asset URLs Sparse UI (player bar, queue) now reads disk covers via the same tier ladder as dense grids, so a warm 800.webp satisfies a 128px request. Reject non-asset convertFileSrc results on Windows, widen Tauri asset scope, and seed ladder keys on cover:tier-ready. applyDiskPath uses seedGridDiskSrcCache only to avoid notify/subscriber infinite loops. * fix(artist): top-track thumb uses album coverArt already warm in grid Song coverArt ids often differ from album cover ids (e.g. Octastorium in the grid vs empty track thumb). Prefer the album row's coverArt on artist pages and ensure high priority for 32px dense cells. * fix(cover): albumId for playback/queue; no broken img until disk URL ready Prefer albumId over track-id coverArt (Navidrome). Wire queue to CoverArtImage with playback scope. CoverArtImage renders a placeholder div until asset src exists to avoid the browser broken-image icon. * fix(test): add song id to resolveArtistPageSongCoverArtId fixture Pick<SubsonicSong, …> requires id; fixes tsc in CI/build. * fix(cover): resolve albumId for Now Playing and artist top tracks Prefer albumId when album.coverArt echoes track id; use sparse surface on artist suggestion thumbs; apply resolveSubsonicSongCoverArtId across playback surfaces (Now Playing, fullscreen, mobile, mini). * fix(cover): decode PNG from Subsonic before WebP tier encode Enable `png` in the image crate — some servers return PNG cover art; failed decode left `.fetch-failed` and empty thumbs for those albums. * refactor(cover): consolidate cover id resolution and align tests Move resolveSubsonicSongCoverArtId helpers to src/cover/resolveCoverArtId.ts with resolvePlaybackTrackCoverArtId for player surfaces; co-locate tests; fix FullscreenPlayer expectations for albumId-first resolution. * docs: CHANGELOG and credits for PR #878 * fix(cover): keep per-track coverArt when distinct from song id Address PR #878 review (b): albumId only when coverArt is missing or echoes track id; pin case with unit test; comment isRawFsPath symmetry. * chore(cover): address PR #878 review nits (scope, tests, rename) Narrow asset scope to cover-cache dirs only; add diskSrcCache Windows-path tests; rename ArtistTopTrackCover; CHANGELOG symptom-first wording. * fix(cover): restore asset scope to app data dirs (Windows regression) $APPDATA/cover-cache/** did not match Tauri scope resolution — covers were blocked after load. Use $APPDATA/** and $APPLOCALDATA/** (no $DATA). * fix(cover): Windows asset URLs — restore DATA scope, path normalize Regression after review nits: dropped $DATA/** and strict isAssetProtocolUrl blocked valid http://asset.localhost URLs on Windows. Normalize C:/ paths before convertFileSrc; CoverArtImage/Hero hide broken img on load error. * fix(cover): disk peek fallbacks when cache folder id differs Small surfaces resolve albumId while cover-cache often stores WebP under track id or album.coverArt from the grid. Peek batch now tries legacy ids; playback scope resolves server index key by URL key, not UUID-only lookup. * fix(cover): Navidrome al-* vs mf-* disk id mismatch UI used mf-* coverArtId while library backfill only cached al-* folders. Prefer album id for display/peek when coverArt is mf-*; backfill now queues both distinct album_id and cover_art_id values. * fix(cover): mf→al disk peek when mf folder missing in cache Navidrome Subsonic often returns mf-* coverArtId while backfill only creates al-* folders. Peek mf first, then al-* from hints; load albumId from library when Subsonic omits it; ensure fallback uses al-* id. * feat(cover): CoverArtRef, segment disk layout, library-index backfill Normalize cover caching around stable entity ids from the local library and Navidrome fetch ids. Disk paths live in psysonic_core::cover_cache_layout (album/<entityId>/); UI uses CoverArtRef with cacheEntityId + fetchCoverArtId. - Remove SQLite/mf peek helpers (diskPeekIds, peekCoverOnDisk, mergeDiskIdHints) - Backfill reads album/artist rows from library SQLite (bare Navidrome ids ok) - Use stored cover_art_id for HTTP; per-disc dirs only when discs differ - Migrate call sites to albumCoverRef / albumCoverRefForPlayback * feat(cover): central CoverEntry resolver (artist, album, track) Add resolveEntry.ts and Rust CoverEntry helpers as the single source of truth for cache_entity_id vs fetch_cover_art_id. ref.ts delegates to them; resolveCoverArtId becomes a thin compatibility shim. * feat(cover): resolve cover entries from local library index Add library_resolve_cover_entry IPC and cover_resolve.rs so album, artist, and track covers use SQLite cover_art_id + disc detection. TypeScript helpers in resolveEntryLibrary.ts prefer the index over live API fields when rows exist. * feat(cover): library-first hooks for grids and playback UI Add useAlbumCoverRef, useArtistCoverRef, useTrackCoverRef, and usePlaybackTrackCoverRef — sync fallback then SQLite index upgrade. Wire album/artist cards, album header, song card, and all player surfaces to resolve covers from the local library when indexed. * feat(cover): complete library-first migration across all UI surfaces Add Album/Artist/TrackCoverArtImage, useLibraryCoverPrefetch, and batch resolve helpers. Migrate grids, search, home, playback sidecars, warm peek, playlists, and share flows to hooks that upgrade from SQLite. Backfill normalizes album rows through cover_resolve; document paths in COVER_PATHS.md. Radio remains a deliberate non-library exception. * fix(cover): stop render loop from unstable serverScope in library hooks Default param `{ kind: 'active' }` created a new object every render, so every grid cell re-ran library_resolve IPC and setState in a loop. Use COVER_SCOPE_ACTIVE singleton, coverScopeKey deps, and guarded sync updates. * chore(cover): remove COVER_PATHS.md from app tree (lives in workdocs) Audit doc is team spec — see workdocs 2026-05-cover-art-pipeline/cover-paths-audit.md. * fix(cover): unstick library backfill after route changes (PR #870 regression) useCoverNavigationPriority cleanup called beginNavigation instead of end, leaking navigationHoldDepth so ui_priority_hold never released and backfill never downloaded. Also skip disk check after cover_resolve normalization. * fix(cover): segment progress, cap backfill CPU, include artists in catalog Progress and disk size now scan album/ and artist/ segments (canonical 800.webp). Prune legacy flat server/al-* dirs on startup and backfill pass. Backfill: max 2 concurrent ensures; JPEG decode and WebP encode run on the blocking pool behind a shared 2-permit semaphore so Tokio workers stay cool. Artists were missing because the catalog only read the empty artist table; add distinct artist_id from track and album rows. Paginate with a composite (kind, id) cursor so album and artist rows are not skipped. * fix(cover): drop legacy prune; backfill per-disc and artist catalog Remove prune_legacy_* and cover_cache_catalog_entry — layout is only cover_dir (album|artist segments); stale flat dirs clear on LAYOUT_STAMP change. Backfill: artists from track/album artist_id; expand albums to per-CD mf-* slots when discs differ; fix resolve_album_cover_entry when album row is missing. * fix(cover): reduce library IPC storms and fix multi-disc player art Skip per-row library_resolve on live search and artist album grids; warm grids from API coverArt after mount instead of blocking layout. Dedupe and cap concurrent library_resolve calls. Restore per-disc cache keys in the player and queue when track mf-* art differs from the album bucket. * fix(cover): skip library resolve on advanced and full search rows Use API coverArt for album/artist rails and lazy viewport artwork so result pages do not fire hundreds of library_resolve IPC calls at once. * fix(cover): default libraryResolve off for browse grids and rails Skip per-card library_resolve on album/artist/song browse UI by default; keep it on album/artist headers, playback queue rows, and orbit approval. * fix(cover): split UI/backfill CPU pools and restore mainstage hero carousel Library backfill no longer shares the 2-permit JPEG/WebP semaphore with visible cover ensures. Hero initializes albums from props, re-binds scroll visibility after mount, updates backdrop on slide change, and uses library resolve for correct cover art on the banner. * fix(analysis): resume full-library scan after candidates phase Reset the SQL cursor when entering full-library mode so tracks with partial analysis are not skipped. Tighten TS backfill completion and CPU queue watermarking; align cover-cache key tests with album-scoped storage keys. * fix(library): remove useless map_err in cover_resolve (clippy) CI treats clippy::useless-conversion as error on rusqlite optional() chains. * fix(cover): satisfy clippy on cover_cache_ensure IPC args Pass CoverCacheEnsureArgs as a single Tauri parameter instead of nine positional fields; align frontend invoke payload with { args }.
This commit is contained in:
@@ -67,7 +67,7 @@ describe('coverCacheEnsure', () => {
|
||||
|
||||
const call = invokeMock.mock.calls.find(c => c[0] === 'cover_cache_ensure');
|
||||
expect(call).toBeTruthy();
|
||||
const payload = call?.[1] as Record<string, unknown>;
|
||||
const payload = (call?.[1] as { args: Record<string, unknown> }).args;
|
||||
expect(payload.restBaseUrl).toBe('http://playback.example:5533');
|
||||
expect(payload.username).toBe('playback-user');
|
||||
expect(payload.password).toBe('playback-pass');
|
||||
|
||||
+24
-14
@@ -1,6 +1,6 @@
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { coverIndexKeyFromRef } from '../cover/storageKeys';
|
||||
import { coverIndexKeyFromRef, coverStorageKeyFromRef } from '../cover/storageKeys';
|
||||
import { serverIndexKeyForProfile } from '../utils/server/serverIndexKey';
|
||||
import { getPlaybackServerId } from '../utils/playback/playbackServer';
|
||||
import { restBaseFromUrl } from './subsonicClient';
|
||||
@@ -44,7 +44,9 @@ function ensureArgsFromRef(ref: CoverArtRef, tier: CoverArtTier) {
|
||||
if (scope.kind === 'server') {
|
||||
return {
|
||||
serverIndexKey: coverIndexKeyFromRef(ref),
|
||||
coverArtId: ref.coverArtId,
|
||||
cacheKind: ref.cacheKind,
|
||||
cacheEntityId: ref.cacheEntityId,
|
||||
coverArtId: ref.fetchCoverArtId,
|
||||
tier,
|
||||
restBaseUrl: coverCacheRestHost(scope.url),
|
||||
username: scope.username,
|
||||
@@ -67,7 +69,9 @@ function ensureArgsFromRef(ref: CoverArtRef, tier: CoverArtTier) {
|
||||
const baseUrl = server?.url || getBaseUrl();
|
||||
return {
|
||||
serverIndexKey: coverIndexKeyFromRef(ref),
|
||||
coverArtId: ref.coverArtId,
|
||||
cacheKind: ref.cacheKind,
|
||||
cacheEntityId: ref.cacheEntityId,
|
||||
coverArtId: ref.fetchCoverArtId,
|
||||
tier,
|
||||
restBaseUrl: baseUrl ? coverCacheRestHost(baseUrl) : '',
|
||||
username: server?.username ?? '',
|
||||
@@ -77,22 +81,26 @@ function ensureArgsFromRef(ref: CoverArtRef, tier: CoverArtTier) {
|
||||
|
||||
export type CoverCachePeekItem = {
|
||||
serverIndexKey: string;
|
||||
coverArtId: string;
|
||||
cacheKind: 'album' | 'artist';
|
||||
cacheEntityId: string;
|
||||
tier: CoverArtTier;
|
||||
storageKey: string;
|
||||
};
|
||||
|
||||
/** Disk-only — no HTTP. Returns map storageKey → absolute .webp path. */
|
||||
export async function coverCachePeekBatch(
|
||||
items: CoverCachePeekItem[],
|
||||
refs: CoverArtRef[],
|
||||
tier: CoverArtTier,
|
||||
): Promise<Record<string, string>> {
|
||||
if (items.length === 0) return {};
|
||||
const raw = await invoke<Record<string, string>>('cover_cache_peek_batch', { items });
|
||||
const out: Record<string, string> = {};
|
||||
for (const item of items) {
|
||||
const key = `${item.serverIndexKey}:cover:${item.coverArtId}:${item.tier}`;
|
||||
if (raw[key]) out[key] = raw[key];
|
||||
}
|
||||
return out;
|
||||
if (refs.length === 0) return {};
|
||||
const items: CoverCachePeekItem[] = refs.map(ref => ({
|
||||
serverIndexKey: coverIndexKeyFromRef(ref),
|
||||
cacheKind: ref.cacheKind,
|
||||
cacheEntityId: ref.cacheEntityId,
|
||||
tier,
|
||||
storageKey: coverStorageKeyFromRef(ref, tier),
|
||||
}));
|
||||
return invoke<Record<string, string>>('cover_cache_peek_batch', { items });
|
||||
}
|
||||
|
||||
export async function coverCacheEnsure(
|
||||
@@ -100,7 +108,9 @@ export async function coverCacheEnsure(
|
||||
tier: CoverArtTier,
|
||||
_priority?: string,
|
||||
): Promise<CoverCacheEnsureResult> {
|
||||
return invoke<CoverCacheEnsureResult>('cover_cache_ensure', ensureArgsFromRef(ref, tier));
|
||||
return invoke<CoverCacheEnsureResult>('cover_cache_ensure', {
|
||||
args: ensureArgsFromRef(ref, tier),
|
||||
});
|
||||
}
|
||||
|
||||
export async function coverCacheEnsureBatch(
|
||||
|
||||
@@ -130,12 +130,12 @@ describe('getClient', () => {
|
||||
describe('coverArtCacheKey', () => {
|
||||
it('uses host index key + entity id + tier as a stable cache key', () => {
|
||||
setUpServer();
|
||||
expect(coverArtCacheKey('cover-1')).toBe('music.example.com:cover:cover-1:256');
|
||||
expect(coverArtCacheKey('cover-1', 200)).toBe('music.example.com:cover:cover-1:200');
|
||||
expect(coverArtCacheKey('cover-1')).toBe('music.example.com:cover:album:cover-1:256');
|
||||
expect(coverArtCacheKey('cover-1', 200)).toBe('music.example.com:cover:album:cover-1:200');
|
||||
});
|
||||
|
||||
it('falls back to "_" as the server-id segment when no server is active', () => {
|
||||
expect(coverArtCacheKey('cover-99')).toBe('_:cover:cover-99:256');
|
||||
expect(coverArtCacheKey('cover-99')).toBe('_:cover:album:cover-99:256');
|
||||
});
|
||||
|
||||
it('does not embed the ephemeral salt or token — keys stay cacheable across calls', () => {
|
||||
@@ -214,7 +214,7 @@ describe('buildCoverArtUrlForServer', () => {
|
||||
describe('coverArtCacheKeyForServer', () => {
|
||||
it('scopes cache keys by host index key when profile is known', () => {
|
||||
const profileId = setUpServer({ url: 'https://b.example' });
|
||||
expect(coverArtCacheKeyForServer(profileId, 'cover-1', 80)).toBe('b.example:cover:cover-1:80');
|
||||
expect(coverArtCacheKeyForServer(profileId, 'cover-1', 80)).toBe('b.example:cover:album:cover-1:80');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import md5 from 'md5';
|
||||
import { coverStorageKey } from '../cover/storageKeys';
|
||||
import { coverStorageKey, coverStorageKeyFromRef } from '../cover/storageKeys';
|
||||
import { coverEntryToRef, resolveAlbumCoverEntry } from '../cover/resolveEntry';
|
||||
import type { CoverArtTier } from '../cover/types';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { findServerByIdOrIndexKey } from '../utils/server/serverLookup';
|
||||
@@ -57,14 +58,18 @@ export function buildStreamUrl(id: string): string {
|
||||
|
||||
/** @deprecated Use `coverStorageKey` from `src/cover/storageKeys` — shim until migration. */
|
||||
export function coverArtCacheKey(id: string, size = 256): string {
|
||||
return coverStorageKey({ kind: 'active' }, id, size as CoverArtTier);
|
||||
const entry = resolveAlbumCoverEntry(id, id);
|
||||
const ref = coverEntryToRef(entry ?? { cacheKind: 'album', cacheEntityId: id, fetchCoverArtId: id });
|
||||
return coverStorageKeyFromRef(ref, size as CoverArtTier);
|
||||
}
|
||||
|
||||
/** @deprecated Use `coverStorageKey` from `src/cover/storageKeys` — shim until migration. */
|
||||
export function coverArtCacheKeyForServer(serverIdOrKey: string, id: string, size = 256): string {
|
||||
const server = findServerByIdOrIndexKey(serverIdOrKey);
|
||||
if (!server) return `${serverIdOrKey}:cover:${id}:${size}`;
|
||||
return coverStorageKey(
|
||||
if (!server) return `${serverIdOrKey}:cover:album:${id}:${size}`;
|
||||
const entry = resolveAlbumCoverEntry(id, id);
|
||||
const ref = coverEntryToRef(
|
||||
entry ?? { cacheKind: 'album', cacheEntityId: id, fetchCoverArtId: id },
|
||||
{
|
||||
kind: 'server',
|
||||
serverId: server.id,
|
||||
@@ -72,9 +77,8 @@ export function coverArtCacheKeyForServer(serverIdOrKey: string, id: string, siz
|
||||
username: server.username,
|
||||
password: server.password,
|
||||
},
|
||||
id,
|
||||
size as CoverArtTier,
|
||||
);
|
||||
return coverStorageKeyFromRef(ref, size as CoverArtTier);
|
||||
}
|
||||
|
||||
/** @deprecated Use `buildCoverArtFetchUrl` from `src/cover/fetchUrl` — shim until migration. */
|
||||
|
||||
@@ -9,9 +9,10 @@ import { usePlayerStore } from '../store/playerStore';
|
||||
import { useOfflineStore } from '../store/offlineStore';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { CoverArtImage } from '../cover/CoverArtImage';
|
||||
import { useAlbumCoverRef } from '../cover/useLibraryCoverRef';
|
||||
import { coverStorageKeyFromRef } from '../cover/storageKeys';
|
||||
import type { CoverPrefetchPriority } from '../cover/types';
|
||||
import { COVER_DENSE_GRID_MIN_CELL_CSS_PX } from '../cover/layoutSizes';
|
||||
import { coverStorageKey } from '../cover/storageKeys';
|
||||
import { resolveCoverDisplayTier } from '../cover/tiers';
|
||||
import { acquireUrl } from '../utils/imageCache/urlPool';
|
||||
import { OpenArtistRefInline } from './OpenArtistRefInline';
|
||||
@@ -38,6 +39,8 @@ interface AlbumCardProps {
|
||||
observeScrollRootId?: string;
|
||||
/** `high` for bounded grids (Random Albums, …) — skip defer-until-visible. */
|
||||
ensurePriority?: CoverPrefetchPriority;
|
||||
/** Artist/detail grids: API `coverArt` is enough — skip per-card library_resolve IPC. */
|
||||
libraryResolve?: boolean;
|
||||
}
|
||||
|
||||
function AlbumCard({
|
||||
@@ -53,6 +56,7 @@ function AlbumCard({
|
||||
observeScrollRootId,
|
||||
ensurePriority,
|
||||
linkQuery,
|
||||
libraryResolve = false,
|
||||
}: AlbumCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
@@ -65,11 +69,12 @@ function AlbumCard({
|
||||
return meta.trackIds.every(tid => !!s.tracks[`${serverId}:${tid}`]);
|
||||
});
|
||||
const psyDrag = useDragDrop();
|
||||
const coverRef = useAlbumCoverRef(album.id, album.coverArt, undefined, { libraryResolve });
|
||||
const dragCoverKey = useMemo(() => {
|
||||
if (!album.coverArt) return '';
|
||||
if (!coverRef) return '';
|
||||
const tier = resolveCoverDisplayTier(displayCssPx, { surface: 'dense' });
|
||||
return coverStorageKey({ kind: 'active' }, album.coverArt, tier);
|
||||
}, [album.coverArt, displayCssPx]);
|
||||
return coverStorageKeyFromRef(coverRef, tier);
|
||||
}, [coverRef, displayCssPx]);
|
||||
const isNewAlbum = isAlbumRecentlyAdded(album.created);
|
||||
const artistRefs = useMemo(() => deriveAlbumArtistRefs(album), [album]);
|
||||
|
||||
@@ -112,9 +117,9 @@ function AlbumCard({
|
||||
}}
|
||||
>
|
||||
<div className="album-card-cover">
|
||||
{!disableArtwork && album.coverArt ? (
|
||||
{!disableArtwork && coverRef ? (
|
||||
<CoverArtImage
|
||||
coverArtId={album.coverArt}
|
||||
coverRef={coverRef}
|
||||
displayCssPx={displayCssPx}
|
||||
surface="dense"
|
||||
alt={`${album.name} Cover`}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { createPortal } from 'react-dom';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Play, Heart, ExternalLink, X, ChevronLeft, Download, ListPlus, HardDriveDownload, Share2, Highlighter, Loader2, Shuffle } from 'lucide-react';
|
||||
import { CoverArtImage } from '../cover/CoverArtImage';
|
||||
import { coverArtRef } from '../cover/ref';
|
||||
import { useAlbumCoverRef } from '../cover/useLibraryCoverRef';
|
||||
import { useCoverLightboxSrc } from '../cover/lightbox';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useIsMobile } from '../hooks/useIsMobile';
|
||||
@@ -121,10 +121,7 @@ export default function AlbumHeader({
|
||||
const isMobile = useIsMobile();
|
||||
const enableCoverArtBackground = useThemeStore(s => s.enableCoverArtBackground);
|
||||
|
||||
const coverRef = useMemo(
|
||||
() => (coverArtId ? coverArtRef(coverArtId) : null),
|
||||
[coverArtId],
|
||||
);
|
||||
const coverRef = useAlbumCoverRef(info.id, coverArtId, undefined, { libraryResolve: true });
|
||||
const { open: openLightbox, lightbox } = useCoverLightboxSrc(coverRef, {
|
||||
alt: `${info.name} Cover`,
|
||||
});
|
||||
@@ -167,7 +164,7 @@ export default function AlbumHeader({
|
||||
<ChevronLeft size={16} /> {t('albumDetail.back')}
|
||||
</button>
|
||||
<div className="album-detail-hero">
|
||||
{coverArtId ? (
|
||||
{coverRef ? (
|
||||
<button
|
||||
className="album-detail-cover-btn"
|
||||
onClick={openLightbox}
|
||||
@@ -176,7 +173,7 @@ export default function AlbumHeader({
|
||||
>
|
||||
<CoverArtImage
|
||||
className="album-detail-cover"
|
||||
coverArtId={coverArtId}
|
||||
coverRef={coverRef}
|
||||
displayCssPx={400}
|
||||
surface="sparse"
|
||||
alt={`${info.name} Cover`}
|
||||
|
||||
@@ -24,6 +24,8 @@ interface Props {
|
||||
initialArtworkBudget?: number;
|
||||
/** Appended to `/album/:id` links, e.g. `lossless=1`. */
|
||||
albumLinkQuery?: string;
|
||||
/** Search/browse rows: API `coverArt` only — no per-card library_resolve IPC. */
|
||||
libraryResolve?: boolean;
|
||||
}
|
||||
|
||||
export default function AlbumRow({
|
||||
@@ -41,6 +43,7 @@ export default function AlbumRow({
|
||||
windowArtworkByViewport = false,
|
||||
initialArtworkBudget = 8,
|
||||
albumLinkQuery,
|
||||
libraryResolve = false,
|
||||
}: Props) {
|
||||
const perfFlags = usePerfProbeFlags();
|
||||
const artworkDisabled = perfFlags.disableMainstageRailArtwork || disableArtwork;
|
||||
@@ -171,6 +174,7 @@ export default function AlbumRow({
|
||||
album={a}
|
||||
showRating={showRating}
|
||||
linkQuery={albumLinkQuery}
|
||||
libraryResolve={libraryResolve}
|
||||
disableArtwork={
|
||||
artworkDisabled ||
|
||||
(windowArtworkByViewport && idx >= artworkBudget)
|
||||
|
||||
@@ -4,27 +4,29 @@ import { useNavigate } from 'react-router-dom';
|
||||
import { Users } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { CoverArtImage } from '../cover/CoverArtImage';
|
||||
import { coverArtIdFromArtist } from '../cover/ids';
|
||||
import { useArtistCoverRef } from '../cover/useLibraryCoverRef';
|
||||
import { COVER_DENSE_GRID_MIN_CELL_CSS_PX } from '../cover/layoutSizes';
|
||||
|
||||
interface Props {
|
||||
artist: SubsonicArtist;
|
||||
/** Appended to `/artist/:id`, e.g. `lossless=1`. */
|
||||
linkQuery?: string;
|
||||
/** Search/browse rows: API `coverArt` only — no per-card library_resolve IPC. */
|
||||
libraryResolve?: boolean;
|
||||
}
|
||||
|
||||
export default function ArtistCardLocal({ artist, linkQuery }: Props) {
|
||||
export default function ArtistCardLocal({ artist, linkQuery, libraryResolve = false }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const coverId = coverArtIdFromArtist(artist);
|
||||
const coverRef = useArtistCoverRef(artist.id, artist.coverArt, undefined, { libraryResolve });
|
||||
const href = linkQuery ? `/artist/${artist.id}?${linkQuery}` : `/artist/${artist.id}`;
|
||||
|
||||
return (
|
||||
<div className="artist-card" onClick={() => navigate(href)}>
|
||||
<div className="artist-card-avatar">
|
||||
{artist.coverArt || artist.id ? (
|
||||
{coverRef ? (
|
||||
<CoverArtImage
|
||||
coverArtId={coverId}
|
||||
coverRef={coverRef}
|
||||
displayCssPx={COVER_DENSE_GRID_MIN_CELL_CSS_PX}
|
||||
surface="dense"
|
||||
alt={artist.name}
|
||||
|
||||
@@ -10,9 +10,13 @@ interface Props {
|
||||
moreLink?: string;
|
||||
moreText?: string;
|
||||
artistLinkQuery?: string;
|
||||
/** Search results: use API coverArt ids only. */
|
||||
libraryResolve?: boolean;
|
||||
}
|
||||
|
||||
export default function ArtistRow({ title, artists, moreLink, moreText, artistLinkQuery }: Props) {
|
||||
export default function ArtistRow({
|
||||
title, artists, moreLink, moreText, artistLinkQuery, libraryResolve = false,
|
||||
}: Props) {
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const navigate = useNavigate();
|
||||
const [showLeft, setShowLeft] = useState(false);
|
||||
@@ -55,7 +59,14 @@ export default function ArtistRow({ title, artists, moreLink, moreText, artistLi
|
||||
|
||||
<div className="album-grid-wrapper">
|
||||
<div className="album-grid" ref={scrollRef} onScroll={handleScroll}>
|
||||
{artists.map(a => <ArtistCardLocal key={a.id} artist={a} linkQuery={artistLinkQuery} />)}
|
||||
{artists.map(a => (
|
||||
<ArtistCardLocal
|
||||
key={a.id}
|
||||
artist={a}
|
||||
linkQuery={artistLinkQuery}
|
||||
libraryResolve={libraryResolve}
|
||||
/>
|
||||
))}
|
||||
{moreLink && (
|
||||
<div className="album-card-more" onClick={() => navigate(moreLink)}>
|
||||
<div style={{ padding: '1rem', background: 'var(--bg-app)', borderRadius: 'var(--radius-sm)' }}>
|
||||
|
||||
@@ -7,8 +7,8 @@ import React, { memo, useEffect, useLayoutEffect, useMemo, useRef, useState } fr
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Play, ListPlus, Music } from 'lucide-react';
|
||||
import { coverArtRef } from '../cover/ref';
|
||||
import { coverPrefetchRegister } from '../cover/prefetchRegistry';
|
||||
import { useAlbumCoverRef } from '../cover/useLibraryCoverRef';
|
||||
import { useLibraryCoverPrefetch } from '../cover/useLibraryCoverPrefetch';
|
||||
import { coverImgSrc } from '../cover/imgSrc';
|
||||
import { useCoverArt } from '../cover/useCoverArt';
|
||||
import { primeAlbumCoversForDisplay } from '../cover/warmDiskPeek';
|
||||
@@ -500,11 +500,10 @@ export default function BecauseYouLikeRail({
|
||||
return () => { cancelled = true; };
|
||||
}, [pool, activeServerId, disableArtwork, poolKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (disableArtwork || recs.length === 0) return;
|
||||
const refs = recs.flatMap(a => (a.coverArt ? [coverArtRef(a.coverArt)] : []));
|
||||
return coverPrefetchRegister(refs, { surface: 'dense', priority: 'high' });
|
||||
}, [recs, disableArtwork]);
|
||||
useLibraryCoverPrefetch(
|
||||
disableArtwork || recs.length === 0 ? [] : [{ albums: recs, priority: 'high' }],
|
||||
[recs, disableArtwork],
|
||||
);
|
||||
|
||||
if (pool.length === 0) {
|
||||
return <div ref={containerRef} />;
|
||||
@@ -562,7 +561,8 @@ const BecauseCard = memo(function BecauseCard({ album, anchor, disableArtwork, e
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const enqueue = usePlayerStore(s => s.enqueue);
|
||||
const coverHandle = useCoverArt(album.coverArt, BECAUSE_CARD_COVER_CSS_PX, {
|
||||
const coverRef = useAlbumCoverRef(album.id, album.coverArt, undefined, { libraryResolve: false });
|
||||
const coverHandle = useCoverArt(coverRef, BECAUSE_CARD_COVER_CSS_PX, {
|
||||
surface: 'dense',
|
||||
ensurePriority: 'high',
|
||||
});
|
||||
|
||||
@@ -103,25 +103,28 @@ describe('FullscreenPlayer — regression §4.5 of v2 plan', () => {
|
||||
// The `false` arg is load-bearing — it avoids a double crossfade by
|
||||
// routing through the cache-only path. Pin it.
|
||||
it('passes opt=false on the cover-art useCachedUrl call (no fetchUrl fallback)', () => {
|
||||
usePlayerStore.setState({ currentTrack: makeTrack({ coverArt: 'art-1' }) });
|
||||
usePlayerStore.setState({
|
||||
currentTrack: makeTrack({ coverArt: 'art-1', albumId: 'album-1' }),
|
||||
});
|
||||
renderWithProviders(<FullscreenPlayer onClose={() => {}} />);
|
||||
|
||||
const calls = vi.mocked(useCachedUrl).mock.calls;
|
||||
// Find the call whose cacheKey targets the 500 px cover (`...:cover:art-1:500`).
|
||||
const coverCall = calls.find(c => c[2] === false);
|
||||
expect(coverCall).toBeDefined();
|
||||
expect(typeof coverCall?.[1]).toBe('string');
|
||||
expect(String(coverCall?.[1])).toContain('art-1');
|
||||
expect(String(coverCall?.[1])).toContain('album-1');
|
||||
});
|
||||
|
||||
it('also issues a useCachedUrl call with the default behaviour for the small art box', () => {
|
||||
usePlayerStore.setState({ currentTrack: makeTrack({ coverArt: 'art-1' }) });
|
||||
usePlayerStore.setState({
|
||||
currentTrack: makeTrack({ coverArt: 'art-1', albumId: 'album-1' }),
|
||||
});
|
||||
renderWithProviders(<FullscreenPlayer onClose={() => {}} />);
|
||||
|
||||
const calls = vi.mocked(useCachedUrl).mock.calls;
|
||||
const defaultOptCalls = calls.filter(c => c[2] !== false);
|
||||
expect(defaultOptCalls.length).toBeGreaterThanOrEqual(1);
|
||||
expect(defaultOptCalls.some(c => String(c[1]).includes('art-1'))).toBe(true);
|
||||
expect(defaultOptCalls.some(c => String(c[1]).includes('album-1'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { queueSongStar } from '../store/pendingStarSync';
|
||||
import { usePlaybackCoverArt } from '../hooks/usePlaybackCoverArt';
|
||||
import { playbackCoverArtForId } from '../utils/playback/playbackServer';
|
||||
import { usePlaybackTrackCoverRef } from '../cover/useLibraryCoverRef';
|
||||
import { playbackCoverArtForAlbum } from '../utils/playback/playbackServer';
|
||||
import React, { useCallback, useEffect, useState, useRef, useMemo } from 'react';
|
||||
import {
|
||||
SkipBack, SkipForward,
|
||||
@@ -50,11 +51,12 @@ export default function FullscreenPlayer({ onClose }: FullscreenPlayerProps) {
|
||||
|
||||
const duration = currentTrack?.duration ?? 0;
|
||||
|
||||
// 300px for the small art box; 500px for the right-side portrait fallback.
|
||||
const artCover = usePlaybackCoverArt(currentTrack?.coverArt, 300);
|
||||
const playbackCoverRef = usePlaybackTrackCoverRef(currentTrack ?? undefined);
|
||||
|
||||
const artCover = usePlaybackCoverArt(playbackCoverRef, 300);
|
||||
const artUrl = artCover.src;
|
||||
const artKey = artCover.cacheKey;
|
||||
const portraitCover = usePlaybackCoverArt(currentTrack?.coverArt, 500);
|
||||
const portraitCover = usePlaybackCoverArt(playbackCoverRef, 500);
|
||||
const coverUrl = portraitCover.src;
|
||||
const coverKey = portraitCover.cacheKey;
|
||||
// `false` = no fetchUrl fallback — prevents double crossfade (fetchUrl → blobUrl).
|
||||
@@ -79,14 +81,17 @@ export default function FullscreenPlayer({ onClose }: FullscreenPlayerProps) {
|
||||
// around the current index keeps it warm).
|
||||
const queueIndex = usePlayerStore(s => s.queueIndex);
|
||||
const nextTrack = useQueueTrackAt(queueIndex + 1);
|
||||
const nextCoverArt = queueIndex >= 0 ? (nextTrack?.coverArt ?? null) : null;
|
||||
const queueServerId = usePlayerStore(s => s.queueServerId);
|
||||
const activeServerId = useAuthStore(s => s.activeServerId);
|
||||
useEffect(() => {
|
||||
if (!nextCoverArt) return;
|
||||
const { src: url, cacheKey: key } = playbackCoverArtForId(nextCoverArt, 300);
|
||||
if (!nextTrack?.albumId || !nextTrack.coverArt) return;
|
||||
const { src: url, cacheKey: key } = playbackCoverArtForAlbum(
|
||||
nextTrack.albumId,
|
||||
nextTrack.coverArt,
|
||||
300,
|
||||
);
|
||||
getCachedBlob(url, key).catch(() => {});
|
||||
}, [nextCoverArt, queueServerId, activeServerId]);
|
||||
}, [nextTrack?.albumId, nextTrack?.coverArt, queueServerId, activeServerId]);
|
||||
|
||||
// Lyrics settings popover state
|
||||
const [lyricsMenuOpen, setLyricsMenuOpen] = useState(false);
|
||||
|
||||
+16
-6
@@ -6,6 +6,7 @@ import { useNavigate } from 'react-router-dom';
|
||||
import { Play, ListPlus, ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import { CoverArtImage } from '../cover/CoverArtImage';
|
||||
import { useCoverArt } from '../cover/useCoverArt';
|
||||
import { useAlbumCoverRef } from '../cover/useLibraryCoverRef';
|
||||
import { usePlayerStore } from '../store/playerStore';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { playAlbum } from '../utils/playback/playAlbum';
|
||||
@@ -74,7 +75,9 @@ export default function Hero({ albums: albumsProp }: HeroProps = {}) {
|
||||
const enableCoverArtBackground = useThemeStore(s => s.enableCoverArtBackground);
|
||||
const mixMinRatingAlbum = useAuthStore(s => s.mixMinRatingAlbum);
|
||||
const mixMinRatingArtist = useAuthStore(s => s.mixMinRatingArtist);
|
||||
const [albums, setAlbums] = useState<SubsonicAlbum[]>([]);
|
||||
const [albums, setAlbums] = useState<SubsonicAlbum[]>(() =>
|
||||
albumsProp?.length ? albumsProp : [],
|
||||
);
|
||||
const [activeIdx, setActiveIdx] = useState(0);
|
||||
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const windowHidden = useWindowVisibility();
|
||||
@@ -125,6 +128,8 @@ export default function Hero({ albums: albumsProp }: HeroProps = {}) {
|
||||
heroScrollRootRef.current =
|
||||
scrollRoot ?? (node.closest('.app-shell-route-scroll__viewport') as HTMLElement | null);
|
||||
updateHeroVisibility();
|
||||
// Layout may settle after first paint (hero mounts after albums hydrate from props).
|
||||
const layoutRaf = window.requestAnimationFrame(() => updateHeroVisibility());
|
||||
const root = heroScrollRootRef.current;
|
||||
const onScroll = () => {
|
||||
if (visibilityRafRef.current != null) return;
|
||||
@@ -148,8 +153,9 @@ export default function Hero({ albums: albumsProp }: HeroProps = {}) {
|
||||
window.cancelAnimationFrame(visibilityRafRef.current);
|
||||
visibilityRafRef.current = null;
|
||||
}
|
||||
window.cancelAnimationFrame(layoutRaf);
|
||||
};
|
||||
}, [updateHeroVisibility]);
|
||||
}, [updateHeroVisibility, albums.length]);
|
||||
|
||||
useEffect(() => {
|
||||
const updateBlurState = () => {
|
||||
@@ -259,7 +265,8 @@ export default function Hero({ albums: albumsProp }: HeroProps = {}) {
|
||||
});
|
||||
}, [album?.id]);
|
||||
|
||||
const bgHandle = useCoverArt(album?.coverArt, HERO_BG_CSS_PX, {
|
||||
const heroCoverRef = useAlbumCoverRef(album?.id, album?.coverArt);
|
||||
const bgHandle = useCoverArt(heroCoverRef, HERO_BG_CSS_PX, {
|
||||
surface: 'dense',
|
||||
ensurePriority: 'high',
|
||||
});
|
||||
@@ -267,7 +274,10 @@ export default function Hero({ albums: albumsProp }: HeroProps = {}) {
|
||||
// Keep the last known good URL so HeroBg never receives '' during a cache-miss
|
||||
// transition (which would cause the background to flash empty before fading in).
|
||||
const stableBgUrl = useRef('');
|
||||
if (bgHandle.src) stableBgUrl.current = bgHandle.src;
|
||||
const albumId = album?.id;
|
||||
useEffect(() => {
|
||||
if (bgHandle.src) stableBgUrl.current = bgHandle.src;
|
||||
}, [bgHandle.src, albumId]);
|
||||
|
||||
if (!album) return <div className="hero-placeholder" />;
|
||||
|
||||
@@ -285,9 +295,9 @@ export default function Hero({ albums: albumsProp }: HeroProps = {}) {
|
||||
|
||||
{/* key causes re-mount → animate-fade-in triggers on each album change */}
|
||||
<div className="hero-content" key={album.id}>
|
||||
{album.coverArt && !isMobile && (
|
||||
{heroCoverRef && !isMobile && (
|
||||
<CoverArtImage
|
||||
coverArtId={album.coverArt}
|
||||
coverRef={heroCoverRef}
|
||||
displayCssPx={HERO_FG_CSS_PX}
|
||||
surface="dense"
|
||||
ensurePriority="high"
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
suggestionKey,
|
||||
} from '../utils/orbit';
|
||||
import { CoverArtImage } from '../cover/CoverArtImage';
|
||||
import { TrackCoverArtImage } from '../cover/TrackCoverArtImage';
|
||||
import { ORBIT_DEFAULT_SETTINGS } from '../api/orbit';
|
||||
|
||||
const HOST_APPROVAL_COVER_CSS_PX = 36;
|
||||
@@ -85,9 +86,10 @@ export default function HostApprovalQueue() {
|
||||
const key = suggestionKey(q);
|
||||
return (
|
||||
<div key={key} className="host-approval__item">
|
||||
{song?.coverArt ? (
|
||||
<CoverArtImage
|
||||
coverArtId={song.coverArt}
|
||||
{song ? (
|
||||
<TrackCoverArtImage
|
||||
song={song}
|
||||
libraryResolve
|
||||
displayCssPx={HOST_APPROVAL_COVER_CSS_PX}
|
||||
surface="dense"
|
||||
alt=""
|
||||
|
||||
@@ -28,11 +28,12 @@ import { useAuthStore } from '../store/authStore';
|
||||
import { useLibraryIndexStore } from '../store/libraryIndexStore';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { FETCH_QUEUE_BIAS_SEARCH_ARTIST_OVER_ALBUM } from './CachedImage';
|
||||
import type { SubsonicSong } from '../api/subsonicTypes';
|
||||
import { AlbumCoverArtImage } from '../cover/AlbumCoverArtImage';
|
||||
import { ArtistCoverArtImage } from '../cover/ArtistCoverArtImage';
|
||||
import { CoverArtImage } from '../cover/CoverArtImage';
|
||||
import { COVER_DENSE_SEARCH_CSS_PX } from '../cover/layoutSizes';
|
||||
import { coverArtIdFromArtist } from '../cover/ids';
|
||||
import { coverPrefetchRegister } from '../cover/prefetchRegistry';
|
||||
import { coverArtRef } from '../cover/ref';
|
||||
import { albumCoverRefForSong } from '../cover/ref';
|
||||
import { showToast } from '../utils/ui/toast';
|
||||
import { useShareSearch } from '../hooks/useShareSearch';
|
||||
import ShareSearchResults from './search/ShareSearchResults';
|
||||
@@ -40,31 +41,54 @@ import { resolveIndexKey } from '../utils/server/serverIndexKey';
|
||||
|
||||
type LiveSearchSource = 'local' | 'network';
|
||||
|
||||
function LiveSearchAlbumThumb({ coverArt }: { coverArt: string }) {
|
||||
function LiveSearchAlbumThumb({ albumId, coverArt }: { albumId: string; coverArt: string }) {
|
||||
return (
|
||||
<CoverArtImage
|
||||
coverArtId={coverArt}
|
||||
<AlbumCoverArtImage
|
||||
albumId={albumId}
|
||||
coverArt={coverArt}
|
||||
libraryResolve={false}
|
||||
displayCssPx={COVER_DENSE_SEARCH_CSS_PX}
|
||||
surface="dense"
|
||||
className="search-result-thumb"
|
||||
alt=""
|
||||
ensurePriority="high"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function LiveSearchSongThumb({ song }: { song: Pick<SubsonicSong, 'id' | 'albumId' | 'coverArt' | 'discNumber'> }) {
|
||||
const coverRef = React.useMemo(
|
||||
() => (song.albumId?.trim() ? albumCoverRefForSong(song) : undefined),
|
||||
[song.id, song.albumId, song.coverArt, song.discNumber],
|
||||
);
|
||||
if (!coverRef) return null;
|
||||
return (
|
||||
<CoverArtImage
|
||||
coverRef={coverRef}
|
||||
displayCssPx={COVER_DENSE_SEARCH_CSS_PX}
|
||||
surface="dense"
|
||||
className="search-result-thumb"
|
||||
alt=""
|
||||
ensurePriority="high"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function LiveSearchArtistThumb({ artist }: { artist: Pick<SubsonicArtist, 'id' | 'coverArt'> }) {
|
||||
const [failed, setFailed] = useState(false);
|
||||
const coverId = coverArtIdFromArtist(artist);
|
||||
useEffect(() => { setFailed(false); }, [coverId]);
|
||||
useEffect(() => { setFailed(false); }, [artist.id, artist.coverArt]);
|
||||
if (failed) return <div className="search-result-icon"><Users size={14} /></div>;
|
||||
return (
|
||||
<CoverArtImage
|
||||
coverArtId={coverId}
|
||||
<ArtistCoverArtImage
|
||||
artistId={artist.id}
|
||||
coverArt={artist.coverArt}
|
||||
libraryResolve={false}
|
||||
displayCssPx={COVER_DENSE_SEARCH_CSS_PX}
|
||||
surface="dense"
|
||||
className="search-result-thumb"
|
||||
alt=""
|
||||
loading="eager"
|
||||
ensurePriority="high"
|
||||
fetchQueueBias={FETCH_QUEUE_BIAS_SEARCH_ARTIST_OVER_ALBUM}
|
||||
onError={() => setFailed(true)}
|
||||
/>
|
||||
@@ -422,19 +446,6 @@ export default function LiveSearch() {
|
||||
!!share.shareMatch ||
|
||||
(results && (results.artists.length || results.albums.length || results.songs.length));
|
||||
|
||||
useEffect(() => {
|
||||
if (!results || share.shareMatch) return () => {};
|
||||
const refs = [
|
||||
...results.artists.map(a => coverArtRef(coverArtIdFromArtist(a))),
|
||||
...results.albums.flatMap(a => (a.coverArt ? [coverArtRef(a.coverArt)] : [])),
|
||||
...results.songs.flatMap(s => {
|
||||
const id = s.coverArt ?? s.albumId;
|
||||
return id ? [coverArtRef(id)] : [];
|
||||
}),
|
||||
];
|
||||
return coverPrefetchRegister(refs, { surface: 'dense', priority: 'high' });
|
||||
}, [results, share.shareMatch]);
|
||||
|
||||
// Flat list of all navigable items for keyboard nav
|
||||
const flatItems = share.shareMatch && share.hasShareKeyboardTarget ? [
|
||||
{
|
||||
@@ -674,7 +685,7 @@ export default function LiveSearch() {
|
||||
}}
|
||||
role="option" aria-selected={activeIndex === i}>
|
||||
{a.coverArt ? (
|
||||
<LiveSearchAlbumThumb coverArt={a.coverArt} />
|
||||
<LiveSearchAlbumThumb albumId={a.id} coverArt={a.coverArt} />
|
||||
) : (
|
||||
<div className="search-result-icon"><Disc3 size={14} /></div>
|
||||
)}
|
||||
@@ -710,7 +721,7 @@ export default function LiveSearch() {
|
||||
}}
|
||||
role="option" aria-selected={activeIndex === i}>
|
||||
{(s.coverArt ?? s.albumId) ? (
|
||||
<LiveSearchAlbumThumb coverArt={s.coverArt ?? s.albumId!} />
|
||||
<LiveSearchSongThumb song={s} />
|
||||
) : (
|
||||
<div className="search-result-icon"><Music size={14} /></div>
|
||||
)}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { usePlaybackCoverArt } from '../hooks/usePlaybackCoverArt';
|
||||
import { usePlaybackTrackCoverRef } from '../cover/useLibraryCoverRef';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { emit } from '@tauri-apps/api/event';
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
@@ -140,7 +141,8 @@ export default function MiniPlayer() {
|
||||
}, [queueOpen, state.queueIndex]);
|
||||
|
||||
const { track, isPlaying } = state;
|
||||
const { src: miniCoverSrc, cacheKey: miniCoverKey } = usePlaybackCoverArt(track?.coverArt, 300);
|
||||
const miniCoverRef = usePlaybackTrackCoverRef(track ?? undefined);
|
||||
const { src: miniCoverSrc, cacheKey: miniCoverKey } = usePlaybackCoverArt(miniCoverRef, 300);
|
||||
const progress = duration > 0 ? Math.min(100, (currentTime / duration) * 100) : 0;
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { queueSongStar } from '../store/pendingStarSync';
|
||||
import { usePlaybackCoverArt } from '../hooks/usePlaybackCoverArt';
|
||||
import { usePlaybackTrackCoverRef } from '../cover/useLibraryCoverRef';
|
||||
import type { Track } from '../store/playerStoreTypes';
|
||||
import { getPlaybackProgressSnapshot, subscribePlaybackProgress } from '../store/playbackProgress';
|
||||
import React, { useState, useCallback, useMemo, useRef, useEffect, useSyncExternalStore, CSSProperties } from 'react';
|
||||
@@ -223,7 +224,8 @@ export default function MobilePlayerView() {
|
||||
|
||||
const duration = currentTrack?.duration ?? 0;
|
||||
|
||||
const { src: coverFetchUrl, cacheKey: coverKey } = usePlaybackCoverArt(currentTrack?.coverArt, 800);
|
||||
const playbackCoverRef = usePlaybackTrackCoverRef(currentTrack ?? undefined);
|
||||
const { src: coverFetchUrl, cacheKey: coverKey } = usePlaybackCoverArt(playbackCoverRef, 800);
|
||||
const resolvedCover = useCachedUrl(coverFetchUrl, coverKey);
|
||||
|
||||
// Dynamic background color extracted from cover art
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { search } from '../api/subsonicSearch';
|
||||
import type { SearchResults, SubsonicArtist } from '../api/subsonicTypes';
|
||||
import { songToTrack } from '../utils/playback/songToTrack';
|
||||
import React, { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { X, Search, Disc3, Users, Music, Music2, Clock, ChevronRight } from 'lucide-react';
|
||||
@@ -9,10 +9,10 @@ import { usePlayerStore } from '../store/playerStore';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { FETCH_QUEUE_BIAS_SEARCH_ARTIST_OVER_ALBUM } from './CachedImage';
|
||||
import { AlbumCoverArtImage } from '../cover/AlbumCoverArtImage';
|
||||
import { ArtistCoverArtImage } from '../cover/ArtistCoverArtImage';
|
||||
import { CoverArtImage } from '../cover/CoverArtImage';
|
||||
import { coverArtIdFromArtist } from '../cover/ids';
|
||||
import { coverPrefetchRegister } from '../cover/prefetchRegistry';
|
||||
import { coverArtRef } from '../cover/ref';
|
||||
import { albumCoverRefForSong } from '../cover/ref';
|
||||
import { showToast } from '../utils/ui/toast';
|
||||
import { useShareSearch } from '../hooks/useShareSearch';
|
||||
import ShareSearchResults from './search/ShareSearchResults';
|
||||
@@ -38,10 +38,31 @@ function debounce(fn: (q: string) => void, ms: number): (q: string) => void {
|
||||
/** Mobile search row thumb — larger than desktop live search (32px). */
|
||||
const MOBILE_SEARCH_THUMB_CSS_PX = 80;
|
||||
|
||||
function MobileSearchSongThumb({
|
||||
song,
|
||||
}: {
|
||||
song: Pick<SearchResults['songs'][number], 'id' | 'albumId' | 'coverArt' | 'discNumber'>;
|
||||
}) {
|
||||
const coverRef = useMemo(
|
||||
() => (song.albumId?.trim() ? albumCoverRefForSong(song) : undefined),
|
||||
[song.id, song.albumId, song.coverArt, song.discNumber],
|
||||
);
|
||||
if (!coverRef) return null;
|
||||
return (
|
||||
<CoverArtImage
|
||||
coverRef={coverRef}
|
||||
displayCssPx={MOBILE_SEARCH_THUMB_CSS_PX}
|
||||
surface="dense"
|
||||
className="mobile-search-thumb"
|
||||
alt=""
|
||||
ensurePriority="high"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function MobileSearchArtistThumb({ artist }: { artist: Pick<SubsonicArtist, 'id' | 'coverArt'> }) {
|
||||
const [failed, setFailed] = useState(false);
|
||||
const coverId = coverArtIdFromArtist(artist);
|
||||
useEffect(() => { setFailed(false); }, [coverId]);
|
||||
useEffect(() => { setFailed(false); }, [artist.id, artist.coverArt]);
|
||||
if (failed) {
|
||||
return (
|
||||
<div className="mobile-search-avatar mobile-search-avatar--circle">
|
||||
@@ -50,8 +71,10 @@ function MobileSearchArtistThumb({ artist }: { artist: Pick<SubsonicArtist, 'id'
|
||||
);
|
||||
}
|
||||
return (
|
||||
<CoverArtImage
|
||||
coverArtId={coverId}
|
||||
<ArtistCoverArtImage
|
||||
artistId={artist.id}
|
||||
coverArt={artist.coverArt}
|
||||
libraryResolve={false}
|
||||
displayCssPx={MOBILE_SEARCH_THUMB_CSS_PX}
|
||||
surface="dense"
|
||||
className="mobile-search-thumb mobile-search-thumb--artist-round"
|
||||
@@ -103,16 +126,6 @@ export default function MobileSearchOverlay({ onClose }: { onClose: () => void }
|
||||
doSearch(query);
|
||||
}, [query, doSearch, share.shareMatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!results) return () => {};
|
||||
const refs = [
|
||||
...results.artists.map(a => coverArtRef(coverArtIdFromArtist(a))),
|
||||
...results.albums.flatMap(a => (a.coverArt ? [coverArtRef(a.coverArt)] : [])),
|
||||
...results.songs.flatMap(s => (s.coverArt ? [coverArtRef(s.coverArt)] : [])),
|
||||
];
|
||||
return coverPrefetchRegister(refs, { surface: 'dense', priority: 'high' });
|
||||
}, [results]);
|
||||
|
||||
const commit = (q: string) => {
|
||||
if (q.trim()) setRecentSearches(prev => saveRecent(q, prev));
|
||||
};
|
||||
@@ -287,12 +300,15 @@ export default function MobileSearchOverlay({ onClose }: { onClose: () => void }
|
||||
{results!.albums.map(a => (
|
||||
<button key={a.id} className="mobile-search-item" onClick={() => goTo(`/album/${a.id}`)}>
|
||||
{a.coverArt ? (
|
||||
<CoverArtImage
|
||||
coverArtId={a.coverArt}
|
||||
<AlbumCoverArtImage
|
||||
albumId={a.id}
|
||||
coverArt={a.coverArt}
|
||||
libraryResolve={false}
|
||||
displayCssPx={MOBILE_SEARCH_THUMB_CSS_PX}
|
||||
surface="dense"
|
||||
className="mobile-search-thumb"
|
||||
alt=""
|
||||
ensurePriority="high"
|
||||
/>
|
||||
) : (
|
||||
<div className="mobile-search-avatar">
|
||||
@@ -314,14 +330,8 @@ export default function MobileSearchOverlay({ onClose }: { onClose: () => void }
|
||||
<div className="mobile-search-section-label">{t('search.songs')}</div>
|
||||
{results!.songs.map(s => (
|
||||
<button key={s.id} className="mobile-search-item" onClick={() => enqueueSong(s)}>
|
||||
{s.coverArt ? (
|
||||
<CoverArtImage
|
||||
coverArtId={s.coverArt}
|
||||
displayCssPx={MOBILE_SEARCH_THUMB_CSS_PX}
|
||||
surface="dense"
|
||||
className="mobile-search-thumb"
|
||||
alt=""
|
||||
/>
|
||||
{s.albumId && (s.coverArt ?? s.albumId) ? (
|
||||
<MobileSearchSongThumb song={s} />
|
||||
) : (
|
||||
<div className="mobile-search-avatar">
|
||||
<Music size={20} />
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { CoverArtImage } from '../cover/CoverArtImage';
|
||||
import { TrackCoverArtImage } from '../cover/TrackCoverArtImage';
|
||||
import { getNowPlaying } from '../api/subsonicScrobble';
|
||||
import type { SubsonicNowPlaying } from '../api/subsonicTypes';
|
||||
import React, { useState, useEffect, useRef, useCallback, useLayoutEffect } from 'react';
|
||||
@@ -161,9 +162,14 @@ export default function NowPlayingDropdown() {
|
||||
style={{ display: 'flex', gap: '0.75rem', alignItems: 'center', background: 'var(--bg-hover)', padding: '0.5rem', borderRadius: '8px', cursor: stream.albumId ? 'pointer' : 'default' }}
|
||||
>
|
||||
<div style={{ width: '48px', height: '48px', flexShrink: 0, borderRadius: '6px', overflow: 'hidden', background: 'var(--bg-surface)' }}>
|
||||
{stream.coverArt ? (
|
||||
<CoverArtImage
|
||||
coverArtId={stream.coverArt}
|
||||
{stream.albumId && stream.coverArt ? (
|
||||
<TrackCoverArtImage
|
||||
song={{
|
||||
id: stream.id,
|
||||
albumId: stream.albumId,
|
||||
coverArt: stream.coverArt,
|
||||
discNumber: undefined,
|
||||
}}
|
||||
displayCssPx={50}
|
||||
surface="sparse"
|
||||
alt="Cover"
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useEffect, useMemo, useState } from 'react';
|
||||
import { Radio, Clock } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useOrbitStore } from '../store/orbitStore';
|
||||
import { CoverArtImage } from '../cover/CoverArtImage';
|
||||
import { TrackCoverArtImage } from '../cover/TrackCoverArtImage';
|
||||
import OrbitQueueHead from './OrbitQueueHead';
|
||||
|
||||
const ORBIT_QUEUE_COVER_LG_CSS_PX = 54;
|
||||
@@ -78,8 +78,9 @@ export default function OrbitGuestQueue() {
|
||||
</div>
|
||||
<div className="orbit-guest-queue__current-body">
|
||||
{currentSong?.coverArt ? (
|
||||
<CoverArtImage
|
||||
coverArtId={currentSong.coverArt}
|
||||
<TrackCoverArtImage
|
||||
song={currentSong}
|
||||
libraryResolve
|
||||
displayCssPx={ORBIT_QUEUE_COVER_LG_CSS_PX}
|
||||
surface="dense"
|
||||
alt=""
|
||||
@@ -115,8 +116,9 @@ export default function OrbitGuestQueue() {
|
||||
return (
|
||||
<div key={trackId} className="orbit-guest-queue__item orbit-guest-queue__item--pending">
|
||||
{song?.coverArt ? (
|
||||
<CoverArtImage
|
||||
coverArtId={song.coverArt}
|
||||
<TrackCoverArtImage
|
||||
song={song}
|
||||
libraryResolve
|
||||
displayCssPx={ORBIT_QUEUE_COVER_SM_CSS_PX}
|
||||
surface="dense"
|
||||
alt=""
|
||||
@@ -154,8 +156,9 @@ export default function OrbitGuestQueue() {
|
||||
className="orbit-guest-queue__item"
|
||||
>
|
||||
{song?.coverArt ? (
|
||||
<CoverArtImage
|
||||
coverArtId={song.coverArt}
|
||||
<TrackCoverArtImage
|
||||
song={song}
|
||||
libraryResolve
|
||||
displayCssPx={ORBIT_QUEUE_COVER_SM_CSS_PX}
|
||||
surface="dense"
|
||||
alt=""
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { queueSongStar } from '../store/pendingStarSync';
|
||||
import { usePlaybackCoverArt } from '../hooks/usePlaybackCoverArt';
|
||||
import { coverArtIdFromRadio } from '../cover/ids';
|
||||
import { resolvePlaybackTrackCoverArtId } from '../cover/resolveCoverArtId';
|
||||
import type { SubsonicAlbum } from '../api/subsonicTypes';
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
@@ -142,15 +142,15 @@ export default function PlayerBar() {
|
||||
// Preview takes visual priority over the queued track in the player-bar info
|
||||
// cell, but only when not in radio mode (radio has its own meta layout).
|
||||
const showPreviewMeta = isPreviewing && !isRadio && previewingTrack !== null;
|
||||
const displayCoverArt = showPreviewMeta ? previewingTrack!.coverArt : currentTrack?.coverArt;
|
||||
const displayTitle = showPreviewMeta ? previewingTrack!.title : (currentTrack?.title ?? t('player.noTitle'));
|
||||
const displayArtist = showPreviewMeta ? previewingTrack!.artist : (currentTrack?.artist ?? '—');
|
||||
const displayArtistRefs = !showPreviewMeta && currentTrack?.artists && currentTrack.artists.length > 0
|
||||
? currentTrack.artists
|
||||
: undefined;
|
||||
|
||||
usePlaybackCoverArt(showPreviewMeta ? undefined : displayCoverArt, 128);
|
||||
const coverArtId = showPreviewMeta ? previewingTrack?.coverArt : displayCoverArt;
|
||||
const coverArtId = showPreviewMeta
|
||||
? previewingTrack?.coverArt
|
||||
: resolvePlaybackTrackCoverArtId(currentTrack);
|
||||
|
||||
const handleVolume = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setVolume(parseFloat(e.target.value));
|
||||
@@ -197,7 +197,6 @@ export default function PlayerBar() {
|
||||
radioMeta={radioMeta}
|
||||
radioCoverArtId={radioCoverArtId}
|
||||
coverArtId={coverArtId}
|
||||
displayCoverArt={displayCoverArt}
|
||||
displayTitle={displayTitle}
|
||||
displayArtist={displayArtist}
|
||||
displayArtistRefs={displayArtistRefs}
|
||||
|
||||
@@ -31,7 +31,6 @@ import { QueueToolbar } from './queuePanel/QueueToolbar';
|
||||
import { QueueList } from './queuePanel/QueueList';
|
||||
import { QueueTabBar } from './queuePanel/QueueTabBar';
|
||||
import { useQueueAutoScroll } from '../hooks/useQueueAutoScroll';
|
||||
import { usePlaybackCoverArt } from '../hooks/usePlaybackCoverArt';
|
||||
|
||||
export default function QueuePanel() {
|
||||
const orbitRole = useOrbitStore(s => s.role);
|
||||
@@ -79,7 +78,6 @@ function QueuePanelHostOrSolo() {
|
||||
const queueIndex = usePlayerStore(s => s.queueIndex);
|
||||
const currentTrack = usePlayerStore(s => s.currentTrack);
|
||||
const userRatingOverrides = usePlayerStore(s => s.userRatingOverrides);
|
||||
const { src: currentCoverSrc } = usePlaybackCoverArt(currentTrack?.coverArt, 128);
|
||||
const isQueueVisible = usePlayerStore(s => s.isQueueVisible);
|
||||
const playTrack = usePlayerStore(s => s.playTrack);
|
||||
const clearQueue = usePlayerStore(s => s.clearQueue);
|
||||
@@ -255,7 +253,6 @@ function QueuePanelHostOrSolo() {
|
||||
{currentTrack && !isNowPlayingCollapsed && (
|
||||
<QueueCurrentTrack
|
||||
currentTrack={currentTrack}
|
||||
currentCoverSrc={currentCoverSrc}
|
||||
userRatingOverrides={userRatingOverrides}
|
||||
orbitAttributionLabel={orbitAttributionLabel}
|
||||
navigate={navigatePlaybackLibrary}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import { usePlayerStore } from '../store/playerStore';
|
||||
import { CoverArtImage } from '../cover/CoverArtImage';
|
||||
import { useCoverArt } from '../cover/useCoverArt';
|
||||
import { useTrackCoverRef } from '../cover/useLibraryCoverRef';
|
||||
import { COVER_DENSE_RAIL_CELL_CSS_PX } from '../cover/layoutSizes';
|
||||
import { enqueueAndPlay } from '../utils/playback/playSong';
|
||||
import { useDragDrop } from '../contexts/DragDropContext';
|
||||
@@ -32,8 +33,8 @@ function SongCard({
|
||||
const navigate = useNavigate();
|
||||
const openContextMenu = usePlayerStore(s => s.openContextMenu);
|
||||
const enqueue = usePlayerStore(s => s.enqueue);
|
||||
const coverArtId = song.coverArt ?? song.albumId;
|
||||
const coverHandle = useCoverArt(coverArtId, layoutPx, {
|
||||
const coverRef = useTrackCoverRef(song, undefined, { libraryResolve: false });
|
||||
const coverHandle = useCoverArt(coverRef, layoutPx, {
|
||||
surface: 'dense',
|
||||
ensurePriority: 'middle',
|
||||
});
|
||||
@@ -93,9 +94,9 @@ function SongCard({
|
||||
}}
|
||||
>
|
||||
<div className="song-card-cover">
|
||||
{!disableArtwork && coverArtId ? (
|
||||
{!disableArtwork && coverRef ? (
|
||||
<CoverArtImage
|
||||
coverArtId={coverArtId}
|
||||
coverRef={coverRef}
|
||||
displayCssPx={layoutPx}
|
||||
surface="dense"
|
||||
alt={`${song.album} Cover`}
|
||||
|
||||
@@ -11,8 +11,8 @@ import { useOfflineJobStore } from '../../store/offlineJobStore';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useIsMobile } from '../../hooks/useIsMobile';
|
||||
import { ArtistHeroCover } from '../../cover/artistHero';
|
||||
import { coverArtRef } from '../../cover/ref';
|
||||
import { useCoverLightboxSrc } from '../../cover/lightbox';
|
||||
import type { CoverArtRef } from '../../cover/types';
|
||||
import LastfmIcon from '../LastfmIcon';
|
||||
import StarRating from '../StarRating';
|
||||
|
||||
@@ -36,6 +36,7 @@ interface Props {
|
||||
openedLink: string | null;
|
||||
openLink: (url: string, key: string) => void;
|
||||
coverId: string;
|
||||
coverRef: CoverArtRef | null;
|
||||
coverRevision: number;
|
||||
headerCoverFailed: boolean;
|
||||
setHeaderCoverFailed: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
@@ -46,7 +47,7 @@ export default function ArtistDetailHero({
|
||||
toggleStar, handlePlayAll, handleShuffle, handleStartRadio, handleShareArtist,
|
||||
handleImageUpload, playAllLoading, radioLoading, uploading,
|
||||
openedLink, openLink,
|
||||
coverId, coverRevision, headerCoverFailed, setHeaderCoverFailed,
|
||||
coverId, coverRef, coverRevision, headerCoverFailed, setHeaderCoverFailed,
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
@@ -58,10 +59,6 @@ export default function ArtistDetailHero({
|
||||
const entityRatingSupportByServer = useAuthStore(s => s.entityRatingSupportByServer);
|
||||
const artistEntityRatingSupport = entityRatingSupportByServer[activeServerId] ?? 'unknown';
|
||||
|
||||
const coverRef = useMemo(
|
||||
() => (coverId ? coverArtRef(coverId) : null),
|
||||
[coverId],
|
||||
);
|
||||
const { open: openLightbox, lightbox } = useCoverLightboxSrc(coverRef, { alt: artist.name });
|
||||
|
||||
const wikiUrl = `https://en.wikipedia.org/wiki/${encodeURIComponent(artist.name)}`;
|
||||
|
||||
@@ -1,23 +1,25 @@
|
||||
import React, { Fragment } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { AudioLines, ChevronRight, Play, Square } from 'lucide-react';
|
||||
import type { SubsonicSong } from '../../api/subsonicTypes';
|
||||
import type { SubsonicAlbum, SubsonicSong } from '../../api/subsonicTypes';
|
||||
import { resolveArtistPageSongCoverArtId } from '../../cover/resolveCoverArtId';
|
||||
import { usePlayerStore } from '../../store/playerStore';
|
||||
import { usePreviewStore } from '../../store/previewStore';
|
||||
import { useOrbitSongRowBehavior } from '../../hooks/useOrbitSongRowBehavior';
|
||||
import { songToTrack } from '../../utils/playback/songToTrack';
|
||||
import { formatTrackTime } from '../../utils/format/formatDuration';
|
||||
import ArtistSuggestionTrackCover from './ArtistSuggestionTrackCover';
|
||||
import ArtistTopTrackCover from './ArtistTopTrackCover';
|
||||
|
||||
interface Props {
|
||||
topSongs: SubsonicSong[];
|
||||
albums: SubsonicAlbum[];
|
||||
marginTop: string;
|
||||
playTopSongWithContinuation: (startIndex: number) => Promise<void>;
|
||||
losslessOnly?: boolean;
|
||||
}
|
||||
|
||||
export default function ArtistDetailTopTracks({
|
||||
topSongs, marginTop, playTopSongWithContinuation, losslessOnly = false,
|
||||
topSongs, albums, marginTop, playTopSongWithContinuation, losslessOnly = false,
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
const currentTrack = usePlayerStore(s => s.currentTrack);
|
||||
@@ -92,9 +94,19 @@ export default function ArtistDetailTopTracks({
|
||||
? <Square size={9} fill="currentColor" strokeWidth={0} className="playlist-suggestion-preview-icon" />
|
||||
: <ChevronRight size={14} className="playlist-suggestion-preview-icon playlist-suggestion-preview-icon-play" />}
|
||||
</button>
|
||||
{song.coverArt && (
|
||||
<ArtistSuggestionTrackCover coverArt={song.coverArt} album={song.album} />
|
||||
)}
|
||||
{(() => {
|
||||
const albumRow = song.albumId
|
||||
? albums.find(a => a.id === song.albumId)
|
||||
: albums.find(a => a.name === song.album);
|
||||
const coverId = resolveArtistPageSongCoverArtId(song, albums);
|
||||
return coverId && song.albumId ? (
|
||||
<ArtistTopTrackCover
|
||||
albumId={song.albumId}
|
||||
coverArt={coverId}
|
||||
album={song.album}
|
||||
/>
|
||||
) : null;
|
||||
})()}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', minWidth: 0 }}>
|
||||
<div className="track-title">{song.title}</div>
|
||||
</div>
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import React from 'react';
|
||||
import { CoverArtImage } from '../../cover/CoverArtImage';
|
||||
import { COVER_DENSE_ARTIST_LIST_CSS_PX } from '../../cover/layoutSizes';
|
||||
|
||||
export default function ArtistSuggestionTrackCover({ coverArt, album }: { coverArt: string; album: string }) {
|
||||
return (
|
||||
<CoverArtImage
|
||||
coverArtId={coverArt}
|
||||
displayCssPx={COVER_DENSE_ARTIST_LIST_CSS_PX}
|
||||
surface="dense"
|
||||
alt={album}
|
||||
style={{ width: '32px', height: '32px', borderRadius: '4px', objectFit: 'cover', flexShrink: 0 }}
|
||||
onError={(e) => { (e.currentTarget as HTMLImageElement).style.display = 'none'; }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import React from 'react';
|
||||
import { AlbumCoverArtImage } from '../../cover/AlbumCoverArtImage';
|
||||
import { COVER_ARTIST_TOP_TRACK_CSS_PX } from '../../cover/layoutSizes';
|
||||
|
||||
export default function ArtistTopTrackCover({
|
||||
albumId,
|
||||
coverArt,
|
||||
album,
|
||||
}: {
|
||||
albumId: string;
|
||||
coverArt: string;
|
||||
album: string;
|
||||
}) {
|
||||
return (
|
||||
<AlbumCoverArtImage
|
||||
albumId={albumId}
|
||||
coverArt={coverArt}
|
||||
displayCssPx={COVER_ARTIST_TOP_TRACK_CSS_PX}
|
||||
surface="sparse"
|
||||
ensurePriority="high"
|
||||
alt={album}
|
||||
style={{ width: '32px', height: '32px', borderRadius: '4px', objectFit: 'cover', flexShrink: 0 }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import React from 'react';
|
||||
import type { SubsonicArtist } from '../../api/subsonicTypes';
|
||||
import { CoverArtImage } from '../../cover/CoverArtImage';
|
||||
import { coverArtIdFromArtist } from '../../cover/ids';
|
||||
import { ArtistCoverArtImage } from '../../cover/ArtistCoverArtImage';
|
||||
import {
|
||||
COVER_DENSE_ARTIST_LIST_CSS_PX,
|
||||
COVER_DENSE_GRID_MIN_CELL_CSS_PX,
|
||||
@@ -21,12 +20,12 @@ interface AvatarProps {
|
||||
*/
|
||||
export function ArtistCardAvatar({ artist, showImages }: AvatarProps) {
|
||||
const color = nameColor(artist.name);
|
||||
const coverId = coverArtIdFromArtist(artist);
|
||||
if (showImages && (artist.coverArt || artist.id)) {
|
||||
return (
|
||||
<div className="artist-card-avatar">
|
||||
<CoverArtImage
|
||||
coverArtId={coverId}
|
||||
<ArtistCoverArtImage
|
||||
artistId={artist.id}
|
||||
coverArt={artist.coverArt}
|
||||
displayCssPx={COVER_DENSE_GRID_MIN_CELL_CSS_PX}
|
||||
surface="dense"
|
||||
alt={artist.name}
|
||||
@@ -48,12 +47,12 @@ export function ArtistCardAvatar({ artist, showImages }: AvatarProps) {
|
||||
*/
|
||||
export function ArtistRowAvatar({ artist, showImages }: AvatarProps) {
|
||||
const color = nameColor(artist.name);
|
||||
const coverId = coverArtIdFromArtist(artist);
|
||||
if (showImages && (artist.coverArt || artist.id)) {
|
||||
return (
|
||||
<div className="artist-avatar">
|
||||
<CoverArtImage
|
||||
coverArtId={coverId}
|
||||
<ArtistCoverArtImage
|
||||
artistId={artist.id}
|
||||
coverArt={artist.coverArt}
|
||||
displayCssPx={COVER_DENSE_ARTIST_LIST_CSS_PX}
|
||||
surface="dense"
|
||||
alt={artist.name}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import { Cast, ChevronLeft, ChevronRight, Heart, X } from 'lucide-react';
|
||||
import type { InternetRadioStation } from '../../api/subsonicTypes';
|
||||
import { CoverArtImage } from '../../cover/CoverArtImage';
|
||||
import { albumCoverRef } from '../../cover/ref';
|
||||
import { coverArtIdFromRadio } from '../../cover/ids';
|
||||
import { COVER_DENSE_GRID_MIN_CELL_CSS_PX } from '../../cover/layoutSizes';
|
||||
|
||||
@@ -78,7 +79,7 @@ function RadioFavCard({ station: s, isActive, isPlaying, onPlay, onUnfavorite }:
|
||||
<div className="album-card-cover">
|
||||
{s.coverArt ? (
|
||||
<CoverArtImage
|
||||
coverArtId={coverArtIdFromRadio(s.id)}
|
||||
coverRef={albumCoverRef(coverArtIdFromRadio(s.id), coverArtIdFromRadio(s.id))}
|
||||
displayCssPx={COVER_DENSE_GRID_MIN_CELL_CSS_PX}
|
||||
surface="dense"
|
||||
alt={s.name}
|
||||
|
||||
@@ -2,6 +2,7 @@ import React, { useEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ChevronLeft, ChevronRight, Users } from 'lucide-react';
|
||||
import { CoverArtImage } from '../../cover/CoverArtImage';
|
||||
import { ArtistCoverArtImage } from '../../cover/ArtistCoverArtImage';
|
||||
import { COVER_DENSE_GRID_MIN_CELL_CSS_PX } from '../../cover/layoutSizes';
|
||||
|
||||
export interface TopFavoriteArtist {
|
||||
@@ -92,8 +93,9 @@ function TopFavoriteArtistCard({ artist, isSelected, onClick, songCountLabel }:
|
||||
>
|
||||
<div className="artist-card-avatar">
|
||||
{coverId ? (
|
||||
<CoverArtImage
|
||||
coverArtId={coverId}
|
||||
<ArtistCoverArtImage
|
||||
artistId={artist.id}
|
||||
coverArt={artist.coverArtId}
|
||||
displayCssPx={COVER_DENSE_GRID_MIN_CELL_CSS_PX}
|
||||
surface="dense"
|
||||
alt={artist.name}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { open } from '@tauri-apps/plugin-shell';
|
||||
import type { InternetRadioStation } from '../../api/subsonicTypes';
|
||||
import { useDragDrop, useDragSource } from '../../contexts/DragDropContext';
|
||||
import { CoverArtImage } from '../../cover/CoverArtImage';
|
||||
import { albumCoverRef } from '../../cover/ref';
|
||||
import { coverArtIdFromRadio } from '../../cover/ids';
|
||||
import { COVER_DENSE_GRID_MIN_CELL_CSS_PX } from '../../cover/layoutSizes';
|
||||
|
||||
@@ -87,7 +88,7 @@ export default function RadioCard({
|
||||
<div className="album-card-cover">
|
||||
{s.coverArt ? (
|
||||
<CoverArtImage
|
||||
coverArtId={coverArtIdFromRadio(s.id)}
|
||||
coverRef={albumCoverRef(coverArtIdFromRadio(s.id), coverArtIdFromRadio(s.id))}
|
||||
displayCssPx={COVER_DENSE_GRID_MIN_CELL_CSS_PX}
|
||||
surface="dense"
|
||||
alt={s.name}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import { Camera, Cast, Loader2, X } from 'lucide-react';
|
||||
import type { InternetRadioStation } from '../../api/subsonicTypes';
|
||||
import { CoverArtImage } from '../../cover/CoverArtImage';
|
||||
import { albumCoverRef } from '../../cover/ref';
|
||||
import { coverArtIdFromRadio } from '../../cover/ids';
|
||||
|
||||
interface RadioEditModalProps {
|
||||
@@ -92,7 +93,7 @@ export default function RadioEditModal({ station, onClose, onSave }: RadioEditMo
|
||||
<img src={coverPreview} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
|
||||
) : !coverRemoved && station?.coverArt ? (
|
||||
<CoverArtImage
|
||||
coverArtId={coverArtIdFromRadio(station.id)}
|
||||
coverRef={albumCoverRef(coverArtIdFromRadio(station.id), coverArtIdFromRadio(station.id))}
|
||||
displayCssPx={140}
|
||||
surface="sparse"
|
||||
alt=""
|
||||
|
||||
@@ -2,7 +2,7 @@ import React, { memo, useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Disc3, ExternalLink, Music } from 'lucide-react';
|
||||
import type { SubsonicAlbum } from '../../api/subsonicTypes';
|
||||
import { CoverArtImage } from '../../cover/CoverArtImage';
|
||||
import { AlbumCoverArtImage } from '../../cover/AlbumCoverArtImage';
|
||||
import { COVER_DENSE_RAIL_CELL_CSS_PX } from '../../cover/layoutSizes';
|
||||
|
||||
interface DiscographyCardProps {
|
||||
@@ -52,8 +52,9 @@ const DiscographyCard = memo(function DiscographyCard({ artistId, albums, curren
|
||||
<div className="np-dash-disc-cover">
|
||||
{a.coverArt
|
||||
? (
|
||||
<CoverArtImage
|
||||
coverArtId={a.coverArt}
|
||||
<AlbumCoverArtImage
|
||||
albumId={a.id}
|
||||
coverArt={a.coverArt}
|
||||
displayCssPx={COVER_DENSE_RAIL_CELL_CSS_PX}
|
||||
surface="dense"
|
||||
alt={a.name}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import React, { memo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Headphones, Heart, MicVocal, Music, Star } from 'lucide-react';
|
||||
import { CoverArtImage } from '../../cover/CoverArtImage';
|
||||
import type { CoverArtRef } from '../../cover/types';
|
||||
import type { LastfmArtistStats, LastfmTrackInfo } from '../../api/lastfm';
|
||||
import LastfmIcon from '../LastfmIcon';
|
||||
import { formatTrackTime } from '../../utils/format/formatDuration';
|
||||
@@ -19,7 +21,7 @@ interface HeroProps {
|
||||
lfmLoved: boolean;
|
||||
lfmLoveEnabled: boolean;
|
||||
activeLyricsTab: boolean;
|
||||
coverUrl: string;
|
||||
coverRef?: CoverArtRef;
|
||||
onNavigate: (path: string) => void;
|
||||
onToggleStar: () => void;
|
||||
onToggleLfmLove: () => void;
|
||||
@@ -40,7 +42,7 @@ function renderStars(rating?: number) {
|
||||
);
|
||||
}
|
||||
|
||||
const Hero = memo(function Hero({ track, genre, playCount, userRatingOverride, lfmTrack, lfmArtist, starred, lfmLoved, lfmLoveEnabled, activeLyricsTab, coverUrl, onNavigate, onToggleStar, onToggleLfmLove, onOpenLyrics }: HeroProps) {
|
||||
const Hero = memo(function Hero({ track, genre, playCount, userRatingOverride, lfmTrack, lfmArtist, starred, lfmLoved, lfmLoveEnabled, activeLyricsTab, coverRef, onNavigate, onToggleStar, onToggleLfmLove, onOpenLyrics }: HeroProps) {
|
||||
const { t } = useTranslation();
|
||||
const rating = userRatingOverride ?? track.userRating;
|
||||
const hiRes = (track.bitDepth ?? 0) > 16 || (track.samplingRate ?? 0) > 48000;
|
||||
@@ -49,9 +51,18 @@ const Hero = memo(function Hero({ track, genre, playCount, userRatingOverride, l
|
||||
return (
|
||||
<div className="np-dash-hero">
|
||||
<div className="np-dash-hero-cover">
|
||||
{coverUrl
|
||||
? <img src={coverUrl} alt="" className="np-cover" />
|
||||
: <div className="np-cover np-cover-fallback"><Music size={64} /></div>}
|
||||
{coverRef ? (
|
||||
<CoverArtImage
|
||||
className="np-cover"
|
||||
coverRef={coverRef}
|
||||
displayCssPx={280}
|
||||
surface="sparse"
|
||||
ensurePriority="high"
|
||||
alt=""
|
||||
/>
|
||||
) : (
|
||||
<div className="np-cover np-cover-fallback"><Music size={64} /></div>
|
||||
)}
|
||||
</div>
|
||||
<div className="np-dash-hero-body">
|
||||
<div className="np-dash-hero-title">{track.title}</div>
|
||||
@@ -160,4 +171,4 @@ const Hero = memo(function Hero({ track, genre, playCount, userRatingOverride, l
|
||||
);
|
||||
});
|
||||
|
||||
export default Hero;
|
||||
export default Hero;
|
||||
@@ -6,6 +6,9 @@ import type { PlayerState, Track } from '../../store/playerStoreTypes';
|
||||
import type { RadioMetadata } from '../../hooks/useRadioMetadata';
|
||||
import type { PreviewingTrack } from '../../store/previewStore';
|
||||
import { CoverArtImage } from '../../cover/CoverArtImage';
|
||||
import { albumCoverRef } from '../../cover/ref';
|
||||
import { useAlbumCoverRef } from '../../cover/useLibraryCoverRef';
|
||||
import { usePlaybackTrackCoverRef } from '../../cover/useLibraryCoverRef';
|
||||
import LastfmIcon from '../LastfmIcon';
|
||||
import MarqueeText from '../MarqueeText';
|
||||
import { OpenArtistRefInline } from '../OpenArtistRefInline';
|
||||
@@ -24,7 +27,6 @@ interface Props {
|
||||
radioMeta: RadioMetadata;
|
||||
radioCoverArtId?: string;
|
||||
coverArtId?: string;
|
||||
displayCoverArt: string | undefined;
|
||||
displayTitle: string;
|
||||
displayArtist: string;
|
||||
/** When set (OpenSubsonic `artists` on the playing track), render split links like album track rows. */
|
||||
@@ -45,13 +47,20 @@ interface Props {
|
||||
|
||||
export function PlayerTrackInfo({
|
||||
currentTrack, currentRadio, isRadio, radioMeta, radioCoverArtId,
|
||||
coverArtId, displayCoverArt, displayTitle, displayArtist, displayArtistRefs,
|
||||
coverArtId, displayTitle, displayArtist, displayArtistRefs,
|
||||
showPreviewMeta, previewingTrack, isStarred, toggleStar,
|
||||
lastfmSessionKey, lastfmLoved, toggleLastfmLove,
|
||||
userRatingOverrides, toggleFullscreen,
|
||||
navigate, openContextMenu, t,
|
||||
}: Props) {
|
||||
const showBufferingOverlay = usePlayerStore(s => s.isPlaybackBuffering);
|
||||
const playbackCoverRef = usePlaybackTrackCoverRef(
|
||||
showPreviewMeta ? null : currentTrack ?? undefined,
|
||||
);
|
||||
const previewCoverRef = useAlbumCoverRef(
|
||||
showPreviewMeta ? coverArtId : null,
|
||||
showPreviewMeta ? coverArtId : null,
|
||||
);
|
||||
const layoutItems = usePlayerBarLayoutStore(s => s.items);
|
||||
const isLayoutVisible = (id: PlayerBarLayoutItemId) =>
|
||||
layoutItems.find(i => i.id === id)?.visible !== false;
|
||||
@@ -64,10 +73,10 @@ export function PlayerTrackInfo({
|
||||
data-tooltip={!isRadio && !showPreviewMeta && currentTrack ? t('player.openFullscreen') : undefined}
|
||||
>
|
||||
{isRadio ? (
|
||||
radioCoverArtId ? (
|
||||
radioCoverArtId && currentRadio ? (
|
||||
<CoverArtImage
|
||||
className="player-album-art"
|
||||
coverArtId={radioCoverArtId}
|
||||
coverRef={albumCoverRef(radioCoverArtId, radioCoverArtId)}
|
||||
displayCssPx={128}
|
||||
surface="sparse"
|
||||
alt={currentRadio?.name ?? ''}
|
||||
@@ -77,13 +86,13 @@ export function PlayerTrackInfo({
|
||||
<Cast size={20} />
|
||||
</div>
|
||||
)
|
||||
) : coverArtId ? (
|
||||
) : !isRadio && (showPreviewMeta ? coverArtId : playbackCoverRef) ? (
|
||||
<CoverArtImage
|
||||
className="player-album-art"
|
||||
coverArtId={coverArtId}
|
||||
coverRef={showPreviewMeta ? previewCoverRef! : playbackCoverRef!}
|
||||
displayCssPx={128}
|
||||
surface="sparse"
|
||||
serverScope={showPreviewMeta ? { kind: 'active' } : { kind: 'playback' }}
|
||||
ensurePriority="high"
|
||||
alt={showPreviewMeta ? `${previewingTrack!.title} Cover` : `${currentTrack?.album ?? ''} Cover`}
|
||||
/>
|
||||
) : (
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Camera, Loader2, X } from 'lucide-react';
|
||||
import type { SubsonicPlaylist } from '../../api/subsonicTypes';
|
||||
import type { CoverArtId } from '../../cover/types';
|
||||
import { CoverArtImage } from '../../cover/CoverArtImage';
|
||||
import { AlbumCoverArtImage } from '../../cover/AlbumCoverArtImage';
|
||||
import { PLAYLIST_MAIN_COVER_CSS_PX } from '../../hooks/usePlaylistCovers';
|
||||
import { PlaylistSmartCoverCell } from '../playlists/PlaylistCoverImages';
|
||||
|
||||
@@ -79,8 +80,9 @@ export default function PlaylistEditModal({
|
||||
{coverPreview ? (
|
||||
<img src={coverPreview} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
|
||||
) : !coverRemoved && customCoverId ? (
|
||||
<CoverArtImage
|
||||
coverArtId={customCoverId}
|
||||
<AlbumCoverArtImage
|
||||
albumId={customCoverId}
|
||||
coverArt={customCoverId}
|
||||
displayCssPx={PLAYLIST_MAIN_COVER_CSS_PX}
|
||||
surface="dense"
|
||||
alt=""
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
} from '../../utils/componentHelpers/playlistDetailHelpers';
|
||||
import type { CoverArtId } from '../../cover/types';
|
||||
import { CoverArtImage } from '../../cover/CoverArtImage';
|
||||
import { AlbumCoverArtImage } from '../../cover/AlbumCoverArtImage';
|
||||
import { PLAYLIST_MAIN_COVER_CSS_PX } from '../../hooks/usePlaylistCovers';
|
||||
import { PlaylistSmartCoverCell } from '../playlists/PlaylistCoverImages';
|
||||
|
||||
@@ -87,8 +88,9 @@ export default function PlaylistHero({
|
||||
onClick={() => setEditingMeta(true)}
|
||||
>
|
||||
{customCoverId ? (
|
||||
<CoverArtImage
|
||||
coverArtId={customCoverId}
|
||||
<AlbumCoverArtImage
|
||||
albumId={customCoverId}
|
||||
coverArt={customCoverId}
|
||||
displayCssPx={PLAYLIST_MAIN_COVER_CSS_PX}
|
||||
surface="dense"
|
||||
alt=""
|
||||
|
||||
@@ -5,14 +5,15 @@ import type { SubsonicSong } from '../../api/subsonicTypes';
|
||||
import { usePlayerStore } from '../../store/playerStore';
|
||||
import { songToTrack } from '../../utils/playback/songToTrack';
|
||||
import { formatTrackTime } from '../../utils/format/formatDuration';
|
||||
import { CoverArtImage } from '../../cover/CoverArtImage';
|
||||
import { AlbumCoverArtImage } from '../../cover/AlbumCoverArtImage';
|
||||
import { COVER_DENSE_SEARCH_CSS_PX } from '../../cover/layoutSizes';
|
||||
import { AddToPlaylistSubmenu } from '../ContextMenu';
|
||||
|
||||
function PlaylistSearchResultThumb({ coverArt }: { coverArt: string }) {
|
||||
function PlaylistSearchResultThumb({ albumId, coverArt }: { albumId: string; coverArt: string }) {
|
||||
return (
|
||||
<CoverArtImage
|
||||
coverArtId={coverArt}
|
||||
<AlbumCoverArtImage
|
||||
albumId={albumId}
|
||||
coverArt={coverArt}
|
||||
displayCssPx={COVER_DENSE_SEARCH_CSS_PX}
|
||||
surface="dense"
|
||||
alt=""
|
||||
@@ -133,7 +134,7 @@ export default function PlaylistSongSearchPanel({
|
||||
return next;
|
||||
})}
|
||||
/>
|
||||
<PlaylistSearchResultThumb coverArt={song.coverArt ?? ''} />
|
||||
<PlaylistSearchResultThumb albumId={song.albumId} coverArt={song.coverArt ?? ''} />
|
||||
<div className="playlist-search-info">
|
||||
<span className="playlist-search-title">{song.title}</span>
|
||||
<span className="playlist-search-artist">{song.artist} · <span className="playlist-search-album">{song.album}</span></span>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React from 'react';
|
||||
import { CoverArtImage } from '../../cover/CoverArtImage';
|
||||
import { AlbumCoverArtImage } from '../../cover/AlbumCoverArtImage';
|
||||
|
||||
/** 2×2 collage cell — half of clamp(120px, 15vw, 200px) playlist hero grid. */
|
||||
const PLAYLIST_QUAD_CELL_CSS_PX = 100;
|
||||
@@ -8,8 +8,9 @@ const PLAYLIST_MAIN_COVER_CSS_PX = 200;
|
||||
|
||||
export function PlaylistSmartCoverCell({ coverId }: { coverId: string }) {
|
||||
return (
|
||||
<CoverArtImage
|
||||
coverArtId={coverId}
|
||||
<AlbumCoverArtImage
|
||||
albumId={coverId}
|
||||
coverArt={coverId}
|
||||
displayCssPx={PLAYLIST_QUAD_CELL_CSS_PX}
|
||||
surface="dense"
|
||||
className="playlist-cover-cell"
|
||||
@@ -20,8 +21,9 @@ export function PlaylistSmartCoverCell({ coverId }: { coverId: string }) {
|
||||
|
||||
export function PlaylistCardMainCover({ coverArt, alt }: { coverArt: string; alt: string }) {
|
||||
return (
|
||||
<CoverArtImage
|
||||
coverArtId={coverArt}
|
||||
<AlbumCoverArtImage
|
||||
albumId={coverArt}
|
||||
coverArt={coverArt}
|
||||
displayCssPx={PLAYLIST_MAIN_COVER_CSS_PX}
|
||||
surface="dense"
|
||||
alt={alt}
|
||||
|
||||
@@ -14,11 +14,12 @@ import { formatQueueBpmTech, formatQueueMoodLabels } from '../../utils/library/t
|
||||
import { useQueueTrackEnrichment } from '../../hooks/useQueueTrackEnrichment';
|
||||
import { QueueLufsTargetMenu } from './QueueLufsTargetMenu';
|
||||
import { PlaybackBufferingOverlay } from '../playback/PlaybackBufferingOverlay';
|
||||
import { CoverArtImage } from '../../cover/CoverArtImage';
|
||||
import { usePlaybackTrackCoverRef } from '../../cover/useLibraryCoverRef';
|
||||
import { usePlayerStore } from '../../store/playerStore';
|
||||
|
||||
interface Props {
|
||||
currentTrack: Track;
|
||||
currentCoverSrc: string;
|
||||
userRatingOverrides: Record<string, number>;
|
||||
orbitAttributionLabel: (trackId: string) => string | null;
|
||||
navigate: (to: string) => void | Promise<void>;
|
||||
@@ -42,7 +43,7 @@ interface Props {
|
||||
}
|
||||
|
||||
export function QueueCurrentTrack({
|
||||
currentTrack, currentCoverSrc, userRatingOverrides, orbitAttributionLabel,
|
||||
currentTrack, userRatingOverrides, orbitAttributionLabel,
|
||||
navigate, playbackSource, normalizationEngine, normalizationEngineLive,
|
||||
normalizationNowDb, normalizationTargetLufs, authLoudnessTargetLufs,
|
||||
loudnessPreAnalysisAttenuationDb, expandReplayGain, setExpandReplayGain,
|
||||
@@ -50,6 +51,7 @@ export function QueueCurrentTrack({
|
||||
lufsTgtBtnRef, lufsTgtMenuRef, lufsTgtPopStyle, t,
|
||||
}: Props) {
|
||||
const showBufferingOverlay = usePlayerStore(s => s.isPlaybackBuffering);
|
||||
const coverRef = usePlaybackTrackCoverRef(currentTrack);
|
||||
const enrichment = useQueueTrackEnrichment(currentTrack.id);
|
||||
const bpmTech = formatQueueBpmTech(enrichment, t);
|
||||
const moodLine = formatQueueMoodLabels(enrichment.moodLabels, t);
|
||||
@@ -201,8 +203,15 @@ export function QueueCurrentTrack({
|
||||
})()}
|
||||
<div className="queue-current-track-body">
|
||||
<div className={`queue-current-cover${showBufferingOverlay ? ' playback-buffering' : ''}`}>
|
||||
{currentTrack.coverArt && currentCoverSrc ? (
|
||||
<img src={currentCoverSrc} alt="" loading="eager" />
|
||||
{coverRef ? (
|
||||
<CoverArtImage
|
||||
coverRef={coverRef}
|
||||
displayCssPx={128}
|
||||
surface="sparse"
|
||||
ensurePriority="high"
|
||||
alt=""
|
||||
loading="eager"
|
||||
/>
|
||||
) : (
|
||||
<div className="fallback"><Music size={32} /></div>
|
||||
)}
|
||||
|
||||
@@ -11,7 +11,8 @@ import OverlayScrollArea from '../OverlayScrollArea';
|
||||
import { usePlayerStore } from '../../store/playerStore';
|
||||
import { CoverArtImage } from '../../cover/CoverArtImage';
|
||||
import { COVER_DENSE_SEARCH_CSS_PX } from '../../cover/layoutSizes';
|
||||
import type { CoverServerScope } from '../../cover/types';
|
||||
import { COVER_SCOPE_ACTIVE, type CoverServerScope } from '../../cover/types';
|
||||
import { AlbumCoverArtImage } from '../../cover/AlbumCoverArtImage';
|
||||
|
||||
type ShareQueuePreviewModalProps = {
|
||||
open: boolean;
|
||||
@@ -36,7 +37,7 @@ function shareCoverServerScope(coverServer?: ServerProfile | null): CoverServerS
|
||||
password: coverServer.password,
|
||||
};
|
||||
}
|
||||
return { kind: 'active' };
|
||||
return COVER_SCOPE_ACTIVE;
|
||||
}
|
||||
|
||||
function QueuePreviewTrackRow({
|
||||
@@ -51,11 +52,12 @@ function QueuePreviewTrackRow({
|
||||
return (
|
||||
<li className="share-queue-preview-track">
|
||||
{song.coverArt ? (
|
||||
<CoverArtImage
|
||||
coverArtId={coverId}
|
||||
<AlbumCoverArtImage
|
||||
albumId={song.albumId ?? coverId}
|
||||
coverArt={song.coverArt}
|
||||
serverScope={shareCoverServerScope(coverServer)}
|
||||
displayCssPx={COVER_DENSE_SEARCH_CSS_PX}
|
||||
surface="dense"
|
||||
serverScope={shareCoverServerScope(coverServer)}
|
||||
className="share-queue-preview-track__thumb"
|
||||
alt=""
|
||||
/>
|
||||
|
||||
@@ -9,10 +9,10 @@ import { activateShareSearchServer } from '../../utils/share/enqueueShareSearchP
|
||||
import { sharePayloadTotal, type ShareSearchMatch } from '../../utils/share/shareSearch';
|
||||
import type { ShareSearchPreviewState } from '../../hooks/useShareSearchPreview';
|
||||
import { FETCH_QUEUE_BIAS_SEARCH_ARTIST_OVER_ALBUM } from '../CachedImage';
|
||||
import { CoverArtImage } from '../../cover/CoverArtImage';
|
||||
import { AlbumCoverArtImage } from '../../cover/AlbumCoverArtImage';
|
||||
import { ArtistCoverArtImage } from '../../cover/ArtistCoverArtImage';
|
||||
import { COVER_DENSE_SEARCH_CSS_PX } from '../../cover/layoutSizes';
|
||||
import { coverArtIdFromArtist } from '../../cover/ids';
|
||||
import type { CoverServerScope } from '../../cover/types';
|
||||
import { COVER_SCOPE_ACTIVE, type CoverServerScope } from '../../cover/types';
|
||||
import { useShareQueuePreview } from '../../hooks/useShareQueuePreview';
|
||||
import ShareQueuePreviewModal from './ShareQueuePreviewModal';
|
||||
|
||||
@@ -42,25 +42,28 @@ function shareCoverServerScope(coverServer?: ServerProfile | null): CoverServerS
|
||||
password: coverServer.password,
|
||||
};
|
||||
}
|
||||
return { kind: 'active' };
|
||||
return COVER_SCOPE_ACTIVE;
|
||||
}
|
||||
|
||||
function ShareAlbumThumb({
|
||||
albumId,
|
||||
coverArt,
|
||||
displayCssPx,
|
||||
coverServer,
|
||||
}: {
|
||||
albumId: string;
|
||||
coverArt: string;
|
||||
displayCssPx: number;
|
||||
coverServer?: ServerProfile | null;
|
||||
}) {
|
||||
const cls = displayCssPx >= 64 ? 'mobile-search-thumb' : 'search-result-thumb';
|
||||
return (
|
||||
<CoverArtImage
|
||||
coverArtId={coverArt}
|
||||
<AlbumCoverArtImage
|
||||
albumId={albumId}
|
||||
coverArt={coverArt}
|
||||
serverScope={shareCoverServerScope(coverServer)}
|
||||
displayCssPx={displayCssPx}
|
||||
surface="dense"
|
||||
serverScope={shareCoverServerScope(coverServer)}
|
||||
className={cls}
|
||||
alt=""
|
||||
/>
|
||||
@@ -77,8 +80,7 @@ function ShareArtistThumb({
|
||||
coverServer?: ServerProfile | null;
|
||||
}) {
|
||||
const [failed, setFailed] = useState(false);
|
||||
const coverId = coverArtIdFromArtist(artist);
|
||||
useEffect(() => { setFailed(false); }, [coverId]);
|
||||
useEffect(() => { setFailed(false); }, [artist.id, artist.coverArt]);
|
||||
|
||||
if (failed) {
|
||||
if (displayCssPx >= 64) {
|
||||
@@ -100,11 +102,12 @@ function ShareArtistThumb({
|
||||
? 'mobile-search-thumb mobile-search-thumb--artist-round'
|
||||
: 'search-result-thumb';
|
||||
return (
|
||||
<CoverArtImage
|
||||
coverArtId={coverId}
|
||||
<ArtistCoverArtImage
|
||||
artistId={artist.id}
|
||||
coverArt={artist.coverArt}
|
||||
serverScope={shareCoverServerScope(coverServer)}
|
||||
displayCssPx={displayCssPx}
|
||||
surface="dense"
|
||||
serverScope={shareCoverServerScope(coverServer)}
|
||||
className={cls}
|
||||
alt=""
|
||||
loading="eager"
|
||||
@@ -319,7 +322,7 @@ export default function ShareSearchResults(props: ShareSearchResultsProps) {
|
||||
aria-selected={desktop ? activeIndex === 0 : undefined}
|
||||
>
|
||||
{shareAlbum.coverArt ? (
|
||||
<ShareAlbumThumb coverArt={shareAlbum.coverArt} displayCssPx={thumbDisplayCssPx} coverServer={shareCoverServer} />
|
||||
<ShareAlbumThumb albumId={shareAlbum.id} coverArt={shareAlbum.coverArt} displayCssPx={thumbDisplayCssPx} coverServer={shareCoverServer} />
|
||||
) : (
|
||||
<StaticIcon className={iconCls}><Disc3 size={desktop ? 14 : 20} /></StaticIcon>
|
||||
)}
|
||||
@@ -370,7 +373,7 @@ export default function ShareSearchResults(props: ShareSearchResultsProps) {
|
||||
aria-selected={desktop ? activeIndex === 0 : undefined}
|
||||
>
|
||||
{shareTrackSong.coverArt ? (
|
||||
<ShareAlbumThumb coverArt={shareTrackSong.coverArt} displayCssPx={thumbDisplayCssPx} coverServer={shareCoverServer} />
|
||||
<ShareAlbumThumb albumId={shareTrackSong.albumId} coverArt={shareTrackSong.coverArt} displayCssPx={thumbDisplayCssPx} coverServer={shareCoverServer} />
|
||||
) : (
|
||||
<StaticIcon className={iconCls}><Music size={desktop ? 14 : 20} /></StaticIcon>
|
||||
)}
|
||||
|
||||
@@ -134,6 +134,7 @@ const CONTRIBUTOR_ENTRIES = [
|
||||
'Lossless: local index browse, Advanced Search and All Albums filters, artist/album drill-down mode, conserved sidebar page (PR #871)',
|
||||
'Albums: combined browse filters (genre/year/favorites/lossless/compilations), session restore from album detail, favorites reconcile via local index (PR #876)',
|
||||
'Artist detail: sort albums by year (newest/oldest) in the Albums section (PR #877)',
|
||||
'Cover art: Windows thumbnails, tier fallback, PNG decode, Subsonic coverArt id resolution (PR #878)',
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { CoverArtImage, type CoverArtImageProps } from './CoverArtImage';
|
||||
import { useAlbumCoverRef } from './useLibraryCoverRef';
|
||||
import { COVER_SCOPE_ACTIVE, type CoverServerScope } from './types';
|
||||
|
||||
export type AlbumCoverArtImageProps = Omit<CoverArtImageProps, 'coverRef'> & {
|
||||
albumId: string;
|
||||
coverArt?: string | null;
|
||||
serverScope?: CoverServerScope;
|
||||
/** Live search: use API `coverArt` ids only (avoids library IPC per row). */
|
||||
libraryResolve?: boolean;
|
||||
};
|
||||
|
||||
export function AlbumCoverArtImage({
|
||||
albumId,
|
||||
coverArt,
|
||||
serverScope,
|
||||
libraryResolve = false,
|
||||
...rest
|
||||
}: AlbumCoverArtImageProps) {
|
||||
const coverRef = useAlbumCoverRef(
|
||||
albumId,
|
||||
coverArt,
|
||||
serverScope ?? COVER_SCOPE_ACTIVE,
|
||||
{ libraryResolve },
|
||||
);
|
||||
if (!coverRef) return null;
|
||||
return <CoverArtImage coverRef={coverRef} {...rest} />;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { CoverArtImage, type CoverArtImageProps } from './CoverArtImage';
|
||||
import { useArtistCoverRef } from './useLibraryCoverRef';
|
||||
import { COVER_SCOPE_ACTIVE, type CoverServerScope } from './types';
|
||||
|
||||
export type ArtistCoverArtImageProps = Omit<CoverArtImageProps, 'coverRef'> & {
|
||||
artistId: string;
|
||||
coverArt?: string | null;
|
||||
serverScope?: CoverServerScope;
|
||||
libraryResolve?: boolean;
|
||||
};
|
||||
|
||||
export function ArtistCoverArtImage({
|
||||
artistId,
|
||||
coverArt,
|
||||
serverScope,
|
||||
libraryResolve = false,
|
||||
...rest
|
||||
}: ArtistCoverArtImageProps) {
|
||||
const coverRef = useArtistCoverRef(
|
||||
artistId,
|
||||
coverArt,
|
||||
serverScope ?? COVER_SCOPE_ACTIVE,
|
||||
{ libraryResolve },
|
||||
);
|
||||
if (!coverRef) return null;
|
||||
return <CoverArtImage coverRef={coverRef} {...rest} />;
|
||||
}
|
||||
+31
-16
@@ -1,20 +1,19 @@
|
||||
import type { ImgHTMLAttributes } from 'react';
|
||||
import type React from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { DEFAULT_CACHED_IMAGE_PREPARE_MARGIN } from '../components/CachedImage';
|
||||
import { resolveIntersectionScrollRoot } from '../utils/ui/resolveIntersectionScrollRoot';
|
||||
import { coverEnsureBump } from './ensureQueue';
|
||||
import { coverPrefetchBumpPriority } from './prefetchRegistry';
|
||||
import { coverArtRef } from './ref';
|
||||
import { coverStorageKey } from './storageKeys';
|
||||
import { coverStorageKeyFromRef } from './storageKeys';
|
||||
import { resolveCoverDisplayTier } from './tiers';
|
||||
import { coverImgSrc } from './imgSrc';
|
||||
import { useCoverArt } from './useCoverArt';
|
||||
import type { CoverArtId, CoverPrefetchPriority, CoverServerScope, CoverSurfaceKind } from './types';
|
||||
import type { CoverArtRef, CoverPrefetchPriority, CoverSurfaceKind } from './types';
|
||||
|
||||
export type CoverArtImageProps = {
|
||||
coverArtId: CoverArtId | null | undefined;
|
||||
coverRef: CoverArtRef;
|
||||
displayCssPx: number;
|
||||
serverScope?: CoverServerScope;
|
||||
surface?: CoverSurfaceKind;
|
||||
fullRes?: boolean;
|
||||
className?: string;
|
||||
@@ -22,14 +21,12 @@ export type CoverArtImageProps = {
|
||||
fetchQueueBias?: number;
|
||||
observeRootMargin?: string;
|
||||
observeScrollRootId?: string;
|
||||
/** Initial ensure tier — use `high` for hero / above-the-fold cells. */
|
||||
ensurePriority?: CoverPrefetchPriority;
|
||||
} & Omit<ImgHTMLAttributes<HTMLImageElement>, 'src'>;
|
||||
|
||||
export function CoverArtImage({
|
||||
coverArtId,
|
||||
coverRef,
|
||||
displayCssPx,
|
||||
serverScope,
|
||||
surface,
|
||||
fullRes,
|
||||
className,
|
||||
@@ -41,34 +38,37 @@ export function CoverArtImage({
|
||||
onError: restOnError,
|
||||
...rest
|
||||
}: CoverArtImageProps) {
|
||||
const scope = serverScope ?? { kind: 'active' };
|
||||
const [ensurePriority, setEnsurePriority] = useState<CoverPrefetchPriority>(
|
||||
ensurePriorityProp ?? 'middle',
|
||||
);
|
||||
const imgRef = useRef<HTMLImageElement>(null);
|
||||
const [imgLoadFailed, setImgLoadFailed] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (ensurePriorityProp) setEnsurePriority(ensurePriorityProp);
|
||||
}, [ensurePriorityProp]);
|
||||
|
||||
useEffect(() => {
|
||||
setImgLoadFailed(false);
|
||||
}, [coverRef.cacheEntityId, coverRef.cacheKind, coverRef.fetchCoverArtId, displayCssPx, surface, fullRes]);
|
||||
|
||||
useEffect(() => {
|
||||
const el = imgRef.current;
|
||||
if (!el || !coverArtId) return;
|
||||
if (!el) return;
|
||||
|
||||
const root =
|
||||
(observeScrollRootId
|
||||
? (document.getElementById(observeScrollRootId) as Element | null)
|
||||
: null) ?? resolveIntersectionScrollRoot(el);
|
||||
|
||||
const ref = coverArtRef(coverArtId, scope);
|
||||
const tier = resolveCoverDisplayTier(displayCssPx, { surface, fullRes });
|
||||
const storageKey = coverStorageKey(scope, coverArtId, tier);
|
||||
const storageKey = coverStorageKeyFromRef(coverRef, tier);
|
||||
const observer = new IntersectionObserver(
|
||||
entries => {
|
||||
for (const entry of entries) {
|
||||
if (entry.isIntersecting) {
|
||||
setEnsurePriority('high');
|
||||
coverPrefetchBumpPriority(ref, 'high');
|
||||
coverPrefetchBumpPriority(coverRef, 'high');
|
||||
coverEnsureBump(storageKey, 'high');
|
||||
}
|
||||
}
|
||||
@@ -81,10 +81,9 @@ export function CoverArtImage({
|
||||
);
|
||||
observer.observe(el);
|
||||
return () => observer.disconnect();
|
||||
}, [coverArtId, scope, displayCssPx, surface, fullRes, observeRootMargin, observeScrollRootId]);
|
||||
}, [coverRef, displayCssPx, surface, fullRes, observeRootMargin, observeScrollRootId]);
|
||||
|
||||
const { src, provisional, onImgError } = useCoverArt(coverArtId, displayCssPx, {
|
||||
serverScope: scope,
|
||||
const { src, provisional, onImgError } = useCoverArt(coverRef, displayCssPx, {
|
||||
surface,
|
||||
fullRes,
|
||||
ensurePriority,
|
||||
@@ -93,6 +92,21 @@ export function CoverArtImage({
|
||||
|
||||
const imgSrc = coverImgSrc(src);
|
||||
|
||||
if (!imgSrc || imgLoadFailed) {
|
||||
return (
|
||||
<div
|
||||
ref={imgRef as React.RefObject<HTMLDivElement | null>}
|
||||
className={className}
|
||||
data-cover-provisional="true"
|
||||
data-observe-root-margin={observeRootMargin}
|
||||
data-observe-scroll-root={observeScrollRootId}
|
||||
role="img"
|
||||
aria-label={alt ?? ''}
|
||||
{...(rest as React.HTMLAttributes<HTMLDivElement>)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<img
|
||||
ref={imgRef}
|
||||
@@ -104,6 +118,7 @@ export function CoverArtImage({
|
||||
data-observe-scroll-root={observeScrollRootId}
|
||||
{...rest}
|
||||
onError={e => {
|
||||
setImgLoadFailed(true);
|
||||
onImgError?.();
|
||||
restOnError?.(e);
|
||||
}}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { SubsonicSong } from '../api/subsonicTypes';
|
||||
import { CoverArtImage, type CoverArtImageProps } from './CoverArtImage';
|
||||
import { useTrackCoverRef } from './useLibraryCoverRef';
|
||||
import { COVER_SCOPE_ACTIVE, type CoverServerScope } from './types';
|
||||
|
||||
export type TrackCoverArtImageProps = Omit<CoverArtImageProps, 'coverRef'> & {
|
||||
song: Pick<SubsonicSong, 'id' | 'albumId' | 'coverArt' | 'discNumber'>;
|
||||
serverScope?: CoverServerScope;
|
||||
/** Default false for browse rails; true for queue/player rows needing per-disc art. */
|
||||
libraryResolve?: boolean;
|
||||
};
|
||||
|
||||
export function TrackCoverArtImage({
|
||||
song,
|
||||
serverScope,
|
||||
libraryResolve = false,
|
||||
...rest
|
||||
}: TrackCoverArtImageProps) {
|
||||
const coverRef = useTrackCoverRef(song, serverScope ?? COVER_SCOPE_ACTIVE, { libraryResolve });
|
||||
if (!coverRef) return null;
|
||||
return <CoverArtImage coverRef={coverRef} {...rest} />;
|
||||
}
|
||||
@@ -71,11 +71,10 @@ export function ArtistHeroCover({
|
||||
);
|
||||
}
|
||||
|
||||
if (coverFallback?.coverArtId) {
|
||||
if (coverFallback?.fetchCoverArtId) {
|
||||
return (
|
||||
<CoverArtImage
|
||||
coverArtId={coverFallback.coverArtId}
|
||||
serverScope={coverFallback.serverScope}
|
||||
coverRef={coverFallback}
|
||||
displayCssPx={displayCssPx}
|
||||
surface={surface}
|
||||
className={className}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../api/coverCache', () => ({
|
||||
libraryCoverBackfillConfigure: vi.fn(async () => {}),
|
||||
libraryCoverBackfillSetUiPriority: vi.fn(async () => {}),
|
||||
}));
|
||||
|
||||
import { libraryCoverBackfillSetUiPriority } from '../api/coverCache';
|
||||
import {
|
||||
__test_resetCoverTraffic,
|
||||
coverTrafficBackgroundPaused,
|
||||
coverTrafficBeginNavigation,
|
||||
coverTrafficEndNavigation,
|
||||
} from './coverTraffic';
|
||||
|
||||
describe('coverTraffic navigation hold', () => {
|
||||
beforeEach(() => {
|
||||
__test_resetCoverTraffic();
|
||||
vi.mocked(libraryCoverBackfillSetUiPriority).mockClear();
|
||||
});
|
||||
|
||||
it('route effect cleanup ends navigation hold (does not leak begin)', () => {
|
||||
coverTrafficBeginNavigation();
|
||||
coverTrafficEndNavigation();
|
||||
expect(coverTrafficBackgroundPaused()).toBe(false);
|
||||
|
||||
coverTrafficBeginNavigation();
|
||||
coverTrafficEndNavigation();
|
||||
expect(coverTrafficBackgroundPaused()).toBe(false);
|
||||
});
|
||||
|
||||
it('simulates useCoverNavigationPriority cleanup on pathname change', () => {
|
||||
coverTrafficBeginNavigation();
|
||||
coverTrafficEndNavigation();
|
||||
expect(coverTrafficBackgroundPaused()).toBe(false);
|
||||
|
||||
coverTrafficBeginNavigation();
|
||||
coverTrafficEndNavigation();
|
||||
coverTrafficEndNavigation();
|
||||
expect(coverTrafficBackgroundPaused()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -85,3 +85,13 @@ function scheduleNavigationResume(): void {
|
||||
syncBackfillUiPriority();
|
||||
}, NAVIGATION_QUIET_MS);
|
||||
}
|
||||
|
||||
/** Test-only — reset module hold state between cases. */
|
||||
export function __test_resetCoverTraffic(): void {
|
||||
navigationHoldDepth = 0;
|
||||
serverSwitchHold = false;
|
||||
if (resumeTimer) clearTimeout(resumeTimer);
|
||||
if (serverSwitchEndTimer) clearTimeout(serverSwitchEndTimer);
|
||||
resumeTimer = null;
|
||||
serverSwitchEndTimer = null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('@tauri-apps/api/core', () => ({
|
||||
isTauri: vi.fn(() => true),
|
||||
convertFileSrc: vi.fn(),
|
||||
}));
|
||||
|
||||
import { convertFileSrc } from '@tauri-apps/api/core';
|
||||
import { clearAllDiskSrcCache, coverDiskUrl, getDiskSrc, rememberDiskSrc } from './diskSrcCache';
|
||||
|
||||
describe('coverDiskUrl', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(convertFileSrc).mockReset();
|
||||
});
|
||||
|
||||
it('rejects raw Windows path when convertFileSrc returns passthrough', () => {
|
||||
const fsPath =
|
||||
'C:\\Users\\me\\AppData\\Roaming\\dev.psysonic.player\\cover-cache\\srv\\al-1\\128.webp';
|
||||
vi.mocked(convertFileSrc).mockReturnValue(fsPath);
|
||||
expect(coverDiskUrl(fsPath)).toBe('');
|
||||
});
|
||||
|
||||
it('accepts asset.localhost URLs from convertFileSrc', () => {
|
||||
const fsPath = 'C:\\cache\\cover-cache\\srv\\al-1\\128.webp';
|
||||
vi.mocked(convertFileSrc).mockReturnValue('https://asset.localhost/C%3A%2Fcache%2F128.webp');
|
||||
expect(coverDiskUrl(fsPath)).toBe('https://asset.localhost/C%3A%2Fcache%2F128.webp');
|
||||
});
|
||||
|
||||
it('normalizes Windows backslashes before convertFileSrc', () => {
|
||||
const fsPath = 'C:\\Users\\me\\cover-cache\\al-1\\128.webp';
|
||||
vi.mocked(convertFileSrc).mockImplementation((p: string) =>
|
||||
`https://asset.localhost/${encodeURIComponent(p)}`,
|
||||
);
|
||||
const url = coverDiskUrl(fsPath);
|
||||
expect(convertFileSrc).toHaveBeenCalledWith('C:/Users/me/cover-cache/al-1/128.webp');
|
||||
expect(url).toContain('asset.localhost');
|
||||
});
|
||||
|
||||
it('accepts asset: protocol URLs from convertFileSrc', () => {
|
||||
const fsPath = '/home/u/.local/share/dev.psysonic.player/cover-cache/srv/al-1/128.webp';
|
||||
vi.mocked(convertFileSrc).mockReturnValue('asset://localhost/home/u/.../128.webp');
|
||||
expect(coverDiskUrl(fsPath)).toBe('asset://localhost/home/u/.../128.webp');
|
||||
});
|
||||
});
|
||||
|
||||
describe('rememberDiskSrc', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(convertFileSrc).mockReset();
|
||||
clearAllDiskSrcCache();
|
||||
});
|
||||
|
||||
it('does not cache when coverDiskUrl rejects the path', () => {
|
||||
const fsPath = 'C:\\bad\\128.webp';
|
||||
vi.mocked(convertFileSrc).mockReturnValue(fsPath);
|
||||
expect(rememberDiskSrc('srv:cover:al-1:128', fsPath)).toBe('');
|
||||
expect(getDiskSrc('srv:cover:al-1:128')).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,6 @@
|
||||
import { convertFileSrc, isTauri } from '@tauri-apps/api/core';
|
||||
import { coverIndexKeyFromScope } from './storageKeys';
|
||||
import type { CoverServerScope } from './types';
|
||||
|
||||
/** Stable asset URLs for disk `.webp` tiers — survives route unmount. */
|
||||
const diskSrcByStorageKey = new Map<string, string>();
|
||||
@@ -27,23 +29,60 @@ export function getDiskSrcCacheGeneration(): number {
|
||||
return cacheGeneration;
|
||||
}
|
||||
|
||||
function isAssetProtocolUrl(url: string): boolean {
|
||||
return url.startsWith('asset:') || /^https?:\/\/asset\.localhost/i.test(url);
|
||||
}
|
||||
|
||||
/** Windows: forward slashes before `convertFileSrc` (tauri#7970). */
|
||||
function normalizePathForConvert(fsPath: string): string {
|
||||
if (/^[a-zA-Z]:[\\/]/.test(fsPath)) {
|
||||
return fsPath.replace(/\\/g, '/');
|
||||
}
|
||||
return fsPath;
|
||||
}
|
||||
|
||||
/** True when `convertFileSrc` failed and returned the filesystem path unchanged. */
|
||||
function isRawFsPath(url: string, fsPath: string): boolean {
|
||||
return url === fsPath || (url.startsWith('/') && fsPath.startsWith('/'));
|
||||
if (url === fsPath) return true;
|
||||
if (url.startsWith('/') && fsPath.startsWith('/')) return true;
|
||||
if (/^[a-zA-Z]:[\\/]/.test(fsPath)) {
|
||||
const norm = fsPath.replace(/\\/g, '/');
|
||||
const urlNorm = url.replace(/\\/g, '/');
|
||||
// `endsWith(norm)`: convertFileSrc passthrough; `norm.endsWith(urlNorm)`: partial URL match.
|
||||
if (urlNorm === norm || urlNorm.endsWith(norm) || norm.endsWith(urlNorm)) {
|
||||
return !isAssetProtocolUrl(url);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn a Rust disk path into a webview-loadable URL.
|
||||
* Returns empty when not in Tauri or path is outside asset scope (never put raw paths in `<img src>`).
|
||||
*/
|
||||
function tryCoverDiskUrl(fsPath: string): string {
|
||||
const paths = fsPath.includes('\\')
|
||||
? [normalizePathForConvert(fsPath), fsPath]
|
||||
: [fsPath, normalizePathForConvert(fsPath)];
|
||||
const seen = new Set<string>();
|
||||
for (const p of paths) {
|
||||
if (!p || seen.has(p)) continue;
|
||||
seen.add(p);
|
||||
const src = convertFileSrc(p);
|
||||
if (!src || isRawFsPath(src, p) || isRawFsPath(src, fsPath)) continue;
|
||||
return src;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
export function coverDiskUrl(fsPath: string): string {
|
||||
if (!fsPath || !isTauri()) return '';
|
||||
const src = convertFileSrc(fsPath);
|
||||
if (isRawFsPath(src, fsPath)) {
|
||||
if (import.meta.env.DEV) {
|
||||
console.warn('[cover] convertFileSrc out of asset scope — check tauri.conf assetProtocol', fsPath);
|
||||
}
|
||||
return '';
|
||||
const src = tryCoverDiskUrl(fsPath);
|
||||
if (!src && import.meta.env.DEV) {
|
||||
console.warn('[cover] convertFileSrc out of asset scope — check tauri.conf assetProtocol', {
|
||||
fsPath,
|
||||
src: convertFileSrc(normalizePathForConvert(fsPath)),
|
||||
});
|
||||
}
|
||||
return src;
|
||||
}
|
||||
@@ -67,8 +106,13 @@ export function forgetDiskSrc(storageKey: string): void {
|
||||
if (diskSrcByStorageKey.delete(storageKey)) bumpDiskSrcCache();
|
||||
}
|
||||
|
||||
export function forgetDiskSrcPrefix(serverIndexKey: string, coverArtId: string): void {
|
||||
const prefix = `${serverIndexKey}:cover:${coverArtId}:`;
|
||||
export function forgetDiskSrcPrefix(ref: {
|
||||
serverScope: CoverServerScope;
|
||||
cacheKind: string;
|
||||
cacheEntityId: string;
|
||||
}): void {
|
||||
const serverIndexKey = coverIndexKeyFromScope(ref.serverScope);
|
||||
const prefix = `${serverIndexKey}:cover:${ref.cacheKind}:${ref.cacheEntityId}:`;
|
||||
let changed = false;
|
||||
for (const key of diskSrcByStorageKey.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { albumCoverRef } from './ref';
|
||||
|
||||
vi.mock('./diskSrcCache', () => ({
|
||||
rememberDiskSrc: vi.fn(() => 'asset://cover.webp'),
|
||||
@@ -12,7 +13,7 @@ vi.mock('./diskHandoff', () => ({
|
||||
|
||||
import { rememberDiskSrc } from './diskSrcCache';
|
||||
import { notifyCoverDiskReady } from './diskHandoff';
|
||||
import { gridDiskSrcLookupOrder, rememberGridDiskSrc } from './diskSrcLookup';
|
||||
import { gridDiskSrcLookupOrder, rememberDiskSrcLadder, rememberGridDiskSrc } from './diskSrcLookup';
|
||||
|
||||
describe('gridDiskSrcLookupOrder', () => {
|
||||
it('prefers 800 right after 512 when 512 is wanted', () => {
|
||||
@@ -32,9 +33,25 @@ describe('rememberGridDiskSrc', () => {
|
||||
});
|
||||
|
||||
it('seeds 512 and 800 keys from one on-disk path (800.webp fallback)', () => {
|
||||
const hit = rememberGridDiskSrc({ kind: 'active' }, 'al-1', 512, '/data/800.webp');
|
||||
const ref = albumCoverRef('al-1', 'al-1');
|
||||
const hit = rememberGridDiskSrc(ref, 512, '/data/800.webp');
|
||||
expect(hit).toBe(true);
|
||||
expect(vi.mocked(rememberDiskSrc).mock.calls.length).toBeGreaterThanOrEqual(2);
|
||||
expect(vi.mocked(notifyCoverDiskReady)).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('rememberDiskSrcLadder', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(rememberDiskSrc).mockClear();
|
||||
vi.mocked(rememberDiskSrc).mockReturnValue('asset://x');
|
||||
});
|
||||
|
||||
it('seeds 128 when only 800.webp path arrives', () => {
|
||||
const hit = rememberDiskSrcLadder('srv', { cacheKind: 'album', cacheEntityId: 'al-1' }, 128, '/data/800.webp');
|
||||
expect(hit).toBe(true);
|
||||
const keys = vi.mocked(rememberDiskSrc).mock.calls.map(c => c[0]);
|
||||
expect(keys).toContain('srv:cover:album:al-1:128');
|
||||
expect(keys).toContain('srv:cover:album:al-1:800');
|
||||
});
|
||||
});
|
||||
|
||||
+25
-23
@@ -1,7 +1,7 @@
|
||||
import { getDiskSrc, rememberDiskSrc } from './diskSrcCache';
|
||||
import { hasCoverDiskReadyListeners, notifyCoverDiskReady } from './diskHandoff';
|
||||
import { coverStorageKey } from './storageKeys';
|
||||
import type { CoverArtId, CoverArtTier, CoverServerScope } from './types';
|
||||
import { coverStorageKeyFromRef } from './storageKeys';
|
||||
import type { CoverArtRef, CoverArtTier } from './types';
|
||||
|
||||
/** Dense grids: prefer a larger on-disk tier (800) before tiny thumbs when the ideal tier is missing. */
|
||||
export function gridDiskSrcLookupOrder(want: CoverArtTier): CoverArtTier[] {
|
||||
@@ -17,29 +17,20 @@ export function gridDiskSrcLookupOrder(want: CoverArtTier): CoverArtTier[] {
|
||||
}
|
||||
|
||||
/** Synchronous hit from `diskSrcCache` — any tier already warmed/peeked for this cover. */
|
||||
export function getDiskSrcForGrid(
|
||||
scope: CoverServerScope,
|
||||
coverArtId: CoverArtId,
|
||||
wantTier: CoverArtTier,
|
||||
): string {
|
||||
export function getDiskSrcForGrid(ref: CoverArtRef, wantTier: CoverArtTier): string {
|
||||
for (const tier of gridDiskSrcLookupOrder(wantTier)) {
|
||||
const src = getDiskSrc(coverStorageKey(scope, coverArtId, tier));
|
||||
const src = getDiskSrc(coverStorageKeyFromRef(ref, tier));
|
||||
if (src) return src;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/** Seed lookup-order tier keys (512 + 800 fallback path, etc.) — no subscriber wakeups. */
|
||||
export function seedGridDiskSrcCache(
|
||||
scope: CoverServerScope,
|
||||
coverArtId: CoverArtId,
|
||||
wantTier: CoverArtTier,
|
||||
fsPath: string,
|
||||
): boolean {
|
||||
export function seedGridDiskSrcCache(ref: CoverArtRef, wantTier: CoverArtTier, fsPath: string): boolean {
|
||||
if (!fsPath) return false;
|
||||
let hit = false;
|
||||
for (const tier of gridDiskSrcLookupOrder(wantTier)) {
|
||||
if (rememberDiskSrc(coverStorageKey(scope, coverArtId, tier), fsPath)) hit = true;
|
||||
if (rememberDiskSrc(coverStorageKeyFromRef(ref, tier), fsPath)) hit = true;
|
||||
}
|
||||
return hit;
|
||||
}
|
||||
@@ -47,17 +38,28 @@ export function seedGridDiskSrcCache(
|
||||
/**
|
||||
* After peek/ensure: seed cache and wake mounted cells once (avoids 4× notify / re-render storms).
|
||||
*/
|
||||
export function rememberGridDiskSrc(
|
||||
scope: CoverServerScope,
|
||||
coverArtId: CoverArtId,
|
||||
wantTier: CoverArtTier,
|
||||
fsPath: string,
|
||||
): boolean {
|
||||
const hit = seedGridDiskSrcCache(scope, coverArtId, wantTier, fsPath);
|
||||
export function rememberGridDiskSrc(ref: CoverArtRef, wantTier: CoverArtTier, fsPath: string): boolean {
|
||||
const hit = seedGridDiskSrcCache(ref, wantTier, fsPath);
|
||||
if (!hit) return false;
|
||||
const wantKey = coverStorageKey(scope, coverArtId, wantTier);
|
||||
const wantKey = coverStorageKeyFromRef(ref, wantTier);
|
||||
if (hasCoverDiskReadyListeners(wantKey)) {
|
||||
notifyCoverDiskReady(wantKey, fsPath);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Rust `cover:tier-ready` — seed ladder keys so sparse cells see 800.webp when they want 128. */
|
||||
export function rememberDiskSrcLadder(
|
||||
serverIndexKey: string,
|
||||
ref: Pick<CoverArtRef, 'cacheKind' | 'cacheEntityId'>,
|
||||
wantTier: CoverArtTier,
|
||||
fsPath: string,
|
||||
): boolean {
|
||||
if (!serverIndexKey || !ref.cacheEntityId || !fsPath) return false;
|
||||
let hit = false;
|
||||
for (const tier of gridDiskSrcLookupOrder(wantTier)) {
|
||||
const key = `${serverIndexKey}:cover:${ref.cacheKind}:${ref.cacheEntityId}:${tier}`;
|
||||
if (rememberDiskSrc(key, fsPath)) hit = true;
|
||||
}
|
||||
return hit;
|
||||
}
|
||||
|
||||
@@ -2,9 +2,9 @@ import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
|
||||
const { ensureImpl } = vi.hoisted(() => ({
|
||||
ensureImpl: vi.fn(
|
||||
async (_ref: { coverArtId: string }, _tier: number, _priority: string) => {
|
||||
async (ref: { fetchCoverArtId: string }, _tier: number, _priority: string) => {
|
||||
await new Promise(r => setTimeout(r, 2));
|
||||
return { hit: true, path: `/tmp/${_ref.coverArtId}.webp`, tier: 128 };
|
||||
return { hit: true, path: `/tmp/${ref.fetchCoverArtId}.webp`, tier: 128 };
|
||||
},
|
||||
),
|
||||
}));
|
||||
|
||||
@@ -61,7 +61,7 @@ function trimQueue(): void {
|
||||
}
|
||||
|
||||
function coverInflightKey(ref: CoverArtRef): string {
|
||||
return `${coverIndexKeyFromRef(ref)}:${ref.coverArtId}`;
|
||||
return `${coverIndexKeyFromRef(ref)}:${ref.cacheKind}:${ref.cacheEntityId}`;
|
||||
}
|
||||
|
||||
/** Serialize ensures per cover ID so we do not re-download for every tier. */
|
||||
@@ -164,12 +164,12 @@ export function __test_resetCoverEnsureQueue(): void {
|
||||
|
||||
/** @internal Vitest-only — queued cover art IDs front-to-back. */
|
||||
export function __test_queuedCoverIds(): string[] {
|
||||
return queue.map(j => j.ref.coverArtId);
|
||||
return queue.map(j => j.ref.cacheEntityId);
|
||||
}
|
||||
|
||||
function ensureMemoryHit(storageKey: string, ref: CoverArtRef, tier: CoverArtTier): boolean {
|
||||
if (getDiskSrc(storageKey)) return true;
|
||||
return Boolean(getDiskSrcForGrid(ref.serverScope, ref.coverArtId, tier));
|
||||
return Boolean(getDiskSrcForGrid(ref, tier));
|
||||
}
|
||||
|
||||
/** Rust disk ensure — parallel slots; one download chain per cover art ID. */
|
||||
|
||||
@@ -8,13 +8,13 @@ import type { CoverArtRef, CoverArtTier } from './types';
|
||||
|
||||
/** Builds ephemeral getCoverArt URL — NOT a cache key */
|
||||
export function buildCoverArtFetchUrl(ref: CoverArtRef, tier: CoverArtTier): string {
|
||||
const { coverArtId, serverScope } = ref;
|
||||
const { fetchCoverArtId, serverScope } = ref;
|
||||
if (serverScope.kind === 'server') {
|
||||
return buildCoverArtUrlForServer(
|
||||
serverScope.url,
|
||||
serverScope.username,
|
||||
serverScope.password,
|
||||
coverArtId,
|
||||
fetchCoverArtId,
|
||||
tier,
|
||||
);
|
||||
}
|
||||
@@ -28,11 +28,11 @@ export function buildCoverArtFetchUrl(ref: CoverArtRef, tier: CoverArtTier): str
|
||||
server.url,
|
||||
server.username,
|
||||
server.password,
|
||||
coverArtId,
|
||||
fetchCoverArtId,
|
||||
tier,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return buildCoverArtUrl(coverArtId, tier);
|
||||
return buildCoverArtUrl(fetchCoverArtId, tier);
|
||||
}
|
||||
|
||||
@@ -7,9 +7,21 @@ export * from './ids';
|
||||
export * from './storageKeys';
|
||||
export * from './reachability';
|
||||
export * from './layoutSizes';
|
||||
export * from './resolveEntry';
|
||||
export * from './resolveEntryLibrary';
|
||||
export * from './ref';
|
||||
export { useCoverArt } from './useCoverArt';
|
||||
export {
|
||||
useAlbumCoverRef,
|
||||
useArtistCoverRef,
|
||||
usePlaybackTrackCoverRef,
|
||||
useTrackCoverRef,
|
||||
} from './useLibraryCoverRef';
|
||||
export { CoverArtImage } from './CoverArtImage';
|
||||
export { AlbumCoverArtImage } from './AlbumCoverArtImage';
|
||||
export { ArtistCoverArtImage } from './ArtistCoverArtImage';
|
||||
export { TrackCoverArtImage } from './TrackCoverArtImage';
|
||||
export { useLibraryCoverPrefetch } from './useLibraryCoverPrefetch';
|
||||
export {
|
||||
clearAllDiskSrcCache,
|
||||
forgetDiskSrc,
|
||||
@@ -18,6 +30,24 @@ export {
|
||||
rememberDiskSrc,
|
||||
} from './diskSrcCache';
|
||||
export { usePlaybackCoverArt } from './usePlaybackCoverArt';
|
||||
export {
|
||||
resolveAlbumCoverEntry,
|
||||
resolveArtistCoverEntry,
|
||||
resolveArtistPageSongFetchCoverArtId,
|
||||
resolveTrackCoverEntry,
|
||||
resolveSongFetchCoverArtId,
|
||||
coverEntryToRef,
|
||||
} from './resolveEntry';
|
||||
export {
|
||||
resolveAlbumCoverRefsFromLibrary,
|
||||
resolveArtistCoverRefsFromLibrary,
|
||||
resolveTrackCoverRefsFromLibrary,
|
||||
} from './resolveEntryLibrary';
|
||||
export {
|
||||
resolveArtistPageSongCoverArtId,
|
||||
resolvePlaybackTrackCoverArtId,
|
||||
resolveSubsonicSongCoverArtId,
|
||||
} from './resolveCoverArtId';
|
||||
export { ensureCoverTierJs } from './resolveJs';
|
||||
export { ensureCoverTierDiskSrc, ensureCoverTierDiskBlob } from './resolveDisk';
|
||||
export { buildCoverArtFetchUrl } from './fetchUrl';
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { computeCardGridColumnCount, computeCellWidthPx } from '../utils/cardGridLayout';
|
||||
|
||||
export const COVER_DENSE_SEARCH_CSS_PX = 40;
|
||||
/** Artist detail top-track thumb (32×32 CSS px). */
|
||||
export const COVER_ARTIST_TOP_TRACK_CSS_PX = 32;
|
||||
export const COVER_DENSE_ARTIST_LIST_CSS_PX = 64;
|
||||
export const COVER_DENSE_RAIL_CELL_CSS_PX = 180;
|
||||
export const COVER_DENSE_GRID_MIN_CELL_CSS_PX = 140;
|
||||
|
||||
@@ -30,7 +30,7 @@ export function useCoverLightboxSrc(
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [open, ref?.coverArtId, ref?.serverScope]);
|
||||
}, [open, ref?.cacheEntityId, ref?.cacheKind, ref?.fetchCoverArtId, ref?.serverScope]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) return;
|
||||
|
||||
+18
-16
@@ -3,12 +3,12 @@ import { getDiskSrc } from './diskSrcCache';
|
||||
import { getDiskSrcForGrid } from './diskSrcLookup';
|
||||
import { coverTrafficServerSwitchPaused } from './coverTraffic';
|
||||
import { rememberGridDiskSrc } from './diskSrcLookup';
|
||||
import { coverIndexKeyFromRef } from './storageKeys';
|
||||
import { coverStorageKeyFromRef } from './storageKeys';
|
||||
import type { CoverArtRef, CoverArtTier } from './types';
|
||||
|
||||
function peekMemoryHit(storageKey: string, ref: CoverArtRef, tier: CoverArtTier): boolean {
|
||||
if (getDiskSrc(storageKey)) return true;
|
||||
return Boolean(getDiskSrcForGrid(ref.serverScope, ref.coverArtId, tier));
|
||||
return Boolean(getDiskSrcForGrid(ref, tier));
|
||||
}
|
||||
|
||||
type PeekJob = {
|
||||
@@ -51,22 +51,24 @@ async function flush(): Promise<void> {
|
||||
}
|
||||
if (needDisk.length === 0) return;
|
||||
|
||||
const hits = await coverCachePeekBatch(
|
||||
needDisk.map(job => ({
|
||||
serverIndexKey: coverIndexKeyFromRef(job.ref),
|
||||
coverArtId: job.ref.coverArtId,
|
||||
tier: job.tier,
|
||||
})),
|
||||
);
|
||||
|
||||
const byTier = new Map<CoverArtTier, PeekJob[]>();
|
||||
for (const job of needDisk) {
|
||||
const path = hits[job.storageKey];
|
||||
const hit = Boolean(
|
||||
path
|
||||
&& rememberGridDiskSrc(job.ref.serverScope, job.ref.coverArtId, job.tier, path),
|
||||
const list = byTier.get(job.tier) ?? [];
|
||||
list.push(job);
|
||||
byTier.set(job.tier, list);
|
||||
}
|
||||
|
||||
for (const [tier, jobs] of byTier) {
|
||||
const hits = await coverCachePeekBatch(
|
||||
jobs.map(j => j.ref),
|
||||
tier,
|
||||
);
|
||||
job.resolve(hit);
|
||||
inflight.delete(job.storageKey);
|
||||
for (const job of jobs) {
|
||||
const path = hits[job.storageKey] ?? '';
|
||||
const hit = Boolean(path && rememberGridDiskSrc(job.ref, job.tier, path));
|
||||
job.resolve(hit);
|
||||
inflight.delete(job.storageKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ const MAX_REGISTRY = 120;
|
||||
const registry = new Map<string, { ref: CoverArtRef; priority: CoverPrefetchPriority }>();
|
||||
|
||||
function registryKey(ref: CoverArtRef): string {
|
||||
return `${coverIndexKeyFromRef(ref)}:${ref.coverArtId}`;
|
||||
return `${coverIndexKeyFromRef(ref)}:${ref.cacheKind}:${ref.cacheEntityId}`;
|
||||
}
|
||||
|
||||
export function coverPrefetchRegister(
|
||||
@@ -23,7 +23,7 @@ export function coverPrefetchRegister(
|
||||
|
||||
const keys: string[] = [];
|
||||
for (const ref of refs) {
|
||||
if (!ref.coverArtId || !coverServerReachable(ref.serverScope)) continue;
|
||||
if (!ref.cacheEntityId || !coverServerReachable(ref.serverScope)) continue;
|
||||
const key = registryKey(ref);
|
||||
if (registry.size >= MAX_REGISTRY && !registry.has(key)) {
|
||||
const drop = [...registry.entries()].find(([, v]) => v.priority === 'low');
|
||||
@@ -62,7 +62,7 @@ export function coverPrefetchBumpPriority(
|
||||
ref: CoverArtRef,
|
||||
priority: CoverPrefetchPriority,
|
||||
): void {
|
||||
if (!ref.coverArtId || !coverServerReachable(ref.serverScope)) return;
|
||||
if (!ref.cacheEntityId || !coverServerReachable(ref.serverScope)) return;
|
||||
const key = registryKey(ref);
|
||||
const existing = registry.get(key);
|
||||
if (!existing) {
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
albumCoverRef,
|
||||
albumCoverRefForPlayback,
|
||||
albumCoverRefForSong,
|
||||
albumHasDistinctDiscCovers,
|
||||
rememberAlbumDistinctDiscCovers,
|
||||
resolveAlbumCoverCacheEntityId,
|
||||
resolveDistinctDiscCoversForAlbum,
|
||||
} from './ref';
|
||||
|
||||
describe('resolveAlbumCoverCacheEntityId', () => {
|
||||
it('uses album id when fetch matches or is empty', () => {
|
||||
expect(resolveAlbumCoverCacheEntityId('al-1', 'al-1')).toBe('al-1');
|
||||
expect(resolveAlbumCoverCacheEntityId('al-1', null)).toBe('al-1');
|
||||
expect(resolveAlbumCoverCacheEntityId('al-1', '')).toBe('al-1');
|
||||
});
|
||||
|
||||
it('ignores mf-* fetch unless distinctDiscCovers', () => {
|
||||
expect(resolveAlbumCoverCacheEntityId('al-box', 'mf-disc2_abc')).toBe('al-box');
|
||||
expect(resolveAlbumCoverCacheEntityId('al-box', 'mf-disc2_abc', true)).toBe('mf-disc2_abc');
|
||||
});
|
||||
});
|
||||
|
||||
describe('albumHasDistinctDiscCovers', () => {
|
||||
it('false for single disc', () => {
|
||||
expect(
|
||||
albumHasDistinctDiscCovers([
|
||||
{ id: 't1', albumId: 'al-1', coverArt: 'mf-a', discNumber: 1 },
|
||||
]),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('false when two discs share the same art id', () => {
|
||||
expect(
|
||||
albumHasDistinctDiscCovers([
|
||||
{ id: 't1', albumId: 'al-1', coverArt: 'mf-same', discNumber: 1 },
|
||||
{ id: 't2', albumId: 'al-1', coverArt: 'mf-same', discNumber: 2 },
|
||||
]),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('true when two discs have different art ids', () => {
|
||||
expect(
|
||||
albumHasDistinctDiscCovers([
|
||||
{ id: 't1', albumId: 'al-1', coverArt: 'mf-a', discNumber: 1 },
|
||||
{ id: 't2', albumId: 'al-1', coverArt: 'mf-b', discNumber: 2 },
|
||||
]),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('albumCoverRef', () => {
|
||||
it('keys by album id for mf fetch by default', () => {
|
||||
const ref = albumCoverRef('al-box', 'mf-disc1_xyz');
|
||||
expect(ref.cacheEntityId).toBe('al-box');
|
||||
expect(ref.fetchCoverArtId).toBe('mf-disc1_xyz');
|
||||
});
|
||||
|
||||
it('keys by fetch id when distinctDiscCovers', () => {
|
||||
const ref = albumCoverRef('al-box', 'mf-disc1_xyz', { distinctDiscCovers: true });
|
||||
expect(ref.cacheEntityId).toBe('mf-disc1_xyz');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveDistinctDiscCoversForAlbum', () => {
|
||||
it('detects mf-* fetch id before album page visit', () => {
|
||||
expect(resolveDistinctDiscCoversForAlbum('al-box', 'mf-d2')).toBe(true);
|
||||
expect(resolveDistinctDiscCoversForAlbum('al-box', 'al-box')).toBe(false);
|
||||
});
|
||||
|
||||
it('respects remembered false for same art on all discs', () => {
|
||||
rememberAlbumDistinctDiscCovers('al-same', [
|
||||
{ id: 't1', albumId: 'al-same', coverArt: 'mf-x', discNumber: 1 },
|
||||
{ id: 't2', albumId: 'al-same', coverArt: 'mf-x', discNumber: 2 },
|
||||
]);
|
||||
expect(resolveDistinctDiscCoversForAlbum('al-same', 'mf-x')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('albumCoverRefForSong', () => {
|
||||
it('keys per-disc without library resolve', () => {
|
||||
const ref = albumCoverRefForSong({
|
||||
id: 't2',
|
||||
albumId: 'al-box',
|
||||
coverArt: 'mf-d2',
|
||||
discNumber: 2,
|
||||
});
|
||||
expect(ref?.cacheEntityId).toBe('mf-d2');
|
||||
});
|
||||
});
|
||||
|
||||
describe('albumCoverRefForPlayback', () => {
|
||||
it('keys per-disc from mf coverArt before album page visit', () => {
|
||||
const ref = albumCoverRefForPlayback(
|
||||
{ albumId: 'al-box', coverArt: 'mf-disc2', id: 't2', discNumber: 2 },
|
||||
{ kind: 'active' },
|
||||
);
|
||||
expect(ref?.cacheEntityId).toBe('mf-disc2');
|
||||
expect(ref?.fetchCoverArtId).toBe('mf-disc2');
|
||||
});
|
||||
|
||||
it('uses remembered album flag', () => {
|
||||
rememberAlbumDistinctDiscCovers('al-1', [
|
||||
{ id: 't1', albumId: 'al-1', coverArt: 'mf-a', discNumber: 1 },
|
||||
{ id: 't2', albumId: 'al-1', coverArt: 'mf-b', discNumber: 2 },
|
||||
]);
|
||||
const ref = albumCoverRefForPlayback(
|
||||
{ albumId: 'al-1', coverArt: 'mf-b', id: 't2', discNumber: 2 },
|
||||
{ kind: 'active' },
|
||||
);
|
||||
expect(ref?.cacheEntityId).toBe('mf-b');
|
||||
});
|
||||
});
|
||||
+179
-3
@@ -1,19 +1,195 @@
|
||||
import { getPlaybackServerId } from '../utils/playback/playbackServer';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import type { CoverArtId, CoverArtRef, CoverServerScope } from './types';
|
||||
import { findServerByIdOrIndexKey } from '../utils/server/serverLookup';
|
||||
import type { SubsonicSong } from '../api/subsonicTypes';
|
||||
import type { CoverArtId, CoverArtRef, CoverCacheKind, CoverServerScope } from './types';
|
||||
import {
|
||||
albumHasDistinctDiscCovers,
|
||||
coverEntryToRef,
|
||||
resolveAlbumCoverEntry,
|
||||
resolveArtistCoverEntry,
|
||||
resolveTrackCoverEntry,
|
||||
} from './resolveEntry';
|
||||
|
||||
export type { CoverEntry } from './resolveEntry';
|
||||
export { albumHasDistinctDiscCovers } from './resolveEntry';
|
||||
|
||||
export type AlbumCoverRefOptions = {
|
||||
serverScope?: CoverServerScope;
|
||||
distinctDiscCovers?: boolean;
|
||||
};
|
||||
|
||||
const albumDistinctDiscCoversByAlbumId = new Map<string, boolean>();
|
||||
|
||||
export function rememberAlbumDistinctDiscCovers(
|
||||
albumId: string,
|
||||
songs: ReadonlyArray<Pick<SubsonicSong, 'discNumber' | 'coverArt' | 'id' | 'albumId'>>,
|
||||
): void {
|
||||
const id = albumId.trim();
|
||||
if (!id) return;
|
||||
albumDistinctDiscCoversByAlbumId.set(id, albumHasDistinctDiscCovers(songs));
|
||||
}
|
||||
|
||||
export function forgetAlbumDistinctDiscCovers(albumId: string): void {
|
||||
albumDistinctDiscCoversByAlbumId.delete(albumId.trim());
|
||||
}
|
||||
|
||||
export type DistinctDiscCoversHint = Pick<
|
||||
SubsonicSong,
|
||||
'discNumber' | 'coverArt' | 'id' | 'albumId'
|
||||
>;
|
||||
|
||||
/**
|
||||
* Whether per-disc `mf-*` cache slots apply — from album tracklist memory or song hints
|
||||
* when the album page has not been opened yet.
|
||||
*/
|
||||
export function resolveDistinctDiscCoversForAlbum(
|
||||
albumId: string,
|
||||
fetchCoverArtId?: string | null,
|
||||
songHint?: DistinctDiscCoversHint,
|
||||
): boolean {
|
||||
const album = albumId.trim();
|
||||
if (!album) return false;
|
||||
|
||||
const known = albumDistinctDiscCoversByAlbumId.get(album);
|
||||
if (known === true) return true;
|
||||
if (known === false) return false;
|
||||
|
||||
if (songHint) {
|
||||
const cover = songHint.coverArt?.trim();
|
||||
if ((songHint.discNumber ?? 1) > 1 && Boolean(cover && cover !== album)) return true;
|
||||
}
|
||||
|
||||
const fetch = fetchCoverArtId?.trim();
|
||||
if (fetch && fetch !== album && fetch.startsWith('mf-')) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function resolveAlbumCoverRefOptions(
|
||||
third?: CoverServerScope | AlbumCoverRefOptions,
|
||||
): { serverScope: CoverServerScope; distinctDiscCovers: boolean } {
|
||||
if (!third || 'kind' in third) {
|
||||
return { serverScope: third ?? { kind: 'active' }, distinctDiscCovers: false };
|
||||
}
|
||||
return {
|
||||
serverScope: third.serverScope ?? { kind: 'active' },
|
||||
distinctDiscCovers: third.distinctDiscCovers ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
/** @deprecated Use {@link resolveAlbumCoverEntry}. */
|
||||
export function resolveAlbumCoverCacheEntityId(
|
||||
albumId: string,
|
||||
fetchCoverArtId?: string | null,
|
||||
distinctDiscCovers = false,
|
||||
): string {
|
||||
return resolveAlbumCoverEntry(albumId, fetchCoverArtId, distinctDiscCovers)?.cacheEntityId ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync fallback for cover identity — UI should prefer {@link useAlbumCoverRef} /
|
||||
* {@link AlbumCoverArtImage}; async paths should use {@link resolveAlbumCoverRefFromLibrary}.
|
||||
*/
|
||||
export function albumCoverRef(
|
||||
albumId: string,
|
||||
fetchCoverArtId?: string | null,
|
||||
scopeOrOpts: CoverServerScope | AlbumCoverRefOptions = { kind: 'active' },
|
||||
): CoverArtRef {
|
||||
const { serverScope, distinctDiscCovers } = resolveAlbumCoverRefOptions(scopeOrOpts);
|
||||
const entry = resolveAlbumCoverEntry(albumId, fetchCoverArtId, distinctDiscCovers);
|
||||
if (!entry) {
|
||||
const id = (fetchCoverArtId ?? albumId).trim();
|
||||
return coverEntryToRef(
|
||||
{ cacheKind: 'album', cacheEntityId: id, fetchCoverArtId: id },
|
||||
serverScope,
|
||||
);
|
||||
}
|
||||
return coverEntryToRef(entry, serverScope);
|
||||
}
|
||||
|
||||
export function albumCoverRefForSong(
|
||||
song: Pick<SubsonicSong, 'albumId' | 'coverArt' | 'id' | 'discNumber'>,
|
||||
distinctDiscCovers?: boolean,
|
||||
serverScope: CoverServerScope = { kind: 'active' },
|
||||
): CoverArtRef | undefined {
|
||||
const albumId = song.albumId?.trim();
|
||||
const distinct =
|
||||
distinctDiscCovers
|
||||
?? (albumId ? resolveDistinctDiscCoversForAlbum(albumId, song.coverArt, song) : false);
|
||||
const entry = resolveTrackCoverEntry(song, distinct);
|
||||
return entry ? coverEntryToRef(entry, serverScope) : undefined;
|
||||
}
|
||||
|
||||
export function albumCoverRefForPlayback(
|
||||
track: Pick<SubsonicSong, 'coverArt' | 'id' | 'discNumber'> & { albumId?: string | null },
|
||||
serverScope: CoverServerScope = resolvePlaybackCoverScope(),
|
||||
): CoverArtRef | undefined {
|
||||
const albumId = track.albumId?.trim();
|
||||
if (!albumId) return undefined;
|
||||
const distinctDiscCovers = resolveDistinctDiscCoversForAlbum(
|
||||
albumId,
|
||||
track.coverArt,
|
||||
{ ...track, albumId } as DistinctDiscCoversHint,
|
||||
);
|
||||
return albumCoverRefForSong(
|
||||
{ ...track, albumId } as Pick<SubsonicSong, 'albumId' | 'coverArt' | 'id' | 'discNumber'>,
|
||||
distinctDiscCovers,
|
||||
serverScope,
|
||||
);
|
||||
}
|
||||
|
||||
export function artistCoverRef(
|
||||
artistId: string,
|
||||
fetchCoverArtId?: string | null,
|
||||
serverScope: CoverServerScope = { kind: 'active' },
|
||||
): CoverArtRef {
|
||||
const entry = resolveArtistCoverEntry(artistId, fetchCoverArtId);
|
||||
if (!entry) {
|
||||
const id = (fetchCoverArtId ?? artistId).trim();
|
||||
return coverEntryToRef(
|
||||
{ cacheKind: 'artist', cacheEntityId: id, fetchCoverArtId: id },
|
||||
serverScope,
|
||||
);
|
||||
}
|
||||
return coverEntryToRef(entry, serverScope);
|
||||
}
|
||||
|
||||
export function coverRefFromEntity(
|
||||
cacheKind: CoverCacheKind,
|
||||
cacheEntityId: string,
|
||||
fetchCoverArtId?: string | null,
|
||||
serverScope: CoverServerScope = { kind: 'active' },
|
||||
): CoverArtRef {
|
||||
const entry =
|
||||
cacheKind === 'artist'
|
||||
? resolveArtistCoverEntry(cacheEntityId, fetchCoverArtId)
|
||||
: resolveAlbumCoverEntry(cacheEntityId, fetchCoverArtId);
|
||||
if (!entry) {
|
||||
const id = (fetchCoverArtId ?? cacheEntityId).trim();
|
||||
return coverEntryToRef(
|
||||
{ cacheKind, cacheEntityId: id, fetchCoverArtId: id },
|
||||
serverScope,
|
||||
);
|
||||
}
|
||||
return coverEntryToRef(entry, serverScope);
|
||||
}
|
||||
|
||||
/** @deprecated Prefer entity helpers in {@link resolveEntry}. */
|
||||
export function coverArtRef(
|
||||
coverArtId: CoverArtId,
|
||||
serverScope: CoverServerScope = { kind: 'active' },
|
||||
): CoverArtRef {
|
||||
return { coverArtId, serverScope };
|
||||
const id = coverArtId.trim();
|
||||
if (id.startsWith('ar-')) return artistCoverRef(id, id, serverScope);
|
||||
return albumCoverRef(id, id, serverScope);
|
||||
}
|
||||
|
||||
export function resolvePlaybackCoverScope(): CoverServerScope {
|
||||
const playbackSid = getPlaybackServerId();
|
||||
const activeSid = useAuthStore.getState().activeServerId;
|
||||
if (playbackSid && activeSid && playbackSid !== activeSid) {
|
||||
const server = useAuthStore.getState().servers.find(s => s.id === playbackSid);
|
||||
const server = findServerByIdOrIndexKey(playbackSid);
|
||||
if (server) {
|
||||
return {
|
||||
kind: 'server',
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
resolveArtistPageSongCoverArtId,
|
||||
resolvePlaybackTrackCoverArtId,
|
||||
resolveSubsonicSongCoverArtId,
|
||||
} from './resolveCoverArtId';
|
||||
|
||||
describe('resolveSubsonicSongCoverArtId', () => {
|
||||
it('prefers albumId when coverArt is the track id', () => {
|
||||
expect(
|
||||
resolveSubsonicSongCoverArtId({
|
||||
id: 'tr-1',
|
||||
coverArt: 'tr-1',
|
||||
albumId: 'al-42',
|
||||
}),
|
||||
).toBe('al-42');
|
||||
});
|
||||
|
||||
it('keeps coverArt when it differs from song id and albumId is set', () => {
|
||||
expect(
|
||||
resolveSubsonicSongCoverArtId({
|
||||
id: 'tr-1',
|
||||
coverArt: 'cov-track',
|
||||
albumId: 'al-42',
|
||||
}),
|
||||
).toBe('cov-track');
|
||||
});
|
||||
|
||||
it('keeps mf-* coverArt for per-disc art', () => {
|
||||
expect(
|
||||
resolveSubsonicSongCoverArtId({
|
||||
id: 'tr-1',
|
||||
coverArt: 'mf-Gg7kLxzr2dNSB7BZ9eV2Xz_69d63a8a',
|
||||
albumId: 'al-07lZYKfVt0F4MOgbhsmeyo_69d63b4d',
|
||||
}),
|
||||
).toBe('mf-Gg7kLxzr2dNSB7BZ9eV2Xz_69d63a8a');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolvePlaybackTrackCoverArtId', () => {
|
||||
it('returns undefined for null track', () => {
|
||||
expect(resolvePlaybackTrackCoverArtId(null)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('resolves albumId when coverArt echoes track id', () => {
|
||||
expect(
|
||||
resolvePlaybackTrackCoverArtId({
|
||||
id: 'tr-1',
|
||||
coverArt: 'tr-1',
|
||||
albumId: 'al-42',
|
||||
}),
|
||||
).toBe('al-42');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveArtistPageSongCoverArtId', () => {
|
||||
it('prefers album coverArt over song coverArt', () => {
|
||||
expect(
|
||||
resolveArtistPageSongCoverArtId(
|
||||
{ id: 'tr-1', coverArt: 'tr-1', albumId: 'al-octa', album: 'Octastorium' },
|
||||
[{ id: 'al-octa', name: 'Octastorium', coverArt: 'cov-octa' }],
|
||||
),
|
||||
).toBe('cov-octa');
|
||||
});
|
||||
|
||||
it('ignores album coverArt when it echoes track id', () => {
|
||||
expect(
|
||||
resolveArtistPageSongCoverArtId(
|
||||
{ id: 'tr-1', coverArt: 'tr-1', albumId: 'al-octa', album: 'Octastorium' },
|
||||
[{ id: 'al-octa', name: 'Octastorium', coverArt: 'tr-1' }],
|
||||
),
|
||||
).toBe('al-octa');
|
||||
});
|
||||
|
||||
it('uses album row coverArt when present', () => {
|
||||
expect(
|
||||
resolveArtistPageSongCoverArtId(
|
||||
{
|
||||
id: 'tr-1',
|
||||
coverArt: 'mf-x_1',
|
||||
albumId: 'al-octa_2',
|
||||
album: 'Octastorium',
|
||||
},
|
||||
[{ id: 'al-octa_2', name: 'Octastorium', coverArt: 'mf-x_1' }],
|
||||
),
|
||||
).toBe('mf-x_1');
|
||||
});
|
||||
|
||||
it('uses per-disc coverArt when it differs from the album row', () => {
|
||||
expect(
|
||||
resolveArtistPageSongCoverArtId(
|
||||
{
|
||||
id: 'tr-2',
|
||||
coverArt: 'mf-disc2',
|
||||
albumId: 'al-box',
|
||||
album: 'Box Set',
|
||||
discNumber: 2,
|
||||
},
|
||||
[{ id: 'al-box', name: 'Box Set', coverArt: 'mf-disc1' }],
|
||||
),
|
||||
).toBe('mf-disc2');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
/** @deprecated Import from `./resolveEntry` — kept for gradual migration. */
|
||||
export type { CoverArtResolvableSong } from './resolveEntry';
|
||||
export {
|
||||
resolveArtistPageSongFetchCoverArtId as resolveArtistPageSongCoverArtId,
|
||||
resolveSongFetchCoverArtId as resolveSubsonicSongCoverArtId,
|
||||
} from './resolveEntry';
|
||||
|
||||
import type { CoverArtResolvableSong } from './resolveEntry';
|
||||
import { resolveSongFetchCoverArtId } from './resolveEntry';
|
||||
|
||||
/** @deprecated Use {@link resolveSongFetchCoverArtId}. */
|
||||
export function resolvePlaybackTrackCoverArtId(
|
||||
track: CoverArtResolvableSong | null | undefined,
|
||||
): string | undefined {
|
||||
if (!track) return undefined;
|
||||
return resolveSongFetchCoverArtId({
|
||||
id: track.id,
|
||||
coverArt: track.coverArt,
|
||||
albumId: track.albumId ?? '',
|
||||
});
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { isTauri } from '@tauri-apps/api/core';
|
||||
import { coverCacheEnsure } from '../api/coverCache';
|
||||
import { invalidateCacheKey } from '../utils/imageCache';
|
||||
import { getDiskSrcForGrid } from './diskSrcLookup';
|
||||
import { getDiskSrc, rememberDiskSrc } from './diskSrcCache';
|
||||
import { coverStorageKey } from './storageKeys';
|
||||
import { coverStorageKeyFromRef } from './storageKeys';
|
||||
import type { CoverArtRef, CoverArtTier } from './types';
|
||||
|
||||
/**
|
||||
@@ -12,10 +13,10 @@ export async function ensureCoverTierDiskSrc(
|
||||
ref: CoverArtRef,
|
||||
tier: CoverArtTier,
|
||||
): Promise<string> {
|
||||
if (!ref.coverArtId || !isTauri()) return '';
|
||||
if (!ref.fetchCoverArtId || !isTauri()) return '';
|
||||
|
||||
const storageKey = coverStorageKey(ref.serverScope, ref.coverArtId, tier);
|
||||
const cached = getDiskSrc(storageKey);
|
||||
const storageKey = coverStorageKeyFromRef(ref, tier);
|
||||
const cached = getDiskSrcForGrid(ref, tier) || getDiskSrc(storageKey);
|
||||
if (cached) return cached;
|
||||
|
||||
const result = await coverCacheEnsure(ref, tier, 'high');
|
||||
@@ -34,7 +35,7 @@ export async function ensureCoverTierDiskBlob(
|
||||
tier: CoverArtTier,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Blob | null> {
|
||||
const storageKey = coverStorageKey(ref.serverScope, ref.coverArtId, tier);
|
||||
const storageKey = coverStorageKeyFromRef(ref, tier);
|
||||
const existing = getDiskSrc(storageKey);
|
||||
if (existing) {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
albumHasDistinctDiscCovers,
|
||||
resolveAlbumCoverEntry,
|
||||
resolveArtistCoverEntry,
|
||||
resolveSongFetchCoverArtId,
|
||||
resolveTrackCoverEntry,
|
||||
} from './resolveEntry';
|
||||
|
||||
describe('resolveAlbumCoverEntry', () => {
|
||||
it('uses bare Navidrome album id on disk', () => {
|
||||
const e = resolveAlbumCoverEntry('0DurV2S7arIOBQVEknOPWX', 'al-0Dur_abc');
|
||||
expect(e?.cacheEntityId).toBe('0DurV2S7arIOBQVEknOPWX');
|
||||
expect(e?.fetchCoverArtId).toBe('al-0Dur_abc');
|
||||
});
|
||||
|
||||
it('ignores mf fetch unless distinctDiscCovers', () => {
|
||||
expect(resolveAlbumCoverEntry('al-box', 'mf-d2')?.cacheEntityId).toBe('al-box');
|
||||
expect(resolveAlbumCoverEntry('al-box', 'mf-d2', true)?.cacheEntityId).toBe('mf-d2');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveArtistCoverEntry', () => {
|
||||
it('keys by artist id', () => {
|
||||
const e = resolveArtistCoverEntry('03b645ef2100dfc4', 'ar-03b645ef');
|
||||
expect(e?.cacheKind).toBe('artist');
|
||||
expect(e?.cacheEntityId).toBe('03b645ef2100dfc4');
|
||||
expect(e?.fetchCoverArtId).toBe('ar-03b645ef');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveTrackCoverEntry', () => {
|
||||
it('defaults to album bucket', () => {
|
||||
const e = resolveTrackCoverEntry({
|
||||
id: 't1',
|
||||
albumId: 'al-1',
|
||||
coverArt: 'mf-a',
|
||||
});
|
||||
expect(e?.cacheEntityId).toBe('al-1');
|
||||
expect(e?.fetchCoverArtId).toBe('mf-a');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveSongFetchCoverArtId', () => {
|
||||
it('falls back to albumId when coverArt echoes track id', () => {
|
||||
expect(
|
||||
resolveSongFetchCoverArtId({ id: 'tr-1', coverArt: 'tr-1', albumId: 'al-42' }),
|
||||
).toBe('al-42');
|
||||
});
|
||||
});
|
||||
|
||||
describe('albumHasDistinctDiscCovers', () => {
|
||||
it('true when discs differ', () => {
|
||||
expect(
|
||||
albumHasDistinctDiscCovers([
|
||||
{ id: 't1', albumId: 'al-1', coverArt: 'mf-a', discNumber: 1 },
|
||||
{ id: 't2', albumId: 'al-1', coverArt: 'mf-b', discNumber: 2 },
|
||||
]),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* Single source of truth for cover cache keys and HTTP fetch ids.
|
||||
*
|
||||
* Entities: **artist**, **album**, **track-on-album** (track art is always album-scoped
|
||||
* unless the album has distinct per-CD covers).
|
||||
*
|
||||
* Disk path shape is Rust-only (`psysonic_core::cover_cache_layout`); this module must
|
||||
* stay in sync with `resolve_album_cover` / `resolve_artist_cover` there.
|
||||
*/
|
||||
|
||||
import type { SubsonicAlbum, SubsonicSong } from '../api/subsonicTypes';
|
||||
import type { CoverArtRef, CoverCacheKind, CoverServerScope } from './types';
|
||||
|
||||
/** Resolved cover identity — maps 1:1 to Rust `CoverEntry`. */
|
||||
export type CoverEntry = {
|
||||
cacheKind: CoverCacheKind;
|
||||
cacheEntityId: string;
|
||||
fetchCoverArtId: string;
|
||||
};
|
||||
|
||||
export type CoverArtResolvableSong = Pick<SubsonicSong, 'id' | 'coverArt'> & {
|
||||
albumId?: string | null;
|
||||
};
|
||||
|
||||
/** Navidrome `getCoverArt` id for a song row (ignores echo of track id with no art). */
|
||||
export function resolveSongFetchCoverArtId(song: CoverArtResolvableSong): string | undefined {
|
||||
const albumId = song.albumId?.trim();
|
||||
const cover = song.coverArt?.trim();
|
||||
const songId = song.id?.trim();
|
||||
if (cover && (!songId || cover !== songId)) return cover;
|
||||
if (albumId) return albumId;
|
||||
if (cover) return cover;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** True when 2+ discs use different cover art ids. */
|
||||
export function albumHasDistinctDiscCovers(
|
||||
songs: ReadonlyArray<Pick<SubsonicSong, 'discNumber' | 'coverArt' | 'id' | 'albumId'>>,
|
||||
): boolean {
|
||||
const artByDisc = new Map<number, string>();
|
||||
for (const song of songs) {
|
||||
const disc = song.discNumber ?? 1;
|
||||
const artId = resolveSongFetchCoverArtId(song);
|
||||
if (!artId) continue;
|
||||
const prev = artByDisc.get(disc);
|
||||
if (prev !== undefined && prev !== artId) return true;
|
||||
artByDisc.set(disc, artId);
|
||||
}
|
||||
if (artByDisc.size <= 1) return false;
|
||||
return new Set(artByDisc.values()).size > 1;
|
||||
}
|
||||
|
||||
/** Album entity — one cache slot per album unless `distinctDiscCovers`. */
|
||||
export function resolveAlbumCoverEntry(
|
||||
albumId: string,
|
||||
coverArtId?: string | null,
|
||||
distinctDiscCovers = false,
|
||||
): CoverEntry | undefined {
|
||||
const album = albumId.trim();
|
||||
if (!album) return undefined;
|
||||
const fetch = (coverArtId?.trim() || album);
|
||||
const cacheEntityId =
|
||||
distinctDiscCovers && fetch !== album ? fetch : album;
|
||||
return { cacheKind: 'album', cacheEntityId, fetchCoverArtId: fetch };
|
||||
}
|
||||
|
||||
/** Artist entity — one cache slot per artist. */
|
||||
export function resolveArtistCoverEntry(
|
||||
artistId: string,
|
||||
coverArtId?: string | null,
|
||||
): CoverEntry | undefined {
|
||||
const artist = artistId.trim();
|
||||
if (!artist) return undefined;
|
||||
const fetch = coverArtId?.trim() || artist;
|
||||
return { cacheKind: 'artist', cacheEntityId: artist, fetchCoverArtId: fetch };
|
||||
}
|
||||
|
||||
/** Track on an album — album cache by default; per-disc fetch id when `distinctDiscCovers`. */
|
||||
export function resolveTrackCoverEntry(
|
||||
song: Pick<SubsonicSong, 'albumId' | 'coverArt' | 'id' | 'discNumber'>,
|
||||
distinctDiscCovers = false,
|
||||
): CoverEntry | undefined {
|
||||
const albumId = song.albumId?.trim();
|
||||
if (!albumId) return undefined;
|
||||
const fetch = resolveSongFetchCoverArtId(song) ?? albumId;
|
||||
return resolveAlbumCoverEntry(albumId, fetch, distinctDiscCovers);
|
||||
}
|
||||
|
||||
export function coverEntryToRef(
|
||||
entry: CoverEntry,
|
||||
serverScope: CoverServerScope = { kind: 'active' },
|
||||
): CoverArtRef {
|
||||
return {
|
||||
cacheKind: entry.cacheKind,
|
||||
cacheEntityId: entry.cacheEntityId,
|
||||
fetchCoverArtId: entry.fetchCoverArtId,
|
||||
serverScope,
|
||||
};
|
||||
}
|
||||
|
||||
/** Artist top tracks: prefer album row `coverArt` when the grid already has it. */
|
||||
/** @deprecated Alias for {@link resolveSongFetchCoverArtId}. */
|
||||
export const resolveSubsonicSongCoverArtId = resolveSongFetchCoverArtId;
|
||||
|
||||
export function resolveArtistPageSongFetchCoverArtId(
|
||||
song: Pick<SubsonicSong, 'id' | 'coverArt' | 'albumId' | 'album' | 'discNumber'>,
|
||||
albums: ReadonlyArray<Pick<SubsonicAlbum, 'id' | 'name' | 'coverArt'>>,
|
||||
): string | undefined {
|
||||
const songArt = resolveSongFetchCoverArtId(song);
|
||||
const album = song.albumId
|
||||
? albums.find(a => a.id === song.albumId)
|
||||
: albums.find(a => a.name === song.album);
|
||||
const albumCover = album?.coverArt?.trim();
|
||||
const songId = song.id?.trim();
|
||||
|
||||
const songRowArt = song.coverArt?.trim();
|
||||
const perDiscArt =
|
||||
Boolean(songArt && albumCover && songArt !== albumCover)
|
||||
&& Boolean(
|
||||
(songRowArt && songRowArt !== songId)
|
||||
|| (songArt?.startsWith('mf-') ?? false),
|
||||
);
|
||||
|
||||
if (perDiscArt && songArt) return songArt;
|
||||
|
||||
if (albumCover && (!songId || albumCover !== songId)) return albumCover;
|
||||
return songArt;
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
/**
|
||||
* Cover resolution backed by the local library index — preferred over live API fields
|
||||
* when the album/artist/track row exists in SQLite.
|
||||
*/
|
||||
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { librarySqlServerId } from '../api/coverCache';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { COVER_SCOPE_ACTIVE, type CoverArtRef, CoverCacheKind, CoverServerScope } from './types';
|
||||
import {
|
||||
coverEntryToRef,
|
||||
resolveAlbumCoverEntry,
|
||||
resolveArtistCoverEntry,
|
||||
resolveTrackCoverEntry,
|
||||
resolveSongFetchCoverArtId,
|
||||
type CoverEntry,
|
||||
} from './resolveEntry';
|
||||
import { resolveDistinctDiscCoversForAlbum } from './ref';
|
||||
import { coverIndexKeyFromScope } from './storageKeys';
|
||||
|
||||
export type LibraryCoverEntryDto = {
|
||||
cacheKind: CoverCacheKind;
|
||||
cacheEntityId: string;
|
||||
fetchCoverArtId: string;
|
||||
};
|
||||
|
||||
export type CoverLibraryEntity = 'album' | 'artist' | 'track';
|
||||
|
||||
function dtoToEntry(dto: LibraryCoverEntryDto): CoverEntry {
|
||||
return {
|
||||
cacheKind: dto.cacheKind,
|
||||
cacheEntityId: dto.cacheEntityId,
|
||||
fetchCoverArtId: dto.fetchCoverArtId,
|
||||
};
|
||||
}
|
||||
|
||||
export function libraryServerIdFromScope(scope: CoverServerScope): string {
|
||||
if (scope.kind === 'server') {
|
||||
return librarySqlServerId(scope.serverId);
|
||||
}
|
||||
const key = coverIndexKeyFromScope(scope);
|
||||
if (key && key !== '_') return librarySqlServerId(key);
|
||||
const active = useAuthStore.getState().activeServerId;
|
||||
return active ? librarySqlServerId(active) : '_';
|
||||
}
|
||||
|
||||
function libraryResolveCacheKey(
|
||||
serverId: string,
|
||||
entity: CoverLibraryEntity,
|
||||
entityId: string,
|
||||
): string {
|
||||
return `${librarySqlServerId(serverId)}\u0000${entity}\u0000${entityId.trim()}`;
|
||||
}
|
||||
|
||||
const resolvedEntryCache = new Map<string, CoverEntry | null>();
|
||||
const inflightResolves = new Map<string, Promise<CoverEntry | null>>();
|
||||
|
||||
const LIBRARY_RESOLVE_MAX_INFLIGHT = 4;
|
||||
let libraryResolveActive = 0;
|
||||
const libraryResolveWaiters: Array<() => void> = [];
|
||||
|
||||
function runLibraryResolveLimited<T>(fn: () => Promise<T>): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const start = () => {
|
||||
libraryResolveActive += 1;
|
||||
fn()
|
||||
.then(resolve, reject)
|
||||
.finally(() => {
|
||||
libraryResolveActive -= 1;
|
||||
const next = libraryResolveWaiters.shift();
|
||||
if (next) next();
|
||||
});
|
||||
};
|
||||
if (libraryResolveActive < LIBRARY_RESOLVE_MAX_INFLIGHT) start();
|
||||
else libraryResolveWaiters.push(start);
|
||||
});
|
||||
}
|
||||
|
||||
export async function libraryResolveCoverEntry(
|
||||
serverId: string,
|
||||
entity: CoverLibraryEntity,
|
||||
entityId: string,
|
||||
): Promise<CoverEntry | null> {
|
||||
const id = entityId.trim();
|
||||
if (!id || !serverId.trim()) return null;
|
||||
|
||||
const key = libraryResolveCacheKey(serverId, entity, id);
|
||||
if (resolvedEntryCache.has(key)) return resolvedEntryCache.get(key) ?? null;
|
||||
|
||||
const inflight = inflightResolves.get(key);
|
||||
if (inflight) return inflight;
|
||||
|
||||
const promise = runLibraryResolveLimited(async () => {
|
||||
try {
|
||||
const dto = await invoke<LibraryCoverEntryDto | null>('library_resolve_cover_entry', {
|
||||
serverId: librarySqlServerId(serverId),
|
||||
entity,
|
||||
entityId: id,
|
||||
});
|
||||
const entry = dto ? dtoToEntry(dto) : null;
|
||||
resolvedEntryCache.set(key, entry);
|
||||
return entry;
|
||||
} catch {
|
||||
resolvedEntryCache.set(key, null);
|
||||
return null;
|
||||
} finally {
|
||||
inflightResolves.delete(key);
|
||||
}
|
||||
});
|
||||
|
||||
inflightResolves.set(key, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
export async function resolveAlbumCoverRefFromLibrary(
|
||||
albumId: string,
|
||||
fallbackCoverArt: string | null | undefined,
|
||||
serverScope: CoverServerScope = COVER_SCOPE_ACTIVE,
|
||||
): Promise<CoverArtRef> {
|
||||
const entry =
|
||||
(await libraryResolveCoverEntry(libraryServerIdFromScope(serverScope), 'album', albumId))
|
||||
?? resolveAlbumCoverEntry(albumId, fallbackCoverArt);
|
||||
return coverEntryToRef(entry!, serverScope);
|
||||
}
|
||||
|
||||
export async function resolveArtistCoverRefFromLibrary(
|
||||
artistId: string,
|
||||
fallbackCoverArt: string | null | undefined,
|
||||
serverScope: CoverServerScope = COVER_SCOPE_ACTIVE,
|
||||
): Promise<CoverArtRef> {
|
||||
const entry =
|
||||
(await libraryResolveCoverEntry(libraryServerIdFromScope(serverScope), 'artist', artistId))
|
||||
?? resolveArtistCoverEntry(artistId, fallbackCoverArt);
|
||||
return coverEntryToRef(entry!, serverScope);
|
||||
}
|
||||
|
||||
function pickTrackCoverEntry(
|
||||
song: Parameters<typeof resolveTrackCoverEntry>[0],
|
||||
fromLibrary: CoverEntry | null,
|
||||
distinctDiscCovers: boolean,
|
||||
): CoverEntry | undefined {
|
||||
const albumId = song.albumId?.trim();
|
||||
const fromClient = resolveTrackCoverEntry(song, distinctDiscCovers);
|
||||
if (!fromLibrary) return fromClient;
|
||||
if (!fromClient) return fromLibrary;
|
||||
|
||||
const songArt = resolveSongFetchCoverArtId(song);
|
||||
const libraryIsAlbumBucket =
|
||||
Boolean(albumId)
|
||||
&& fromLibrary.cacheEntityId === albumId
|
||||
&& fromClient.cacheEntityId !== albumId;
|
||||
|
||||
if (
|
||||
distinctDiscCovers
|
||||
&& libraryIsAlbumBucket
|
||||
&& songArt
|
||||
&& fromClient.fetchCoverArtId === songArt
|
||||
) {
|
||||
return fromClient;
|
||||
}
|
||||
|
||||
if (fromClient.cacheEntityId !== fromLibrary.cacheEntityId && distinctDiscCovers) {
|
||||
return fromClient;
|
||||
}
|
||||
|
||||
return fromLibrary;
|
||||
}
|
||||
|
||||
export async function resolveTrackCoverRefFromLibrary(
|
||||
song: Parameters<typeof resolveTrackCoverEntry>[0],
|
||||
serverScope: CoverServerScope = COVER_SCOPE_ACTIVE,
|
||||
distinctDiscCovers?: boolean,
|
||||
): Promise<CoverArtRef | undefined> {
|
||||
const albumId = song.albumId?.trim();
|
||||
const distinct =
|
||||
distinctDiscCovers
|
||||
?? (albumId ? resolveDistinctDiscCoversForAlbum(albumId, song.coverArt, song) : false);
|
||||
const trackId = song.id?.trim();
|
||||
const fromLibrary = trackId
|
||||
? await libraryResolveCoverEntry(libraryServerIdFromScope(serverScope), 'track', trackId)
|
||||
: null;
|
||||
const entry = pickTrackCoverEntry(song, fromLibrary, distinct);
|
||||
return entry ? coverEntryToRef(entry, serverScope) : undefined;
|
||||
}
|
||||
|
||||
export async function resolveAlbumCoverRefsFromLibrary(
|
||||
albums: ReadonlyArray<{ id: string; coverArt?: string | null }>,
|
||||
serverScope: CoverServerScope = COVER_SCOPE_ACTIVE,
|
||||
): Promise<CoverArtRef[]> {
|
||||
return Promise.all(
|
||||
albums.map(a => resolveAlbumCoverRefFromLibrary(a.id, a.coverArt, serverScope)),
|
||||
);
|
||||
}
|
||||
|
||||
export async function resolveArtistCoverRefsFromLibrary(
|
||||
artists: ReadonlyArray<{ id: string; coverArt?: string | null }>,
|
||||
serverScope: CoverServerScope = COVER_SCOPE_ACTIVE,
|
||||
): Promise<CoverArtRef[]> {
|
||||
return Promise.all(
|
||||
artists.map(a => resolveArtistCoverRefFromLibrary(a.id, a.coverArt, serverScope)),
|
||||
);
|
||||
}
|
||||
|
||||
export async function resolveTrackCoverRefsFromLibrary(
|
||||
songs: ReadonlyArray<Parameters<typeof resolveTrackCoverEntry>[0]>,
|
||||
serverScope: CoverServerScope = COVER_SCOPE_ACTIVE,
|
||||
): Promise<CoverArtRef[]> {
|
||||
const refs = await Promise.all(
|
||||
songs.map(s => resolveTrackCoverRefFromLibrary(s, serverScope)),
|
||||
);
|
||||
return refs.filter((r): r is CoverArtRef => !!r);
|
||||
}
|
||||
@@ -8,9 +8,9 @@ vi.mock('../utils/imageCache', () => ({
|
||||
|
||||
vi.mock('../utils/imageCache/coverSiblings', () => ({
|
||||
parseCoverCacheKey: (key: string) => {
|
||||
const m = key.match(/^(.+):cover:(.+):(\d+)$/);
|
||||
const m = key.match(/^(.+):cover:(.+):(.+):(\d+)$/);
|
||||
if (!m) return null;
|
||||
return { stem: `${m[1]}:cover:${m[2]}`, size: Number(m[3]) };
|
||||
return { stem: `${m[1]}:cover:${m[2]}:${m[3]}`, size: Number(m[4]) };
|
||||
},
|
||||
probeSiblingCoverBlobInMemory: () => null,
|
||||
probeSiblingCoverBlobFromIDB: async () => null,
|
||||
@@ -38,7 +38,9 @@ vi.mock('./fetchUrl', () => ({
|
||||
}));
|
||||
|
||||
const ref: CoverArtRef = {
|
||||
coverArtId: 'al-1',
|
||||
cacheKind: 'album',
|
||||
cacheEntityId: 'al-1',
|
||||
fetchCoverArtId: 'al-1',
|
||||
serverScope: { kind: 'active' },
|
||||
};
|
||||
|
||||
@@ -48,7 +50,7 @@ describe('ensureCoverTierJs', () => {
|
||||
});
|
||||
|
||||
it('returns null when cover id missing', async () => {
|
||||
expect(await ensureCoverTierJs({ ...ref, coverArtId: '' }, 128)).toBeNull();
|
||||
expect(await ensureCoverTierJs({ ...ref, fetchCoverArtId: '' }, 128)).toBeNull();
|
||||
});
|
||||
|
||||
it('fetches via getCachedBlob on cold path', async () => {
|
||||
|
||||
@@ -13,7 +13,7 @@ import { rememberBlob } from '../utils/imageCache/blobCache';
|
||||
import { putBlob } from '../utils/imageCache/idbStore';
|
||||
import { buildCoverArtFetchUrl } from './fetchUrl';
|
||||
import { coverServerReachable } from './reachability';
|
||||
import { coverStorageKey } from './storageKeys';
|
||||
import { coverStorageKeyFromRef } from './storageKeys';
|
||||
import type { CoverArtRef, CoverArtTier } from './types';
|
||||
|
||||
const CANONICAL_TIER = 800 as CoverArtTier;
|
||||
@@ -40,8 +40,8 @@ async function scheduleColdCoverRace(
|
||||
signal: AbortSignal | undefined,
|
||||
getPriority?: () => number,
|
||||
): Promise<Blob | null> {
|
||||
const targetKey = coverStorageKey(ref.serverScope, ref.coverArtId, tier);
|
||||
const canonicalKey = coverStorageKey(ref.serverScope, ref.coverArtId, CANONICAL_TIER);
|
||||
const targetKey = coverStorageKeyFromRef(ref, tier);
|
||||
const canonicalKey = coverStorageKeyFromRef(ref, CANONICAL_TIER);
|
||||
const chainCtl = new AbortController();
|
||||
const directCtl = new AbortController();
|
||||
let winner = false;
|
||||
@@ -96,9 +96,9 @@ export async function ensureCoverTierJs(
|
||||
signal?: AbortSignal,
|
||||
getPriority?: () => number,
|
||||
): Promise<Blob | null> {
|
||||
if (!ref.coverArtId || signal?.aborted) return null;
|
||||
if (!ref.fetchCoverArtId || signal?.aborted) return null;
|
||||
|
||||
const cacheKey = coverStorageKey(ref.serverScope, ref.coverArtId, tier);
|
||||
const cacheKey = coverStorageKeyFromRef(ref, tier);
|
||||
const mem = blobCache.get(cacheKey);
|
||||
if (mem) return mem;
|
||||
|
||||
@@ -128,7 +128,7 @@ export async function ensureCoverTierJs(
|
||||
return getCachedBlob(buildCoverArtFetchUrl(ref, 2000), cacheKey, signal, getPriority);
|
||||
}
|
||||
|
||||
const canonicalKey = coverStorageKey(ref.serverScope, ref.coverArtId, CANONICAL_TIER);
|
||||
const canonicalKey = coverStorageKeyFromRef(ref, CANONICAL_TIER);
|
||||
const hasChain =
|
||||
blobCache.has(canonicalKey) ||
|
||||
(parsed && (await probeSiblingCoverBlobFromIDB(parsed.stem, parsed.size)) !== null);
|
||||
|
||||
@@ -36,9 +36,9 @@ describe('coverStorageKey', () => {
|
||||
});
|
||||
|
||||
it('uses host index key for active scope (not profile uuid)', () => {
|
||||
expect(coverStorageKey({ kind: 'active' }, 'al-42', 128)).toBe(
|
||||
'music.local:4533:cover:al-42:128',
|
||||
);
|
||||
expect(
|
||||
coverStorageKey({ kind: 'active' }, { cacheKind: 'album', cacheEntityId: 'al-42' }, 128),
|
||||
).toBe('music.local:4533:cover:album:al-42:128');
|
||||
});
|
||||
|
||||
it('uses host index key from explicit server url', () => {
|
||||
@@ -51,10 +51,10 @@ describe('coverStorageKey', () => {
|
||||
username: 'u',
|
||||
password: 'p',
|
||||
},
|
||||
'ar-1',
|
||||
{ cacheKind: 'artist', cacheEntityId: 'ar-1' },
|
||||
512,
|
||||
),
|
||||
).toBe('nav.example.com/navidrome:cover:ar-1:512');
|
||||
).toBe('nav.example.com/navidrome:cover:artist:ar-1:512');
|
||||
});
|
||||
|
||||
it('coverIndexKeyFromScope matches library-style keys', () => {
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { getPlaybackServerId } from '../utils/playback/playbackServer';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { findServerByIdOrIndexKey } from '../utils/server/serverLookup';
|
||||
import {
|
||||
resolveIndexKey,
|
||||
serverIndexKeyForProfile,
|
||||
serverIndexKeyFromUrl,
|
||||
} from '../utils/server/serverIndexKey';
|
||||
import type { CoverArtId, CoverArtRef, CoverArtTier, CoverServerScope } from './types';
|
||||
import type { CoverArtRef, CoverArtTier, CoverServerScope } from './types';
|
||||
|
||||
/**
|
||||
* Stable server bucket for cover disk + IDB — same host index key as library SQLite (`server_id` column).
|
||||
@@ -18,10 +20,9 @@ export function coverIndexKeyFromScope(scope: CoverServerScope): string {
|
||||
const playbackSid = getPlaybackServerId();
|
||||
const activeSid = useAuthStore.getState().activeServerId;
|
||||
const sid = playbackSid || activeSid;
|
||||
const server = sid
|
||||
? useAuthStore.getState().servers.find(s => s.id === sid)
|
||||
: undefined;
|
||||
const server = sid ? findServerByIdOrIndexKey(sid) : undefined;
|
||||
if (server) return serverIndexKeyForProfile(server);
|
||||
if (sid) return resolveIndexKey(sid) || sid;
|
||||
return '_';
|
||||
}
|
||||
const server = useAuthStore.getState().getActiveServer();
|
||||
@@ -38,8 +39,12 @@ export const serverIdFromScope = coverIndexKeyFromScope;
|
||||
|
||||
export function coverStorageKey(
|
||||
serverScope: CoverServerScope,
|
||||
coverArtId: CoverArtId,
|
||||
ref: Pick<CoverArtRef, 'cacheKind' | 'cacheEntityId'>,
|
||||
tier: CoverArtTier,
|
||||
): string {
|
||||
return `${coverIndexKeyFromScope(serverScope)}:cover:${coverArtId}:${tier}`;
|
||||
return `${coverIndexKeyFromScope(serverScope)}:cover:${ref.cacheKind}:${ref.cacheEntityId}:${tier}`;
|
||||
}
|
||||
|
||||
export function coverStorageKeyFromRef(ref: CoverArtRef, tier: CoverArtTier): string {
|
||||
return coverStorageKey(ref.serverScope, ref, tier);
|
||||
}
|
||||
|
||||
+18
-2
@@ -1,6 +1,8 @@
|
||||
/** Subsonic / Navidrome cover art ID passed to getCoverArt.view */
|
||||
/** Subsonic / Navidrome id passed to `getCoverArt.view` (`al-*`, `ar-*`, …). */
|
||||
export type CoverArtId = string;
|
||||
|
||||
export type CoverCacheKind = 'album' | 'artist';
|
||||
|
||||
/** Fixed storage / server-request tiers */
|
||||
export const COVER_ART_TIERS = [64, 128, 256, 512, 800, 2000] as const;
|
||||
|
||||
@@ -14,12 +16,26 @@ export type CoverServerScope =
|
||||
| { kind: 'playback' }
|
||||
| { kind: 'server'; serverId: string; url: string; username: string; password: string };
|
||||
|
||||
/** Stable singleton — never inline `{ kind: 'active' }` in hook deps or default params. */
|
||||
export const COVER_SCOPE_ACTIVE: CoverServerScope = { kind: 'active' };
|
||||
|
||||
export function coverScopeKey(scope: CoverServerScope): string {
|
||||
if (scope.kind === 'active') return 'active';
|
||||
if (scope.kind === 'playback') return 'playback';
|
||||
return `server:${scope.serverId}`;
|
||||
}
|
||||
|
||||
export type CoverSurfaceKind = 'dense' | 'sparse';
|
||||
|
||||
export type CoverPrefetchPriority = 'high' | 'middle' | 'low';
|
||||
|
||||
/** Disk cache is keyed by `cacheKind` + `cacheEntityId`; HTTP uses `fetchCoverArtId`. */
|
||||
export type CoverArtRef = {
|
||||
coverArtId: CoverArtId;
|
||||
cacheKind: CoverCacheKind;
|
||||
/** Disk segment — usually `al-*` / `ar-*`; per-CD `mf-*` only when album has distinct disc art. */
|
||||
cacheEntityId: string;
|
||||
/** Navidrome `getCoverArt` id — usually matches `cacheEntityId`; may differ only transiently. */
|
||||
fetchCoverArtId: CoverArtId;
|
||||
serverScope: CoverServerScope;
|
||||
};
|
||||
|
||||
|
||||
+18
-36
@@ -3,22 +3,18 @@ import { coverEnsureQueued, coverEnsureRelease } from './ensureQueue';
|
||||
import { coverPeekQueued } from './peekQueue';
|
||||
import { getDiskSrcForGrid, seedGridDiskSrcCache } from './diskSrcLookup';
|
||||
import {
|
||||
forgetDiskSrc,
|
||||
getDiskSrc,
|
||||
forgetDiskSrcPrefix,
|
||||
getDiskSrcCacheGeneration,
|
||||
rememberDiskSrc,
|
||||
subscribeDiskSrcCache,
|
||||
} from './diskSrcCache';
|
||||
import { subscribeCoverDiskReady } from './diskHandoff';
|
||||
import { coverArtRef } from './ref';
|
||||
import { coverServerReachable } from './reachability';
|
||||
import { coverStorageKey } from './storageKeys';
|
||||
import { coverStorageKeyFromRef } from './storageKeys';
|
||||
import { resolveCoverDisplayTier } from './tiers';
|
||||
import type {
|
||||
CoverArtHandle,
|
||||
CoverArtId,
|
||||
CoverArtRef,
|
||||
CoverPrefetchPriority,
|
||||
CoverServerScope,
|
||||
CoverSurfaceKind,
|
||||
} from './types';
|
||||
|
||||
@@ -26,73 +22,58 @@ import type {
|
||||
* Disk cache in Rust (WebP tiers) — no webview `getCoverArt` fetch when server is reachable.
|
||||
*/
|
||||
export function useCoverArt(
|
||||
coverArtId: CoverArtId | null | undefined,
|
||||
coverRef: CoverArtRef | null | undefined,
|
||||
displayCssPx: number,
|
||||
opts?: {
|
||||
serverScope?: CoverServerScope;
|
||||
surface?: CoverSurfaceKind;
|
||||
fullRes?: boolean;
|
||||
fetchQueueBias?: number;
|
||||
observeRootMargin?: string;
|
||||
alt?: string;
|
||||
/** Download / ensure ordering — visible cells should pass `high`. */
|
||||
ensurePriority?: CoverPrefetchPriority;
|
||||
},
|
||||
): CoverArtHandle {
|
||||
const serverScope = opts?.serverScope ?? { kind: 'active' };
|
||||
const ref = coverRef ?? null;
|
||||
const surface = opts?.surface ?? 'sparse';
|
||||
const reachable = coverServerReachable(serverScope);
|
||||
const reachable = ref ? coverServerReachable(ref.serverScope) : false;
|
||||
|
||||
const tier = useMemo(
|
||||
() =>
|
||||
coverArtId
|
||||
ref
|
||||
? resolveCoverDisplayTier(displayCssPx, {
|
||||
surface,
|
||||
fullRes: opts?.fullRes,
|
||||
})
|
||||
: 128,
|
||||
[coverArtId, displayCssPx, surface, opts?.fullRes],
|
||||
);
|
||||
|
||||
const ref = useMemo(
|
||||
() => (coverArtId ? coverArtRef(coverArtId, serverScope) : null),
|
||||
[coverArtId, serverScope],
|
||||
[ref, displayCssPx, surface, opts?.fullRes],
|
||||
);
|
||||
|
||||
const storageKey = useMemo(
|
||||
() => (ref ? coverStorageKey(ref.serverScope, ref.coverArtId, tier) : ''),
|
||||
() => (ref ? coverStorageKeyFromRef(ref, tier) : ''),
|
||||
[ref, tier],
|
||||
);
|
||||
|
||||
const ensurePriority: CoverPrefetchPriority = opts?.ensurePriority ?? 'middle';
|
||||
|
||||
/** Dense grids: peek on mount; HTTP ensure only when IO marks the cell `high`. */
|
||||
const deferEnsureUntilVisible = surface === 'dense' && ensurePriority !== 'high';
|
||||
|
||||
const readCachedSrc = useCallback(() => {
|
||||
if (!ref) return '';
|
||||
if (surface === 'dense') {
|
||||
return getDiskSrcForGrid(ref.serverScope, ref.coverArtId, tier);
|
||||
}
|
||||
return getDiskSrc(storageKey);
|
||||
}, [ref, storageKey, surface, tier]);
|
||||
return getDiskSrcForGrid(ref, tier);
|
||||
}, [ref, tier]);
|
||||
|
||||
useSyncExternalStore(subscribeDiskSrcCache, getDiskSrcCacheGeneration);
|
||||
|
||||
const cachedSrc = readCachedSrc();
|
||||
|
||||
const applyDiskPath = useCallback((path: string) => {
|
||||
if (!ref || !storageKey) return;
|
||||
if (!ref) return;
|
||||
if (!path) {
|
||||
forgetDiskSrc(storageKey);
|
||||
forgetDiskSrcPrefix(ref);
|
||||
return;
|
||||
}
|
||||
if (surface === 'dense') {
|
||||
seedGridDiskSrcCache(ref.serverScope, ref.coverArtId, tier, path);
|
||||
} else {
|
||||
rememberDiskSrc(storageKey, path);
|
||||
}
|
||||
}, [ref, storageKey, tier, surface, readCachedSrc]);
|
||||
seedGridDiskSrcCache(ref, tier, path);
|
||||
}, [ref, tier]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ref || !storageKey) return;
|
||||
@@ -139,8 +120,9 @@ export function useCoverArt(
|
||||
const provisional = Boolean(ref && storageKey && !src);
|
||||
|
||||
const onImgError = useCallback(() => {
|
||||
forgetDiskSrc(storageKey);
|
||||
if (ref && reachable) {
|
||||
if (!ref) return;
|
||||
forgetDiskSrcPrefix(ref);
|
||||
if (reachable) {
|
||||
void coverEnsureQueued(storageKey, ref, tier, 'high').then(result => {
|
||||
if (result.hit && result.path) applyDiskPath(result.path);
|
||||
});
|
||||
|
||||
@@ -6,7 +6,7 @@ import { useAuthStore } from '../store/authStore';
|
||||
import { coverPrefetchDrainBatch } from './prefetchRegistry';
|
||||
import { coverTrafficBackgroundPaused } from './coverTraffic';
|
||||
import { coverEnsureQueued } from './ensureQueue';
|
||||
import { coverStorageKey } from './storageKeys';
|
||||
import { coverStorageKeyFromRef } from './storageKeys';
|
||||
import { resolveCoverDisplayTier } from './tiers';
|
||||
import type { CoverArtTier } from './types';
|
||||
|
||||
@@ -43,7 +43,7 @@ export function useCoverArtPrefetch(enabled = true): void {
|
||||
if (batch.length > 0) {
|
||||
await Promise.all(
|
||||
batch.map(ref => {
|
||||
const key = coverStorageKey(ref.serverScope, ref.coverArtId, DENSE_PREFETCH_TIER);
|
||||
const key = coverStorageKeyFromRef(ref, DENSE_PREFETCH_TIER);
|
||||
return coverEnsureQueued(key, ref, DENSE_PREFETCH_TIER, 'low');
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { useEffect } from 'react';
|
||||
import type { SubsonicSong } from '../api/subsonicTypes';
|
||||
import { coverPrefetchRegister } from './prefetchRegistry';
|
||||
import {
|
||||
resolveAlbumCoverRefsFromLibrary,
|
||||
resolveArtistCoverRefsFromLibrary,
|
||||
resolveTrackCoverRefsFromLibrary,
|
||||
} from './resolveEntryLibrary';
|
||||
import { COVER_SCOPE_ACTIVE, type CoverPrefetchPriority, type CoverServerScope, type CoverSurfaceKind } from './types';
|
||||
|
||||
export type LibraryCoverPrefetchBucket = {
|
||||
albums?: ReadonlyArray<{ id: string; coverArt?: string | null }>;
|
||||
artists?: ReadonlyArray<{ id: string; coverArt?: string | null }>;
|
||||
songs?: ReadonlyArray<Pick<SubsonicSong, 'id' | 'albumId' | 'coverArt' | 'discNumber'>>;
|
||||
limit?: number;
|
||||
priority: CoverPrefetchPriority;
|
||||
surface?: CoverSurfaceKind;
|
||||
serverScope?: CoverServerScope;
|
||||
};
|
||||
|
||||
/** Register cover prefetch after resolving refs from the local library index. */
|
||||
export function useLibraryCoverPrefetch(
|
||||
buckets: LibraryCoverPrefetchBucket[],
|
||||
deps: readonly unknown[],
|
||||
): void {
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const unregisters: Array<() => void> = [];
|
||||
|
||||
void (async () => {
|
||||
for (const bucket of buckets) {
|
||||
const scope = bucket.serverScope ?? COVER_SCOPE_ACTIVE;
|
||||
const refs = [
|
||||
...(bucket.albums?.length
|
||||
? await resolveAlbumCoverRefsFromLibrary(bucket.albums, scope)
|
||||
: []),
|
||||
...(bucket.artists?.length
|
||||
? await resolveArtistCoverRefsFromLibrary(bucket.artists, scope)
|
||||
: []),
|
||||
...(bucket.songs?.length
|
||||
? await resolveTrackCoverRefsFromLibrary(bucket.songs, scope)
|
||||
: []),
|
||||
];
|
||||
const capped = bucket.limit != null ? refs.slice(0, bucket.limit) : refs;
|
||||
if (cancelled || capped.length === 0) continue;
|
||||
unregisters.push(
|
||||
coverPrefetchRegister(capped, {
|
||||
surface: bucket.surface ?? 'dense',
|
||||
priority: bucket.priority,
|
||||
}),
|
||||
);
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
for (const unreg of unregisters) unreg();
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- caller supplies `deps` for bucket inputs
|
||||
}, deps);
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
import { useEffect, useMemo, useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import type { SubsonicSong } from '../api/subsonicTypes';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { usePlayerStore } from '../store/playerStore';
|
||||
import {
|
||||
albumCoverRef,
|
||||
albumCoverRefForPlayback,
|
||||
albumCoverRefForSong,
|
||||
artistCoverRef,
|
||||
resolveDistinctDiscCoversForAlbum,
|
||||
resolvePlaybackCoverScope,
|
||||
} from './ref';
|
||||
import {
|
||||
resolveAlbumCoverRefFromLibrary,
|
||||
resolveArtistCoverRefFromLibrary,
|
||||
resolveTrackCoverRefFromLibrary,
|
||||
} from './resolveEntryLibrary';
|
||||
import { COVER_SCOPE_ACTIVE, coverScopeKey, type CoverArtRef, type CoverServerScope } from './types';
|
||||
|
||||
function coverRefsEqual(a: CoverArtRef, b: CoverArtRef): boolean {
|
||||
return (
|
||||
a.cacheKind === b.cacheKind
|
||||
&& a.cacheEntityId === b.cacheEntityId
|
||||
&& a.fetchCoverArtId === b.fetchCoverArtId
|
||||
);
|
||||
}
|
||||
|
||||
function applySyncRef<T extends CoverArtRef | null | undefined>(
|
||||
setRef: Dispatch<SetStateAction<T>>,
|
||||
syncRef: T,
|
||||
): void {
|
||||
setRef(prev => {
|
||||
if (!syncRef) return syncRef;
|
||||
if (prev && coverRefsEqual(prev, syncRef)) return prev;
|
||||
return syncRef;
|
||||
});
|
||||
}
|
||||
|
||||
export type LibraryCoverRefOptions = {
|
||||
/**
|
||||
* When false, use API/index `coverArt` only — no per-mount `library_resolve_cover_entry`.
|
||||
* Default for browse/search grids is false at the component layer; enable on album/artist
|
||||
* detail headers and queue rows that need per-disc slots from SQLite.
|
||||
*/
|
||||
libraryResolve?: boolean;
|
||||
};
|
||||
|
||||
/** Album grid / card — sync fallback, then local library index when indexed. */
|
||||
export function useAlbumCoverRef(
|
||||
albumId: string | null | undefined,
|
||||
fallbackCoverArt?: string | null,
|
||||
serverScope: CoverServerScope = COVER_SCOPE_ACTIVE,
|
||||
options?: LibraryCoverRefOptions,
|
||||
): CoverArtRef | null {
|
||||
const libraryResolve = options?.libraryResolve !== false;
|
||||
const scopeKey = coverScopeKey(serverScope);
|
||||
const distinctDiscCovers = useMemo(
|
||||
() => resolveDistinctDiscCoversForAlbum(albumId ?? '', fallbackCoverArt),
|
||||
[albumId, fallbackCoverArt],
|
||||
);
|
||||
const syncRef = useMemo(() => {
|
||||
const id = albumId?.trim();
|
||||
if (!id) return null;
|
||||
return albumCoverRef(id, fallbackCoverArt, { serverScope, distinctDiscCovers });
|
||||
}, [albumId, fallbackCoverArt, scopeKey, serverScope, distinctDiscCovers]);
|
||||
|
||||
const [ref, setRef] = useState<CoverArtRef | null>(syncRef);
|
||||
|
||||
useEffect(() => {
|
||||
applySyncRef(setRef, syncRef);
|
||||
if (!libraryResolve) return;
|
||||
const id = albumId?.trim();
|
||||
if (!id) return;
|
||||
let cancelled = false;
|
||||
void resolveAlbumCoverRefFromLibrary(id, fallbackCoverArt, serverScope).then(next => {
|
||||
if (!cancelled) {
|
||||
setRef(prev => (prev && coverRefsEqual(prev, next) ? prev : next));
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [albumId, fallbackCoverArt, scopeKey, syncRef, libraryResolve]);
|
||||
|
||||
return libraryResolve ? ref : syncRef;
|
||||
}
|
||||
|
||||
/** Artist grid — sync fallback, then library index. */
|
||||
export function useArtistCoverRef(
|
||||
artistId: string | null | undefined,
|
||||
fallbackCoverArt?: string | null,
|
||||
serverScope: CoverServerScope = COVER_SCOPE_ACTIVE,
|
||||
options?: LibraryCoverRefOptions,
|
||||
): CoverArtRef | null {
|
||||
const libraryResolve = options?.libraryResolve !== false;
|
||||
const scopeKey = coverScopeKey(serverScope);
|
||||
const syncRef = useMemo(() => {
|
||||
const id = artistId?.trim();
|
||||
if (!id) return null;
|
||||
return artistCoverRef(id, fallbackCoverArt, serverScope);
|
||||
}, [artistId, fallbackCoverArt, scopeKey, serverScope]);
|
||||
|
||||
const [ref, setRef] = useState<CoverArtRef | null>(syncRef);
|
||||
|
||||
useEffect(() => {
|
||||
applySyncRef(setRef, syncRef);
|
||||
if (!libraryResolve) return;
|
||||
const id = artistId?.trim();
|
||||
if (!id) return;
|
||||
let cancelled = false;
|
||||
void resolveArtistCoverRefFromLibrary(id, fallbackCoverArt, serverScope).then(next => {
|
||||
if (!cancelled) {
|
||||
setRef(prev => (prev && coverRefsEqual(prev, next) ? prev : next));
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [artistId, fallbackCoverArt, scopeKey, syncRef, libraryResolve]);
|
||||
|
||||
return libraryResolve ? ref : syncRef;
|
||||
}
|
||||
|
||||
/** Track row / song card — album-scoped; multi-CD from library when indexed. */
|
||||
export function useTrackCoverRef(
|
||||
song: Pick<SubsonicSong, 'id' | 'albumId' | 'coverArt' | 'discNumber'> | null | undefined,
|
||||
serverScope: CoverServerScope = COVER_SCOPE_ACTIVE,
|
||||
options?: LibraryCoverRefOptions,
|
||||
): CoverArtRef | undefined {
|
||||
const libraryResolve = options?.libraryResolve !== false;
|
||||
const scopeKey = coverScopeKey(serverScope);
|
||||
const songId = song?.id;
|
||||
const albumId = song?.albumId;
|
||||
const coverArt = song?.coverArt;
|
||||
const discNumber = song?.discNumber;
|
||||
|
||||
const distinctDiscCovers = useMemo(
|
||||
() => (albumId?.trim()
|
||||
? resolveDistinctDiscCoversForAlbum(albumId, coverArt, {
|
||||
id: songId ?? '',
|
||||
albumId,
|
||||
coverArt,
|
||||
discNumber,
|
||||
})
|
||||
: false),
|
||||
[albumId, coverArt, discNumber, songId],
|
||||
);
|
||||
|
||||
const syncRef = useMemo(() => {
|
||||
if (!songId?.trim() || !albumId?.trim()) return undefined;
|
||||
return albumCoverRefForSong(
|
||||
{ id: songId, albumId, coverArt, discNumber },
|
||||
distinctDiscCovers,
|
||||
);
|
||||
}, [songId, albumId, coverArt, discNumber, distinctDiscCovers]);
|
||||
|
||||
const [ref, setRef] = useState<CoverArtRef | undefined>(syncRef);
|
||||
|
||||
useEffect(() => {
|
||||
applySyncRef(setRef, syncRef);
|
||||
if (!libraryResolve) return;
|
||||
const trackId = songId?.trim();
|
||||
const al = albumId?.trim();
|
||||
if (!trackId || !al || !song) return;
|
||||
let cancelled = false;
|
||||
void resolveTrackCoverRefFromLibrary(
|
||||
{ ...song, id: trackId, albumId: al },
|
||||
serverScope,
|
||||
distinctDiscCovers,
|
||||
).then(next => {
|
||||
if (!cancelled) {
|
||||
setRef(prev => {
|
||||
if (!next) return undefined;
|
||||
if (
|
||||
prev
|
||||
&& prev.cacheKind === 'album'
|
||||
&& next.cacheKind === 'album'
|
||||
&& al
|
||||
&& next.cacheEntityId === al
|
||||
&& prev.cacheEntityId !== al
|
||||
&& prev.fetchCoverArtId !== next.fetchCoverArtId
|
||||
) {
|
||||
return prev;
|
||||
}
|
||||
if (prev && coverRefsEqual(prev, next)) return prev;
|
||||
return next;
|
||||
});
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [song, songId, albumId, coverArt, discNumber, scopeKey, syncRef, libraryResolve, distinctDiscCovers]);
|
||||
|
||||
return libraryResolve ? ref : syncRef;
|
||||
}
|
||||
|
||||
/** Now playing / queue — playback server scope + library-backed multi-CD. */
|
||||
export function usePlaybackTrackCoverRef(
|
||||
track: Parameters<typeof albumCoverRefForPlayback>[0] | null | undefined,
|
||||
): CoverArtRef | undefined {
|
||||
const queueServerId = usePlayerStore(s => s.queueServerId);
|
||||
const queueLength = usePlayerStore(s => s.queueItems.length);
|
||||
const activeServerId = useAuthStore(s => s.activeServerId);
|
||||
const serversFingerprint = useAuthStore(s =>
|
||||
s.servers
|
||||
.map(srv => `${srv.id}\u0001${srv.url}\u0001${srv.username}\u0001${srv.password}`)
|
||||
.join('\u0002'),
|
||||
);
|
||||
|
||||
const scope = useMemo(
|
||||
() => resolvePlaybackCoverScope(),
|
||||
[queueServerId, queueLength, activeServerId, serversFingerprint],
|
||||
);
|
||||
const scopeKey = coverScopeKey(scope);
|
||||
|
||||
const trackId = track?.id;
|
||||
const albumId = track?.albumId;
|
||||
const coverArt = track?.coverArt;
|
||||
const discNumber = track?.discNumber;
|
||||
|
||||
const syncRef = useMemo(() => {
|
||||
if (!albumId?.trim() || !track) return undefined;
|
||||
return albumCoverRefForPlayback(track, scope);
|
||||
}, [track, trackId, albumId, coverArt, discNumber, scopeKey]);
|
||||
|
||||
const [ref, setRef] = useState<CoverArtRef | undefined>(syncRef);
|
||||
|
||||
useEffect(() => {
|
||||
applySyncRef(setRef, syncRef);
|
||||
const tid = trackId?.trim();
|
||||
const al = albumId?.trim();
|
||||
if (!tid || !al || !track) return;
|
||||
let cancelled = false;
|
||||
const distinctDiscCovers = resolveDistinctDiscCoversForAlbum(al, track.coverArt, {
|
||||
id: tid,
|
||||
albumId: al,
|
||||
coverArt: track.coverArt,
|
||||
discNumber: track.discNumber,
|
||||
});
|
||||
void resolveTrackCoverRefFromLibrary(
|
||||
{ ...track, id: tid, albumId: al } as Pick<SubsonicSong, 'id' | 'albumId' | 'coverArt' | 'discNumber'>,
|
||||
scope,
|
||||
distinctDiscCovers,
|
||||
).then(next => {
|
||||
if (!cancelled) {
|
||||
setRef(prev => {
|
||||
if (!next) return prev ?? next;
|
||||
if (
|
||||
prev
|
||||
&& prev.cacheKind === 'album'
|
||||
&& next.cacheKind === 'album'
|
||||
&& next.cacheEntityId === al
|
||||
&& prev.cacheEntityId !== al
|
||||
&& prev.fetchCoverArtId !== next.fetchCoverArtId
|
||||
) {
|
||||
return prev;
|
||||
}
|
||||
if (prev && coverRefsEqual(prev, next)) return prev;
|
||||
return next;
|
||||
});
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [track, trackId, albumId, coverArt, discNumber, scopeKey, syncRef]);
|
||||
|
||||
return ref;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { CoverArtHandle } from './types';
|
||||
import { albumCoverRef } from './ref';
|
||||
import { usePlaybackCoverArt } from './usePlaybackCoverArt';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { usePlayerStore } from '../store/playerStore';
|
||||
@@ -10,7 +11,7 @@ import { toQueueItemRefs } from '../utils/library/queueItemRef';
|
||||
|
||||
const hoisted = vi.hoisted(() => ({
|
||||
useCoverArtMock: vi.fn(
|
||||
(_coverArtId?: unknown, _displayCssPx?: unknown, _opts?: unknown): CoverArtHandle => ({
|
||||
(_coverRef?: unknown, _displayCssPx?: unknown, _opts?: unknown): CoverArtHandle => ({
|
||||
src: '',
|
||||
storageKey: '',
|
||||
cacheKey: '',
|
||||
@@ -24,7 +25,7 @@ vi.mock('./useCoverArt', () => ({
|
||||
useCoverArt: hoisted.useCoverArtMock,
|
||||
}));
|
||||
|
||||
function seedPlaybackState(): { active: string; playback: string } {
|
||||
function seedPlaybackState(): { active: string; playback: string; track: ReturnType<typeof makeTrack> } {
|
||||
const active = useAuthStore.getState().addServer({
|
||||
name: 'Active',
|
||||
url: 'https://active.test',
|
||||
@@ -38,14 +39,14 @@ function seedPlaybackState(): { active: string; playback: string } {
|
||||
password: 'play-pass',
|
||||
});
|
||||
useAuthStore.getState().setActiveServer(active);
|
||||
const track = makeTrack({ id: 'song-1', coverArt: 'cover-1' });
|
||||
const track = makeTrack({ id: 'song-1', albumId: 'album-1', coverArt: 'cover-1' });
|
||||
usePlayerStore.setState({
|
||||
queueItems: toQueueItemRefs(playback, [track]),
|
||||
queueIndex: 0,
|
||||
queueServerId: playback,
|
||||
currentTrack: track,
|
||||
});
|
||||
return { active, playback };
|
||||
return { active, playback, track };
|
||||
}
|
||||
|
||||
describe('usePlaybackCoverArt', () => {
|
||||
@@ -55,13 +56,14 @@ describe('usePlaybackCoverArt', () => {
|
||||
});
|
||||
|
||||
it('recomputes server scope when playback server credentials change', async () => {
|
||||
const { playback } = seedPlaybackState();
|
||||
const { rerender } = renderHook(() => usePlaybackCoverArt('cover-1', 300));
|
||||
const { playback, track } = seedPlaybackState();
|
||||
const coverRef = albumCoverRef(track.albumId!, track.coverArt!);
|
||||
const { rerender } = renderHook(() => usePlaybackCoverArt(coverRef, 300));
|
||||
|
||||
const calls = hoisted.useCoverArtMock.mock.calls as Array<
|
||||
[unknown, unknown, { serverScope?: Record<string, unknown> }]
|
||||
[{ serverScope?: Record<string, unknown> } | null, unknown, unknown]
|
||||
>;
|
||||
const firstScope = calls[0]?.[2]?.serverScope;
|
||||
const firstScope = calls[0]?.[0]?.serverScope;
|
||||
expect(firstScope).toMatchObject({
|
||||
kind: 'server',
|
||||
serverId: playback,
|
||||
@@ -79,7 +81,7 @@ describe('usePlaybackCoverArt', () => {
|
||||
rerender();
|
||||
|
||||
await waitFor(() => {
|
||||
const latestScope = calls[calls.length - 1]?.[2]?.serverScope;
|
||||
const latestScope = calls[calls.length - 1]?.[0]?.serverScope;
|
||||
expect(latestScope).toMatchObject({
|
||||
kind: 'server',
|
||||
serverId: playback,
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { useMemo } from 'react';
|
||||
import { resolvePlaybackCoverScope } from './ref';
|
||||
import type { CoverArtHandle, CoverArtId } from './types';
|
||||
import type { CoverArtHandle, CoverArtRef } from './types';
|
||||
import { useCoverArt } from './useCoverArt';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { usePlayerStore } from '../store/playerStore';
|
||||
|
||||
/** Cover art for playback queue — uses queue server when it differs from browsed server. */
|
||||
export function usePlaybackCoverArt(
|
||||
coverArtId: CoverArtId | undefined,
|
||||
coverRef: CoverArtRef | undefined,
|
||||
displayCssPx: number,
|
||||
): CoverArtHandle {
|
||||
const queueServerId = usePlayerStore(s => s.queueServerId);
|
||||
@@ -23,8 +23,11 @@ export function usePlaybackCoverArt(
|
||||
() => resolvePlaybackCoverScope(),
|
||||
[queueServerId, queueLength, activeServerId, serversFingerprint],
|
||||
);
|
||||
return useCoverArt(coverArtId, displayCssPx, {
|
||||
serverScope: scope,
|
||||
const refWithScope = useMemo(
|
||||
() => (coverRef ? { ...coverRef, serverScope: scope } : null),
|
||||
[coverRef, scope],
|
||||
);
|
||||
return useCoverArt(refWithScope, displayCssPx, {
|
||||
surface: 'sparse',
|
||||
});
|
||||
}
|
||||
|
||||
+79
-42
@@ -2,8 +2,9 @@ import { coverCachePeekBatch } from '../api/coverCache';
|
||||
import type { SubsonicAlbum } from '../api/subsonicTypes';
|
||||
import { coverEnsureQueued } from './ensureQueue';
|
||||
import { getDiskSrcForGrid, rememberGridDiskSrc } from './diskSrcLookup';
|
||||
import { coverArtRef } from './ref';
|
||||
import { coverIndexKeyFromRef, coverStorageKey } from './storageKeys';
|
||||
import { albumCoverRef } from './ref';
|
||||
import { resolveAlbumCoverRefFromLibrary } from './resolveEntryLibrary';
|
||||
import { coverStorageKeyFromRef } from './storageKeys';
|
||||
import { resolveCoverDisplayTier } from './tiers';
|
||||
import type { CoverArtRef, CoverArtTier, CoverSurfaceKind } from './types';
|
||||
|
||||
@@ -13,30 +14,66 @@ export type CoverWarmItem = {
|
||||
storageKey: string;
|
||||
};
|
||||
|
||||
/** @deprecated Sync fallback — prefer {@link coverWarmItemFromLibrary}. */
|
||||
export function coverWarmItem(
|
||||
coverArtId: string,
|
||||
albumId: string,
|
||||
fetchCoverArtId: string,
|
||||
displayCssPx: number,
|
||||
surface: CoverSurfaceKind = 'dense',
|
||||
): CoverWarmItem {
|
||||
const ref = coverArtRef(coverArtId);
|
||||
const ref = albumCoverRef(albumId, fetchCoverArtId);
|
||||
const tier = resolveCoverDisplayTier(displayCssPx, { surface });
|
||||
return {
|
||||
ref,
|
||||
tier,
|
||||
storageKey: coverStorageKey(ref.serverScope, ref.coverArtId, tier),
|
||||
storageKey: coverStorageKeyFromRef(ref, tier),
|
||||
};
|
||||
}
|
||||
|
||||
export async function coverWarmItemFromLibrary(
|
||||
albumId: string,
|
||||
fetchCoverArtId: string,
|
||||
displayCssPx: number,
|
||||
surface: CoverSurfaceKind = 'dense',
|
||||
): Promise<CoverWarmItem> {
|
||||
const ref = await resolveAlbumCoverRefFromLibrary(albumId, fetchCoverArtId);
|
||||
const tier = resolveCoverDisplayTier(displayCssPx, { surface });
|
||||
return {
|
||||
ref,
|
||||
tier,
|
||||
storageKey: coverStorageKeyFromRef(ref, tier),
|
||||
};
|
||||
}
|
||||
|
||||
export function collectAlbumCoverWarmItems(
|
||||
albums: ReadonlyArray<{ coverArt?: string | null }>,
|
||||
albums: ReadonlyArray<{ id?: string; coverArt?: string | null }>,
|
||||
displayCssPx: number,
|
||||
surface: CoverSurfaceKind = 'dense',
|
||||
limit = 96,
|
||||
): CoverWarmItem[] {
|
||||
const out: CoverWarmItem[] = [];
|
||||
for (const a of albums) {
|
||||
if (!a.coverArt || out.length >= limit) break;
|
||||
out.push(coverWarmItem(a.coverArt, displayCssPx, surface));
|
||||
if (out.length >= limit) break;
|
||||
const entityId = a.id ?? a.coverArt;
|
||||
if (!entityId) continue;
|
||||
// Grid warm/peek uses API coverArt ids — avoids N sequential library_resolve IPC.
|
||||
out.push(coverWarmItem(entityId, a.coverArt ?? entityId, displayCssPx, surface));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function collectSongCoverWarmItems(
|
||||
songs: ReadonlyArray<{ albumId?: string; coverArt?: string | null }>,
|
||||
displayCssPx: number,
|
||||
surface: CoverSurfaceKind = 'dense',
|
||||
limit = 96,
|
||||
): Promise<CoverWarmItem[]> {
|
||||
const out: CoverWarmItem[] = [];
|
||||
for (const s of songs) {
|
||||
if (!s.albumId || out.length >= limit) break;
|
||||
out.push(
|
||||
await coverWarmItemFromLibrary(s.albumId, s.coverArt ?? s.albumId, displayCssPx, surface),
|
||||
);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -48,20 +85,14 @@ export async function warmCoverDiskSrcBatch(items: CoverWarmItem[]): Promise<num
|
||||
if (items.length === 0) return 0;
|
||||
|
||||
const hits = await coverCachePeekBatch(
|
||||
items.map(item => ({
|
||||
serverIndexKey: coverIndexKeyFromRef(item.ref),
|
||||
coverArtId: item.ref.coverArtId,
|
||||
tier: item.tier,
|
||||
})),
|
||||
items.map(item => item.ref),
|
||||
items[0]!.tier,
|
||||
);
|
||||
|
||||
let warmed = 0;
|
||||
for (const item of items) {
|
||||
const path = hits[item.storageKey];
|
||||
if (
|
||||
path
|
||||
&& rememberGridDiskSrc(item.ref.serverScope, item.ref.coverArtId, item.tier, path)
|
||||
) {
|
||||
if (path && rememberGridDiskSrc(item.ref, item.tier, path)) {
|
||||
warmed += 1;
|
||||
}
|
||||
}
|
||||
@@ -70,7 +101,7 @@ export async function warmCoverDiskSrcBatch(items: CoverWarmItem[]): Promise<num
|
||||
|
||||
/** High-priority ensure for albums still missing disk `src` after peek. */
|
||||
export async function ensureAlbumCoverMisses(
|
||||
albums: ReadonlyArray<{ coverArt?: string | null }>,
|
||||
albums: ReadonlyArray<{ id?: string; coverArt?: string | null }>,
|
||||
displayCssPx: number,
|
||||
opts?: { surface?: CoverSurfaceKind; limit?: number },
|
||||
): Promise<void> {
|
||||
@@ -79,23 +110,26 @@ export async function ensureAlbumCoverMisses(
|
||||
const tier = resolveCoverDisplayTier(displayCssPx, { surface });
|
||||
const slice = albums.slice(0, limit);
|
||||
|
||||
const needEnsure = slice.filter(album => {
|
||||
if (!album.coverArt) return false;
|
||||
return !getDiskSrcForGrid({ kind: 'active' }, album.coverArt, tier);
|
||||
});
|
||||
const needEnsure: Array<{ entityId: string; coverArt: string; ref: CoverArtRef }> = [];
|
||||
for (const album of slice) {
|
||||
const entityId = album.id ?? album.coverArt;
|
||||
if (!entityId || !album.coverArt) continue;
|
||||
const ref = albumCoverRef(entityId, album.coverArt);
|
||||
if (!getDiskSrcForGrid(ref, tier)) {
|
||||
needEnsure.push({ entityId, coverArt: album.coverArt, ref });
|
||||
}
|
||||
}
|
||||
if (needEnsure.length === 0) return;
|
||||
|
||||
const PRIME_CHUNK = 8;
|
||||
for (let i = 0; i < needEnsure.length; i += PRIME_CHUNK) {
|
||||
const chunk = needEnsure.slice(i, i + PRIME_CHUNK);
|
||||
await Promise.all(
|
||||
chunk.map(async album => {
|
||||
const id = album.coverArt!;
|
||||
const ref = coverArtRef(id);
|
||||
const key = coverStorageKey(ref.serverScope, ref.coverArtId, tier);
|
||||
chunk.map(async ({ ref }) => {
|
||||
const key = coverStorageKeyFromRef(ref, tier);
|
||||
const result = await coverEnsureQueued(key, ref, tier, 'high');
|
||||
if (result.hit && result.path) {
|
||||
rememberGridDiskSrc(ref.serverScope, ref.coverArtId, tier, result.path);
|
||||
rememberGridDiskSrc(ref, tier, result.path);
|
||||
}
|
||||
}),
|
||||
);
|
||||
@@ -106,7 +140,7 @@ export async function ensureAlbumCoverMisses(
|
||||
* Peek + high-priority ensure so cards paint with `src` on first frame.
|
||||
*/
|
||||
export async function primeAlbumCoversForDisplay(
|
||||
albums: ReadonlyArray<{ coverArt?: string | null }>,
|
||||
albums: ReadonlyArray<{ id?: string; coverArt?: string | null }>,
|
||||
displayCssPx: number,
|
||||
opts?: { surface?: CoverSurfaceKind; limit?: number; disabled?: boolean },
|
||||
): Promise<void> {
|
||||
@@ -138,7 +172,7 @@ export async function warmHomeMainstageCovers(snapshot: {
|
||||
mostPlayed: SubsonicAlbum[];
|
||||
recentlyPlayed: SubsonicAlbum[];
|
||||
starred: SubsonicAlbum[];
|
||||
discoverSongs?: Array<{ coverArt?: string | null }>;
|
||||
discoverSongs?: Array<{ albumId?: string; coverArt?: string | null }>;
|
||||
}): Promise<void> {
|
||||
const items = dedupeWarmItems([
|
||||
...collectAlbumCoverWarmItems(snapshot.heroAlbums, 220, 'dense', 12),
|
||||
@@ -147,34 +181,34 @@ export async function warmHomeMainstageCovers(snapshot: {
|
||||
...collectAlbumCoverWarmItems(snapshot.mostPlayed, 300, 'dense', 20),
|
||||
...collectAlbumCoverWarmItems(snapshot.recentlyPlayed, 300, 'dense', 20),
|
||||
...collectAlbumCoverWarmItems(snapshot.starred, 300, 'dense', 20),
|
||||
...collectAlbumCoverWarmItems(snapshot.discoverSongs ?? [], 200, 'dense', 20),
|
||||
...(await collectSongCoverWarmItems(snapshot.discoverSongs ?? [], 200, 'dense', 20)),
|
||||
]);
|
||||
await warmCoverDiskSrcBatch(items);
|
||||
|
||||
// Prepare above-the-fold mainstage covers ahead of return navigation:
|
||||
// if a refreshed snapshot introduces new albums not yet on disk, ensure them
|
||||
// now in background so Hero / first rows don't wait on per-cell ensure.
|
||||
// `discoverSongs` shares the same dense surface as the album rails — the
|
||||
// pre-merge code only walked album collections here and the song row was
|
||||
// left to lazy per-card ensure, which produced visible placeholder cards
|
||||
// on cold caches.
|
||||
const discoverSongsForEnsure = snapshot.discoverSongs ?? [];
|
||||
await Promise.allSettled([
|
||||
ensureAlbumCoverMisses(snapshot.heroAlbums, 220, { surface: 'dense', limit: 8 }),
|
||||
ensureAlbumCoverMisses(snapshot.recent, 300, { surface: 'dense', limit: 14 }),
|
||||
ensureAlbumCoverMisses(snapshot.random, 300, { surface: 'dense', limit: 10 }),
|
||||
ensureAlbumCoverMisses(discoverSongsForEnsure, 200, { surface: 'dense', limit: 12 }),
|
||||
ensureAlbumCoverMisses(
|
||||
discoverSongsForEnsure.filter(s => s.albumId).map(s => ({ id: s.albumId!, coverArt: s.coverArt })),
|
||||
200,
|
||||
{ surface: 'dense', limit: 12 },
|
||||
),
|
||||
]);
|
||||
|
||||
// Fire-and-forget decode warmup to reduce first-paint "from cache" delay.
|
||||
void predecodeWarmAlbums(snapshot.heroAlbums, 220, 8);
|
||||
void predecodeWarmAlbums(snapshot.recent, 300, 10);
|
||||
void predecodeWarmAlbums(snapshot.random, 300, 8);
|
||||
void predecodeWarmAlbums(discoverSongsForEnsure, 200, 8);
|
||||
void predecodeWarmAlbums(
|
||||
discoverSongsForEnsure.filter(s => s.albumId).map(s => ({ id: s.albumId!, coverArt: s.coverArt })),
|
||||
200,
|
||||
8,
|
||||
);
|
||||
}
|
||||
|
||||
async function predecodeWarmAlbums(
|
||||
albums: ReadonlyArray<{ coverArt?: string | null }>,
|
||||
albums: ReadonlyArray<{ id?: string; coverArt?: string | null }>,
|
||||
displayCssPx: number,
|
||||
limit: number,
|
||||
): Promise<void> {
|
||||
@@ -183,7 +217,10 @@ async function predecodeWarmAlbums(
|
||||
const urls: string[] = [];
|
||||
for (const album of albums) {
|
||||
if (!album.coverArt || urls.length >= limit) continue;
|
||||
const src = getDiskSrcForGrid({ kind: 'active' }, album.coverArt, tier);
|
||||
const entityId = album.id ?? album.coverArt;
|
||||
if (!entityId) continue;
|
||||
const ref = albumCoverRef(entityId, album.coverArt);
|
||||
const src = getDiskSrcForGrid(ref, tier);
|
||||
if (!src) continue;
|
||||
urls.push(src);
|
||||
}
|
||||
|
||||
@@ -3,23 +3,25 @@ import { listen } from '@tauri-apps/api/event';
|
||||
import {
|
||||
clearAllDiskSrcCache,
|
||||
forgetDiskSrcPrefix,
|
||||
rememberDiskSrc,
|
||||
} from '../../cover/diskSrcCache';
|
||||
import { rememberDiskSrcLadder } from '../../cover/diskSrcLookup';
|
||||
import { notifyCoverDiskReady } from '../../cover/diskHandoff';
|
||||
import { invalidateCacheKey } from '../../utils/imageCache';
|
||||
import { COVER_ART_TIERS } from '../../cover/tiers';
|
||||
import type { CoverArtTier } from '../../cover/types';
|
||||
import type { CoverArtTier, CoverCacheKind } from '../../cover/types';
|
||||
|
||||
type CoverTierReadyPayload = {
|
||||
serverIndexKey: string;
|
||||
coverArtId: string;
|
||||
cacheKind: CoverCacheKind;
|
||||
cacheEntityId: string;
|
||||
tier: CoverArtTier;
|
||||
path: string;
|
||||
};
|
||||
|
||||
type CoverEvictedPayload = {
|
||||
serverIndexKey: string;
|
||||
coverArtId: string;
|
||||
cacheKind: CoverCacheKind;
|
||||
cacheEntityId: string;
|
||||
};
|
||||
|
||||
/** Rust → UI: disk `.webp` ready — do not invalidate IDB (that caused webview refetch storms). */
|
||||
@@ -29,10 +31,10 @@ export function useCoverArtBridge(): void {
|
||||
void (async () => {
|
||||
unsubs.push(
|
||||
await listen<CoverTierReadyPayload>('cover:tier-ready', ev => {
|
||||
const { serverIndexKey, coverArtId, tier, path } = ev.payload;
|
||||
const { serverIndexKey, cacheKind, cacheEntityId, tier, path } = ev.payload;
|
||||
if (!path) return;
|
||||
const key = `${serverIndexKey}:cover:${coverArtId}:${tier}`;
|
||||
rememberDiskSrc(key, path);
|
||||
const key = `${serverIndexKey}:cover:${cacheKind}:${cacheEntityId}:${tier}`;
|
||||
rememberDiskSrcLadder(serverIndexKey, { cacheKind, cacheEntityId }, tier, path);
|
||||
notifyCoverDiskReady(key, path);
|
||||
void invalidateCacheKey(key);
|
||||
}),
|
||||
@@ -44,10 +46,14 @@ export function useCoverArtBridge(): void {
|
||||
);
|
||||
unsubs.push(
|
||||
await listen<CoverEvictedPayload>('cover:evicted', ev => {
|
||||
const { serverIndexKey, coverArtId } = ev.payload;
|
||||
forgetDiskSrcPrefix(serverIndexKey, coverArtId);
|
||||
const { serverIndexKey, cacheKind, cacheEntityId } = ev.payload;
|
||||
forgetDiskSrcPrefix({
|
||||
serverScope: { kind: 'active' },
|
||||
cacheKind,
|
||||
cacheEntityId,
|
||||
});
|
||||
for (const tier of COVER_ART_TIERS) {
|
||||
notifyCoverDiskReady(`${serverIndexKey}:cover:${coverArtId}:${tier}`, '');
|
||||
notifyCoverDiskReady(`${serverIndexKey}:cover:${cacheKind}:${cacheEntityId}:${tier}`, '');
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -16,7 +16,7 @@ export function useCoverNavigationPriority(): void {
|
||||
coverTrafficBeginNavigation();
|
||||
coverTrafficEndNavigation();
|
||||
return () => {
|
||||
coverTrafficBeginNavigation();
|
||||
coverTrafficEndNavigation();
|
||||
};
|
||||
}, [pathname]);
|
||||
}
|
||||
|
||||
@@ -20,8 +20,10 @@ import { libraryIsReady } from '../utils/library/libraryReady';
|
||||
const TOP_UP_POLL_MS = 500;
|
||||
const STEADY_POLL_MS = 2000;
|
||||
const READY_POLL_MS = 5000;
|
||||
const EXHAUSTED_PAUSE_MS = 60_000;
|
||||
const EXHAUSTED_PAUSE_MS = 15_000;
|
||||
const COMPLETED_RECHECK_MS = 5 * 60_000;
|
||||
/** Consecutive exhausted scans with zero enqueue before treating the library as done. */
|
||||
const EXHAUSTED_DONE_STREAK = 2;
|
||||
|
||||
const EMPTY_PIPELINE_STATS = {
|
||||
pipelineWorkers: 1,
|
||||
@@ -56,6 +58,7 @@ export function useLibraryAnalysisBackfill(enabled = true): void {
|
||||
);
|
||||
const cursorRef = useRef<string | null>(null);
|
||||
const completedTotalRef = useRef<number | null>(null);
|
||||
const exhaustedIdleStreakRef = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
@@ -69,19 +72,9 @@ export function useLibraryAnalysisBackfill(enabled = true): void {
|
||||
|
||||
let cancelled = false;
|
||||
const serverId = activeServerId;
|
||||
let initialized = false;
|
||||
|
||||
void (async () => {
|
||||
while (!cancelled) {
|
||||
if (!initialized) {
|
||||
initialized = true;
|
||||
const progress = await libraryAnalysisProgress(serverId).catch(() => null);
|
||||
if (progress && progress.pendingTracks <= 0) {
|
||||
completedTotalRef.current = progress.totalTracks;
|
||||
cursorRef.current = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (completedTotalRef.current !== null) {
|
||||
const totalTracks = await libraryCountLiveTracks(serverId).catch(() => null);
|
||||
if (!Number.isFinite(totalTracks)) {
|
||||
@@ -94,6 +87,7 @@ export function useLibraryAnalysisBackfill(enabled = true): void {
|
||||
}
|
||||
completedTotalRef.current = null;
|
||||
cursorRef.current = null;
|
||||
exhaustedIdleStreakRef.current = 0;
|
||||
}
|
||||
|
||||
if (!(await libraryIsReady(serverId))) {
|
||||
@@ -145,19 +139,31 @@ export function useLibraryAnalysisBackfill(enabled = true): void {
|
||||
|
||||
if (cancelled) return;
|
||||
|
||||
if (batch.trackIds.length > 0) {
|
||||
exhaustedIdleStreakRef.current = 0;
|
||||
}
|
||||
|
||||
if (batch.exhausted) {
|
||||
cursorRef.current = null;
|
||||
const progress = await libraryAnalysisProgress(serverId).catch(() => null);
|
||||
if (progress && progress.pendingTracks <= 0) {
|
||||
completedTotalRef.current = progress.totalTracks;
|
||||
await new Promise(r => setTimeout(r, COMPLETED_RECHECK_MS));
|
||||
const pending = progress?.pendingTracks ?? -1;
|
||||
if (pending <= 0 && batch.trackIds.length === 0) {
|
||||
exhaustedIdleStreakRef.current += 1;
|
||||
if (exhaustedIdleStreakRef.current >= EXHAUSTED_DONE_STREAK && progress) {
|
||||
completedTotalRef.current = progress.totalTracks;
|
||||
await new Promise(r => setTimeout(r, COMPLETED_RECHECK_MS));
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
exhaustedIdleStreakRef.current = 0;
|
||||
}
|
||||
if (pending > 0) {
|
||||
continue;
|
||||
}
|
||||
await new Promise(r => setTimeout(r, EXHAUSTED_PAUSE_MS));
|
||||
} else if (batch.trackIds.length === 0) {
|
||||
await new Promise(r => setTimeout(r, TOP_UP_POLL_MS));
|
||||
}
|
||||
// else: loop immediately if still below watermark
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -165,6 +171,7 @@ export function useLibraryAnalysisBackfill(enabled = true): void {
|
||||
cancelled = true;
|
||||
cursorRef.current = null;
|
||||
completedTotalRef.current = null;
|
||||
exhaustedIdleStreakRef.current = 0;
|
||||
};
|
||||
}, [strategy, activeServerId, advancedParallelism, enabled]);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { coverCacheEnsure, coverCachePeekBatch } from '../api/coverCache';
|
||||
import { serverIndexKeyForProfile } from '../utils/server/serverIndexKey';
|
||||
import { coverIndexKeyFromRef } from '../cover/storageKeys';
|
||||
import { useNowPlayingPrewarm } from './useNowPlayingPrewarm';
|
||||
import { prewarmNowPlayingFetchers } from './useNowPlayingFetchers';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
@@ -10,10 +10,14 @@ import { makeTrack } from '../test/helpers/factories';
|
||||
import { resetAllStores } from '../test/helpers/storeReset';
|
||||
import { toQueueItemRefs } from '../utils/library/queueItemRef';
|
||||
|
||||
vi.mock('../api/coverCache', () => ({
|
||||
coverCachePeekBatch: vi.fn(async () => ({})),
|
||||
coverCacheEnsure: vi.fn(async () => ({ hit: false, path: '', tier: 800 })),
|
||||
}));
|
||||
vi.mock('../api/coverCache', async importOriginal => {
|
||||
const actual = await importOriginal<typeof import('../api/coverCache')>();
|
||||
return {
|
||||
...actual,
|
||||
coverCachePeekBatch: vi.fn(async () => ({})),
|
||||
coverCacheEnsure: vi.fn(async () => ({ hit: false, path: '', tier: 800 })),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('./useNowPlayingFetchers', () => ({
|
||||
prewarmNowPlayingFetchers: vi.fn(async () => undefined),
|
||||
@@ -65,10 +69,10 @@ describe('useNowPlayingPrewarm', () => {
|
||||
expect(coverCachePeekBatch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
const peekArg = vi.mocked(coverCachePeekBatch).mock.calls[0]?.[0]?.[0];
|
||||
const peekRef = vi.mocked(coverCachePeekBatch).mock.calls[0]?.[0]?.[0];
|
||||
const playbackProfile = useAuthStore.getState().servers.find(s => s.id === playback);
|
||||
expect(playbackProfile).toBeDefined();
|
||||
expect(peekArg?.serverIndexKey).toBe(serverIndexKeyForProfile(playbackProfile!));
|
||||
expect(peekRef && coverIndexKeyFromRef(peekRef)).toBe('playback.test');
|
||||
const ensureRef = vi.mocked(coverCacheEnsure).mock.calls[0]?.[0];
|
||||
expect(ensureRef?.serverScope.kind).toBe('server');
|
||||
});
|
||||
@@ -95,10 +99,10 @@ describe('useNowPlayingPrewarm', () => {
|
||||
expect(coverCachePeekBatch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
const peekArg = vi.mocked(coverCachePeekBatch).mock.calls[0]?.[0]?.[0];
|
||||
const peekRef = vi.mocked(coverCachePeekBatch).mock.calls[0]?.[0]?.[0];
|
||||
const activeProfile = useAuthStore.getState().servers.find(s => s.id === active);
|
||||
expect(activeProfile).toBeDefined();
|
||||
expect(peekArg?.serverIndexKey).toBe(serverIndexKeyForProfile(activeProfile!));
|
||||
expect(peekRef && coverIndexKeyFromRef(peekRef)).toBe('active.test');
|
||||
const ensureRef = vi.mocked(coverCacheEnsure).mock.calls[0]?.[0];
|
||||
expect(ensureRef?.serverScope).toEqual({ kind: 'active' });
|
||||
});
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { useEffect } from 'react';
|
||||
import { coverCacheEnsure, coverCachePeekBatch } from '../api/coverCache';
|
||||
import { coverArtRef, resolvePlaybackCoverScope } from '../cover/ref';
|
||||
import { albumCoverRef } from '../cover/ref';
|
||||
import { resolvePlaybackCoverScope } from '../cover/ref';
|
||||
import { resolveTrackCoverRefFromLibrary } from '../cover/resolveEntryLibrary';
|
||||
import { getDiskSrc, rememberDiskSrc } from '../cover/diskSrcCache';
|
||||
import { coverIndexKeyFromRef, coverStorageKey } from '../cover/storageKeys';
|
||||
import { coverStorageKeyFromRef } from '../cover/storageKeys';
|
||||
import { resolveCoverDisplayTier } from '../cover/tiers';
|
||||
import { coverArtIdFromRadio } from '../cover/ids';
|
||||
import type { CoverServerScope } from '../cover/types';
|
||||
import type { CoverArtRef } from '../cover/types';
|
||||
import { prewarmNowPlayingFetchers } from './useNowPlayingFetchers';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { usePlayerStore } from '../store/playerStore';
|
||||
@@ -13,23 +15,13 @@ import { usePlaybackServerId } from './usePlaybackServerId';
|
||||
|
||||
const NOW_PLAYING_COVER_CSS_PX = 800;
|
||||
|
||||
async function prewarmCoverForScope(
|
||||
coverArtId: string,
|
||||
scope: CoverServerScope,
|
||||
): Promise<void> {
|
||||
if (!coverArtId) return;
|
||||
async function prewarmCoverRef(ref: CoverArtRef): Promise<void> {
|
||||
if (!ref.fetchCoverArtId) return;
|
||||
const tier = resolveCoverDisplayTier(NOW_PLAYING_COVER_CSS_PX, { surface: 'sparse' });
|
||||
const ref = coverArtRef(coverArtId, scope);
|
||||
const storageKey = coverStorageKey(ref.serverScope, ref.coverArtId, tier);
|
||||
const storageKey = coverStorageKeyFromRef(ref, tier);
|
||||
if (getDiskSrc(storageKey)) return;
|
||||
|
||||
const hits = await coverCachePeekBatch([
|
||||
{
|
||||
serverIndexKey: coverIndexKeyFromRef(ref),
|
||||
coverArtId: ref.coverArtId,
|
||||
tier,
|
||||
},
|
||||
]);
|
||||
const hits = await coverCachePeekBatch([ref], tier);
|
||||
const hitPath = hits[storageKey];
|
||||
if (hitPath) {
|
||||
rememberDiskSrc(storageKey, hitPath);
|
||||
@@ -73,8 +65,18 @@ export function useNowPlayingPrewarm(): void {
|
||||
fetchEnabled: true,
|
||||
});
|
||||
|
||||
if (currentTrack.coverArt) {
|
||||
void prewarmCoverForScope(currentTrack.coverArt, resolvePlaybackCoverScope());
|
||||
if (currentTrack.albumId && currentTrack.id) {
|
||||
void resolveTrackCoverRefFromLibrary(
|
||||
{
|
||||
id: currentTrack.id,
|
||||
albumId: currentTrack.albumId,
|
||||
coverArt: currentTrack.coverArt,
|
||||
discNumber: (currentTrack as { discNumber?: number }).discNumber,
|
||||
},
|
||||
resolvePlaybackCoverScope(),
|
||||
).then(ref => {
|
||||
if (ref) void prewarmCoverRef(ref);
|
||||
});
|
||||
}
|
||||
}, [
|
||||
currentTrack?.id,
|
||||
@@ -91,6 +93,6 @@ export function useNowPlayingPrewarm(): void {
|
||||
useEffect(() => {
|
||||
if (!currentRadio?.coverArt || !activeServerId) return;
|
||||
const radioCoverArtId = coverArtIdFromRadio(currentRadio.id);
|
||||
void prewarmCoverForScope(radioCoverArtId, { kind: 'active' });
|
||||
void prewarmCoverRef(albumCoverRef(radioCoverArtId, radioCoverArtId, { kind: 'active' }));
|
||||
}, [currentRadio?.id, currentRadio?.coverArt, activeServerId]);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useEffect, useMemo } from 'react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import type { SubsonicSong } from '../api/subsonicTypes';
|
||||
import type { CoverArtId } from '../cover/types';
|
||||
import type { CoverArtId, CoverArtRef } from '../cover/types';
|
||||
import { coverPrefetchRegister } from '../cover/prefetchRegistry';
|
||||
import { coverArtRef } from '../cover/ref';
|
||||
import { resolveAlbumCoverRefFromLibrary } from '../cover/resolveEntryLibrary';
|
||||
import { useCoverArt } from '../cover/useCoverArt';
|
||||
|
||||
const PLAYLIST_HERO_BG_CSS_PX = 200;
|
||||
@@ -14,6 +14,17 @@ export interface PlaylistCovers {
|
||||
resolvedBgUrl: string;
|
||||
}
|
||||
|
||||
async function playlistCoverRefFromLibrary(
|
||||
coverId: string,
|
||||
songs: SubsonicSong[],
|
||||
): Promise<CoverArtRef> {
|
||||
const song = songs.find(s => s.coverArt === coverId || s.albumId === coverId);
|
||||
if (song?.albumId) {
|
||||
return resolveAlbumCoverRefFromLibrary(song.albumId, coverId);
|
||||
}
|
||||
return resolveAlbumCoverRefFromLibrary(coverId, coverId);
|
||||
}
|
||||
|
||||
export function usePlaylistCovers(songs: SubsonicSong[], customCoverId: string | null): PlaylistCovers {
|
||||
const coverQuad = useMemo(() => {
|
||||
const seen = new Set<string>();
|
||||
@@ -38,18 +49,46 @@ export function usePlaylistCovers(songs: SubsonicSong[], customCoverId: string |
|
||||
);
|
||||
|
||||
const bgCoverId = customCoverId ?? coverQuad[0] ?? null;
|
||||
const { src: resolvedBgUrl } = useCoverArt(bgCoverId, PLAYLIST_HERO_BG_CSS_PX, {
|
||||
const [bgCoverRef, setBgCoverRef] = useState<CoverArtRef | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!bgCoverId) {
|
||||
setBgCoverRef(null);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
void playlistCoverRefFromLibrary(bgCoverId, songs).then(ref => {
|
||||
if (!cancelled) setBgCoverRef(ref);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [bgCoverId, songs]);
|
||||
|
||||
const { src: resolvedBgUrl } = useCoverArt(bgCoverRef, PLAYLIST_HERO_BG_CSS_PX, {
|
||||
surface: 'dense',
|
||||
ensurePriority: 'high',
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const refs = coverQuadIds
|
||||
.filter((id): id is CoverArtId => !!id)
|
||||
.map(id => coverArtRef(id));
|
||||
if (bgCoverId) refs.push(coverArtRef(bgCoverId));
|
||||
return coverPrefetchRegister(refs, { surface: 'dense', priority: 'middle' });
|
||||
}, [coverQuadIds, bgCoverId]);
|
||||
const ids = [
|
||||
...coverQuadIds.filter((id): id is CoverArtId => !!id),
|
||||
...(bgCoverId ? [bgCoverId] : []),
|
||||
];
|
||||
if (ids.length === 0) return;
|
||||
let cancelled = false;
|
||||
let unreg: (() => void) | undefined;
|
||||
void (async () => {
|
||||
const refs = await Promise.all(ids.map(id => playlistCoverRefFromLibrary(id, songs)));
|
||||
if (!cancelled) {
|
||||
unreg = coverPrefetchRegister(refs, { surface: 'dense', priority: 'middle' });
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
unreg?.();
|
||||
};
|
||||
}, [coverQuadIds, bgCoverId, songs]);
|
||||
|
||||
return { coverQuadIds, bgCoverId, resolvedBgUrl };
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useLayoutEffect, useMemo } from 'react';
|
||||
import { useEffect, useMemo } from 'react';
|
||||
import { GRID_COVER_PRIME_ALL_MAX } from '../cover/layoutSizes';
|
||||
import {
|
||||
collectAlbumCoverWarmItems,
|
||||
@@ -10,7 +10,7 @@ import type { CoverSurfaceKind } from '../cover/types';
|
||||
const DEFAULT_LIMIT = 120;
|
||||
|
||||
/**
|
||||
* Peek before paint; for small grids (≤48) queue ensures only for disk misses.
|
||||
* Peek after mount (non-blocking); for small grids (≤48) queue ensures only for disk misses.
|
||||
*/
|
||||
export function useWarmGridCovers(
|
||||
items: ReadonlyArray<{ coverArt?: string | null }>,
|
||||
@@ -37,13 +37,13 @@ export function useWarmGridCovers(
|
||||
|
||||
const primeAllMisses = items.length > 0 && items.length <= GRID_COVER_PRIME_ALL_MAX;
|
||||
|
||||
useLayoutEffect(() => {
|
||||
useEffect(() => {
|
||||
if (!enabled || displayCssPx <= 0) return;
|
||||
const batch = collectAlbumCoverWarmItems(items, displayCssPx, surface, limit);
|
||||
if (batch.length === 0) return;
|
||||
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
const batch = collectAlbumCoverWarmItems(items, displayCssPx, surface, limit);
|
||||
if (cancelled || batch.length === 0) return;
|
||||
await warmCoverDiskSrcBatch(batch);
|
||||
if (cancelled) return;
|
||||
if (primeAllMisses) {
|
||||
|
||||
@@ -650,6 +650,8 @@ export default function AdvancedSearch() {
|
||||
title={`${t('search.albums')} (${filteredResults.albums.length})`}
|
||||
albums={filteredResults.albums}
|
||||
albumLinkQuery={activeSearch?.losslessOnly ? LOSSLESS_MODE_QUERY : undefined}
|
||||
windowArtworkByViewport
|
||||
initialArtworkBudget={12}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -23,6 +23,11 @@ import AlbumHeader from '../components/AlbumHeader';
|
||||
import AlbumTrackList from '../components/AlbumTrackList';
|
||||
import { AlbumDetailToolbar } from '../components/albumDetail/AlbumDetailToolbar';
|
||||
import { useCoverArt } from '../cover/useCoverArt';
|
||||
import {
|
||||
forgetAlbumDistinctDiscCovers,
|
||||
rememberAlbumDistinctDiscCovers,
|
||||
} from '../cover/ref';
|
||||
import { useAlbumCoverRef } from '../cover/useLibraryCoverRef';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { showToast } from '../utils/ui/toast';
|
||||
import { useSelectionStore } from '../store/selectionStore';
|
||||
@@ -90,6 +95,12 @@ export default function AlbumDetail() {
|
||||
return album.songs.filter(s => isLosslessSuffix(s.suffix));
|
||||
}, [album?.songs, losslessOnly]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!albumId || !effectiveSongs?.length) return;
|
||||
rememberAlbumDistinctDiscCovers(albumId, effectiveSongs);
|
||||
return () => forgetAlbumDistinctDiscCovers(albumId);
|
||||
}, [albumId, effectiveSongs]);
|
||||
|
||||
const handlePlayAll = () => {
|
||||
if (!album || !effectiveSongs) return;
|
||||
const albumGenre = album.album.genre;
|
||||
@@ -270,7 +281,13 @@ const handleShuffleAll = () => {
|
||||
userRatingOverrides,
|
||||
});
|
||||
|
||||
const albumCover = useCoverArt(album?.album.coverArt, 400, { surface: 'sparse' });
|
||||
const albumCoverRefResolved = useAlbumCoverRef(
|
||||
album?.album.id,
|
||||
album?.album.coverArt,
|
||||
undefined,
|
||||
{ libraryResolve: true },
|
||||
);
|
||||
const albumCover = useCoverArt(albumCoverRefResolved, 400, { surface: 'sparse' });
|
||||
const resolvedCoverUrl = albumCover.src || null;
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
+10
-9
@@ -4,8 +4,7 @@ import { songToTrack } from '../utils/playback/songToTrack';
|
||||
import { useState, useEffect, useLayoutEffect, useRef, useCallback, useMemo } from 'react';
|
||||
import AlbumCard from '../components/AlbumCard';
|
||||
import { albumGridWarmCovers, coverDisplayCssPxForAlbumGrid } from '../cover/layoutSizes';
|
||||
import { coverPrefetchRegister } from '../cover/prefetchRegistry';
|
||||
import { coverArtRef } from '../cover/ref';
|
||||
import { useLibraryCoverPrefetch } from '../cover/useLibraryCoverPrefetch';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { clampLibraryGridMaxColumns } from '../store/authStoreHelpers';
|
||||
import { computeCardGridColumnCount } from '../utils/cardGridLayout';
|
||||
@@ -211,13 +210,15 @@ export default function Albums() {
|
||||
return () => ro.disconnect();
|
||||
}, [maxGridCols, visibleAlbums.length]);
|
||||
|
||||
useEffect(() => {
|
||||
const viewportBudget = Math.max(albumGridCols * 3, albumGridCols);
|
||||
const refs = visibleAlbums
|
||||
.slice(0, viewportBudget)
|
||||
.flatMap(a => (a.coverArt ? [coverArtRef(a.coverArt)] : []));
|
||||
return coverPrefetchRegister(refs, { surface: 'dense', priority: 'high' });
|
||||
}, [visibleAlbums, albumGridCols]);
|
||||
useLibraryCoverPrefetch(
|
||||
[
|
||||
{
|
||||
albums: visibleAlbums.slice(0, Math.max(albumGridCols * 3, albumGridCols)),
|
||||
priority: 'high',
|
||||
},
|
||||
],
|
||||
[visibleAlbums, albumGridCols],
|
||||
);
|
||||
|
||||
const mainstageHeaderTight = useMainstageInpageHeaderTight(scrollBodyEl, [
|
||||
sort,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { uploadArtistImage } from '../api/subsonicPlaylists';
|
||||
import { useCoverArt } from '../cover/useCoverArt';
|
||||
import { useArtistCoverRef } from '../cover/useLibraryCoverRef';
|
||||
import { setRating, star, unstar } from '../api/subsonicStarRating';
|
||||
import { getAlbum } from '../api/subsonicLibrary';
|
||||
import type { SubsonicArtist, SubsonicAlbum, SubsonicSong, SubsonicArtistInfo } from '../api/subsonicTypes';
|
||||
@@ -44,6 +45,7 @@ import ArtistCard from '../components/nowPlaying/ArtistCard';
|
||||
import LosslessModeBanner from '../components/LosslessModeBanner';
|
||||
import { usePerfProbeFlags } from '../utils/perf/perfFlags';
|
||||
import { albumGridWarmCovers } from '../cover/layoutSizes';
|
||||
import { rememberAlbumDistinctDiscCovers } from '../cover/ref';
|
||||
import { VirtualCardGrid } from '../components/VirtualCardGrid';
|
||||
import { LOSSLESS_MODE_QUERY } from '../utils/library/losslessMode';
|
||||
import { sortArtistAlbumsByYear } from '../utils/library/sortArtistAlbums';
|
||||
@@ -167,7 +169,10 @@ export default function ArtistDetail() {
|
||||
|
||||
// Cover URLs — must run every render (before early returns) or hook order breaks.
|
||||
const coverId = artist ? (artist.coverArt || artist.id) : '';
|
||||
const artistCoverFallback = useCoverArt(coverId || undefined, 80, { surface: 'sparse' });
|
||||
const artistCoverRefResolved = useArtistCoverRef(artist?.id, artist?.coverArt, undefined, {
|
||||
libraryResolve: true,
|
||||
});
|
||||
const artistCoverFallback = useCoverArt(artistCoverRefResolved, 80, { surface: 'sparse' });
|
||||
|
||||
const groupedAlbums = useMemo(() => {
|
||||
if (albums.length === 0) return [];
|
||||
@@ -210,6 +215,19 @@ export default function ArtistDetail() {
|
||||
setHeaderCoverFailed(false);
|
||||
}, [coverId, coverRevision, id]);
|
||||
|
||||
useEffect(() => {
|
||||
const byAlbum = new Map<string, SubsonicSong[]>();
|
||||
for (const song of topSongs) {
|
||||
const albumId = song.albumId?.trim();
|
||||
if (!albumId) continue;
|
||||
if (!byAlbum.has(albumId)) byAlbum.set(albumId, []);
|
||||
byAlbum.get(albumId)!.push(song);
|
||||
}
|
||||
for (const [albumId, songs] of byAlbum) {
|
||||
rememberAlbumDistinctDiscCovers(albumId, songs);
|
||||
}
|
||||
}, [topSongs]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="content-body" style={{ display: 'flex', justifyContent: 'center', padding: '4rem' }}>
|
||||
@@ -284,6 +302,7 @@ export default function ArtistDetail() {
|
||||
openedLink={openedLink}
|
||||
openLink={openLink}
|
||||
coverId={coverId}
|
||||
coverRef={artistCoverRefResolved}
|
||||
coverRevision={coverRevision}
|
||||
headerCoverFailed={headerCoverFailed}
|
||||
setHeaderCoverFailed={setHeaderCoverFailed}
|
||||
@@ -313,6 +332,7 @@ export default function ArtistDetail() {
|
||||
<ArtistDetailTopTracks
|
||||
key="topTracks"
|
||||
topSongs={topSongs}
|
||||
albums={albums}
|
||||
marginTop={sectionMt('topTracks')}
|
||||
playTopSongWithContinuation={playTopSongWithContinuation}
|
||||
losslessOnly={losslessOnly}
|
||||
@@ -377,7 +397,10 @@ export default function ArtistDetail() {
|
||||
wrapClassName="album-grid-wrap album-grid-wrap--artist"
|
||||
warmGridCovers={albumGridWarmCovers()}
|
||||
renderItem={a => (
|
||||
<AlbumCard album={a} linkQuery={losslessOnly ? LOSSLESS_MODE_QUERY : undefined} />
|
||||
<AlbumCard
|
||||
album={a}
|
||||
linkQuery={losslessOnly ? LOSSLESS_MODE_QUERY : undefined}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
) : groupedAlbums.map(([label, group]) => (
|
||||
@@ -395,7 +418,10 @@ export default function ArtistDetail() {
|
||||
wrapClassName="album-grid-wrap album-grid-wrap--artist"
|
||||
warmGridCovers={albumGridWarmCovers()}
|
||||
renderItem={a => (
|
||||
<AlbumCard album={a} linkQuery={losslessOnly ? LOSSLESS_MODE_QUERY : undefined} />
|
||||
<AlbumCard
|
||||
album={a}
|
||||
linkQuery={losslessOnly ? LOSSLESS_MODE_QUERY : undefined}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
+15
-33
@@ -18,9 +18,7 @@ import { usePerfProbeFlags } from '../utils/perf/perfFlags';
|
||||
import { bumpPerfCounter } from '../utils/perf/perfTelemetry';
|
||||
import { dedupeById } from '../utils/dedupeById';
|
||||
import { shuffleArray } from '../utils/playback/shuffleArray';
|
||||
import { coverArtIdFromArtist } from '../cover/ids';
|
||||
import { coverPrefetchRegister } from '../cover/prefetchRegistry';
|
||||
import { coverArtRef } from '../cover/ref';
|
||||
import { useLibraryCoverPrefetch } from '../cover/useLibraryCoverPrefetch';
|
||||
import { primeAlbumCoversForDisplay, warmHomeMainstageCovers } from '../cover/warmDiskPeek';
|
||||
import { readBecauseYouLikeCache } from '../store/becauseYouLikeCache';
|
||||
import {
|
||||
@@ -103,36 +101,20 @@ export default function Home() {
|
||||
bumpPerfCounter('homeCommits');
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const heroRefs = heroAlbums.flatMap(a => (a.coverArt ? [coverArtRef(a.coverArt)] : []));
|
||||
const recentRefs = recent.flatMap(a => (a.coverArt ? [coverArtRef(a.coverArt)] : []));
|
||||
const restAlbumRefs = [...random, ...mostPlayed, ...recentlyPlayed, ...starred].flatMap(a =>
|
||||
a.coverArt ? [coverArtRef(a.coverArt)] : [],
|
||||
);
|
||||
const artistRefs = randomArtists.map(a => coverArtRef(coverArtIdFromArtist(a)));
|
||||
const songRefs = discoverSongs.flatMap(s => {
|
||||
const id = s.coverArt ?? s.albumId;
|
||||
return id ? [coverArtRef(id)] : [];
|
||||
});
|
||||
const unregHero = coverPrefetchRegister(heroRefs, { surface: 'dense', priority: 'high' });
|
||||
const unregRecent = coverPrefetchRegister(recentRefs, { surface: 'dense', priority: 'high' });
|
||||
// The album-and-artist `cappedRest` bucket is sized for the visible album
|
||||
// rails (random + mostPlayed + recentlyPlayed + starred = 48 refs, plus
|
||||
// 16 artist refs) and would otherwise crowd `songRefs` out entirely at
|
||||
// the 24-entry slice. Register the Discover Songs rail on its own with
|
||||
// its own modest cap so the song row gets a fair share of background
|
||||
// bandwidth without inflating the 'low' bucket.
|
||||
const cappedRest = [...restAlbumRefs, ...artistRefs].slice(0, 24);
|
||||
const unregRest = coverPrefetchRegister(cappedRest, { surface: 'dense', priority: 'low' });
|
||||
const cappedSongs = songRefs.slice(0, 16);
|
||||
const unregSongs = coverPrefetchRegister(cappedSongs, { surface: 'dense', priority: 'middle' });
|
||||
return () => {
|
||||
unregHero();
|
||||
unregRecent();
|
||||
unregRest();
|
||||
unregSongs();
|
||||
};
|
||||
}, [heroAlbums, recent, random, mostPlayed, recentlyPlayed, starred, randomArtists, discoverSongs]);
|
||||
useLibraryCoverPrefetch(
|
||||
[
|
||||
{ albums: heroAlbums, priority: 'high' },
|
||||
{ albums: recent, priority: 'high' },
|
||||
{
|
||||
albums: [...random, ...mostPlayed, ...recentlyPlayed, ...starred],
|
||||
artists: randomArtists,
|
||||
limit: 24,
|
||||
priority: 'low',
|
||||
},
|
||||
{ songs: discoverSongs, limit: 16, priority: 'middle' },
|
||||
],
|
||||
[heroAlbums, recent, random, mostPlayed, recentlyPlayed, starred, randomArtists, discoverSongs],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeServerId) return;
|
||||
|
||||
+18
-14
@@ -6,7 +6,8 @@ import { useNavigate } from 'react-router-dom';
|
||||
import { ArrowUpDown, ArrowDown, ArrowUp, TrendingUp, UsersRound, Play, ListPlus } from 'lucide-react';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { usePlayerStore } from '../store/playerStore';
|
||||
import { CoverArtImage } from '../cover/CoverArtImage';
|
||||
import { AlbumCoverArtImage } from '../cover/AlbumCoverArtImage';
|
||||
import { ArtistCoverArtImage } from '../cover/ArtistCoverArtImage';
|
||||
import { playAlbum } from '../utils/playback/playAlbum';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
@@ -55,17 +56,6 @@ function formatPlays(n: number, t: ReturnType<typeof import('react-i18next').use
|
||||
/** Most-played list row cover layout px. */
|
||||
const MOST_PLAYED_COVER_CSS_PX = 80;
|
||||
|
||||
function MpCover80({ coverArt, alt, className }: { coverArt: string; alt: string; className: string }) {
|
||||
return (
|
||||
<CoverArtImage
|
||||
coverArtId={coverArt}
|
||||
displayCssPx={MOST_PLAYED_COVER_CSS_PX}
|
||||
surface="dense"
|
||||
alt={alt}
|
||||
className={className}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default function MostPlayed() {
|
||||
const { t } = useTranslation();
|
||||
@@ -169,7 +159,14 @@ export default function MostPlayed() {
|
||||
>
|
||||
<span className="mp-rank">{i + 1}</span>
|
||||
{artist.coverArt ? (
|
||||
<MpCover80 coverArt={artist.coverArt} alt="" className="mp-artist-avatar" />
|
||||
<ArtistCoverArtImage
|
||||
artistId={artist.id}
|
||||
coverArt={artist.coverArt}
|
||||
displayCssPx={MOST_PLAYED_COVER_CSS_PX}
|
||||
surface="dense"
|
||||
alt=""
|
||||
className="mp-artist-avatar"
|
||||
/>
|
||||
) : (
|
||||
<div className="mp-artist-avatar mp-artist-avatar--placeholder" />
|
||||
)}
|
||||
@@ -206,7 +203,14 @@ export default function MostPlayed() {
|
||||
>
|
||||
<span className="mp-album-rank">{sortAsc ? withPlays.length - i : i + 1}</span>
|
||||
{album.coverArt ? (
|
||||
<MpCover80 coverArt={album.coverArt} alt="" className="mp-album-cover" />
|
||||
<AlbumCoverArtImage
|
||||
albumId={album.id}
|
||||
coverArt={album.coverArt}
|
||||
displayCssPx={MOST_PLAYED_COVER_CSS_PX}
|
||||
surface="dense"
|
||||
alt=""
|
||||
className="mp-album-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="mp-album-cover mp-album-cover--placeholder" />
|
||||
)}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { usePlaybackCoverArt } from '../hooks/usePlaybackCoverArt';
|
||||
import { useCoverArt } from '../cover/useCoverArt';
|
||||
import { albumCoverRef } from '../cover/ref';
|
||||
import { usePlaybackTrackCoverRef } from '../cover/useLibraryCoverRef';
|
||||
import { coverArtIdFromRadio } from '../cover/ids';
|
||||
import type { SubsonicArtistInfo, SubsonicSong } from '../api/subsonicTypes';
|
||||
import React, { useState, useRef, useEffect, useCallback, useMemo, memo } from 'react';
|
||||
@@ -95,11 +96,14 @@ export default function NowPlaying() {
|
||||
showLyrics();
|
||||
}, [isQueueVisible, toggleQueue, showLyrics]);
|
||||
|
||||
const trackCover = usePlaybackCoverArt(currentTrack?.coverArt, 800);
|
||||
const resolvedCover = trackCover.src;
|
||||
const playbackCoverRef = usePlaybackTrackCoverRef(currentTrack ?? undefined);
|
||||
|
||||
const radioCoverArtId = currentRadio?.coverArt ? coverArtIdFromRadio(currentRadio.id) : undefined;
|
||||
const radioCover = useCoverArt(radioCoverArtId, 800, { surface: 'sparse' });
|
||||
const radioCover = useCoverArt(
|
||||
radioCoverArtId ? albumCoverRef(radioCoverArtId, radioCoverArtId) : null,
|
||||
800,
|
||||
{ surface: 'sparse' },
|
||||
);
|
||||
const resolvedRadioCover = radioCover.src;
|
||||
|
||||
const contributorRows = useMemo(
|
||||
@@ -242,7 +246,7 @@ export default function NowPlaying() {
|
||||
lfmLoved={lfmLoved}
|
||||
lfmLoveEnabled={lfmLoveEnabled}
|
||||
activeLyricsTab={activeTab === 'lyrics' && isQueueVisible}
|
||||
coverUrl={resolvedCover}
|
||||
coverRef={playbackCoverRef}
|
||||
onNavigate={stableNavigate}
|
||||
onToggleStar={toggleStar}
|
||||
onToggleLfmLove={toggleLfmLove}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useOfflineStore, type OfflineAlbumMeta } from '../store/offlineStore';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { usePlayerStore } from '../store/playerStore';
|
||||
import { CoverArtImage } from '../cover/CoverArtImage';
|
||||
import { AlbumCoverArtImage } from '../cover/AlbumCoverArtImage';
|
||||
import { usePerfProbeFlags } from '../utils/perf/perfFlags';
|
||||
import { albumGridWarmCovers } from '../cover/layoutSizes';
|
||||
import { VirtualCardGrid } from '../components/VirtualCardGrid';
|
||||
@@ -82,11 +83,12 @@ export default function OfflineLibrary() {
|
||||
return (
|
||||
<div className="album-card card offline-library-card">
|
||||
<div className="album-card-cover">
|
||||
{coverScope && album.coverArt ? (
|
||||
<CoverArtImage
|
||||
coverArtId={album.coverArt}
|
||||
displayCssPx={OFFLINE_CARD_COVER_CSS_PX}
|
||||
{coverScope ? (
|
||||
<AlbumCoverArtImage
|
||||
albumId={album.id}
|
||||
coverArt={album.coverArt}
|
||||
serverScope={coverScope}
|
||||
displayCssPx={OFFLINE_CARD_COVER_CSS_PX}
|
||||
surface="dense"
|
||||
alt={`${album.name} Cover`}
|
||||
loading="lazy"
|
||||
|
||||
@@ -134,7 +134,12 @@ export default function SearchResults() {
|
||||
)}
|
||||
|
||||
{results.albums.length > 0 && (
|
||||
<AlbumRow title={t('search.albums')} albums={results.albums} />
|
||||
<AlbumRow
|
||||
title={t('search.albums')}
|
||||
albums={results.albums}
|
||||
windowArtworkByViewport
|
||||
initialArtworkBudget={12}
|
||||
/>
|
||||
)}
|
||||
|
||||
{results.songs.length > 0 && (
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { CoverArtImage } from '../cover/CoverArtImage';
|
||||
import { AlbumCoverArtImage } from '../cover/AlbumCoverArtImage';
|
||||
import { getRandomSongs } from '../api/subsonicLibrary';
|
||||
import type { SubsonicSong } from '../api/subsonicTypes';
|
||||
import { songToTrack } from '../utils/playback/songToTrack';
|
||||
@@ -109,9 +110,10 @@ export default function Tracks() {
|
||||
{!perfFlags.disableMainstageHero && hero && (
|
||||
<section className="tracks-hero">
|
||||
<div className="tracks-hero-cover">
|
||||
{hero.coverArt ? (
|
||||
<CoverArtImage
|
||||
coverArtId={hero.coverArt}
|
||||
{hero.albumId && hero.coverArt ? (
|
||||
<AlbumCoverArtImage
|
||||
albumId={hero.albumId}
|
||||
coverArt={hero.coverArt}
|
||||
displayCssPx={600}
|
||||
surface="sparse"
|
||||
alt=""
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { coverArtRef, resolvePlaybackCoverScope } from '../../cover/ref';
|
||||
import { resolvePlaybackCoverScope } from '../../cover/ref';
|
||||
import { resolveTrackCoverRefFromLibrary } from '../../cover/resolveEntryLibrary';
|
||||
import { coverArtUrlForDiscord } from '../../cover/integrations/discord';
|
||||
import { useAuthStore } from '../authStore';
|
||||
import { usePlayerStore } from '../playerStore';
|
||||
@@ -82,13 +83,28 @@ export function setupDiscordPresence(): () => void {
|
||||
if (cached !== undefined) {
|
||||
sendPresence(cached);
|
||||
} else {
|
||||
const ref = coverArtRef(currentTrack.coverArt, resolvePlaybackCoverScope());
|
||||
coverArtUrlForDiscord(ref).then(url => {
|
||||
discordServerCoverCache.set(cacheKey, url);
|
||||
sendPresence(url);
|
||||
}).catch(() => {
|
||||
discordServerCoverCache.set(cacheKey, null);
|
||||
sendPresence(null);
|
||||
void resolveTrackCoverRefFromLibrary(
|
||||
{
|
||||
id: currentTrack.id,
|
||||
albumId: currentTrack.albumId,
|
||||
coverArt: currentTrack.coverArt,
|
||||
discNumber: (currentTrack as { discNumber?: number }).discNumber,
|
||||
},
|
||||
resolvePlaybackCoverScope(),
|
||||
).then(ref => {
|
||||
if (!ref) {
|
||||
sendPresence(null);
|
||||
return;
|
||||
}
|
||||
return coverArtUrlForDiscord(ref)
|
||||
.then(url => {
|
||||
discordServerCoverCache.set(cacheKey, url);
|
||||
sendPresence(url);
|
||||
})
|
||||
.catch(() => {
|
||||
discordServerCoverCache.set(cacheKey, null);
|
||||
sendPresence(null);
|
||||
});
|
||||
});
|
||||
}
|
||||
} else {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user