@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.
@@ -30,6 +30,12 @@ export interface VirtualListStyles {
30
30
  item?: Partial<BoxProps>;
31
31
  }
32
32
 
33
+ /**
34
+ * How much of the list stays mounted beyond the live window — see
35
+ * {@link VirtualListOwnProps.keepMounted} for the ladder.
36
+ */
37
+ export type KeepMounted = boolean | number | "all";
38
+
33
39
  /** Slot names of {@link VirtualListStyles}, for `slotStyles`. */
34
40
  export const VIRTUAL_LIST_SLOTS = [
35
41
  "scrollArea",
@@ -58,7 +64,14 @@ export interface VirtualListHandle {
58
64
  scrollToOffset(options: { offset: number; animated?: boolean }): void;
59
65
  /** Scroll to the very top. */
60
66
  scrollToTop(animated?: boolean): void;
61
- /** Scroll to the very end (bottom). */
67
+ /**
68
+ * Scroll to the very end (bottom).
69
+ *
70
+ * Under `maintainVisibleContentPosition` a non-animated call HOLDS the end
71
+ * rather than hitting it once, re-deriving it as the rows there measure — which
72
+ * is what a list opening at the bottom of unmeasured content needs, since the
73
+ * total it aims at starts out mostly estimate.
74
+ */
62
75
  scrollToEnd(animated?: boolean): void;
63
76
  /** The current vertical scroll offset (px). */
64
77
  getScrollOffset(): number;
@@ -77,9 +90,12 @@ export interface VirtualListOwnProps<T> {
77
90
  renderItem: (info: VirtualListRenderItemInfo<T>) => React.ReactNode;
78
91
 
79
92
  /**
80
- * Stable identity per row. Defaults to the index, which is only safe for
81
- * append-only data — supply this whenever rows can be inserted/removed/reordered
82
- * so measurements and React state track the right item.
93
+ * Stable identity per row. Supply this whenever rows can be inserted, removed,
94
+ * reordered or filtered: it is what makes the list's caches follow *items*
95
+ * instead of slots, so a measured height, a retained (`keepMounted`) row and its
96
+ * React state all move with their item. Without it the index is the identity,
97
+ * which is only correct for append/pop — a prepend shifts every measurement onto
98
+ * the wrong row and the list jumps while it re-measures.
83
99
  */
84
100
  keyExtractor?: (item: T, index: number) => string;
85
101
 
@@ -104,6 +120,39 @@ export interface VirtualListOwnProps<T> {
104
120
  */
105
121
  drawDistance?: number;
106
122
 
123
+ /**
124
+ * How much stays mounted beyond the live window. Rows kept this way sit in the
125
+ * tree at their real offsets (clipped by the scroller), so their React state,
126
+ * DOM/native state and any in-flight work survive scrolling away and back — no
127
+ * re-fetch, no reset inputs, no video restarting.
128
+ *
129
+ * An escalating ladder, cheapest first:
130
+ *
131
+ * - `false` (default) — pure virtualization: leaving the window unmounts.
132
+ * - a number — keep at most that many already-seen rows outside the current
133
+ * window, evicting the least-recently-visible first (an LRU warm pool).
134
+ * The safe choice for long lists: bounded memory, and the rows the user is
135
+ * likely to come back to are exactly the ones kept.
136
+ * - `true` — keep every row that has ever been mounted, for as long as it is in
137
+ * `data`. Unbounded, but still LAZY: a row the user has never scrolled to has
138
+ * never mounted, so a 10k-row list costs nothing until it is scrolled.
139
+ * - `"all"` — no windowing at all. Every row in `data` is mounted immediately,
140
+ * whether or not it has ever been on screen, and `drawDistance` is moot. This
141
+ * is the escape hatch for when rows must exist before they are seen — measuring
142
+ * them all up front, letting `Ctrl-F`/find-in-page reach every row, printing,
143
+ * or driving something that needs the whole tree. It gives up the entire point
144
+ * of virtualization: mount cost is O(data), so keep it to lists of a size you
145
+ * would have rendered with `.map()` anyway.
146
+ *
147
+ * Kept rows are still measured and still re-render on `extraData`. Under a number
148
+ * or `true` they do NOT widen {@link VirtualListOwnProps.onRenderedRangeChange},
149
+ * which keeps reporting the live window; under `"all"` the window IS the whole
150
+ * list, so it reports `{ start: 0, end: data.length - 1 }`.
151
+ *
152
+ * @default false
153
+ */
154
+ keepMounted?: KeepMounted;
155
+
107
156
  /** Re-render trigger for `renderItem` when external state changes (PureComponent-style). */
108
157
  extraData?: unknown;
109
158
 
@@ -117,6 +166,47 @@ export interface VirtualListOwnProps<T> {
117
166
  */
118
167
  onEndReachedThreshold?: number;
119
168
 
169
+ /**
170
+ * Fired once as the start (top) comes within `onStartReachedThreshold`
171
+ * viewports — the mirror of {@link onEndReached}, for a list paginated
172
+ * BACKWARDS (a chat thread loading older messages, a log tailing history).
173
+ *
174
+ * Like `onEndReached` on a list shorter than its viewport, this fires on mount
175
+ * when the list rests at offset 0, because it genuinely IS at the start. A
176
+ * caller that opens the list scrolled elsewhere (`scrollToEnd` on a chat
177
+ * thread) should gate its loader until that initial scroll has been applied,
178
+ * or the first frame spends a page request on nothing.
179
+ *
180
+ * Pair it with `maintainVisibleContentPosition` — without it, the rows the
181
+ * user is reading slide down by the height of whatever gets prepended.
182
+ */
183
+ onStartReached?: () => void;
184
+ /**
185
+ * Distance from the start at which `onStartReached` fires, in units of visible
186
+ * length (a viewport). @default 0.5
187
+ */
188
+ onStartReachedThreshold?: number;
189
+
190
+ /**
191
+ * Hold the reading position across a layout change instead of letting the rows
192
+ * slide. Two things stop being jumpy:
193
+ *
194
+ * - A **prepend** (a `onStartReached` page of history) has its inserted height
195
+ * added to the scroll offset in the same frame, so the row the user was
196
+ * looking at does not move. Requires `keyExtractor` — a prepend is detected by
197
+ * finding the previous first row's key at its new index, and index keys carry
198
+ * no identity to find it by.
199
+ * - A non-animated **`scrollToEnd`** holds the bottom while the rows there
200
+ * measure, rather than aiming once at a total that is still mostly estimate.
201
+ *
202
+ * Off by default: it takes over the scroll position, which a list that only
203
+ * grows at the tail has no reason to hand over. Either correction is abandoned
204
+ * the moment the user scrolls — continuing to correct through a live gesture
205
+ * would fight it — and as soon as the rows in question have all been measured,
206
+ * since nothing can move after that.
207
+ */
208
+ maintainVisibleContentPosition?: boolean;
209
+
120
210
  /**
121
211
  * The set of currently-rendered row indices whenever it changes. Useful for
122
212
  * prefetch/telemetry; not a viewability report (that is phase 2).
@@ -153,8 +243,10 @@ export const DEFAULT_ESTIMATED_ITEM_SIZE = 200;
153
243
  export const DEFAULT_DRAW_DISTANCE = 250;
154
244
  /** Default `onEndReached` threshold, in viewports. */
155
245
  export const DEFAULT_END_REACHED_THRESHOLD = 0.5;
156
- /** Height change (px) below which a measurement is treated as unchanged. */
157
- const MEASURE_EPSILON = 0.5;
246
+ /** Default `onStartReached` threshold, in viewports. */
247
+ export const DEFAULT_START_REACHED_THRESHOLD = 0.5;
248
+ /** Height change (px) at or below which a measurement is treated as unchanged. */
249
+ export const MEASURE_EPSILON = 0.5;
158
250
 
159
251
  /* -------------------------------------------------------------------------- */
160
252
  /* Layout store (pure, unit-tested) */
@@ -173,6 +265,12 @@ interface AverageBucket {
173
265
  count: number;
174
266
  }
175
267
 
268
+ /** One row's measurement, cached against its stable key. */
269
+ interface CachedMeasurement {
270
+ height: number;
271
+ type: string | number;
272
+ }
273
+
176
274
  /**
177
275
  * Mutable layout model for a variable-height, single-axis list. Holds each row
178
276
  * wrapper's measured height (or a per-type estimate until measured) and lazily
@@ -191,10 +289,26 @@ export interface LayoutState {
191
289
  averages: Map<string | number, AverageBucket>;
192
290
  /** Lowest index whose offset may be stale; `count + 1` means clean. */
193
291
  dirtyFrom: number;
292
+ /**
293
+ * The key of each row, when the caller supplied a `keyExtractor`; `null` in
294
+ * index mode. Present keys make measurements follow *items* rather than slots —
295
+ * see {@link syncLayoutKeys}.
296
+ */
297
+ keys: readonly string[] | null;
298
+ /** Measurement per key, so a row keeps its height across data changes. */
299
+ cache: Map<string, CachedMeasurement>;
194
300
  }
195
301
 
196
302
  const DEFAULT_TYPE = 0;
197
303
 
304
+ /**
305
+ * Retained multiple of `count` for the per-key measurement cache. Entries for
306
+ * rows no longer in `data` are kept until the cache outgrows this, so the common
307
+ * filter-then-restore (a search box) still finds its heights, while a long churn
308
+ * cannot grow the cache without bound.
309
+ */
310
+ const CACHE_SLACK = 2;
311
+
198
312
  /** Create a layout store for `count` rows, seeding every row with `estimate`. */
199
313
  export const createLayoutState = (count: number, estimate: number): LayoutState => ({
200
314
  count,
@@ -205,6 +319,8 @@ export const createLayoutState = (count: number, estimate: number): LayoutState
205
319
  offsets: new Array(count + 1).fill(0),
206
320
  averages: new Map(),
207
321
  dirtyFrom: 0,
322
+ keys: null,
323
+ cache: new Map(),
208
324
  });
209
325
 
210
326
  const bucketAverage = (bucket: AverageBucket | undefined, fallback: number): number => {
@@ -220,11 +336,79 @@ const estimateFor = (state: LayoutState, type: string | number): number =>
220
336
  export const heightAt = (state: LayoutState, i: number): number =>
221
337
  state.measured[i] ? state.heights[i] : estimateFor(state, state.types[i]);
222
338
 
339
+ /**
340
+ * Re-key the store to `keys` (one per row, in data order) and restore each row's
341
+ * measurement from the per-key cache.
342
+ *
343
+ * This is what makes a data change *identity-correct* rather than slot-correct, and
344
+ * it is the store half of backwards pagination. Index-keyed measurement is only
345
+ * right for append/pop: prepend one row and every height shifts to the wrong item,
346
+ * so the list reflows for the whole first scroll back up, re-learning heights in
347
+ * slots that already claimed to know them. Keyed by the caller's `keyExtractor`, a
348
+ * prepend, insert, removal, sort or filter moves each height with its item, and rows
349
+ * already measured never flash.
350
+ *
351
+ * Rebuilds the per-index arrays from the cache (O(n) — run only when the key list
352
+ * actually changes, not per render) and marks offsets stale from the first row that
353
+ * moved. Restored measurements deliberately do NOT re-feed the per-type running
354
+ * averages: they were counted when first measured.
355
+ */
356
+ export const syncLayoutKeys = (state: LayoutState, keys: readonly string[]): void => {
357
+ const count = keys.length;
358
+ const prevCount = state.count;
359
+ let firstChanged = count;
360
+
361
+ const note = (i: number) => {
362
+ if (i < firstChanged) firstChanged = i;
363
+ };
364
+
365
+ for (let i = 0; i < count; i++) {
366
+ const hit = state.cache.get(keys[i]);
367
+ const height = hit ? hit.height : state.estimate;
368
+ const measured = hit !== undefined;
369
+ const type = hit ? hit.type : DEFAULT_TYPE;
370
+ if (
371
+ i >= prevCount ||
372
+ state.measured[i] !== measured ||
373
+ state.types[i] !== type ||
374
+ state.heights[i] !== height
375
+ ) {
376
+ note(i);
377
+ }
378
+ state.heights[i] = height;
379
+ state.measured[i] = measured;
380
+ state.types[i] = type;
381
+ }
382
+
383
+ if (count < prevCount) {
384
+ state.heights.length = count;
385
+ state.measured.length = count;
386
+ state.types.length = count;
387
+ note(count);
388
+ }
389
+ state.offsets.length = count + 1;
390
+ state.count = count;
391
+ state.keys = keys;
392
+ state.dirtyFrom = Math.min(state.dirtyFrom, firstChanged);
393
+
394
+ // Bound the cache: drop measurements for keys the data no longer holds, but only
395
+ // once it has grown past the slack, so short-lived removals keep their heights.
396
+ if (state.cache.size > count * CACHE_SLACK + 1) {
397
+ const live = new Set(keys);
398
+ for (const key of state.cache.keys()) {
399
+ if (!live.has(key)) state.cache.delete(key);
400
+ }
401
+ }
402
+ };
403
+
223
404
  /**
224
405
  * Grow/shrink the store to `count` rows, preserving existing measurements by
225
- * index (correct for append/pop; a prepend/reorder without a stable
226
- * `keyExtractor` would misattribute — a known v1 limitation). Returns the new
227
- * state (same instance, mutated) so callers can keep their ref.
406
+ * index — correct for an append or a pop, which is what row `i` keeping its height
407
+ * means, and the only option in index mode (no `keyExtractor`). A PREPEND is not
408
+ * that shape, and neither is a reorder or a filter: supply a `keyExtractor` and
409
+ * {@link syncLayoutKeys} keeps every measurement attached to its item across any
410
+ * data change instead. Returns the new state (same instance, mutated) so callers
411
+ * can keep their ref.
228
412
  */
229
413
  export const resizeLayoutState = (state: LayoutState, count: number): LayoutState => {
230
414
  if (count === state.count) return state;
@@ -246,6 +430,19 @@ export const resizeLayoutState = (state: LayoutState, count: number): LayoutStat
246
430
  return state;
247
431
  };
248
432
 
433
+ /**
434
+ * Whether every row in `[from, to)` carries a real measurement — i.e. whether
435
+ * anything in that band can still move. Used to release the prepend anchor once
436
+ * the inserted rows have settled.
437
+ */
438
+ export const areRowsMeasured = (state: LayoutState, from: number, to: number): boolean => {
439
+ const hi = Math.min(to, state.count);
440
+ for (let i = Math.max(0, from); i < hi; i++) {
441
+ if (!state.measured[i]) return false;
442
+ }
443
+ return true;
444
+ };
445
+
249
446
  /**
250
447
  * Record a measured wrapper height for row `i` of `type`. Updates the per-type
251
448
  * running average and marks offsets stale from `i`. Returns `true` when the
@@ -279,6 +476,9 @@ export const setMeasured = (
279
476
  state.heights[i] = height;
280
477
  state.measured[i] = true;
281
478
  state.dirtyFrom = Math.min(state.dirtyFrom, i);
479
+ // Mirror into the per-key cache so the measurement survives a data change.
480
+ const key = state.keys?.[i];
481
+ if (key !== undefined) state.cache.set(key, { height, type });
282
482
  return true;
283
483
  };
284
484
 
@@ -357,3 +557,181 @@ export const findVisibleRange = (
357
557
  const end = Math.max(start, lastRowStartingBefore(state, bottom));
358
558
  return { start, end };
359
559
  };
560
+
561
+ /* -------------------------------------------------------------------------- */
562
+ /* Retention pool (pure, unit-tested) */
563
+ /* -------------------------------------------------------------------------- */
564
+
565
+ /**
566
+ * The `keepMounted` warm pool: which already-seen rows stay mounted after they
567
+ * leave the window. A `Set` doubles as the LRU order — JS iterates insertion
568
+ * order, and re-visiting a row is `delete` + `add`, which moves it to the back —
569
+ * so the front of the set is always the least-recently-visible row and eviction
570
+ * is a forward walk.
571
+ */
572
+ export interface RetainState {
573
+ /** Every retained index, oldest-visible first. */
574
+ seen: Set<number>;
575
+ /**
576
+ * Bumped on every content change. The component derives its mounted extras from
577
+ * the pool during render rather than mirroring them into state (state would go
578
+ * stale the moment a data change remapped the pool mid-render); this counter is
579
+ * what lets that derivation be cached across the renders in between.
580
+ */
581
+ version: number;
582
+ }
583
+
584
+ /** Create an empty retention pool. */
585
+ export const createRetainState = (): RetainState => ({ seen: new Set(), version: 0 });
586
+
587
+ /** Empty extras list — a shared constant so "nothing retained" is one identity. */
588
+ export const NO_RETAINED: readonly number[] = [];
589
+
590
+ /** The `keepMounted` value that turns windowing off entirely. */
591
+ export const MOUNT_ALL = "all";
592
+
593
+ /** Whether `keepMounted` asks for the whole list to be mounted up front. */
594
+ export const isMountAll = (keepMounted: KeepMounted | undefined): boolean =>
595
+ keepMounted === MOUNT_ALL;
596
+
597
+ /**
598
+ * Resolve the `keepMounted` prop to a pool capacity: `0` (off), a positive integer,
599
+ * or `Infinity` (unbounded). `"all"` resolves to `0` — with every row inside the
600
+ * window there is nothing left for a pool to hold.
601
+ */
602
+ export const resolveRetainLimit = (keepMounted: KeepMounted | undefined): number => {
603
+ if (keepMounted === true) return Infinity;
604
+ if (typeof keepMounted === "number") return keepMounted > 0 ? Math.floor(keepMounted) : 0;
605
+ return 0;
606
+ };
607
+
608
+ /**
609
+ * Fold the live window `range` into the pool: rows in the window are (re)marked
610
+ * most-recently-visible (which is also how a row first enters the pool), rows the
611
+ * data no longer has are dropped, and once the rows outside the window exceed
612
+ * `limit` the least-recently-visible ones are evicted until they fit. A `limit` of
613
+ * `0` empties the pool, so turning `keepMounted` off releases everything.
614
+ *
615
+ * Mutates `state`, bumping `state.version` only when something actually changed,
616
+ * and is idempotent for an unchanged `(range, count, limit)`. Read the result with
617
+ * {@link retainedOutside}.
618
+ */
619
+ export const retainRange = (
620
+ state: RetainState,
621
+ range: { start: number; end: number },
622
+ count: number,
623
+ limit: number,
624
+ ): void => {
625
+ const { seen } = state;
626
+ let changed = false;
627
+
628
+ if (limit <= 0) {
629
+ if (seen.size > 0) {
630
+ seen.clear();
631
+ state.version++;
632
+ }
633
+ return;
634
+ }
635
+
636
+ // Rows the data no longer has can never be rendered again.
637
+ for (const i of seen) {
638
+ if (i >= count) {
639
+ seen.delete(i);
640
+ changed = true;
641
+ }
642
+ }
643
+
644
+ // Re-insert the live rows so the window is always the most-recently-visible end
645
+ // of the LRU order. Re-inserting an already-present row reorders the pool without
646
+ // changing which rows it holds — that is a change the render does not care about
647
+ // (the window is mounted regardless), so it does not bump the version.
648
+ const first = Math.max(0, range.start);
649
+ const last = Math.min(range.end, count - 1);
650
+ for (let i = first; i <= last; i++) {
651
+ if (!seen.delete(i)) changed = true;
652
+ seen.add(i);
653
+ }
654
+
655
+ const inWindow = (i: number): boolean => i >= first && i <= last;
656
+
657
+ let extras = 0;
658
+ for (const i of seen) {
659
+ if (!inWindow(i)) extras++;
660
+ }
661
+ // Evict oldest-first; the live window is never evictable (it is mounted anyway).
662
+ if (extras > limit) {
663
+ for (const i of seen) {
664
+ if (extras <= limit) break;
665
+ if (inWindow(i)) continue;
666
+ seen.delete(i);
667
+ extras--;
668
+ changed = true;
669
+ }
670
+ }
671
+
672
+ if (changed) state.version++;
673
+ };
674
+
675
+ /**
676
+ * The retained rows that fall OUTSIDE `range`, ascending — exactly the extra rows
677
+ * to mount on top of the window. Pure: safe to call during render.
678
+ */
679
+ export const retainedOutside = (
680
+ state: RetainState,
681
+ range: { start: number; end: number },
682
+ count: number,
683
+ ): number[] => {
684
+ const out: number[] = [];
685
+ for (const i of state.seen) {
686
+ if (i < 0 || i >= count) continue;
687
+ if (i >= range.start && i <= range.end) continue;
688
+ out.push(i);
689
+ }
690
+ // Ascending, so mounted children stay in reading order (they are absolutely
691
+ // positioned, so this is about tab/screen-reader order, not layout).
692
+ out.sort((a, b) => a - b);
693
+ return out;
694
+ };
695
+
696
+ /**
697
+ * Move the pool's indices onto a new key list, so "already mounted" tracks the
698
+ * *item* across a data change instead of the slot it happened to occupy. Rows that
699
+ * left the data drop out; the LRU order is preserved (a `Set` rebuilt in iteration
700
+ * order keeps oldest-visible first). A no-op when nothing is retained.
701
+ */
702
+ export const remapRetainState = (
703
+ state: RetainState,
704
+ oldKeys: readonly string[],
705
+ newKeys: readonly string[],
706
+ ): void => {
707
+ if (state.seen.size === 0) return;
708
+ const indexByKey = new Map<string, number>();
709
+ for (let i = 0; i < newKeys.length; i++) indexByKey.set(newKeys[i], i);
710
+ const next = new Set<number>();
711
+ for (const i of state.seen) {
712
+ const key = oldKeys[i];
713
+ if (key === undefined) continue;
714
+ const at = indexByKey.get(key);
715
+ if (at !== undefined) next.add(at);
716
+ }
717
+ state.seen = next;
718
+ state.version++;
719
+ };
720
+
721
+ /**
722
+ * One-level equality for two prop bags. Used to give an inline `styles.item`
723
+ * object a stable identity across renders, so a caller writing the idiomatic
724
+ * `styles={{ item: { … } }}` literal does not defeat every row's memo.
725
+ */
726
+ export const shallowEqualProps = (
727
+ a: Record<string, unknown>,
728
+ b: Record<string, unknown>,
729
+ ): boolean => {
730
+ if (a === b) return true;
731
+ const aKeys = Object.keys(a);
732
+ if (aKeys.length !== Object.keys(b).length) return false;
733
+ for (const key of aKeys) {
734
+ if (!Object.is(a[key], b[key])) return false;
735
+ }
736
+ return true;
737
+ };