Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283import { createEffect, createMemo, createSignal, For, onSettled, untrack } from "solid-js";import type { JSX } from "@solidjs/web";import { count } from "../lib/print";
/** * Minimal fixed-height virtual list — no dependency, because the Solid 2.0 * RC ecosystem makes third-party list libs a coin flip (see persist.ts for * the war story). Fixed row height is by design: section rows and track * rows share one row metric, so the windowing math stays trivial. * * `viewportHeight` is overridable for tests (jsdom has no layout). */export interface VirtualListProps<T> { items: T[]; itemHeight: number; /** px rendered above/below the visible window */ buffer?: number; viewportHeight?: number; class?: string; onScrollTopChange?: (top: number) => void; /** * Row to align with the top of the window, carrying a nonce so writing the * same row again still scrolls (clicking the same cover twice). Applied by an * effect rather than by poking scrollTop from a click handler: a hidden * (inert / visibility:hidden) scroller can refuse the write, and this gets to * try again when `active` flips — see `active`. * * `keepInView` changes the question from "scroll to this row" to "only scroll if * this row has left the screen", which is what a cursor moving one row at a * time needs: otherwise every keystroke scrolls a line and the list slides * under a reader who is not moving. Judged against the *visible* window, not the * buffered one — the buffer exists to have rows ready to render, and treating it * as visibility would let the cursor walk a screenful below the fold before the * list deigned to follow. * * `center` is `keepInView`'s answer with a different place to land: the row goes * to the middle of the window instead of an edge, and still only when it has * actually left the screen. It is for a key that moves the *subject* — `n`/`p` * asking for the next record — where the reader wants to see what comes next in * context rather than pressed against the fold, and where a list that re-centred * on every keystroke would be a list that never stops moving. `offset` is not * consulted: centring is its own alignment. */ scrollTo?: { row: number; offset?: number; n: number; keepInView?: boolean; center?: boolean; } | null; /** False while this list is the inactive view. */ active?: boolean; /** * Pinned chrome for the first visible row — e.g. the artist and album * headers governing the track under the fold. Called (from a tracking memo) * with the first visible index whenever the window moves; the pairs it * returns render as an overlay on top of the scroller, outside it, so they can * pin while the window itself translates. `position: sticky` cannot do this: * rows live inside the translated window, and sticky would confine them to ~a * screen of siblings. * * Pairs rather than elements, because a computation owns the DOM built in its * callback: nodes minted inside the memo that drives this would have their * bindings torn down by the *next* scroll frame, while a caller-side cache went * on handing those now-dead nodes back to the overlay — a pinned header that * had silently stopped following the section it pins. Callers return plain * data; identity is handled here, as it is for the window. */ sticky?: (firstVisible: number) => [T, number][] | null; /** How one pinned row is rendered — the caller's row markup, minus whatever * must not be duplicated on a copy of a row that is also in the list. */ renderSticky?: (item: T, index: number) => JSX.Element; children: (item: T, index: number) => JSX.Element;}
export function VirtualList<T>(props: VirtualListProps<T>) { const [scrollTop, setScrollTop] = createSignal(0); const [measured, setMeasured] = createSignal(0); let scroller: HTMLDivElement | undefined = undefined;
const buffer = () => props.buffer ?? 300; const viewport = () => props.viewportHeight ?? measured(); const itemCount = () => props.items.length; const totalHeight = () => itemCount() * props.itemHeight;
const start = () => Math.max(0, Math.floor((scrollTop() - buffer()) / props.itemHeight)); const end = () => Math.min(itemCount(), Math.ceil((scrollTop() + viewport() + buffer()) / props.itemHeight));
// Tripwire, not a clamp: a window taller than ~400 items means the scroller // is content-sized — the classic broken flex/height chain, where the RO // reports the sizer's own 880k px as the viewport and the "virtual" list // renders the entire library (221k nodes, 750ms forced reflows). Say so. if (import.meta.env.DEV) { let warned = false; createEffect( () => [end() - start(), itemCount()] as const, ([visible, total]) => { if (!warned && total > 2 * visible && visible > 400) { warned = true; console.warn( `[vlist] viewport fits ${count(visible, "item")} — the scroller is probably content-sized ` + `(check the html>body>.lib>.pane>.lib-scroll height/flex chain). Rendering everything; ` + `this is the 220k-node failure mode.`, ); } }, { name: "vlist-tripwire" }, ); }
// The reveal lives in state, not in a click handler, for two reasons: the // hidden scroller can refuse a scrollTop write (so the jump must be re-applied // when the pane becomes active), and the window must follow the number rather // than hope a scroll event arrives. createEffect( () => [props.scrollTo, props.active] as const, ([target, active]) => { const el = scroller as HTMLDivElement | undefined; // ref assignment defeats narrowing if (!el || !target || active === false) return; // A deliberate snapshot, hence untrack: this asks "is the row on screen *now*, // at the moment of the jump", and must not subscribe — a viewport re-measure is // no reason to replay a scroll the user has since moved on from. The effect // already re-runs on `scrollTo` and on `active`. const visible = untrack(() => viewport()); // Untracked for the same reason, and with a sharper edge: `props.items` is a // getter that evaluates the *parent's* expression, so reading it from here // evaluates the caller's `rows()` memo inside this effect's scope — which is a // `STRICT_READ_UNTRACKED` on somebody else's computation, and a scroll replayed // on every rebuild is the behaviour that would follow. The height is asked for // as it stands at the moment of the jump, which is the only moment it matters. const maxScroll = Math.max(0, untrack(() => totalHeight()) - visible); const first = Math.max(0, Math.floor(el.scrollTop / props.itemHeight)); const last = Math.ceil((el.scrollTop + visible) / props.itemHeight); const onScreen = target.row >= first && target.row < last;
// "Only if it left the screen", in both of its shapes: a cursor walking one row // at a time and a key asking for the next record both mean a list that slides // under a reader who is not moving if it answers every time. if (target.keepInView || target.center) { if (onScreen) return; }
// Centred rather than aligned to an edge: the row's own top half a window away // from the middle, so there is as much list above it as below. Clamped at zero — // the first rows cannot be pulled up to the middle, and pretending otherwise // would have the list jump to the top and stop, which reads as a bug. const wanted = target.center ? target.row * props.itemHeight - Math.max(0, visible - props.itemHeight) / 2 : (target.row + (target.offset ?? 0)) * props.itemHeight; // Clamped here rather than left to the browser: the retry below asks whether the // write was accepted, and an intentionally overshoot target would fail that // question forever, re-arming a frame every frame at the bottom of a list. const top = Math.min(Math.max(0, wanted), maxScroll); const apply = () => { el.scrollTop = top; // Read back what the browser accepted rather than assuming it took the // write: an inactive scroller can refuse it, and the window must follow // the truth or it renders rows that are not on screen. One layout read // on a deliberate jump is worth that correctness. setScrollTop(el.scrollTop); }; apply(); // A pane that has only just become visible can refuse the write — the // compositor has not caught up with the visibility flip. Ask again next // frame, when it certainly has; without this the reveal silently does // nothing in the browser while every jsdom test passes. if (el.scrollTop !== top) requestAnimationFrame(apply); }, { name: "vlist-scroll-to" }, );
// Observe the viewport once the component settles. `onSettled` is the 2.0 // replacement for onMount+onCleanup: it cannot host onCleanup(), so the // teardown is *returned* and runs when this component's owner disposes. // (onSettled also cannot be re-entered for re-runs — reads here are untracked // by design, which is what we want: one observer per mount.) // // No initial `el.clientHeight` read: reading layout here forces a synchronous // reflow right after the rows were built (the "Forced reflow while executing // JavaScript" violation). ResizeObserver delivers the size on observe, in a // callback the browser runs when layout is already clean. onSettled(() => { const el = scroller as HTMLDivElement | undefined; // ref assignment defeats narrowing if (!el) return; if (typeof ResizeObserver === "undefined") return; // jsdom has none const ro = new ResizeObserver(() => setMeasured(el.clientHeight)); ro.observe(el); // fires once immediately with the current size return () => ro.disconnect(); });
// [item, absoluteIndex] pairs keep the For callback free of index signals — // but they must be *reused*, not rebuilt. <For> keys rows by item identity, so // handing it a fresh tuple for a row that is still on screen disposes that // row's DOM and state and recreates it on every scroll frame (the // UNSTABLE_LIST_IDENTITY diagnostic). Only the window is retained, so the // cache is bounded by what is rendered, not by the size of the library. let tuples = new Map<number, [T, number]>(); // A scroll tick fires per pixel, and most pixels do not change *which* rows are // on screen. Without this gate the memo republishes a new array of identical // tuples on every one of those ticks, every subscriber re-runs, and the whole // rendered window recomputes for a one-pixel move — UNSTABLE_MEMO_OUTPUT said as // much the moment the keyboard cursor started nudging the scroll. The tuples // above are reused rather than rebuilt, so comparing them by identity is both // cheap and exactly the question being asked. const sameWindow = (a: [T, number][], b: [T, number][]) => a.length === b.length && a.every((pair, i) => pair === b[i]); const visible = createMemo<[T, number][]>( () => { const items = props.items; const previous = tuples; const next = new Map<number, [T, number]>(); const out: [T, number][] = []; for (let i = start(); i < end(); i++) { const item = items[i]; const held = previous.get(i); const pair = held && held[0] === item ? held : ([item, i] as [T, number]); next.set(i, pair); out.push(pair); } tuples = next; return out; }, { equals: sameWindow, name: "vlist-visible" }, );
// Which rows are pinned, as [row, index] pairs — see `props.sticky` for why this // memo returns data and never DOM. Comparison is by pair identity, the same // contract the window's tuples above honour: `<For>` below keys rows by item, so // the caller interns the pairs it hands back and most scroll frames publish // nothing at all. const samePinned = (a: [T, number][] | null, b: [T, number][] | null) => a === b || (!!a && !!b && a.length === b.length && a.every((pair, i) => pair === b[i])); const pinned = createMemo( () => { const fn = props.sticky; if (!fn || itemCount() === 0) return null; const first = Math.min(itemCount() - 1, Math.floor(scrollTop() / props.itemHeight)); const wanted = fn(first); return wanted && wanted.length > 0 ? wanted : null; }, { equals: samePinned, name: "vlist-pinned" }, );
return ( <> <div ref={scroller} class={props.class} onScroll={(e) => { const top = e.currentTarget.scrollTop; setScrollTop(top); props.onScrollTopChange?.(top); }} > {/* The tall empty div inspectors ask about. It exists to give the scroller a real scrollHeight, so the native scrollbar, wheel, Space/PgDn and touch momentum all work on a 10k-row library exactly as they would on a 10k-row list; the rows themselves live in the absolutely positioned window below and are moved with a composited translateY. One node, no children, no per-pixel cost — the alternative is synthesizing scroll physics in JS, which is worse. */} <div class="vlist-sizer" style={{ height: `${totalHeight()}px` }}> <div class="vlist-window" style={{ transform: `translateY(${start() * props.itemHeight}px)` }} > <For each={visible()}>{([item, index]) => props.children(item, index)}</For> </div> </div> </div> {/* Pinned section chrome — outside the scroller so it can't scroll away, pointer-events:none so its duplicate rows never eat a click meant for the real row under it. */} {pinned() && props.renderSticky ? ( <div class="vlist-sticky" aria-hidden="true"> <For each={pinned()}>{([item, index]) => props.renderSticky!(item, index)}</For> </div> ) : null} </> );}