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