fix(v2): cancel gallery windows that scroll out of view

Switching from per-card to per-window fetching dropped the departure
cancellation the per-card path had: scrolling through a large library
started a request per 72-item window encountered and left every departed
window downloading and applying in the background, the wasted network /
backend / render work this change set out to avoid on low-power devices.

Add store.syncVisibleWindows(positions): it starts the windows covering
the visible positions (deduped in fetchWindowAt) and aborts any in-flight
or retry-pending window that no longer covers one. The shell's debounced
viewport sync now delegates to it. Also abort in-flight windows when the
gallery unmounts (onBeforeRouteLeave doesn't reset the store), keeping
the loaded cache so returning is still instant. Drops the shell's dead
visiblePositions bookkeeping.

Generated-By: PostHog Code
Task-Id: 6690877a-9c32-4c91-a78b-3d6fd3851fb7
This commit is contained in:
Georges-Antoine Assi
2026-07-16 09:05:25 -04:00
parent f6f3519c92
commit 79f350ab3e
2 changed files with 69 additions and 32 deletions

View File

@@ -551,22 +551,26 @@ const currentLetter = computed<string>(() => {
return "";
});
// Viewport-driven fetch. The shell tracks which positions are
// currently visible (from the rows in `viewportRange`) and keeps
// Viewport-driven fetch. The shell collects the positions currently in
// view (rows in `viewportRange`) and hands them to the store, which keeps
// `byPosition` in sync by fetching the 72-item windows those positions
// fall into via `fetchWindowAt`. Windows are shared across cards and
// cached in the store, so a full viewport resolves in a handful of
// paginated requests rather than one per card.
// fall into. Windows are shared across cards and cached, so a full
// viewport resolves in a handful of paginated requests rather than one
// per card. (Fetching per-card instead issued one request plus one DB
// lookup per visible card, so ~100 simultaneous round-trips on a full
// grid, which the browser's per-host connection cap then serialized into
// slow waves on low-power devices.)
//
// No idle-time prefetch: when the user stops scrolling, no new
// requests are fired. Windows already covering the viewport keep
// loading; everything off-screen waits until the user scrolls there.
// The store also aborts windows that scrolled out of view, so paging
// through a large library doesn't leave departed windows downloading.
//
// No idle-time prefetch: when the user stops scrolling, no new requests
// are fired for off-screen positions.
//
// A small debounce on viewport changes prevents request storms during
// smooth scrolling: only when the viewport settles for
// `FETCH_DEBOUNCE_MS` do we sync.
const FETCH_DEBOUNCE_MS = 80;
const visiblePositions = new Set<number>();
let fetchDebounceTimer: ReturnType<typeof setTimeout> | null = null;
let pendingRange: { first: number; last: number } | null = null;
@@ -586,24 +590,7 @@ function collectVisiblePositions(range: {
}
function syncFetches(range: { first: number; last: number }) {
const next = collectVisiblePositions(range);
// Fetch the windows covering the positions that just entered. The
// store aligns each position to its 72-item window and dedupes
// against pending + loaded windows, so this collapses to one
// paginated request per window regardless of how many cards are on
// screen. (Fetching per-card instead issued one request plus one DB
// lookup per visible card, so ~100 simultaneous round-trips on a full
// grid, which the browser's per-host connection cap then serialized
// into slow waves on low-power devices.)
for (const p of next) {
if (!galleryRoms.byPosition.has(p)) {
void galleryRoms.fetchWindowAt(p);
}
}
visiblePositions.clear();
for (const p of next) visiblePositions.add(p);
galleryRoms.syncVisibleWindows(collectVisiblePositions(range));
}
function scheduleFetchSync(range: { first: number; last: number }) {
@@ -619,11 +606,10 @@ function scheduleFetchSync(range: { first: number; last: number }) {
}
// When the virtualItems list itself changes (gallery context switch,
// search invalidate), drop the visible-position bookkeeping. The
// store's `invalidateWindows` / `resetGallery` already aborts every
// in-flight request, so we just clear local state.
// search invalidate), drop the pending debounced sync. The store's
// `invalidateWindows` / `resetGallery` already aborts every in-flight
// request, so we just clear local state.
watch(virtualItems, () => {
visiblePositions.clear();
if (fetchDebounceTimer) {
clearTimeout(fetchDebounceTimer);
fetchDebounceTimer = null;
@@ -786,7 +772,11 @@ onBeforeUnmount(() => {
gallerySelection.clear();
if (searchDebounce) clearTimeout(searchDebounce);
if (fetchDebounceTimer) clearTimeout(fetchDebounceTimer);
visiblePositions.clear();
// Leaving the gallery entirely (onBeforeRouteLeave doesn't reset the
// store): stop any window fetches still downloading so navigating away
// mid-scroll doesn't keep the network / backend busy. Keeps the loaded
// cache so returning to the same gallery is instant.
galleryRoms.abortInFlight();
inflowResizeObserver?.disconnect();
inflowResizeObserver = null;
// Drop the debug stats so the overlay doesn't show stale gallery numbers

View File

@@ -97,6 +97,14 @@ function abortAllInFlight() {
retryCounts.clear();
}
// Abort a single in-flight window fetch. The rejected request is caught
// as a cancel in `fetchWindowAt` (no `failedWindows` entry, no retry) and
// its `finally` clears the pending/controller bookkeeping.
function cancelWindow(offset: number) {
const ctrl = inFlightControllers.get(`window:${offset}`);
if (ctrl) ctrl.abort();
}
// Apply items to `byPosition` in row-sized batches with a rAF yield
// between batches. Each Map.set() invalidates Vue's per-key dep, and
// when many cards are in the viewport / overscan zone they all
@@ -521,6 +529,45 @@ export default defineStore("v2GalleryRoms", {
}
},
/** Reconcile in-flight window fetches with the currently visible
* positions. Starts any window covering a visible position (deduped
* inside `fetchWindowAt`) and aborts any in-flight or retry-pending
* window that no longer covers one. Without the abort, scrolling
* through a large library would leave every window it passed
* downloading and applying in the background — the exact wasted
* network / backend / render work this store exists to avoid on
* low-power devices. Driven by the shell's debounced viewport sync. */
syncVisibleWindows(positions: Iterable<number>) {
const wanted = new Set<number>();
for (const p of positions) {
if (p < 0) continue;
if (this.total > 0 && p >= this.total) continue;
wanted.add(alignToWindow(p));
}
// Cancel windows that drifted out of view. Snapshot first: aborting
// settles a fetch's `finally` (which mutates these sets) on a later
// microtask, but iterate a copy to stay safe regardless.
for (const offset of [...this.pendingWindows]) {
if (!wanted.has(offset)) cancelWindow(offset);
}
for (const offset of [...retryTimers.keys()]) {
if (!wanted.has(offset)) clearRetry(offset);
}
for (const offset of wanted) {
void this.fetchWindowAt(offset);
}
},
/** Abort every in-flight window fetch + pending retry without wiping
* the loaded cache. The shell calls this when the gallery unmounts so
* navigating away mid-scroll doesn't leave downloads running; a
* return to the same gallery still reuses `loadedWindows`. */
abortInFlight() {
abortAllInFlight();
this.pendingWindows = new Set();
this.initialFetching = false;
},
/** Apply (in place) an updated ROM to whatever position currently
* holds it — used by edit / favourite / status flows. Mutating
* via `set(pos, rom)` on the reactive Map triggers only the