@legendapp/list 2.1.0-next.1 → 3.0.0-beta.1

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