perf(frontend): virtualize the photos timeline (square + justified)

The Photos "moments" grid rendered every tile into the DOM, so a 20k-photo
library mounted ~140k nodes / 20k <img> elements, held ~196MB JS heap, took
~3.5s to first paint and scrolled at ~6fps. It also ran the justified-layout
maths inside the template (recomputed on every reactive change) and generated
client-side video thumbnails for every off-screen video, not just visible ones.

Introduce `VirtualRows` — a variable-height, section-aware sibling of
`VirtualList` — and flatten the grouped timeline into one list of fixed-height
rows (a date header or a strip of explicitly-sized tiles) shared by both the
square and justified layouts. Only the rows near the viewport are mounted; a
prefix-sum offset table + binary search find the visible band, and a spacer
reserves the full height so the sticky header and load-more sentinel are
unchanged. The justified packing now runs once per groups/width/layout change
in a $derived, not per render.

To avoid duplicating the scroll-tracking logic across the two windowing
components, extract it into a `useVirtualWindow` composable (scroll-ancestor
detection + rAF-throttled aboveBy/viewportH signals); `VirtualList` is
refactored onto it with identical measured numbers.

Measured in headless Chromium (1280x900), synthetic photos, before/after:

  SQUARE      | mount→tiles | DOM nodes | <img> | JS heap | scroll frame
  ------------+-------------+-----------+-------+---------+-------------
   2000       | 416→94 ms   | 14k→629   |2000→96| 21→5 MB | 29→29 ms
   5000       | 916→114 ms  | 35k→629   |5000→96| 50→9 MB | 62→26 ms
  20000       | 3455→220 ms | 140k→629  |20k→96 |196→29 MB|152→33 ms

  JUSTIFIED 20000: mount 245 ms · DOM 315 · <img> 44 · heap 33 MB · ~60fps

Rendered DOM, mounted <img> count and heap are now flat (O(visible)) regardless
of library size; mount is ~16x faster and scroll jank drops from 413 to ≤24
frames. Off-screen video-thumbnail generation no longer fires for non-visible
tiles. Correctness verified by probing a deep scroll in both layouts (tiles
land within the viewport band; square cells equal-width, justified rows
aspect-preserving).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M8Vb9QHmLZnEMzHz7MrFy6
This commit is contained in:
Claude
2026-06-19 14:25:12 +00:00
parent 5fdcf8cb56
commit ccb85f53c0
4 changed files with 294 additions and 115 deletions
+12 -66
View File
@@ -30,6 +30,7 @@
<script lang="ts" generics="T">
import { onMount } from 'svelte';
import { useVirtualWindow } from '$lib/composables/useVirtualWindow.svelte';
let {
items,
@@ -45,59 +46,24 @@
let rootEl: HTMLDivElement;
/** Measured row pitch in px; 0 until known, then refined from a real row. */
let measuredRow = $state(0);
let firstRow = $state(0);
let lastRow = $state(0);
const vw = useVirtualWindow();
const cols = $derived(Math.max(1, columns));
const effRowH = $derived(measuredRow > 0 ? measuredRow : rowHeight);
const rowCount = $derived(Math.ceil(items.length / cols));
const totalHeight = $derived(rowCount * effRowH);
// Visible row band, derived from the shared scroll signals + the row pitch.
const rh = $derived(effRowH || rowHeight);
const firstRow = $derived(Math.max(0, Math.floor(vw.aboveBy / rh) - overscan));
const lastRow = $derived(
Math.min(rowCount, Math.ceil((vw.aboveBy + vw.viewportH) / rh) + overscan)
);
const startIndex = $derived(firstRow * cols);
const endIndex = $derived(Math.min(items.length, lastRow * cols));
const offsetY = $derived(firstRow * effRowH);
const visible = $derived(items.slice(startIndex, endIndex));
let scroller: HTMLElement | null = null;
/** Nearest scrollable ancestor, or null to mean the window/document. */
function findScroller(el: HTMLElement): HTMLElement | null {
let node = el.parentElement;
while (node) {
const oy = getComputedStyle(node).overflowY;
if (oy === 'auto' || oy === 'scroll' || oy === 'overlay') return node;
node = node.parentElement;
}
return null;
}
function viewportRect(): { top: number; height: number } {
if (scroller) {
const r = scroller.getBoundingClientRect();
return { top: r.top, height: scroller.clientHeight };
}
return { top: 0, height: window.innerHeight };
}
function measure(): void {
if (!rootEl) return;
const { top: vTop, height: vH } = viewportRect();
// How far the list's top has scrolled above the viewport top (px).
const aboveBy = vTop - rootEl.getBoundingClientRect().top;
const rh = effRowH || rowHeight;
firstRow = Math.max(0, Math.floor(aboveBy / rh) - overscan);
lastRow = Math.min(rowCount, Math.ceil((aboveBy + vH) / rh) + overscan);
}
let ticking = false;
function onScroll(): void {
if (ticking) return;
ticking = true;
requestAnimationFrame(() => {
ticking = false;
measure();
});
}
/** Single-column: adopt the real rendered row height once it's known. */
function refineRowHeight(): void {
if (cols !== 1 || !rootEl) return;
@@ -108,32 +74,12 @@
}
onMount(() => {
scroller = findScroller(rootEl);
const target: EventTarget = scroller ?? window;
target.addEventListener('scroll', onScroll, { passive: true });
window.addEventListener('resize', onScroll, { passive: true });
const ro = new ResizeObserver(() => onScroll());
if (scroller) ro.observe(scroller);
ro.observe(rootEl);
measure();
const stop = vw.observe(rootEl);
requestAnimationFrame(() => {
refineRowHeight();
measure();
vw.remeasure();
});
return () => {
target.removeEventListener('scroll', onScroll);
window.removeEventListener('resize', onScroll);
ro.disconnect();
};
});
// Re-window when the dataset size or column count changes (load-more, reload,
// viewport breakpoint). `effRowH` is read so a refined height re-runs it too.
$effect(() => {
void items.length;
void cols;
void effRowH;
measure();
return stop;
});
// Refine the measured row height once rows are actually in the DOM.