@legendapp/list 3.0.0-beta.8 → 3.0.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 (49) hide show
  1. package/.DS_Store +0 -0
  2. package/CHANGELOG.md +21 -1
  3. package/README.md +8 -2
  4. package/animated.d.ts +659 -5
  5. package/animated.js +2 -2
  6. package/animated.mjs +1 -1
  7. package/keyboard-legacy.d.ts +226 -0
  8. package/keyboard-legacy.js +456 -0
  9. package/keyboard-legacy.mjs +435 -0
  10. package/keyboard.d.ts +261 -9
  11. package/keyboard.js +114 -135
  12. package/keyboard.mjs +115 -137
  13. package/package.json +55 -5
  14. package/{types-DjNeqVEk.d.mts → react-native.d.ts} +318 -278
  15. package/react-native.js +6453 -0
  16. package/react-native.mjs +6424 -0
  17. package/react-native.web.d.ts +771 -0
  18. package/react-native.web.js +7111 -0
  19. package/react-native.web.mjs +7082 -0
  20. package/react.d.ts +771 -0
  21. package/react.js +7111 -0
  22. package/react.mjs +7082 -0
  23. package/reanimated.d.ts +681 -8
  24. package/reanimated.js +225 -29
  25. package/reanimated.mjs +227 -31
  26. package/section-list.d.ts +663 -5
  27. package/section-list.js +39 -3720
  28. package/section-list.mjs +37 -3719
  29. package/animated.d.mts +0 -9
  30. package/index.d.mts +0 -23
  31. package/index.d.ts +0 -23
  32. package/index.js +0 -3826
  33. package/index.mjs +0 -3798
  34. package/index.native.d.mts +0 -23
  35. package/index.native.d.ts +0 -23
  36. package/index.native.js +0 -3580
  37. package/index.native.mjs +0 -3552
  38. package/keyboard-controller.d.mts +0 -12
  39. package/keyboard-controller.d.ts +0 -12
  40. package/keyboard-controller.js +0 -69
  41. package/keyboard-controller.mjs +0 -48
  42. package/keyboard.d.mts +0 -13
  43. package/reanimated.d.mts +0 -18
  44. package/section-list.d.mts +0 -113
  45. package/section-list.native.d.mts +0 -113
  46. package/section-list.native.d.ts +0 -113
  47. package/section-list.native.js +0 -3738
  48. package/section-list.native.mjs +0 -3717
  49. package/types-DjNeqVEk.d.ts +0 -669
package/section-list.mjs CHANGED
@@ -1,3712 +1,18 @@
1
- import * as React3 from 'react';
2
- import React3__default, { forwardRef, useReducer, useEffect, createContext, useRef, useState, useMemo, useCallback, useImperativeHandle, useLayoutEffect, memo, useContext } from 'react';
3
- import { Platform as Platform$1 } from 'react-native';
4
- import { useSyncExternalStore } from 'use-sync-external-store/shim';
5
- import { unstable_batchedUpdates } from 'react-dom';
1
+ import * as React from 'react';
2
+ import { Platform } from 'react-native';
3
+ import { internal, LegendList } from '@legendapp/list/react-native';
6
4
 
7
5
  // src/section-list/SectionList.tsx
8
- forwardRef(function AnimatedView2(props, ref) {
9
- return /* @__PURE__ */ React3.createElement("div", { ref, ...props });
10
- });
11
- var View = forwardRef(function View2(props, ref) {
12
- return /* @__PURE__ */ React3.createElement("div", { ref, ...props });
13
- });
14
- var Text = View;
15
-
16
- // src/platform/Animated.tsx
17
- var createAnimatedValue = (value) => value;
18
-
19
- // src/state/state.tsx
20
- var ContextState = React3.createContext(null);
21
- function StateProvider({ children }) {
22
- const [value] = React3.useState(() => ({
23
- animatedScrollY: createAnimatedValue(0),
24
- columnWrapperStyle: void 0,
25
- internalState: void 0,
26
- listeners: /* @__PURE__ */ new Map(),
27
- mapViewabilityAmountCallbacks: /* @__PURE__ */ new Map(),
28
- mapViewabilityAmountValues: /* @__PURE__ */ new Map(),
29
- mapViewabilityCallbacks: /* @__PURE__ */ new Map(),
30
- mapViewabilityConfigStates: /* @__PURE__ */ new Map(),
31
- mapViewabilityValues: /* @__PURE__ */ new Map(),
32
- values: /* @__PURE__ */ new Map([
33
- ["alignItemsPaddingTop", 0],
34
- ["stylePaddingTop", 0],
35
- ["headerSize", 0],
36
- ["numContainers", 0],
37
- ["activeStickyIndex", void 0],
38
- ["totalSize", 0],
39
- ["scrollAdjustPending", 0],
40
- ["scrollingTo", void 0]
41
- ]),
42
- viewRefs: /* @__PURE__ */ new Map()
43
- }));
44
- return /* @__PURE__ */ React3.createElement(ContextState.Provider, { value }, children);
45
- }
46
- function useStateContext() {
47
- return React3.useContext(ContextState);
48
- }
49
- function createSelectorFunctionsArr(ctx, signalNames) {
50
- let lastValues = [];
51
- let lastSignalValues = [];
52
- return {
53
- get: () => {
54
- const currentValues = [];
55
- let hasChanged = false;
56
- for (let i = 0; i < signalNames.length; i++) {
57
- const value = peek$(ctx, signalNames[i]);
58
- currentValues.push(value);
59
- if (value !== lastSignalValues[i]) {
60
- hasChanged = true;
61
- }
62
- }
63
- lastSignalValues = currentValues;
64
- if (hasChanged) {
65
- lastValues = currentValues;
66
- }
67
- return lastValues;
68
- },
69
- subscribe: (cb) => {
70
- const listeners = [];
71
- for (const signalName of signalNames) {
72
- listeners.push(listen$(ctx, signalName, cb));
73
- }
74
- return () => {
75
- for (const listener of listeners) {
76
- listener();
77
- }
78
- };
79
- }
80
- };
81
- }
82
- function listen$(ctx, signalName, cb) {
83
- const { listeners } = ctx;
84
- let setListeners = listeners.get(signalName);
85
- if (!setListeners) {
86
- setListeners = /* @__PURE__ */ new Set();
87
- listeners.set(signalName, setListeners);
88
- }
89
- setListeners.add(cb);
90
- return () => setListeners.delete(cb);
91
- }
92
- function peek$(ctx, signalName) {
93
- const { values } = ctx;
94
- return values.get(signalName);
95
- }
96
- function set$(ctx, signalName, value) {
97
- const { listeners, values } = ctx;
98
- if (values.get(signalName) !== value) {
99
- values.set(signalName, value);
100
- const setListeners = listeners.get(signalName);
101
- if (setListeners) {
102
- for (const listener of setListeners) {
103
- listener(value);
104
- }
105
- }
106
- }
107
- }
108
- function getContentSize(ctx) {
109
- var _a3, _b;
110
- const { values, internalState } = ctx;
111
- const stylePaddingTop = values.get("stylePaddingTop") || 0;
112
- const stylePaddingBottom = (internalState == null ? void 0 : internalState.props.stylePaddingBottom) || 0;
113
- const headerSize = values.get("headerSize") || 0;
114
- const footerSize = values.get("footerSize") || 0;
115
- const totalSize = (_b = (_a3 = ctx.internalState) == null ? void 0 : _a3.pendingTotalSize) != null ? _b : values.get("totalSize");
116
- return headerSize + footerSize + totalSize + stylePaddingTop + stylePaddingBottom;
117
- }
118
- function useArr$(signalNames) {
119
- const ctx = React3.useContext(ContextState);
120
- const { subscribe, get } = React3.useMemo(() => createSelectorFunctionsArr(ctx, signalNames), [ctx, signalNames]);
121
- const value = useSyncExternalStore(subscribe, get);
122
- return value;
123
- }
124
- function useSelector$(signalName, selector) {
125
- const ctx = React3.useContext(ContextState);
126
- const { subscribe, get } = React3.useMemo(() => createSelectorFunctionsArr(ctx, [signalName]), [ctx, signalName]);
127
- const value = useSyncExternalStore(subscribe, () => selector(get()[0]));
128
- return value;
129
- }
130
-
131
- // src/components/DebugView.tsx
132
- var DebugRow = ({ children }) => {
133
- return /* @__PURE__ */ React3.createElement(View, { style: { alignItems: "center", flexDirection: "row", justifyContent: "space-between" } }, children);
134
- };
135
- var DebugView = React3.memo(function DebugView2({ state }) {
136
- const ctx = useStateContext();
137
- const [totalSize = 0, scrollAdjust = 0, rawScroll = 0, scroll = 0, _numContainers = 0, _numContainersPooled = 0] = useArr$([
138
- "totalSize",
139
- "scrollAdjust",
140
- "debugRawScroll",
141
- "debugComputedScroll",
142
- "numContainers",
143
- "numContainersPooled"
144
- ]);
145
- const contentSize = getContentSize(ctx);
146
- const [, forceUpdate] = useReducer((x) => x + 1, 0);
147
- useInterval(() => {
148
- forceUpdate();
149
- }, 100);
150
- return /* @__PURE__ */ React3.createElement(
151
- View,
152
- {
153
- pointerEvents: "none",
154
- style: {
155
- // height: 100,
156
- backgroundColor: "#FFFFFFCC",
157
- borderRadius: 4,
158
- padding: 4,
159
- paddingBottom: 4,
160
- paddingLeft: 4,
161
- position: "absolute",
162
- right: 0,
163
- top: 0
164
- }
165
- },
166
- /* @__PURE__ */ React3.createElement(DebugRow, null, /* @__PURE__ */ React3.createElement(Text, null, "TotalSize:"), /* @__PURE__ */ React3.createElement(Text, null, totalSize.toFixed(2))),
167
- /* @__PURE__ */ React3.createElement(DebugRow, null, /* @__PURE__ */ React3.createElement(Text, null, "ContentSize:"), /* @__PURE__ */ React3.createElement(Text, null, contentSize.toFixed(2))),
168
- /* @__PURE__ */ React3.createElement(DebugRow, null, /* @__PURE__ */ React3.createElement(Text, null, "At end:"), /* @__PURE__ */ React3.createElement(Text, null, String(state.isAtEnd))),
169
- /* @__PURE__ */ React3.createElement(DebugRow, null, /* @__PURE__ */ React3.createElement(Text, null, "ScrollAdjust:"), /* @__PURE__ */ React3.createElement(Text, null, scrollAdjust.toFixed(2))),
170
- /* @__PURE__ */ React3.createElement(DebugRow, null, /* @__PURE__ */ React3.createElement(Text, null, "RawScroll: "), /* @__PURE__ */ React3.createElement(Text, null, rawScroll.toFixed(2))),
171
- /* @__PURE__ */ React3.createElement(DebugRow, null, /* @__PURE__ */ React3.createElement(Text, null, "ComputedScroll: "), /* @__PURE__ */ React3.createElement(Text, null, scroll.toFixed(2)))
172
- );
173
- });
174
- function useInterval(callback, delay) {
175
- useEffect(() => {
176
- const interval = setInterval(callback, delay);
177
- return () => clearInterval(interval);
178
- }, [delay]);
179
- }
180
-
181
- // src/utils/devEnvironment.ts
182
- var metroDev = typeof __DEV__ !== "undefined" ? __DEV__ : void 0;
183
- var _a;
184
- var envMode = typeof process !== "undefined" && typeof process.env === "object" && process.env ? (_a = process.env.NODE_ENV) != null ? _a : process.env.MODE : void 0;
185
- var processDev = typeof envMode === "string" ? envMode.toLowerCase() !== "production" : void 0;
186
- var _a2;
187
- var IS_DEV = (_a2 = metroDev != null ? metroDev : processDev) != null ? _a2 : false;
188
-
189
- // src/constants.ts
190
- var POSITION_OUT_OF_VIEW = -1e7;
191
- var ENABLE_DEVMODE = IS_DEV && false;
192
- var ENABLE_DEBUG_VIEW = IS_DEV && false;
193
- var typedForwardRef = forwardRef;
194
- var typedMemo = memo;
195
-
196
- // src/utils/helpers.ts
197
- function isFunction(obj) {
198
- return typeof obj === "function";
199
- }
200
- function isArray(obj) {
201
- return Array.isArray(obj);
202
- }
203
- var warned = /* @__PURE__ */ new Set();
204
- function warnDevOnce(id, text) {
205
- if (IS_DEV && !warned.has(id)) {
206
- warned.add(id);
207
- console.warn(`[legend-list] ${text}`);
208
- }
209
- }
210
- function roundSize(size) {
211
- return Math.floor(size * 8) / 8;
212
- }
213
- function isNullOrUndefined(value) {
214
- return value === null || value === void 0;
215
- }
216
- function comparatorDefault(a, b) {
217
- return a - b;
218
- }
219
- function getPadding(s, type) {
220
- var _a3, _b, _c;
221
- return (_c = (_b = (_a3 = s[`padding${type}`]) != null ? _a3 : s.paddingVertical) != null ? _b : s.padding) != null ? _c : 0;
222
- }
223
- function extractPadding(style, contentContainerStyle, type) {
224
- return getPadding(style, type) + getPadding(contentContainerStyle, type);
225
- }
226
- function findContainerId(ctx, key) {
227
- const numContainers = peek$(ctx, "numContainers");
228
- for (let i = 0; i < numContainers; i++) {
229
- const itemKey = peek$(ctx, `containerItemKey${i}`);
230
- if (itemKey === key) {
231
- return i;
232
- }
233
- }
234
- return -1;
235
- }
236
-
237
- // src/components/PositionView.tsx
238
- var PositionViewState = typedMemo(function PositionViewState2({
239
- id,
240
- horizontal,
241
- style,
242
- refView,
243
- ...rest
244
- }) {
245
- const [position = POSITION_OUT_OF_VIEW] = useArr$([`containerPosition${id}`]);
246
- const base = {
247
- contain: "paint layout style"
248
- };
249
- const composed = isArray(style) ? Object.assign({}, ...style) : style;
250
- const combinedStyle = horizontal ? { ...base, ...composed, left: position } : { ...base, ...composed, top: position };
251
- return /* @__PURE__ */ React3.createElement("div", { ref: refView, style: combinedStyle, ...rest });
252
- });
253
- var PositionViewSticky = typedMemo(function PositionViewSticky2({
254
- id,
255
- horizontal,
256
- style,
257
- refView,
258
- index,
259
- stickyOffset,
260
- animatedScrollY: _animatedScrollY,
261
- children,
262
- ...rest
263
- }) {
264
- const [position = POSITION_OUT_OF_VIEW, headerSize = 0, activeStickyIndex] = useArr$([
265
- `containerPosition${id}`,
266
- "headerSize",
267
- "activeStickyIndex"
268
- ]);
269
- const base = {
270
- contain: "paint layout style"
271
- };
272
- const composed = React3.useMemo(
273
- () => {
274
- var _a3;
275
- return (_a3 = isArray(style) ? Object.assign({}, ...style) : style) != null ? _a3 : {};
276
- },
277
- [style]
278
- );
279
- const viewStyle = React3.useMemo(() => {
280
- var _a3;
281
- const styleBase = { ...base, ...composed };
282
- delete styleBase.transform;
283
- const offset = (_a3 = stickyOffset != null ? stickyOffset : headerSize) != null ? _a3 : 0;
284
- const isActive = activeStickyIndex === index;
285
- styleBase.position = isActive ? "sticky" : "absolute";
286
- styleBase.zIndex = index + 1e3;
287
- if (horizontal) {
288
- styleBase.left = isActive ? offset : position;
289
- } else {
290
- styleBase.top = isActive ? offset : position;
291
- }
292
- return styleBase;
293
- }, [composed, horizontal, position, index, stickyOffset, headerSize, activeStickyIndex]);
294
- return /* @__PURE__ */ React3.createElement("div", { ref: refView, style: viewStyle, ...rest }, children);
295
- });
296
- var PositionView = PositionViewState;
297
-
298
- // src/constants-platform.ts
299
- var IsNewArchitecture = true;
300
-
301
- // src/state/ContextContainer.ts
302
- var ContextContainer = createContext(null);
303
- function useIsLastItem() {
304
- const { itemKey } = useContext(ContextContainer);
305
- const isLast = useSelector$("lastItemKeys", (lastItemKeys) => (lastItemKeys == null ? void 0 : lastItemKeys.includes(itemKey)) || false);
306
- return isLast;
307
- }
308
-
309
- // src/components/Separator.tsx
310
- function Separator({ ItemSeparatorComponent, leadingItem }) {
311
- const isLastItem = useIsLastItem();
312
- return isLastItem ? null : /* @__PURE__ */ React3.createElement(ItemSeparatorComponent, { leadingItem });
313
- }
314
-
315
- // src/hooks/createResizeObserver.ts
316
- var globalResizeObserver = null;
317
- function getGlobalResizeObserver() {
318
- if (!globalResizeObserver) {
319
- globalResizeObserver = new ResizeObserver((entries) => {
320
- for (const entry of entries) {
321
- const callbacks = callbackMap.get(entry.target);
322
- if (callbacks) {
323
- for (const callback of callbacks) {
324
- callback(entry);
325
- }
326
- }
327
- }
328
- });
329
- }
330
- return globalResizeObserver;
331
- }
332
- var callbackMap = /* @__PURE__ */ new WeakMap();
333
- function createResizeObserver(element, callback) {
334
- if (typeof ResizeObserver === "undefined") {
335
- return () => {
336
- };
337
- }
338
- if (!element) {
339
- return () => {
340
- };
341
- }
342
- const observer = getGlobalResizeObserver();
343
- let callbacks = callbackMap.get(element);
344
- if (!callbacks) {
345
- callbacks = /* @__PURE__ */ new Set();
346
- callbackMap.set(element, callbacks);
347
- observer.observe(element);
348
- }
349
- callbacks.add(callback);
350
- return () => {
351
- if (callbacks) {
352
- callbacks.delete(callback);
353
- if (callbacks.size === 0) {
354
- callbackMap.delete(element);
355
- observer.unobserve(element);
356
- }
357
- }
358
- };
359
- }
360
-
361
- // src/hooks/useOnLayoutSync.tsx
362
- function useOnLayoutSync({
363
- ref,
364
- onLayoutProp,
365
- onLayoutChange
366
- }, deps) {
367
- useLayoutEffect(() => {
368
- var _a3, _b;
369
- const current = ref.current;
370
- const scrollableNode = (_b = (_a3 = current == null ? void 0 : current.getScrollableNode) == null ? void 0 : _a3.call(current)) != null ? _b : null;
371
- const element = scrollableNode || current;
372
- if (!element) {
373
- return;
374
- }
375
- const emit = (layout, fromLayoutEffect) => {
376
- if (layout.height === 0 && layout.width === 0) {
377
- return;
378
- }
379
- onLayoutChange(layout, fromLayoutEffect);
380
- onLayoutProp == null ? void 0 : onLayoutProp({ nativeEvent: { layout } });
381
- };
382
- const rect = element.getBoundingClientRect();
383
- emit(toLayout(rect), true);
384
- let prevRect = rect;
385
- return createResizeObserver(element, (entry) => {
386
- var _a4;
387
- const target = entry.target instanceof HTMLElement ? entry.target : void 0;
388
- const rectObserved = (_a4 = entry.contentRect) != null ? _a4 : target == null ? void 0 : target.getBoundingClientRect();
389
- if (rectObserved.width !== prevRect.width || rectObserved.height !== prevRect.height) {
390
- prevRect = rectObserved;
391
- emit(toLayout(rectObserved), false);
392
- }
393
- });
394
- }, deps || []);
395
- return {};
396
- }
397
- function toLayout(rect) {
398
- if (!rect) {
399
- return { height: 0, width: 0, x: 0, y: 0 };
400
- }
401
- return {
402
- height: rect.height,
403
- width: rect.width,
404
- x: rect.left,
405
- y: rect.top
406
- };
407
- }
408
-
409
- // src/components/Container.tsx
410
- var Container = typedMemo(function Container2({
411
- id,
412
- recycleItems,
413
- horizontal,
414
- getRenderedItem: getRenderedItem2,
415
- updateItemSize: updateItemSize2,
416
- ItemSeparatorComponent
417
- }) {
418
- const ctx = useStateContext();
419
- const { columnWrapperStyle, animatedScrollY } = ctx;
420
- const [column = 0, data, itemKey, numColumns, extraData, isSticky, stickyOffset] = useArr$([
421
- `containerColumn${id}`,
422
- `containerItemData${id}`,
423
- `containerItemKey${id}`,
424
- "numColumns",
425
- "extraData",
426
- `containerSticky${id}`,
427
- `containerStickyOffset${id}`
428
- ]);
429
- const itemLayoutRef = useRef({
430
- horizontal,
431
- itemKey,
432
- updateItemSize: updateItemSize2
433
- });
434
- itemLayoutRef.current.horizontal = horizontal;
435
- itemLayoutRef.current.itemKey = itemKey;
436
- itemLayoutRef.current.updateItemSize = updateItemSize2;
437
- const ref = useRef(null);
438
- const [layoutRenderCount, forceLayoutRender] = useState(0);
439
- const otherAxisPos = numColumns > 1 ? `${(column - 1) / numColumns * 100}%` : 0;
440
- const otherAxisSize = numColumns > 1 ? `${1 / numColumns * 100}%` : void 0;
441
- const didLayoutRef = useRef(false);
442
- const style = useMemo(() => {
443
- let paddingStyles;
444
- if (columnWrapperStyle) {
445
- const { columnGap, rowGap, gap } = columnWrapperStyle;
446
- if (horizontal) {
447
- paddingStyles = {
448
- paddingRight: columnGap || gap || void 0,
449
- paddingVertical: numColumns > 1 ? (rowGap || gap || 0) / 2 : void 0
450
- };
451
- } else {
452
- paddingStyles = {
453
- paddingBottom: rowGap || gap || void 0,
454
- paddingHorizontal: numColumns > 1 ? (columnGap || gap || 0) / 2 : void 0
455
- };
456
- }
457
- }
458
- return horizontal ? {
459
- flexDirection: ItemSeparatorComponent ? "row" : void 0,
460
- height: otherAxisSize,
461
- left: 0,
462
- position: "absolute",
463
- top: otherAxisPos,
464
- ...paddingStyles || {}
465
- } : {
466
- left: otherAxisPos,
467
- position: "absolute",
468
- right: numColumns > 1 ? null : 0,
469
- top: 0,
470
- width: otherAxisSize,
471
- ...paddingStyles || {}
472
- };
473
- }, [horizontal, otherAxisPos, otherAxisSize, columnWrapperStyle, numColumns]);
474
- const renderedItemInfo = useMemo(
475
- () => itemKey !== void 0 ? getRenderedItem2(itemKey) : null,
476
- [itemKey, data, extraData]
477
- );
478
- const { index, renderedItem } = renderedItemInfo || {};
479
- const contextValue = useMemo(() => {
480
- ctx.viewRefs.set(id, ref);
481
- return {
482
- containerId: id,
483
- index,
484
- itemKey,
485
- triggerLayout: () => {
486
- forceLayoutRender((v) => v + 1);
487
- },
488
- value: data
489
- };
490
- }, [id, itemKey, index, data]);
491
- const onLayoutChange = useCallback((rectangle) => {
492
- const {
493
- horizontal: currentHorizontal,
494
- itemKey: currentItemKey,
495
- updateItemSize: updateItemSizeFn
496
- } = itemLayoutRef.current;
497
- if (isNullOrUndefined(currentItemKey)) {
498
- return;
499
- }
500
- didLayoutRef.current = true;
501
- let layout = rectangle;
502
- roundSize(rectangle[currentHorizontal ? "width" : "height"]);
503
- const doUpdate = () => {
504
- itemLayoutRef.current.lastSize = { height: layout.height, width: layout.width };
505
- updateItemSizeFn(currentItemKey, layout);
506
- didLayoutRef.current = true;
507
- };
508
- {
509
- doUpdate();
510
- }
511
- }, []);
512
- const { onLayout } = useOnLayoutSync(
513
- {
514
- onLayoutChange,
515
- ref
516
- },
517
- [itemKey, layoutRenderCount]
518
- );
519
- const PositionComponent = isSticky ? PositionViewSticky : PositionView;
520
- return /* @__PURE__ */ React3.createElement(
521
- PositionComponent,
522
- {
523
- animatedScrollY: isSticky ? animatedScrollY : void 0,
524
- horizontal,
525
- id,
526
- index,
527
- key: recycleItems ? void 0 : itemKey,
528
- onLayout,
529
- refView: ref,
530
- stickyOffset: isSticky ? stickyOffset : void 0,
531
- style
532
- },
533
- /* @__PURE__ */ React3.createElement(ContextContainer.Provider, { value: contextValue }, renderedItem, renderedItemInfo && ItemSeparatorComponent && /* @__PURE__ */ React3.createElement(Separator, { ItemSeparatorComponent, leadingItem: renderedItemInfo.item }))
534
- );
535
- });
536
-
537
- // src/platform/Platform.ts
538
- var Platform = {
539
- // Widen the type to avoid unreachable-branch lints in cross-platform code that compares against other OSes
540
- OS: "web"
541
- };
542
-
543
- // src/utils/reordering.ts
544
- var mapFn = (element) => {
545
- const indexStr = element.getAttribute("index");
546
- return [element, indexStr === null ? null : parseInt(indexStr)];
547
- };
548
- function sortDOMElements(container) {
549
- const elements = Array.from(container.children);
550
- if (elements.length <= 1) return elements;
551
- const items = elements.map(mapFn);
552
- items.sort((a, b) => {
553
- const aKey = a[1];
554
- const bKey = b[1];
555
- if (aKey === null) {
556
- return 1;
557
- }
558
- if (bKey === null) {
559
- return -1;
560
- }
561
- return aKey - bKey;
562
- });
563
- const targetPositions = /* @__PURE__ */ new Map();
564
- items.forEach((item, index) => {
565
- targetPositions.set(item[0], index);
566
- });
567
- const currentPositions = elements.map((el) => targetPositions.get(el));
568
- const lis = findLIS(currentPositions);
569
- const stableIndices = new Set(lis);
570
- for (let targetPos = 0; targetPos < items.length; targetPos++) {
571
- const element = items[targetPos][0];
572
- const currentPos = elements.indexOf(element);
573
- if (!stableIndices.has(currentPos)) {
574
- let nextStableElement = null;
575
- for (let i = targetPos + 1; i < items.length; i++) {
576
- const nextEl = items[i][0];
577
- const nextCurrentPos = elements.indexOf(nextEl);
578
- if (stableIndices.has(nextCurrentPos)) {
579
- nextStableElement = nextEl;
580
- break;
581
- }
582
- }
583
- if (nextStableElement) {
584
- container.insertBefore(element, nextStableElement);
585
- } else {
586
- container.appendChild(element);
587
- }
588
- }
589
- }
590
- }
591
- function findLIS(arr) {
592
- const n = arr.length;
593
- const tails = [];
594
- const predecessors = new Array(n).fill(-1);
595
- const indices = [];
596
- for (let i = 0; i < n; i++) {
597
- const num = arr[i];
598
- let left = 0, right = tails.length;
599
- while (left < right) {
600
- const mid = Math.floor((left + right) / 2);
601
- if (arr[indices[mid]] < num) {
602
- left = mid + 1;
603
- } else {
604
- right = mid;
605
- }
606
- }
607
- if (left === tails.length) {
608
- tails.push(num);
609
- indices.push(i);
610
- } else {
611
- tails[left] = num;
612
- indices[left] = i;
613
- }
614
- if (left > 0) {
615
- predecessors[i] = indices[left - 1];
616
- }
617
- }
618
- const result = [];
619
- let k = indices[indices.length - 1];
620
- while (k !== -1) {
621
- result.unshift(k);
622
- k = predecessors[k];
623
- }
624
- return result;
625
- }
626
-
627
- // src/hooks/useDOMOrder.ts
628
- function useDOMOrder(ref) {
629
- const ctx = useStateContext();
630
- const debounceRef = useRef(void 0);
631
- useEffect(() => {
632
- const unsubscribe = listen$(ctx, "lastPositionUpdate", () => {
633
- if (debounceRef.current !== void 0) {
634
- clearTimeout(debounceRef.current);
635
- }
636
- debounceRef.current = setTimeout(() => {
637
- const parent = ref.current;
638
- if (parent) {
639
- sortDOMElements(parent);
640
- }
641
- debounceRef.current = void 0;
642
- }, 500);
643
- });
644
- return () => {
645
- unsubscribe();
646
- if (debounceRef.current !== void 0) {
647
- clearTimeout(debounceRef.current);
648
- }
649
- };
650
- }, [ctx]);
651
- }
652
-
653
- // src/components/Containers.tsx
654
- var ContainersInner = typedMemo(function ContainersInner2({ horizontal, numColumns, children }) {
655
- const ref = useRef(null);
656
- const ctx = useStateContext();
657
- const columnWrapperStyle = ctx.columnWrapperStyle;
658
- const [totalSize, otherAxisSize] = useArr$(["totalSize", "otherAxisSize"]);
659
- useDOMOrder(ref);
660
- const style = horizontal ? { minHeight: otherAxisSize, position: "relative", width: totalSize } : { height: totalSize, minWidth: otherAxisSize, position: "relative" };
661
- if (columnWrapperStyle && numColumns > 1) {
662
- const { columnGap, rowGap, gap } = columnWrapperStyle;
663
- const gapX = columnGap || gap || 0;
664
- const gapY = rowGap || gap || 0;
665
- if (horizontal) {
666
- if (gapY) {
667
- style.marginTop = style.marginBottom = -gapY / 2;
668
- }
669
- if (gapX) {
670
- style.marginRight = -gapX;
671
- }
672
- } else {
673
- if (gapX) {
674
- style.marginLeft = style.marginRight = -gapX;
675
- }
676
- if (gapY) {
677
- style.marginBottom = -gapY;
678
- }
679
- }
680
- }
681
- return /* @__PURE__ */ React3.createElement("div", { ref, style }, children);
682
- });
683
- var Containers = typedMemo(function Containers2({
684
- horizontal,
685
- recycleItems,
686
- ItemSeparatorComponent,
687
- waitForInitialLayout,
688
- updateItemSize: updateItemSize2,
689
- getRenderedItem: getRenderedItem2
690
- }) {
691
- const [numContainers, numColumns] = useArr$(["numContainersPooled", "numColumns"]);
692
- const containers = [];
693
- for (let i = 0; i < numContainers; i++) {
694
- containers.push(
695
- /* @__PURE__ */ React3.createElement(
696
- Container,
697
- {
698
- getRenderedItem: getRenderedItem2,
699
- horizontal,
700
- ItemSeparatorComponent,
701
- id: i,
702
- key: i,
703
- recycleItems,
704
- updateItemSize: updateItemSize2
705
- }
706
- )
707
- );
708
- }
709
- return /* @__PURE__ */ React3.createElement(ContainersInner, { horizontal, numColumns, waitForInitialLayout }, containers);
710
- });
711
- function DevNumbers() {
712
- return IS_DEV && // biome-ignore lint/nursery/noShadow: const function name shadowing is intentional
713
- React3.memo(function DevNumbers2() {
714
- return Array.from({ length: 100 }).map((_, index) => /* @__PURE__ */ React3.createElement(
715
- "div",
716
- {
717
- key: index,
718
- style: {
719
- height: 100,
720
- pointerEvents: "none",
721
- position: "absolute",
722
- top: index * 100,
723
- width: "100%"
724
- }
725
- },
726
- /* @__PURE__ */ React3.createElement("div", { style: { color: "red" } }, index * 100)
727
- ));
728
- });
729
- }
730
-
731
- // src/platform/StyleSheet.tsx
732
- function flattenStyles(styles) {
733
- if (isArray(styles)) {
734
- return Object.assign({}, ...styles.filter(Boolean));
735
- }
736
- return styles;
737
- }
738
- var StyleSheet = {
739
- create: (styles) => styles,
740
- flatten: (style) => flattenStyles(style)
741
- };
742
-
743
- // src/components/ListComponentScrollView.tsx
744
- var ListComponentScrollView = forwardRef(function ListComponentScrollView2({
745
- children,
746
- style,
747
- contentContainerStyle,
748
- horizontal = false,
749
- contentOffset,
750
- maintainVisibleContentPosition,
751
- onScroll: onScroll2,
752
- onMomentumScrollEnd,
753
- showsHorizontalScrollIndicator = true,
754
- showsVerticalScrollIndicator = true,
755
- refreshControl,
756
- onLayout,
757
- ...props
758
- }, ref) {
759
- const scrollRef = useRef(null);
760
- const contentRef = useRef(null);
761
- useImperativeHandle(ref, () => {
762
- const api = {
763
- getBoundingClientRect: () => {
764
- var _a3;
765
- return (_a3 = scrollRef.current) == null ? void 0 : _a3.getBoundingClientRect();
766
- },
767
- getScrollableNode: () => scrollRef.current,
768
- getScrollResponder: () => scrollRef.current,
769
- scrollBy: (x, y) => {
770
- const el = scrollRef.current;
771
- if (!el) return;
772
- el.scrollBy(x, y);
773
- },
774
- scrollTo: (options) => {
775
- const el = scrollRef.current;
776
- if (!el) return;
777
- const { x = 0, y = 0, animated = true } = options;
778
- el.scrollTo({ behavior: animated ? "smooth" : "auto", left: x, top: y });
779
- },
780
- scrollToEnd: (options = {}) => {
781
- const el = scrollRef.current;
782
- if (!el) return;
783
- const { animated = true } = options;
784
- if (horizontal) {
785
- el.scrollTo({ behavior: animated ? "smooth" : "auto", left: el.scrollWidth });
786
- } else {
787
- el.scrollTo({ behavior: animated ? "smooth" : "auto", top: el.scrollHeight });
788
- }
789
- },
790
- scrollToOffset: (params) => {
791
- const el = scrollRef.current;
792
- if (!el) return;
793
- const { offset, animated = true } = params;
794
- if (horizontal) {
795
- el.scrollTo({ behavior: animated ? "smooth" : "auto", left: offset });
796
- } else {
797
- el.scrollTo({ behavior: animated ? "smooth" : "auto", top: offset });
798
- }
799
- }
800
- };
801
- return api;
802
- }, [horizontal]);
803
- const handleScroll = useCallback(
804
- (event) => {
805
- if (!onScroll2 || !(event == null ? void 0 : event.target)) {
806
- return;
807
- }
808
- const target = event.target;
809
- const scrollEvent = {
810
- nativeEvent: {
811
- contentOffset: {
812
- x: target.scrollLeft,
813
- y: target.scrollTop
814
- },
815
- contentSize: {
816
- height: target.scrollHeight,
817
- width: target.scrollWidth
818
- },
819
- layoutMeasurement: {
820
- height: target.clientHeight,
821
- width: target.clientWidth
822
- }
823
- }
824
- };
825
- onScroll2(scrollEvent);
826
- },
827
- [onScroll2, onMomentumScrollEnd]
828
- );
829
- useLayoutEffect(() => {
830
- const element = scrollRef.current;
831
- if (!element) return;
832
- element.addEventListener("scroll", handleScroll);
833
- return () => {
834
- element.removeEventListener("scroll", handleScroll);
835
- };
836
- }, [handleScroll]);
837
- useEffect(() => {
838
- const doScroll = () => {
839
- if (contentOffset && scrollRef.current) {
840
- scrollRef.current.scrollLeft = contentOffset.x || 0;
841
- scrollRef.current.scrollTop = contentOffset.y || 0;
842
- }
843
- };
844
- doScroll();
845
- requestAnimationFrame(doScroll);
846
- }, [contentOffset == null ? void 0 : contentOffset.x, contentOffset == null ? void 0 : contentOffset.y]);
847
- useLayoutEffect(() => {
848
- if (!onLayout || !scrollRef.current) return;
849
- const element = scrollRef.current;
850
- const fireLayout = () => {
851
- const rect = element.getBoundingClientRect();
852
- onLayout({
853
- nativeEvent: {
854
- layout: {
855
- height: rect.height,
856
- width: rect.width,
857
- x: rect.left,
858
- y: rect.top
859
- }
860
- }
861
- });
862
- };
863
- fireLayout();
864
- const resizeObserver = new ResizeObserver(() => {
865
- fireLayout();
866
- });
867
- resizeObserver.observe(element);
868
- return () => resizeObserver.disconnect();
869
- }, [onLayout]);
870
- const scrollViewStyle = {
871
- overflow: "auto",
872
- overflowX: horizontal ? "auto" : showsHorizontalScrollIndicator ? "auto" : "hidden",
873
- overflowY: horizontal ? showsVerticalScrollIndicator ? "auto" : "hidden" : "auto",
874
- position: "relative",
875
- // Ensure proper positioning context
876
- WebkitOverflowScrolling: "touch",
877
- // iOS momentum scrolling
878
- ...StyleSheet.flatten(style)
879
- };
880
- const contentStyle = {
881
- display: horizontal ? "flex" : "block",
882
- flexDirection: horizontal ? "row" : void 0,
883
- minHeight: horizontal ? void 0 : "100%",
884
- minWidth: horizontal ? "100%" : void 0,
885
- ...StyleSheet.flatten(contentContainerStyle)
886
- };
887
- return /* @__PURE__ */ React3.createElement("div", { ref: scrollRef, style: scrollViewStyle, ...props }, refreshControl, /* @__PURE__ */ React3.createElement("div", { ref: contentRef, style: contentStyle }, children));
888
- });
889
- function Padding() {
890
- const [paddingTop] = useArr$(["alignItemsPaddingTop"]);
891
- return /* @__PURE__ */ React3.createElement("div", { style: { paddingTop } });
892
- }
893
- function PaddingDevMode() {
894
- const [paddingTop] = useArr$(["alignItemsPaddingTop"]);
895
- return /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement("div", { style: { paddingTop } }), /* @__PURE__ */ React3.createElement(
896
- "div",
897
- {
898
- style: {
899
- backgroundColor: "green",
900
- height: paddingTop,
901
- left: 0,
902
- position: "absolute",
903
- right: 0,
904
- top: 0
905
- }
906
- }
907
- ));
908
- }
909
- function useValueListener$(key, callback) {
910
- const ctx = useStateContext();
911
- useLayoutEffect(() => {
912
- const unsubscribe = listen$(ctx, key, (value) => {
913
- callback(value);
914
- });
915
- return unsubscribe;
916
- }, [callback, ctx, key]);
917
- }
918
-
919
- // src/components/ScrollAdjust.tsx
920
- function ScrollAdjust() {
921
- const ctx = useStateContext();
922
- const lastScrollOffsetRef = React3.useRef(0);
923
- const callback = React3.useCallback(() => {
924
- var _a3;
925
- const scrollAdjust = peek$(ctx, "scrollAdjust");
926
- const scrollAdjustUserOffset = peek$(ctx, "scrollAdjustUserOffset");
927
- const scrollOffset = (scrollAdjust || 0) + (scrollAdjustUserOffset || 0);
928
- const scrollView = (_a3 = ctx.internalState) == null ? void 0 : _a3.refScroller.current;
929
- if (scrollView && scrollOffset !== lastScrollOffsetRef.current) {
930
- const scrollDelta = scrollOffset - lastScrollOffsetRef.current;
931
- if (scrollDelta !== 0) {
932
- const el = scrollView.getScrollableNode();
933
- const prevScroll = el.scrollTop;
934
- const nextScroll = prevScroll + scrollDelta;
935
- const totalSize = el.scrollHeight;
936
- if (scrollDelta > 0 && !ctx.internalState.adjustingFromInitialMount && totalSize < nextScroll + el.clientHeight) {
937
- const child = el.firstElementChild;
938
- const prevPaddingBottom = child.style.paddingBottom;
939
- const pad = (nextScroll + el.clientHeight - totalSize) * 2;
940
- child.style.paddingBottom = `${pad}px`;
941
- void el.offsetHeight;
942
- scrollView.scrollBy(0, scrollDelta);
943
- requestAnimationFrame(() => {
944
- child.style.paddingBottom = prevPaddingBottom;
945
- });
946
- } else {
947
- scrollView.scrollBy(0, scrollDelta);
948
- }
949
- if (IS_DEV) {
950
- console.log("ScrollAdjust (web scrollBy)", scrollDelta, "total offset:", scrollOffset);
951
- }
952
- }
953
- lastScrollOffsetRef.current = scrollOffset;
954
- }
955
- }, [ctx]);
956
- useValueListener$("scrollAdjust", callback);
957
- useValueListener$("scrollAdjustUserOffset", callback);
958
- return null;
959
- }
960
- function SnapWrapper({ ScrollComponent, ...props }) {
961
- const [snapToOffsets] = useArr$(["snapToOffsets"]);
962
- return /* @__PURE__ */ React3.createElement(ScrollComponent, { ...props, snapToOffsets });
963
- }
964
- var LayoutView = ({ onLayoutChange, refView, children, ...rest }) => {
965
- const ref = refView != null ? refView : useRef();
966
- useOnLayoutSync({ onLayoutChange, ref });
967
- return /* @__PURE__ */ React3.createElement("div", { ...rest, ref }, children);
968
- };
969
-
970
- // src/components/ListComponent.tsx
971
- var getComponent = (Component) => {
972
- if (React3.isValidElement(Component)) {
973
- return Component;
974
- }
975
- if (Component) {
976
- return /* @__PURE__ */ React3.createElement(Component, null);
977
- }
978
- return null;
979
- };
980
- var ListComponent = typedMemo(function ListComponent2({
981
- canRender,
982
- style,
983
- contentContainerStyle,
984
- horizontal,
985
- initialContentOffset,
986
- recycleItems,
987
- ItemSeparatorComponent,
988
- alignItemsAtEnd,
989
- waitForInitialLayout,
990
- onScroll: onScroll2,
991
- onLayout,
992
- ListHeaderComponent,
993
- ListHeaderComponentStyle,
994
- ListFooterComponent,
995
- ListFooterComponentStyle,
996
- ListEmptyComponent,
997
- getRenderedItem: getRenderedItem2,
998
- updateItemSize: updateItemSize2,
999
- refScrollView,
1000
- maintainVisibleContentPosition,
1001
- renderScrollComponent,
1002
- scrollAdjustHandler,
1003
- onLayoutHeader,
1004
- snapToIndices,
1005
- stickyHeaderIndices,
1006
- ...rest
1007
- }) {
1008
- const ctx = useStateContext();
1009
- const ScrollComponent = renderScrollComponent ? useMemo(
1010
- () => React3.forwardRef((props, ref) => renderScrollComponent({ ...props, ref })),
1011
- [renderScrollComponent]
1012
- ) : ListComponentScrollView;
1013
- const SnapOrScroll = snapToIndices ? SnapWrapper : ScrollComponent;
1014
- return /* @__PURE__ */ React3.createElement(
1015
- SnapOrScroll,
1016
- {
1017
- ...rest,
1018
- contentContainerStyle: [
1019
- contentContainerStyle,
1020
- horizontal ? {
1021
- height: "100%"
1022
- } : {}
1023
- ],
1024
- contentOffset: initialContentOffset ? horizontal ? { x: initialContentOffset, y: 0 } : { x: 0, y: initialContentOffset } : void 0,
1025
- horizontal,
1026
- maintainVisibleContentPosition: maintainVisibleContentPosition ? { minIndexForVisible: 0 } : void 0,
1027
- onLayout,
1028
- onScroll: onScroll2,
1029
- ref: refScrollView,
1030
- ScrollComponent: snapToIndices ? ScrollComponent : void 0,
1031
- style
1032
- },
1033
- /* @__PURE__ */ React3.createElement(ScrollAdjust, null),
1034
- ENABLE_DEVMODE ? /* @__PURE__ */ React3.createElement(PaddingDevMode, null) : /* @__PURE__ */ React3.createElement(Padding, null),
1035
- ListHeaderComponent && /* @__PURE__ */ React3.createElement(LayoutView, { onLayoutChange: onLayoutHeader, style: ListHeaderComponentStyle }, getComponent(ListHeaderComponent)),
1036
- ListEmptyComponent && getComponent(ListEmptyComponent),
1037
- canRender && !ListEmptyComponent && /* @__PURE__ */ React3.createElement(
1038
- Containers,
1039
- {
1040
- getRenderedItem: getRenderedItem2,
1041
- horizontal,
1042
- ItemSeparatorComponent,
1043
- recycleItems,
1044
- updateItemSize: updateItemSize2,
1045
- waitForInitialLayout
1046
- }
1047
- ),
1048
- ListFooterComponent && /* @__PURE__ */ React3.createElement(
1049
- LayoutView,
1050
- {
1051
- onLayoutChange: (layout) => {
1052
- const size = layout[horizontal ? "width" : "height"];
1053
- set$(ctx, "footerSize", size);
1054
- },
1055
- style: ListFooterComponentStyle
1056
- },
1057
- getComponent(ListFooterComponent)
1058
- ),
1059
- IS_DEV && ENABLE_DEVMODE && /* @__PURE__ */ React3.createElement(DevNumbers, null)
1060
- );
1061
- });
1062
-
1063
- // src/utils/getId.ts
1064
- function getId(state, index) {
1065
- const { data, keyExtractor } = state.props;
1066
- if (!data) {
1067
- return "";
1068
- }
1069
- const ret = index < data.length ? keyExtractor ? keyExtractor(data[index], index) : index : null;
1070
- const id = ret;
1071
- state.idCache[index] = id;
1072
- return id;
1073
- }
1074
-
1075
- // src/core/calculateOffsetForIndex.ts
1076
- function calculateOffsetForIndex(ctx, state, index) {
1077
- let position = 0;
1078
- if (index !== void 0) {
1079
- position = (state == null ? void 0 : state.positions.get(getId(state, index))) || 0;
1080
- const paddingTop = peek$(ctx, "stylePaddingTop");
1081
- if (paddingTop) {
1082
- position += paddingTop;
1083
- }
1084
- const headerSize = peek$(ctx, "headerSize");
1085
- if (headerSize) {
1086
- position += headerSize;
1087
- }
1088
- }
1089
- return position;
1090
- }
1091
-
1092
- // src/utils/setPaddingTop.ts
1093
- function setPaddingTop(ctx, state, { stylePaddingTop, alignItemsPaddingTop }) {
1094
- if (stylePaddingTop !== void 0) {
1095
- const prevStylePaddingTop = peek$(ctx, "stylePaddingTop") || 0;
1096
- if (stylePaddingTop < prevStylePaddingTop) {
1097
- let prevTotalSize = peek$(ctx, "totalSize") || 0;
1098
- set$(ctx, "totalSize", prevTotalSize + prevStylePaddingTop);
1099
- state.timeoutSetPaddingTop = setTimeout(() => {
1100
- prevTotalSize = peek$(ctx, "totalSize") || 0;
1101
- set$(ctx, "totalSize", prevTotalSize - prevStylePaddingTop);
1102
- }, 16);
1103
- }
1104
- set$(ctx, "stylePaddingTop", stylePaddingTop);
1105
- }
1106
- if (alignItemsPaddingTop !== void 0) {
1107
- set$(ctx, "alignItemsPaddingTop", alignItemsPaddingTop);
1108
- }
1109
- }
1110
-
1111
- // src/utils/updateAlignItemsPaddingTop.ts
1112
- function updateAlignItemsPaddingTop(ctx, state) {
1113
- const {
1114
- scrollLength,
1115
- props: { alignItemsAtEnd, data }
1116
- } = state;
1117
- if (alignItemsAtEnd) {
1118
- let alignItemsPaddingTop = 0;
1119
- if ((data == null ? void 0 : data.length) > 0) {
1120
- const contentSize = getContentSize(ctx);
1121
- alignItemsPaddingTop = Math.max(0, Math.floor(scrollLength - contentSize));
1122
- }
1123
- setPaddingTop(ctx, state, { alignItemsPaddingTop });
1124
- }
1125
- }
1126
-
1127
- // src/core/addTotalSize.ts
1128
- function addTotalSize(ctx, state, key, add) {
1129
- const { alignItemsAtEnd } = state.props;
1130
- const prevTotalSize = state.totalSize;
1131
- let totalSize = state.totalSize;
1132
- if (key === null) {
1133
- totalSize = add;
1134
- if (state.timeoutSetPaddingTop) {
1135
- clearTimeout(state.timeoutSetPaddingTop);
1136
- state.timeoutSetPaddingTop = void 0;
1137
- }
1138
- } else {
1139
- totalSize += add;
1140
- }
1141
- if (prevTotalSize !== totalSize) {
1142
- {
1143
- state.pendingTotalSize = void 0;
1144
- state.totalSize = totalSize;
1145
- set$(ctx, "totalSize", totalSize);
1146
- if (alignItemsAtEnd) {
1147
- updateAlignItemsPaddingTop(ctx, state);
1148
- }
1149
- }
1150
- }
1151
- }
1152
-
1153
- // src/core/setSize.ts
1154
- function setSize(ctx, state, itemKey, size) {
1155
- const { sizes } = state;
1156
- const previousSize = sizes.get(itemKey);
1157
- const diff = previousSize !== void 0 ? size - previousSize : size;
1158
- if (diff !== 0) {
1159
- addTotalSize(ctx, state, itemKey, diff);
1160
- }
1161
- sizes.set(itemKey, size);
1162
- }
1163
-
1164
- // src/utils/getItemSize.ts
1165
- function getItemSize(ctx, state, key, index, data, useAverageSize, preferCachedSize) {
1166
- var _a3, _b;
1167
- const {
1168
- sizesKnown,
1169
- sizes,
1170
- averageSizes,
1171
- props: { estimatedItemSize, getEstimatedItemSize, getFixedItemSize, getItemType }
1172
- } = state;
1173
- const sizeKnown = sizesKnown.get(key);
1174
- if (sizeKnown !== void 0) {
1175
- return sizeKnown;
1176
- }
1177
- let size;
1178
- const itemType = getItemType ? (_a3 = getItemType(data, index)) != null ? _a3 : "" : "";
1179
- const scrollingTo = peek$(ctx, "scrollingTo");
1180
- if (preferCachedSize) {
1181
- const cachedSize = sizes.get(key);
1182
- if (cachedSize !== void 0) {
1183
- return cachedSize;
1184
- }
1185
- }
1186
- if (getFixedItemSize) {
1187
- size = getFixedItemSize(index, data, itemType);
1188
- if (size !== void 0) {
1189
- sizesKnown.set(key, size);
1190
- }
1191
- }
1192
- if (size === void 0 && useAverageSize && sizeKnown === void 0 && !scrollingTo) {
1193
- const averageSizeForType = (_b = averageSizes[itemType]) == null ? void 0 : _b.avg;
1194
- if (averageSizeForType !== void 0) {
1195
- size = roundSize(averageSizeForType);
1196
- }
1197
- }
1198
- if (size === void 0) {
1199
- size = sizes.get(key);
1200
- if (size !== void 0) {
1201
- return size;
1202
- }
1203
- }
1204
- if (size === void 0) {
1205
- size = getEstimatedItemSize ? getEstimatedItemSize(index, data, itemType) : estimatedItemSize;
1206
- }
1207
- setSize(ctx, state, key, size);
1208
- return size;
1209
- }
1210
-
1211
- // src/core/calculateOffsetWithOffsetPosition.ts
1212
- function calculateOffsetWithOffsetPosition(ctx, state, offsetParam, params) {
1213
- const { index, viewOffset, viewPosition } = params;
1214
- let offset = offsetParam;
1215
- if (viewOffset) {
1216
- offset -= viewOffset;
1217
- }
1218
- if (viewPosition !== void 0 && index !== void 0) {
1219
- offset -= viewPosition * (state.scrollLength - getItemSize(ctx, state, getId(state, index), index, state.props.data[index]));
1220
- }
1221
- return offset;
1222
- }
1223
-
1224
- // src/core/finishScrollTo.ts
1225
- function finishScrollTo(ctx, state) {
1226
- var _a3, _b;
1227
- if (state) {
1228
- state.scrollHistory.length = 0;
1229
- state.initialScroll = void 0;
1230
- state.initialAnchor = void 0;
1231
- set$(ctx, "scrollingTo", void 0);
1232
- if (state.pendingTotalSize !== void 0) {
1233
- addTotalSize(ctx, state, null, state.pendingTotalSize);
1234
- }
1235
- if ((_a3 = state.props) == null ? void 0 : _a3.data) {
1236
- (_b = state.triggerCalculateItemsInView) == null ? void 0 : _b.call(state, { forceFullItemPositions: true });
1237
- }
1238
- }
1239
- }
1240
-
1241
- // src/core/doScrollTo.ts
1242
- var SCROLL_END_IDLE_MS = 80;
1243
- var SCROLL_END_MAX_MS = 1500;
1244
- var SMOOTH_SCROLL_DURATION_MS = 320;
1245
- function doScrollTo(ctx, state, params) {
1246
- const { animated, horizontal, offset } = params;
1247
- const scroller = state.refScroller.current;
1248
- const node = typeof (scroller == null ? void 0 : scroller.getScrollableNode) === "function" ? scroller.getScrollableNode() : scroller;
1249
- if (node) {
1250
- const left = horizontal ? offset : 0;
1251
- const top = horizontal ? 0 : offset;
1252
- node.scrollTo({ behavior: animated ? "smooth" : "auto", left, top });
1253
- if (animated) {
1254
- listenForScrollEnd(ctx, state, node);
1255
- } else {
1256
- state.scroll = offset;
1257
- setTimeout(() => {
1258
- finishScrollTo(ctx, state);
1259
- }, 100);
1260
- }
1261
- }
1262
- }
1263
- function listenForScrollEnd(ctx, state, node) {
1264
- const supportsScrollEnd = "onscrollend" in node;
1265
- let idleTimeout;
1266
- let maxTimeout;
1267
- let settled = false;
1268
- const targetToken = peek$(ctx, "scrollingTo");
1269
- const finish = () => {
1270
- if (settled) return;
1271
- settled = true;
1272
- cleanup();
1273
- if (targetToken === peek$(ctx, "scrollingTo")) {
1274
- finishScrollTo(ctx, state);
1275
- }
1276
- };
1277
- const onScroll2 = () => {
1278
- if (idleTimeout) {
1279
- clearTimeout(idleTimeout);
1280
- }
1281
- idleTimeout = setTimeout(finish, SCROLL_END_IDLE_MS);
1282
- };
1283
- const cleanup = () => {
1284
- if (supportsScrollEnd) {
1285
- node.removeEventListener("scrollend", finish);
1286
- } else {
1287
- node.removeEventListener("scroll", onScroll2);
1288
- }
1289
- if (idleTimeout) {
1290
- clearTimeout(idleTimeout);
1291
- }
1292
- if (maxTimeout) {
1293
- clearTimeout(maxTimeout);
1294
- }
1295
- };
1296
- if (supportsScrollEnd) {
1297
- node.addEventListener("scrollend", finish, { once: true });
1298
- } else {
1299
- node.addEventListener("scroll", onScroll2);
1300
- idleTimeout = setTimeout(finish, SMOOTH_SCROLL_DURATION_MS);
1301
- maxTimeout = setTimeout(finish, SCROLL_END_MAX_MS);
1302
- }
1303
- return cleanup;
1304
- }
1305
-
1306
- // src/core/scrollTo.ts
1307
- function scrollTo(ctx, state, params) {
1308
- const { noScrollingTo, ...scrollTarget } = params;
1309
- const { animated, isInitialScroll, offset: scrollTargetOffset, precomputedWithViewOffset } = scrollTarget;
1310
- const {
1311
- props: { horizontal }
1312
- } = state;
1313
- let offset = precomputedWithViewOffset ? scrollTargetOffset : calculateOffsetWithOffsetPosition(ctx, state, scrollTargetOffset, scrollTarget);
1314
- if (Number.isFinite(state.scrollLength) && Number.isFinite(state.totalSize)) {
1315
- const maxOffset = Math.max(0, getContentSize(ctx) - state.scrollLength);
1316
- offset = Math.min(offset, maxOffset);
1317
- }
1318
- state.scrollHistory.length = 0;
1319
- if (!noScrollingTo) {
1320
- set$(ctx, "scrollingTo", scrollTarget);
1321
- }
1322
- state.scrollPending = offset;
1323
- if (!isInitialScroll || Platform.OS === "android") {
1324
- doScrollTo(ctx, state, { animated, horizontal, isInitialScroll, offset });
1325
- } else {
1326
- state.scroll = offset;
1327
- }
1328
- }
1329
-
1330
- // src/utils/checkThreshold.ts
1331
- var HYSTERESIS_MULTIPLIER = 1.3;
1332
- var checkThreshold = (distance, atThreshold, threshold, wasReached, snapshot, context, onReached, setSnapshot) => {
1333
- const absDistance = Math.abs(distance);
1334
- const within = atThreshold || threshold > 0 && absDistance <= threshold;
1335
- if (wasReached === null) {
1336
- if (!within && distance >= 0) {
1337
- console.log("checkThreshold A: false", distance);
1338
- return false;
1339
- }
1340
- return null;
1341
- }
1342
- const updateSnapshot = () => {
1343
- setSnapshot == null ? void 0 : setSnapshot({
1344
- atThreshold,
1345
- contentSize: context.contentSize,
1346
- dataLength: context.dataLength,
1347
- scrollPosition: context.scrollPosition
1348
- });
1349
- };
1350
- if (!wasReached) {
1351
- if (!within) {
1352
- return false;
1353
- }
1354
- onReached == null ? void 0 : onReached(distance);
1355
- updateSnapshot();
1356
- return true;
1357
- }
1358
- const reset = !atThreshold && threshold > 0 && absDistance >= threshold * HYSTERESIS_MULTIPLIER || !atThreshold && threshold <= 0 && absDistance > 0;
1359
- if (reset) {
1360
- setSnapshot == null ? void 0 : setSnapshot(void 0);
1361
- return false;
1362
- }
1363
- if (within) {
1364
- const changed = !snapshot || snapshot.atThreshold !== atThreshold || snapshot.contentSize !== context.contentSize || snapshot.dataLength !== context.dataLength;
1365
- if (changed) {
1366
- onReached == null ? void 0 : onReached(distance);
1367
- updateSnapshot();
1368
- }
1369
- }
1370
- return true;
1371
- };
1372
-
1373
- // src/utils/checkAtBottom.ts
1374
- function checkAtBottom(ctx, state) {
1375
- var _a3;
1376
- if (!state) {
1377
- return;
1378
- }
1379
- const {
1380
- queuedInitialLayout,
1381
- scrollLength,
1382
- scroll,
1383
- maintainingScrollAtEnd,
1384
- props: { maintainScrollAtEndThreshold, onEndReachedThreshold }
1385
- } = state;
1386
- const contentSize = getContentSize(ctx);
1387
- if (contentSize > 0 && queuedInitialLayout && !maintainingScrollAtEnd) {
1388
- const distanceFromEnd = contentSize - scroll - scrollLength;
1389
- const isContentLess = contentSize < scrollLength;
1390
- state.isAtEnd = isContentLess || distanceFromEnd < scrollLength * maintainScrollAtEndThreshold;
1391
- state.isEndReached = checkThreshold(
1392
- distanceFromEnd,
1393
- isContentLess,
1394
- onEndReachedThreshold * scrollLength,
1395
- state.isEndReached,
1396
- state.endReachedSnapshot,
1397
- {
1398
- contentSize,
1399
- dataLength: (_a3 = state.props.data) == null ? void 0 : _a3.length,
1400
- scrollPosition: scroll
1401
- },
1402
- (distance) => {
1403
- var _a4, _b;
1404
- return (_b = (_a4 = state.props).onEndReached) == null ? void 0 : _b.call(_a4, { distanceFromEnd: distance });
1405
- },
1406
- (snapshot) => {
1407
- state.endReachedSnapshot = snapshot;
1408
- }
1409
- );
1410
- }
1411
- }
1412
-
1413
- // src/utils/checkAtTop.ts
1414
- function checkAtTop(state) {
1415
- var _a3;
1416
- if (!state) {
1417
- return;
1418
- }
1419
- const {
1420
- scrollLength,
1421
- scroll,
1422
- props: { onStartReachedThreshold }
1423
- } = state;
1424
- const distanceFromTop = scroll;
1425
- state.isAtStart = distanceFromTop <= 0;
1426
- state.isStartReached = checkThreshold(
1427
- distanceFromTop,
1428
- false,
1429
- onStartReachedThreshold * scrollLength,
1430
- state.isStartReached,
1431
- state.startReachedSnapshot,
1432
- {
1433
- contentSize: state.totalSize,
1434
- dataLength: (_a3 = state.props.data) == null ? void 0 : _a3.length,
1435
- scrollPosition: scroll
1436
- },
1437
- (distance) => {
1438
- var _a4, _b;
1439
- return (_b = (_a4 = state.props).onStartReached) == null ? void 0 : _b.call(_a4, { distanceFromStart: distance });
1440
- },
1441
- (snapshot) => {
1442
- state.startReachedSnapshot = snapshot;
1443
- }
1444
- );
1445
- }
1446
-
1447
- // src/core/updateScroll.ts
1448
- function updateScroll(ctx, state, newScroll, forceUpdate) {
1449
- var _a3;
1450
- const scrollingTo = peek$(ctx, "scrollingTo");
1451
- state.hasScrolled = true;
1452
- state.lastBatchingAction = Date.now();
1453
- const currentTime = Date.now();
1454
- const adjust = state.scrollAdjustHandler.getAdjust();
1455
- const lastHistoryAdjust = state.lastScrollAdjustForHistory;
1456
- const adjustChanged = lastHistoryAdjust !== void 0 && Math.abs(adjust - lastHistoryAdjust) > 0.1;
1457
- if (adjustChanged) {
1458
- state.scrollHistory.length = 0;
1459
- }
1460
- state.lastScrollAdjustForHistory = adjust;
1461
- if (scrollingTo === void 0 && !(state.scrollHistory.length === 0 && newScroll === state.scroll)) {
1462
- if (!adjustChanged) {
1463
- state.scrollHistory.push({ scroll: newScroll, time: currentTime });
1464
- }
1465
- }
1466
- if (state.scrollHistory.length > 5) {
1467
- state.scrollHistory.shift();
1468
- }
1469
- state.scrollPrev = state.scroll;
1470
- state.scrollPrevTime = state.scrollTime;
1471
- state.scroll = newScroll;
1472
- state.scrollTime = currentTime;
1473
- const ignoreScrollFromMVCP = state.ignoreScrollFromMVCP;
1474
- if (ignoreScrollFromMVCP && !scrollingTo) {
1475
- const { lt, gt } = ignoreScrollFromMVCP;
1476
- if (lt && newScroll < lt || gt && newScroll > gt) {
1477
- state.ignoreScrollFromMVCPIgnored = true;
1478
- return;
1479
- }
1480
- }
1481
- const lastCalculated = state.scrollLastCalculate;
1482
- const shouldUpdate = state.dataChangeNeedsScrollUpdate || state.scrollLastCalculate === void 0 || lastCalculated === void 0 || Math.abs(state.scroll - lastCalculated) > 2;
1483
- if (shouldUpdate) {
1484
- state.scrollLastCalculate = state.scroll;
1485
- state.ignoreScrollFromMVCPIgnored = false;
1486
- (_a3 = state.triggerCalculateItemsInView) == null ? void 0 : _a3.call(state, { doMVCP: scrollingTo !== void 0 });
1487
- checkAtBottom(ctx, state);
1488
- checkAtTop(state);
1489
- state.dataChangeNeedsScrollUpdate = false;
1490
- }
1491
- }
1492
-
1493
- // src/utils/requestAdjust.ts
1494
- function requestAdjust(ctx, state, positionDiff, dataChanged) {
1495
- if (Math.abs(positionDiff) > 0.1) {
1496
- const doit = () => {
1497
- {
1498
- state.scrollAdjustHandler.requestAdjust(positionDiff);
1499
- if (state.adjustingFromInitialMount) {
1500
- state.adjustingFromInitialMount--;
1501
- }
1502
- }
1503
- };
1504
- state.scroll += positionDiff;
1505
- state.scrollForNextCalculateItemsInView = void 0;
1506
- const didLayout = peek$(ctx, "containersDidLayout");
1507
- if (didLayout) {
1508
- doit();
1509
- } else {
1510
- state.adjustingFromInitialMount = (state.adjustingFromInitialMount || 0) + 1;
1511
- requestAnimationFrame(doit);
1512
- }
1513
- }
1514
- }
1515
-
1516
- // src/core/ensureInitialAnchor.ts
1517
- var INITIAL_ANCHOR_TOLERANCE = 0.5;
1518
- var INITIAL_ANCHOR_MAX_ATTEMPTS = 4;
1519
- var INITIAL_ANCHOR_SETTLED_TICKS = 2;
1520
- function ensureInitialAnchor(ctx, state) {
1521
- var _a3, _b, _c, _d, _e;
1522
- const anchor = state.initialAnchor;
1523
- const item = state.props.data[anchor.index];
1524
- const containersDidLayout = peek$(ctx, "containersDidLayout");
1525
- if (!containersDidLayout) {
1526
- return;
1527
- }
1528
- const id = getId(state, anchor.index);
1529
- if (state.positions.get(id) === void 0) {
1530
- return;
1531
- }
1532
- const size = getItemSize(ctx, state, id, anchor.index, item, true, true);
1533
- if (size === void 0) {
1534
- return;
1535
- }
1536
- const availableSpace = Math.max(0, state.scrollLength - size);
1537
- const desiredOffset = calculateOffsetForIndex(ctx, state, anchor.index) - ((_a3 = anchor.viewOffset) != null ? _a3 : 0) - ((_b = anchor.viewPosition) != null ? _b : 0) * availableSpace;
1538
- const contentSize = getContentSize(ctx);
1539
- const maxOffset = Math.max(0, contentSize - state.scrollLength);
1540
- const clampedDesiredOffset = Math.max(0, Math.min(desiredOffset, maxOffset));
1541
- const delta = clampedDesiredOffset - state.scroll;
1542
- if (Math.abs(delta) <= INITIAL_ANCHOR_TOLERANCE) {
1543
- const settledTicks = ((_c = anchor.settledTicks) != null ? _c : 0) + 1;
1544
- if (settledTicks >= INITIAL_ANCHOR_SETTLED_TICKS) {
1545
- state.initialAnchor = void 0;
1546
- } else {
1547
- anchor.settledTicks = settledTicks;
1548
- }
1549
- return;
1550
- }
1551
- if (((_d = anchor.attempts) != null ? _d : 0) >= INITIAL_ANCHOR_MAX_ATTEMPTS) {
1552
- state.initialAnchor = void 0;
1553
- return;
1554
- }
1555
- const lastDelta = anchor.lastDelta;
1556
- if (lastDelta !== void 0 && Math.abs(delta) >= Math.abs(lastDelta)) {
1557
- state.initialAnchor = void 0;
1558
- return;
1559
- }
1560
- Object.assign(anchor, {
1561
- attempts: ((_e = anchor.attempts) != null ? _e : 0) + 1,
1562
- lastDelta: delta,
1563
- settledTicks: 0
1564
- });
1565
- requestAdjust(ctx, state, delta);
1566
- }
1567
-
1568
- // src/core/mvcp.ts
1569
- function prepareMVCP(ctx, state, dataChanged) {
1570
- const { idsInView, positions, props } = state;
1571
- const { maintainVisibleContentPosition } = props;
1572
- const scrollingTo = peek$(ctx, "scrollingTo");
1573
- let prevPosition;
1574
- let targetId;
1575
- const idsInViewWithPositions = [];
1576
- const scrollTarget = scrollingTo == null ? void 0 : scrollingTo.index;
1577
- const shouldMVCP = !dataChanged || maintainVisibleContentPosition;
1578
- const indexByKey = state.indexByKey;
1579
- if (shouldMVCP) {
1580
- if (scrollTarget !== void 0) {
1581
- targetId = getId(state, scrollTarget);
1582
- } else if (idsInView.length > 0 && peek$(ctx, "containersDidLayout")) {
1583
- if (dataChanged) {
1584
- for (let i = 0; i < idsInView.length; i++) {
1585
- const id = idsInView[i];
1586
- const index = indexByKey.get(id);
1587
- if (index !== void 0) {
1588
- idsInViewWithPositions.push({ id, position: positions.get(id) });
1589
- }
1590
- }
1591
- } else {
1592
- targetId = idsInView.find((id) => indexByKey.get(id) !== void 0);
1593
- }
1594
- }
1595
- if (targetId !== void 0) {
1596
- prevPosition = positions.get(targetId);
1597
- }
1598
- return () => {
1599
- let positionDiff;
1600
- if (dataChanged && targetId === void 0 && maintainVisibleContentPosition) {
1601
- for (let i = 0; i < idsInViewWithPositions.length; i++) {
1602
- const { id, position } = idsInViewWithPositions[i];
1603
- const newPosition = positions.get(id);
1604
- if (newPosition !== void 0) {
1605
- positionDiff = newPosition - position;
1606
- break;
1607
- }
1608
- }
1609
- }
1610
- if (targetId !== void 0 && prevPosition !== void 0) {
1611
- const newPosition = positions.get(targetId);
1612
- if (newPosition !== void 0) {
1613
- const totalSize = getContentSize(ctx);
1614
- let diff = newPosition - prevPosition;
1615
- if (diff !== 0 && state.scroll + state.scrollLength > totalSize) {
1616
- if (diff > 0) {
1617
- diff = Math.max(0, totalSize - state.scroll - state.scrollLength);
1618
- } else {
1619
- diff = 0;
1620
- }
1621
- }
1622
- positionDiff = diff;
1623
- }
1624
- }
1625
- if (positionDiff !== void 0 && Math.abs(positionDiff) > 0.1) {
1626
- requestAdjust(ctx, state, positionDiff);
1627
- }
1628
- };
1629
- }
1630
- }
1631
-
1632
- // src/core/prepareColumnStartState.ts
1633
- function prepareColumnStartState(ctx, state, startIndex, useAverageSize) {
1634
- var _a3;
1635
- const numColumns = peek$(ctx, "numColumns");
1636
- let rowStartIndex = startIndex;
1637
- const columnAtStart = state.columns.get(state.idCache[startIndex]);
1638
- if (columnAtStart !== 1) {
1639
- rowStartIndex = findRowStartIndex(state, numColumns, startIndex);
1640
- }
1641
- let currentRowTop = 0;
1642
- const curId = state.idCache[rowStartIndex];
1643
- const column = state.columns.get(curId);
1644
- if (rowStartIndex > 0) {
1645
- const prevIndex = rowStartIndex - 1;
1646
- const prevId = state.idCache[prevIndex];
1647
- const prevPosition = (_a3 = state.positions.get(prevId)) != null ? _a3 : 0;
1648
- const prevRowStart = findRowStartIndex(state, numColumns, prevIndex);
1649
- const prevRowHeight = calculateRowMaxSize(ctx, state, prevRowStart, prevIndex, useAverageSize);
1650
- currentRowTop = prevPosition + prevRowHeight;
1651
- }
1652
- return {
1653
- column,
1654
- currentRowTop,
1655
- startIndex: rowStartIndex
1656
- };
1657
- }
1658
- function findRowStartIndex(state, numColumns, index) {
1659
- if (numColumns <= 1) {
1660
- return Math.max(0, index);
1661
- }
1662
- let rowStart = Math.max(0, index);
1663
- while (rowStart > 0) {
1664
- const columnForIndex = state.columns.get(state.idCache[rowStart]);
1665
- if (columnForIndex === 1) {
1666
- break;
1667
- }
1668
- rowStart--;
1669
- }
1670
- return rowStart;
1671
- }
1672
- function calculateRowMaxSize(ctx, state, startIndex, endIndex, useAverageSize) {
1673
- if (endIndex < startIndex) {
1674
- return 0;
1675
- }
1676
- const { data } = state.props;
1677
- if (!data) {
1678
- return 0;
1679
- }
1680
- let maxSize = 0;
1681
- for (let i = startIndex; i <= endIndex; i++) {
1682
- if (i < 0 || i >= data.length) {
1683
- continue;
1684
- }
1685
- const id = state.idCache[i];
1686
- const size = getItemSize(ctx, state, id, i, data[i], useAverageSize);
1687
- if (size > maxSize) {
1688
- maxSize = size;
1689
- }
1690
- }
1691
- return maxSize;
1692
- }
1693
-
1694
- // src/core/updateTotalSize.ts
1695
- function updateTotalSize(ctx, state) {
1696
- const {
1697
- positions,
1698
- props: { data }
1699
- } = state;
1700
- if (data.length === 0) {
1701
- addTotalSize(ctx, state, null, 0);
1702
- } else {
1703
- const lastId = getId(state, data.length - 1);
1704
- if (lastId !== void 0) {
1705
- const lastPosition = positions.get(lastId);
1706
- if (lastPosition !== void 0) {
1707
- const lastSize = getItemSize(ctx, state, lastId, data.length - 1, data[data.length - 1]);
1708
- if (lastSize !== void 0) {
1709
- const totalSize = lastPosition + lastSize;
1710
- addTotalSize(ctx, state, null, totalSize);
1711
- }
1712
- }
1713
- }
1714
- }
1715
- }
1716
-
1717
- // src/utils/getScrollVelocity.ts
1718
- var getScrollVelocity = (state) => {
1719
- const { scrollHistory } = state;
1720
- let velocity = 0;
1721
- if (scrollHistory.length >= 1) {
1722
- const newest = scrollHistory[scrollHistory.length - 1];
1723
- let oldest;
1724
- let start = 0;
1725
- const now = Date.now();
1726
- for (let i = 0; i < scrollHistory.length - 1; i++) {
1727
- const entry = scrollHistory[i];
1728
- const nextEntry = scrollHistory[i + 1];
1729
- if (i > 0) {
1730
- const prevEntry = scrollHistory[i - 1];
1731
- const prevDirection = entry.scroll - prevEntry.scroll;
1732
- const currentDirection = nextEntry.scroll - entry.scroll;
1733
- if (prevDirection > 0 && currentDirection < 0 || prevDirection < 0 && currentDirection > 0) {
1734
- start = i;
1735
- break;
1736
- }
1737
- }
1738
- }
1739
- for (let i = start; i < scrollHistory.length - 1; i++) {
1740
- const entry = scrollHistory[i];
1741
- if (now - entry.time <= 1e3) {
1742
- oldest = entry;
1743
- break;
1744
- }
1745
- }
1746
- if (oldest && oldest !== newest) {
1747
- const scrollDiff = newest.scroll - oldest.scroll;
1748
- const timeDiff = newest.time - oldest.time;
1749
- velocity = timeDiff > 0 ? scrollDiff / timeDiff : 0;
1750
- }
1751
- }
1752
- return velocity;
1753
- };
1754
-
1755
- // src/utils/updateSnapToOffsets.ts
1756
- function updateSnapToOffsets(ctx, state) {
1757
- const {
1758
- positions,
1759
- props: { snapToIndices }
1760
- } = state;
1761
- const snapToOffsets = Array(snapToIndices.length);
1762
- for (let i = 0; i < snapToIndices.length; i++) {
1763
- const idx = snapToIndices[i];
1764
- const key = getId(state, idx);
1765
- snapToOffsets[i] = positions.get(key);
1766
- }
1767
- set$(ctx, "snapToOffsets", snapToOffsets);
1768
- }
1769
-
1770
- // src/core/updateItemPositions.ts
1771
- function updateItemPositions(ctx, state, dataChanged, { startIndex, scrollBottomBuffered, forceFullUpdate = false, doMVCP } = {
1772
- doMVCP: false,
1773
- forceFullUpdate: false,
1774
- scrollBottomBuffered: -1,
1775
- startIndex: 0
1776
- }) {
1777
- var _a3, _b, _c, _d, _e;
1778
- const {
1779
- columns,
1780
- indexByKey,
1781
- positions,
1782
- idCache,
1783
- sizesKnown,
1784
- props: { getEstimatedItemSize, snapToIndices, enableAverages }
1785
- } = state;
1786
- const data = state.props.data;
1787
- const dataLength = data.length;
1788
- const numColumns = peek$(ctx, "numColumns");
1789
- const scrollingTo = peek$(ctx, "scrollingTo");
1790
- const hasColumns = numColumns > 1;
1791
- const indexByKeyForChecking = IS_DEV ? /* @__PURE__ */ new Map() : void 0;
1792
- const shouldOptimize = !forceFullUpdate && !dataChanged && Math.abs(getScrollVelocity(state)) > 0;
1793
- const maxVisibleArea = scrollBottomBuffered + 1e3;
1794
- const useAverageSize = enableAverages && !getEstimatedItemSize;
1795
- const preferCachedSize = !doMVCP || dataChanged || state.scrollAdjustHandler.getAdjust() !== 0 || ((_a3 = peek$(ctx, "scrollAdjustPending")) != null ? _a3 : 0) !== 0;
1796
- let currentRowTop = 0;
1797
- let column = 1;
1798
- let maxSizeInRow = 0;
1799
- if (startIndex > 0) {
1800
- if (hasColumns) {
1801
- const { startIndex: processedStartIndex, currentRowTop: initialRowTop } = prepareColumnStartState(
1802
- ctx,
1803
- state,
1804
- startIndex,
1805
- useAverageSize
1806
- );
1807
- startIndex = processedStartIndex;
1808
- currentRowTop = initialRowTop;
1809
- } else if (startIndex < dataLength) {
1810
- const prevIndex = startIndex - 1;
1811
- const prevId = getId(state, prevIndex);
1812
- const prevPosition = (_b = positions.get(prevId)) != null ? _b : 0;
1813
- const prevSize = (_c = sizesKnown.get(prevId)) != null ? _c : getItemSize(ctx, state, prevId, prevIndex, data[prevIndex], useAverageSize, preferCachedSize);
1814
- currentRowTop = prevPosition + prevSize;
1815
- }
1816
- }
1817
- const needsIndexByKey = dataChanged || indexByKey.size === 0;
1818
- let didBreakEarly = false;
1819
- let breakAt;
1820
- for (let i = startIndex; i < dataLength; i++) {
1821
- if (shouldOptimize && breakAt !== void 0 && i > breakAt) {
1822
- didBreakEarly = true;
1823
- break;
1824
- }
1825
- if (shouldOptimize && breakAt === void 0 && !scrollingTo && !dataChanged && currentRowTop > maxVisibleArea) {
1826
- const itemsPerRow = hasColumns ? numColumns : 1;
1827
- breakAt = i + itemsPerRow + 10;
1828
- }
1829
- const id = (_d = idCache[i]) != null ? _d : getId(state, i);
1830
- const size = (_e = sizesKnown.get(id)) != null ? _e : getItemSize(ctx, state, id, i, data[i], useAverageSize, preferCachedSize);
1831
- if (IS_DEV && needsIndexByKey) {
1832
- if (indexByKeyForChecking.has(id)) {
1833
- console.error(
1834
- `[legend-list] Error: Detected overlapping key (${id}) which causes missing items and gaps and other terrrible things. Check that keyExtractor returns unique values.`
1835
- );
1836
- }
1837
- indexByKeyForChecking.set(id, i);
1838
- }
1839
- positions.set(id, currentRowTop);
1840
- if (needsIndexByKey) {
1841
- indexByKey.set(id, i);
1842
- }
1843
- columns.set(id, column);
1844
- if (hasColumns) {
1845
- if (size > maxSizeInRow) {
1846
- maxSizeInRow = size;
1847
- }
1848
- column++;
1849
- if (column > numColumns) {
1850
- currentRowTop += maxSizeInRow;
1851
- column = 1;
1852
- maxSizeInRow = 0;
1853
- }
1854
- } else {
1855
- currentRowTop += size;
1856
- }
1857
- }
1858
- if (!didBreakEarly) {
1859
- updateTotalSize(ctx, state);
1860
- }
1861
- if (snapToIndices) {
1862
- updateSnapToOffsets(ctx, state);
1863
- }
1864
- }
1865
-
1866
- // src/core/viewability.ts
1867
- function ensureViewabilityState(ctx, configId) {
1868
- let map = ctx.mapViewabilityConfigStates;
1869
- if (!map) {
1870
- map = /* @__PURE__ */ new Map();
1871
- ctx.mapViewabilityConfigStates = map;
1872
- }
1873
- let state = map.get(configId);
1874
- if (!state) {
1875
- state = { end: -1, previousEnd: -1, previousStart: -1, start: -1, viewableItems: [] };
1876
- map.set(configId, state);
1877
- }
1878
- return state;
1879
- }
1880
- function setupViewability(props) {
1881
- let { viewabilityConfig, viewabilityConfigCallbackPairs, onViewableItemsChanged } = props;
1882
- if (viewabilityConfig || onViewableItemsChanged) {
1883
- viewabilityConfigCallbackPairs = [
1884
- ...viewabilityConfigCallbackPairs || [],
1885
- {
1886
- onViewableItemsChanged,
1887
- viewabilityConfig: viewabilityConfig || {
1888
- viewAreaCoveragePercentThreshold: 0
1889
- }
1890
- }
1891
- ];
1892
- }
1893
- return viewabilityConfigCallbackPairs;
1894
- }
1895
- function updateViewableItems(state, ctx, viewabilityConfigCallbackPairs, scrollSize, start, end) {
1896
- const {
1897
- timeouts,
1898
- props: { data }
1899
- } = state;
1900
- for (const viewabilityConfigCallbackPair of viewabilityConfigCallbackPairs) {
1901
- const viewabilityState = ensureViewabilityState(ctx, viewabilityConfigCallbackPair.viewabilityConfig.id);
1902
- viewabilityState.start = start;
1903
- viewabilityState.end = end;
1904
- if (viewabilityConfigCallbackPair.viewabilityConfig.minimumViewTime) {
1905
- const timer = setTimeout(() => {
1906
- timeouts.delete(timer);
1907
- updateViewableItemsWithConfig(data, viewabilityConfigCallbackPair, state, ctx, scrollSize);
1908
- }, viewabilityConfigCallbackPair.viewabilityConfig.minimumViewTime);
1909
- timeouts.add(timer);
1910
- } else {
1911
- updateViewableItemsWithConfig(data, viewabilityConfigCallbackPair, state, ctx, scrollSize);
1912
- }
1913
- }
1914
- }
1915
- function updateViewableItemsWithConfig(data, viewabilityConfigCallbackPair, state, ctx, scrollSize) {
1916
- const { viewabilityConfig, onViewableItemsChanged } = viewabilityConfigCallbackPair;
1917
- const configId = viewabilityConfig.id;
1918
- const viewabilityState = ensureViewabilityState(ctx, configId);
1919
- const { viewableItems: previousViewableItems, start, end } = viewabilityState;
1920
- const viewabilityTokens = /* @__PURE__ */ new Map();
1921
- for (const [containerId, value] of ctx.mapViewabilityAmountValues) {
1922
- viewabilityTokens.set(
1923
- containerId,
1924
- computeViewability(
1925
- state,
1926
- ctx,
1927
- viewabilityConfig,
1928
- containerId,
1929
- value.key,
1930
- scrollSize,
1931
- value.item,
1932
- value.index
1933
- )
1934
- );
1935
- }
1936
- const changed = [];
1937
- if (previousViewableItems) {
1938
- for (const viewToken of previousViewableItems) {
1939
- const containerId = findContainerId(ctx, viewToken.key);
1940
- if (!checkIsViewable(
1941
- state,
1942
- ctx,
1943
- viewabilityConfig,
1944
- containerId,
1945
- viewToken.key,
1946
- scrollSize,
1947
- viewToken.item,
1948
- viewToken.index
1949
- )) {
1950
- viewToken.isViewable = false;
1951
- changed.push(viewToken);
1952
- }
1953
- }
1954
- }
1955
- const viewableItems = [];
1956
- for (let i = start; i <= end; i++) {
1957
- const item = data[i];
1958
- if (item) {
1959
- const key = getId(state, i);
1960
- const containerId = findContainerId(ctx, key);
1961
- if (checkIsViewable(state, ctx, viewabilityConfig, containerId, key, scrollSize, item, i)) {
1962
- const viewToken = {
1963
- containerId,
1964
- index: i,
1965
- isViewable: true,
1966
- item,
1967
- key
1968
- };
1969
- viewableItems.push(viewToken);
1970
- if (!(previousViewableItems == null ? void 0 : previousViewableItems.find((v) => v.key === viewToken.key))) {
1971
- changed.push(viewToken);
1972
- }
1973
- }
1974
- }
1975
- }
1976
- Object.assign(viewabilityState, {
1977
- previousEnd: end,
1978
- previousStart: start,
1979
- viewableItems
1980
- });
1981
- if (changed.length > 0) {
1982
- viewabilityState.viewableItems = viewableItems;
1983
- for (let i = 0; i < changed.length; i++) {
1984
- const change = changed[i];
1985
- maybeUpdateViewabilityCallback(ctx, configId, change.containerId, change);
1986
- }
1987
- if (onViewableItemsChanged) {
1988
- onViewableItemsChanged({ changed, viewableItems });
1989
- }
1990
- }
1991
- for (const [containerId, value] of ctx.mapViewabilityAmountValues) {
1992
- if (value.sizeVisible < 0) {
1993
- ctx.mapViewabilityAmountValues.delete(containerId);
1994
- }
1995
- }
1996
- }
1997
- function shallowEqual(prev, next) {
1998
- if (!prev) return false;
1999
- const keys = Object.keys(next);
2000
- for (let i = 0; i < keys.length; i++) {
2001
- const k = keys[i];
2002
- if (prev[k] !== next[k]) return false;
2003
- }
2004
- return true;
2005
- }
2006
- function computeViewability(state, ctx, viewabilityConfig, containerId, key, scrollSize, item, index) {
2007
- const { sizes, positions, scroll: scrollState } = state;
2008
- const topPad = (peek$(ctx, "stylePaddingTop") || 0) + (peek$(ctx, "headerSize") || 0);
2009
- const { itemVisiblePercentThreshold, viewAreaCoveragePercentThreshold } = viewabilityConfig;
2010
- const viewAreaMode = viewAreaCoveragePercentThreshold != null;
2011
- const viewablePercentThreshold = viewAreaMode ? viewAreaCoveragePercentThreshold : itemVisiblePercentThreshold;
2012
- const scroll = scrollState - topPad;
2013
- const top = positions.get(key) - scroll;
2014
- const size = sizes.get(key) || 0;
2015
- const bottom = top + size;
2016
- const isEntirelyVisible = top >= 0 && bottom <= scrollSize && bottom > top;
2017
- const sizeVisible = isEntirelyVisible ? size : Math.min(bottom, scrollSize) - Math.max(top, 0);
2018
- const percentVisible = size ? isEntirelyVisible ? 100 : 100 * (sizeVisible / size) : 0;
2019
- const percentOfScroller = size ? 100 * (sizeVisible / scrollSize) : 0;
2020
- const percent = isEntirelyVisible ? 100 : viewAreaMode ? percentOfScroller : percentVisible;
2021
- const isViewable = percent >= viewablePercentThreshold;
2022
- const value = {
2023
- containerId,
2024
- index,
2025
- isViewable,
2026
- item,
2027
- key,
2028
- percentOfScroller,
2029
- percentVisible,
2030
- scrollSize,
2031
- size,
2032
- sizeVisible
2033
- };
2034
- const prev = ctx.mapViewabilityAmountValues.get(containerId);
2035
- if (!shallowEqual(prev, value)) {
2036
- ctx.mapViewabilityAmountValues.set(containerId, value);
2037
- const cb = ctx.mapViewabilityAmountCallbacks.get(containerId);
2038
- if (cb) {
2039
- cb(value);
2040
- }
2041
- }
2042
- return value;
2043
- }
2044
- function checkIsViewable(state, ctx, viewabilityConfig, containerId, key, scrollSize, item, index) {
2045
- let value = ctx.mapViewabilityAmountValues.get(containerId);
2046
- if (!value || value.key !== key) {
2047
- value = computeViewability(state, ctx, viewabilityConfig, containerId, key, scrollSize, item, index);
2048
- }
2049
- return value.isViewable;
2050
- }
2051
- function maybeUpdateViewabilityCallback(ctx, configId, containerId, viewToken) {
2052
- const key = containerId + configId;
2053
- ctx.mapViewabilityValues.set(key, viewToken);
2054
- const cb = ctx.mapViewabilityCallbacks.get(key);
2055
- cb == null ? void 0 : cb(viewToken);
2056
- }
2057
-
2058
- // src/utils/checkAllSizesKnown.ts
2059
- function isNullOrUndefined2(value) {
2060
- return value === null || value === void 0;
2061
- }
2062
- function checkAllSizesKnown(state) {
2063
- const { startBuffered, endBuffered, sizesKnown } = state;
2064
- if (!isNullOrUndefined2(endBuffered) && !isNullOrUndefined2(startBuffered) && startBuffered >= 0 && endBuffered >= 0) {
2065
- let areAllKnown = true;
2066
- for (let i = startBuffered; areAllKnown && i <= endBuffered; i++) {
2067
- const key = getId(state, i);
2068
- areAllKnown && (areAllKnown = sizesKnown.has(key));
2069
- }
2070
- return areAllKnown;
2071
- }
2072
- return false;
2073
- }
2074
-
2075
- // src/utils/findAvailableContainers.ts
2076
- function findAvailableContainers(ctx, state, numNeeded, startBuffered, endBuffered, pendingRemoval, requiredItemTypes, needNewContainers) {
2077
- const numContainers = peek$(ctx, "numContainers");
2078
- const { stickyContainerPool, containerItemTypes } = state;
2079
- const result = [];
2080
- const availableContainers = [];
2081
- const pendingRemovalSet = new Set(pendingRemoval);
2082
- let pendingRemovalChanged = false;
2083
- const stickyIndicesSet = state.props.stickyIndicesSet;
2084
- const stickyItemIndices = (needNewContainers == null ? void 0 : needNewContainers.filter((index) => stickyIndicesSet.has(index))) || [];
2085
- const canReuseContainer = (containerIndex, requiredType) => {
2086
- if (!requiredType) return true;
2087
- const existingType = containerItemTypes.get(containerIndex);
2088
- if (!existingType) return true;
2089
- return existingType === requiredType;
2090
- };
2091
- const neededTypes = requiredItemTypes ? [...requiredItemTypes] : [];
2092
- let typeIndex = 0;
2093
- for (let i = 0; i < stickyItemIndices.length; i++) {
2094
- const requiredType = neededTypes[typeIndex];
2095
- let foundContainer = false;
2096
- for (const containerIndex of stickyContainerPool) {
2097
- const key = peek$(ctx, `containerItemKey${containerIndex}`);
2098
- const isPendingRemoval = pendingRemovalSet.has(containerIndex);
2099
- if ((key === void 0 || isPendingRemoval) && canReuseContainer(containerIndex, requiredType) && !result.includes(containerIndex)) {
2100
- result.push(containerIndex);
2101
- if (isPendingRemoval && pendingRemovalSet.delete(containerIndex)) {
2102
- pendingRemovalChanged = true;
2103
- }
2104
- foundContainer = true;
2105
- if (requiredItemTypes) typeIndex++;
2106
- break;
2107
- }
2108
- }
2109
- if (!foundContainer) {
2110
- const newContainerIndex = numContainers + result.filter((index) => index >= numContainers).length;
2111
- result.push(newContainerIndex);
2112
- stickyContainerPool.add(newContainerIndex);
2113
- if (requiredItemTypes) typeIndex++;
2114
- }
2115
- }
2116
- for (let u = 0; u < numContainers && result.length < numNeeded; u++) {
2117
- if (stickyContainerPool.has(u)) {
2118
- continue;
2119
- }
2120
- const key = peek$(ctx, `containerItemKey${u}`);
2121
- const requiredType = neededTypes[typeIndex];
2122
- const isPending = key !== void 0 && pendingRemovalSet.has(u);
2123
- const canUse = key === void 0 || isPending && canReuseContainer(u, requiredType);
2124
- if (canUse) {
2125
- if (isPending) {
2126
- pendingRemovalSet.delete(u);
2127
- pendingRemovalChanged = true;
2128
- }
2129
- result.push(u);
2130
- if (requiredItemTypes) {
2131
- typeIndex++;
2132
- }
2133
- }
2134
- }
2135
- for (let u = 0; u < numContainers && result.length < numNeeded; u++) {
2136
- if (stickyContainerPool.has(u)) {
2137
- continue;
2138
- }
2139
- const key = peek$(ctx, `containerItemKey${u}`);
2140
- if (key === void 0) continue;
2141
- const index = state.indexByKey.get(key);
2142
- const isOutOfView = index < startBuffered || index > endBuffered;
2143
- if (isOutOfView) {
2144
- const distance = index < startBuffered ? startBuffered - index : index - endBuffered;
2145
- if (!requiredItemTypes || typeIndex < neededTypes.length && canReuseContainer(u, neededTypes[typeIndex])) {
2146
- availableContainers.push({ distance, index: u });
2147
- }
2148
- }
2149
- }
2150
- const remaining = numNeeded - result.length;
2151
- if (remaining > 0) {
2152
- if (availableContainers.length > 0) {
2153
- if (availableContainers.length > remaining) {
2154
- availableContainers.sort(comparatorByDistance);
2155
- availableContainers.length = remaining;
2156
- }
2157
- for (const container of availableContainers) {
2158
- result.push(container.index);
2159
- if (requiredItemTypes) {
2160
- typeIndex++;
2161
- }
2162
- }
2163
- }
2164
- const stillNeeded = numNeeded - result.length;
2165
- if (stillNeeded > 0) {
2166
- for (let i = 0; i < stillNeeded; i++) {
2167
- result.push(numContainers + i);
2168
- }
2169
- if (IS_DEV && numContainers + stillNeeded > peek$(ctx, "numContainersPooled")) {
2170
- console.warn(
2171
- "[legend-list] No unused container available, so creating one on demand. This can be a minor performance issue and is likely caused by the estimatedItemSize being too large. Consider decreasing estimatedItemSize or increasing initialContainerPoolRatio.",
2172
- {
2173
- debugInfo: {
2174
- numContainers,
2175
- numContainersPooled: peek$(ctx, "numContainersPooled"),
2176
- numNeeded,
2177
- stillNeeded
2178
- }
2179
- }
2180
- );
2181
- }
2182
- }
2183
- }
2184
- if (pendingRemovalChanged) {
2185
- pendingRemoval.length = 0;
2186
- for (const value of pendingRemovalSet) {
2187
- pendingRemoval.push(value);
2188
- }
2189
- }
2190
- return result.sort(comparatorDefault);
2191
- }
2192
- function comparatorByDistance(a, b) {
2193
- return b.distance - a.distance;
2194
- }
2195
-
2196
- // src/core/scrollToIndex.ts
2197
- function scrollToIndex(ctx, state, { index, viewOffset = 0, animated = true, viewPosition }) {
2198
- if (index >= state.props.data.length) {
2199
- index = state.props.data.length - 1;
2200
- } else if (index < 0) {
2201
- index = 0;
2202
- }
2203
- const firstIndexOffset = calculateOffsetForIndex(ctx, state, index);
2204
- const isLast = index === state.props.data.length - 1;
2205
- if (isLast && viewPosition === void 0) {
2206
- viewPosition = 1;
2207
- }
2208
- state.scrollForNextCalculateItemsInView = void 0;
2209
- scrollTo(ctx, state, {
2210
- animated,
2211
- index,
2212
- offset: firstIndexOffset,
2213
- viewOffset,
2214
- viewPosition: viewPosition != null ? viewPosition : 0
2215
- });
2216
- }
2217
-
2218
- // src/utils/setDidLayout.ts
2219
- function setDidLayout(ctx, state) {
2220
- const {
2221
- loadStartTime,
2222
- initialScroll,
2223
- props: { onLoad }
2224
- } = state;
2225
- state.queuedInitialLayout = true;
2226
- checkAtBottom(ctx, state);
2227
- const setIt = () => {
2228
- set$(ctx, "containersDidLayout", true);
2229
- if (onLoad) {
2230
- onLoad({ elapsedTimeInMs: Date.now() - loadStartTime });
2231
- }
2232
- };
2233
- {
2234
- setIt();
2235
- }
2236
- }
2237
-
2238
- // src/core/calculateItemsInView.ts
2239
- function findCurrentStickyIndex(stickyArray, scroll, state) {
2240
- var _a3;
2241
- const idCache = state.idCache;
2242
- const positions = state.positions;
2243
- for (let i = stickyArray.length - 1; i >= 0; i--) {
2244
- const stickyIndex = stickyArray[i];
2245
- const stickyId = (_a3 = idCache[stickyIndex]) != null ? _a3 : getId(state, stickyIndex);
2246
- const stickyPos = stickyId ? positions.get(stickyId) : void 0;
2247
- if (stickyPos !== void 0 && scroll >= stickyPos) {
2248
- return i;
2249
- }
2250
- }
2251
- return -1;
2252
- }
2253
- function getActiveStickyIndices(ctx, state, stickyHeaderIndices) {
2254
- return new Set(
2255
- Array.from(state.stickyContainerPool).map((i) => peek$(ctx, `containerItemKey${i}`)).map((key) => key ? state.indexByKey.get(key) : void 0).filter((idx) => idx !== void 0 && stickyHeaderIndices.has(idx))
2256
- );
2257
- }
2258
- function handleStickyActivation(ctx, state, stickyHeaderIndices, stickyArray, currentStickyIdx, needNewContainers, startBuffered, endBuffered) {
2259
- var _a3;
2260
- const activeIndices = getActiveStickyIndices(ctx, state, stickyHeaderIndices);
2261
- state.activeStickyIndex = currentStickyIdx >= 0 ? stickyArray[currentStickyIdx] : void 0;
2262
- for (let offset = 0; offset <= 1; offset++) {
2263
- const idx = currentStickyIdx - offset;
2264
- if (idx < 0 || activeIndices.has(stickyArray[idx])) continue;
2265
- const stickyIndex = stickyArray[idx];
2266
- const stickyId = (_a3 = state.idCache[stickyIndex]) != null ? _a3 : getId(state, stickyIndex);
2267
- if (stickyId && !state.containerItemKeys.has(stickyId) && (stickyIndex < startBuffered || stickyIndex > endBuffered)) {
2268
- needNewContainers.push(stickyIndex);
2269
- }
2270
- }
2271
- }
2272
- function handleStickyRecycling(ctx, state, stickyArray, scroll, scrollBuffer, currentStickyIdx, pendingRemoval) {
2273
- var _a3, _b, _c;
2274
- for (const containerIndex of state.stickyContainerPool) {
2275
- const itemKey = peek$(ctx, `containerItemKey${containerIndex}`);
2276
- const itemIndex = itemKey ? state.indexByKey.get(itemKey) : void 0;
2277
- if (itemIndex === void 0) continue;
2278
- const arrayIdx = stickyArray.indexOf(itemIndex);
2279
- if (arrayIdx === -1) {
2280
- state.stickyContainerPool.delete(containerIndex);
2281
- set$(ctx, `containerSticky${containerIndex}`, false);
2282
- set$(ctx, `containerStickyOffset${containerIndex}`, void 0);
2283
- continue;
2284
- }
2285
- const isRecentSticky = arrayIdx >= currentStickyIdx - 1 && arrayIdx <= currentStickyIdx + 1;
2286
- if (isRecentSticky) continue;
2287
- const nextIndex = stickyArray[arrayIdx + 1];
2288
- let shouldRecycle = false;
2289
- if (nextIndex) {
2290
- const nextId = (_a3 = state.idCache[nextIndex]) != null ? _a3 : getId(state, nextIndex);
2291
- const nextPos = nextId ? state.positions.get(nextId) : void 0;
2292
- shouldRecycle = nextPos !== void 0 && scroll > nextPos + scrollBuffer * 2;
2293
- } else {
2294
- const currentId = (_b = state.idCache[itemIndex]) != null ? _b : getId(state, itemIndex);
2295
- if (currentId) {
2296
- const currentPos = state.positions.get(currentId);
2297
- const currentSize = (_c = state.sizes.get(currentId)) != null ? _c : getItemSize(ctx, state, currentId, itemIndex, state.props.data[itemIndex]);
2298
- shouldRecycle = currentPos !== void 0 && scroll > currentPos + currentSize + scrollBuffer * 3;
2299
- }
2300
- }
2301
- if (shouldRecycle) {
2302
- pendingRemoval.push(containerIndex);
2303
- }
2304
- }
2305
- }
2306
- function calculateItemsInView(ctx, state, params = {}) {
2307
- unstable_batchedUpdates(() => {
2308
- var _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j;
2309
- const {
2310
- columns,
2311
- containerItemKeys,
2312
- enableScrollForNextCalculateItemsInView,
2313
- idCache,
2314
- indexByKey,
2315
- initialScroll,
2316
- minIndexSizeChanged,
2317
- positions,
2318
- props: { getItemType, itemsAreEqual, keyExtractor, onStickyHeaderChange, scrollBuffer },
2319
- scrollForNextCalculateItemsInView,
2320
- scrollLength,
2321
- sizes,
2322
- startBufferedId: startBufferedIdOrig,
2323
- viewabilityConfigCallbackPairs
2324
- } = state;
2325
- const { data } = state.props;
2326
- const stickyIndicesArr = state.props.stickyIndicesArr || [];
2327
- const stickyIndicesSet = state.props.stickyIndicesSet || /* @__PURE__ */ new Set();
2328
- const prevNumContainers = peek$(ctx, "numContainers");
2329
- if (!data || scrollLength === 0 || !prevNumContainers) {
2330
- if (state.initialAnchor) {
2331
- ensureInitialAnchor(ctx, state);
2332
- }
2333
- return;
2334
- }
2335
- const totalSize = getContentSize(ctx);
2336
- const topPad = peek$(ctx, "stylePaddingTop") + peek$(ctx, "headerSize");
2337
- const numColumns = peek$(ctx, "numColumns");
2338
- const { dataChanged, doMVCP, forceFullItemPositions } = params;
2339
- const speed = getScrollVelocity(state);
2340
- const scrollExtra = 0;
2341
- const { queuedInitialLayout } = state;
2342
- let { scroll: scrollState } = state;
2343
- if (!queuedInitialLayout && initialScroll) {
2344
- const updatedOffset = calculateOffsetWithOffsetPosition(
2345
- ctx,
2346
- state,
2347
- calculateOffsetForIndex(ctx, state, initialScroll.index),
2348
- initialScroll
2349
- );
2350
- scrollState = updatedOffset;
2351
- }
2352
- const scrollAdjustPending = (_a3 = peek$(ctx, "scrollAdjustPending")) != null ? _a3 : 0;
2353
- const scrollAdjustPad = scrollAdjustPending - topPad;
2354
- let scroll = Math.round(scrollState + scrollExtra + scrollAdjustPad);
2355
- if (scroll + scrollLength > totalSize) {
2356
- scroll = Math.max(0, totalSize - scrollLength);
2357
- }
2358
- if (ENABLE_DEBUG_VIEW) {
2359
- set$(ctx, "debugRawScroll", scrollState);
2360
- set$(ctx, "debugComputedScroll", scroll);
2361
- }
2362
- const previousStickyIndex = state.activeStickyIndex;
2363
- const currentStickyIdx = stickyIndicesArr.length > 0 ? findCurrentStickyIndex(stickyIndicesArr, scroll, state) : -1;
2364
- const nextActiveStickyIndex = currentStickyIdx >= 0 ? stickyIndicesArr[currentStickyIdx] : void 0;
2365
- state.activeStickyIndex = nextActiveStickyIndex;
2366
- set$(ctx, "activeStickyIndex", nextActiveStickyIndex);
2367
- let scrollBufferTop = scrollBuffer;
2368
- let scrollBufferBottom = scrollBuffer;
2369
- if (speed > 0 || speed === 0 && scroll < Math.max(50, scrollBuffer)) {
2370
- scrollBufferTop = scrollBuffer * 0.5;
2371
- scrollBufferBottom = scrollBuffer * 1.5;
2372
- } else {
2373
- scrollBufferTop = scrollBuffer * 1.5;
2374
- scrollBufferBottom = scrollBuffer * 0.5;
2375
- }
2376
- const scrollTopBuffered = scroll - scrollBufferTop;
2377
- const scrollBottom = scroll + scrollLength + (scroll < 0 ? -scroll : 0);
2378
- const scrollBottomBuffered = scrollBottom + scrollBufferBottom;
2379
- if (!dataChanged && !forceFullItemPositions && scrollForNextCalculateItemsInView) {
2380
- const { top, bottom } = scrollForNextCalculateItemsInView;
2381
- if ((top === null || scrollTopBuffered > top) && (bottom === null || scrollBottomBuffered < bottom)) {
2382
- if (state.initialAnchor) {
2383
- ensureInitialAnchor(ctx, state);
2384
- }
2385
- return;
2386
- }
2387
- }
2388
- const checkMVCP = doMVCP ? prepareMVCP(ctx, state, dataChanged) : void 0;
2389
- if (dataChanged) {
2390
- indexByKey.clear();
2391
- idCache.length = 0;
2392
- positions.clear();
2393
- }
2394
- const startIndex = forceFullItemPositions || dataChanged ? 0 : (_b = minIndexSizeChanged != null ? minIndexSizeChanged : state.startBuffered) != null ? _b : 0;
2395
- updateItemPositions(ctx, state, dataChanged, {
2396
- doMVCP,
2397
- forceFullUpdate: !!forceFullItemPositions,
2398
- scrollBottomBuffered,
2399
- startIndex
2400
- });
2401
- if (minIndexSizeChanged !== void 0) {
2402
- state.minIndexSizeChanged = void 0;
2403
- }
2404
- checkMVCP == null ? void 0 : checkMVCP();
2405
- let startNoBuffer = null;
2406
- let startBuffered = null;
2407
- let startBufferedId = null;
2408
- let endNoBuffer = null;
2409
- let endBuffered = null;
2410
- let loopStart = !dataChanged && startBufferedIdOrig ? indexByKey.get(startBufferedIdOrig) || 0 : 0;
2411
- for (let i = loopStart; i >= 0; i--) {
2412
- const id = (_c = idCache[i]) != null ? _c : getId(state, i);
2413
- const top = positions.get(id);
2414
- const size = (_d = sizes.get(id)) != null ? _d : getItemSize(ctx, state, id, i, data[i]);
2415
- const bottom = top + size;
2416
- if (bottom > scroll - scrollBufferTop) {
2417
- loopStart = i;
2418
- } else {
2419
- break;
2420
- }
2421
- }
2422
- const loopStartMod = loopStart % numColumns;
2423
- if (loopStartMod > 0) {
2424
- loopStart -= loopStartMod;
2425
- }
2426
- let foundEnd = false;
2427
- let nextTop;
2428
- let nextBottom;
2429
- let maxIndexRendered = 0;
2430
- for (let i = 0; i < prevNumContainers; i++) {
2431
- const key = peek$(ctx, `containerItemKey${i}`);
2432
- if (key !== void 0) {
2433
- const index = indexByKey.get(key);
2434
- maxIndexRendered = Math.max(maxIndexRendered, index);
2435
- }
2436
- }
2437
- let firstFullyOnScreenIndex;
2438
- const dataLength = data.length;
2439
- for (let i = Math.max(0, loopStart); i < dataLength && (!foundEnd || i <= maxIndexRendered); i++) {
2440
- const id = (_e = idCache[i]) != null ? _e : getId(state, i);
2441
- const size = (_f = sizes.get(id)) != null ? _f : getItemSize(ctx, state, id, i, data[i]);
2442
- const top = positions.get(id);
2443
- if (!foundEnd) {
2444
- if (startNoBuffer === null && top + size > scroll) {
2445
- startNoBuffer = i;
2446
- }
2447
- if (firstFullyOnScreenIndex === void 0 && top >= scroll - 10) {
2448
- firstFullyOnScreenIndex = i;
2449
- }
2450
- if (startBuffered === null && top + size > scrollTopBuffered) {
2451
- startBuffered = i;
2452
- startBufferedId = id;
2453
- if (scrollTopBuffered < 0) {
2454
- nextTop = null;
2455
- } else {
2456
- nextTop = top;
2457
- }
2458
- }
2459
- if (startNoBuffer !== null) {
2460
- if (top <= scrollBottom) {
2461
- endNoBuffer = i;
2462
- }
2463
- if (top <= scrollBottomBuffered) {
2464
- endBuffered = i;
2465
- if (scrollBottomBuffered > totalSize) {
2466
- nextBottom = null;
2467
- } else {
2468
- nextBottom = top + size;
2469
- }
2470
- } else {
2471
- foundEnd = true;
2472
- }
2473
- }
2474
- }
2475
- }
2476
- const idsInView = [];
2477
- for (let i = firstFullyOnScreenIndex; i <= endNoBuffer; i++) {
2478
- const id = (_g = idCache[i]) != null ? _g : getId(state, i);
2479
- idsInView.push(id);
2480
- }
2481
- Object.assign(state, {
2482
- endBuffered,
2483
- endNoBuffer,
2484
- firstFullyOnScreenIndex,
2485
- idsInView,
2486
- startBuffered,
2487
- startBufferedId,
2488
- startNoBuffer
2489
- });
2490
- if (enableScrollForNextCalculateItemsInView && nextTop !== void 0 && nextBottom !== void 0) {
2491
- state.scrollForNextCalculateItemsInView = nextTop !== void 0 && nextBottom !== void 0 ? {
2492
- bottom: nextBottom,
2493
- top: nextTop
2494
- } : void 0;
2495
- }
2496
- let numContainers = prevNumContainers;
2497
- const pendingRemoval = [];
2498
- if (dataChanged) {
2499
- for (let i = 0; i < numContainers; i++) {
2500
- const itemKey = peek$(ctx, `containerItemKey${i}`);
2501
- if (!keyExtractor || itemKey && indexByKey.get(itemKey) === void 0) {
2502
- pendingRemoval.push(i);
2503
- }
2504
- }
2505
- }
2506
- if (startBuffered !== null && endBuffered !== null) {
2507
- const needNewContainers = [];
2508
- for (let i = startBuffered; i <= endBuffered; i++) {
2509
- const id = (_h = idCache[i]) != null ? _h : getId(state, i);
2510
- if (!containerItemKeys.has(id)) {
2511
- needNewContainers.push(i);
2512
- }
2513
- }
2514
- if (stickyIndicesArr.length > 0) {
2515
- handleStickyActivation(
2516
- ctx,
2517
- state,
2518
- stickyIndicesSet,
2519
- stickyIndicesArr,
2520
- currentStickyIdx,
2521
- needNewContainers,
2522
- startBuffered,
2523
- endBuffered
2524
- );
2525
- } else {
2526
- state.activeStickyIndex = void 0;
2527
- set$(ctx, "activeStickyIndex", void 0);
2528
- }
2529
- if (needNewContainers.length > 0) {
2530
- const requiredItemTypes = getItemType ? needNewContainers.map((i) => {
2531
- const itemType = getItemType(data[i], i);
2532
- return itemType ? String(itemType) : "";
2533
- }) : void 0;
2534
- const availableContainers = findAvailableContainers(
2535
- ctx,
2536
- state,
2537
- needNewContainers.length,
2538
- startBuffered,
2539
- endBuffered,
2540
- pendingRemoval,
2541
- requiredItemTypes,
2542
- needNewContainers
2543
- );
2544
- for (let idx = 0; idx < needNewContainers.length; idx++) {
2545
- const i = needNewContainers[idx];
2546
- const containerIndex = availableContainers[idx];
2547
- const id = (_i = idCache[i]) != null ? _i : getId(state, i);
2548
- const oldKey = peek$(ctx, `containerItemKey${containerIndex}`);
2549
- if (oldKey && oldKey !== id) {
2550
- containerItemKeys.delete(oldKey);
2551
- }
2552
- set$(ctx, `containerItemKey${containerIndex}`, id);
2553
- set$(ctx, `containerItemData${containerIndex}`, data[i]);
2554
- if (requiredItemTypes) {
2555
- state.containerItemTypes.set(containerIndex, requiredItemTypes[idx]);
2556
- }
2557
- containerItemKeys.add(id);
2558
- const containerSticky = `containerSticky${containerIndex}`;
2559
- if (stickyIndicesSet.has(i)) {
2560
- set$(ctx, containerSticky, true);
2561
- const topPadding = (peek$(ctx, "stylePaddingTop") || 0) + (peek$(ctx, "headerSize") || 0);
2562
- set$(ctx, `containerStickyOffset${containerIndex}`, topPadding);
2563
- state.stickyContainerPool.add(containerIndex);
2564
- } else if (peek$(ctx, containerSticky)) {
2565
- set$(ctx, containerSticky, false);
2566
- state.stickyContainerPool.delete(containerIndex);
2567
- }
2568
- if (containerIndex >= numContainers) {
2569
- numContainers = containerIndex + 1;
2570
- }
2571
- }
2572
- if (numContainers !== prevNumContainers) {
2573
- set$(ctx, "numContainers", numContainers);
2574
- if (numContainers > peek$(ctx, "numContainersPooled")) {
2575
- set$(ctx, "numContainersPooled", Math.ceil(numContainers * 1.5));
2576
- }
2577
- }
2578
- }
2579
- }
2580
- if (stickyIndicesArr.length > 0) {
2581
- handleStickyRecycling(ctx, state, stickyIndicesArr, scroll, scrollBuffer, currentStickyIdx, pendingRemoval);
2582
- }
2583
- let didChangePositions = false;
2584
- for (let i = 0; i < numContainers; i++) {
2585
- const itemKey = peek$(ctx, `containerItemKey${i}`);
2586
- if (pendingRemoval.includes(i)) {
2587
- if (itemKey !== void 0) {
2588
- containerItemKeys.delete(itemKey);
2589
- }
2590
- state.containerItemTypes.delete(i);
2591
- if (state.stickyContainerPool.has(i)) {
2592
- set$(ctx, `containerSticky${i}`, false);
2593
- set$(ctx, `containerStickyOffset${i}`, void 0);
2594
- state.stickyContainerPool.delete(i);
2595
- }
2596
- set$(ctx, `containerItemKey${i}`, void 0);
2597
- set$(ctx, `containerItemData${i}`, void 0);
2598
- set$(ctx, `containerPosition${i}`, POSITION_OUT_OF_VIEW);
2599
- set$(ctx, `containerColumn${i}`, -1);
2600
- } else {
2601
- const itemIndex = indexByKey.get(itemKey);
2602
- const item = data[itemIndex];
2603
- if (item !== void 0) {
2604
- const id = (_j = idCache[itemIndex]) != null ? _j : getId(state, itemIndex);
2605
- const positionValue = positions.get(id);
2606
- if (positionValue === void 0) {
2607
- set$(ctx, `containerPosition${i}`, POSITION_OUT_OF_VIEW);
2608
- } else {
2609
- const position = (positionValue || 0) - scrollAdjustPending;
2610
- const column = columns.get(id) || 1;
2611
- const prevPos = peek$(ctx, `containerPosition${i}`);
2612
- const prevColumn = peek$(ctx, `containerColumn${i}`);
2613
- const prevData = peek$(ctx, `containerItemData${i}`);
2614
- if (position > POSITION_OUT_OF_VIEW && position !== prevPos) {
2615
- set$(ctx, `containerPosition${i}`, position);
2616
- didChangePositions = true;
2617
- }
2618
- if (column >= 0 && column !== prevColumn) {
2619
- set$(ctx, `containerColumn${i}`, column);
2620
- }
2621
- if (prevData !== item && (itemsAreEqual ? !itemsAreEqual(prevData, item, itemIndex, data) : true)) {
2622
- set$(ctx, `containerItemData${i}`, item);
2623
- }
2624
- }
2625
- }
2626
- }
2627
- }
2628
- if (didChangePositions) {
2629
- set$(ctx, "lastPositionUpdate", Date.now());
2630
- }
2631
- if (!queuedInitialLayout && endBuffered !== null) {
2632
- if (checkAllSizesKnown(state)) {
2633
- setDidLayout(ctx, state);
2634
- }
2635
- }
2636
- if (viewabilityConfigCallbackPairs) {
2637
- updateViewableItems(state, ctx, viewabilityConfigCallbackPairs, scrollLength, startNoBuffer, endNoBuffer);
2638
- }
2639
- if (onStickyHeaderChange && stickyIndicesArr.length > 0 && nextActiveStickyIndex !== void 0 && nextActiveStickyIndex !== previousStickyIndex) {
2640
- const item = data[nextActiveStickyIndex];
2641
- if (item !== void 0) {
2642
- onStickyHeaderChange({ index: nextActiveStickyIndex, item });
2643
- }
2644
- }
2645
- });
2646
- if (state.initialAnchor) {
2647
- ensureInitialAnchor(ctx, state);
2648
- }
2649
- }
2650
-
2651
- // src/core/checkActualChange.ts
2652
- function checkActualChange(state, dataProp, previousData) {
2653
- if (!previousData || !dataProp || dataProp.length !== previousData.length) {
2654
- return true;
2655
- }
2656
- const {
2657
- idCache,
2658
- props: { keyExtractor }
2659
- } = state;
2660
- for (let i = 0; i < dataProp.length; i++) {
2661
- if (dataProp[i] !== previousData[i]) {
2662
- return true;
2663
- }
2664
- if (keyExtractor ? idCache[i] !== keyExtractor(previousData[i], i) : dataProp[i] !== previousData[i]) {
2665
- return true;
2666
- }
2667
- }
2668
- return false;
2669
- }
2670
-
2671
- // src/core/doMaintainScrollAtEnd.ts
2672
- function doMaintainScrollAtEnd(ctx, state, animated) {
2673
- const {
2674
- refScroller,
2675
- props: { maintainScrollAtEnd }
2676
- } = state;
2677
- if ((state == null ? void 0 : state.isAtEnd) && maintainScrollAtEnd && peek$(ctx, "containersDidLayout")) {
2678
- const paddingTop = peek$(ctx, "alignItemsPaddingTop");
2679
- if (paddingTop > 0) {
2680
- state.scroll = 0;
2681
- }
2682
- requestAnimationFrame(() => {
2683
- var _a3;
2684
- if (state == null ? void 0 : state.isAtEnd) {
2685
- state.maintainingScrollAtEnd = true;
2686
- (_a3 = refScroller.current) == null ? void 0 : _a3.scrollToEnd({
2687
- animated
2688
- });
2689
- setTimeout(
2690
- () => {
2691
- state.maintainingScrollAtEnd = false;
2692
- },
2693
- 0
2694
- );
2695
- }
2696
- });
2697
- return true;
2698
- }
2699
- return false;
2700
- }
2701
-
2702
- // src/utils/updateAveragesOnDataChange.ts
2703
- function updateAveragesOnDataChange(state, oldData, newData) {
2704
- var _a3;
2705
- const {
2706
- averageSizes,
2707
- sizesKnown,
2708
- indexByKey,
2709
- props: { itemsAreEqual, getItemType, keyExtractor }
2710
- } = state;
2711
- if (!itemsAreEqual || !oldData.length || !newData.length) {
2712
- for (const key in averageSizes) {
2713
- delete averageSizes[key];
2714
- }
2715
- return;
2716
- }
2717
- const itemTypesToPreserve = {};
2718
- const newDataLength = newData.length;
2719
- const oldDataLength = oldData.length;
2720
- for (let newIndex = 0; newIndex < newDataLength; newIndex++) {
2721
- const newItem = newData[newIndex];
2722
- const id = keyExtractor ? keyExtractor(newItem, newIndex) : String(newIndex);
2723
- const oldIndex = indexByKey.get(id);
2724
- if (oldIndex !== void 0 && oldIndex < oldDataLength) {
2725
- const knownSize = sizesKnown.get(id);
2726
- if (knownSize === void 0) continue;
2727
- const oldItem = oldData[oldIndex];
2728
- const areEqual = itemsAreEqual(oldItem, newItem, newIndex, newData);
2729
- if (areEqual) {
2730
- const itemType = getItemType ? (_a3 = getItemType(newItem, newIndex)) != null ? _a3 : "" : "";
2731
- let typeData = itemTypesToPreserve[itemType];
2732
- if (!typeData) {
2733
- typeData = itemTypesToPreserve[itemType] = { count: 0, totalSize: 0 };
2734
- }
2735
- typeData.totalSize += knownSize;
2736
- typeData.count++;
2737
- }
2738
- }
2739
- }
2740
- for (const key in averageSizes) {
2741
- delete averageSizes[key];
2742
- }
2743
- for (const itemType in itemTypesToPreserve) {
2744
- const { totalSize, count } = itemTypesToPreserve[itemType];
2745
- if (count > 0) {
2746
- averageSizes[itemType] = {
2747
- avg: totalSize / count,
2748
- num: count
2749
- };
2750
- }
2751
- }
2752
- }
2753
-
2754
- // src/core/checkResetContainers.ts
2755
- function checkResetContainers(ctx, state, dataProp) {
2756
- const { previousData } = state;
2757
- if (previousData) {
2758
- updateAveragesOnDataChange(state, previousData, dataProp);
2759
- }
2760
- const { maintainScrollAtEnd } = state.props;
2761
- calculateItemsInView(ctx, state, { dataChanged: true, doMVCP: true });
2762
- const shouldMaintainScrollAtEnd = maintainScrollAtEnd === true || maintainScrollAtEnd.onDataChange;
2763
- const didMaintainScrollAtEnd = shouldMaintainScrollAtEnd && doMaintainScrollAtEnd(ctx, state, false);
2764
- if (!didMaintainScrollAtEnd && previousData && dataProp.length > previousData.length) {
2765
- state.isEndReached = false;
2766
- }
2767
- if (!didMaintainScrollAtEnd) {
2768
- checkAtTop(state);
2769
- checkAtBottom(ctx, state);
2770
- }
2771
- delete state.previousData;
2772
- }
2773
-
2774
- // src/core/doInitialAllocateContainers.ts
2775
- function doInitialAllocateContainers(ctx, state) {
2776
- var _a3, _b, _c;
2777
- const {
2778
- scrollLength,
2779
- props: {
2780
- data,
2781
- getEstimatedItemSize,
2782
- getFixedItemSize,
2783
- getItemType,
2784
- scrollBuffer,
2785
- numColumns,
2786
- estimatedItemSize
2787
- }
2788
- } = state;
2789
- const hasContainers = peek$(ctx, "numContainers");
2790
- if (scrollLength > 0 && data.length > 0 && !hasContainers) {
2791
- let averageItemSize;
2792
- if (getFixedItemSize || getEstimatedItemSize) {
2793
- let totalSize = 0;
2794
- const num = Math.min(20, data.length);
2795
- for (let i = 0; i < num; i++) {
2796
- const item = data[i];
2797
- const itemType = getItemType ? (_a3 = getItemType(item, i)) != null ? _a3 : "" : "";
2798
- totalSize += (_c = (_b = getFixedItemSize == null ? void 0 : getFixedItemSize(i, item, itemType)) != null ? _b : getEstimatedItemSize == null ? void 0 : getEstimatedItemSize(i, item, itemType)) != null ? _c : estimatedItemSize;
2799
- }
2800
- averageItemSize = totalSize / num;
2801
- } else {
2802
- averageItemSize = estimatedItemSize;
2803
- }
2804
- const numContainers = Math.ceil((scrollLength + scrollBuffer * 2) / averageItemSize * numColumns);
2805
- for (let i = 0; i < numContainers; i++) {
2806
- set$(ctx, `containerPosition${i}`, POSITION_OUT_OF_VIEW);
2807
- set$(ctx, `containerColumn${i}`, -1);
2808
- }
2809
- set$(ctx, "numContainers", numContainers);
2810
- set$(ctx, "numContainersPooled", numContainers * state.props.initialContainerPoolRatio);
2811
- if (state.lastLayout) {
2812
- if (state.initialScroll) {
2813
- requestAnimationFrame(() => {
2814
- calculateItemsInView(ctx, state, { dataChanged: true, doMVCP: true });
2815
- });
2816
- } else {
2817
- calculateItemsInView(ctx, state, { dataChanged: true, doMVCP: true });
2818
- }
2819
- }
2820
- return true;
2821
- }
2822
- }
2823
-
2824
- // src/core/handleLayout.ts
2825
- function handleLayout(ctx, state, layout, setCanRender) {
2826
- const { maintainScrollAtEnd } = state.props;
2827
- const measuredLength = layout[state.props.horizontal ? "width" : "height"];
2828
- const previousLength = state.scrollLength;
2829
- const scrollLength = measuredLength > 0 ? measuredLength : previousLength;
2830
- const otherAxisSize = layout[state.props.horizontal ? "height" : "width"];
2831
- const needsCalculate = !state.lastLayout || scrollLength > state.scrollLength || state.lastLayout.x !== layout.x || state.lastLayout.y !== layout.y;
2832
- state.lastLayout = layout;
2833
- const prevOtherAxisSize = state.otherAxisSize;
2834
- const didChange = scrollLength !== state.scrollLength || otherAxisSize !== prevOtherAxisSize;
2835
- if (didChange) {
2836
- state.scrollLength = scrollLength;
2837
- state.otherAxisSize = otherAxisSize;
2838
- state.lastBatchingAction = Date.now();
2839
- state.scrollForNextCalculateItemsInView = void 0;
2840
- if (scrollLength > 0) {
2841
- doInitialAllocateContainers(ctx, state);
2842
- }
2843
- if (needsCalculate) {
2844
- calculateItemsInView(ctx, state, { doMVCP: true });
2845
- }
2846
- if (didChange || otherAxisSize !== prevOtherAxisSize) {
2847
- set$(ctx, "scrollSize", { height: layout.height, width: layout.width });
2848
- }
2849
- if (maintainScrollAtEnd === true || maintainScrollAtEnd.onLayout) {
2850
- doMaintainScrollAtEnd(ctx, state, false);
2851
- }
2852
- updateAlignItemsPaddingTop(ctx, state);
2853
- checkAtBottom(ctx, state);
2854
- checkAtTop(state);
2855
- if (state) {
2856
- state.needsOtherAxisSize = otherAxisSize - (state.props.stylePaddingTop || 0) < 10;
2857
- }
2858
- if (IS_DEV && measuredLength === 0) {
2859
- warnDevOnce(
2860
- "height0",
2861
- `List ${state.props.horizontal ? "width" : "height"} is 0. You may need to set a style or \`flex: \` for the list, because children are absolutely positioned.`
2862
- );
2863
- }
2864
- }
2865
- setCanRender(true);
2866
- }
2867
-
2868
- // src/core/onScroll.ts
2869
- function onScroll(ctx, state, event) {
2870
- var _a3, _b, _c;
2871
- const {
2872
- scrollProcessingEnabled,
2873
- props: { onScroll: onScrollProp }
2874
- } = state;
2875
- if (scrollProcessingEnabled === false) {
2876
- return;
2877
- }
2878
- if (((_b = (_a3 = event.nativeEvent) == null ? void 0 : _a3.contentSize) == null ? void 0 : _b.height) === 0 && ((_c = event.nativeEvent.contentSize) == null ? void 0 : _c.width) === 0) {
2879
- return;
2880
- }
2881
- let newScroll = event.nativeEvent.contentOffset[state.props.horizontal ? "x" : "y"];
2882
- state.scrollPending = newScroll;
2883
- const maxOffset = Math.max(0, getContentSize(ctx) - state.scrollLength);
2884
- if (state.initialScroll && newScroll > maxOffset) {
2885
- newScroll = maxOffset;
2886
- scrollTo(ctx, state, {
2887
- noScrollingTo: true,
2888
- offset: newScroll
2889
- });
2890
- }
2891
- updateScroll(ctx, state, newScroll);
2892
- onScrollProp == null ? void 0 : onScrollProp(event);
2893
- }
2894
-
2895
- // src/core/ScrollAdjustHandler.ts
2896
- var ScrollAdjustHandler = class {
2897
- constructor(ctx) {
2898
- this.appliedAdjust = 0;
2899
- this.pendingAdjust = 0;
2900
- this.context = ctx;
2901
- {
2902
- const commitPendingAdjust = () => {
2903
- const state = this.context.internalState;
2904
- const pending = this.pendingAdjust;
2905
- if (pending !== 0) {
2906
- this.pendingAdjust = 0;
2907
- this.appliedAdjust += pending;
2908
- state.scroll += pending;
2909
- state.scrollForNextCalculateItemsInView = void 0;
2910
- set$(this.context, "scrollAdjustPending", 0);
2911
- set$(this.context, "scrollAdjust", this.appliedAdjust);
2912
- calculateItemsInView(this.context, this.context.internalState);
2913
- }
2914
- };
2915
- listen$(this.context, "scrollingTo", (value) => {
2916
- if (value === void 0) {
2917
- commitPendingAdjust();
2918
- }
2919
- });
2920
- }
2921
- }
2922
- requestAdjust(add) {
2923
- const scrollingTo = peek$(this.context, "scrollingTo");
2924
- if ((scrollingTo == null ? void 0 : scrollingTo.animated) && !scrollingTo.isInitialScroll) {
2925
- this.pendingAdjust += add;
2926
- set$(this.context, "scrollAdjustPending", this.pendingAdjust);
2927
- } else {
2928
- this.appliedAdjust += add;
2929
- set$(this.context, "scrollAdjust", this.appliedAdjust);
2930
- }
2931
- }
2932
- getAdjust() {
2933
- return this.appliedAdjust;
2934
- }
2935
- };
2936
-
2937
- // src/core/updateItemSize.ts
2938
- function updateItemSize(ctx, state, itemKey, sizeObj) {
2939
- var _a3;
2940
- const {
2941
- sizesKnown,
2942
- props: {
2943
- getFixedItemSize,
2944
- getItemType,
2945
- horizontal,
2946
- suggestEstimatedItemSize,
2947
- onItemSizeChanged,
2948
- data,
2949
- maintainScrollAtEnd
2950
- }
2951
- } = state;
2952
- if (!data) return;
2953
- const index = state.indexByKey.get(itemKey);
2954
- if (getFixedItemSize) {
2955
- if (index === void 0) {
2956
- return;
2957
- }
2958
- const itemData = state.props.data[index];
2959
- if (itemData === void 0) {
2960
- return;
2961
- }
2962
- const type = getItemType ? (_a3 = getItemType(itemData, index)) != null ? _a3 : "" : "";
2963
- const size2 = getFixedItemSize(index, itemData, type);
2964
- if (size2 !== void 0 && size2 === sizesKnown.get(itemKey)) {
2965
- return;
2966
- }
2967
- }
2968
- const containersDidLayout = peek$(ctx, "containersDidLayout");
2969
- let needsRecalculate = !containersDidLayout;
2970
- let shouldMaintainScrollAtEnd = false;
2971
- let minIndexSizeChanged;
2972
- let maxOtherAxisSize = peek$(ctx, "otherAxisSize") || 0;
2973
- const prevSizeKnown = state.sizesKnown.get(itemKey);
2974
- const diff = updateOneItemSize(ctx, state, itemKey, sizeObj);
2975
- const size = roundSize(horizontal ? sizeObj.width : sizeObj.height);
2976
- if (diff !== 0) {
2977
- minIndexSizeChanged = minIndexSizeChanged !== void 0 ? Math.min(minIndexSizeChanged, index) : index;
2978
- const { startBuffered, endBuffered } = state;
2979
- needsRecalculate || (needsRecalculate = index >= startBuffered && index <= endBuffered);
2980
- if (!needsRecalculate) {
2981
- const numContainers = ctx.values.get("numContainers");
2982
- for (let i = 0; i < numContainers; i++) {
2983
- if (peek$(ctx, `containerItemKey${i}`) === itemKey) {
2984
- needsRecalculate = true;
2985
- break;
2986
- }
2987
- }
2988
- }
2989
- if (state.needsOtherAxisSize) {
2990
- const otherAxisSize = horizontal ? sizeObj.height : sizeObj.width;
2991
- maxOtherAxisSize = Math.max(maxOtherAxisSize, otherAxisSize);
2992
- }
2993
- if (prevSizeKnown !== void 0 && Math.abs(prevSizeKnown - size) > 5) {
2994
- shouldMaintainScrollAtEnd = true;
2995
- }
2996
- onItemSizeChanged == null ? void 0 : onItemSizeChanged({
2997
- index,
2998
- itemData: state.props.data[index],
2999
- itemKey,
3000
- previous: size - diff,
3001
- size
3002
- });
3003
- }
3004
- if (minIndexSizeChanged !== void 0) {
3005
- state.minIndexSizeChanged = state.minIndexSizeChanged !== void 0 ? Math.min(state.minIndexSizeChanged, minIndexSizeChanged) : minIndexSizeChanged;
3006
- }
3007
- if (IS_DEV && suggestEstimatedItemSize && minIndexSizeChanged !== void 0) {
3008
- if (state.timeoutSizeMessage) clearTimeout(state.timeoutSizeMessage);
3009
- state.timeoutSizeMessage = setTimeout(() => {
3010
- var _a4;
3011
- state.timeoutSizeMessage = void 0;
3012
- const num = state.sizesKnown.size;
3013
- const avg = (_a4 = state.averageSizes[""]) == null ? void 0 : _a4.avg;
3014
- console.warn(
3015
- `[legend-list] Based on the ${num} items rendered so far, the optimal estimated size is ${avg}.`
3016
- );
3017
- }, 1e3);
3018
- }
3019
- const cur = peek$(ctx, "otherAxisSize");
3020
- if (!cur || maxOtherAxisSize > cur) {
3021
- set$(ctx, "otherAxisSize", maxOtherAxisSize);
3022
- }
3023
- if (containersDidLayout || checkAllSizesKnown(state)) {
3024
- if (needsRecalculate) {
3025
- state.scrollForNextCalculateItemsInView = void 0;
3026
- calculateItemsInView(ctx, state, { doMVCP: true });
3027
- }
3028
- if (shouldMaintainScrollAtEnd) {
3029
- if (maintainScrollAtEnd === true || maintainScrollAtEnd.onItemLayout) {
3030
- doMaintainScrollAtEnd(ctx, state, false);
3031
- }
3032
- }
3033
- }
3034
- }
3035
- function updateOneItemSize(ctx, state, itemKey, sizeObj) {
3036
- var _a3;
3037
- const {
3038
- indexByKey,
3039
- sizesKnown,
3040
- averageSizes,
3041
- props: { data, horizontal, getEstimatedItemSize, getItemType, getFixedItemSize }
3042
- } = state;
3043
- if (!data) return 0;
3044
- const index = indexByKey.get(itemKey);
3045
- const prevSize = getItemSize(ctx, state, itemKey, index, data[index]);
3046
- const rawSize = horizontal ? sizeObj.width : sizeObj.height;
3047
- const size = Math.round(rawSize) ;
3048
- sizesKnown.set(itemKey, size);
3049
- if (!getEstimatedItemSize && !getFixedItemSize && size > 0) {
3050
- const itemType = getItemType ? (_a3 = getItemType(data[index], index)) != null ? _a3 : "" : "";
3051
- let averages = averageSizes[itemType];
3052
- if (!averages) {
3053
- averages = averageSizes[itemType] = { avg: 0, num: 0 };
3054
- }
3055
- averages.avg = (averages.avg * averages.num + size) / (averages.num + 1);
3056
- averages.num++;
3057
- }
3058
- if (!prevSize || Math.abs(prevSize - size) > 0.1) {
3059
- setSize(ctx, state, itemKey, size);
3060
- return size - prevSize;
3061
- }
3062
- return 0;
3063
- }
3064
- var useCombinedRef = (...refs) => {
3065
- const callback = useCallback((element) => {
3066
- for (const ref of refs) {
3067
- if (!ref) {
3068
- continue;
3069
- }
3070
- if (isFunction(ref)) {
3071
- ref(element);
3072
- } else {
3073
- ref.current = element;
3074
- }
3075
- }
3076
- }, refs);
3077
- return callback;
3078
- };
3079
-
3080
- // src/platform/RefreshControl.tsx
3081
- function RefreshControl(_props) {
3082
- return null;
3083
- }
3084
-
3085
- // src/platform/useStickyScrollHandler.ts
3086
- function useStickyScrollHandler(_stickyHeaderIndices, _horizontal, _ctx, onScroll2) {
3087
- return onScroll2;
3088
- }
3089
-
3090
- // src/utils/createColumnWrapperStyle.ts
3091
- function createColumnWrapperStyle(contentContainerStyle) {
3092
- const { gap, columnGap, rowGap } = contentContainerStyle;
3093
- if (gap || columnGap || rowGap) {
3094
- contentContainerStyle.gap = void 0;
3095
- contentContainerStyle.columnGap = void 0;
3096
- contentContainerStyle.rowGap = void 0;
3097
- return {
3098
- columnGap,
3099
- gap,
3100
- rowGap
3101
- };
3102
- }
3103
- }
3104
-
3105
- // src/utils/createImperativeHandle.ts
3106
- function createImperativeHandle(ctx, state) {
3107
- const scrollIndexIntoView = (options) => {
3108
- if (state) {
3109
- const { index, ...rest } = options;
3110
- const { startNoBuffer, endNoBuffer } = state;
3111
- if (index < startNoBuffer || index > endNoBuffer) {
3112
- const viewPosition = index < startNoBuffer ? 0 : 1;
3113
- scrollToIndex(ctx, state, {
3114
- ...rest,
3115
- index,
3116
- viewPosition
3117
- });
3118
- }
3119
- }
3120
- };
3121
- const refScroller = state.refScroller;
3122
- return {
3123
- flashScrollIndicators: () => refScroller.current.flashScrollIndicators(),
3124
- getNativeScrollRef: () => refScroller.current,
3125
- getScrollableNode: () => refScroller.current.getScrollableNode(),
3126
- getScrollResponder: () => refScroller.current.getScrollResponder(),
3127
- getState: () => ({
3128
- activeStickyIndex: state.activeStickyIndex,
3129
- contentLength: state.totalSize,
3130
- data: state.props.data,
3131
- elementAtIndex: (index) => {
3132
- var _a3;
3133
- return (_a3 = ctx.viewRefs.get(findContainerId(ctx, getId(state, index)))) == null ? void 0 : _a3.current;
3134
- },
3135
- end: state.endNoBuffer,
3136
- endBuffered: state.endBuffered,
3137
- isAtEnd: state.isAtEnd,
3138
- isAtStart: state.isAtStart,
3139
- positionAtIndex: (index) => state.positions.get(getId(state, index)),
3140
- positions: state.positions,
3141
- scroll: state.scroll,
3142
- scrollLength: state.scrollLength,
3143
- sizeAtIndex: (index) => state.sizesKnown.get(getId(state, index)),
3144
- sizes: state.sizesKnown,
3145
- start: state.startNoBuffer,
3146
- startBuffered: state.startBuffered
3147
- }),
3148
- scrollIndexIntoView,
3149
- scrollItemIntoView: ({ item, ...props }) => {
3150
- const data = state.props.data;
3151
- const index = data.indexOf(item);
3152
- if (index !== -1) {
3153
- scrollIndexIntoView({ index, ...props });
3154
- }
3155
- },
3156
- scrollToEnd: (options) => {
3157
- const data = state.props.data;
3158
- const stylePaddingBottom = state.props.stylePaddingBottom;
3159
- const index = data.length - 1;
3160
- if (index !== -1) {
3161
- const paddingBottom = stylePaddingBottom || 0;
3162
- const footerSize = peek$(ctx, "footerSize") || 0;
3163
- scrollToIndex(ctx, state, {
3164
- index,
3165
- viewOffset: -paddingBottom - footerSize + ((options == null ? void 0 : options.viewOffset) || 0),
3166
- viewPosition: 1,
3167
- ...options
3168
- });
3169
- }
3170
- },
3171
- scrollToIndex: (params) => scrollToIndex(ctx, state, params),
3172
- scrollToItem: ({ item, ...props }) => {
3173
- const data = state.props.data;
3174
- const index = data.indexOf(item);
3175
- if (index !== -1) {
3176
- scrollToIndex(ctx, state, { index, ...props });
3177
- }
3178
- },
3179
- scrollToOffset: (params) => scrollTo(ctx, state, params),
3180
- setScrollProcessingEnabled: (enabled) => {
3181
- state.scrollProcessingEnabled = enabled;
3182
- },
3183
- setVisibleContentAnchorOffset: (value) => {
3184
- const val = isFunction(value) ? value(peek$(ctx, "scrollAdjustUserOffset") || 0) : value;
3185
- set$(ctx, "scrollAdjustUserOffset", val);
3186
- }
3187
- };
3188
- }
3189
- function getRenderedItem(ctx, state, key) {
3190
- var _a3;
3191
- if (!state) {
3192
- return null;
3193
- }
3194
- const {
3195
- indexByKey,
3196
- props: { data, getItemType, renderItem }
3197
- } = state;
3198
- const index = indexByKey.get(key);
3199
- if (index === void 0) {
3200
- return null;
3201
- }
3202
- let renderedItem = null;
3203
- const extraData = peek$(ctx, "extraData");
3204
- const item = data[index];
3205
- if (renderItem && !isNullOrUndefined(item)) {
3206
- const itemProps = {
3207
- data,
3208
- extraData,
3209
- index,
3210
- item,
3211
- type: getItemType ? (_a3 = getItemType(item, index)) != null ? _a3 : "" : ""
3212
- };
3213
- renderedItem = isFunction(renderItem) ? renderItem(itemProps) : React3__default.createElement(renderItem, itemProps);
3214
- }
3215
- return { index, item: data[index], renderedItem };
3216
- }
3217
- function useThrottleDebounce(mode) {
3218
- const timeoutRef = useRef(null);
3219
- const lastCallTimeRef = useRef(0);
3220
- const lastArgsRef = useRef(null);
3221
- const clearTimeoutRef = () => {
3222
- if (timeoutRef.current) {
3223
- clearTimeout(timeoutRef.current);
3224
- timeoutRef.current = null;
3225
- }
3226
- };
3227
- const execute = useCallback(
3228
- (callback, delay, ...args) => {
3229
- {
3230
- const now = Date.now();
3231
- lastArgsRef.current = args;
3232
- if (now - lastCallTimeRef.current >= delay) {
3233
- lastCallTimeRef.current = now;
3234
- callback(...args);
3235
- clearTimeoutRef();
3236
- } else {
3237
- clearTimeoutRef();
3238
- timeoutRef.current = setTimeout(
3239
- () => {
3240
- if (lastArgsRef.current) {
3241
- lastCallTimeRef.current = Date.now();
3242
- callback(...lastArgsRef.current);
3243
- timeoutRef.current = null;
3244
- lastArgsRef.current = null;
3245
- }
3246
- },
3247
- delay - (now - lastCallTimeRef.current)
3248
- );
3249
- }
3250
- }
3251
- },
3252
- [mode]
3253
- );
3254
- return execute;
3255
- }
3256
-
3257
- // src/utils/throttledOnScroll.ts
3258
- function useThrottledOnScroll(originalHandler, scrollEventThrottle) {
3259
- const throttle = useThrottleDebounce("throttle");
3260
- return (event) => throttle(originalHandler, scrollEventThrottle, { nativeEvent: event.nativeEvent });
3261
- }
3262
-
3263
- // src/components/LegendList.tsx
3264
- var DEFAULT_DRAW_DISTANCE = 250;
3265
- var DEFAULT_ITEM_SIZE = 100;
3266
- var LegendList = typedMemo(
3267
- // biome-ignore lint/nursery/noShadow: const function name shadowing is intentional
3268
- typedForwardRef(function LegendList2(props, forwardedRef) {
3269
- const { children, data: dataProp, renderItem: renderItemProp, ...restProps } = props;
3270
- const isChildrenMode = children !== void 0 && dataProp === void 0;
3271
- const processedProps = isChildrenMode ? {
3272
- ...restProps,
3273
- childrenMode: true,
3274
- data: (isArray(children) ? children : React3.Children.toArray(children)).flat(1),
3275
- renderItem: ({ item }) => item
3276
- } : {
3277
- ...restProps,
3278
- data: dataProp || [],
3279
- renderItem: renderItemProp
3280
- };
3281
- return /* @__PURE__ */ React3.createElement(StateProvider, null, /* @__PURE__ */ React3.createElement(LegendListInner, { ...processedProps, ref: forwardedRef }));
3282
- })
3283
- );
3284
- var LegendListInner = typedForwardRef(function LegendListInner2(props, forwardedRef) {
3285
- var _a3, _b;
3286
- const {
3287
- alignItemsAtEnd = false,
3288
- columnWrapperStyle,
3289
- contentContainerStyle: contentContainerStyleProp,
3290
- data: dataProp = [],
3291
- dataVersion,
3292
- drawDistance = 250,
3293
- enableAverages = true,
3294
- estimatedItemSize: estimatedItemSizeProp,
3295
- estimatedListSize,
3296
- extraData,
3297
- getEstimatedItemSize,
3298
- getFixedItemSize,
3299
- getItemType,
3300
- horizontal,
3301
- initialContainerPoolRatio = 2,
3302
- initialScrollAtEnd = false,
3303
- initialScrollIndex: initialScrollIndexProp,
3304
- initialScrollOffset: initialScrollOffsetProp,
3305
- itemsAreEqual,
3306
- keyExtractor: keyExtractorProp,
3307
- ListEmptyComponent,
3308
- ListHeaderComponent,
3309
- maintainScrollAtEnd = false,
3310
- maintainScrollAtEndThreshold = 0.1,
3311
- maintainVisibleContentPosition = false,
3312
- numColumns: numColumnsProp = 1,
3313
- onEndReached,
3314
- onEndReachedThreshold = 0.5,
3315
- onItemSizeChanged,
3316
- onLayout: onLayoutProp,
3317
- onLoad,
3318
- onMomentumScrollEnd,
3319
- onRefresh,
3320
- onScroll: onScrollProp,
3321
- onStartReached,
3322
- onStartReachedThreshold = 0.5,
3323
- onStickyHeaderChange,
3324
- onViewableItemsChanged,
3325
- progressViewOffset,
3326
- recycleItems = false,
3327
- refreshControl,
3328
- refreshing,
3329
- refScrollView,
3330
- renderItem,
3331
- scrollEventThrottle,
3332
- snapToIndices,
3333
- stickyHeaderIndices: stickyHeaderIndicesProp,
3334
- stickyIndices: stickyIndicesDeprecated,
3335
- style: styleProp,
3336
- suggestEstimatedItemSize,
3337
- viewabilityConfig,
3338
- viewabilityConfigCallbackPairs,
3339
- waitForInitialLayout = true,
3340
- ...rest
3341
- } = props;
3342
- const { childrenMode } = rest;
3343
- const contentContainerStyle = { ...StyleSheet.flatten(contentContainerStyleProp) };
3344
- const style = { ...StyleSheet.flatten(styleProp) };
3345
- const stylePaddingTopState = extractPadding(style, contentContainerStyle, "Top");
3346
- const stylePaddingBottomState = extractPadding(style, contentContainerStyle, "Bottom");
3347
- const [renderNum, setRenderNum] = useState(0);
3348
- const initialScrollProp = initialScrollAtEnd ? { index: Math.max(0, dataProp.length - 1), viewOffset: -stylePaddingBottomState } : initialScrollIndexProp || initialScrollOffsetProp ? typeof initialScrollIndexProp === "object" ? { index: initialScrollIndexProp.index || 0, viewOffset: initialScrollIndexProp.viewOffset || 0 } : { index: initialScrollIndexProp || 0, viewOffset: initialScrollOffsetProp || 0 } : void 0;
3349
- const [canRender, setCanRender] = React3.useState(!IsNewArchitecture);
3350
- const ctx = useStateContext();
3351
- ctx.columnWrapperStyle = columnWrapperStyle || (contentContainerStyle ? createColumnWrapperStyle(contentContainerStyle) : void 0);
3352
- const refScroller = useRef(null);
3353
- const combinedRef = useCombinedRef(refScroller, refScrollView);
3354
- const estimatedItemSize = estimatedItemSizeProp != null ? estimatedItemSizeProp : DEFAULT_ITEM_SIZE;
3355
- const scrollBuffer = (drawDistance != null ? drawDistance : DEFAULT_DRAW_DISTANCE) || 1;
3356
- const keyExtractor = keyExtractorProp != null ? keyExtractorProp : (_item, index) => index.toString();
3357
- const stickyHeaderIndices = stickyHeaderIndicesProp != null ? stickyHeaderIndicesProp : stickyIndicesDeprecated;
3358
- if (IS_DEV && stickyIndicesDeprecated && !stickyHeaderIndicesProp) {
3359
- warnDevOnce(
3360
- "stickyIndices",
3361
- "stickyIndices has been renamed to stickyHeaderIndices. Please update your props to use stickyHeaderIndices."
3362
- );
3363
- }
3364
- const refState = useRef();
3365
- if (!refState.current) {
3366
- if (!ctx.internalState) {
3367
- const initialScrollLength = (estimatedListSize != null ? estimatedListSize : { height: 0, width: 0 } )[horizontal ? "width" : "height"];
3368
- ctx.internalState = {
3369
- activeStickyIndex: void 0,
3370
- averageSizes: {},
3371
- columns: /* @__PURE__ */ new Map(),
3372
- containerItemKeys: /* @__PURE__ */ new Set(),
3373
- containerItemTypes: /* @__PURE__ */ new Map(),
3374
- dataChangeNeedsScrollUpdate: false,
3375
- didColumnsChange: false,
3376
- didDataChange: false,
3377
- enableScrollForNextCalculateItemsInView: true,
3378
- endBuffered: -1,
3379
- endNoBuffer: -1,
3380
- endReachedSnapshot: void 0,
3381
- firstFullyOnScreenIndex: -1,
3382
- idCache: [],
3383
- idsInView: [],
3384
- indexByKey: /* @__PURE__ */ new Map(),
3385
- initialAnchor: (initialScrollProp == null ? void 0 : initialScrollProp.index) !== void 0 && (initialScrollProp == null ? void 0 : initialScrollProp.viewPosition) !== void 0 ? {
3386
- attempts: 0,
3387
- index: initialScrollProp.index,
3388
- settledTicks: 0,
3389
- viewOffset: (_a3 = initialScrollProp.viewOffset) != null ? _a3 : 0,
3390
- viewPosition: initialScrollProp.viewPosition
3391
- } : void 0,
3392
- initialScroll: initialScrollProp,
3393
- isAtEnd: false,
3394
- isAtStart: false,
3395
- isEndReached: null,
3396
- isFirst: true,
3397
- isStartReached: null,
3398
- lastBatchingAction: Date.now(),
3399
- lastLayout: void 0,
3400
- loadStartTime: Date.now(),
3401
- minIndexSizeChanged: 0,
3402
- nativeMarginTop: 0,
3403
- positions: /* @__PURE__ */ new Map(),
3404
- props: {},
3405
- queuedCalculateItemsInView: 0,
3406
- refScroller: void 0,
3407
- scroll: 0,
3408
- scrollAdjustHandler: new ScrollAdjustHandler(ctx),
3409
- scrollForNextCalculateItemsInView: void 0,
3410
- scrollHistory: [],
3411
- scrollLength: initialScrollLength,
3412
- scrollPending: 0,
3413
- scrollPrev: 0,
3414
- scrollPrevTime: 0,
3415
- scrollProcessingEnabled: true,
3416
- scrollTime: 0,
3417
- sizes: /* @__PURE__ */ new Map(),
3418
- sizesKnown: /* @__PURE__ */ new Map(),
3419
- startBuffered: -1,
3420
- startNoBuffer: -1,
3421
- startReachedSnapshot: void 0,
3422
- stickyContainerPool: /* @__PURE__ */ new Set(),
3423
- stickyContainers: /* @__PURE__ */ new Map(),
3424
- timeoutSizeMessage: 0,
3425
- timeouts: /* @__PURE__ */ new Set(),
3426
- totalSize: 0,
3427
- viewabilityConfigCallbackPairs: void 0
3428
- };
3429
- const internalState = ctx.internalState;
3430
- internalState.triggerCalculateItemsInView = (params) => calculateItemsInView(ctx, internalState, params);
3431
- set$(ctx, "maintainVisibleContentPosition", maintainVisibleContentPosition);
3432
- set$(ctx, "extraData", extraData);
3433
- }
3434
- refState.current = ctx.internalState;
3435
- }
3436
- const state = refState.current;
3437
- const isFirstLocal = state.isFirst;
3438
- state.didColumnsChange = numColumnsProp !== state.props.numColumns;
3439
- const didDataChangeLocal = state.props.dataVersion !== dataVersion || state.props.data !== dataProp && checkActualChange(state, dataProp, state.props.data);
3440
- if (didDataChangeLocal) {
3441
- state.dataChangeNeedsScrollUpdate = true;
3442
- state.didDataChange = true;
3443
- state.previousData = state.props.data;
3444
- }
3445
- const throttleScrollFn = scrollEventThrottle && onScrollProp ? useThrottledOnScroll(onScrollProp, scrollEventThrottle) : onScrollProp;
3446
- state.props = {
3447
- alignItemsAtEnd,
3448
- data: dataProp,
3449
- dataVersion,
3450
- enableAverages,
3451
- estimatedItemSize,
3452
- getEstimatedItemSize,
3453
- getFixedItemSize,
3454
- getItemType,
3455
- horizontal: !!horizontal,
3456
- initialContainerPoolRatio,
3457
- itemsAreEqual,
3458
- keyExtractor,
3459
- maintainScrollAtEnd,
3460
- maintainScrollAtEndThreshold,
3461
- maintainVisibleContentPosition,
3462
- numColumns: numColumnsProp,
3463
- onEndReached,
3464
- onEndReachedThreshold,
3465
- onItemSizeChanged,
3466
- onLoad,
3467
- onScroll: throttleScrollFn,
3468
- onStartReached,
3469
- onStartReachedThreshold,
3470
- onStickyHeaderChange,
3471
- recycleItems: !!recycleItems,
3472
- renderItem,
3473
- scrollBuffer,
3474
- snapToIndices,
3475
- stickyIndicesArr: stickyHeaderIndices != null ? stickyHeaderIndices : [],
3476
- stickyIndicesSet: useMemo(() => new Set(stickyHeaderIndices != null ? stickyHeaderIndices : []), [stickyHeaderIndices == null ? void 0 : stickyHeaderIndices.join(",")]),
3477
- stylePaddingBottom: stylePaddingBottomState,
3478
- stylePaddingTop: stylePaddingTopState,
3479
- suggestEstimatedItemSize: !!suggestEstimatedItemSize
3480
- };
3481
- state.refScroller = refScroller;
3482
- const memoizedLastItemKeys = useMemo(() => {
3483
- if (!dataProp.length) return [];
3484
- return Array.from(
3485
- { length: Math.min(numColumnsProp, dataProp.length) },
3486
- (_, i) => getId(state, dataProp.length - 1 - i)
3487
- );
3488
- }, [dataProp, dataVersion, numColumnsProp]);
3489
- const initializeStateVars = () => {
3490
- set$(ctx, "lastItemKeys", memoizedLastItemKeys);
3491
- set$(ctx, "numColumns", numColumnsProp);
3492
- const prevPaddingTop = peek$(ctx, "stylePaddingTop");
3493
- setPaddingTop(ctx, state, { stylePaddingTop: stylePaddingTopState });
3494
- refState.current.props.stylePaddingBottom = stylePaddingBottomState;
3495
- let paddingDiff = stylePaddingTopState - prevPaddingTop;
3496
- if (paddingDiff && prevPaddingTop !== void 0 && Platform.OS === "ios") {
3497
- if (state.scroll < 0) {
3498
- paddingDiff += state.scroll;
3499
- }
3500
- requestAdjust(ctx, state, paddingDiff);
3501
- }
3502
- };
3503
- if (isFirstLocal) {
3504
- initializeStateVars();
3505
- updateItemPositions(
3506
- ctx,
3507
- state,
3508
- /*dataChanged*/
3509
- true
3510
- );
3511
- }
3512
- const initialContentOffset = useMemo(() => {
3513
- var _a4, _b2;
3514
- const { initialScroll } = refState.current;
3515
- if (!initialScroll) {
3516
- refState.current.initialAnchor = void 0;
3517
- return 0;
3518
- }
3519
- if (initialScroll.index !== void 0 && (!refState.current.initialAnchor || ((_a4 = refState.current.initialAnchor) == null ? void 0 : _a4.index) !== initialScroll.index)) {
3520
- refState.current.initialAnchor = {
3521
- attempts: 0,
3522
- index: initialScroll.index,
3523
- settledTicks: 0,
3524
- viewOffset: (_b2 = initialScroll.viewOffset) != null ? _b2 : 0,
3525
- viewPosition: initialScroll.viewPosition
3526
- };
3527
- }
3528
- if (initialScroll.contentOffset !== void 0) {
3529
- return initialScroll.contentOffset;
3530
- }
3531
- const baseOffset = initialScroll.index !== void 0 ? calculateOffsetForIndex(ctx, state, initialScroll.index) : 0;
3532
- const resolvedOffset = calculateOffsetWithOffsetPosition(ctx, state, baseOffset, initialScroll);
3533
- let clampedOffset = resolvedOffset;
3534
- if (Number.isFinite(state.scrollLength) && Number.isFinite(state.totalSize)) {
3535
- const maxOffset = Math.max(0, state.totalSize - state.scrollLength);
3536
- clampedOffset = Math.min(clampedOffset, maxOffset);
3537
- }
3538
- clampedOffset = Math.max(0, clampedOffset);
3539
- const updatedInitialScroll = { ...initialScroll, contentOffset: clampedOffset };
3540
- refState.current.initialScroll = updatedInitialScroll;
3541
- state.initialScroll = updatedInitialScroll;
3542
- return clampedOffset;
3543
- }, [renderNum]);
3544
- if (isFirstLocal || didDataChangeLocal || numColumnsProp !== peek$(ctx, "numColumns")) {
3545
- refState.current.lastBatchingAction = Date.now();
3546
- if (!keyExtractorProp && !isFirstLocal && didDataChangeLocal) {
3547
- IS_DEV && !childrenMode && warnDevOnce(
3548
- "keyExtractor",
3549
- "Changing data without a keyExtractor can cause slow performance and resetting scroll. If your list data can change you should use a keyExtractor with a unique id for best performance and behavior."
3550
- );
3551
- refState.current.sizes.clear();
3552
- refState.current.positions.clear();
3553
- refState.current.totalSize = 0;
3554
- set$(ctx, "totalSize", 0);
3555
- }
3556
- }
3557
- const onLayoutHeader = useCallback((rect, fromLayoutEffect) => {
3558
- const { initialScroll } = refState.current;
3559
- const size = rect[horizontal ? "width" : "height"];
3560
- set$(ctx, "headerSize", size);
3561
- if ((initialScroll == null ? void 0 : initialScroll.index) !== void 0) {
3562
- {
3563
- if (fromLayoutEffect) {
3564
- setRenderNum((v) => v + 1);
3565
- }
3566
- }
3567
- }
3568
- }, []);
3569
- const doInitialScroll = useCallback(() => {
3570
- var _a4;
3571
- const initialScroll = state.initialScroll;
3572
- if (initialScroll) {
3573
- scrollTo(ctx, state, {
3574
- animated: false,
3575
- index: (_a4 = state.initialScroll) == null ? void 0 : _a4.index,
3576
- isInitialScroll: true,
3577
- offset: initialContentOffset,
3578
- precomputedWithViewOffset: true
3579
- });
3580
- {
3581
- const unlisten = listen$(ctx, "containersDidLayout", (value) => {
3582
- if (value && peek$(ctx, "scrollingTo")) {
3583
- finishScrollTo(ctx, state);
3584
- unlisten();
3585
- }
3586
- });
3587
- }
3588
- }
3589
- }, [initialContentOffset]);
3590
- const onLayoutChange = useCallback((layout) => {
3591
- doInitialScroll();
3592
- handleLayout(ctx, state, layout, setCanRender);
3593
- }, []);
3594
- const { onLayout } = useOnLayoutSync({
3595
- onLayoutChange,
3596
- onLayoutProp,
3597
- ref: refScroller
3598
- // the type of ScrollView doesn't include measure?
3599
- });
3600
- useLayoutEffect(() => {
3601
- if (snapToIndices) {
3602
- updateSnapToOffsets(ctx, state);
3603
- }
3604
- }, [snapToIndices]);
3605
- useLayoutEffect(() => {
3606
- const {
3607
- didColumnsChange,
3608
- didDataChange,
3609
- isFirst,
3610
- props: { data }
3611
- } = state;
3612
- const didAllocateContainers = data.length > 0 && doInitialAllocateContainers(ctx, state);
3613
- if (!didAllocateContainers && !isFirst && (didDataChange || didColumnsChange)) {
3614
- checkResetContainers(ctx, state, data);
3615
- }
3616
- state.didColumnsChange = false;
3617
- state.didDataChange = false;
3618
- state.isFirst = false;
3619
- }, [dataProp, dataVersion, numColumnsProp]);
3620
- useLayoutEffect(() => {
3621
- set$(ctx, "extraData", extraData);
3622
- }, [extraData]);
3623
- useLayoutEffect(initializeStateVars, [
3624
- dataVersion,
3625
- memoizedLastItemKeys.join(","),
3626
- numColumnsProp,
3627
- stylePaddingBottomState,
3628
- stylePaddingTopState
3629
- ]);
3630
- useEffect(() => {
3631
- const viewability = setupViewability({
3632
- onViewableItemsChanged,
3633
- viewabilityConfig,
3634
- viewabilityConfigCallbackPairs
3635
- });
3636
- state.viewabilityConfigCallbackPairs = viewability;
3637
- state.enableScrollForNextCalculateItemsInView = !viewability;
3638
- }, [viewabilityConfig, viewabilityConfigCallbackPairs, onViewableItemsChanged]);
3639
- useImperativeHandle(forwardedRef, () => createImperativeHandle(ctx, state), []);
3640
- {
3641
- useEffect(doInitialScroll, []);
3642
- }
3643
- const fns = useMemo(
3644
- () => ({
3645
- getRenderedItem: (key) => getRenderedItem(ctx, state, key),
3646
- onScroll: (event) => onScroll(ctx, state, event),
3647
- updateItemSize: (itemKey, sizeObj) => updateItemSize(ctx, state, itemKey, sizeObj)
3648
- }),
3649
- []
3650
- );
3651
- const onScrollHandler = useStickyScrollHandler(stickyHeaderIndices, horizontal, ctx, fns.onScroll);
3652
- return /* @__PURE__ */ React3.createElement(React3.Fragment, null, /* @__PURE__ */ React3.createElement(
3653
- ListComponent,
3654
- {
3655
- ...rest,
3656
- alignItemsAtEnd,
3657
- canRender,
3658
- contentContainerStyle,
3659
- getRenderedItem: fns.getRenderedItem,
3660
- horizontal,
3661
- initialContentOffset,
3662
- ListEmptyComponent: dataProp.length === 0 ? ListEmptyComponent : void 0,
3663
- ListHeaderComponent,
3664
- maintainVisibleContentPosition,
3665
- onLayout,
3666
- onLayoutHeader,
3667
- onMomentumScrollEnd: (event) => {
3668
- {
3669
- requestAnimationFrame(() => {
3670
- finishScrollTo(ctx, refState.current);
3671
- });
3672
- }
3673
- if (onMomentumScrollEnd) {
3674
- onMomentumScrollEnd(event);
3675
- }
3676
- },
3677
- onScroll: onScrollHandler,
3678
- recycleItems,
3679
- refreshControl: refreshControl ? stylePaddingTopState > 0 ? React3.cloneElement(refreshControl, {
3680
- progressViewOffset: (refreshControl.props.progressViewOffset || 0) + stylePaddingTopState
3681
- }) : refreshControl : onRefresh && /* @__PURE__ */ React3.createElement(
3682
- RefreshControl,
3683
- {
3684
- onRefresh,
3685
- progressViewOffset: (progressViewOffset || 0) + stylePaddingTopState,
3686
- refreshing: !!refreshing
3687
- }
3688
- ),
3689
- refScrollView: combinedRef,
3690
- scrollAdjustHandler: (_b = refState.current) == null ? void 0 : _b.scrollAdjustHandler,
3691
- scrollEventThrottle: 16 ,
3692
- snapToIndices,
3693
- stickyHeaderIndices,
3694
- style,
3695
- updateItemSize: fns.updateItemSize,
3696
- waitForInitialLayout
3697
- }
3698
- ), IS_DEV && ENABLE_DEBUG_VIEW && /* @__PURE__ */ React3.createElement(DebugView, { state: refState.current }));
3699
- });
3700
6
 
3701
7
  // src/section-list/flattenSections.ts
3702
8
  var defaultKeyExtractor = (item, index) => {
3703
- var _a3;
3704
- const key = (_a3 = item == null ? void 0 : item.key) != null ? _a3 : item == null ? void 0 : item.id;
9
+ var _a;
10
+ const key = (_a = item == null ? void 0 : item.key) != null ? _a : item == null ? void 0 : item.id;
3705
11
  return key != null ? String(key) : String(index);
3706
12
  };
3707
13
  var getSectionKey = (section, sectionIndex) => {
3708
- var _a3;
3709
- return (_a3 = section.key) != null ? _a3 : `section-${sectionIndex}`;
14
+ var _a;
15
+ return (_a = section.key) != null ? _a : `section-${sectionIndex}`;
3710
16
  };
3711
17
  function buildSectionListData({
3712
18
  sections,
@@ -3717,14 +23,14 @@ function buildSectionListData({
3717
23
  stickySectionHeadersEnabled,
3718
24
  keyExtractor = defaultKeyExtractor
3719
25
  }) {
3720
- var _a3, _b;
26
+ var _a, _b;
3721
27
  const data = [];
3722
28
  const sectionMeta = [];
3723
29
  const stickyHeaderIndices = [];
3724
30
  let absoluteItemIndex = 0;
3725
31
  for (let sectionIndex = 0; sectionIndex < sections.length; sectionIndex++) {
3726
32
  const section = sections[sectionIndex];
3727
- const items = (_a3 = section.data) != null ? _a3 : [];
33
+ const items = (_a = section.data) != null ? _a : [];
3728
34
  const meta = { items: [] };
3729
35
  const sectionKey = getSectionKey(section, sectionIndex);
3730
36
  const hasHeader = typeof renderSectionHeader === "function";
@@ -3795,6 +101,7 @@ function buildSectionListData({
3795
101
  }
3796
102
 
3797
103
  // src/section-list/SectionList.tsx
104
+ var { typedForwardRef, typedMemo } = internal;
3798
105
  var defaultSeparators = {
3799
106
  highlight: () => {
3800
107
  },
@@ -3805,11 +112,11 @@ var defaultSeparators = {
3805
112
  };
3806
113
  function resolveSeparatorComponent(component, props) {
3807
114
  if (!component) return null;
3808
- if (React3.isValidElement(component)) {
115
+ if (React.isValidElement(component)) {
3809
116
  return component;
3810
117
  }
3811
118
  const Component = component;
3812
- return /* @__PURE__ */ React3.createElement(Component, { ...props });
119
+ return /* @__PURE__ */ React.createElement(Component, { ...props });
3813
120
  }
3814
121
  var SectionList = typedMemo(
3815
122
  typedForwardRef(function SectionListInner(props, ref) {
@@ -3820,15 +127,15 @@ var SectionList = typedMemo(
3820
127
  renderSectionFooter,
3821
128
  ItemSeparatorComponent,
3822
129
  SectionSeparatorComponent,
3823
- stickySectionHeadersEnabled = Platform$1.OS === "ios",
130
+ stickySectionHeadersEnabled = Platform.OS === "ios",
3824
131
  keyExtractor,
3825
132
  extraData,
3826
133
  onViewableItemsChanged,
3827
134
  horizontal,
3828
135
  ...restProps
3829
136
  } = props;
3830
- const legendListRef = React3.useRef(null);
3831
- const flattened = React3.useMemo(
137
+ const legendListRef = React.useRef(null);
138
+ const flattened = React.useMemo(
3832
139
  () => buildSectionListData({
3833
140
  ItemSeparatorComponent,
3834
141
  keyExtractor,
@@ -3851,11 +158,15 @@ var SectionList = typedMemo(
3851
158
  ]
3852
159
  );
3853
160
  const { data, sectionMeta, stickyHeaderIndices } = flattened;
3854
- const handleViewableItemsChanged = React3.useMemo(() => {
161
+ const handleViewableItemsChanged = React.useMemo(() => {
3855
162
  if (!onViewableItemsChanged) return void 0;
3856
163
  return ({
3857
164
  viewableItems,
3858
- changed
165
+ changed,
166
+ start,
167
+ end,
168
+ startBuffered,
169
+ endBuffered
3859
170
  }) => {
3860
171
  const mapToken = (token) => {
3861
172
  if (token.item.kind !== "item") return null;
@@ -3869,19 +180,26 @@ var SectionList = typedMemo(
3869
180
  };
3870
181
  const mappedViewable = viewableItems.map(mapToken).filter(Boolean);
3871
182
  const mappedChanged = changed.map(mapToken).filter(Boolean);
3872
- onViewableItemsChanged({ changed: mappedChanged, viewableItems: mappedViewable });
183
+ onViewableItemsChanged({
184
+ changed: mappedChanged,
185
+ end,
186
+ endBuffered,
187
+ start,
188
+ startBuffered,
189
+ viewableItems: mappedViewable
190
+ });
3873
191
  };
3874
192
  }, [onViewableItemsChanged]);
3875
- const renderItem = React3.useCallback(
193
+ const renderItem = React.useCallback(
3876
194
  ({ item }) => {
3877
- var _a3, _b;
195
+ var _a, _b;
3878
196
  switch (item.kind) {
3879
197
  case "header":
3880
198
  return renderSectionHeader ? renderSectionHeader({ section: item.section }) : null;
3881
199
  case "footer":
3882
200
  return renderSectionFooter ? renderSectionFooter({ section: item.section }) : null;
3883
201
  case "item": {
3884
- const render = (_a3 = item.section.renderItem) != null ? _a3 : renderItemProp;
202
+ const render = (_a = item.section.renderItem) != null ? _a : renderItemProp;
3885
203
  if (!render) return null;
3886
204
  return render({
3887
205
  index: item.itemIndex,
@@ -3920,12 +238,12 @@ var SectionList = typedMemo(
3920
238
  renderSectionHeader
3921
239
  ]
3922
240
  );
3923
- const scrollToLocation = React3.useCallback(
241
+ const scrollToLocation = React.useCallback(
3924
242
  ({ sectionIndex, itemIndex, viewOffset, viewPosition, animated }) => {
3925
- var _a3, _b, _c;
243
+ var _a, _b, _c;
3926
244
  const meta = sectionMeta[sectionIndex];
3927
245
  if (!meta) return;
3928
- const target = itemIndex === -1 ? (_b = (_a3 = meta.header) != null ? _a3 : meta.items[0]) != null ? _b : meta.footer : meta.items[itemIndex];
246
+ const target = itemIndex === -1 ? (_b = (_a = meta.header) != null ? _a : meta.items[0]) != null ? _b : meta.footer : meta.items[itemIndex];
3929
247
  if (target === void 0) return;
3930
248
  (_c = legendListRef.current) == null ? void 0 : _c.scrollToIndex({
3931
249
  animated,
@@ -3936,7 +254,7 @@ var SectionList = typedMemo(
3936
254
  },
3937
255
  [sectionMeta]
3938
256
  );
3939
- React3.useImperativeHandle(
257
+ React.useImperativeHandle(
3940
258
  ref,
3941
259
  () => ({
3942
260
  ...legendListRef.current,
@@ -3944,7 +262,7 @@ var SectionList = typedMemo(
3944
262
  }),
3945
263
  [scrollToLocation]
3946
264
  );
3947
- return /* @__PURE__ */ React3.createElement(
265
+ return /* @__PURE__ */ React.createElement(
3948
266
  LegendList,
3949
267
  {
3950
268
  ...restProps,