@knitui/components 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,16 +7,29 @@ import { Box, type BoxProps } from "../Box";
7
7
  import { slotStyles } from "../internal/styles";
8
8
  import { ScrollArea, type ScrollAreaHandle } from "../ScrollArea";
9
9
  import {
10
+ areRowsMeasured,
10
11
  createLayoutState,
12
+ createRetainState,
11
13
  DEFAULT_DRAW_DISTANCE,
12
14
  DEFAULT_END_REACHED_THRESHOLD,
13
15
  DEFAULT_ESTIMATED_ITEM_SIZE,
16
+ DEFAULT_START_REACHED_THRESHOLD,
14
17
  findVisibleRange,
15
18
  getContentSize,
16
19
  getItemOffset,
20
+ isMountAll,
17
21
  type LayoutState,
22
+ MEASURE_EPSILON,
23
+ NO_RETAINED,
24
+ remapRetainState,
18
25
  resizeLayoutState,
26
+ resolveRetainLimit,
27
+ retainedOutside,
28
+ retainRange,
29
+ type RetainState,
19
30
  setMeasured,
31
+ shallowEqualProps,
32
+ syncLayoutKeys,
20
33
  VIRTUAL_LIST_SLOTS,
21
34
  type VirtualListHandle,
22
35
  type VirtualListOwnProps,
@@ -46,22 +59,62 @@ export type {
46
59
  * less first-scroll correction). Mirrors the familiar `FlatList` / `FlashList`
47
60
  * surface for the v1 subset: vertical, single-column lists.
48
61
  *
62
+ * ## What a scroll costs
63
+ *
64
+ * Scrolling itself never renders. The live offset, viewport height, window and
65
+ * `onEndReached` latch all live in refs, and the only `setState` on the scroll path
66
+ * fires when the window actually crosses a row boundary — one render per crossing,
67
+ * not per frame. That render re-creates row elements, but two memo boundaries keep
68
+ * the work off the user's code: the outer {@link Row} skips rows that merely stayed
69
+ * mounted, and the inner {@link RowContent} means even a row the wrapper *did*
70
+ * re-render (a shifted `top`, a new separator element, a fresh `styles.item`
71
+ * literal) does not re-run `renderItem`.
72
+ *
49
73
  * ## Keep the row props stable
50
74
  *
51
- * Each mounted row is a memoized cell, so scrolling only re-renders the rows that
52
- * actually enter or leave the window — but ONLY if the props handed to those rows
53
- * keep their identity. For the memo to pay off, `renderItem` (and, when supplied,
54
- * `getItemType`, `ItemSeparatorComponent` and `styles.item`) must be referentially
55
- * stable: hoist them, or wrap them in `useCallback` / `useMemo`. An inline
56
- * `renderItem={({ item }) => …}` is a new function on every parent render and
57
- * therefore re-runs for every mounted row — cheap for a handful of rows, the
58
- * dominant scroll cost for a large window.
75
+ * The memos only pay off if the props handed to rows keep their identity. Hoist
76
+ * `renderItem` and `getItemType`, or wrap them in `useCallback` — an inline
77
+ * `renderItem={({ item }) => …}` is a new function on every parent render and so
78
+ * re-runs for every mounted row. (`ItemSeparatorComponent` and `styles.item` are
79
+ * stabilised internally, so inline literals there are free.)
80
+ *
81
+ * `renderItem` is deliberately NOT stabilised internally (e.g. via
82
+ * `useCallbackRef`), because one closing over component state must be able to
83
+ * produce new output when that state changes. Pass `extraData` when your rows
84
+ * depend on state a stable `renderItem` cannot see: it is compared by the row memo
85
+ * and re-renders every mounted row.
86
+ *
87
+ * ## Identity, not slots
88
+ *
89
+ * Supply a `keyExtractor` and every cache — measured heights, the per-type size
90
+ * averages, the `keepMounted` pool, React's own reconciliation — is keyed by item,
91
+ * so inserts, removals, sorts and filters move each row's height and state with it.
92
+ * Without one, the index is the identity and only append/pop is correct.
59
93
  *
60
- * They are deliberately NOT stabilised internally (e.g. via `useCallbackRef`),
61
- * because a `renderItem` closing over component state must be able to produce new
62
- * output when that state changes. Pass `extraData` when your rows depend on state
63
- * a stable `renderItem` cannot see: it is compared by the row memo and re-renders
64
- * every mounted row.
94
+ * ## Lazy loading, in both directions
95
+ *
96
+ * `onEndReached` pages forward, the ordinary infinite feed. `onStartReached` pages
97
+ * BACKWARDS, for a list whose history grows at the head — a chat thread loading
98
+ * older messages is the case it exists for.
99
+ *
100
+ * Backwards pagination needs one thing forward pagination does not: an insert at
101
+ * the head moves every row already on screen. Pass `maintainVisibleContentPosition`
102
+ * and the list absorbs the inserted height into its own scroll offset, so the
103
+ * message the user was reading does not slide out from under them. Both need
104
+ * `keyExtractor` to be set — a prepend is recognised by finding the old head row at
105
+ * its new index, and the keyed size model is what carries each row's measurement to
106
+ * its new position instead of leaving it on a stranger.
107
+ *
108
+ * ## Keeping rows mounted
109
+ *
110
+ * Unmounting is what makes windowing cheap, but it also throws away whatever the
111
+ * row held — local state, focus, a playing video, a half-typed input. `keepMounted`
112
+ * is the escalating ladder out of that: a number bounds an LRU warm pool of
113
+ * already-seen rows, `true` keeps every row that has ever mounted, and `"all"` drops
114
+ * windowing altogether and mounts the entire `data` up front (rows that have never
115
+ * been seen included — the only rung that costs O(data) on mount). Kept rows sit at
116
+ * their real offsets and are simply clipped by the scroller, so scrolling back to
117
+ * one shows real content immediately instead of a blank frame.
65
118
  */
66
119
  const VirtualListFrame = styled(Box, {
67
120
  name: "VirtualList",
@@ -93,36 +146,75 @@ const VirtualListItem = styled(Box, {
93
146
  *
94
147
  * `slots.get("item") ?? {}` allocated a FRESH object on every render, and that
95
148
  * object is handed to the memoized {@link Row} as `itemProps` — so the common
96
- * case (no `styles.item`) silently defeated the row memo and re-ran `renderItem`
97
- * for every mounted row on every windowing render and every measurement-driven
149
+ * case (no `styles.item`) silently defeated the row memo, re-rendering every
150
+ * mounted row on every windowing render and every measurement-driven
98
151
  * `bumpLayout`. One module-level constant keeps the reference identical forever.
99
152
  */
100
153
  const EMPTY_ITEM_PROPS: Partial<BoxProps> = {};
101
154
 
102
- interface RowProps<T> {
155
+ /**
156
+ * Give a prop bag a stable identity for as long as its contents are unchanged,
157
+ * so the idiomatic inline `styles={{ item: { … } }}` literal — a fresh object on
158
+ * every parent render — still lets {@link Row}'s memo hold. A render-time ref
159
+ * cache is safe here: it is a pure value-keyed cache, idempotent under the
160
+ * double-invocation of StrictMode and under a render React later throws away.
161
+ */
162
+ const useStableProps = (next: Partial<BoxProps>): Partial<BoxProps> => {
163
+ const ref = React.useRef(next);
164
+ if (
165
+ ref.current !== next &&
166
+ !shallowEqualProps(ref.current as Record<string, unknown>, next as Record<string, unknown>)
167
+ ) {
168
+ ref.current = next;
169
+ }
170
+ return ref.current;
171
+ };
172
+
173
+ interface RowContentProps<T> {
103
174
  item: T;
104
175
  index: number;
176
+ renderItem: VirtualListOwnProps<T>["renderItem"];
177
+ /**
178
+ * Not read — carried purely so `React.memo` compares it. This is what makes the
179
+ * documented `extraData` escape hatch work now that a row's other props can all
180
+ * be referentially stable: change `extraData` and every mounted row re-runs
181
+ * `renderItem`, even though its `item` did not change.
182
+ */
183
+ extraData?: unknown;
184
+ }
185
+
186
+ /**
187
+ * The inner memo boundary: the ONLY thing that re-runs `renderItem`.
188
+ *
189
+ * Deliberately kept to the minimum prop set that can change what a row's content
190
+ * should be — `item`, `index`, `renderItem`, `extraData` — so everything that is
191
+ * merely about *where* or *how* the row sits (its `top`, the separator element,
192
+ * the `styles.item` passthrough) cannot reach it. That split matters because in a
193
+ * variable-height list those positional props change constantly: every measurement
194
+ * anywhere above a row shifts its `top`, and a caller's inline
195
+ * `ItemSeparatorComponent={<Box … />}` or `styles={{ item: … }}` is a fresh
196
+ * identity on every parent render. Before the split, each of those re-ran user
197
+ * `renderItem` for every mounted row; now they re-render only the cheap wrapper.
198
+ */
199
+ const RowContentInner = <T,>({ item, index, renderItem }: RowContentProps<T>) => (
200
+ <>{renderItem({ item, index })}</>
201
+ );
202
+ const RowContent = React.memo(RowContentInner) as typeof RowContentInner;
203
+
204
+ interface RowProps<T> extends RowContentProps<T> {
105
205
  top: number;
106
206
  isLast: boolean;
107
- renderItem: VirtualListOwnProps<T>["renderItem"];
108
207
  getItemType?: VirtualListOwnProps<T>["getItemType"];
109
208
  separator: React.ReactNode;
110
209
  onMeasure: (index: number, height: number, type: string | number) => void;
111
210
  itemProps: Partial<BoxProps>;
112
- /**
113
- * Not read by the row — carried purely so `React.memo` compares it. This is
114
- * what makes the documented `extraData` escape hatch work now that the row's
115
- * other props can all be referentially stable: change `extraData` and every
116
- * mounted row re-runs `renderItem`, even though its `item` did not change.
117
- */
118
- extraData?: unknown;
119
211
  }
120
212
 
121
213
  /**
122
- * A single mounted row. Memoized so that pure scrolling — which only changes the
123
- * *set* of mounted indices, not the props of rows that stay mounted — never
124
- * re-runs `renderItem` for a surviving row. `top` only changes on relayout, so
125
- * scroll alone is free.
214
+ * One mounted row: the absolutely-positioned, measured wrapper around
215
+ * {@link RowContent}. Memoized as the outer boundary so that pure scrolling —
216
+ * which changes only the *set* of mounted indices, not the props of rows that stay
217
+ * mounted — re-renders nothing at all for a surviving row.
126
218
  */
127
219
  const RowInner = <T,>({
128
220
  item,
@@ -134,6 +226,7 @@ const RowInner = <T,>({
134
226
  separator,
135
227
  onMeasure,
136
228
  itemProps,
229
+ extraData,
137
230
  }: RowProps<T>) => {
138
231
  const handleLayout = React.useCallback(
139
232
  (e: LayoutChangeEvent) => {
@@ -144,7 +237,7 @@ const RowInner = <T,>({
144
237
  );
145
238
  return (
146
239
  <VirtualListItem top={top} onLayout={handleLayout} {...itemProps}>
147
- {renderItem({ item, index })}
240
+ <RowContent<T> item={item} index={index} renderItem={renderItem} extraData={extraData} />
148
241
  {isLast ? null : separator}
149
242
  </VirtualListItem>
150
243
  );
@@ -174,9 +267,13 @@ function VirtualListInner<T>(
174
267
  getItemType,
175
268
  estimatedItemSize = DEFAULT_ESTIMATED_ITEM_SIZE,
176
269
  drawDistance = DEFAULT_DRAW_DISTANCE,
270
+ keepMounted = false,
177
271
  extraData,
178
272
  onEndReached,
179
273
  onEndReachedThreshold = DEFAULT_END_REACHED_THRESHOLD,
274
+ onStartReached,
275
+ onStartReachedThreshold = DEFAULT_START_REACHED_THRESHOLD,
276
+ maintainVisibleContentPosition = false,
180
277
  onRenderedRangeChange,
181
278
  ListHeaderComponent,
182
279
  ListFooterComponent,
@@ -190,27 +287,75 @@ function VirtualListInner<T>(
190
287
  const slots = slotStyles<VirtualListStyles>(styles, VIRTUAL_LIST_SLOTS, "VirtualList");
191
288
  const scrollAreaSlot = slots.get("scrollArea");
192
289
  const contentSlot = slots.get("content");
193
- // Referentially stable when the caller passes no `styles.item` — see
194
- // {@link EMPTY_ITEM_PROPS}; a fresh `{}` here would break every row's memo.
195
- const itemSlot = slots.get("item") ?? EMPTY_ITEM_PROPS;
290
+ // Referentially stable both when the caller passes no `styles.item` (see
291
+ // {@link EMPTY_ITEM_PROPS}) and when they pass an inline literal (see
292
+ // {@link useStableProps}) — a fresh object here breaks every row's memo.
293
+ const itemSlot = useStableProps(slots.get("item") ?? EMPTY_ITEM_PROPS);
196
294
 
197
295
  const count = data.length;
198
296
 
297
+ // Row identities, computed once per `data` change (never per render — this walks
298
+ // the WHOLE list, not just the window). With them, measurements and the
299
+ // `keepMounted` pool follow items through prepends, inserts, removals and sorts;
300
+ // without a `keyExtractor` there is no identity to follow and both fall back to
301
+ // index semantics, which is only correct for append/pop.
302
+ const keys = React.useMemo(
303
+ () => (keyExtractor ? data.map((item, i) => keyExtractor(item, i)) : null),
304
+ [data, keyExtractor],
305
+ );
306
+
199
307
  // ── layout model (mutable, in a ref — never triggers a render by itself) ──
200
308
  const layoutRef = React.useRef<LayoutState>(createLayoutState(count, estimatedItemSize));
201
- // Keep the store sized to the data. Reset entirely if the seed changed.
202
- if (layoutRef.current.estimate !== estimatedItemSize) {
203
- layoutRef.current = createLayoutState(count, estimatedItemSize);
204
- } else if (layoutRef.current.count !== count) {
205
- resizeLayoutState(layoutRef.current, count);
206
- }
309
+
310
+ // The head row's key as of the last reconcile, and the prepend not yet
311
+ // compensated for. Both are written in the body, alongside the store mutation
312
+ // they describe — the reconcile is already a render-phase side effect, and
313
+ // keeping them in step with it is what makes a double render idempotent (the
314
+ // second pass sees `added === 0` and does nothing).
315
+ const firstKeyRef = React.useRef<string | null>(null);
316
+ const pendingPrependRef = React.useRef(0);
317
+ // What the list is holding on to across a layout change, live only until the
318
+ // rows involved have settled (or the user scrolls). Either a specific ROW and
319
+ // where it sat relative to the viewport top — how a prepend is absorbed — or the
320
+ // END, which is a destination rather than a row and has to be recomputed as the
321
+ // total height changes underneath it.
322
+ const anchorRef = React.useRef<
323
+ { kind: "row"; index: number; gap: number } | { kind: "end" } | null
324
+ >(null);
325
+
326
+ // A "load older" page grows the data at the HEAD, and the viewport would jump by
327
+ // the inserted height unless the scroll offset absorbs it. Detected in O(1) rather
328
+ // than by diffing — a pure prepend puts the old head row at exactly `added`, so one
329
+ // key comparison confirms it. Needs `keyExtractor`; index keys carry no identity to
330
+ // recognise the row by.
331
+ //
332
+ // Read here, BEFORE the store is re-keyed below, because `added` is the difference
333
+ // between the data and the store as it still stands. Carrying each measurement to
334
+ // its row's new index is not this detection's job: that falls out of the keyed size
335
+ // model (`syncLayoutKeys`), which handles a prepend as one case of any data change.
336
+ // What the detection is still needed for is the scroll anchor — how much height
337
+ // went in at the head.
338
+ const added = count - layoutRef.current.count;
339
+ const firstKey = keys && count > 0 ? keys[0] : null;
340
+ const prepended =
341
+ keys &&
342
+ added > 0 &&
343
+ added < count &&
344
+ firstKeyRef.current != null &&
345
+ keys[added] === firstKeyRef.current
346
+ ? added
347
+ : 0;
207
348
 
208
349
  // Live scroll offset lives in a ref so scrolling never re-renders on its own.
209
350
  const scrollTopRef = React.useRef(0);
210
351
  const viewportHRef = React.useRef(0);
211
352
  const rangeRef = React.useRef<{ start: number; end: number }>({ start: 0, end: -1 });
212
353
  const endReachedFiredRef = React.useRef(false);
354
+ const startReachedFiredRef = React.useRef(false);
213
355
  const scrollAreaRef = React.useRef<ScrollAreaHandle | null>(null);
356
+ // The offset the anchor correction last asked for, so the scroll event it
357
+ // causes can be told apart from the user moving the list.
358
+ const compensatedTopRef = React.useRef<number | null>(null);
214
359
 
215
360
  // The three pieces of state that DO drive re-renders: the mounted index range,
216
361
  // the viewport height (needed for the first window), and a layout version bumped
@@ -221,6 +366,61 @@ function VirtualListInner<T>(
221
366
  });
222
367
  const [viewportH, setViewportH] = React.useState(0);
223
368
  const [layoutVersion, bumpLayout] = React.useReducer((v: number) => v + 1, 0);
369
+ // ── `keepMounted` pool: already-seen rows mounted outside the live window ──
370
+ // The pool is a ref — LRU bookkeeping must not render — and the list of rows to
371
+ // mount on top of the window is DERIVED from it during render, not mirrored into
372
+ // state. Mirroring would go stale in exactly the case that matters: a data change
373
+ // remaps the pool while rendering, and a stale copy would mount the wrong rows for
374
+ // a frame, unmounting (and so resetting) the very rows `keepMounted` promised to
375
+ // keep. Every pool mutation already coincides with a render — a window crossing
376
+ // (`setRange`), a data/prop change, or the re-window effect — so no extra trigger
377
+ // is needed; `pool.version` just lets the derivation be cached in between.
378
+ const retainRef = React.useRef<RetainState>(createRetainState());
379
+ const extrasRef = React.useRef<{ sig: string; list: readonly number[] }>({
380
+ sig: "",
381
+ list: NO_RETAINED,
382
+ });
383
+ // What the pool was last folded against, so a scroll frame that does not cross a
384
+ // row boundary skips the (O(pool)) retention pass entirely.
385
+ const retainSigRef = React.useRef<{
386
+ count: number;
387
+ limit: number;
388
+ keys: readonly string[] | null;
389
+ }>({ count: -1, limit: -1, keys: null });
390
+
391
+ // ── keep the mutable models in step with the data (render-time, idempotent) ──
392
+ // These are value-keyed caches rather than derived state: re-running this block on
393
+ // a render React later throws away, or twice under StrictMode, produces exactly
394
+ // the same models, and nothing here can schedule a render.
395
+ const syncedKeysRef = React.useRef<readonly string[] | null>(null);
396
+ // A new seed invalidates every estimate, so start the model over — and with it
397
+ // anything the list was holding on to about where the old rows sat.
398
+ if (layoutRef.current.estimate !== estimatedItemSize) {
399
+ layoutRef.current = createLayoutState(count, estimatedItemSize);
400
+ syncedKeysRef.current = null;
401
+ anchorRef.current = null;
402
+ pendingPrependRef.current = 0;
403
+ }
404
+ if (keys) {
405
+ if (syncedKeysRef.current !== keys) {
406
+ const prevKeys = syncedKeysRef.current;
407
+ // One keyed re-sync covers every shape of data change, a prepend included: each
408
+ // row's measurement is restored at the row's NEW index straight from the per-key
409
+ // cache, so nothing has to be shifted by hand.
410
+ syncLayoutKeys(layoutRef.current, keys);
411
+ // Carry the `keepMounted` pool across the data change by identity, so a row
412
+ // the user already opened stays mounted even if it moved.
413
+ if (prevKeys) remapRetainState(retainRef.current, prevKeys, keys);
414
+ syncedKeysRef.current = keys;
415
+ }
416
+ } else if (layoutRef.current.count !== count) {
417
+ resizeLayoutState(layoutRef.current, count);
418
+ }
419
+ // Accumulated, not overwritten: two pages can land before the compensating effect
420
+ // runs, and both inserted at the head.
421
+ if (prepended > 0) pendingPrependRef.current += prepended;
422
+ firstKeyRef.current = firstKey;
423
+
224
424
  const [headerH, setHeaderH] = React.useState(0);
225
425
  const [footerH, setFooterH] = React.useState(0);
226
426
  // The chrome heights are ALSO mirrored into refs, written by the same layout
@@ -258,38 +458,106 @@ function VirtualListInner<T>(
258
458
  }
259
459
  });
260
460
 
461
+ // The mirror of `maybeEndReached`, measured from offset 0. Same one-shot latch:
462
+ // it re-arms only once the list has scrolled back out of the threshold band, so
463
+ // a caller whose page lands while still near the top is asked once, not per frame.
464
+ const maybeStartReached = useCallbackRef(() => {
465
+ if (!onStartReached) return;
466
+ const vh = viewportHRef.current;
467
+ if (vh <= 0) return;
468
+ if (scrollTopRef.current <= onStartReachedThreshold * vh) {
469
+ if (!startReachedFiredRef.current) {
470
+ startReachedFiredRef.current = true;
471
+ onStartReached();
472
+ }
473
+ } else {
474
+ startReachedFiredRef.current = false;
475
+ }
476
+ });
477
+
261
478
  // Recompute the mounted range from the live scroll + viewport, and only commit
262
479
  // to React state when the range actually changes (one render per row-crossing,
263
480
  // not per scroll frame).
264
481
  const recomputeRange = useCallbackRef(() => {
265
482
  const vh = viewportHRef.current;
266
- const next = findVisibleRange(
267
- layoutRef.current,
268
- scrollTopRef.current - headerHRef.current,
269
- vh,
270
- drawDistance,
271
- );
483
+ // `keepMounted="all"` opts out of windowing: the window IS the list, so scroll
484
+ // position stops mattering and every row is mounted from the first commit.
485
+ const next = isMountAll(keepMounted)
486
+ ? { start: 0, end: count - 1 }
487
+ : findVisibleRange(
488
+ layoutRef.current,
489
+ scrollTopRef.current - headerHRef.current,
490
+ vh,
491
+ drawDistance,
492
+ );
272
493
  const prev = rangeRef.current;
273
- if (next.start !== prev.start || next.end !== prev.end) {
494
+ const rangeChanged = next.start !== prev.start || next.end !== prev.end;
495
+ if (rangeChanged) {
274
496
  rangeRef.current = next;
275
497
  setRange(next);
276
498
  onRenderedRangeChange?.(next);
277
499
  }
500
+
501
+ // Fold the new window into the `keepMounted` pool. Only worth doing when the
502
+ // window moved, the data changed, or the capacity changed — the pool's contents
503
+ // are a pure function of those, so a plain scroll frame is a no-op. A reorder
504
+ // counts as a change even at the same length: the window now holds different
505
+ // items, and those are the ones that must be marked most-recently-visible.
506
+ const limit = resolveRetainLimit(keepMounted);
507
+ const sig = retainSigRef.current;
508
+ if (rangeChanged || sig.count !== count || sig.limit !== limit || sig.keys !== keys) {
509
+ retainSigRef.current = { count, limit, keys };
510
+ retainRange(retainRef.current, next, count, limit);
511
+ }
278
512
  });
279
513
 
280
514
  const handleScroll = useCallbackRef((pos: { x: number; y: number }) => {
515
+ // Our own compensation scroll landing, or the user taking over? Anything that
516
+ // is not the offset we last asked for means the gesture is theirs, and
517
+ // correcting a live gesture would fight it — so the anchor is dropped.
518
+ //
519
+ // The target is NOT consumed on a match: one programmatic scroll can report
520
+ // its position more than once (the set itself, then again after the layout
521
+ // change it causes), and treating the second report as the user is what made
522
+ // the anchor die on the frame it was created — a list opening at the end came
523
+ // to rest on its pre-measurement estimate, half a screen short of the bottom.
524
+ // The target instead stays as "where we last put it" until superseded.
525
+ const target = compensatedTopRef.current;
526
+ if (anchorRef.current && (target == null || Math.abs(pos.y - target) > 1)) {
527
+ anchorRef.current = null;
528
+ compensatedTopRef.current = null;
529
+ }
281
530
  scrollTopRef.current = pos.y;
282
531
  recomputeRange();
532
+ maybeStartReached();
283
533
  maybeEndReached();
284
534
  });
285
535
 
286
536
  const handleFrameLayout = React.useCallback((e: LayoutChangeEvent) => {
287
537
  const h = e.nativeEvent.layout.height;
288
- if (h === viewportHRef.current) return;
538
+ // Sub-pixel churn (a fractional flex height, a device pixel ratio round-trip)
539
+ // must not re-window the whole list, so tolerate it like the chrome heights do.
540
+ if (Math.abs(h - viewportHRef.current) <= MEASURE_EPSILON) return;
289
541
  viewportHRef.current = h;
290
542
  setViewportH(h);
291
543
  }, []);
292
544
 
545
+ // The chrome measurers, hoisted out of the JSX so they keep one identity for the
546
+ // life of the list instead of re-registering an observer on every render.
547
+ const handleHeaderLayout = React.useCallback((e: LayoutChangeEvent) => {
548
+ const h = e.nativeEvent.layout.height;
549
+ if (Math.abs(headerHRef.current - h) <= MEASURE_EPSILON) return;
550
+ headerHRef.current = h;
551
+ setHeaderH(h);
552
+ }, []);
553
+
554
+ const handleFooterLayout = React.useCallback((e: LayoutChangeEvent) => {
555
+ const h = e.nativeEvent.layout.height;
556
+ if (Math.abs(footerHRef.current - h) <= MEASURE_EPSILON) return;
557
+ footerHRef.current = h;
558
+ setFooterH(h);
559
+ }, []);
560
+
293
561
  const handleMeasure = React.useCallback(
294
562
  (index: number, height: number, type: string | number) => {
295
563
  if (setMeasured(layoutRef.current, index, type, height)) {
@@ -307,17 +575,24 @@ function VirtualListInner<T>(
307
575
  // to reach this list through those callbacks' identities.
308
576
  React.useEffect(() => {
309
577
  recomputeRange();
578
+ maybeStartReached();
310
579
  maybeEndReached();
311
580
  }, [
312
581
  layoutVersion,
313
582
  viewportH,
314
583
  count,
584
+ // A reorder/filter that keeps the same length still moves every offset, so the
585
+ // window has to be recomputed even though `count` did not change.
586
+ keys,
315
587
  headerH,
316
588
  footerH,
317
589
  extraData,
318
590
  drawDistance,
591
+ keepMounted,
319
592
  onEndReachedThreshold,
593
+ onStartReachedThreshold,
320
594
  recomputeRange,
595
+ maybeStartReached,
321
596
  maybeEndReached,
322
597
  ]);
323
598
 
@@ -327,23 +602,110 @@ function VirtualListInner<T>(
327
602
  scrollAreaRef.current?.scrollTo({ y: offset, animated });
328
603
  }, []);
329
604
 
605
+ /* ---------------- prepend compensation ---------------- */
606
+
607
+ // Hold the anchor row still across a prepend. Pre-paint (a passive effect would
608
+ // show one frame of the content having slid down by the inserted height), and
609
+ // re-run on every layout bump because the inserted rows start on the ESTIMATE:
610
+ // each real measurement above the anchor moves it again, and against a 25-row
611
+ // page a few px of per-row error is a visible drift.
612
+ //
613
+ // The anchor is released once nothing above it can still move — or by
614
+ // `handleScroll`, as soon as the user's own gesture arrives.
615
+ React.useLayoutEffect(() => {
616
+ if (!maintainVisibleContentPosition) {
617
+ pendingPrependRef.current = 0;
618
+ return;
619
+ }
620
+ const inserted = pendingPrependRef.current;
621
+ if (inserted > 0) {
622
+ pendingPrependRef.current = 0;
623
+ const prev = anchorRef.current;
624
+ anchorRef.current =
625
+ prev?.kind === "row"
626
+ ? // A second page landed before the first had settled: the same anchor row
627
+ // moved further down, but its resting place in the viewport is unchanged.
628
+ { kind: "row", index: prev.index + inserted, gap: prev.gap }
629
+ : {
630
+ kind: "row",
631
+ index: inserted,
632
+ gap: scrollTopRef.current - headerHRef.current,
633
+ };
634
+ }
635
+
636
+ const anchor = anchorRef.current;
637
+ if (!anchor) return;
638
+
639
+ const total = getContentSize(layoutRef.current) + headerHRef.current + footerHRef.current;
640
+ const desired =
641
+ anchor.kind === "end"
642
+ ? Math.max(0, total - viewportHRef.current)
643
+ : headerHRef.current + getItemOffset(layoutRef.current, anchor.index) + anchor.gap;
644
+
645
+ // Recorded even when no scroll is needed, so the scroll reports this position
646
+ // still generates are recognised as ours rather than read as the user moving.
647
+ compensatedTopRef.current = desired;
648
+ if (Math.abs(desired - scrollTopRef.current) > 0.5) {
649
+ // Written through so the very next windowing pass reads the corrected
650
+ // position instead of the pre-insert one it would otherwise window against.
651
+ scrollTopRef.current = desired;
652
+ scrollToOffset(desired, false);
653
+ }
654
+
655
+ // Release once nothing that can still move is left. For a row anchor that is
656
+ // the band above it; for the end it is everything currently mounted, since any
657
+ // of those measuring changes the total the destination is derived from.
658
+ const settled =
659
+ anchor.kind === "end"
660
+ ? areRowsMeasured(layoutRef.current, rangeRef.current.start, count)
661
+ : areRowsMeasured(layoutRef.current, 0, anchor.index);
662
+ if (settled) anchorRef.current = null;
663
+ }, [count, layoutVersion, headerH, footerH, maintainVisibleContentPosition, scrollToOffset]);
664
+
330
665
  const buildHandle = React.useCallback(
331
666
  (): VirtualListHandle => ({
332
667
  scrollToIndex: ({ index, animated, viewPosition = 0, viewOffset = 0 }) => {
668
+ // An explicit destination overrides whatever the list was holding on to.
669
+ anchorRef.current = null;
333
670
  const clamped = Math.max(0, Math.min(index, count - 1));
334
671
  const top = headerH + getItemOffset(layoutRef.current, clamped);
335
672
  const slack = viewPosition * viewportHRef.current;
336
673
  scrollToOffset(top - slack - viewOffset, animated);
337
674
  },
338
- scrollToOffset: ({ offset, animated }) => scrollToOffset(offset, animated),
339
- scrollToTop: (animated) => scrollToOffset(0, animated),
675
+ scrollToOffset: ({ offset, animated }) => {
676
+ anchorRef.current = null;
677
+ scrollToOffset(offset, animated);
678
+ },
679
+ scrollToTop: (animated) => {
680
+ anchorRef.current = null;
681
+ scrollToOffset(0, animated);
682
+ },
340
683
  scrollToEnd: (animated) => {
341
684
  const total = getContentSize(layoutRef.current) + headerH + footerH;
342
- scrollToOffset(Math.max(0, total - viewportHRef.current), animated);
685
+ const desired = Math.max(0, total - viewportHRef.current);
686
+ // The end is computed from the TOTAL height, and on a list opening deep
687
+ // into unmeasured content that total is mostly estimate — so landing there
688
+ // once leaves the last rows short of the bottom by the accumulated error
689
+ // (25 chat bubbles a dozen px under their estimate is a third of a screen).
690
+ // With `maintainVisibleContentPosition` the destination is held instead of
691
+ // hit once, and re-derived as the rows measure.
692
+ //
693
+ // Only for a NON-animated call. An animated scroll reports a stream of
694
+ // intermediate positions, and telling those apart from the user grabbing
695
+ // the list mid-flight is not something this can do — so an animated
696
+ // `scrollToEnd` stays a one-shot. That is the append case (a sent message,
697
+ // one row of error), where it does not matter.
698
+ if (maintainVisibleContentPosition && !animated) {
699
+ anchorRef.current = { kind: "end" };
700
+ compensatedTopRef.current = desired;
701
+ } else {
702
+ anchorRef.current = null;
703
+ }
704
+ scrollToOffset(desired, animated);
343
705
  },
344
706
  getScrollOffset: () => scrollTopRef.current,
345
707
  }),
346
- [count, headerH, footerH, scrollToOffset],
708
+ [count, headerH, footerH, maintainVisibleContentPosition, scrollToOffset],
347
709
  );
348
710
 
349
711
  React.useImperativeHandle(ref, buildHandle, [buildHandle]);
@@ -356,11 +718,21 @@ function VirtualListInner<T>(
356
718
  const isEmpty = count === 0;
357
719
 
358
720
  const rows: React.ReactNode[] = [];
359
- if (!isEmpty && range.end >= range.start) {
360
- for (let i = range.start; i <= range.end; i++) {
721
+ if (!isEmpty) {
722
+ // Clamp the window to the data we actually have. `range` is state, so a render
723
+ // triggered by `data` shrinking (a filter, a reset, a page rollback) still
724
+ // carries the window computed against the OLD, longer list — indexing `data`
725
+ // with it would hand `renderItem`/`keyExtractor` an `undefined` item. The
726
+ // re-window effect corrects `range` immediately after this commit; this keeps
727
+ // the one transitional render safe (and pinned to the new tail).
728
+ const winStart = Math.max(0, Math.min(range.start, count - 1));
729
+ const winEnd = Math.min(range.end, count - 1);
730
+ const hasWindow = winEnd >= winStart;
731
+ const renderRow = (i: number) => {
361
732
  const item = data[i];
362
- const key = keyExtractor ? keyExtractor(item, i) : String(i);
363
- rows.push(
733
+ // `keys` is already computed for the whole list; never re-derive per render.
734
+ const key = keys ? keys[i] : String(i);
735
+ return (
364
736
  <Row<T>
365
737
  key={key}
366
738
  item={item}
@@ -373,9 +745,42 @@ function VirtualListInner<T>(
373
745
  onMeasure={handleMeasure}
374
746
  itemProps={itemSlot}
375
747
  extraData={extraData}
376
- />,
748
+ />
377
749
  );
750
+ };
751
+
752
+ // The `keepMounted` extras, derived from the live pool against the window we
753
+ // are actually about to render (so they can never disagree) and cached on
754
+ // `(pool version, window, count)` — the renders in between, e.g. a measurement
755
+ // bumping `layoutVersion`, reuse the same list and the same array identity.
756
+ const retained = (() => {
757
+ const pool = retainRef.current;
758
+ if (pool.seen.size === 0) return NO_RETAINED;
759
+ const sig = `${pool.version}:${winStart}:${winEnd}:${count}`;
760
+ if (extrasRef.current.sig === sig) return extrasRef.current.list;
761
+ const list = retainedOutside(pool, { start: winStart, end: winEnd }, count);
762
+ const next = list.length === 0 ? NO_RETAINED : list;
763
+ extrasRef.current = { sig, list: next };
764
+ return next;
765
+ })();
766
+
767
+ // Window rows plus the extras, merged in ascending index order (both lists are
768
+ // already ascending, and `retainedOutside` guarantees the extras are in range
769
+ // and disjoint from the window). Rows are absolutely positioned, so the order is
770
+ // cosmetic — it keeps child order matching reading order.
771
+ let cursor = 0;
772
+ const emitExtrasBefore = (bound: number) => {
773
+ while (cursor < retained.length && retained[cursor] < bound) {
774
+ rows.push(renderRow(retained[cursor]));
775
+ cursor++;
776
+ }
777
+ };
778
+
779
+ if (hasWindow) {
780
+ emitExtrasBefore(winStart);
781
+ for (let i = winStart; i <= winEnd; i++) rows.push(renderRow(i));
378
782
  }
783
+ emitExtrasBefore(count);
379
784
  }
380
785
 
381
786
  return (
@@ -395,18 +800,7 @@ function VirtualListInner<T>(
395
800
  ) : (
396
801
  <VirtualListContent height={spacerHeight} {...contentSlot}>
397
802
  {ListHeaderComponent != null && (
398
- <Box
399
- position="absolute"
400
- top={0}
401
- left={0}
402
- right={0}
403
- onLayout={(e: LayoutChangeEvent) => {
404
- const h = e.nativeEvent.layout.height;
405
- if (Math.abs(headerHRef.current - h) <= 0.5) return;
406
- headerHRef.current = h;
407
- setHeaderH(h);
408
- }}
409
- >
803
+ <Box position="absolute" top={0} left={0} right={0} onLayout={handleHeaderLayout}>
410
804
  {ListHeaderComponent}
411
805
  </Box>
412
806
  )}
@@ -417,12 +811,7 @@ function VirtualListInner<T>(
417
811
  top={headerH + contentTotal}
418
812
  left={0}
419
813
  right={0}
420
- onLayout={(e: LayoutChangeEvent) => {
421
- const h = e.nativeEvent.layout.height;
422
- if (Math.abs(footerHRef.current - h) <= 0.5) return;
423
- footerHRef.current = h;
424
- setFooterH(h);
425
- }}
814
+ onLayout={handleFooterLayout}
426
815
  >
427
816
  {ListFooterComponent}
428
817
  </Box>