/**
* 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
* 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 lines
export 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 = (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.
pace.onScroll(top)}
>
{(row) => (
{(cell) => (
)}
)}
);
};
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 (
);
};
/** 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();
}