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

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