Perf/UI cover cache mainstage (#468)

* Enhance CachedImage and ArtistDetail components with improved image caching and priority handling

- Refactor CachedImage to utilize a priority system for image loading based on viewport visibility, improving performance during scrolling.
- Update useCachedUrl to accept an optional getPriority function for better cache management.
- Optimize ArtistDetail and Artists components by using useMemo for cover art URLs, reducing redundant calculations and improving rendering efficiency.
- Adjust image loading logic in CachedImage to ensure smoother transitions and avoid unnecessary fetch requests.

* perf(ui): unblock IDB cover art, stabilize mainstage rails and virtual lists

Let IndexedDB reads bypass the network concurrency slot so cached thumbnails
paint without queueing behind remote fetches; debounce disk eviction during
heavy scrolling.

Fix mainstage horizontal rails: dedupe album/song ids for React keys, widen
artwork budget overscan, avoid resetting the budget on list append, and raise
Home initial artwork budgets. CachedImage treats already-decoded images as
loaded; rail cards load cover images eagerly.

Refresh dynamic color extraction and extend virtual scrolling / scroll roots on
Albums, Artists, Playlists, and related surfaces.


Remove local agent-only commit instructions from the repository tree.

* perf(virtual): viewport-based overscan for main scroll lists

Drive TanStack Virtual overscan from measured scroll height so each list
renders about one screen of extra rows above and below the viewport for
snappier scrolling on Albums, Artists (list mode), and Tracks virtual song list.

Introduce useResizeClientHeight helpers (ID + ref) for ResizeObserver-based
clientHeight tracking.

* docs(changelog): note PR #468 UI cover cache, rails, and virtual lists

Add a coarse summary under 1.46.0 Changed for cover-art pipeline,
mainstage rails, viewport-based overscan, and library/chrome polish.
This commit is contained in:
cucadmuh
2026-05-06 00:15:58 +03:00
committed by GitHub
parent d8d8a76e0f
commit 9d30285ff1
23 changed files with 895 additions and 279 deletions
+82 -19
View File
@@ -1,4 +1,5 @@
import React, { useEffect, useRef, useState } from 'react';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { APP_MAIN_SCROLL_VIEWPORT_ID } from '../constants/appScroll';
import { acquireUrl, getCachedBlob, releaseUrl } from '../utils/imageCache';
interface CachedImageProps extends React.ImgHTMLAttributes<HTMLImageElement> {
@@ -17,7 +18,19 @@ interface CachedImageProps extends React.ImgHTMLAttributes<HTMLImageElement> {
* loading immediately. Pass false for CSS background-image consumers that
* should only see a stable blob URL (prevents a double crossfade).
*/
export function useCachedUrl(fetchUrl: string, cacheKey: string, fallbackToFetch = true): string {
export function useCachedUrl(
fetchUrl: string,
cacheKey: string,
fallbackToFetch = true,
getPriority?: () => number,
): string {
// `buildCoverArtUrl` rotates salt/token on every call — `fetchUrl` is a new
// string each render though the logical image is unchanged (`cacheKey`). If
// `fetchUrl` were an effect dependency, cleanup would run every frame, call
// `releaseUrl`, revoke the blob, and break <img> until onError hides it.
const fetchUrlRef = useRef(fetchUrl);
fetchUrlRef.current = fetchUrl;
// Synchronously acquire on first render when the blob is already hot. This
// makes the very first <img src> a blob URL, avoiding a fetchUrl→blobUrl
// swap that would trigger a redundant network request and decode pass.
@@ -26,6 +39,9 @@ export function useCachedUrl(fetchUrl: string, cacheKey: string, fallbackToFetch
// exactly what to release on cleanup or when keys change.
const ownedKeyRef = useRef<string | null>(resolved ? cacheKey : null);
const getPriorityRef = useRef(getPriority);
getPriorityRef.current = getPriority;
useEffect(() => {
const release = () => {
if (ownedKeyRef.current) {
@@ -34,14 +50,17 @@ export function useCachedUrl(fetchUrl: string, cacheKey: string, fallbackToFetch
}
};
if (!fetchUrl) {
const currentUrl = fetchUrlRef.current;
if (!currentUrl) {
release();
setResolved('');
return;
return release;
}
// Lazy initializer (or a previous run) already acquired the right key.
if (ownedKeyRef.current === cacheKey) return release;
// Same logical image as last run — only `cacheKey` drives this effect.
if (ownedKeyRef.current === cacheKey) {
return release;
}
// Different key than we're currently holding: drop the old one.
release();
@@ -57,7 +76,7 @@ export function useCachedUrl(fetchUrl: string, cacheKey: string, fallbackToFetch
// Slow path: fetch (or read from IDB), then acquire.
setResolved('');
const controller = new AbortController();
getCachedBlob(fetchUrl, cacheKey, controller.signal).then(blob => {
getCachedBlob(currentUrl, cacheKey, controller.signal, () => getPriorityRef.current?.() ?? 0).then(blob => {
if (controller.signal.aborted || !blob) return;
const url = acquireUrl(cacheKey);
if (!url) return;
@@ -68,32 +87,59 @@ export function useCachedUrl(fetchUrl: string, cacheKey: string, fallbackToFetch
controller.abort();
release();
};
}, [fetchUrl, cacheKey]);
}, [cacheKey]);
return fallbackToFetch ? (resolved || fetchUrl) : resolved;
}
export default function CachedImage({ src, cacheKey, style, onLoad, onError, ...props }: CachedImageProps) {
const [inView, setInView] = useState(false);
const [fallbackSrc, setFallbackSrc] = useState<string | undefined>(undefined);
const imgRef = useRef<HTMLImageElement>(null);
/**
* Drives disk/network waiter ordering only. We intentionally do **not** gate
* `useCachedUrl` on intersection — relying on IO to “arm” loading proved brittle
* (custom scroll roots, content-visibility, horizontal rails) and led to blank covers.
*/
const priorityRef = useRef(0);
const getViewportImagePriority = useCallback(() => priorityRef.current, []);
useEffect(() => {
const el = imgRef.current;
if (!el) return;
const root =
typeof document !== 'undefined'
? (document.getElementById(APP_MAIN_SCROLL_VIEWPORT_ID) as Element | null)
: null;
const updateFromEntry = (entry: IntersectionObserverEntry) => {
if (entry.isIntersecting) {
const r = entry.boundingClientRect;
const rootEl = entry.rootBounds;
const vh = (rootEl?.height ?? window.innerHeight) || 1;
const originTop = rootEl?.top ?? 0;
const vc = originTop + vh * 0.5;
const cy = r.top + r.height * 0.5;
const dist = Math.abs(cy - vc);
priorityRef.current = entry.intersectionRatio * 1e7 - dist * 1e3;
} else {
priorityRef.current = -1e12;
}
};
const observer = new IntersectionObserver(
([entry]) => { if (entry.isIntersecting) { setInView(true); observer.disconnect(); } },
{ rootMargin: '300px' }, // start fetching 300px before entering viewport
entries => { for (const e of entries) updateFromEntry(e); },
{
root: root ?? undefined,
rootMargin: '300px',
threshold: [0, 0.02, 0.1, 0.25, 0.5, 0.75, 1],
},
);
observer.observe(el);
return () => observer.disconnect();
}, []);
// Pass empty string when not yet in view so useCachedUrl skips the fetch entirely.
// fallbackToFetch=false: avoid the fetchUrl→blobUrl src swap, which causes the browser
// to start a server fetch, then abort it when we replace src with the blob URL —
// visible in DevTools as a flood of "Pending / 0 B" requests on Chromium/WebView2.
const resolvedSrc = useCachedUrl(inView ? src : '', cacheKey, false);
// Same as Hero/PlayerBar: show the salted fetch URL while IndexedDB/network resolves,
// then swap to the shared blob URL — avoids an <img> with no src and opacity stuck at 0.
// Priority still applies to the slow path inside getCachedBlob.
const resolvedSrc = useCachedUrl(src, cacheKey, true, getViewportImagePriority);
const [loaded, setLoaded] = useState(false);
// Reset only when the logical image changes (cacheKey), not on fetchUrl→blobUrl
@@ -103,6 +149,26 @@ export default function CachedImage({ src, cacheKey, style, onLoad, onError, ...
setFallbackSrc(undefined);
}, [cacheKey]);
const isFallback = fallbackSrc !== undefined;
const finalSrc = fallbackSrc ?? (resolvedSrc || undefined);
// Browsers sometimes skip `load` for cache hits / lazy + horizontal scroll — unstick opacity.
useEffect(() => {
if (!finalSrc) return;
let alive = true;
const id = requestAnimationFrame(() => {
if (!alive) return;
const img = imgRef.current;
if (img?.complete && img.naturalWidth > 0) {
setLoaded(true);
}
});
return () => {
alive = false;
cancelAnimationFrame(id);
};
}, [finalSrc]);
const handleError = (e: React.SyntheticEvent<HTMLImageElement>) => {
if (onError) {
// Caller wants custom error handling (e.g. hide the element)
@@ -114,9 +180,6 @@ export default function CachedImage({ src, cacheKey, style, onLoad, onError, ...
}
};
const isFallback = fallbackSrc !== undefined;
const finalSrc = fallbackSrc ?? (resolvedSrc || undefined);
const fallbackStyle: React.CSSProperties = isFallback
? { objectFit: 'contain', background: 'var(--bg-card, var(--ctp-surface0, #313244))', padding: '15%' }
: {};