@legendapp/list 2.1.0-beta.0 → 2.1.0-beta.10

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