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