@legendapp/list 2.1.0-beta.5 → 2.1.0-beta.7

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