Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255/** * The grid view: album covers, virtualized as rows of cells. * * Two things keep this cheap at five-figure libraries. The rows are windowed by * the same VirtualList the track list uses, so no cover is even requested until * its cell exists — a plain CSS grid of everything would create thousands of * <img> nodes and fire thousands of getCoverArt requests. And the component is * never unmounted to switch modes (see LibraryView), so its scroll position and * loaded images survive a trip to the list and back. */import { createMemo, createSignal, For, Show, onCleanup, onSettled, untrack, type Component,} from "solid-js";
import { connectionSignal } from "../lib/connection";import { coverHasLanded, coverRequestSize, createScrollPace, markCoverLanded,} from "../lib/library/covers";import { gridColumns, gridRows, sameRows, type GridAlbum } from "../lib/library/grid";import { traceCellMount, traceCoverHeld, traceCoverLanded, traceImgMount, traceRecompute, traceWidthWrite,} from "../lib/library/gridtrace";import { SubsonicClient } from "../lib/subsonic/client";import { VirtualList } from "./VirtualList";
/** Cell metric. Fixed so the virtualizer's row math stays trivial. */export const CELL_ART = 160;export const CELL_W = 160;export const CELL_H = 208; // art + two caption linesexport const CELL_GAP = 10;
export interface AlbumGridProps { cells: GridAlbum[]; onSelect: (cell: GridAlbum) => void; /** Test escape hatches, mirroring VirtualList's viewportHeight. */ columns?: number; viewportHeight?: number;}
export const AlbumGrid: Component<AlbumGridProps> = (props) => { const [width, setWidth] = createSignal(0, { name: "grid-width" }); let frame: HTMLDivElement | undefined = undefined;
// One client for the whole grid, not one per cell: it is built from the same // connection and only ever used to assemble a cover URL, and a screenful of // cells was constructing dozens of them. const client = createMemo( () => { const c = connectionSignal(); return c ? new SubsonicClient(c) : null; }, { name: "grid-client" }, );
// The queue, guarded. See lib/library/covers: a fling asks for hundreds of // server-side thumbnails that will be off the screen before they land, and // they go in front of the ones the reader stopped for. const [flinging, setFlinging] = createSignal(false, { name: "cover-flinging" }); const pace = createScrollPace(CELL_H, setFlinging); onCleanup(() => pace.dispose());
// Width comes from the non-scrolling frame, not the scroller: a vertical // scrollbar would otherwise feed a resize back into the column count. No // synchronous clientWidth read — see VirtualList; the observer's first // delivery is the measurement, and reading layout here would force a reflow // on top of the rows that were just created. onSettled(() => { const el = frame as HTMLDivElement | undefined; // ref assignment defeats narrowing if (!el || typeof ResizeObserver === "undefined") return; // jsdom has none const ro = new ResizeObserver(() => { const px = el.clientWidth; // Only a *change* is churn: the observer's first delivery is the one // measurement everybody waits for, and it is not a loop. if (import.meta.env.DEV && px !== width()) traceWidthWrite(px); setWidth(px); }); ro.observe(el); // fires once immediately with the current size return () => ro.disconnect(); });
// The frame is measured, but the rows live inside `.album-scroll`, which // carries CELL_GAP of padding on each side and does not give it to the cells. // Counting columns out of the frame's own width could therefore seat a whole // cover in the padding — invisible while the row was packed to the left, and // a clipped edge the moment the row is centred, because centring sends half of // that overshoot off each side. const columns = createMemo( () => props.columns ?? gridColumns(width() - 2 * CELL_GAP, CELL_W + CELL_GAP, CELL_GAP), { name: "grid-columns" }, );
// Dev-only witnesses for the probe: what the last run produced. Not state — // plain locals written in the memo body, which is the only place that knows a // run happened at all (an effect would not fire on a retained one). let lastOut: GridAlbum[][] | undefined = undefined; const rows = createMemo( () => { const cols = columns(); const cells = props.cells; const next = gridRows(cells, cols); if (import.meta.env.DEV) { // The question the line has to answer is not "did this run" but "did // the window have to be rebuilt" — which is what `equals` decides, and // the same test, so the two can never disagree. The first run counts as // a rebuild: before it there was no window to keep. const rebuilt = lastOut === undefined || !sameRows(lastOut, next); traceRecompute( "grid-rows", rebuilt, `${cells.length} cells × ${cols} cols` + (lastOut === undefined ? " (first)" : rebuilt ? " (rebuilt)" : " (retained)"), ); lastOut = next; } return next; }, { equals: sameRows, name: "grid-rows" }, );
return ( // `--album-cols` is the column count handed to CSS, which lays the row out on // that many fixed tracks and centres them as a block (see `.album-cellrow`). // One number, counted here and obeyed there, so the virtualizer's row height // and the browser's row cannot disagree about where a cover sits. <div ref={frame} class="album-grid" style={{ "--album-cols": String(columns()) }}> <VirtualList items={rows()} itemHeight={CELL_H} viewportHeight={props.viewportHeight} buffer={CELL_H * 3} class="album-scroll" onScrollTopChange={(top) => pace.onScroll(top)} > {(row) => ( <div class="album-cellrow"> <For each={row}> {(cell) => ( <AlbumCell cell={cell} client={client} hold={flinging} onSelect={props.onSelect} /> )} </For> </div> )} </VirtualList> </div> );};
const AlbumCell: Component<{ cell: GridAlbum; client: () => SubsonicClient | null; /** True while the scroller is moving fast enough that a cover asked for now will not be seen. */ hold: () => boolean; onSelect: (c: GridAlbum) => void;}> = (props) => { if (import.meta.env.DEV) traceCellMount(); const url = () => { const c = props.client(); const id = props.cell.coverId; // Asked for at the size the tile is drawn into rather than a flat 2×: the // server resamples every cover, so the doubled request was four times the // work on a 1× screen for pixels nobody has a screen for. return c && id ? c.coverArtUrl(id, coverRequestSize(CELL_ART)) : ""; }; // A cover that already landed this session is a memory-cache hit: it is not // standing in the queue's way, so it is not held behind the queue either, and // it does not need to fade up from initials a second time. const landed = () => coverHasLanded(url()); const [loaded, setLoaded] = createSignal(untrack(landed), { name: "cell-loaded" }); const [failed, setFailed] = createSignal(false, { name: "cell-failed" }); if (import.meta.env.DEV) { traceCellMount(); // Counted at birth: a cell born mid-fling and held is the request that used // to go out and queue behind the last screenful. if (untrack(() => props.hold() && !landed())) traceCoverHeld(); }
return ( <button type="button" class="album-cell" title={`${props.cell.artist} — ${props.cell.name}`} onClick={() => props.onSelect(props.cell)} > <span class="album-art" data-loaded={loaded() ? "true" : "false"}> {/* Under the image, not instead of it: covers arrive over the network, and a tile that is empty until then makes the whole grid look like it appears a second late. Initials + caption give the cell its final shape immediately; the art fades in over them. */} <span class="album-art-ph" aria-hidden="true"> {initials(props.cell.name)} </span> {/* Held while the reader is in motion, unless we already have these bytes. The tile's shape does not change, so holding is invisible — which is the whole trick: the work that used to arrive late is work that is now never asked for. */} <Show when={url() && !failed() && (!props.hold() || landed())}> <img class="album-img" src={url()} alt="" width={CELL_ART} height={CELL_ART} loading="lazy" decoding="async" // Read off the node, not from `url()`: a ref runs in the scope that // created the element, and subscribing it to the cover URL would // make the probe itself a reason to re-render. ref={(el) => { if (import.meta.env.DEV) traceImgMount(el.getAttribute("src") ?? ""); }} onLoad={() => { const u = url(); markCoverLanded(u); if (import.meta.env.DEV) traceCoverLanded(u); setLoaded(true); }} onError={() => setFailed(true)} /> </Show> </span> <span class="album-name">{props.cell.name}</span> <span class="album-artist"> {props.cell.artist} {props.cell.year ? <span class="album-year"> {props.cell.year}</span> : null} </span> </button> );};
/** Two letters of the album title, for the tile shown before or instead of art. */export function initials(name: string): string { const words = name .replace(/^[([]?\s*(the|a|an)\s+/i, "") .trim() .split(/\s+/); const first = words[0] ?? ""; const second = words.length > 1 ? (words[1] ?? "") : ""; return (first[0] ?? "?").toUpperCase() + (second[0] ?? first[1] ?? "").toUpperCase();}