hackermusic docs research rendering-performance.md
16 kB · 305 lines
Markdown
at main

Research: rendering TONS of elements at 60fps #

Goal context: hackermusic is a keyboard-driven player for Subsonic/Navidrome servers. Realistic worst cases: a 10k-track library view, an album grid of ~2k covers, a queue with thousands of rows, instant fuzzy-search filtering of all of it. Findings below, ordered from "free" to "heavy machinery".

0. Principle: fewer DOM nodes first, tricks second #

Every trick below is a mitigation for having too many live DOM nodes. The best render is the one that never happens:

  • Render only what can scroll into view (virtualization) or what is near it (content-visibility).
  • Keep rows dead simple: one row = ~4–6 elements (art placeholder, title, artist, duration, maybe a button). Rows built from 30-node component trees kill scroll perf no matter what virtualizer you use.
  • Defer richness: render a row skeleton cheaply; hydrate play-count badges, waveform thumbnails, action menus only when visible/idle.
  • Paginate server-side (getAlbumList2/search3 are already paged) — the UI should only ever hold what the user has browsed, not the entire DB.

1. Native browser machinery (no dependencies) #

CSS content-visibility: auto — the "native virtualization" #

Skips layout+paint (and rendering subtree work) for off-screen elements while keeping them in the DOM. Measured in the wild: ~15x reduction in forced reflow cost on heavy pages, ~40% less rendering/painting time for offscreen sections.

.track-row,
.album-card {
  content-visibility: auto;
  contain-intrinsic-size: auto 40px; /* remember last-rendered size */
}

Rules of thumb:

  • Apply to self-contained items/blocks, not the scroll container.
  • Always pair with contain-intrinsic-size (auto <estimate>) or the scrollbar jumps / CLS explodes. The auto keyword lets the browser cache the real size after first render.
  • Keeps native Ctrl+F, find-in-page, accessibility, and focus order working — things JS virtualization breaks.
  • Caveat: DOM nodes stay in memory and layout tree cost still scales with node count. Fine up to roughly 1k–3k items; beyond that use real virtualization (sources agree on this threshold).
  • If items are tiny, group them into blocks (e.g. 50–100 rows per block element) and put content-visibility on the blocks to cut management overhead.
  • Support caveat: it's a Chromium-born feature; feature-detect and fall back to JS virtualization where absent.

CSS containment #

.track-row {
  contain: layout style paint;
} /* or contain: content */

Isolates a subtree so layout/paint/style changes inside it can't invalidate the rest of the page. Cheap, safe on every row. content-visibility: auto already implies containment; use explicit contain for rows that are always visible (e.g. the currently-playing row chrome).

  • contain: layout — internal layout can't affect outside.
  • contain: paint — subtree never paints outside its bounds; also promotes a stacking context.
  • contain: strict (adds size containment) for fixed-size slots like cover art tiles whose size we dictate anyway.

Layer & animation hygiene #

  • Animate only transform and opacity (compositor-only, no layout/paint). Position virtualized items with transform: translateY() (virtua/tanstack both do this) — never top.
  • will-change: transform only on elements that are actually animating right now, and remove it after — blanket will-change wastes GPU memory and can make things slower.
  • Avoid box-shadow, filter, backdrop-filter on scrollable row content; pre-render effects into images or apply them only to hover/focus states of a single row.
  • contain: paint gives you a compositing boundary for free.

DOM-write discipline #

  • Batch writes, then read. Interleaved element.offsetHeight reads after writes cause layout thrash. In scroll handlers: read scrollTop once (passive listener), compute, then write.
  • Build subtrees in a DocumentFragment and append once when injecting many nodes manually (Solid mostly does the right thing already; this matters for imperative DOM code, e.g. rendering a canvas waveform legend).
  • Throttle scroll/UI work with requestAnimationFrame; keep scroll and wheel/touch listeners passive (never call preventDefault in them).
  • overscroll-behavior: contain on inner scroll panes stops scroll chaining and avoids full-page rubber-band work — great for the multi-pane layout we want.
  • overflow-anchor: none on virtualized scroll containers (required by virtua) to stop browser scroll-anchoring fights.

Chunked rendering — scheduler.yield() (Chromium 129+) + fallback #

When a huge list must materialize (e.g. user hits "end" in queue, or a filter matches 8k rows), don't render it in one long task. Yield to the browser between chunks so keystrokes/scroll stay at 60fps:

function yieldToMain(): Promise<void> {
  if ("scheduler" in window && "yield" in window.scheduler) {
    return window.scheduler.yield();
  }
  // Fallback: MessageChannel beats setTimeout (no 4ms nested-timer clamp)
  return new Promise((resolve) => {
    const ch = new MessageChannel();
    ch.port1.onmessage = () => {
      ch.port1.close();
      resolve();
    };
    ch.port2.postMessage(null);
  });
}

async function renderChunked<T>(items: T[], renderItem: (t: T) => void) {
  for (let i = 0; i < items.length; i += 200) {
    items.slice(i, i + 200).forEach(renderItem);
    await yieldToMain();
  }
}

Media/lazy-loading primitives #

  • Cover art: <img loading="lazy" decoding="async" fetchpriority="low" decoding=async> inside a fixed aspect-ratio: 1 container (so layout never shifts when the image lands). decoding="async" keeps decode off the main-thread paint path.
  • <img> for art beats CSS background-image for lazy-loading and priority hints.
  • IntersectionObserver (not scroll math): use for "hydrate when near" — attach expensive stuff (EqualizerCanvas, row action buttons, listeners) only when a row enters an expanded root margin; tear down when it leaves.

View Transitions API (same-document) #

For route morphs (artist page → album grid → track list) use document.startViewTransition() with view-transition-name on only the few elements that should morph (e.g. the cover art flying from grid tile to now-playing bar). Snapshots are real work: keep the DOM shallow during capture, unique names per snapshot (duplicate names skip the transition), and clear the names after the transition. Compositor-driven, so it's cheap if you name little.

Audio-adjacent (off the render path entirely) #

Playback must never compete with list rendering:

  • Decode/stream in a worker-adjacent setup; serve cached tracks from OPFS using createSyncAccessHandle() inside a Web Worker — dramatically faster than IndexedDB for binary blobs and never touches the main thread's event loop. Use IndexedDB (via idb) for metadata, favorites, config only.
  • Feed <audio>/<audio-worklet> via URL.createObjectURL() from OPFS blobs, or MediaSource; revoke URLs when done. Never data URLs.
  • Pass buffers across threads with transferables (zero-copy) or structuredClone; wrap the worker in comlink for ergonomics.
  • Media Session API for OS media keys — keyboard-driven includes hardware keys.

2. Virtualization packages (2026 landscape) #

Package Solid support Size Notes
virtua (virtua/solid) first-class (VList, Virtualizer, WindowVirtualizer, experimental VGrid) ~3 kB gz, tree-shakeable Zero-config: measures dynamic sizes itself (ResizeObserver), handles reverse/infinite scroll, RTL, scroll restoration, smooth scrollToIndex, DnD, keyboard navigation, sticky. Best feature matrix for a music app.
@tanstack/solid-virtual (3.13.x) headless createVirtualizer / createWindowVirtualizer small, headless Maximum control, great dynamic measurement; you build the markup yourself (pass getters for count/scroll element to stay reactive). Known edge: Suspense interplay.
@solid-primitives/virtual (0.2.x) native Solid (createVirtualList + <VirtualList>) tiny Simplest option: fixed item height, unstyled vertical lists. Track rows are fixed-height — legitimately sufficient and cheapest.

Decisions from the 2026 comparisons: virtuoso-class batteries-included APIs are React-only; react-window is effectively maintenance-mode (avoid for new projects); TanStack Virtual is the headless standard across frameworks; virtua is the "fast + zero-config, solid adapter" pick and the only one with first-class Solid components plus a grid story (album art grids).

Recommendation for hackermusic:

  • Track lists / queue / search results: virtua VList (or TanStack headless if we want to own the DOM). Track rows are uniform-height, so either is trivially fast; virtua gives scrollToIndex for the keyboard-driven "jump to playing track" for free.
  • Album/artist grids: virtua's experimental VGrid or a CSS-Grid + virtualized-columns hybrid.
  • Under ~1k items (settings panes, playlists): no virtualization at all — just content-visibility: auto on sections.
  • Virtualizing breaks Ctrl+F — fine here: the app has its own keyboard-driven fuzzy search (also faster than find-in-page on a virtualized list).

Integration notes that matter:

  • Fixed-height rows (~40px) + estimateSize exact ⇒ no measure pass, no scroll jitter. Measure-once cache keyed by track id for any variable-height elements (multi-disc, grouped headers).
  • Position items with transforms; container gets overflow-anchor: none.
  • Scroll-jump on infinite scroll (prepend) is the classic bug — virtua and TanStack both handle scroll position adjustment; hand-rolled needs ResizeObserver + manual scrollTop compensation.
  • Keyboard nav is ours to build anyway (that's the product): virtualizers only need scrollToIndex({ align }) + keeping focus within the rendered window (focus a sentinel, use tabindex="-1" + focus() on the current row after render — rAF it).
  • overscan (render a few off-screen rows) ≈ 5 is the sweet spot; more hurts, fewer risks white flashes on fast flicks.

3. Solid-specific leverage (we're already ahead) #

Solid's fine-grained reactivity removes most of the reasons these tricks exist in React/Vue apps — no VDOM diffing, updates touch exact text nodes:

  • Solid 2.0 unified <For> (keyed={true} = old For, keyed={false} = old Index). For the queue (reorderable: drag, move, shuffle) use keyed For so DOM nodes move instead of re-rendering. For positionally stable, value-swapping lists (paged search results re-filled in place), non-keyed avoids per-item state churn. See documentation/solid-2.0/03-control-flow.md in solidjs/solid@next.
  • No memo needed: a row component runs once; per-row signals update independently. The "now playing" highlight should be one shared signal (currentTrackId) that rows read — each row subscribes and only the two affected rows update their class. Never prop-drill an isActive boolean computed in the parent (that re-renders all rows).
  • batch() around multi-signal updates (e.g. swap tracks: update queue index + time + title atomically, one DOM flush).
  • untrack() inside scroll/worker-callback paths where reactivity is a leak, not a feature.
  • Component creation cost inside a virtualizer is the remaining hot spot (thousands of closures on filter): virtualizers window this for us; keep row components flat and hoist statics.
  • createMemo the filtered/sorted list — Solid's memos only recompute on true dependency change, so keystroke-filtering 10k items produces one array memo + the visible window's DOM ops, nothing else. Pair with chunking (§1) or a worker-side index (e.g. minisearch/fuse in a worker) for instant-feeling search.

4. Measurement plan (so the "highly optimized" claim is real) #

  • Chrome DevTools Performance traces with 10k synthetic rows: scroll at 60fps, zero long tasks (>50ms) during scroll; INP < 100ms on keypress while a list scrolls.
  • PerformanceObserver for longtask and event latency in dev builds; fail CI perf-test on regressions.
  • Test the worst case on a throttled CPU (6x) and a Navidrome on a Raspberry Pi — the API is often the slow part, not rendering; caching (§1) is what makes it feel instant.
  • Memory check: heap stays flat while scrolling 10k virtualized rows (detach rows properly; watch ResizeObserver leaks).

Quick reference — the actual CSS/JS starter kit #

.pane {
  overflow-y: auto;
  overscroll-behavior: contain;
  contain: strict; /* fixed-size panes we control */
}
.track-row {
  contain: layout style paint;
}
.section:not(.track-list) {
  content-visibility: auto;
  contain-intrinsic-size: auto 300px;
}
.cover {
  aspect-ratio: 1;
  content-visibility: auto;
  contain-intrinsic-size: auto 160px;
}
.cover img {
  width: 100%;
  height: auto;
}
img[aria-hidden="true"] {
  pointer-events: none;
}
.now-playing {
  transition: none;
} /* never animate the row chrome */

Key sources #