@legendapp/list 3.0.0-beta.4 → 3.0.0-beta.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/.DS_Store +0 -0
  2. package/CHANGELOG.md +19 -0
  3. package/README.md +9 -2
  4. package/animated.d.ts +620 -5
  5. package/animated.js +2 -2
  6. package/animated.mjs +1 -1
  7. package/index.d.ts +1227 -11
  8. package/index.js +2594 -1023
  9. package/index.mjs +2593 -1024
  10. package/index.native.js +2347 -961
  11. package/index.native.mjs +2327 -943
  12. package/keyboard-test.d.ts +206 -0
  13. package/keyboard-test.js +34 -0
  14. package/keyboard-test.mjs +13 -0
  15. package/keyboard.d.ts +206 -8
  16. package/keyboard.js +340 -32
  17. package/keyboard.mjs +343 -34
  18. package/package.json +62 -1
  19. package/{types-JPHClxiw.d.mts → react-native.d.ts} +436 -158
  20. package/react-native.js +4942 -0
  21. package/react-native.mjs +4911 -0
  22. package/{types-JPHClxiw.d.ts → react-native.web.d.ts} +493 -158
  23. package/react-native.web.js +5357 -0
  24. package/react-native.web.mjs +5326 -0
  25. package/{types-YNdphn_A.d.mts → react.d.ts} +493 -158
  26. package/react.js +5357 -0
  27. package/react.mjs +5326 -0
  28. package/reanimated.d.ts +631 -7
  29. package/reanimated.js +156 -30
  30. package/reanimated.mjs +155 -29
  31. package/section-list.d.ts +620 -5
  32. package/section-list.js +38 -3679
  33. package/section-list.mjs +34 -3676
  34. package/animated.d.mts +0 -9
  35. package/index.d.mts +0 -23
  36. package/index.native.d.mts +0 -23
  37. package/index.native.d.ts +0 -23
  38. package/keyboard-controller.d.mts +0 -12
  39. package/keyboard-controller.d.ts +0 -12
  40. package/keyboard-controller.js +0 -69
  41. package/keyboard-controller.mjs +0 -48
  42. package/keyboard.d.mts +0 -13
  43. package/reanimated.d.mts +0 -18
  44. package/section-list.d.mts +0 -113
  45. package/section-list.native.d.mts +0 -113
  46. package/section-list.native.d.ts +0 -113
  47. package/section-list.native.js +0 -3700
  48. package/section-list.native.mjs +0 -3679
  49. package/types-YNdphn_A.d.ts +0 -670
@@ -0,0 +1,4911 @@
1
+ import * as React2 from 'react';
2
+ import React2__default, { useReducer, useEffect, createContext, useRef, useState, useMemo, useCallback, useLayoutEffect, useImperativeHandle, useContext } from 'react';
3
+ import * as ReactNative from 'react-native';
4
+ import { Animated, View as View$1, Text as Text$1, Platform, StyleSheet as StyleSheet$1, RefreshControl, Dimensions } from 'react-native';
5
+ import { useSyncExternalStore } from 'use-sync-external-store/shim';
6
+
7
+ // src/components/LegendList.tsx
8
+ Animated.View;
9
+ var View = View$1;
10
+ var Text = Text$1;
11
+
12
+ // src/state/getContentInsetEnd.ts
13
+ function getContentInsetEnd(state) {
14
+ var _a3;
15
+ const { props } = state;
16
+ const horizontal = props.horizontal;
17
+ const contentInset = props.contentInset;
18
+ const baseInset = contentInset != null ? contentInset : state.nativeContentInset;
19
+ const overrideInset = (_a3 = state.contentInsetOverride) != null ? _a3 : void 0;
20
+ if (overrideInset) {
21
+ const mergedInset = { bottom: 0, right: 0, ...baseInset, ...overrideInset };
22
+ return (horizontal ? mergedInset.right : mergedInset.bottom) || 0;
23
+ }
24
+ if (baseInset) {
25
+ return (horizontal ? baseInset.right : baseInset.bottom) || 0;
26
+ }
27
+ return 0;
28
+ }
29
+
30
+ // src/state/getContentSize.ts
31
+ function getContentSize(ctx) {
32
+ var _a3;
33
+ const { values, state } = ctx;
34
+ const stylePaddingTop = values.get("stylePaddingTop") || 0;
35
+ const stylePaddingBottom = state.props.stylePaddingBottom || 0;
36
+ const headerSize = values.get("headerSize") || 0;
37
+ const footerSize = values.get("footerSize") || 0;
38
+ const contentInsetBottom = getContentInsetEnd(state);
39
+ const totalSize = (_a3 = state.pendingTotalSize) != null ? _a3 : values.get("totalSize");
40
+ return headerSize + footerSize + totalSize + stylePaddingTop + stylePaddingBottom + (contentInsetBottom || 0);
41
+ }
42
+ var createAnimatedValue = (value) => new Animated.Value(value);
43
+
44
+ // src/state/state.tsx
45
+ var ContextState = React2.createContext(null);
46
+ var contextNum = 0;
47
+ function StateProvider({ children }) {
48
+ const [value] = React2.useState(() => ({
49
+ animatedScrollY: createAnimatedValue(0),
50
+ columnWrapperStyle: void 0,
51
+ contextNum: contextNum++,
52
+ listeners: /* @__PURE__ */ new Map(),
53
+ mapViewabilityAmountCallbacks: /* @__PURE__ */ new Map(),
54
+ mapViewabilityAmountValues: /* @__PURE__ */ new Map(),
55
+ mapViewabilityCallbacks: /* @__PURE__ */ new Map(),
56
+ mapViewabilityConfigStates: /* @__PURE__ */ new Map(),
57
+ mapViewabilityValues: /* @__PURE__ */ new Map(),
58
+ positionListeners: /* @__PURE__ */ new Map(),
59
+ state: void 0,
60
+ values: /* @__PURE__ */ new Map([
61
+ ["stylePaddingTop", 0],
62
+ ["headerSize", 0],
63
+ ["numContainers", 0],
64
+ ["activeStickyIndex", -1],
65
+ ["totalSize", 0],
66
+ ["scrollAdjustPending", 0]
67
+ ]),
68
+ viewRefs: /* @__PURE__ */ new Map()
69
+ }));
70
+ return /* @__PURE__ */ React2.createElement(ContextState.Provider, { value }, children);
71
+ }
72
+ function useStateContext() {
73
+ return React2.useContext(ContextState);
74
+ }
75
+ function createSelectorFunctionsArr(ctx, signalNames) {
76
+ let lastValues = [];
77
+ let lastSignalValues = [];
78
+ return {
79
+ get: () => {
80
+ const currentValues = [];
81
+ let hasChanged = false;
82
+ for (let i = 0; i < signalNames.length; i++) {
83
+ const value = peek$(ctx, signalNames[i]);
84
+ currentValues.push(value);
85
+ if (value !== lastSignalValues[i]) {
86
+ hasChanged = true;
87
+ }
88
+ }
89
+ lastSignalValues = currentValues;
90
+ if (hasChanged) {
91
+ lastValues = currentValues;
92
+ }
93
+ return lastValues;
94
+ },
95
+ subscribe: (cb) => {
96
+ const listeners = [];
97
+ for (const signalName of signalNames) {
98
+ listeners.push(listen$(ctx, signalName, cb));
99
+ }
100
+ return () => {
101
+ for (const listener of listeners) {
102
+ listener();
103
+ }
104
+ };
105
+ }
106
+ };
107
+ }
108
+ function listen$(ctx, signalName, cb) {
109
+ const { listeners } = ctx;
110
+ let setListeners = listeners.get(signalName);
111
+ if (!setListeners) {
112
+ setListeners = /* @__PURE__ */ new Set();
113
+ listeners.set(signalName, setListeners);
114
+ }
115
+ setListeners.add(cb);
116
+ return () => setListeners.delete(cb);
117
+ }
118
+ function peek$(ctx, signalName) {
119
+ const { values } = ctx;
120
+ return values.get(signalName);
121
+ }
122
+ function set$(ctx, signalName, value) {
123
+ const { listeners, values } = ctx;
124
+ if (values.get(signalName) !== value) {
125
+ values.set(signalName, value);
126
+ const setListeners = listeners.get(signalName);
127
+ if (setListeners) {
128
+ for (const listener of setListeners) {
129
+ listener(value);
130
+ }
131
+ }
132
+ }
133
+ }
134
+ function listenPosition$(ctx, key, cb) {
135
+ const { positionListeners } = ctx;
136
+ let setListeners = positionListeners.get(key);
137
+ if (!setListeners) {
138
+ setListeners = /* @__PURE__ */ new Set();
139
+ positionListeners.set(key, setListeners);
140
+ }
141
+ setListeners.add(cb);
142
+ return () => setListeners.delete(cb);
143
+ }
144
+ function notifyPosition$(ctx, key, value) {
145
+ const { positionListeners } = ctx;
146
+ const setListeners = positionListeners.get(key);
147
+ if (setListeners) {
148
+ for (const listener of setListeners) {
149
+ listener(value);
150
+ }
151
+ }
152
+ }
153
+ function useArr$(signalNames) {
154
+ const ctx = React2.useContext(ContextState);
155
+ const { subscribe, get } = React2.useMemo(() => createSelectorFunctionsArr(ctx, signalNames), [ctx, signalNames]);
156
+ const value = useSyncExternalStore(subscribe, get);
157
+ return value;
158
+ }
159
+ function useSelector$(signalName, selector) {
160
+ const ctx = React2.useContext(ContextState);
161
+ const { subscribe, get } = React2.useMemo(() => createSelectorFunctionsArr(ctx, [signalName]), [ctx, signalName]);
162
+ const value = useSyncExternalStore(subscribe, () => selector(get()[0]));
163
+ return value;
164
+ }
165
+
166
+ // src/components/DebugView.tsx
167
+ var DebugRow = ({ children }) => {
168
+ return /* @__PURE__ */ React2.createElement(View, { style: { alignItems: "center", flexDirection: "row", justifyContent: "space-between" } }, children);
169
+ };
170
+ React2.memo(function DebugView2({ state }) {
171
+ const ctx = useStateContext();
172
+ const [totalSize = 0, scrollAdjust = 0, rawScroll = 0, scroll = 0, _numContainers = 0, _numContainersPooled = 0] = useArr$([
173
+ "totalSize",
174
+ "scrollAdjust",
175
+ "debugRawScroll",
176
+ "debugComputedScroll",
177
+ "numContainers",
178
+ "numContainersPooled"
179
+ ]);
180
+ const contentSize = getContentSize(ctx);
181
+ const [, forceUpdate] = useReducer((x) => x + 1, 0);
182
+ useInterval(() => {
183
+ forceUpdate();
184
+ }, 100);
185
+ return /* @__PURE__ */ React2.createElement(
186
+ View,
187
+ {
188
+ pointerEvents: "none",
189
+ style: {
190
+ // height: 100,
191
+ backgroundColor: "#FFFFFFCC",
192
+ borderRadius: 4,
193
+ padding: 4,
194
+ paddingBottom: 4,
195
+ paddingLeft: 4,
196
+ position: "absolute",
197
+ right: 0,
198
+ top: 0
199
+ }
200
+ },
201
+ /* @__PURE__ */ React2.createElement(DebugRow, null, /* @__PURE__ */ React2.createElement(Text, null, "TotalSize:"), /* @__PURE__ */ React2.createElement(Text, null, totalSize.toFixed(2))),
202
+ /* @__PURE__ */ React2.createElement(DebugRow, null, /* @__PURE__ */ React2.createElement(Text, null, "ContentSize:"), /* @__PURE__ */ React2.createElement(Text, null, contentSize.toFixed(2))),
203
+ /* @__PURE__ */ React2.createElement(DebugRow, null, /* @__PURE__ */ React2.createElement(Text, null, "At end:"), /* @__PURE__ */ React2.createElement(Text, null, String(state.isAtEnd))),
204
+ /* @__PURE__ */ React2.createElement(DebugRow, null, /* @__PURE__ */ React2.createElement(Text, null, "ScrollAdjust:"), /* @__PURE__ */ React2.createElement(Text, null, scrollAdjust.toFixed(2))),
205
+ /* @__PURE__ */ React2.createElement(DebugRow, null, /* @__PURE__ */ React2.createElement(Text, null, "RawScroll: "), /* @__PURE__ */ React2.createElement(Text, null, rawScroll.toFixed(2))),
206
+ /* @__PURE__ */ React2.createElement(DebugRow, null, /* @__PURE__ */ React2.createElement(Text, null, "ComputedScroll: "), /* @__PURE__ */ React2.createElement(Text, null, scroll.toFixed(2)))
207
+ );
208
+ });
209
+ function useInterval(callback, delay) {
210
+ useEffect(() => {
211
+ const interval = setInterval(callback, delay);
212
+ return () => clearInterval(interval);
213
+ }, [delay]);
214
+ }
215
+
216
+ // src/utils/devEnvironment.ts
217
+ var metroDev = typeof __DEV__ !== "undefined" ? __DEV__ : void 0;
218
+ var _a;
219
+ var envMode = typeof process !== "undefined" && typeof process.env === "object" && process.env ? (_a = process.env.NODE_ENV) != null ? _a : process.env.MODE : void 0;
220
+ var processDev = typeof envMode === "string" ? envMode.toLowerCase() !== "production" : void 0;
221
+ var _a2;
222
+ var IS_DEV = (_a2 = processDev != null ? processDev : metroDev) != null ? _a2 : false;
223
+
224
+ // src/constants.ts
225
+ var POSITION_OUT_OF_VIEW = -1e7;
226
+ var ENABLE_DEVMODE = IS_DEV && false;
227
+ var ENABLE_DEBUG_VIEW = IS_DEV && false;
228
+
229
+ // src/constants-platform.native.ts
230
+ var f = global.nativeFabricUIManager;
231
+ var IsNewArchitecture = f !== void 0 && f != null;
232
+ var useAnimatedValue = (initialValue) => {
233
+ const [animAnimatedValue] = useState(() => new Animated.Value(initialValue));
234
+ return animAnimatedValue;
235
+ };
236
+
237
+ // src/utils/helpers.ts
238
+ function isFunction(obj) {
239
+ return typeof obj === "function";
240
+ }
241
+ function isArray(obj) {
242
+ return Array.isArray(obj);
243
+ }
244
+ var warned = /* @__PURE__ */ new Set();
245
+ function warnDevOnce(id, text) {
246
+ if (IS_DEV && !warned.has(id)) {
247
+ warned.add(id);
248
+ console.warn(`[legend-list] ${text}`);
249
+ }
250
+ }
251
+ function roundSize(size) {
252
+ return Math.floor(size * 8) / 8;
253
+ }
254
+ function isNullOrUndefined(value) {
255
+ return value === null || value === void 0;
256
+ }
257
+ function comparatorDefault(a, b) {
258
+ return a - b;
259
+ }
260
+ function getPadding(s, type) {
261
+ var _a3, _b, _c;
262
+ return (_c = (_b = (_a3 = s[`padding${type}`]) != null ? _a3 : s.paddingVertical) != null ? _b : s.padding) != null ? _c : 0;
263
+ }
264
+ function extractPadding(style, contentContainerStyle, type) {
265
+ return getPadding(style, type) + getPadding(contentContainerStyle, type);
266
+ }
267
+ function findContainerId(ctx, key) {
268
+ var _a3, _b;
269
+ const directMatch = (_b = (_a3 = ctx.state) == null ? void 0 : _a3.containerItemKeys) == null ? void 0 : _b.get(key);
270
+ if (directMatch !== void 0) {
271
+ return directMatch;
272
+ }
273
+ const numContainers = peek$(ctx, "numContainers");
274
+ for (let i = 0; i < numContainers; i++) {
275
+ const itemKey = peek$(ctx, `containerItemKey${i}`);
276
+ if (itemKey === key) {
277
+ return i;
278
+ }
279
+ }
280
+ return -1;
281
+ }
282
+
283
+ // src/hooks/useValue$.ts
284
+ function useValue$(key, params) {
285
+ const { getValue, delay } = params || {};
286
+ const ctx = useStateContext();
287
+ const getNewValue = () => {
288
+ var _a3;
289
+ return (_a3 = getValue ? getValue(peek$(ctx, key)) : peek$(ctx, key)) != null ? _a3 : 0;
290
+ };
291
+ const animValue = useAnimatedValue(getNewValue());
292
+ useMemo(() => {
293
+ let prevValue;
294
+ let didQueueTask = false;
295
+ listen$(ctx, key, () => {
296
+ const newValue = getNewValue();
297
+ if (delay !== void 0) {
298
+ const fn = () => {
299
+ didQueueTask = false;
300
+ const latestValue = getNewValue();
301
+ if (latestValue !== void 0) {
302
+ animValue.setValue(latestValue);
303
+ }
304
+ };
305
+ const delayValue = isFunction(delay) ? delay(newValue, prevValue) : delay;
306
+ prevValue = newValue;
307
+ if (!didQueueTask) {
308
+ didQueueTask = true;
309
+ if (delayValue === void 0) {
310
+ fn();
311
+ } else if (delayValue === 0) {
312
+ queueMicrotask(fn);
313
+ } else {
314
+ setTimeout(fn, delayValue);
315
+ }
316
+ }
317
+ } else {
318
+ animValue.setValue(newValue);
319
+ }
320
+ });
321
+ }, []);
322
+ return animValue;
323
+ }
324
+ var typedMemo = React2.memo;
325
+ var getComponent = (Component) => {
326
+ if (React2.isValidElement(Component)) {
327
+ return Component;
328
+ }
329
+ if (Component) {
330
+ return /* @__PURE__ */ React2.createElement(Component, null);
331
+ }
332
+ return null;
333
+ };
334
+
335
+ // src/components/PositionView.native.tsx
336
+ var PositionViewState = typedMemo(function PositionViewState2({
337
+ id,
338
+ horizontal,
339
+ style,
340
+ refView,
341
+ ...rest
342
+ }) {
343
+ const [position = POSITION_OUT_OF_VIEW] = useArr$([`containerPosition${id}`]);
344
+ return /* @__PURE__ */ React2.createElement(
345
+ View$1,
346
+ {
347
+ ref: refView,
348
+ style: [
349
+ style,
350
+ horizontal ? { transform: [{ translateX: position }] } : { transform: [{ translateY: position }] }
351
+ ],
352
+ ...rest
353
+ }
354
+ );
355
+ });
356
+ var PositionViewAnimated = typedMemo(function PositionViewAnimated2({
357
+ id,
358
+ horizontal,
359
+ style,
360
+ refView,
361
+ ...rest
362
+ }) {
363
+ const position$ = useValue$(`containerPosition${id}`, {
364
+ getValue: (v) => v != null ? v : POSITION_OUT_OF_VIEW
365
+ });
366
+ let position;
367
+ if (Platform.OS === "ios" || Platform.OS === "android") {
368
+ position = horizontal ? { transform: [{ translateX: position$ }] } : { transform: [{ translateY: position$ }] };
369
+ } else {
370
+ position = horizontal ? { left: position$ } : { top: position$ };
371
+ }
372
+ return /* @__PURE__ */ React2.createElement(Animated.View, { ref: refView, style: [style, position], ...rest });
373
+ });
374
+ var PositionViewSticky = typedMemo(function PositionViewSticky2({
375
+ id,
376
+ horizontal,
377
+ style,
378
+ refView,
379
+ animatedScrollY,
380
+ index,
381
+ stickyHeaderConfig,
382
+ children,
383
+ ...rest
384
+ }) {
385
+ const [position = POSITION_OUT_OF_VIEW, headerSize = 0, stylePaddingTop = 0] = useArr$([
386
+ `containerPosition${id}`,
387
+ "headerSize",
388
+ "stylePaddingTop"
389
+ ]);
390
+ const transform = React2.useMemo(() => {
391
+ var _a3;
392
+ if (animatedScrollY) {
393
+ const stickyConfigOffset = (_a3 = stickyHeaderConfig == null ? void 0 : stickyHeaderConfig.offset) != null ? _a3 : 0;
394
+ const stickyStart = position + headerSize + stylePaddingTop - stickyConfigOffset;
395
+ const stickyPosition = animatedScrollY.interpolate({
396
+ extrapolateLeft: "clamp",
397
+ extrapolateRight: "extend",
398
+ inputRange: [stickyStart, stickyStart + 5e3],
399
+ outputRange: [position, position + 5e3]
400
+ });
401
+ return horizontal ? [{ translateX: stickyPosition }] : [{ translateY: stickyPosition }];
402
+ }
403
+ }, [animatedScrollY, headerSize, horizontal, position, stylePaddingTop, stickyHeaderConfig == null ? void 0 : stickyHeaderConfig.offset]);
404
+ const viewStyle = React2.useMemo(() => [style, { zIndex: index + 1e3 }, { transform }], [style, transform]);
405
+ const renderStickyHeaderBackdrop = React2.useMemo(() => {
406
+ if (!(stickyHeaderConfig == null ? void 0 : stickyHeaderConfig.backdropComponent)) {
407
+ return null;
408
+ }
409
+ return /* @__PURE__ */ React2.createElement(
410
+ View$1,
411
+ {
412
+ style: {
413
+ inset: 0,
414
+ pointerEvents: "none",
415
+ position: "absolute"
416
+ }
417
+ },
418
+ getComponent(stickyHeaderConfig == null ? void 0 : stickyHeaderConfig.backdropComponent)
419
+ );
420
+ }, [stickyHeaderConfig == null ? void 0 : stickyHeaderConfig.backdropComponent]);
421
+ return /* @__PURE__ */ React2.createElement(Animated.View, { ref: refView, style: viewStyle, ...rest }, renderStickyHeaderBackdrop, children);
422
+ });
423
+ var PositionView = IsNewArchitecture ? PositionViewState : PositionViewAnimated;
424
+ function useInit(cb) {
425
+ useState(() => cb());
426
+ }
427
+
428
+ // src/state/ContextContainer.ts
429
+ var ContextContainer = createContext(null);
430
+ function useContextContainer() {
431
+ return useContext(ContextContainer);
432
+ }
433
+ function useViewability(callback, configId) {
434
+ const ctx = useStateContext();
435
+ const containerContext = useContextContainer();
436
+ useInit(() => {
437
+ if (!containerContext) {
438
+ return;
439
+ }
440
+ const { containerId } = containerContext;
441
+ const key = containerId + (configId != null ? configId : "");
442
+ const value = ctx.mapViewabilityValues.get(key);
443
+ if (value) {
444
+ callback(value);
445
+ }
446
+ });
447
+ useEffect(() => {
448
+ if (!containerContext) {
449
+ return;
450
+ }
451
+ const { containerId } = containerContext;
452
+ const key = containerId + (configId != null ? configId : "");
453
+ ctx.mapViewabilityCallbacks.set(key, callback);
454
+ return () => {
455
+ ctx.mapViewabilityCallbacks.delete(key);
456
+ };
457
+ }, [ctx, callback, configId, containerContext]);
458
+ }
459
+ function useViewabilityAmount(callback) {
460
+ const ctx = useStateContext();
461
+ const containerContext = useContextContainer();
462
+ useInit(() => {
463
+ if (!containerContext) {
464
+ return;
465
+ }
466
+ const { containerId } = containerContext;
467
+ const value = ctx.mapViewabilityAmountValues.get(containerId);
468
+ if (value) {
469
+ callback(value);
470
+ }
471
+ });
472
+ useEffect(() => {
473
+ if (!containerContext) {
474
+ return;
475
+ }
476
+ const { containerId } = containerContext;
477
+ ctx.mapViewabilityAmountCallbacks.set(containerId, callback);
478
+ return () => {
479
+ ctx.mapViewabilityAmountCallbacks.delete(containerId);
480
+ };
481
+ }, [ctx, callback, containerContext]);
482
+ }
483
+ function useRecyclingEffect(effect) {
484
+ const containerContext = useContextContainer();
485
+ const prevValues = useRef({
486
+ prevIndex: void 0,
487
+ prevItem: void 0
488
+ });
489
+ useEffect(() => {
490
+ if (!containerContext) {
491
+ return;
492
+ }
493
+ const { index, value } = containerContext;
494
+ let ret;
495
+ if (prevValues.current.prevIndex !== void 0 && prevValues.current.prevItem !== void 0) {
496
+ ret = effect({
497
+ index,
498
+ item: value,
499
+ prevIndex: prevValues.current.prevIndex,
500
+ prevItem: prevValues.current.prevItem
501
+ });
502
+ }
503
+ prevValues.current = {
504
+ prevIndex: index,
505
+ prevItem: value
506
+ };
507
+ return ret;
508
+ }, [effect, containerContext]);
509
+ }
510
+ function useRecyclingState(valueOrFun) {
511
+ var _a3, _b;
512
+ const containerContext = useContextContainer();
513
+ const computeValue = (ctx) => {
514
+ if (isFunction(valueOrFun)) {
515
+ const initializer = valueOrFun;
516
+ return ctx ? initializer({
517
+ index: ctx.index,
518
+ item: ctx.value,
519
+ prevIndex: void 0,
520
+ prevItem: void 0
521
+ }) : initializer();
522
+ }
523
+ return valueOrFun;
524
+ };
525
+ const [stateValue, setStateValue] = useState(() => {
526
+ return computeValue(containerContext);
527
+ });
528
+ const prevItemKeyRef = useRef((_a3 = containerContext == null ? void 0 : containerContext.itemKey) != null ? _a3 : null);
529
+ const currentItemKey = (_b = containerContext == null ? void 0 : containerContext.itemKey) != null ? _b : null;
530
+ if (currentItemKey !== null && prevItemKeyRef.current !== currentItemKey) {
531
+ prevItemKeyRef.current = currentItemKey;
532
+ setStateValue(computeValue(containerContext));
533
+ }
534
+ const triggerLayout = containerContext == null ? void 0 : containerContext.triggerLayout;
535
+ const setState = useCallback(
536
+ (newState) => {
537
+ if (!triggerLayout) {
538
+ return;
539
+ }
540
+ setStateValue((prevValue) => {
541
+ return isFunction(newState) ? newState(prevValue) : newState;
542
+ });
543
+ triggerLayout();
544
+ },
545
+ [triggerLayout]
546
+ );
547
+ return [stateValue, setState];
548
+ }
549
+ function useIsLastItem() {
550
+ const containerContext = useContextContainer();
551
+ const isLast = useSelector$("lastItemKeys", (lastItemKeys) => {
552
+ if (containerContext) {
553
+ const { itemKey } = containerContext;
554
+ if (!isNullOrUndefined(itemKey)) {
555
+ return (lastItemKeys == null ? void 0 : lastItemKeys.includes(itemKey)) || false;
556
+ }
557
+ }
558
+ return false;
559
+ });
560
+ return isLast;
561
+ }
562
+ function useListScrollSize() {
563
+ const [scrollSize] = useArr$(["scrollSize"]);
564
+ return scrollSize;
565
+ }
566
+ var noop = () => {
567
+ };
568
+ function useSyncLayout() {
569
+ const containerContext = useContextContainer();
570
+ if (IsNewArchitecture && containerContext) {
571
+ const { triggerLayout: syncLayout } = containerContext;
572
+ return syncLayout;
573
+ } else {
574
+ return noop;
575
+ }
576
+ }
577
+
578
+ // src/components/Separator.tsx
579
+ function Separator({ ItemSeparatorComponent, leadingItem }) {
580
+ const isLastItem = useIsLastItem();
581
+ return isLastItem ? null : /* @__PURE__ */ React2.createElement(ItemSeparatorComponent, { leadingItem });
582
+ }
583
+ function useOnLayoutSync({
584
+ ref,
585
+ onLayoutProp,
586
+ onLayoutChange
587
+ }, deps = []) {
588
+ const lastLayoutRef = useRef(null);
589
+ const onLayout = useCallback(
590
+ (event) => {
591
+ var _a3, _b;
592
+ const { layout } = event.nativeEvent;
593
+ if (layout.height !== ((_a3 = lastLayoutRef.current) == null ? void 0 : _a3.height) || layout.width !== ((_b = lastLayoutRef.current) == null ? void 0 : _b.width)) {
594
+ onLayoutChange(layout, false);
595
+ onLayoutProp == null ? void 0 : onLayoutProp(event);
596
+ lastLayoutRef.current = layout;
597
+ }
598
+ },
599
+ [onLayoutChange]
600
+ );
601
+ if (IsNewArchitecture) {
602
+ useLayoutEffect(() => {
603
+ if (ref.current) {
604
+ ref.current.measure((x, y, width, height) => {
605
+ const layout = { height, width, x, y };
606
+ lastLayoutRef.current = layout;
607
+ onLayoutChange(layout, true);
608
+ });
609
+ }
610
+ }, deps);
611
+ }
612
+ return { onLayout };
613
+ }
614
+ var Platform2 = Platform;
615
+ var PlatformAdjustBreaksScroll = Platform2.OS === "android";
616
+ var typedForwardRef = React2.forwardRef;
617
+ var typedMemo2 = React2.memo;
618
+
619
+ // src/utils/isInMVCPActiveMode.native.ts
620
+ function isInMVCPActiveMode(state) {
621
+ return state.dataChangeNeedsScrollUpdate;
622
+ }
623
+
624
+ // src/components/Container.tsx
625
+ var Container = typedMemo2(function Container2({
626
+ id,
627
+ recycleItems,
628
+ horizontal,
629
+ getRenderedItem: getRenderedItem2,
630
+ updateItemSize: updateItemSize2,
631
+ ItemSeparatorComponent,
632
+ stickyHeaderConfig
633
+ }) {
634
+ const ctx = useStateContext();
635
+ const { columnWrapperStyle, animatedScrollY } = ctx;
636
+ const positionComponentInternal = ctx.state.props.positionComponentInternal;
637
+ const stickyPositionComponentInternal = ctx.state.props.stickyPositionComponentInternal;
638
+ const [column = 0, span = 1, data, itemKey, numColumns = 1, extraData, isSticky] = useArr$([
639
+ `containerColumn${id}`,
640
+ `containerSpan${id}`,
641
+ `containerItemData${id}`,
642
+ `containerItemKey${id}`,
643
+ "numColumns",
644
+ "extraData",
645
+ `containerSticky${id}`
646
+ ]);
647
+ const itemLayoutRef = useRef({
648
+ didLayout: false,
649
+ horizontal,
650
+ itemKey,
651
+ pendingShrinkToken: 0,
652
+ updateItemSize: updateItemSize2
653
+ });
654
+ itemLayoutRef.current.horizontal = horizontal;
655
+ itemLayoutRef.current.itemKey = itemKey;
656
+ itemLayoutRef.current.updateItemSize = updateItemSize2;
657
+ const ref = useRef(null);
658
+ const [layoutRenderCount, forceLayoutRender] = useState(0);
659
+ const resolvedColumn = column > 0 ? column : 1;
660
+ const resolvedSpan = Math.min(Math.max(span || 1, 1), numColumns);
661
+ const otherAxisPos = numColumns > 1 ? `${(resolvedColumn - 1) / numColumns * 100}%` : 0;
662
+ const otherAxisSize = numColumns > 1 ? `${resolvedSpan / numColumns * 100}%` : void 0;
663
+ const style = useMemo(() => {
664
+ let paddingStyles;
665
+ if (columnWrapperStyle) {
666
+ const { columnGap, rowGap, gap } = columnWrapperStyle;
667
+ if (horizontal) {
668
+ paddingStyles = {
669
+ paddingRight: columnGap || gap || void 0,
670
+ paddingVertical: numColumns > 1 ? (rowGap || gap || 0) / 2 : void 0
671
+ };
672
+ } else {
673
+ paddingStyles = {
674
+ paddingBottom: rowGap || gap || void 0,
675
+ paddingHorizontal: numColumns > 1 ? (columnGap || gap || 0) / 2 : void 0
676
+ };
677
+ }
678
+ }
679
+ return horizontal ? {
680
+ flexDirection: ItemSeparatorComponent ? "row" : void 0,
681
+ height: otherAxisSize,
682
+ left: 0,
683
+ position: "absolute",
684
+ top: otherAxisPos,
685
+ ...paddingStyles || {}
686
+ } : {
687
+ left: otherAxisPos,
688
+ position: "absolute",
689
+ right: numColumns > 1 ? null : 0,
690
+ top: 0,
691
+ width: otherAxisSize,
692
+ ...paddingStyles || {}
693
+ };
694
+ }, [horizontal, otherAxisPos, otherAxisSize, columnWrapperStyle, numColumns]);
695
+ const renderedItemInfo = useMemo(
696
+ () => itemKey !== void 0 ? getRenderedItem2(itemKey) : null,
697
+ [itemKey, data, extraData]
698
+ );
699
+ const { index, renderedItem } = renderedItemInfo || {};
700
+ const contextValue = useMemo(() => {
701
+ ctx.viewRefs.set(id, ref);
702
+ return {
703
+ containerId: id,
704
+ index,
705
+ itemKey,
706
+ triggerLayout: () => {
707
+ forceLayoutRender((v) => v + 1);
708
+ },
709
+ value: data
710
+ };
711
+ }, [id, itemKey, index, data]);
712
+ const onLayoutChange = useCallback((rectangle) => {
713
+ var _a3, _b;
714
+ const {
715
+ horizontal: currentHorizontal,
716
+ itemKey: currentItemKey,
717
+ updateItemSize: updateItemSizeFn,
718
+ lastSize,
719
+ pendingShrinkToken
720
+ } = itemLayoutRef.current;
721
+ if (isNullOrUndefined(currentItemKey)) {
722
+ return;
723
+ }
724
+ itemLayoutRef.current.didLayout = true;
725
+ let layout = rectangle;
726
+ const axis = currentHorizontal ? "width" : "height";
727
+ const size = roundSize(rectangle[axis]);
728
+ const prevSize = lastSize ? roundSize(lastSize[axis]) : void 0;
729
+ const doUpdate = () => {
730
+ itemLayoutRef.current.lastSize = layout;
731
+ updateItemSizeFn(currentItemKey, layout);
732
+ itemLayoutRef.current.didLayout = true;
733
+ };
734
+ const shouldDeferWebShrinkLayoutUpdate = Platform2.OS === "web" && !isInMVCPActiveMode(ctx.state) && prevSize !== void 0 && size + 1 < prevSize;
735
+ if (shouldDeferWebShrinkLayoutUpdate) {
736
+ const token = pendingShrinkToken + 1;
737
+ itemLayoutRef.current.pendingShrinkToken = token;
738
+ requestAnimationFrame(() => {
739
+ var _a4;
740
+ if (itemLayoutRef.current.pendingShrinkToken !== token) {
741
+ return;
742
+ }
743
+ const element = ref.current;
744
+ const rect = (_a4 = element == null ? void 0 : element.getBoundingClientRect) == null ? void 0 : _a4.call(element);
745
+ if (rect) {
746
+ layout = { height: rect.height, width: rect.width };
747
+ }
748
+ doUpdate();
749
+ });
750
+ return;
751
+ }
752
+ if (IsNewArchitecture || size > 0) {
753
+ doUpdate();
754
+ } else {
755
+ (_b = (_a3 = ref.current) == null ? void 0 : _a3.measure) == null ? void 0 : _b.call(_a3, (_x, _y, width, height) => {
756
+ layout = { height, width };
757
+ doUpdate();
758
+ });
759
+ }
760
+ }, []);
761
+ const { onLayout } = useOnLayoutSync(
762
+ {
763
+ onLayoutChange,
764
+ ref},
765
+ [itemKey, layoutRenderCount]
766
+ );
767
+ if (!IsNewArchitecture) {
768
+ useEffect(() => {
769
+ if (!isNullOrUndefined(itemKey)) {
770
+ itemLayoutRef.current.didLayout = false;
771
+ const timeout = setTimeout(() => {
772
+ if (!itemLayoutRef.current.didLayout) {
773
+ const {
774
+ itemKey: currentItemKey,
775
+ lastSize,
776
+ updateItemSize: updateItemSizeFn
777
+ } = itemLayoutRef.current;
778
+ if (lastSize && !isNullOrUndefined(currentItemKey)) {
779
+ updateItemSizeFn(currentItemKey, lastSize);
780
+ itemLayoutRef.current.didLayout = true;
781
+ }
782
+ }
783
+ }, 16);
784
+ return () => {
785
+ clearTimeout(timeout);
786
+ };
787
+ }
788
+ }, [itemKey]);
789
+ }
790
+ const PositionComponent = isSticky ? stickyPositionComponentInternal ? stickyPositionComponentInternal : PositionViewSticky : positionComponentInternal ? positionComponentInternal : PositionView;
791
+ return /* @__PURE__ */ React2.createElement(
792
+ PositionComponent,
793
+ {
794
+ animatedScrollY: isSticky ? animatedScrollY : void 0,
795
+ horizontal,
796
+ id,
797
+ index,
798
+ key: recycleItems ? void 0 : itemKey,
799
+ onLayout,
800
+ refView: ref,
801
+ stickyHeaderConfig,
802
+ style
803
+ },
804
+ /* @__PURE__ */ React2.createElement(ContextContainer.Provider, { value: contextValue }, renderedItem, renderedItemInfo && ItemSeparatorComponent && /* @__PURE__ */ React2.createElement(Separator, { ItemSeparatorComponent, leadingItem: renderedItemInfo.item }))
805
+ );
806
+ });
807
+
808
+ // src/components/Containers.native.tsx
809
+ var Containers = typedMemo(function Containers2({
810
+ horizontal,
811
+ recycleItems,
812
+ ItemSeparatorComponent,
813
+ waitForInitialLayout,
814
+ stickyHeaderConfig,
815
+ updateItemSize: updateItemSize2,
816
+ getRenderedItem: getRenderedItem2
817
+ }) {
818
+ const ctx = useStateContext();
819
+ const columnWrapperStyle = ctx.columnWrapperStyle;
820
+ const [numContainers, numColumns] = useArr$(["numContainersPooled", "numColumns"]);
821
+ const animSize = useValue$("totalSize", {
822
+ // Use a microtask if increasing the size significantly, otherwise use a timeout
823
+ // If this is the initial scroll, we don't want to delay because we want to update the size immediately
824
+ delay: (value, prevValue) => {
825
+ var _a3;
826
+ return !((_a3 = ctx.state) == null ? void 0 : _a3.initialScroll) ? !prevValue || value - prevValue > 20 ? 0 : 200 : void 0;
827
+ }
828
+ });
829
+ const animOpacity = waitForInitialLayout ? useValue$("readyToRender", { getValue: (value) => value ? 1 : 0 }) : void 0;
830
+ const otherAxisSize = useValue$("otherAxisSize", { delay: 0 });
831
+ const containers = [];
832
+ for (let i = 0; i < numContainers; i++) {
833
+ containers.push(
834
+ /* @__PURE__ */ React2.createElement(
835
+ Container,
836
+ {
837
+ getRenderedItem: getRenderedItem2,
838
+ horizontal,
839
+ ItemSeparatorComponent,
840
+ id: i,
841
+ key: i,
842
+ recycleItems,
843
+ stickyHeaderConfig,
844
+ updateItemSize: updateItemSize2
845
+ }
846
+ )
847
+ );
848
+ }
849
+ const style = horizontal ? { minHeight: otherAxisSize, opacity: animOpacity, width: animSize } : { height: animSize, minWidth: otherAxisSize, opacity: animOpacity };
850
+ if (columnWrapperStyle) {
851
+ const { columnGap, rowGap, gap } = columnWrapperStyle;
852
+ const gapX = columnGap || gap || 0;
853
+ const gapY = rowGap || gap || 0;
854
+ if (horizontal) {
855
+ if (gapY && numColumns > 1) {
856
+ style.marginVertical = -gapY / 2;
857
+ }
858
+ if (gapX) {
859
+ style.marginRight = -gapX;
860
+ }
861
+ } else {
862
+ if (gapX && numColumns > 1) {
863
+ style.marginHorizontal = -gapX;
864
+ }
865
+ if (gapY) {
866
+ style.marginBottom = -gapY;
867
+ }
868
+ }
869
+ }
870
+ return /* @__PURE__ */ React2.createElement(Animated.View, { style }, containers);
871
+ });
872
+ var ListComponentScrollView = Animated.ScrollView;
873
+ function ScrollAdjust() {
874
+ const bias = 1e7;
875
+ const [scrollAdjust, scrollAdjustUserOffset] = useArr$(["scrollAdjust", "scrollAdjustUserOffset"]);
876
+ const scrollOffset = (scrollAdjust || 0) + (scrollAdjustUserOffset || 0) + bias;
877
+ return /* @__PURE__ */ React2.createElement(
878
+ View$1,
879
+ {
880
+ style: {
881
+ height: 0,
882
+ left: 0,
883
+ position: "absolute",
884
+ top: scrollOffset,
885
+ width: 0
886
+ }
887
+ }
888
+ );
889
+ }
890
+ function SnapWrapper({ ScrollComponent, ...props }) {
891
+ const [snapToOffsets] = useArr$(["snapToOffsets"]);
892
+ return /* @__PURE__ */ React2.createElement(ScrollComponent, { ...props, snapToOffsets });
893
+ }
894
+ var LayoutView = ({ onLayoutChange, refView, ...rest }) => {
895
+ const ref = refView != null ? refView : useRef(null);
896
+ const { onLayout } = useOnLayoutSync({ onLayoutChange, ref });
897
+ return /* @__PURE__ */ React2.createElement(View$1, { ...rest, onLayout, ref });
898
+ };
899
+
900
+ // src/components/ListComponent.tsx
901
+ var ListComponent = typedMemo2(function ListComponent2({
902
+ canRender,
903
+ style,
904
+ contentContainerStyle,
905
+ horizontal,
906
+ initialContentOffset,
907
+ recycleItems,
908
+ ItemSeparatorComponent,
909
+ alignItemsAtEnd: _alignItemsAtEnd,
910
+ waitForInitialLayout,
911
+ onScroll: onScroll2,
912
+ onLayout,
913
+ ListHeaderComponent,
914
+ ListHeaderComponentStyle,
915
+ ListFooterComponent,
916
+ ListFooterComponentStyle,
917
+ ListEmptyComponent,
918
+ getRenderedItem: getRenderedItem2,
919
+ updateItemSize: updateItemSize2,
920
+ refScrollView,
921
+ renderScrollComponent,
922
+ onLayoutFooter,
923
+ scrollAdjustHandler,
924
+ snapToIndices,
925
+ stickyHeaderConfig,
926
+ stickyHeaderIndices,
927
+ useWindowScroll = false,
928
+ ...rest
929
+ }) {
930
+ const ctx = useStateContext();
931
+ const maintainVisibleContentPosition = ctx.state.props.maintainVisibleContentPosition;
932
+ const ScrollComponent = renderScrollComponent ? useMemo(
933
+ () => React2.forwardRef(
934
+ (props, ref) => renderScrollComponent({ ...props, ref })
935
+ ),
936
+ [renderScrollComponent]
937
+ ) : ListComponentScrollView;
938
+ const SnapOrScroll = snapToIndices ? SnapWrapper : ScrollComponent;
939
+ useLayoutEffect(() => {
940
+ if (!ListHeaderComponent) {
941
+ set$(ctx, "headerSize", 0);
942
+ }
943
+ if (!ListFooterComponent) {
944
+ set$(ctx, "footerSize", 0);
945
+ }
946
+ }, [ListHeaderComponent, ListFooterComponent, ctx]);
947
+ const onLayoutHeader = useCallback(
948
+ (rect) => {
949
+ const size = rect[horizontal ? "width" : "height"];
950
+ set$(ctx, "headerSize", size);
951
+ },
952
+ [ctx, horizontal]
953
+ );
954
+ const onLayoutFooterInternal = useCallback(
955
+ (rect, fromLayoutEffect) => {
956
+ const size = rect[horizontal ? "width" : "height"];
957
+ set$(ctx, "footerSize", size);
958
+ onLayoutFooter == null ? void 0 : onLayoutFooter(rect, fromLayoutEffect);
959
+ },
960
+ [ctx, horizontal, onLayoutFooter]
961
+ );
962
+ return /* @__PURE__ */ React2.createElement(
963
+ SnapOrScroll,
964
+ {
965
+ ...rest,
966
+ ...ScrollComponent === ListComponentScrollView ? { useWindowScroll } : {},
967
+ contentContainerStyle: [
968
+ contentContainerStyle,
969
+ horizontal ? {
970
+ height: "100%"
971
+ } : {}
972
+ ],
973
+ contentOffset: initialContentOffset ? horizontal ? { x: initialContentOffset, y: 0 } : { x: 0, y: initialContentOffset } : void 0,
974
+ horizontal,
975
+ maintainVisibleContentPosition: maintainVisibleContentPosition.size || maintainVisibleContentPosition.data ? { minIndexForVisible: 0 } : void 0,
976
+ onLayout,
977
+ onScroll: onScroll2,
978
+ ref: refScrollView,
979
+ ScrollComponent: snapToIndices ? ScrollComponent : void 0,
980
+ style
981
+ },
982
+ /* @__PURE__ */ React2.createElement(ScrollAdjust, null),
983
+ ListHeaderComponent && /* @__PURE__ */ React2.createElement(LayoutView, { onLayoutChange: onLayoutHeader, style: ListHeaderComponentStyle }, getComponent(ListHeaderComponent)),
984
+ ListEmptyComponent && getComponent(ListEmptyComponent),
985
+ canRender && !ListEmptyComponent && /* @__PURE__ */ React2.createElement(
986
+ Containers,
987
+ {
988
+ getRenderedItem: getRenderedItem2,
989
+ horizontal,
990
+ ItemSeparatorComponent,
991
+ recycleItems,
992
+ stickyHeaderConfig,
993
+ updateItemSize: updateItemSize2,
994
+ waitForInitialLayout
995
+ }
996
+ ),
997
+ ListFooterComponent && /* @__PURE__ */ React2.createElement(LayoutView, { onLayoutChange: onLayoutFooterInternal, style: ListFooterComponentStyle }, getComponent(ListFooterComponent)),
998
+ IS_DEV && ENABLE_DEVMODE
999
+ );
1000
+ });
1001
+
1002
+ // src/core/calculateOffsetForIndex.ts
1003
+ function calculateOffsetForIndex(ctx, index) {
1004
+ const state = ctx.state;
1005
+ return index !== void 0 ? state.positions[index] || 0 : 0;
1006
+ }
1007
+
1008
+ // src/core/getTopOffsetAdjustment.ts
1009
+ function getTopOffsetAdjustment(ctx) {
1010
+ return (peek$(ctx, "stylePaddingTop") || 0) + (peek$(ctx, "headerSize") || 0);
1011
+ }
1012
+
1013
+ // src/utils/getId.ts
1014
+ function getId(state, index) {
1015
+ const { data, keyExtractor } = state.props;
1016
+ if (!data) {
1017
+ return "";
1018
+ }
1019
+ const ret = index < data.length ? keyExtractor ? keyExtractor(data[index], index) : index : null;
1020
+ const id = ret;
1021
+ state.idCache[index] = id;
1022
+ return id;
1023
+ }
1024
+
1025
+ // src/core/addTotalSize.ts
1026
+ function addTotalSize(ctx, key, add) {
1027
+ const state = ctx.state;
1028
+ const prevTotalSize = state.totalSize;
1029
+ let totalSize = state.totalSize;
1030
+ if (key === null) {
1031
+ totalSize = add;
1032
+ if (state.timeoutSetPaddingTop) {
1033
+ clearTimeout(state.timeoutSetPaddingTop);
1034
+ state.timeoutSetPaddingTop = void 0;
1035
+ }
1036
+ } else {
1037
+ totalSize += add;
1038
+ }
1039
+ if (prevTotalSize !== totalSize) {
1040
+ if (!IsNewArchitecture && state.initialScroll && totalSize < prevTotalSize) {
1041
+ state.pendingTotalSize = totalSize;
1042
+ } else {
1043
+ state.pendingTotalSize = void 0;
1044
+ state.totalSize = totalSize;
1045
+ set$(ctx, "totalSize", totalSize);
1046
+ }
1047
+ }
1048
+ }
1049
+
1050
+ // src/core/setSize.ts
1051
+ function setSize(ctx, itemKey, size) {
1052
+ const state = ctx.state;
1053
+ const { sizes } = state;
1054
+ const previousSize = sizes.get(itemKey);
1055
+ const diff = previousSize !== void 0 ? size - previousSize : size;
1056
+ if (diff !== 0) {
1057
+ addTotalSize(ctx, itemKey, diff);
1058
+ }
1059
+ sizes.set(itemKey, size);
1060
+ }
1061
+
1062
+ // src/utils/getItemSize.ts
1063
+ function getItemSize(ctx, key, index, data, useAverageSize, preferCachedSize) {
1064
+ var _a3, _b;
1065
+ const state = ctx.state;
1066
+ const {
1067
+ sizesKnown,
1068
+ sizes,
1069
+ averageSizes,
1070
+ props: { estimatedItemSize, getEstimatedItemSize, getFixedItemSize, getItemType },
1071
+ scrollingTo
1072
+ } = state;
1073
+ const sizeKnown = sizesKnown.get(key);
1074
+ if (sizeKnown !== void 0) {
1075
+ return sizeKnown;
1076
+ }
1077
+ let size;
1078
+ if (preferCachedSize) {
1079
+ const cachedSize = sizes.get(key);
1080
+ if (cachedSize !== void 0) {
1081
+ return cachedSize;
1082
+ }
1083
+ }
1084
+ const itemType = getItemType ? (_a3 = getItemType(data, index)) != null ? _a3 : "" : "";
1085
+ if (getFixedItemSize) {
1086
+ size = getFixedItemSize(data, index, itemType);
1087
+ if (size !== void 0) {
1088
+ sizesKnown.set(key, size);
1089
+ }
1090
+ }
1091
+ if (size === void 0 && useAverageSize && sizeKnown === void 0 && !scrollingTo) {
1092
+ const averageSizeForType = (_b = averageSizes[itemType]) == null ? void 0 : _b.avg;
1093
+ if (averageSizeForType !== void 0) {
1094
+ size = roundSize(averageSizeForType);
1095
+ }
1096
+ }
1097
+ if (size === void 0) {
1098
+ size = sizes.get(key);
1099
+ if (size !== void 0) {
1100
+ return size;
1101
+ }
1102
+ }
1103
+ if (size === void 0) {
1104
+ size = getEstimatedItemSize ? getEstimatedItemSize(data, index, itemType) : estimatedItemSize;
1105
+ }
1106
+ setSize(ctx, key, size);
1107
+ return size;
1108
+ }
1109
+
1110
+ // src/core/calculateOffsetWithOffsetPosition.ts
1111
+ function calculateOffsetWithOffsetPosition(ctx, offsetParam, params) {
1112
+ var _a3;
1113
+ const state = ctx.state;
1114
+ const { index, viewOffset, viewPosition } = params;
1115
+ let offset = offsetParam;
1116
+ if (viewOffset) {
1117
+ offset -= viewOffset;
1118
+ }
1119
+ if (index !== void 0) {
1120
+ const topOffsetAdjustment = getTopOffsetAdjustment(ctx);
1121
+ if (topOffsetAdjustment) {
1122
+ offset += topOffsetAdjustment;
1123
+ }
1124
+ }
1125
+ if (viewPosition !== void 0 && index !== void 0) {
1126
+ const dataLength = state.props.data.length;
1127
+ if (dataLength === 0) {
1128
+ return offset;
1129
+ }
1130
+ const isOutOfBounds = index < 0 || index >= dataLength;
1131
+ const fallbackEstimatedSize = (_a3 = state.props.estimatedItemSize) != null ? _a3 : 0;
1132
+ const itemSize = isOutOfBounds ? fallbackEstimatedSize : getItemSize(ctx, getId(state, index), index, state.props.data[index]);
1133
+ const trailingInset = getContentInsetEnd(state);
1134
+ offset -= viewPosition * (state.scrollLength - trailingInset - itemSize);
1135
+ if (!isOutOfBounds && index === state.props.data.length - 1) {
1136
+ const footerSize = peek$(ctx, "footerSize") || 0;
1137
+ offset += footerSize;
1138
+ }
1139
+ }
1140
+ return offset;
1141
+ }
1142
+
1143
+ // src/core/clampScrollOffset.ts
1144
+ function clampScrollOffset(ctx, offset, scrollTarget) {
1145
+ const state = ctx.state;
1146
+ const contentSize = getContentSize(ctx);
1147
+ let clampedOffset = offset;
1148
+ if (Number.isFinite(contentSize) && Number.isFinite(state.scrollLength) && (Platform2.OS !== "android" || state.lastLayout)) {
1149
+ const baseMaxOffset = Math.max(0, contentSize - state.scrollLength);
1150
+ const viewOffset = scrollTarget == null ? void 0 : scrollTarget.viewOffset;
1151
+ const extraEndOffset = typeof viewOffset === "number" && viewOffset < 0 ? -viewOffset : 0;
1152
+ const maxOffset = baseMaxOffset + extraEndOffset;
1153
+ clampedOffset = Math.min(offset, maxOffset);
1154
+ }
1155
+ clampedOffset = Math.max(0, clampedOffset);
1156
+ return clampedOffset;
1157
+ }
1158
+
1159
+ // src/utils/checkThreshold.ts
1160
+ var HYSTERESIS_MULTIPLIER = 1.3;
1161
+ var checkThreshold = (distance, atThreshold, threshold, wasReached, snapshot, context, onReached, setSnapshot, allowReentryOnChange) => {
1162
+ const absDistance = Math.abs(distance);
1163
+ const within = atThreshold || threshold > 0 && absDistance <= threshold;
1164
+ const updateSnapshot = () => {
1165
+ setSnapshot({
1166
+ atThreshold,
1167
+ contentSize: context.contentSize,
1168
+ dataLength: context.dataLength,
1169
+ scrollPosition: context.scrollPosition
1170
+ });
1171
+ };
1172
+ if (!wasReached) {
1173
+ if (!within) {
1174
+ return false;
1175
+ }
1176
+ onReached(distance);
1177
+ updateSnapshot();
1178
+ return true;
1179
+ }
1180
+ const reset = !atThreshold && threshold > 0 && absDistance >= threshold * HYSTERESIS_MULTIPLIER || !atThreshold && threshold <= 0 && absDistance > 0;
1181
+ if (reset) {
1182
+ setSnapshot(void 0);
1183
+ return false;
1184
+ }
1185
+ if (within) {
1186
+ const changed = !snapshot || snapshot.atThreshold !== atThreshold || snapshot.contentSize !== context.contentSize || snapshot.dataLength !== context.dataLength;
1187
+ if (changed) {
1188
+ if (allowReentryOnChange) {
1189
+ onReached(distance);
1190
+ }
1191
+ updateSnapshot();
1192
+ }
1193
+ }
1194
+ return true;
1195
+ };
1196
+
1197
+ // src/utils/checkAtBottom.ts
1198
+ function checkAtBottom(ctx) {
1199
+ var _a3;
1200
+ const state = ctx.state;
1201
+ if (!state || state.initialScroll) {
1202
+ return;
1203
+ }
1204
+ const {
1205
+ queuedInitialLayout,
1206
+ scrollLength,
1207
+ scroll,
1208
+ maintainingScrollAtEnd,
1209
+ props: { maintainScrollAtEndThreshold, onEndReachedThreshold }
1210
+ } = state;
1211
+ if (state.initialScroll) {
1212
+ return;
1213
+ }
1214
+ const contentSize = getContentSize(ctx);
1215
+ if (contentSize > 0 && queuedInitialLayout && !maintainingScrollAtEnd) {
1216
+ const insetEnd = getContentInsetEnd(state);
1217
+ const distanceFromEnd = contentSize - scroll - scrollLength - insetEnd;
1218
+ const isContentLess = contentSize < scrollLength;
1219
+ state.isAtEnd = isContentLess || distanceFromEnd < scrollLength * maintainScrollAtEndThreshold;
1220
+ state.isEndReached = checkThreshold(
1221
+ distanceFromEnd,
1222
+ isContentLess,
1223
+ onEndReachedThreshold * scrollLength,
1224
+ state.isEndReached,
1225
+ state.endReachedSnapshot,
1226
+ {
1227
+ contentSize,
1228
+ dataLength: (_a3 = state.props.data) == null ? void 0 : _a3.length,
1229
+ scrollPosition: scroll
1230
+ },
1231
+ (distance) => {
1232
+ var _a4, _b;
1233
+ return (_b = (_a4 = state.props).onEndReached) == null ? void 0 : _b.call(_a4, { distanceFromEnd: distance });
1234
+ },
1235
+ (snapshot) => {
1236
+ state.endReachedSnapshot = snapshot;
1237
+ },
1238
+ true
1239
+ );
1240
+ }
1241
+ }
1242
+
1243
+ // src/utils/checkAtTop.ts
1244
+ function checkAtTop(ctx) {
1245
+ const state = ctx == null ? void 0 : ctx.state;
1246
+ if (!state || state.initialScroll || state.scrollingTo) {
1247
+ return;
1248
+ }
1249
+ const {
1250
+ dataChangeEpoch,
1251
+ isStartReached,
1252
+ props: { data, onStartReachedThreshold },
1253
+ scroll,
1254
+ scrollLength,
1255
+ startReachedSnapshot,
1256
+ startReachedSnapshotDataChangeEpoch,
1257
+ totalSize
1258
+ } = state;
1259
+ const dataLength = data.length;
1260
+ const threshold = onStartReachedThreshold * scrollLength;
1261
+ const dataChanged = startReachedSnapshotDataChangeEpoch !== dataChangeEpoch;
1262
+ const withinThreshold = threshold > 0 && Math.abs(scroll) <= threshold;
1263
+ const allowReentryOnDataChange = !!isStartReached && withinThreshold && !!dataChanged && !isInMVCPActiveMode(state);
1264
+ if (isStartReached && threshold > 0 && scroll > threshold && startReachedSnapshot && (dataChanged || startReachedSnapshot.contentSize !== totalSize || startReachedSnapshot.dataLength !== dataLength)) {
1265
+ state.isStartReached = false;
1266
+ state.startReachedSnapshot = void 0;
1267
+ state.startReachedSnapshotDataChangeEpoch = void 0;
1268
+ }
1269
+ state.isAtStart = scroll <= 0;
1270
+ if (isStartReached && withinThreshold && dataChanged && !allowReentryOnDataChange) {
1271
+ return;
1272
+ }
1273
+ state.isStartReached = checkThreshold(
1274
+ scroll,
1275
+ false,
1276
+ threshold,
1277
+ state.isStartReached,
1278
+ allowReentryOnDataChange ? void 0 : startReachedSnapshot,
1279
+ {
1280
+ contentSize: totalSize,
1281
+ dataLength,
1282
+ scrollPosition: scroll
1283
+ },
1284
+ (distance) => {
1285
+ var _a3, _b;
1286
+ return (_b = (_a3 = state.props).onStartReached) == null ? void 0 : _b.call(_a3, { distanceFromStart: distance });
1287
+ },
1288
+ (snapshot) => {
1289
+ state.startReachedSnapshot = snapshot;
1290
+ state.startReachedSnapshotDataChangeEpoch = snapshot ? dataChangeEpoch : void 0;
1291
+ },
1292
+ allowReentryOnDataChange
1293
+ );
1294
+ }
1295
+
1296
+ // src/utils/checkThresholds.ts
1297
+ function checkThresholds(ctx) {
1298
+ checkAtBottom(ctx);
1299
+ checkAtTop(ctx);
1300
+ }
1301
+
1302
+ // src/utils/setInitialRenderState.ts
1303
+ function setInitialRenderState(ctx, {
1304
+ didLayout,
1305
+ didInitialScroll
1306
+ }) {
1307
+ const { state } = ctx;
1308
+ const {
1309
+ loadStartTime,
1310
+ props: { onLoad }
1311
+ } = state;
1312
+ if (didLayout) {
1313
+ state.didContainersLayout = true;
1314
+ }
1315
+ if (didInitialScroll) {
1316
+ state.didFinishInitialScroll = true;
1317
+ }
1318
+ const isReadyToRender = Boolean(state.didContainersLayout && state.didFinishInitialScroll);
1319
+ if (isReadyToRender && !peek$(ctx, "readyToRender")) {
1320
+ set$(ctx, "readyToRender", true);
1321
+ if (onLoad) {
1322
+ onLoad({ elapsedTimeInMs: Date.now() - loadStartTime });
1323
+ }
1324
+ }
1325
+ }
1326
+
1327
+ // src/core/finishScrollTo.ts
1328
+ function finishScrollTo(ctx) {
1329
+ var _a3, _b;
1330
+ const state = ctx.state;
1331
+ if (state == null ? void 0 : state.scrollingTo) {
1332
+ const resolvePendingScroll = state.pendingScrollResolve;
1333
+ state.pendingScrollResolve = void 0;
1334
+ const scrollingTo = state.scrollingTo;
1335
+ state.scrollHistory.length = 0;
1336
+ state.initialScroll = void 0;
1337
+ state.initialScrollUsesOffset = false;
1338
+ state.initialAnchor = void 0;
1339
+ state.initialNativeScrollWatchdog = void 0;
1340
+ state.scrollingTo = void 0;
1341
+ if (state.pendingTotalSize !== void 0) {
1342
+ addTotalSize(ctx, null, state.pendingTotalSize);
1343
+ }
1344
+ if ((_a3 = state.props) == null ? void 0 : _a3.data) {
1345
+ (_b = state.triggerCalculateItemsInView) == null ? void 0 : _b.call(state, { forceFullItemPositions: true });
1346
+ }
1347
+ if (PlatformAdjustBreaksScroll) {
1348
+ state.scrollAdjustHandler.commitPendingAdjust(scrollingTo);
1349
+ }
1350
+ setInitialRenderState(ctx, { didInitialScroll: true });
1351
+ checkThresholds(ctx);
1352
+ resolvePendingScroll == null ? void 0 : resolvePendingScroll();
1353
+ }
1354
+ }
1355
+
1356
+ // src/core/checkFinishedScroll.ts
1357
+ var INITIAL_SCROLL_MIN_TARGET_OFFSET = 1;
1358
+ var INITIAL_SCROLL_MAX_FALLBACK_CHECKS = 20;
1359
+ var INITIAL_SCROLL_ZERO_TARGET_EPSILON = 1;
1360
+ function checkFinishedScroll(ctx) {
1361
+ ctx.state.animFrameCheckFinishedScroll = requestAnimationFrame(() => checkFinishedScrollFrame(ctx));
1362
+ }
1363
+ function checkFinishedScrollFrame(ctx) {
1364
+ var _a3;
1365
+ const scrollingTo = ctx.state.scrollingTo;
1366
+ if (scrollingTo) {
1367
+ const { state } = ctx;
1368
+ state.animFrameCheckFinishedScroll = void 0;
1369
+ const scroll = state.scrollPending;
1370
+ const adjust = state.scrollAdjustHandler.getAdjust();
1371
+ const clampedTargetOffset = (_a3 = scrollingTo.targetOffset) != null ? _a3 : clampScrollOffset(ctx, scrollingTo.offset - (scrollingTo.viewOffset || 0), scrollingTo);
1372
+ const maxOffset = clampScrollOffset(ctx, scroll, scrollingTo);
1373
+ const diff1 = Math.abs(scroll - clampedTargetOffset);
1374
+ const diff2 = Math.abs(diff1 - adjust);
1375
+ const isNotOverscrolled = Math.abs(scroll - maxOffset) < 1;
1376
+ const isAtTarget = diff1 < 1 || !scrollingTo.animated && diff2 < 1;
1377
+ if (isNotOverscrolled && isAtTarget) {
1378
+ finishScrollTo(ctx);
1379
+ }
1380
+ }
1381
+ }
1382
+ function checkFinishedScrollFallback(ctx) {
1383
+ const state = ctx.state;
1384
+ const scrollingTo = state.scrollingTo;
1385
+ const shouldFinishInitialZeroTarget = shouldFinishInitialZeroTargetScroll(ctx);
1386
+ const slowTimeout = (scrollingTo == null ? void 0 : scrollingTo.isInitialScroll) && !shouldFinishInitialZeroTarget || !state.didContainersLayout;
1387
+ state.timeoutCheckFinishedScrollFallback = setTimeout(
1388
+ () => {
1389
+ let numChecks = 0;
1390
+ const checkHasScrolled = () => {
1391
+ var _a3, _b;
1392
+ state.timeoutCheckFinishedScrollFallback = void 0;
1393
+ const isStillScrollingTo = state.scrollingTo;
1394
+ if (isStillScrollingTo) {
1395
+ numChecks++;
1396
+ const isNativeInitialPending = isNativeInitialNonZeroTarget(state) && !state.hasScrolled;
1397
+ const maxChecks = isNativeInitialPending ? INITIAL_SCROLL_MAX_FALLBACK_CHECKS : 5;
1398
+ const shouldFinishZeroTarget = shouldFinishInitialZeroTargetScroll(ctx);
1399
+ if (shouldFinishZeroTarget || state.hasScrolled || numChecks > maxChecks) {
1400
+ finishScrollTo(ctx);
1401
+ } else if (isNativeInitialPending && numChecks <= maxChecks) {
1402
+ const targetOffset = (_b = (_a3 = state.initialNativeScrollWatchdog) == null ? void 0 : _a3.targetOffset) != null ? _b : state.scrollPending;
1403
+ const scroller = state.refScroller.current;
1404
+ if (scroller) {
1405
+ scroller.scrollTo({
1406
+ animated: false,
1407
+ x: state.props.horizontal ? targetOffset : 0,
1408
+ y: state.props.horizontal ? 0 : targetOffset
1409
+ });
1410
+ }
1411
+ state.timeoutCheckFinishedScrollFallback = setTimeout(checkHasScrolled, 100);
1412
+ } else {
1413
+ state.timeoutCheckFinishedScrollFallback = setTimeout(checkHasScrolled, 100);
1414
+ }
1415
+ }
1416
+ };
1417
+ checkHasScrolled();
1418
+ },
1419
+ slowTimeout ? 500 : 100
1420
+ );
1421
+ }
1422
+ function isNativeInitialNonZeroTarget(state) {
1423
+ return !state.didFinishInitialScroll && !!state.initialNativeScrollWatchdog && state.initialNativeScrollWatchdog.targetOffset > INITIAL_SCROLL_MIN_TARGET_OFFSET;
1424
+ }
1425
+ function shouldFinishInitialZeroTargetScroll(ctx) {
1426
+ var _a3;
1427
+ const { state } = ctx;
1428
+ return !!((_a3 = state.scrollingTo) == null ? void 0 : _a3.isInitialScroll) && state.props.data.length > 0 && getContentSize(ctx) <= state.scrollLength && state.scrollPending <= INITIAL_SCROLL_ZERO_TARGET_EPSILON;
1429
+ }
1430
+
1431
+ // src/core/doScrollTo.native.ts
1432
+ function doScrollTo(ctx, params) {
1433
+ const state = ctx.state;
1434
+ const { animated, horizontal, offset } = params;
1435
+ const isAnimated = !!animated;
1436
+ const { refScroller } = state;
1437
+ const scroller = refScroller.current;
1438
+ if (!scroller) {
1439
+ return;
1440
+ }
1441
+ scroller.scrollTo({
1442
+ animated: isAnimated,
1443
+ x: horizontal ? offset : 0,
1444
+ y: horizontal ? 0 : offset
1445
+ });
1446
+ if (!isAnimated) {
1447
+ state.scroll = offset;
1448
+ checkFinishedScrollFallback(ctx);
1449
+ }
1450
+ }
1451
+
1452
+ // src/core/scrollTo.ts
1453
+ var WATCHDOG_OFFSET_EPSILON = 1;
1454
+ function scrollTo(ctx, params) {
1455
+ var _a3, _b;
1456
+ const state = ctx.state;
1457
+ const { noScrollingTo, forceScroll, ...scrollTarget } = params;
1458
+ const { animated, isInitialScroll, offset: scrollTargetOffset, precomputedWithViewOffset } = scrollTarget;
1459
+ const {
1460
+ props: { horizontal }
1461
+ } = state;
1462
+ if (state.animFrameCheckFinishedScroll) {
1463
+ cancelAnimationFrame(ctx.state.animFrameCheckFinishedScroll);
1464
+ }
1465
+ if (state.timeoutCheckFinishedScrollFallback) {
1466
+ clearTimeout(ctx.state.timeoutCheckFinishedScrollFallback);
1467
+ }
1468
+ let offset = precomputedWithViewOffset ? scrollTargetOffset : calculateOffsetWithOffsetPosition(ctx, scrollTargetOffset, scrollTarget);
1469
+ offset = clampScrollOffset(ctx, offset, scrollTarget);
1470
+ state.scrollHistory.length = 0;
1471
+ if (!noScrollingTo) {
1472
+ state.scrollingTo = {
1473
+ ...scrollTarget,
1474
+ targetOffset: offset
1475
+ };
1476
+ }
1477
+ state.scrollPending = offset;
1478
+ const shouldWatchInitialNativeScroll = !state.didFinishInitialScroll && (isInitialScroll || !!state.initialNativeScrollWatchdog) && offset > WATCHDOG_OFFSET_EPSILON;
1479
+ const shouldClearInitialNativeScrollWatchdog = !state.didFinishInitialScroll && !!state.initialNativeScrollWatchdog && offset <= WATCHDOG_OFFSET_EPSILON;
1480
+ if (shouldWatchInitialNativeScroll) {
1481
+ state.hasScrolled = false;
1482
+ state.initialNativeScrollWatchdog = {
1483
+ startScroll: (_b = (_a3 = state.initialNativeScrollWatchdog) == null ? void 0 : _a3.startScroll) != null ? _b : state.scroll,
1484
+ targetOffset: offset
1485
+ };
1486
+ } else if (shouldClearInitialNativeScrollWatchdog) {
1487
+ state.initialNativeScrollWatchdog = void 0;
1488
+ }
1489
+ if (forceScroll || !isInitialScroll || Platform2.OS === "android") {
1490
+ doScrollTo(ctx, { animated, horizontal, offset });
1491
+ } else {
1492
+ state.scroll = offset;
1493
+ }
1494
+ }
1495
+
1496
+ // src/core/doMaintainScrollAtEnd.ts
1497
+ function doMaintainScrollAtEnd(ctx) {
1498
+ const state = ctx.state;
1499
+ const {
1500
+ didContainersLayout,
1501
+ isAtEnd,
1502
+ pendingNativeMVCPAdjust,
1503
+ refScroller,
1504
+ props: { maintainScrollAtEnd }
1505
+ } = state;
1506
+ const shouldMaintainScrollAtEnd = !!(isAtEnd && maintainScrollAtEnd && didContainersLayout);
1507
+ if (pendingNativeMVCPAdjust) {
1508
+ state.pendingMaintainScrollAtEnd = shouldMaintainScrollAtEnd;
1509
+ return false;
1510
+ }
1511
+ state.pendingMaintainScrollAtEnd = false;
1512
+ if (shouldMaintainScrollAtEnd) {
1513
+ const contentSize = getContentSize(ctx);
1514
+ if (contentSize < state.scrollLength) {
1515
+ state.scroll = 0;
1516
+ }
1517
+ requestAnimationFrame(() => {
1518
+ var _a3;
1519
+ if (state.isAtEnd) {
1520
+ state.maintainingScrollAtEnd = true;
1521
+ (_a3 = refScroller.current) == null ? void 0 : _a3.scrollToEnd({
1522
+ animated: maintainScrollAtEnd.animated
1523
+ });
1524
+ setTimeout(
1525
+ () => {
1526
+ state.maintainingScrollAtEnd = false;
1527
+ },
1528
+ maintainScrollAtEnd.animated ? 500 : 0
1529
+ );
1530
+ }
1531
+ });
1532
+ return true;
1533
+ }
1534
+ return false;
1535
+ }
1536
+
1537
+ // src/core/mvcp.ts
1538
+ var MVCP_POSITION_EPSILON = 0.1;
1539
+ var MVCP_ANCHOR_LOCK_TTL_MS = 300;
1540
+ var MVCP_ANCHOR_LOCK_QUIET_PASSES_TO_RELEASE = 2;
1541
+ var NATIVE_END_CLAMP_EPSILON = 1;
1542
+ function resolveAnchorLock(state, enableMVCPAnchorLock, mvcpData, now) {
1543
+ if (!enableMVCPAnchorLock) {
1544
+ state.mvcpAnchorLock = void 0;
1545
+ return void 0;
1546
+ }
1547
+ const lock = state.mvcpAnchorLock;
1548
+ if (!lock) {
1549
+ return void 0;
1550
+ }
1551
+ const isExpired = now > lock.expiresAt;
1552
+ const isMissing = state.indexByKey.get(lock.id) === void 0;
1553
+ if (isExpired || isMissing || !mvcpData) {
1554
+ state.mvcpAnchorLock = void 0;
1555
+ return void 0;
1556
+ }
1557
+ return lock;
1558
+ }
1559
+ function updateAnchorLock(state, params) {
1560
+ if (Platform2.OS === "web") {
1561
+ const { anchorId, anchorPosition, dataChanged, now, positionDiff } = params;
1562
+ const enableMVCPAnchorLock = !!dataChanged || !!state.mvcpAnchorLock;
1563
+ const mvcpData = state.props.maintainVisibleContentPosition.data;
1564
+ if (!enableMVCPAnchorLock || !mvcpData || state.scrollingTo || !anchorId || anchorPosition === void 0) {
1565
+ return;
1566
+ }
1567
+ const existingLock = state.mvcpAnchorLock;
1568
+ const quietPasses = !dataChanged && Math.abs(positionDiff) <= MVCP_POSITION_EPSILON && (existingLock == null ? void 0 : existingLock.id) === anchorId ? existingLock.quietPasses + 1 : 0;
1569
+ if (!dataChanged && quietPasses >= MVCP_ANCHOR_LOCK_QUIET_PASSES_TO_RELEASE) {
1570
+ state.mvcpAnchorLock = void 0;
1571
+ return;
1572
+ }
1573
+ state.mvcpAnchorLock = {
1574
+ expiresAt: now + MVCP_ANCHOR_LOCK_TTL_MS,
1575
+ id: anchorId,
1576
+ position: anchorPosition,
1577
+ quietPasses
1578
+ };
1579
+ }
1580
+ }
1581
+ function shouldQueueNativeMVCPAdjust(dataChanged, state, positionDiff, prevTotalSize, prevScroll, scrollTarget) {
1582
+ if (!dataChanged || Platform2.OS === "web" || !state.props.maintainVisibleContentPosition.data || scrollTarget !== void 0 || positionDiff >= -MVCP_POSITION_EPSILON) {
1583
+ return false;
1584
+ }
1585
+ const distanceFromEnd = prevTotalSize - prevScroll - state.scrollLength;
1586
+ return distanceFromEnd < Math.abs(positionDiff) - MVCP_POSITION_EPSILON;
1587
+ }
1588
+ function getPredictedNativeClamp(state, unresolvedAmount, totalSize) {
1589
+ if (Math.abs(unresolvedAmount) <= MVCP_POSITION_EPSILON) {
1590
+ return 0;
1591
+ }
1592
+ const maxScroll = Math.max(0, totalSize - state.scrollLength);
1593
+ const clampDelta = maxScroll - state.scroll;
1594
+ if (unresolvedAmount < 0) {
1595
+ return Math.max(unresolvedAmount, Math.min(0, clampDelta));
1596
+ }
1597
+ if (unresolvedAmount > 0) {
1598
+ return Math.min(unresolvedAmount, Math.max(0, clampDelta));
1599
+ }
1600
+ return 0;
1601
+ }
1602
+ function maybeApplyPredictedNativeMVCPAdjust(ctx) {
1603
+ const state = ctx.state;
1604
+ const pending = state.pendingNativeMVCPAdjust;
1605
+ if (!pending || Math.abs(pending.manualApplied) > MVCP_POSITION_EPSILON) {
1606
+ return;
1607
+ }
1608
+ const totalSize = getContentSize(ctx);
1609
+ const predictedNativeClamp = getPredictedNativeClamp(state, pending.amount, totalSize);
1610
+ if (Math.abs(predictedNativeClamp) <= MVCP_POSITION_EPSILON) {
1611
+ return;
1612
+ }
1613
+ const manualDesired = pending.amount - predictedNativeClamp;
1614
+ if (Math.abs(manualDesired) <= MVCP_POSITION_EPSILON) {
1615
+ return;
1616
+ }
1617
+ pending.manualApplied = manualDesired;
1618
+ requestAdjust(ctx, manualDesired, true);
1619
+ }
1620
+ function resolvePendingNativeMVCPAdjust(ctx, newScroll) {
1621
+ const state = ctx.state;
1622
+ const pending = state.pendingNativeMVCPAdjust;
1623
+ if (!pending) {
1624
+ return false;
1625
+ }
1626
+ const remainingAfterManual = pending.amount - pending.manualApplied;
1627
+ const nativeDelta = newScroll - (pending.startScroll + pending.manualApplied);
1628
+ const isWrongDirection = remainingAfterManual < 0 && nativeDelta > MVCP_POSITION_EPSILON || remainingAfterManual > 0 && nativeDelta < -MVCP_POSITION_EPSILON;
1629
+ if (Math.abs(remainingAfterManual) <= MVCP_POSITION_EPSILON) {
1630
+ state.pendingNativeMVCPAdjust = void 0;
1631
+ return true;
1632
+ }
1633
+ if (isWrongDirection) {
1634
+ state.pendingNativeMVCPAdjust = void 0;
1635
+ return false;
1636
+ }
1637
+ const expectedNativeClampScroll = Math.max(0, getContentSize(ctx) - state.scrollLength);
1638
+ const distanceToClamp = Math.abs(newScroll - expectedNativeClampScroll);
1639
+ const didApproachClamp = distanceToClamp < pending.closestDistanceToClamp - MVCP_POSITION_EPSILON;
1640
+ const didMoveAwayAfterApproach = pending.hasApproachedClamp && distanceToClamp > pending.closestDistanceToClamp + MVCP_POSITION_EPSILON;
1641
+ if (didApproachClamp) {
1642
+ pending.closestDistanceToClamp = distanceToClamp;
1643
+ pending.hasApproachedClamp = true;
1644
+ } else if (didMoveAwayAfterApproach) {
1645
+ state.pendingNativeMVCPAdjust = void 0;
1646
+ return false;
1647
+ }
1648
+ const isAtExpectedNativeClamp = distanceToClamp <= NATIVE_END_CLAMP_EPSILON;
1649
+ if (!isAtExpectedNativeClamp) {
1650
+ return false;
1651
+ }
1652
+ state.pendingNativeMVCPAdjust = void 0;
1653
+ const remaining = remainingAfterManual - nativeDelta;
1654
+ if (Math.abs(remaining) > MVCP_POSITION_EPSILON) {
1655
+ requestAdjust(ctx, remaining, true);
1656
+ }
1657
+ return true;
1658
+ }
1659
+ function prepareMVCP(ctx, dataChanged) {
1660
+ const state = ctx.state;
1661
+ const { idsInView, positions, props } = state;
1662
+ const {
1663
+ maintainVisibleContentPosition: { data: mvcpData, size: mvcpScroll, shouldRestorePosition }
1664
+ } = props;
1665
+ const isWeb = Platform2.OS === "web";
1666
+ const now = Date.now();
1667
+ const enableMVCPAnchorLock = isWeb && (!!dataChanged || !!state.mvcpAnchorLock);
1668
+ const scrollingTo = state.scrollingTo;
1669
+ const anchorLock = isWeb ? resolveAnchorLock(state, enableMVCPAnchorLock, mvcpData, now) : void 0;
1670
+ let prevPosition;
1671
+ let targetId;
1672
+ const idsInViewWithPositions = [];
1673
+ const scrollTarget = scrollingTo == null ? void 0 : scrollingTo.index;
1674
+ const scrollingToViewPosition = scrollingTo == null ? void 0 : scrollingTo.viewPosition;
1675
+ const isEndAnchoredScrollTarget = scrollTarget !== void 0 && state.props.data.length > 0 && scrollTarget >= state.props.data.length - 1 && (scrollingToViewPosition != null ? scrollingToViewPosition : 0) > 0;
1676
+ const shouldMVCP = dataChanged ? mvcpData : mvcpScroll;
1677
+ const indexByKey = state.indexByKey;
1678
+ const prevScroll = state.scroll;
1679
+ const prevTotalSize = getContentSize(ctx);
1680
+ if (shouldMVCP) {
1681
+ if (!isWeb && state.pendingNativeMVCPAdjust && scrollTarget === void 0) {
1682
+ maybeApplyPredictedNativeMVCPAdjust(ctx);
1683
+ return void 0;
1684
+ }
1685
+ if (anchorLock && scrollTarget === void 0) {
1686
+ targetId = anchorLock.id;
1687
+ prevPosition = anchorLock.position;
1688
+ } else if (scrollTarget !== void 0) {
1689
+ if (!IsNewArchitecture && (scrollingTo == null ? void 0 : scrollingTo.isInitialScroll)) {
1690
+ return void 0;
1691
+ }
1692
+ targetId = getId(state, scrollTarget);
1693
+ } else if (idsInView.length > 0 && state.didContainersLayout && !dataChanged) {
1694
+ targetId = idsInView.find((id) => indexByKey.get(id) !== void 0);
1695
+ }
1696
+ if (dataChanged && idsInView.length > 0 && state.didContainersLayout) {
1697
+ for (let i = 0; i < idsInView.length; i++) {
1698
+ const id = idsInView[i];
1699
+ const index = indexByKey.get(id);
1700
+ if (index !== void 0) {
1701
+ const position = positions[index];
1702
+ if (position !== void 0) {
1703
+ idsInViewWithPositions.push({ id, position });
1704
+ }
1705
+ }
1706
+ }
1707
+ }
1708
+ if (targetId !== void 0 && prevPosition === void 0) {
1709
+ const targetIndex = indexByKey.get(targetId);
1710
+ if (targetIndex !== void 0) {
1711
+ prevPosition = positions[targetIndex];
1712
+ }
1713
+ }
1714
+ return () => {
1715
+ let positionDiff = 0;
1716
+ let anchorIdForLock = anchorLock == null ? void 0 : anchorLock.id;
1717
+ let anchorPositionForLock;
1718
+ let skipTargetAnchor = false;
1719
+ const data = state.props.data;
1720
+ const shouldValidateLockedAnchor = isWeb && dataChanged && mvcpData && scrollTarget === void 0 && targetId !== void 0 && (anchorLock == null ? void 0 : anchorLock.id) === targetId && shouldRestorePosition !== void 0;
1721
+ if (shouldValidateLockedAnchor && targetId !== void 0) {
1722
+ const index = indexByKey.get(targetId);
1723
+ if (index !== void 0) {
1724
+ const item = data[index];
1725
+ skipTargetAnchor = item === void 0 || !shouldRestorePosition(item, index, data);
1726
+ if (skipTargetAnchor && (anchorLock == null ? void 0 : anchorLock.id) === targetId) {
1727
+ state.mvcpAnchorLock = void 0;
1728
+ }
1729
+ }
1730
+ }
1731
+ const shouldUseFallbackVisibleAnchor = dataChanged && mvcpData && scrollTarget === void 0 && (() => {
1732
+ if (targetId === void 0 || skipTargetAnchor) {
1733
+ return true;
1734
+ }
1735
+ const targetIndex = indexByKey.get(targetId);
1736
+ return targetIndex === void 0 || positions[targetIndex] === void 0;
1737
+ })();
1738
+ if (shouldUseFallbackVisibleAnchor) {
1739
+ for (let i = 0; i < idsInViewWithPositions.length; i++) {
1740
+ const { id, position } = idsInViewWithPositions[i];
1741
+ const index = indexByKey.get(id);
1742
+ if (index !== void 0 && shouldRestorePosition) {
1743
+ const item = data[index];
1744
+ if (item === void 0 || !shouldRestorePosition(item, index, data)) {
1745
+ continue;
1746
+ }
1747
+ }
1748
+ const newPosition = index !== void 0 ? positions[index] : void 0;
1749
+ if (newPosition !== void 0) {
1750
+ positionDiff = newPosition - position;
1751
+ anchorIdForLock = id;
1752
+ anchorPositionForLock = newPosition;
1753
+ break;
1754
+ }
1755
+ }
1756
+ }
1757
+ if (!skipTargetAnchor && targetId !== void 0 && prevPosition !== void 0) {
1758
+ const targetIndex = indexByKey.get(targetId);
1759
+ const newPosition = targetIndex !== void 0 ? positions[targetIndex] : void 0;
1760
+ if (newPosition !== void 0) {
1761
+ const totalSize = getContentSize(ctx);
1762
+ let diff = newPosition - prevPosition;
1763
+ if (diff !== 0 && isEndAnchoredScrollTarget && state.scroll + state.scrollLength > totalSize) {
1764
+ if (diff > 0) {
1765
+ diff = Math.max(0, totalSize - state.scroll - state.scrollLength);
1766
+ } else {
1767
+ diff = 0;
1768
+ }
1769
+ }
1770
+ positionDiff = diff;
1771
+ anchorIdForLock = targetId;
1772
+ anchorPositionForLock = newPosition;
1773
+ }
1774
+ }
1775
+ if (scrollingToViewPosition && scrollingToViewPosition > 0) {
1776
+ const newSize = getItemSize(ctx, targetId, scrollTarget, state.props.data[scrollTarget]);
1777
+ const prevSize = scrollingTo == null ? void 0 : scrollingTo.itemSize;
1778
+ if (newSize !== void 0 && prevSize !== void 0 && newSize !== prevSize) {
1779
+ const diff = newSize - prevSize;
1780
+ if (diff !== 0) {
1781
+ positionDiff += diff * scrollingToViewPosition;
1782
+ scrollingTo.itemSize = newSize;
1783
+ }
1784
+ }
1785
+ }
1786
+ updateAnchorLock(state, {
1787
+ anchorId: anchorIdForLock,
1788
+ anchorPosition: anchorPositionForLock,
1789
+ dataChanged,
1790
+ now,
1791
+ positionDiff
1792
+ });
1793
+ if (shouldQueueNativeMVCPAdjust(dataChanged, state, positionDiff, prevTotalSize, prevScroll, scrollTarget)) {
1794
+ state.pendingNativeMVCPAdjust = {
1795
+ amount: positionDiff,
1796
+ closestDistanceToClamp: Math.abs(
1797
+ prevScroll - Math.max(0, getContentSize(ctx) - state.scrollLength)
1798
+ ),
1799
+ hasApproachedClamp: false,
1800
+ manualApplied: 0,
1801
+ startScroll: prevScroll
1802
+ };
1803
+ maybeApplyPredictedNativeMVCPAdjust(ctx);
1804
+ return;
1805
+ }
1806
+ if (Math.abs(positionDiff) > MVCP_POSITION_EPSILON) {
1807
+ requestAdjust(ctx, positionDiff, dataChanged && mvcpData);
1808
+ }
1809
+ };
1810
+ }
1811
+ }
1812
+
1813
+ // src/platform/flushSync.native.ts
1814
+ var flushSync = (fn) => {
1815
+ fn();
1816
+ };
1817
+
1818
+ // src/core/updateScroll.ts
1819
+ function updateScroll(ctx, newScroll, forceUpdate) {
1820
+ var _a3;
1821
+ const state = ctx.state;
1822
+ const { ignoreScrollFromMVCP, lastScrollAdjustForHistory, scrollAdjustHandler, scrollHistory, scrollingTo } = state;
1823
+ const prevScroll = state.scroll;
1824
+ state.hasScrolled = true;
1825
+ state.lastBatchingAction = Date.now();
1826
+ const currentTime = Date.now();
1827
+ const adjust = scrollAdjustHandler.getAdjust();
1828
+ const adjustChanged = lastScrollAdjustForHistory !== void 0 && Math.abs(adjust - lastScrollAdjustForHistory) > 0.1;
1829
+ if (adjustChanged) {
1830
+ scrollHistory.length = 0;
1831
+ }
1832
+ state.lastScrollAdjustForHistory = adjust;
1833
+ if (scrollingTo === void 0 && !(scrollHistory.length === 0 && newScroll === state.scroll)) {
1834
+ if (!adjustChanged) {
1835
+ scrollHistory.push({ scroll: newScroll, time: currentTime });
1836
+ }
1837
+ }
1838
+ if (scrollHistory.length > 5) {
1839
+ scrollHistory.shift();
1840
+ }
1841
+ if (ignoreScrollFromMVCP && !scrollingTo) {
1842
+ const { lt, gt } = ignoreScrollFromMVCP;
1843
+ if (lt && newScroll < lt || gt && newScroll > gt) {
1844
+ state.ignoreScrollFromMVCPIgnored = true;
1845
+ return;
1846
+ }
1847
+ }
1848
+ state.scrollPrev = prevScroll;
1849
+ state.scrollPrevTime = state.scrollTime;
1850
+ state.scroll = newScroll;
1851
+ state.scrollTime = currentTime;
1852
+ const scrollDelta = Math.abs(newScroll - prevScroll);
1853
+ const didResolvePendingNativeMVCPAdjust = resolvePendingNativeMVCPAdjust(ctx, newScroll);
1854
+ const scrollLength = state.scrollLength;
1855
+ const lastCalculated = state.scrollLastCalculate;
1856
+ const useAggressiveItemRecalculation = isInMVCPActiveMode(state);
1857
+ const shouldUpdate = useAggressiveItemRecalculation || didResolvePendingNativeMVCPAdjust || forceUpdate || lastCalculated === void 0 || Math.abs(state.scroll - lastCalculated) > 2;
1858
+ if (shouldUpdate) {
1859
+ state.scrollLastCalculate = state.scroll;
1860
+ state.ignoreScrollFromMVCPIgnored = false;
1861
+ state.lastScrollDelta = scrollDelta;
1862
+ const runCalculateItems = () => {
1863
+ var _a4;
1864
+ (_a4 = state.triggerCalculateItemsInView) == null ? void 0 : _a4.call(state, { doMVCP: scrollingTo !== void 0 });
1865
+ checkThresholds(ctx);
1866
+ };
1867
+ if (Platform2.OS === "web" && scrollLength > 0 && scrollingTo === void 0 && scrollDelta > scrollLength) {
1868
+ flushSync(runCalculateItems);
1869
+ } else {
1870
+ runCalculateItems();
1871
+ }
1872
+ const shouldMaintainScrollAtEndAfterPendingSettle = !!state.pendingMaintainScrollAtEnd || !!((_a3 = state.props.maintainScrollAtEnd) == null ? void 0 : _a3.onDataChange);
1873
+ if (didResolvePendingNativeMVCPAdjust && shouldMaintainScrollAtEndAfterPendingSettle) {
1874
+ state.pendingMaintainScrollAtEnd = false;
1875
+ doMaintainScrollAtEnd(ctx);
1876
+ }
1877
+ state.dataChangeNeedsScrollUpdate = false;
1878
+ state.lastScrollDelta = 0;
1879
+ }
1880
+ }
1881
+
1882
+ // src/utils/requestAdjust.ts
1883
+ function requestAdjust(ctx, positionDiff, dataChanged) {
1884
+ const state = ctx.state;
1885
+ if (Math.abs(positionDiff) > 0.1) {
1886
+ const needsScrollWorkaround = Platform2.OS === "android" && !IsNewArchitecture && dataChanged && state.scroll <= positionDiff;
1887
+ const doit = () => {
1888
+ if (needsScrollWorkaround) {
1889
+ scrollTo(ctx, {
1890
+ noScrollingTo: true,
1891
+ offset: state.scroll
1892
+ });
1893
+ } else {
1894
+ state.scrollAdjustHandler.requestAdjust(positionDiff);
1895
+ if (state.adjustingFromInitialMount) {
1896
+ state.adjustingFromInitialMount--;
1897
+ }
1898
+ }
1899
+ };
1900
+ state.scroll += positionDiff;
1901
+ state.scrollForNextCalculateItemsInView = void 0;
1902
+ const readyToRender = peek$(ctx, "readyToRender");
1903
+ if (readyToRender) {
1904
+ doit();
1905
+ if (Platform2.OS !== "web") {
1906
+ const threshold = state.scroll - positionDiff / 2;
1907
+ if (!state.ignoreScrollFromMVCP) {
1908
+ state.ignoreScrollFromMVCP = {};
1909
+ }
1910
+ if (positionDiff > 0) {
1911
+ state.ignoreScrollFromMVCP.lt = threshold;
1912
+ } else {
1913
+ state.ignoreScrollFromMVCP.gt = threshold;
1914
+ }
1915
+ if (state.ignoreScrollFromMVCPTimeout) {
1916
+ clearTimeout(state.ignoreScrollFromMVCPTimeout);
1917
+ }
1918
+ const delay = needsScrollWorkaround ? 250 : 100;
1919
+ state.ignoreScrollFromMVCPTimeout = setTimeout(() => {
1920
+ state.ignoreScrollFromMVCP = void 0;
1921
+ const shouldForceUpdate = state.ignoreScrollFromMVCPIgnored && state.scrollProcessingEnabled !== false;
1922
+ if (shouldForceUpdate) {
1923
+ state.ignoreScrollFromMVCPIgnored = false;
1924
+ state.scrollPending = state.scroll;
1925
+ updateScroll(ctx, state.scroll, true);
1926
+ }
1927
+ }, delay);
1928
+ }
1929
+ } else {
1930
+ state.adjustingFromInitialMount = (state.adjustingFromInitialMount || 0) + 1;
1931
+ requestAnimationFrame(doit);
1932
+ }
1933
+ }
1934
+ }
1935
+
1936
+ // src/core/ensureInitialAnchor.ts
1937
+ var INITIAL_ANCHOR_TOLERANCE = 0.5;
1938
+ var INITIAL_ANCHOR_MAX_ATTEMPTS = 4;
1939
+ var INITIAL_ANCHOR_SETTLED_TICKS = 2;
1940
+ function ensureInitialAnchor(ctx) {
1941
+ var _a3, _b, _c, _d, _e, _f;
1942
+ const state = ctx.state;
1943
+ const { initialAnchor, didContainersLayout, scroll, scrollLength } = state;
1944
+ const anchor = initialAnchor;
1945
+ if (state.initialScroll || ((_a3 = state.scrollingTo) == null ? void 0 : _a3.isInitialScroll)) {
1946
+ return;
1947
+ }
1948
+ const item = state.props.data[anchor.index];
1949
+ if (!didContainersLayout) {
1950
+ return;
1951
+ }
1952
+ const id = getId(state, anchor.index);
1953
+ if (state.positions[anchor.index] === void 0) {
1954
+ return;
1955
+ }
1956
+ const size = getItemSize(ctx, id, anchor.index, item, true, true);
1957
+ if (size === void 0) {
1958
+ return;
1959
+ }
1960
+ const availableSpace = Math.max(0, scrollLength - size);
1961
+ const topOffsetAdjustment = getTopOffsetAdjustment(ctx);
1962
+ const desiredOffset = calculateOffsetForIndex(ctx, anchor.index) + topOffsetAdjustment - ((_b = anchor.viewOffset) != null ? _b : 0) - ((_c = anchor.viewPosition) != null ? _c : 0) * availableSpace;
1963
+ const clampedDesiredOffset = clampScrollOffset(ctx, desiredOffset, anchor);
1964
+ const delta = clampedDesiredOffset - scroll;
1965
+ if (Math.abs(delta) <= INITIAL_ANCHOR_TOLERANCE) {
1966
+ const settledTicks = ((_d = anchor.settledTicks) != null ? _d : 0) + 1;
1967
+ if (settledTicks >= INITIAL_ANCHOR_SETTLED_TICKS) {
1968
+ state.initialAnchor = void 0;
1969
+ } else {
1970
+ anchor.settledTicks = settledTicks;
1971
+ }
1972
+ return;
1973
+ }
1974
+ if (((_e = anchor.attempts) != null ? _e : 0) >= INITIAL_ANCHOR_MAX_ATTEMPTS) {
1975
+ state.initialAnchor = void 0;
1976
+ return;
1977
+ }
1978
+ const lastDelta = anchor.lastDelta;
1979
+ if (lastDelta !== void 0 && Math.abs(delta) >= Math.abs(lastDelta)) {
1980
+ state.initialAnchor = void 0;
1981
+ return;
1982
+ }
1983
+ Object.assign(anchor, {
1984
+ attempts: ((_f = anchor.attempts) != null ? _f : 0) + 1,
1985
+ lastDelta: delta,
1986
+ settledTicks: 0
1987
+ });
1988
+ requestAdjust(ctx, delta);
1989
+ }
1990
+
1991
+ // src/core/prepareColumnStartState.ts
1992
+ function prepareColumnStartState(ctx, startIndex, useAverageSize) {
1993
+ var _a3;
1994
+ const state = ctx.state;
1995
+ const numColumns = peek$(ctx, "numColumns");
1996
+ let rowStartIndex = startIndex;
1997
+ const columnAtStart = state.columns[startIndex];
1998
+ if (columnAtStart !== 1) {
1999
+ rowStartIndex = findRowStartIndex(state, numColumns, startIndex);
2000
+ }
2001
+ let currentRowTop = 0;
2002
+ const column = state.columns[rowStartIndex];
2003
+ if (rowStartIndex > 0) {
2004
+ const prevIndex = rowStartIndex - 1;
2005
+ const prevPosition = (_a3 = state.positions[prevIndex]) != null ? _a3 : 0;
2006
+ const prevRowStart = findRowStartIndex(state, numColumns, prevIndex);
2007
+ const prevRowHeight = calculateRowMaxSize(ctx, prevRowStart, prevIndex, useAverageSize);
2008
+ currentRowTop = prevPosition + prevRowHeight;
2009
+ }
2010
+ return {
2011
+ column,
2012
+ currentRowTop,
2013
+ startIndex: rowStartIndex
2014
+ };
2015
+ }
2016
+ function findRowStartIndex(state, numColumns, index) {
2017
+ if (numColumns <= 1) {
2018
+ return Math.max(0, index);
2019
+ }
2020
+ let rowStart = Math.max(0, index);
2021
+ while (rowStart > 0) {
2022
+ const columnForIndex = state.columns[rowStart];
2023
+ if (columnForIndex === 1) {
2024
+ break;
2025
+ }
2026
+ rowStart--;
2027
+ }
2028
+ return rowStart;
2029
+ }
2030
+ function calculateRowMaxSize(ctx, startIndex, endIndex, useAverageSize) {
2031
+ const state = ctx.state;
2032
+ if (endIndex < startIndex) {
2033
+ return 0;
2034
+ }
2035
+ const { data } = state.props;
2036
+ if (!data) {
2037
+ return 0;
2038
+ }
2039
+ let maxSize = 0;
2040
+ for (let i = startIndex; i <= endIndex; i++) {
2041
+ if (i < 0 || i >= data.length) {
2042
+ continue;
2043
+ }
2044
+ const id = state.idCache[i];
2045
+ const size = getItemSize(ctx, id, i, data[i], useAverageSize);
2046
+ if (size > maxSize) {
2047
+ maxSize = size;
2048
+ }
2049
+ }
2050
+ return maxSize;
2051
+ }
2052
+
2053
+ // src/core/updateTotalSize.ts
2054
+ function updateTotalSize(ctx) {
2055
+ var _a3, _b;
2056
+ const state = ctx.state;
2057
+ const {
2058
+ positions,
2059
+ props: { data }
2060
+ } = state;
2061
+ const numColumns = (_a3 = peek$(ctx, "numColumns")) != null ? _a3 : 1;
2062
+ if (data.length === 0) {
2063
+ addTotalSize(ctx, null, 0);
2064
+ } else {
2065
+ const lastIndex = data.length - 1;
2066
+ const lastId = getId(state, lastIndex);
2067
+ const lastPosition = positions[lastIndex];
2068
+ if (lastId !== void 0 && lastPosition !== void 0) {
2069
+ if (numColumns > 1) {
2070
+ let rowStart = lastIndex;
2071
+ while (rowStart > 0) {
2072
+ const column = state.columns[rowStart];
2073
+ if (column === 1 || column === void 0) {
2074
+ break;
2075
+ }
2076
+ rowStart -= 1;
2077
+ }
2078
+ let maxSize = 0;
2079
+ for (let i = rowStart; i <= lastIndex; i++) {
2080
+ const rowId = (_b = state.idCache[i]) != null ? _b : getId(state, i);
2081
+ const size = getItemSize(ctx, rowId, i, data[i]);
2082
+ if (size > maxSize) {
2083
+ maxSize = size;
2084
+ }
2085
+ }
2086
+ addTotalSize(ctx, null, lastPosition + maxSize);
2087
+ } else {
2088
+ const lastSize = getItemSize(ctx, lastId, lastIndex, data[lastIndex]);
2089
+ if (lastSize !== void 0) {
2090
+ const totalSize = lastPosition + lastSize;
2091
+ addTotalSize(ctx, null, totalSize);
2092
+ }
2093
+ }
2094
+ }
2095
+ }
2096
+ }
2097
+
2098
+ // src/utils/getScrollVelocity.ts
2099
+ var getScrollVelocity = (state) => {
2100
+ const { scrollHistory } = state;
2101
+ const newestIndex = scrollHistory.length - 1;
2102
+ if (newestIndex < 1) {
2103
+ return 0;
2104
+ }
2105
+ const newest = scrollHistory[newestIndex];
2106
+ const now = Date.now();
2107
+ let direction = 0;
2108
+ for (let i = newestIndex; i > 0; i--) {
2109
+ const delta = scrollHistory[i].scroll - scrollHistory[i - 1].scroll;
2110
+ if (delta !== 0) {
2111
+ direction = Math.sign(delta);
2112
+ break;
2113
+ }
2114
+ }
2115
+ if (direction === 0) {
2116
+ return 0;
2117
+ }
2118
+ let oldest = newest;
2119
+ for (let i = newestIndex - 1; i >= 0; i--) {
2120
+ const current = scrollHistory[i];
2121
+ const next = scrollHistory[i + 1];
2122
+ const delta = next.scroll - current.scroll;
2123
+ const deltaSign = Math.sign(delta);
2124
+ if (deltaSign !== 0 && deltaSign !== direction) {
2125
+ break;
2126
+ }
2127
+ if (now - current.time > 1e3) {
2128
+ break;
2129
+ }
2130
+ oldest = current;
2131
+ }
2132
+ const scrollDiff = newest.scroll - oldest.scroll;
2133
+ const timeDiff = newest.time - oldest.time;
2134
+ return timeDiff > 0 ? scrollDiff / timeDiff : 0;
2135
+ };
2136
+
2137
+ // src/utils/updateSnapToOffsets.ts
2138
+ function updateSnapToOffsets(ctx) {
2139
+ const state = ctx.state;
2140
+ const {
2141
+ props: { snapToIndices }
2142
+ } = state;
2143
+ const snapToOffsets = Array(snapToIndices.length);
2144
+ for (let i = 0; i < snapToIndices.length; i++) {
2145
+ const idx = snapToIndices[i];
2146
+ getId(state, idx);
2147
+ snapToOffsets[i] = state.positions[idx];
2148
+ }
2149
+ set$(ctx, "snapToOffsets", snapToOffsets);
2150
+ }
2151
+
2152
+ // src/core/updateItemPositions.ts
2153
+ function updateItemPositions(ctx, dataChanged, { startIndex, scrollBottomBuffered, forceFullUpdate = false, doMVCP } = {
2154
+ doMVCP: false,
2155
+ forceFullUpdate: false,
2156
+ scrollBottomBuffered: -1,
2157
+ startIndex: 0
2158
+ }) {
2159
+ var _a3, _b, _c, _d, _e;
2160
+ const state = ctx.state;
2161
+ const hasPositionListeners = ctx.positionListeners.size > 0;
2162
+ const {
2163
+ columns,
2164
+ columnSpans,
2165
+ indexByKey,
2166
+ positions,
2167
+ idCache,
2168
+ sizesKnown,
2169
+ props: { data, getEstimatedItemSize, overrideItemLayout, snapToIndices },
2170
+ scrollingTo
2171
+ } = state;
2172
+ const dataLength = data.length;
2173
+ const numColumns = (_a3 = peek$(ctx, "numColumns")) != null ? _a3 : 1;
2174
+ const hasColumns = numColumns > 1;
2175
+ const indexByKeyForChecking = IS_DEV ? /* @__PURE__ */ new Map() : void 0;
2176
+ const extraData = peek$(ctx, "extraData");
2177
+ const layoutConfig = overrideItemLayout ? { span: 1 } : void 0;
2178
+ const lastScrollDelta = state.lastScrollDelta;
2179
+ const velocity = getScrollVelocity(state);
2180
+ const shouldOptimize = !forceFullUpdate && !dataChanged && (Math.abs(velocity) > 0 || Platform2.OS === "web" && state.scrollLength > 0 && lastScrollDelta > state.scrollLength);
2181
+ const maxVisibleArea = scrollBottomBuffered + 1e3;
2182
+ const useAverageSize = !getEstimatedItemSize;
2183
+ const preferCachedSize = !doMVCP || dataChanged || state.scrollAdjustHandler.getAdjust() !== 0 || ((_b = peek$(ctx, "scrollAdjustPending")) != null ? _b : 0) !== 0;
2184
+ let currentRowTop = 0;
2185
+ let column = 1;
2186
+ let maxSizeInRow = 0;
2187
+ if (dataChanged) {
2188
+ columnSpans.length = 0;
2189
+ }
2190
+ if (!hasColumns) {
2191
+ if (columns.length) {
2192
+ columns.length = 0;
2193
+ }
2194
+ if (columnSpans.length) {
2195
+ columnSpans.length = 0;
2196
+ }
2197
+ }
2198
+ if (startIndex > 0) {
2199
+ if (hasColumns) {
2200
+ const { startIndex: processedStartIndex, currentRowTop: initialRowTop } = prepareColumnStartState(
2201
+ ctx,
2202
+ startIndex,
2203
+ useAverageSize
2204
+ );
2205
+ startIndex = processedStartIndex;
2206
+ currentRowTop = initialRowTop;
2207
+ } else if (startIndex < dataLength) {
2208
+ const prevIndex = startIndex - 1;
2209
+ const prevId = getId(state, prevIndex);
2210
+ const prevPosition = (_c = positions[prevIndex]) != null ? _c : 0;
2211
+ const prevSize = (_d = sizesKnown.get(prevId)) != null ? _d : getItemSize(ctx, prevId, prevIndex, data[prevIndex], useAverageSize, preferCachedSize);
2212
+ currentRowTop = prevPosition + prevSize;
2213
+ }
2214
+ }
2215
+ const needsIndexByKey = dataChanged || indexByKey.size === 0;
2216
+ const canOverrideSpan = hasColumns && !!overrideItemLayout && !!layoutConfig;
2217
+ let didBreakEarly = false;
2218
+ let breakAt;
2219
+ for (let i = startIndex; i < dataLength; i++) {
2220
+ if (shouldOptimize && breakAt !== void 0 && i > breakAt) {
2221
+ didBreakEarly = true;
2222
+ break;
2223
+ }
2224
+ if (shouldOptimize && breakAt === void 0 && !scrollingTo && !dataChanged && currentRowTop > maxVisibleArea) {
2225
+ const itemsPerRow = hasColumns ? numColumns : 1;
2226
+ breakAt = i + itemsPerRow + 10;
2227
+ }
2228
+ const id = (_e = idCache[i]) != null ? _e : getId(state, i);
2229
+ let span = 1;
2230
+ if (canOverrideSpan) {
2231
+ layoutConfig.span = 1;
2232
+ overrideItemLayout(layoutConfig, data[i], i, numColumns, extraData);
2233
+ const requestedSpan = layoutConfig.span;
2234
+ if (requestedSpan !== void 0 && Number.isFinite(requestedSpan)) {
2235
+ span = Math.max(1, Math.min(numColumns, Math.round(requestedSpan)));
2236
+ }
2237
+ }
2238
+ if (hasColumns && column + span - 1 > numColumns) {
2239
+ currentRowTop += maxSizeInRow;
2240
+ column = 1;
2241
+ maxSizeInRow = 0;
2242
+ }
2243
+ const knownSize = sizesKnown.get(id);
2244
+ const size = knownSize !== void 0 ? knownSize : getItemSize(ctx, id, i, data[i], useAverageSize, preferCachedSize);
2245
+ if (IS_DEV && needsIndexByKey) {
2246
+ if (indexByKeyForChecking.has(id)) {
2247
+ console.error(
2248
+ `[legend-list] Error: Detected overlapping key (${id}) which causes missing items and gaps and other terrrible things. Check that keyExtractor returns unique values.`
2249
+ );
2250
+ }
2251
+ indexByKeyForChecking.set(id, i);
2252
+ }
2253
+ if (currentRowTop !== positions[i]) {
2254
+ positions[i] = currentRowTop;
2255
+ if (hasPositionListeners) {
2256
+ notifyPosition$(ctx, id, currentRowTop);
2257
+ }
2258
+ }
2259
+ if (needsIndexByKey) {
2260
+ indexByKey.set(id, i);
2261
+ }
2262
+ if (!hasColumns) {
2263
+ currentRowTop += size;
2264
+ } else {
2265
+ columns[i] = column;
2266
+ columnSpans[i] = span;
2267
+ if (size > maxSizeInRow) {
2268
+ maxSizeInRow = size;
2269
+ }
2270
+ column += span;
2271
+ if (column > numColumns) {
2272
+ currentRowTop += maxSizeInRow;
2273
+ column = 1;
2274
+ maxSizeInRow = 0;
2275
+ }
2276
+ }
2277
+ }
2278
+ if (!didBreakEarly) {
2279
+ updateTotalSize(ctx);
2280
+ }
2281
+ if (snapToIndices) {
2282
+ updateSnapToOffsets(ctx);
2283
+ }
2284
+ }
2285
+
2286
+ // src/core/viewability.ts
2287
+ function ensureViewabilityState(ctx, configId) {
2288
+ let map = ctx.mapViewabilityConfigStates;
2289
+ if (!map) {
2290
+ map = /* @__PURE__ */ new Map();
2291
+ ctx.mapViewabilityConfigStates = map;
2292
+ }
2293
+ let state = map.get(configId);
2294
+ if (!state) {
2295
+ state = { end: -1, previousEnd: -1, previousStart: -1, start: -1, viewableItems: [] };
2296
+ map.set(configId, state);
2297
+ }
2298
+ return state;
2299
+ }
2300
+ function setupViewability(props) {
2301
+ let { viewabilityConfig, viewabilityConfigCallbackPairs, onViewableItemsChanged } = props;
2302
+ if (viewabilityConfig || onViewableItemsChanged) {
2303
+ viewabilityConfigCallbackPairs = [
2304
+ ...viewabilityConfigCallbackPairs || [],
2305
+ {
2306
+ onViewableItemsChanged,
2307
+ viewabilityConfig: viewabilityConfig || {
2308
+ viewAreaCoveragePercentThreshold: 0
2309
+ }
2310
+ }
2311
+ ];
2312
+ }
2313
+ return viewabilityConfigCallbackPairs;
2314
+ }
2315
+ function updateViewableItems(state, ctx, viewabilityConfigCallbackPairs, scrollSize, start, end) {
2316
+ const {
2317
+ timeouts,
2318
+ props: { data }
2319
+ } = state;
2320
+ for (const viewabilityConfigCallbackPair of viewabilityConfigCallbackPairs) {
2321
+ const viewabilityState = ensureViewabilityState(ctx, viewabilityConfigCallbackPair.viewabilityConfig.id);
2322
+ viewabilityState.start = start;
2323
+ viewabilityState.end = end;
2324
+ if (viewabilityConfigCallbackPair.viewabilityConfig.minimumViewTime) {
2325
+ const timer = setTimeout(() => {
2326
+ timeouts.delete(timer);
2327
+ updateViewableItemsWithConfig(data, viewabilityConfigCallbackPair, state, ctx, scrollSize);
2328
+ }, viewabilityConfigCallbackPair.viewabilityConfig.minimumViewTime);
2329
+ timeouts.add(timer);
2330
+ } else {
2331
+ updateViewableItemsWithConfig(data, viewabilityConfigCallbackPair, state, ctx, scrollSize);
2332
+ }
2333
+ }
2334
+ }
2335
+ function updateViewableItemsWithConfig(data, viewabilityConfigCallbackPair, state, ctx, scrollSize) {
2336
+ const { viewabilityConfig, onViewableItemsChanged } = viewabilityConfigCallbackPair;
2337
+ const configId = viewabilityConfig.id;
2338
+ const viewabilityState = ensureViewabilityState(ctx, configId);
2339
+ const { viewableItems: previousViewableItems, start, end } = viewabilityState;
2340
+ const viewabilityTokens = /* @__PURE__ */ new Map();
2341
+ for (const [containerId, value] of ctx.mapViewabilityAmountValues) {
2342
+ viewabilityTokens.set(
2343
+ containerId,
2344
+ computeViewability(
2345
+ state,
2346
+ ctx,
2347
+ viewabilityConfig,
2348
+ containerId,
2349
+ value.key,
2350
+ scrollSize,
2351
+ value.item,
2352
+ value.index
2353
+ )
2354
+ );
2355
+ }
2356
+ const changed = [];
2357
+ if (previousViewableItems) {
2358
+ for (const viewToken of previousViewableItems) {
2359
+ const containerId = findContainerId(ctx, viewToken.key);
2360
+ if (!checkIsViewable(
2361
+ state,
2362
+ ctx,
2363
+ viewabilityConfig,
2364
+ containerId,
2365
+ viewToken.key,
2366
+ scrollSize,
2367
+ viewToken.item,
2368
+ viewToken.index
2369
+ )) {
2370
+ viewToken.isViewable = false;
2371
+ changed.push(viewToken);
2372
+ }
2373
+ }
2374
+ }
2375
+ const viewableItems = [];
2376
+ for (let i = start; i <= end; i++) {
2377
+ const item = data[i];
2378
+ if (item) {
2379
+ const key = getId(state, i);
2380
+ const containerId = findContainerId(ctx, key);
2381
+ if (checkIsViewable(state, ctx, viewabilityConfig, containerId, key, scrollSize, item, i)) {
2382
+ const viewToken = {
2383
+ containerId,
2384
+ index: i,
2385
+ isViewable: true,
2386
+ item,
2387
+ key
2388
+ };
2389
+ viewableItems.push(viewToken);
2390
+ if (!(previousViewableItems == null ? void 0 : previousViewableItems.find((v) => v.key === viewToken.key))) {
2391
+ changed.push(viewToken);
2392
+ }
2393
+ }
2394
+ }
2395
+ }
2396
+ Object.assign(viewabilityState, {
2397
+ previousEnd: end,
2398
+ previousStart: start,
2399
+ viewableItems
2400
+ });
2401
+ if (changed.length > 0) {
2402
+ viewabilityState.viewableItems = viewableItems;
2403
+ for (let i = 0; i < changed.length; i++) {
2404
+ const change = changed[i];
2405
+ maybeUpdateViewabilityCallback(ctx, configId, change.containerId, change);
2406
+ }
2407
+ if (onViewableItemsChanged) {
2408
+ onViewableItemsChanged({ changed, viewableItems });
2409
+ }
2410
+ }
2411
+ for (const [containerId, value] of ctx.mapViewabilityAmountValues) {
2412
+ if (value.sizeVisible < 0) {
2413
+ ctx.mapViewabilityAmountValues.delete(containerId);
2414
+ }
2415
+ }
2416
+ }
2417
+ function shallowEqual(prev, next) {
2418
+ if (!prev) return false;
2419
+ const keys = Object.keys(next);
2420
+ for (let i = 0; i < keys.length; i++) {
2421
+ const k = keys[i];
2422
+ if (prev[k] !== next[k]) return false;
2423
+ }
2424
+ return true;
2425
+ }
2426
+ function computeViewability(state, ctx, viewabilityConfig, containerId, key, scrollSize, item, index) {
2427
+ const { sizes, scroll: scrollState } = state;
2428
+ const topPad = (peek$(ctx, "stylePaddingTop") || 0) + (peek$(ctx, "headerSize") || 0);
2429
+ const { itemVisiblePercentThreshold, viewAreaCoveragePercentThreshold } = viewabilityConfig;
2430
+ const viewAreaMode = viewAreaCoveragePercentThreshold != null;
2431
+ const viewablePercentThreshold = viewAreaMode ? viewAreaCoveragePercentThreshold : itemVisiblePercentThreshold;
2432
+ const scroll = scrollState - topPad;
2433
+ const position = state.positions[index];
2434
+ const size = sizes.get(key) || 0;
2435
+ if (position === void 0) {
2436
+ const value2 = {
2437
+ containerId,
2438
+ index,
2439
+ isViewable: false,
2440
+ item,
2441
+ key,
2442
+ percentOfScroller: 0,
2443
+ percentVisible: 0,
2444
+ scrollSize,
2445
+ size,
2446
+ sizeVisible: -1
2447
+ };
2448
+ const prev2 = ctx.mapViewabilityAmountValues.get(containerId);
2449
+ if (!shallowEqual(prev2, value2)) {
2450
+ ctx.mapViewabilityAmountValues.set(containerId, value2);
2451
+ const cb = ctx.mapViewabilityAmountCallbacks.get(containerId);
2452
+ if (cb) {
2453
+ cb(value2);
2454
+ }
2455
+ }
2456
+ return value2;
2457
+ }
2458
+ const top = position - scroll;
2459
+ const bottom = top + size;
2460
+ const isEntirelyVisible = top >= 0 && bottom <= scrollSize && bottom > top;
2461
+ const sizeVisible = isEntirelyVisible ? size : Math.min(bottom, scrollSize) - Math.max(top, 0);
2462
+ const percentVisible = size ? isEntirelyVisible ? 100 : 100 * (sizeVisible / size) : 0;
2463
+ const percentOfScroller = size ? 100 * (sizeVisible / scrollSize) : 0;
2464
+ const percent = isEntirelyVisible ? 100 : viewAreaMode ? percentOfScroller : percentVisible;
2465
+ const isViewable = percent >= viewablePercentThreshold;
2466
+ const value = {
2467
+ containerId,
2468
+ index,
2469
+ isViewable,
2470
+ item,
2471
+ key,
2472
+ percentOfScroller,
2473
+ percentVisible,
2474
+ scrollSize,
2475
+ size,
2476
+ sizeVisible
2477
+ };
2478
+ const prev = ctx.mapViewabilityAmountValues.get(containerId);
2479
+ if (!shallowEqual(prev, value)) {
2480
+ ctx.mapViewabilityAmountValues.set(containerId, value);
2481
+ const cb = ctx.mapViewabilityAmountCallbacks.get(containerId);
2482
+ if (cb) {
2483
+ cb(value);
2484
+ }
2485
+ }
2486
+ return value;
2487
+ }
2488
+ function checkIsViewable(state, ctx, viewabilityConfig, containerId, key, scrollSize, item, index) {
2489
+ let value = ctx.mapViewabilityAmountValues.get(containerId);
2490
+ if (!value || value.key !== key) {
2491
+ value = computeViewability(state, ctx, viewabilityConfig, containerId, key, scrollSize, item, index);
2492
+ }
2493
+ return value.isViewable;
2494
+ }
2495
+ function maybeUpdateViewabilityCallback(ctx, configId, containerId, viewToken) {
2496
+ const key = containerId + configId;
2497
+ ctx.mapViewabilityValues.set(key, viewToken);
2498
+ const cb = ctx.mapViewabilityCallbacks.get(key);
2499
+ cb == null ? void 0 : cb(viewToken);
2500
+ }
2501
+ var unstableBatchedUpdates = ReactNative.unstable_batchedUpdates;
2502
+ var batchedUpdates = typeof unstableBatchedUpdates === "function" ? unstableBatchedUpdates : (fn) => fn();
2503
+
2504
+ // src/utils/checkAllSizesKnown.ts
2505
+ function isNullOrUndefined2(value) {
2506
+ return value === null || value === void 0;
2507
+ }
2508
+ function checkAllSizesKnown(state) {
2509
+ const { startBuffered, endBuffered, sizesKnown } = state;
2510
+ if (!isNullOrUndefined2(endBuffered) && !isNullOrUndefined2(startBuffered) && startBuffered >= 0 && endBuffered >= 0) {
2511
+ let areAllKnown = true;
2512
+ for (let i = startBuffered; areAllKnown && i <= endBuffered; i++) {
2513
+ const key = getId(state, i);
2514
+ areAllKnown && (areAllKnown = sizesKnown.has(key));
2515
+ }
2516
+ return areAllKnown;
2517
+ }
2518
+ return false;
2519
+ }
2520
+
2521
+ // src/utils/findAvailableContainers.ts
2522
+ function findAvailableContainers(ctx, numNeeded, startBuffered, endBuffered, pendingRemoval, requiredItemTypes, needNewContainers) {
2523
+ const numContainers = peek$(ctx, "numContainers");
2524
+ const state = ctx.state;
2525
+ const { stickyContainerPool, containerItemTypes } = state;
2526
+ const result = [];
2527
+ const availableContainers = [];
2528
+ const pendingRemovalSet = new Set(pendingRemoval);
2529
+ let pendingRemovalChanged = false;
2530
+ const stickyIndicesSet = state.props.stickyIndicesSet;
2531
+ const stickyItemIndices = (needNewContainers == null ? void 0 : needNewContainers.filter((index) => stickyIndicesSet.has(index))) || [];
2532
+ const canReuseContainer = (containerIndex, requiredType) => {
2533
+ if (!requiredType) return true;
2534
+ const existingType = containerItemTypes.get(containerIndex);
2535
+ if (!existingType) return true;
2536
+ return existingType === requiredType;
2537
+ };
2538
+ const neededTypes = requiredItemTypes ? [...requiredItemTypes] : [];
2539
+ let typeIndex = 0;
2540
+ for (let i = 0; i < stickyItemIndices.length; i++) {
2541
+ const requiredType = neededTypes[typeIndex];
2542
+ let foundContainer = false;
2543
+ for (const containerIndex of stickyContainerPool) {
2544
+ const key = peek$(ctx, `containerItemKey${containerIndex}`);
2545
+ const isPendingRemoval = pendingRemovalSet.has(containerIndex);
2546
+ if ((key === void 0 || isPendingRemoval) && canReuseContainer(containerIndex, requiredType) && !result.includes(containerIndex)) {
2547
+ result.push(containerIndex);
2548
+ if (isPendingRemoval && pendingRemovalSet.delete(containerIndex)) {
2549
+ pendingRemovalChanged = true;
2550
+ }
2551
+ foundContainer = true;
2552
+ if (requiredItemTypes) typeIndex++;
2553
+ break;
2554
+ }
2555
+ }
2556
+ if (!foundContainer) {
2557
+ const newContainerIndex = numContainers + result.filter((index) => index >= numContainers).length;
2558
+ result.push(newContainerIndex);
2559
+ stickyContainerPool.add(newContainerIndex);
2560
+ if (requiredItemTypes) typeIndex++;
2561
+ }
2562
+ }
2563
+ for (let u = 0; u < numContainers && result.length < numNeeded; u++) {
2564
+ if (stickyContainerPool.has(u)) {
2565
+ continue;
2566
+ }
2567
+ const key = peek$(ctx, `containerItemKey${u}`);
2568
+ const requiredType = neededTypes[typeIndex];
2569
+ const isPending = key !== void 0 && pendingRemovalSet.has(u);
2570
+ const canUse = key === void 0 || isPending && canReuseContainer(u, requiredType);
2571
+ if (canUse) {
2572
+ if (isPending) {
2573
+ pendingRemovalSet.delete(u);
2574
+ pendingRemovalChanged = true;
2575
+ }
2576
+ result.push(u);
2577
+ if (requiredItemTypes) {
2578
+ typeIndex++;
2579
+ }
2580
+ }
2581
+ }
2582
+ for (let u = 0; u < numContainers && result.length < numNeeded; u++) {
2583
+ if (stickyContainerPool.has(u)) {
2584
+ continue;
2585
+ }
2586
+ const key = peek$(ctx, `containerItemKey${u}`);
2587
+ if (key === void 0) continue;
2588
+ const index = state.indexByKey.get(key);
2589
+ const isOutOfView = index < startBuffered || index > endBuffered;
2590
+ if (isOutOfView) {
2591
+ const distance = index < startBuffered ? startBuffered - index : index - endBuffered;
2592
+ if (!requiredItemTypes || typeIndex < neededTypes.length && canReuseContainer(u, neededTypes[typeIndex])) {
2593
+ availableContainers.push({ distance, index: u });
2594
+ }
2595
+ }
2596
+ }
2597
+ const remaining = numNeeded - result.length;
2598
+ if (remaining > 0) {
2599
+ if (availableContainers.length > 0) {
2600
+ if (availableContainers.length > remaining) {
2601
+ availableContainers.sort(comparatorByDistance);
2602
+ availableContainers.length = remaining;
2603
+ }
2604
+ for (const container of availableContainers) {
2605
+ result.push(container.index);
2606
+ if (requiredItemTypes) {
2607
+ typeIndex++;
2608
+ }
2609
+ }
2610
+ }
2611
+ const stillNeeded = numNeeded - result.length;
2612
+ if (stillNeeded > 0) {
2613
+ for (let i = 0; i < stillNeeded; i++) {
2614
+ result.push(numContainers + i);
2615
+ }
2616
+ if (IS_DEV && numContainers + stillNeeded > peek$(ctx, "numContainersPooled")) {
2617
+ console.warn(
2618
+ "[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.",
2619
+ {
2620
+ debugInfo: {
2621
+ numContainers,
2622
+ numContainersPooled: peek$(ctx, "numContainersPooled"),
2623
+ numNeeded,
2624
+ stillNeeded
2625
+ }
2626
+ }
2627
+ );
2628
+ }
2629
+ }
2630
+ }
2631
+ if (pendingRemovalChanged) {
2632
+ pendingRemoval.length = 0;
2633
+ for (const value of pendingRemovalSet) {
2634
+ pendingRemoval.push(value);
2635
+ }
2636
+ }
2637
+ return result.sort(comparatorDefault);
2638
+ }
2639
+ function comparatorByDistance(a, b) {
2640
+ return b.distance - a.distance;
2641
+ }
2642
+
2643
+ // src/core/scrollToIndex.ts
2644
+ function scrollToIndex(ctx, {
2645
+ index,
2646
+ viewOffset = 0,
2647
+ animated = true,
2648
+ forceScroll,
2649
+ isInitialScroll,
2650
+ viewPosition
2651
+ }) {
2652
+ const state = ctx.state;
2653
+ const { data } = state.props;
2654
+ if (index >= data.length) {
2655
+ index = data.length - 1;
2656
+ } else if (index < 0) {
2657
+ index = 0;
2658
+ }
2659
+ const firstIndexOffset = calculateOffsetForIndex(ctx, index);
2660
+ const isLast = index === data.length - 1;
2661
+ if (isLast && viewPosition === void 0) {
2662
+ viewPosition = 1;
2663
+ }
2664
+ state.scrollForNextCalculateItemsInView = void 0;
2665
+ const targetId = getId(state, index);
2666
+ const itemSize = getItemSize(ctx, targetId, index, state.props.data[index]);
2667
+ scrollTo(ctx, {
2668
+ animated,
2669
+ forceScroll,
2670
+ index,
2671
+ isInitialScroll,
2672
+ itemSize,
2673
+ offset: firstIndexOffset,
2674
+ viewOffset,
2675
+ viewPosition: viewPosition != null ? viewPosition : 0
2676
+ });
2677
+ }
2678
+
2679
+ // src/utils/performInitialScroll.ts
2680
+ function performInitialScroll(ctx, params) {
2681
+ var _a3;
2682
+ const { forceScroll, initialScrollUsesOffset, resolvedOffset, target } = params;
2683
+ if (initialScrollUsesOffset || resolvedOffset !== void 0) {
2684
+ scrollTo(ctx, {
2685
+ animated: false,
2686
+ forceScroll,
2687
+ index: initialScrollUsesOffset ? void 0 : target.index,
2688
+ isInitialScroll: true,
2689
+ offset: (_a3 = resolvedOffset != null ? resolvedOffset : target.contentOffset) != null ? _a3 : 0,
2690
+ precomputedWithViewOffset: resolvedOffset !== void 0
2691
+ });
2692
+ return;
2693
+ }
2694
+ if (target.index === void 0) {
2695
+ return;
2696
+ }
2697
+ scrollToIndex(ctx, {
2698
+ ...target,
2699
+ animated: false,
2700
+ forceScroll,
2701
+ isInitialScroll: true
2702
+ });
2703
+ }
2704
+
2705
+ // src/utils/setDidLayout.ts
2706
+ function setDidLayout(ctx) {
2707
+ const state = ctx.state;
2708
+ const { initialScroll } = state;
2709
+ state.queuedInitialLayout = true;
2710
+ checkAtBottom(ctx);
2711
+ if (initialScroll) {
2712
+ const runScroll = () => {
2713
+ var _a3, _b;
2714
+ const target = state.initialScroll;
2715
+ if (!target) {
2716
+ return;
2717
+ }
2718
+ const activeInitialTargetOffset = ((_a3 = state.scrollingTo) == null ? void 0 : _a3.isInitialScroll) ? (_b = state.scrollingTo.targetOffset) != null ? _b : state.scrollingTo.offset : void 0;
2719
+ const desiredInitialTargetOffset = state.initialScrollUsesOffset ? target.contentOffset : activeInitialTargetOffset;
2720
+ const isAlreadyAtDesiredInitialTarget = desiredInitialTargetOffset !== void 0 && Math.abs(state.scroll - desiredInitialTargetOffset) <= 1 && Math.abs(state.scrollPending - desiredInitialTargetOffset) <= 1;
2721
+ if (!isAlreadyAtDesiredInitialTarget) {
2722
+ performInitialScroll(ctx, {
2723
+ forceScroll: true,
2724
+ initialScrollUsesOffset: state.initialScrollUsesOffset,
2725
+ // Offset-based initial scrolls do not need item lookup, so they can run even before data exists.
2726
+ // Re-run on the next frame to pick up measured viewport size without waiting for index resolution.
2727
+ target
2728
+ });
2729
+ }
2730
+ };
2731
+ runScroll();
2732
+ requestAnimationFrame(runScroll);
2733
+ }
2734
+ setInitialRenderState(ctx, { didLayout: true });
2735
+ }
2736
+
2737
+ // src/core/calculateItemsInView.ts
2738
+ function findCurrentStickyIndex(stickyArray, scroll, state) {
2739
+ const positions = state.positions;
2740
+ for (let i = stickyArray.length - 1; i >= 0; i--) {
2741
+ const stickyIndex = stickyArray[i];
2742
+ const stickyPos = positions[stickyIndex];
2743
+ if (stickyPos !== void 0 && scroll >= stickyPos) {
2744
+ return i;
2745
+ }
2746
+ }
2747
+ return -1;
2748
+ }
2749
+ function getActiveStickyIndices(ctx, stickyHeaderIndices) {
2750
+ const state = ctx.state;
2751
+ return new Set(
2752
+ Array.from(state.stickyContainerPool).map((i) => peek$(ctx, `containerItemKey${i}`)).map((key) => key ? state.indexByKey.get(key) : void 0).filter((idx) => idx !== void 0 && stickyHeaderIndices.has(idx))
2753
+ );
2754
+ }
2755
+ function handleStickyActivation(ctx, stickyHeaderIndices, stickyArray, currentStickyIdx, needNewContainers, needNewContainersSet, startBuffered, endBuffered) {
2756
+ var _a3;
2757
+ const state = ctx.state;
2758
+ const activeIndices = getActiveStickyIndices(ctx, stickyHeaderIndices);
2759
+ set$(ctx, "activeStickyIndex", currentStickyIdx >= 0 ? stickyArray[currentStickyIdx] : -1);
2760
+ for (let offset = 0; offset <= 1; offset++) {
2761
+ const idx = currentStickyIdx - offset;
2762
+ if (idx < 0 || activeIndices.has(stickyArray[idx])) continue;
2763
+ const stickyIndex = stickyArray[idx];
2764
+ const stickyId = (_a3 = state.idCache[stickyIndex]) != null ? _a3 : getId(state, stickyIndex);
2765
+ if (stickyId && !state.containerItemKeys.has(stickyId) && (stickyIndex < startBuffered || stickyIndex > endBuffered) && !needNewContainersSet.has(stickyIndex)) {
2766
+ needNewContainersSet.add(stickyIndex);
2767
+ needNewContainers.push(stickyIndex);
2768
+ }
2769
+ }
2770
+ }
2771
+ function handleStickyRecycling(ctx, stickyArray, scroll, drawDistance, currentStickyIdx, pendingRemoval, alwaysRenderIndicesSet) {
2772
+ var _a3, _b;
2773
+ const state = ctx.state;
2774
+ for (const containerIndex of state.stickyContainerPool) {
2775
+ const itemKey = peek$(ctx, `containerItemKey${containerIndex}`);
2776
+ const itemIndex = itemKey ? state.indexByKey.get(itemKey) : void 0;
2777
+ if (itemIndex === void 0) continue;
2778
+ if (alwaysRenderIndicesSet.has(itemIndex)) continue;
2779
+ const arrayIdx = stickyArray.indexOf(itemIndex);
2780
+ if (arrayIdx === -1) {
2781
+ state.stickyContainerPool.delete(containerIndex);
2782
+ set$(ctx, `containerSticky${containerIndex}`, false);
2783
+ continue;
2784
+ }
2785
+ const isRecentSticky = arrayIdx >= currentStickyIdx - 1 && arrayIdx <= currentStickyIdx + 1;
2786
+ if (isRecentSticky) continue;
2787
+ const nextIndex = stickyArray[arrayIdx + 1];
2788
+ let shouldRecycle = false;
2789
+ if (nextIndex) {
2790
+ const nextPos = state.positions[nextIndex];
2791
+ shouldRecycle = nextPos !== void 0 && scroll > nextPos + drawDistance * 2;
2792
+ } else {
2793
+ const currentId = (_a3 = state.idCache[itemIndex]) != null ? _a3 : getId(state, itemIndex);
2794
+ if (currentId) {
2795
+ const currentPos = state.positions[itemIndex];
2796
+ const currentSize = (_b = state.sizes.get(currentId)) != null ? _b : getItemSize(ctx, currentId, itemIndex, state.props.data[itemIndex]);
2797
+ shouldRecycle = currentPos !== void 0 && scroll > currentPos + currentSize + drawDistance * 3;
2798
+ }
2799
+ }
2800
+ if (shouldRecycle) {
2801
+ pendingRemoval.push(containerIndex);
2802
+ }
2803
+ }
2804
+ }
2805
+ function calculateItemsInView(ctx, params = {}) {
2806
+ const state = ctx.state;
2807
+ batchedUpdates(() => {
2808
+ var _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
2809
+ const {
2810
+ columns,
2811
+ columnSpans,
2812
+ containerItemKeys,
2813
+ enableScrollForNextCalculateItemsInView,
2814
+ idCache,
2815
+ indexByKey,
2816
+ initialScroll,
2817
+ minIndexSizeChanged,
2818
+ positions,
2819
+ props: {
2820
+ alwaysRenderIndicesArr,
2821
+ alwaysRenderIndicesSet,
2822
+ drawDistance,
2823
+ getItemType,
2824
+ itemsAreEqual,
2825
+ keyExtractor,
2826
+ onStickyHeaderChange
2827
+ },
2828
+ scrollForNextCalculateItemsInView,
2829
+ scrollLength,
2830
+ sizes,
2831
+ startBufferedId: startBufferedIdOrig,
2832
+ viewabilityConfigCallbackPairs
2833
+ } = state;
2834
+ const { data } = state.props;
2835
+ const stickyIndicesArr = state.props.stickyIndicesArr || [];
2836
+ const stickyIndicesSet = state.props.stickyIndicesSet || /* @__PURE__ */ new Set();
2837
+ const alwaysRenderArr = alwaysRenderIndicesArr || [];
2838
+ const alwaysRenderSet = alwaysRenderIndicesSet || /* @__PURE__ */ new Set();
2839
+ const { dataChanged, doMVCP, forceFullItemPositions } = params;
2840
+ const prevNumContainers = peek$(ctx, "numContainers");
2841
+ if (!data || scrollLength === 0 || !prevNumContainers) {
2842
+ if (!IsNewArchitecture && state.initialAnchor) {
2843
+ ensureInitialAnchor(ctx);
2844
+ }
2845
+ return;
2846
+ }
2847
+ let totalSize = getContentSize(ctx);
2848
+ const topPad = peek$(ctx, "stylePaddingTop") + peek$(ctx, "headerSize");
2849
+ const numColumns = peek$(ctx, "numColumns");
2850
+ const speed = getScrollVelocity(state);
2851
+ const scrollExtra = 0;
2852
+ const { queuedInitialLayout } = state;
2853
+ let { scroll: scrollState } = state;
2854
+ if (!queuedInitialLayout && initialScroll) {
2855
+ const updatedOffset = state.initialScrollUsesOffset ? (_a3 = initialScroll.contentOffset) != null ? _a3 : 0 : calculateOffsetWithOffsetPosition(
2856
+ ctx,
2857
+ calculateOffsetForIndex(ctx, initialScroll.index),
2858
+ initialScroll
2859
+ );
2860
+ scrollState = updatedOffset;
2861
+ }
2862
+ const scrollAdjustPending = (_b = peek$(ctx, "scrollAdjustPending")) != null ? _b : 0;
2863
+ const scrollAdjustPad = scrollAdjustPending - topPad;
2864
+ let scroll = Math.round(scrollState + scrollExtra + scrollAdjustPad);
2865
+ if (scroll + scrollLength > totalSize) {
2866
+ scroll = Math.max(0, totalSize - scrollLength);
2867
+ }
2868
+ const previousStickyIndex = peek$(ctx, "activeStickyIndex");
2869
+ const currentStickyIdx = stickyIndicesArr.length > 0 ? findCurrentStickyIndex(stickyIndicesArr, scroll, state) : -1;
2870
+ const nextActiveStickyIndex = currentStickyIdx >= 0 ? stickyIndicesArr[currentStickyIdx] : -1;
2871
+ if (currentStickyIdx >= 0 || previousStickyIndex >= 0) {
2872
+ set$(ctx, "activeStickyIndex", nextActiveStickyIndex);
2873
+ }
2874
+ let scrollBufferTop = drawDistance;
2875
+ let scrollBufferBottom = drawDistance;
2876
+ if (speed > 0 || speed === 0 && scroll < Math.max(50, drawDistance)) {
2877
+ scrollBufferTop = drawDistance * 0.5;
2878
+ scrollBufferBottom = drawDistance * 1.5;
2879
+ } else {
2880
+ scrollBufferTop = drawDistance * 1.5;
2881
+ scrollBufferBottom = drawDistance * 0.5;
2882
+ }
2883
+ const scrollTopBuffered = scroll - scrollBufferTop;
2884
+ const scrollBottom = scroll + scrollLength + (scroll < 0 ? -scroll : 0);
2885
+ const scrollBottomBuffered = scrollBottom + scrollBufferBottom;
2886
+ if (!dataChanged && !forceFullItemPositions && scrollForNextCalculateItemsInView) {
2887
+ const { top, bottom } = scrollForNextCalculateItemsInView;
2888
+ if (top === null && bottom === null) {
2889
+ state.scrollForNextCalculateItemsInView = void 0;
2890
+ } else if ((top === null || scrollTopBuffered > top) && (bottom === null || scrollBottomBuffered < bottom)) {
2891
+ if (!IsNewArchitecture && state.initialAnchor) {
2892
+ ensureInitialAnchor(ctx);
2893
+ }
2894
+ if (Platform2.OS !== "web" || !isInMVCPActiveMode(state)) {
2895
+ return;
2896
+ }
2897
+ }
2898
+ }
2899
+ const checkMVCP = doMVCP ? prepareMVCP(ctx, dataChanged) : void 0;
2900
+ if (dataChanged) {
2901
+ indexByKey.clear();
2902
+ idCache.length = 0;
2903
+ positions.length = 0;
2904
+ columns.length = 0;
2905
+ columnSpans.length = 0;
2906
+ }
2907
+ const startIndex = forceFullItemPositions || dataChanged ? 0 : (_c = minIndexSizeChanged != null ? minIndexSizeChanged : state.startBuffered) != null ? _c : 0;
2908
+ updateItemPositions(ctx, dataChanged, {
2909
+ doMVCP,
2910
+ forceFullUpdate: !!forceFullItemPositions,
2911
+ scrollBottomBuffered,
2912
+ startIndex
2913
+ });
2914
+ totalSize = getContentSize(ctx);
2915
+ if (minIndexSizeChanged !== void 0) {
2916
+ state.minIndexSizeChanged = void 0;
2917
+ }
2918
+ checkMVCP == null ? void 0 : checkMVCP();
2919
+ let startNoBuffer = null;
2920
+ let startBuffered = null;
2921
+ let startBufferedId = null;
2922
+ let endNoBuffer = null;
2923
+ let endBuffered = null;
2924
+ let loopStart = !dataChanged && startBufferedIdOrig ? indexByKey.get(startBufferedIdOrig) || 0 : 0;
2925
+ for (let i = loopStart; i >= 0; i--) {
2926
+ const id = (_d = idCache[i]) != null ? _d : getId(state, i);
2927
+ const top = positions[i];
2928
+ const size = (_e = sizes.get(id)) != null ? _e : getItemSize(ctx, id, i, data[i]);
2929
+ const bottom = top + size;
2930
+ if (bottom > scroll - scrollBufferTop) {
2931
+ loopStart = i;
2932
+ } else {
2933
+ break;
2934
+ }
2935
+ }
2936
+ if (numColumns > 1) {
2937
+ while (loopStart > 0) {
2938
+ const loopColumn = columns[loopStart];
2939
+ if (loopColumn === 1 || loopColumn === void 0) {
2940
+ break;
2941
+ }
2942
+ loopStart -= 1;
2943
+ }
2944
+ }
2945
+ let foundEnd = false;
2946
+ let nextTop;
2947
+ let nextBottom;
2948
+ let maxIndexRendered = 0;
2949
+ for (let i = 0; i < prevNumContainers; i++) {
2950
+ const key = peek$(ctx, `containerItemKey${i}`);
2951
+ if (key !== void 0) {
2952
+ const index = indexByKey.get(key);
2953
+ maxIndexRendered = Math.max(maxIndexRendered, index);
2954
+ }
2955
+ }
2956
+ let firstFullyOnScreenIndex;
2957
+ const dataLength = data.length;
2958
+ for (let i = Math.max(0, loopStart); i < dataLength && (!foundEnd || i <= maxIndexRendered); i++) {
2959
+ const id = (_f = idCache[i]) != null ? _f : getId(state, i);
2960
+ const size = (_g = sizes.get(id)) != null ? _g : getItemSize(ctx, id, i, data[i]);
2961
+ const top = positions[i];
2962
+ if (!foundEnd) {
2963
+ if (startNoBuffer === null && top + size > scroll) {
2964
+ startNoBuffer = i;
2965
+ }
2966
+ if (firstFullyOnScreenIndex === void 0 && top >= scroll - 10 && top <= scrollBottom) {
2967
+ firstFullyOnScreenIndex = i;
2968
+ }
2969
+ if (startBuffered === null && top + size > scrollTopBuffered) {
2970
+ startBuffered = i;
2971
+ startBufferedId = id;
2972
+ if (scrollTopBuffered < 0) {
2973
+ nextTop = null;
2974
+ } else {
2975
+ nextTop = top;
2976
+ }
2977
+ }
2978
+ if (startNoBuffer !== null) {
2979
+ if (top <= scrollBottom) {
2980
+ endNoBuffer = i;
2981
+ }
2982
+ if (top <= scrollBottomBuffered) {
2983
+ endBuffered = i;
2984
+ if (scrollBottomBuffered > totalSize) {
2985
+ nextBottom = null;
2986
+ } else {
2987
+ nextBottom = top + size;
2988
+ }
2989
+ } else {
2990
+ foundEnd = true;
2991
+ }
2992
+ }
2993
+ }
2994
+ }
2995
+ const idsInView = [];
2996
+ const firstVisibleAnchorIndex = firstFullyOnScreenIndex != null ? firstFullyOnScreenIndex : startNoBuffer;
2997
+ if (firstVisibleAnchorIndex !== null && firstVisibleAnchorIndex !== void 0 && endNoBuffer !== null) {
2998
+ for (let i = firstVisibleAnchorIndex; i <= endNoBuffer; i++) {
2999
+ const id = (_h = idCache[i]) != null ? _h : getId(state, i);
3000
+ idsInView.push(id);
3001
+ }
3002
+ }
3003
+ Object.assign(state, {
3004
+ endBuffered,
3005
+ endNoBuffer,
3006
+ firstFullyOnScreenIndex,
3007
+ idsInView,
3008
+ startBuffered,
3009
+ startBufferedId,
3010
+ startNoBuffer
3011
+ });
3012
+ if (enableScrollForNextCalculateItemsInView && nextTop !== void 0 && nextBottom !== void 0) {
3013
+ state.scrollForNextCalculateItemsInView = isNullOrUndefined(nextTop) && isNullOrUndefined(nextBottom) ? void 0 : {
3014
+ bottom: nextBottom,
3015
+ top: nextTop
3016
+ };
3017
+ }
3018
+ let numContainers = prevNumContainers;
3019
+ const pendingRemoval = [];
3020
+ if (dataChanged) {
3021
+ for (let i = 0; i < numContainers; i++) {
3022
+ const itemKey = peek$(ctx, `containerItemKey${i}`);
3023
+ if (!keyExtractor || itemKey && indexByKey.get(itemKey) === void 0) {
3024
+ pendingRemoval.push(i);
3025
+ }
3026
+ }
3027
+ }
3028
+ if (startBuffered !== null && endBuffered !== null) {
3029
+ const needNewContainers = [];
3030
+ const needNewContainersSet = /* @__PURE__ */ new Set();
3031
+ for (let i = startBuffered; i <= endBuffered; i++) {
3032
+ const id = (_i = idCache[i]) != null ? _i : getId(state, i);
3033
+ if (!containerItemKeys.has(id)) {
3034
+ needNewContainersSet.add(i);
3035
+ needNewContainers.push(i);
3036
+ }
3037
+ }
3038
+ if (alwaysRenderArr.length > 0) {
3039
+ for (const index of alwaysRenderArr) {
3040
+ if (index < 0 || index >= dataLength) continue;
3041
+ const id = (_j = idCache[index]) != null ? _j : getId(state, index);
3042
+ if (id && !containerItemKeys.has(id) && !needNewContainersSet.has(index)) {
3043
+ needNewContainersSet.add(index);
3044
+ needNewContainers.push(index);
3045
+ }
3046
+ }
3047
+ }
3048
+ if (stickyIndicesArr.length > 0) {
3049
+ handleStickyActivation(
3050
+ ctx,
3051
+ stickyIndicesSet,
3052
+ stickyIndicesArr,
3053
+ currentStickyIdx,
3054
+ needNewContainers,
3055
+ needNewContainersSet,
3056
+ startBuffered,
3057
+ endBuffered
3058
+ );
3059
+ } else if (previousStickyIndex !== -1) {
3060
+ set$(ctx, "activeStickyIndex", -1);
3061
+ }
3062
+ if (needNewContainers.length > 0) {
3063
+ const requiredItemTypes = getItemType ? needNewContainers.map((i) => {
3064
+ const itemType = getItemType(data[i], i);
3065
+ return itemType !== void 0 ? String(itemType) : "";
3066
+ }) : void 0;
3067
+ const availableContainers = findAvailableContainers(
3068
+ ctx,
3069
+ needNewContainers.length,
3070
+ startBuffered,
3071
+ endBuffered,
3072
+ pendingRemoval,
3073
+ requiredItemTypes,
3074
+ needNewContainers
3075
+ );
3076
+ for (let idx = 0; idx < needNewContainers.length; idx++) {
3077
+ const i = needNewContainers[idx];
3078
+ const containerIndex = availableContainers[idx];
3079
+ const id = (_k = idCache[i]) != null ? _k : getId(state, i);
3080
+ const oldKey = peek$(ctx, `containerItemKey${containerIndex}`);
3081
+ if (oldKey && oldKey !== id) {
3082
+ containerItemKeys.delete(oldKey);
3083
+ }
3084
+ set$(ctx, `containerItemKey${containerIndex}`, id);
3085
+ set$(ctx, `containerItemData${containerIndex}`, data[i]);
3086
+ if (requiredItemTypes) {
3087
+ state.containerItemTypes.set(containerIndex, requiredItemTypes[idx]);
3088
+ }
3089
+ containerItemKeys.set(id, containerIndex);
3090
+ const containerSticky = `containerSticky${containerIndex}`;
3091
+ const isSticky = stickyIndicesSet.has(i);
3092
+ const isAlwaysRender = alwaysRenderSet.has(i);
3093
+ if (isSticky) {
3094
+ set$(ctx, containerSticky, true);
3095
+ state.stickyContainerPool.add(containerIndex);
3096
+ } else {
3097
+ if (peek$(ctx, containerSticky)) {
3098
+ set$(ctx, containerSticky, false);
3099
+ }
3100
+ if (isAlwaysRender) {
3101
+ state.stickyContainerPool.add(containerIndex);
3102
+ } else if (state.stickyContainerPool.has(containerIndex)) {
3103
+ state.stickyContainerPool.delete(containerIndex);
3104
+ }
3105
+ }
3106
+ if (containerIndex >= numContainers) {
3107
+ numContainers = containerIndex + 1;
3108
+ }
3109
+ }
3110
+ if (numContainers !== prevNumContainers) {
3111
+ set$(ctx, "numContainers", numContainers);
3112
+ if (numContainers > peek$(ctx, "numContainersPooled")) {
3113
+ set$(ctx, "numContainersPooled", Math.ceil(numContainers * 1.5));
3114
+ }
3115
+ }
3116
+ }
3117
+ if (alwaysRenderArr.length > 0) {
3118
+ for (const index of alwaysRenderArr) {
3119
+ if (index < 0 || index >= dataLength) continue;
3120
+ const id = (_l = idCache[index]) != null ? _l : getId(state, index);
3121
+ const containerIndex = containerItemKeys.get(id);
3122
+ if (containerIndex !== void 0) {
3123
+ state.stickyContainerPool.add(containerIndex);
3124
+ }
3125
+ }
3126
+ }
3127
+ }
3128
+ if (state.stickyContainerPool.size > 0) {
3129
+ handleStickyRecycling(
3130
+ ctx,
3131
+ stickyIndicesArr,
3132
+ scroll,
3133
+ drawDistance,
3134
+ currentStickyIdx,
3135
+ pendingRemoval,
3136
+ alwaysRenderSet
3137
+ );
3138
+ }
3139
+ let didChangePositions = false;
3140
+ for (let i = 0; i < numContainers; i++) {
3141
+ const itemKey = peek$(ctx, `containerItemKey${i}`);
3142
+ if (pendingRemoval.includes(i)) {
3143
+ if (itemKey !== void 0) {
3144
+ containerItemKeys.delete(itemKey);
3145
+ }
3146
+ state.containerItemTypes.delete(i);
3147
+ if (state.stickyContainerPool.has(i)) {
3148
+ set$(ctx, `containerSticky${i}`, false);
3149
+ state.stickyContainerPool.delete(i);
3150
+ }
3151
+ set$(ctx, `containerItemKey${i}`, void 0);
3152
+ set$(ctx, `containerItemData${i}`, void 0);
3153
+ set$(ctx, `containerPosition${i}`, POSITION_OUT_OF_VIEW);
3154
+ set$(ctx, `containerColumn${i}`, -1);
3155
+ set$(ctx, `containerSpan${i}`, 1);
3156
+ } else {
3157
+ const itemIndex = indexByKey.get(itemKey);
3158
+ const item = data[itemIndex];
3159
+ if (item !== void 0) {
3160
+ const positionValue = positions[itemIndex];
3161
+ if (positionValue === void 0) {
3162
+ set$(ctx, `containerPosition${i}`, POSITION_OUT_OF_VIEW);
3163
+ } else {
3164
+ const position = (positionValue || 0) - scrollAdjustPending;
3165
+ const column = columns[itemIndex] || 1;
3166
+ const span = columnSpans[itemIndex] || 1;
3167
+ const prevPos = peek$(ctx, `containerPosition${i}`);
3168
+ const prevColumn = peek$(ctx, `containerColumn${i}`);
3169
+ const prevSpan = peek$(ctx, `containerSpan${i}`);
3170
+ const prevData = peek$(ctx, `containerItemData${i}`);
3171
+ if (position > POSITION_OUT_OF_VIEW && position !== prevPos) {
3172
+ set$(ctx, `containerPosition${i}`, position);
3173
+ didChangePositions = true;
3174
+ }
3175
+ if (column >= 0 && column !== prevColumn) {
3176
+ set$(ctx, `containerColumn${i}`, column);
3177
+ }
3178
+ if (span !== prevSpan) {
3179
+ set$(ctx, `containerSpan${i}`, span);
3180
+ }
3181
+ if (prevData !== item && (itemsAreEqual ? !itemsAreEqual(prevData, item, itemIndex, data) : true)) {
3182
+ set$(ctx, `containerItemData${i}`, item);
3183
+ }
3184
+ }
3185
+ }
3186
+ }
3187
+ }
3188
+ if (Platform2.OS === "web" && didChangePositions) {
3189
+ set$(ctx, "lastPositionUpdate", Date.now());
3190
+ }
3191
+ if (!queuedInitialLayout && endBuffered !== null) {
3192
+ if (checkAllSizesKnown(state)) {
3193
+ setDidLayout(ctx);
3194
+ }
3195
+ }
3196
+ if (viewabilityConfigCallbackPairs) {
3197
+ updateViewableItems(state, ctx, viewabilityConfigCallbackPairs, scrollLength, startNoBuffer, endNoBuffer);
3198
+ }
3199
+ if (onStickyHeaderChange && stickyIndicesArr.length > 0 && nextActiveStickyIndex !== void 0 && nextActiveStickyIndex !== previousStickyIndex) {
3200
+ const item = data[nextActiveStickyIndex];
3201
+ if (item !== void 0) {
3202
+ onStickyHeaderChange({ index: nextActiveStickyIndex, item });
3203
+ }
3204
+ }
3205
+ });
3206
+ if (!IsNewArchitecture && state.initialAnchor) {
3207
+ ensureInitialAnchor(ctx);
3208
+ }
3209
+ }
3210
+
3211
+ // src/core/checkActualChange.ts
3212
+ function checkActualChange(state, dataProp, previousData) {
3213
+ if (!previousData || !dataProp || dataProp.length !== previousData.length) {
3214
+ return true;
3215
+ }
3216
+ const {
3217
+ idCache,
3218
+ props: { keyExtractor }
3219
+ } = state;
3220
+ for (let i = 0; i < dataProp.length; i++) {
3221
+ if (dataProp[i] !== previousData[i]) {
3222
+ return true;
3223
+ }
3224
+ if (keyExtractor ? idCache[i] !== keyExtractor(previousData[i], i) : dataProp[i] !== previousData[i]) {
3225
+ return true;
3226
+ }
3227
+ }
3228
+ return false;
3229
+ }
3230
+
3231
+ // src/utils/updateAveragesOnDataChange.ts
3232
+ function updateAveragesOnDataChange(state, oldData, newData) {
3233
+ var _a3;
3234
+ const {
3235
+ averageSizes,
3236
+ sizesKnown,
3237
+ indexByKey,
3238
+ props: { itemsAreEqual, getItemType, keyExtractor }
3239
+ } = state;
3240
+ if (!itemsAreEqual || !oldData.length || !newData.length) {
3241
+ for (const key in averageSizes) {
3242
+ delete averageSizes[key];
3243
+ }
3244
+ return;
3245
+ }
3246
+ const itemTypesToPreserve = {};
3247
+ const newDataLength = newData.length;
3248
+ const oldDataLength = oldData.length;
3249
+ for (let newIndex = 0; newIndex < newDataLength; newIndex++) {
3250
+ const newItem = newData[newIndex];
3251
+ const id = keyExtractor ? keyExtractor(newItem, newIndex) : String(newIndex);
3252
+ const oldIndex = indexByKey.get(id);
3253
+ if (oldIndex !== void 0 && oldIndex < oldDataLength) {
3254
+ const knownSize = sizesKnown.get(id);
3255
+ if (knownSize === void 0) continue;
3256
+ const oldItem = oldData[oldIndex];
3257
+ const areEqual = itemsAreEqual(oldItem, newItem, newIndex, newData);
3258
+ if (areEqual) {
3259
+ const itemType = getItemType ? (_a3 = getItemType(newItem, newIndex)) != null ? _a3 : "" : "";
3260
+ let typeData = itemTypesToPreserve[itemType];
3261
+ if (!typeData) {
3262
+ typeData = itemTypesToPreserve[itemType] = { count: 0, totalSize: 0 };
3263
+ }
3264
+ typeData.totalSize += knownSize;
3265
+ typeData.count++;
3266
+ }
3267
+ }
3268
+ }
3269
+ for (const key in averageSizes) {
3270
+ delete averageSizes[key];
3271
+ }
3272
+ for (const itemType in itemTypesToPreserve) {
3273
+ const { totalSize, count } = itemTypesToPreserve[itemType];
3274
+ if (count > 0) {
3275
+ averageSizes[itemType] = {
3276
+ avg: totalSize / count,
3277
+ num: count
3278
+ };
3279
+ }
3280
+ }
3281
+ }
3282
+
3283
+ // src/core/checkResetContainers.ts
3284
+ function checkResetContainers(ctx, dataProp) {
3285
+ const state = ctx.state;
3286
+ const { previousData } = state;
3287
+ if (previousData) {
3288
+ updateAveragesOnDataChange(state, previousData, dataProp);
3289
+ }
3290
+ const { maintainScrollAtEnd } = state.props;
3291
+ calculateItemsInView(ctx, { dataChanged: true, doMVCP: true });
3292
+ const shouldMaintainScrollAtEnd = maintainScrollAtEnd == null ? void 0 : maintainScrollAtEnd.onDataChange;
3293
+ const didMaintainScrollAtEnd = shouldMaintainScrollAtEnd && doMaintainScrollAtEnd(ctx);
3294
+ if (!didMaintainScrollAtEnd && previousData && dataProp.length > previousData.length) {
3295
+ state.isEndReached = false;
3296
+ }
3297
+ if (!didMaintainScrollAtEnd) {
3298
+ checkThresholds(ctx);
3299
+ }
3300
+ delete state.previousData;
3301
+ }
3302
+
3303
+ // src/core/doInitialAllocateContainers.ts
3304
+ function doInitialAllocateContainers(ctx) {
3305
+ var _a3, _b, _c;
3306
+ const state = ctx.state;
3307
+ const {
3308
+ scrollLength,
3309
+ props: {
3310
+ data,
3311
+ drawDistance,
3312
+ getEstimatedItemSize,
3313
+ getFixedItemSize,
3314
+ getItemType,
3315
+ numColumns,
3316
+ estimatedItemSize
3317
+ }
3318
+ } = state;
3319
+ const hasContainers = peek$(ctx, "numContainers");
3320
+ if (scrollLength > 0 && data.length > 0 && !hasContainers) {
3321
+ let averageItemSize;
3322
+ if (getFixedItemSize || getEstimatedItemSize) {
3323
+ let totalSize = 0;
3324
+ const num = Math.min(20, data.length);
3325
+ for (let i = 0; i < num; i++) {
3326
+ const item = data[i];
3327
+ if (item !== void 0) {
3328
+ const itemType = (_a3 = getItemType == null ? void 0 : getItemType(item, i)) != null ? _a3 : "";
3329
+ totalSize += (_c = (_b = getFixedItemSize == null ? void 0 : getFixedItemSize(item, i, itemType)) != null ? _b : getEstimatedItemSize == null ? void 0 : getEstimatedItemSize(item, i, itemType)) != null ? _c : estimatedItemSize;
3330
+ }
3331
+ }
3332
+ averageItemSize = totalSize / num;
3333
+ } else {
3334
+ averageItemSize = estimatedItemSize;
3335
+ }
3336
+ const numContainers = Math.ceil((scrollLength + drawDistance * 2) / averageItemSize * numColumns);
3337
+ for (let i = 0; i < numContainers; i++) {
3338
+ set$(ctx, `containerPosition${i}`, POSITION_OUT_OF_VIEW);
3339
+ set$(ctx, `containerColumn${i}`, -1);
3340
+ set$(ctx, `containerSpan${i}`, 1);
3341
+ }
3342
+ set$(ctx, "numContainers", numContainers);
3343
+ set$(ctx, "numContainersPooled", numContainers * state.props.initialContainerPoolRatio);
3344
+ if (!IsNewArchitecture || state.lastLayout) {
3345
+ if (state.initialScroll) {
3346
+ requestAnimationFrame(() => {
3347
+ calculateItemsInView(ctx, { dataChanged: true, doMVCP: true });
3348
+ });
3349
+ } else {
3350
+ calculateItemsInView(ctx, { dataChanged: true, doMVCP: true });
3351
+ }
3352
+ }
3353
+ return true;
3354
+ }
3355
+ }
3356
+ function getWindowSize() {
3357
+ const screenSize = Dimensions.get("window");
3358
+ return {
3359
+ height: screenSize.height,
3360
+ width: screenSize.width
3361
+ };
3362
+ }
3363
+
3364
+ // src/core/handleLayout.ts
3365
+ function handleLayout(ctx, layoutParam, setCanRender) {
3366
+ const state = ctx.state;
3367
+ const { maintainScrollAtEnd, useWindowScroll } = state.props;
3368
+ const scrollAxis = state.props.horizontal ? "width" : "height";
3369
+ const otherAxis = state.props.horizontal ? "height" : "width";
3370
+ let layout = layoutParam;
3371
+ if (useWindowScroll) {
3372
+ const windowScrollAxisLength = getWindowSize()[scrollAxis];
3373
+ layout = windowScrollAxisLength > 0 ? { ...layoutParam, [scrollAxis]: windowScrollAxisLength } : layoutParam;
3374
+ }
3375
+ const measuredLength = layout[scrollAxis];
3376
+ const previousLength = state.scrollLength;
3377
+ const scrollLength = measuredLength > 0 ? measuredLength : previousLength;
3378
+ const otherAxisSize = layout[otherAxis];
3379
+ const needsCalculate = !state.lastLayout || scrollLength > state.scrollLength || state.lastLayout.x !== layout.x || state.lastLayout.y !== layout.y;
3380
+ state.lastLayout = layout;
3381
+ const prevOtherAxisSize = state.otherAxisSize;
3382
+ const didChange = scrollLength !== state.scrollLength || otherAxisSize !== prevOtherAxisSize;
3383
+ if (didChange) {
3384
+ state.scrollLength = scrollLength;
3385
+ state.otherAxisSize = otherAxisSize;
3386
+ state.lastBatchingAction = Date.now();
3387
+ state.scrollForNextCalculateItemsInView = void 0;
3388
+ if (scrollLength > 0) {
3389
+ doInitialAllocateContainers(ctx);
3390
+ }
3391
+ if (needsCalculate) {
3392
+ calculateItemsInView(ctx, { doMVCP: true });
3393
+ }
3394
+ if (didChange || otherAxisSize !== prevOtherAxisSize) {
3395
+ set$(ctx, "scrollSize", { height: layout.height, width: layout.width });
3396
+ }
3397
+ if (maintainScrollAtEnd == null ? void 0 : maintainScrollAtEnd.onLayout) {
3398
+ doMaintainScrollAtEnd(ctx);
3399
+ }
3400
+ checkThresholds(ctx);
3401
+ if (state) {
3402
+ state.needsOtherAxisSize = otherAxisSize - (state.props.stylePaddingTop || 0) < 10;
3403
+ }
3404
+ if (IS_DEV && measuredLength === 0) {
3405
+ warnDevOnce(
3406
+ "height0",
3407
+ `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.`
3408
+ );
3409
+ }
3410
+ }
3411
+ setCanRender(true);
3412
+ }
3413
+
3414
+ // src/core/onScroll.ts
3415
+ var INITIAL_SCROLL_PROGRESS_EPSILON = 1;
3416
+ function didObserveInitialScrollProgress(newScroll, watchdog) {
3417
+ const previousDistance = Math.abs(watchdog.startScroll - watchdog.targetOffset);
3418
+ const nextDistance = Math.abs(newScroll - watchdog.targetOffset);
3419
+ return nextDistance <= INITIAL_SCROLL_PROGRESS_EPSILON || nextDistance + INITIAL_SCROLL_PROGRESS_EPSILON < previousDistance;
3420
+ }
3421
+ function onScroll(ctx, event) {
3422
+ var _a3, _b, _c, _d;
3423
+ const state = ctx.state;
3424
+ const {
3425
+ scrollProcessingEnabled,
3426
+ props: { onScroll: onScrollProp }
3427
+ } = state;
3428
+ if (scrollProcessingEnabled === false) {
3429
+ return;
3430
+ }
3431
+ 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) {
3432
+ return;
3433
+ }
3434
+ let insetChanged = false;
3435
+ if ((_d = event.nativeEvent) == null ? void 0 : _d.contentInset) {
3436
+ const { contentInset } = event.nativeEvent;
3437
+ const prevInset = state.nativeContentInset;
3438
+ if (!prevInset || prevInset.top !== contentInset.top || prevInset.bottom !== contentInset.bottom || prevInset.left !== contentInset.left || prevInset.right !== contentInset.right) {
3439
+ state.nativeContentInset = contentInset;
3440
+ insetChanged = true;
3441
+ }
3442
+ }
3443
+ let newScroll = event.nativeEvent.contentOffset[state.props.horizontal ? "x" : "y"];
3444
+ if (state.scrollingTo && state.scrollingTo.offset >= newScroll) {
3445
+ const maxOffset = clampScrollOffset(ctx, newScroll, state.scrollingTo);
3446
+ if (newScroll !== maxOffset && Math.abs(newScroll - maxOffset) > 1) {
3447
+ newScroll = maxOffset;
3448
+ scrollTo(ctx, {
3449
+ forceScroll: true,
3450
+ isInitialScroll: true,
3451
+ noScrollingTo: true,
3452
+ offset: newScroll
3453
+ });
3454
+ return;
3455
+ }
3456
+ }
3457
+ state.scrollPending = newScroll;
3458
+ const initialNativeScrollWatchdog = state.initialNativeScrollWatchdog;
3459
+ const didInitialScrollProgress = !!initialNativeScrollWatchdog && didObserveInitialScrollProgress(newScroll, initialNativeScrollWatchdog);
3460
+ if (didInitialScrollProgress) {
3461
+ state.initialNativeScrollWatchdog = void 0;
3462
+ }
3463
+ updateScroll(ctx, newScroll, insetChanged);
3464
+ if (initialNativeScrollWatchdog && !didInitialScrollProgress) {
3465
+ state.hasScrolled = false;
3466
+ state.initialNativeScrollWatchdog = initialNativeScrollWatchdog;
3467
+ }
3468
+ if (state.scrollingTo) {
3469
+ checkFinishedScroll(ctx);
3470
+ }
3471
+ onScrollProp == null ? void 0 : onScrollProp(event);
3472
+ }
3473
+
3474
+ // src/core/ScrollAdjustHandler.ts
3475
+ var ScrollAdjustHandler = class {
3476
+ constructor(ctx) {
3477
+ this.appliedAdjust = 0;
3478
+ this.pendingAdjust = 0;
3479
+ this.ctx = ctx;
3480
+ }
3481
+ requestAdjust(add) {
3482
+ const scrollingTo = this.ctx.state.scrollingTo;
3483
+ if (PlatformAdjustBreaksScroll && (scrollingTo == null ? void 0 : scrollingTo.animated) && !scrollingTo.isInitialScroll) {
3484
+ this.pendingAdjust += add;
3485
+ set$(this.ctx, "scrollAdjustPending", this.pendingAdjust);
3486
+ } else {
3487
+ this.appliedAdjust += add;
3488
+ set$(this.ctx, "scrollAdjust", this.appliedAdjust);
3489
+ }
3490
+ if (this.ctx.state.scrollingTo) {
3491
+ checkFinishedScroll(this.ctx);
3492
+ }
3493
+ }
3494
+ getAdjust() {
3495
+ return this.appliedAdjust;
3496
+ }
3497
+ commitPendingAdjust(scrollTarget) {
3498
+ if (PlatformAdjustBreaksScroll) {
3499
+ const state = this.ctx.state;
3500
+ const pending = this.pendingAdjust;
3501
+ this.pendingAdjust = 0;
3502
+ if (pending !== 0) {
3503
+ let targetScroll;
3504
+ if ((scrollTarget == null ? void 0 : scrollTarget.index) !== void 0) {
3505
+ const currentOffset = calculateOffsetForIndex(this.ctx, scrollTarget.index);
3506
+ targetScroll = calculateOffsetWithOffsetPosition(this.ctx, currentOffset, scrollTarget);
3507
+ targetScroll = clampScrollOffset(this.ctx, targetScroll, scrollTarget);
3508
+ } else {
3509
+ targetScroll = clampScrollOffset(this.ctx, state.scroll + pending);
3510
+ }
3511
+ const adjustment = targetScroll - state.scroll;
3512
+ if (Math.abs(adjustment) > 0.1 || Math.abs(pending) > 0.1) {
3513
+ this.appliedAdjust += adjustment;
3514
+ state.scroll = targetScroll;
3515
+ state.scrollForNextCalculateItemsInView = void 0;
3516
+ set$(this.ctx, "scrollAdjust", this.appliedAdjust);
3517
+ }
3518
+ set$(this.ctx, "scrollAdjustPending", 0);
3519
+ calculateItemsInView(this.ctx);
3520
+ }
3521
+ }
3522
+ }
3523
+ };
3524
+
3525
+ // src/core/updateItemSize.ts
3526
+ function runOrScheduleMVCPRecalculate(ctx) {
3527
+ const state = ctx.state;
3528
+ if (Platform2.OS === "web") {
3529
+ if (!state.mvcpAnchorLock) {
3530
+ if (state.queuedMVCPRecalculate !== void 0) {
3531
+ cancelAnimationFrame(state.queuedMVCPRecalculate);
3532
+ state.queuedMVCPRecalculate = void 0;
3533
+ }
3534
+ calculateItemsInView(ctx, { doMVCP: true });
3535
+ return;
3536
+ }
3537
+ if (state.queuedMVCPRecalculate !== void 0) {
3538
+ return;
3539
+ }
3540
+ state.queuedMVCPRecalculate = requestAnimationFrame(() => {
3541
+ state.queuedMVCPRecalculate = void 0;
3542
+ calculateItemsInView(ctx, { doMVCP: true });
3543
+ });
3544
+ } else {
3545
+ calculateItemsInView(ctx, { doMVCP: true });
3546
+ }
3547
+ }
3548
+ function updateItemSize(ctx, itemKey, sizeObj) {
3549
+ var _a3;
3550
+ const state = ctx.state;
3551
+ const {
3552
+ didContainersLayout,
3553
+ sizesKnown,
3554
+ props: {
3555
+ getFixedItemSize,
3556
+ getItemType,
3557
+ horizontal,
3558
+ suggestEstimatedItemSize,
3559
+ onItemSizeChanged,
3560
+ data,
3561
+ maintainScrollAtEnd
3562
+ }
3563
+ } = state;
3564
+ if (!data) return;
3565
+ const index = state.indexByKey.get(itemKey);
3566
+ if (getFixedItemSize) {
3567
+ if (index === void 0) {
3568
+ return;
3569
+ }
3570
+ const itemData = state.props.data[index];
3571
+ if (itemData === void 0) {
3572
+ return;
3573
+ }
3574
+ const type = getItemType ? (_a3 = getItemType(itemData, index)) != null ? _a3 : "" : "";
3575
+ const size2 = getFixedItemSize(itemData, index, type);
3576
+ if (size2 !== void 0 && size2 === sizesKnown.get(itemKey)) {
3577
+ return;
3578
+ }
3579
+ }
3580
+ let needsRecalculate = !didContainersLayout;
3581
+ let shouldMaintainScrollAtEnd = false;
3582
+ let minIndexSizeChanged;
3583
+ let maxOtherAxisSize = peek$(ctx, "otherAxisSize") || 0;
3584
+ const prevSizeKnown = state.sizesKnown.get(itemKey);
3585
+ const diff = updateOneItemSize(ctx, itemKey, sizeObj);
3586
+ const size = roundSize(horizontal ? sizeObj.width : sizeObj.height);
3587
+ if (diff !== 0) {
3588
+ minIndexSizeChanged = minIndexSizeChanged !== void 0 ? Math.min(minIndexSizeChanged, index) : index;
3589
+ const { startBuffered, endBuffered } = state;
3590
+ needsRecalculate || (needsRecalculate = index >= startBuffered && index <= endBuffered);
3591
+ if (!needsRecalculate && state.containerItemKeys.has(itemKey)) {
3592
+ needsRecalculate = true;
3593
+ }
3594
+ if (state.needsOtherAxisSize) {
3595
+ const otherAxisSize = horizontal ? sizeObj.height : sizeObj.width;
3596
+ maxOtherAxisSize = Math.max(maxOtherAxisSize, otherAxisSize);
3597
+ }
3598
+ if (prevSizeKnown !== void 0 && Math.abs(prevSizeKnown - size) > 5) {
3599
+ shouldMaintainScrollAtEnd = true;
3600
+ }
3601
+ onItemSizeChanged == null ? void 0 : onItemSizeChanged({
3602
+ index,
3603
+ itemData: state.props.data[index],
3604
+ itemKey,
3605
+ previous: size - diff,
3606
+ size
3607
+ });
3608
+ }
3609
+ if (minIndexSizeChanged !== void 0) {
3610
+ state.minIndexSizeChanged = state.minIndexSizeChanged !== void 0 ? Math.min(state.minIndexSizeChanged, minIndexSizeChanged) : minIndexSizeChanged;
3611
+ }
3612
+ if (IS_DEV && suggestEstimatedItemSize && minIndexSizeChanged !== void 0) {
3613
+ if (state.timeoutSizeMessage) clearTimeout(state.timeoutSizeMessage);
3614
+ state.timeoutSizeMessage = setTimeout(() => {
3615
+ var _a4;
3616
+ state.timeoutSizeMessage = void 0;
3617
+ const num = state.sizesKnown.size;
3618
+ const avg = (_a4 = state.averageSizes[""]) == null ? void 0 : _a4.avg;
3619
+ console.warn(
3620
+ `[legend-list] Based on the ${num} items rendered so far, the optimal estimated size is ${avg}.`
3621
+ );
3622
+ }, 1e3);
3623
+ }
3624
+ const cur = peek$(ctx, "otherAxisSize");
3625
+ if (!cur || maxOtherAxisSize > cur) {
3626
+ set$(ctx, "otherAxisSize", maxOtherAxisSize);
3627
+ }
3628
+ if (didContainersLayout || checkAllSizesKnown(state)) {
3629
+ if (needsRecalculate) {
3630
+ state.scrollForNextCalculateItemsInView = void 0;
3631
+ runOrScheduleMVCPRecalculate(ctx);
3632
+ }
3633
+ if (shouldMaintainScrollAtEnd) {
3634
+ if (maintainScrollAtEnd == null ? void 0 : maintainScrollAtEnd.onItemLayout) {
3635
+ doMaintainScrollAtEnd(ctx);
3636
+ }
3637
+ }
3638
+ }
3639
+ }
3640
+ function updateOneItemSize(ctx, itemKey, sizeObj) {
3641
+ var _a3;
3642
+ const state = ctx.state;
3643
+ const {
3644
+ indexByKey,
3645
+ sizesKnown,
3646
+ averageSizes,
3647
+ props: { data, horizontal, getEstimatedItemSize, getItemType, getFixedItemSize }
3648
+ } = state;
3649
+ if (!data) return 0;
3650
+ const index = indexByKey.get(itemKey);
3651
+ const prevSize = getItemSize(ctx, itemKey, index, data[index]);
3652
+ const rawSize = horizontal ? sizeObj.width : sizeObj.height;
3653
+ const size = Platform2.OS === "web" ? Math.round(rawSize) : roundSize(rawSize);
3654
+ const prevSizeKnown = sizesKnown.get(itemKey);
3655
+ sizesKnown.set(itemKey, size);
3656
+ if (!getEstimatedItemSize && !getFixedItemSize && size > 0) {
3657
+ const itemType = getItemType ? (_a3 = getItemType(data[index], index)) != null ? _a3 : "" : "";
3658
+ let averages = averageSizes[itemType];
3659
+ if (!averages) {
3660
+ averages = averageSizes[itemType] = { avg: 0, num: 0 };
3661
+ }
3662
+ if (averages.num === 0) {
3663
+ averages.avg = size;
3664
+ averages.num++;
3665
+ } else if (prevSizeKnown !== void 0 && prevSizeKnown > 0) {
3666
+ averages.avg += (size - prevSizeKnown) / averages.num;
3667
+ } else {
3668
+ averages.avg = (averages.avg * averages.num + size) / (averages.num + 1);
3669
+ averages.num++;
3670
+ }
3671
+ }
3672
+ if (!prevSize || Math.abs(prevSize - size) > 0.1) {
3673
+ setSize(ctx, itemKey, size);
3674
+ return size - prevSize;
3675
+ }
3676
+ return 0;
3677
+ }
3678
+ function useWrapIfItem(fn) {
3679
+ return useMemo(
3680
+ () => fn ? (arg1, arg2, arg3) => arg1 !== void 0 && arg2 !== void 0 ? fn(arg1, arg2, arg3) : void 0 : void 0,
3681
+ [fn]
3682
+ );
3683
+ }
3684
+ var useCombinedRef = (...refs) => {
3685
+ const callback = useCallback((element) => {
3686
+ for (const ref of refs) {
3687
+ if (!ref) {
3688
+ continue;
3689
+ }
3690
+ if (isFunction(ref)) {
3691
+ ref(element);
3692
+ } else {
3693
+ ref.current = element;
3694
+ }
3695
+ }
3696
+ }, refs);
3697
+ return callback;
3698
+ };
3699
+ var StyleSheet = StyleSheet$1;
3700
+ function useStickyScrollHandler(stickyHeaderIndices, horizontal, ctx, onScroll2) {
3701
+ const shouldUseRnAnimatedEngine = !ctx.state.props.stickyPositionComponentInternal;
3702
+ return useMemo(() => {
3703
+ if ((stickyHeaderIndices == null ? void 0 : stickyHeaderIndices.length) && shouldUseRnAnimatedEngine) {
3704
+ const { animatedScrollY } = ctx;
3705
+ return Animated.event(
3706
+ [
3707
+ {
3708
+ nativeEvent: {
3709
+ contentOffset: { [horizontal ? "x" : "y"]: animatedScrollY }
3710
+ }
3711
+ }
3712
+ ],
3713
+ {
3714
+ listener: onScroll2,
3715
+ useNativeDriver: true
3716
+ }
3717
+ );
3718
+ }
3719
+ return onScroll2;
3720
+ }, [stickyHeaderIndices == null ? void 0 : stickyHeaderIndices.join(","), horizontal, shouldUseRnAnimatedEngine]);
3721
+ }
3722
+
3723
+ // src/utils/createColumnWrapperStyle.ts
3724
+ function createColumnWrapperStyle(contentContainerStyle) {
3725
+ const { gap, columnGap, rowGap } = contentContainerStyle;
3726
+ if (gap || columnGap || rowGap) {
3727
+ contentContainerStyle.gap = void 0;
3728
+ contentContainerStyle.columnGap = void 0;
3729
+ contentContainerStyle.rowGap = void 0;
3730
+ return {
3731
+ columnGap,
3732
+ gap,
3733
+ rowGap
3734
+ };
3735
+ }
3736
+ }
3737
+
3738
+ // src/utils/hasActiveMVCPAnchorLock.ts
3739
+ function hasActiveMVCPAnchorLock(state) {
3740
+ const lock = state.mvcpAnchorLock;
3741
+ if (!lock) {
3742
+ return false;
3743
+ }
3744
+ if (Date.now() > lock.expiresAt) {
3745
+ state.mvcpAnchorLock = void 0;
3746
+ return false;
3747
+ }
3748
+ return true;
3749
+ }
3750
+
3751
+ // src/utils/createImperativeHandle.ts
3752
+ function createImperativeHandle(ctx) {
3753
+ const state = ctx.state;
3754
+ const IMPERATIVE_SCROLL_SETTLE_MAX_WAIT_MS = 800;
3755
+ const IMPERATIVE_SCROLL_SETTLE_STABLE_FRAMES = 2;
3756
+ let imperativeScrollToken = 0;
3757
+ const isSettlingAfterDataChange = () => !!state.didDataChange || !!state.didColumnsChange || state.queuedMVCPRecalculate !== void 0 || state.ignoreScrollFromMVCP !== void 0 || hasActiveMVCPAnchorLock(state);
3758
+ const runWhenSettled = (token, run) => {
3759
+ const startedAt = Date.now();
3760
+ let stableFrames = 0;
3761
+ const check = () => {
3762
+ if (token !== imperativeScrollToken) {
3763
+ return;
3764
+ }
3765
+ if (isSettlingAfterDataChange()) {
3766
+ stableFrames = 0;
3767
+ } else {
3768
+ stableFrames += 1;
3769
+ }
3770
+ const timedOut = Date.now() - startedAt >= IMPERATIVE_SCROLL_SETTLE_MAX_WAIT_MS;
3771
+ if (stableFrames >= IMPERATIVE_SCROLL_SETTLE_STABLE_FRAMES || timedOut) {
3772
+ run();
3773
+ return;
3774
+ }
3775
+ requestAnimationFrame(check);
3776
+ };
3777
+ requestAnimationFrame(check);
3778
+ };
3779
+ const runScrollWithPromise = (run) => new Promise((resolve) => {
3780
+ var _a3;
3781
+ const token = ++imperativeScrollToken;
3782
+ (_a3 = state.pendingScrollResolve) == null ? void 0 : _a3.call(state);
3783
+ state.pendingScrollResolve = resolve;
3784
+ const runNow = () => {
3785
+ if (token !== imperativeScrollToken) {
3786
+ return;
3787
+ }
3788
+ const didStartScroll = run();
3789
+ if (!didStartScroll || !state.scrollingTo) {
3790
+ if (state.pendingScrollResolve === resolve) {
3791
+ state.pendingScrollResolve = void 0;
3792
+ }
3793
+ resolve();
3794
+ }
3795
+ };
3796
+ if (isSettlingAfterDataChange()) {
3797
+ runWhenSettled(token, runNow);
3798
+ return;
3799
+ }
3800
+ runNow();
3801
+ });
3802
+ const scrollIndexIntoView = (options) => {
3803
+ if (state) {
3804
+ const { index, ...rest } = options;
3805
+ const { startNoBuffer, endNoBuffer } = state;
3806
+ if (index < startNoBuffer || index > endNoBuffer) {
3807
+ const viewPosition = index < startNoBuffer ? 0 : 1;
3808
+ scrollToIndex(ctx, {
3809
+ ...rest,
3810
+ index,
3811
+ viewPosition
3812
+ });
3813
+ return true;
3814
+ }
3815
+ }
3816
+ return false;
3817
+ };
3818
+ const refScroller = state.refScroller;
3819
+ const clearCaches = (options) => {
3820
+ var _a3, _b;
3821
+ const mode = (_a3 = options == null ? void 0 : options.mode) != null ? _a3 : "sizes";
3822
+ state.sizes.clear();
3823
+ state.sizesKnown.clear();
3824
+ for (const key in state.averageSizes) {
3825
+ delete state.averageSizes[key];
3826
+ }
3827
+ state.minIndexSizeChanged = 0;
3828
+ state.scrollForNextCalculateItemsInView = void 0;
3829
+ state.pendingTotalSize = void 0;
3830
+ state.totalSize = 0;
3831
+ set$(ctx, "totalSize", 0);
3832
+ if (mode === "full") {
3833
+ state.indexByKey.clear();
3834
+ state.idCache.length = 0;
3835
+ state.positions.length = 0;
3836
+ state.columns.length = 0;
3837
+ state.columnSpans.length = 0;
3838
+ }
3839
+ (_b = state.triggerCalculateItemsInView) == null ? void 0 : _b.call(state, { forceFullItemPositions: true });
3840
+ };
3841
+ return {
3842
+ clearCaches,
3843
+ flashScrollIndicators: () => refScroller.current.flashScrollIndicators(),
3844
+ getNativeScrollRef: () => refScroller.current,
3845
+ getScrollableNode: () => refScroller.current.getScrollableNode(),
3846
+ getScrollResponder: () => refScroller.current.getScrollResponder(),
3847
+ getState: () => ({
3848
+ activeStickyIndex: peek$(ctx, "activeStickyIndex"),
3849
+ contentLength: getContentSize(ctx),
3850
+ data: state.props.data,
3851
+ elementAtIndex: (index) => {
3852
+ var _a3;
3853
+ return (_a3 = ctx.viewRefs.get(findContainerId(ctx, getId(state, index)))) == null ? void 0 : _a3.current;
3854
+ },
3855
+ end: state.endNoBuffer,
3856
+ endBuffered: state.endBuffered,
3857
+ isAtEnd: state.isAtEnd,
3858
+ isAtStart: state.isAtStart,
3859
+ isEndReached: state.isEndReached,
3860
+ isStartReached: state.isStartReached,
3861
+ listen: (signalName, cb) => listen$(ctx, signalName, cb),
3862
+ listenToPosition: (key, cb) => listenPosition$(ctx, key, cb),
3863
+ positionAtIndex: (index) => state.positions[index],
3864
+ positionByKey: (key) => {
3865
+ const index = state.indexByKey.get(key);
3866
+ return index === void 0 ? void 0 : state.positions[index];
3867
+ },
3868
+ scroll: state.scroll,
3869
+ scrollLength: state.scrollLength,
3870
+ scrollVelocity: getScrollVelocity(state),
3871
+ sizeAtIndex: (index) => state.sizesKnown.get(getId(state, index)),
3872
+ sizes: state.sizesKnown,
3873
+ start: state.startNoBuffer,
3874
+ startBuffered: state.startBuffered
3875
+ }),
3876
+ reportContentInset: (inset) => {
3877
+ state.contentInsetOverride = inset != null ? inset : void 0;
3878
+ updateScroll(ctx, state.scroll, true);
3879
+ },
3880
+ scrollIndexIntoView: (options) => runScrollWithPromise(() => scrollIndexIntoView(options)),
3881
+ scrollItemIntoView: ({ item, ...props }) => runScrollWithPromise(() => {
3882
+ const data = state.props.data;
3883
+ const index = data.indexOf(item);
3884
+ if (index !== -1) {
3885
+ scrollIndexIntoView({ index, ...props });
3886
+ return true;
3887
+ }
3888
+ return false;
3889
+ }),
3890
+ scrollToEnd: (options) => runScrollWithPromise(() => {
3891
+ const data = state.props.data;
3892
+ const stylePaddingBottom = state.props.stylePaddingBottom;
3893
+ const index = data.length - 1;
3894
+ if (index !== -1) {
3895
+ const paddingBottom = stylePaddingBottom || 0;
3896
+ const footerSize = peek$(ctx, "footerSize") || 0;
3897
+ scrollToIndex(ctx, {
3898
+ ...options,
3899
+ index,
3900
+ viewOffset: -paddingBottom - footerSize + ((options == null ? void 0 : options.viewOffset) || 0),
3901
+ viewPosition: 1
3902
+ });
3903
+ return true;
3904
+ }
3905
+ return false;
3906
+ }),
3907
+ scrollToIndex: (params) => runScrollWithPromise(() => {
3908
+ scrollToIndex(ctx, params);
3909
+ return true;
3910
+ }),
3911
+ scrollToItem: ({ item, ...props }) => runScrollWithPromise(() => {
3912
+ const data = state.props.data;
3913
+ const index = data.indexOf(item);
3914
+ if (index !== -1) {
3915
+ scrollToIndex(ctx, { index, ...props });
3916
+ return true;
3917
+ }
3918
+ return false;
3919
+ }),
3920
+ scrollToOffset: (params) => runScrollWithPromise(() => {
3921
+ scrollTo(ctx, params);
3922
+ return true;
3923
+ }),
3924
+ setScrollProcessingEnabled: (enabled) => {
3925
+ state.scrollProcessingEnabled = enabled;
3926
+ },
3927
+ setVisibleContentAnchorOffset: (value) => {
3928
+ const val = isFunction(value) ? value(peek$(ctx, "scrollAdjustUserOffset") || 0) : value;
3929
+ set$(ctx, "scrollAdjustUserOffset", val);
3930
+ }
3931
+ };
3932
+ }
3933
+
3934
+ // src/utils/getAlwaysRenderIndices.ts
3935
+ var sortAsc = (a, b) => a - b;
3936
+ var toCount = (value) => typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
3937
+ var addIndex = (result, dataLength, index) => {
3938
+ if (index >= 0 && index < dataLength) {
3939
+ result.add(index);
3940
+ }
3941
+ };
3942
+ function getAlwaysRenderIndices(config, data, keyExtractor) {
3943
+ var _a3, _b;
3944
+ if (!config || data.length === 0) {
3945
+ return [];
3946
+ }
3947
+ const result = /* @__PURE__ */ new Set();
3948
+ const dataLength = data.length;
3949
+ const topCount = toCount(config.top);
3950
+ if (topCount > 0) {
3951
+ for (let i = 0; i < Math.min(topCount, dataLength); i++) {
3952
+ addIndex(result, dataLength, i);
3953
+ }
3954
+ }
3955
+ const bottomCount = toCount(config.bottom);
3956
+ if (bottomCount > 0) {
3957
+ for (let i = Math.max(0, dataLength - bottomCount); i < dataLength; i++) {
3958
+ addIndex(result, dataLength, i);
3959
+ }
3960
+ }
3961
+ if ((_a3 = config.indices) == null ? void 0 : _a3.length) {
3962
+ for (const index of config.indices) {
3963
+ if (!Number.isFinite(index)) continue;
3964
+ addIndex(result, dataLength, Math.floor(index));
3965
+ }
3966
+ }
3967
+ if ((_b = config.keys) == null ? void 0 : _b.length) {
3968
+ const keys = new Set(config.keys);
3969
+ for (let i = 0; i < dataLength && keys.size > 0; i++) {
3970
+ const key = keyExtractor(data[i], i);
3971
+ if (keys.has(key)) {
3972
+ addIndex(result, dataLength, i);
3973
+ keys.delete(key);
3974
+ }
3975
+ }
3976
+ }
3977
+ const indices = Array.from(result);
3978
+ indices.sort(sortAsc);
3979
+ return indices;
3980
+ }
3981
+ function getRenderedItem(ctx, key) {
3982
+ var _a3;
3983
+ const state = ctx.state;
3984
+ if (!state) {
3985
+ return null;
3986
+ }
3987
+ const {
3988
+ indexByKey,
3989
+ props: { data, getItemType, renderItem }
3990
+ } = state;
3991
+ const index = indexByKey.get(key);
3992
+ if (index === void 0) {
3993
+ return null;
3994
+ }
3995
+ let renderedItem = null;
3996
+ const extraData = peek$(ctx, "extraData");
3997
+ const item = data[index];
3998
+ if (renderItem && !isNullOrUndefined(item)) {
3999
+ const itemProps = {
4000
+ data,
4001
+ extraData,
4002
+ index,
4003
+ item,
4004
+ type: getItemType ? (_a3 = getItemType(item, index)) != null ? _a3 : "" : ""
4005
+ };
4006
+ renderedItem = isFunction(renderItem) ? renderItem(itemProps) : React2__default.createElement(renderItem, itemProps);
4007
+ }
4008
+ return { index, item: data[index], renderedItem };
4009
+ }
4010
+
4011
+ // src/utils/normalizeMaintainScrollAtEnd.ts
4012
+ function normalizeMaintainScrollAtEndOn(on, hasExplicitOn) {
4013
+ var _a3, _b, _c;
4014
+ return {
4015
+ animated: false,
4016
+ onDataChange: hasExplicitOn ? (_a3 = on == null ? void 0 : on.dataChange) != null ? _a3 : false : true,
4017
+ onItemLayout: hasExplicitOn ? (_b = on == null ? void 0 : on.itemLayout) != null ? _b : false : true,
4018
+ onLayout: hasExplicitOn ? (_c = on == null ? void 0 : on.layout) != null ? _c : false : true
4019
+ };
4020
+ }
4021
+ function normalizeMaintainScrollAtEnd(value) {
4022
+ var _a3;
4023
+ if (!value) {
4024
+ return void 0;
4025
+ }
4026
+ if (value === true) {
4027
+ return {
4028
+ ...normalizeMaintainScrollAtEndOn(void 0, false),
4029
+ animated: false
4030
+ };
4031
+ }
4032
+ const normalizedTriggers = normalizeMaintainScrollAtEndOn(value.on, "on" in value);
4033
+ return {
4034
+ ...normalizedTriggers,
4035
+ animated: (_a3 = value.animated) != null ? _a3 : false
4036
+ };
4037
+ }
4038
+
4039
+ // src/utils/normalizeMaintainVisibleContentPosition.ts
4040
+ function normalizeMaintainVisibleContentPosition(value) {
4041
+ var _a3, _b;
4042
+ if (value === true) {
4043
+ return { data: true, size: true };
4044
+ }
4045
+ if (value && typeof value === "object") {
4046
+ return {
4047
+ data: (_a3 = value.data) != null ? _a3 : false,
4048
+ shouldRestorePosition: value.shouldRestorePosition,
4049
+ size: (_b = value.size) != null ? _b : true
4050
+ };
4051
+ }
4052
+ if (value === false) {
4053
+ return { data: false, size: false };
4054
+ }
4055
+ return { data: false, size: true };
4056
+ }
4057
+
4058
+ // src/utils/setPaddingTop.ts
4059
+ function setPaddingTop(ctx, { stylePaddingTop }) {
4060
+ const state = ctx.state;
4061
+ if (stylePaddingTop !== void 0) {
4062
+ const prevStylePaddingTop = peek$(ctx, "stylePaddingTop") || 0;
4063
+ if (stylePaddingTop < prevStylePaddingTop) {
4064
+ let prevTotalSize = peek$(ctx, "totalSize") || 0;
4065
+ set$(ctx, "totalSize", prevTotalSize + prevStylePaddingTop);
4066
+ state.timeoutSetPaddingTop = setTimeout(() => {
4067
+ prevTotalSize = peek$(ctx, "totalSize") || 0;
4068
+ set$(ctx, "totalSize", prevTotalSize - prevStylePaddingTop);
4069
+ }, 16);
4070
+ }
4071
+ set$(ctx, "stylePaddingTop", stylePaddingTop);
4072
+ }
4073
+ }
4074
+ function useThrottleDebounce(mode) {
4075
+ const timeoutRef = useRef(null);
4076
+ const lastCallTimeRef = useRef(0);
4077
+ const lastArgsRef = useRef(null);
4078
+ const clearTimeoutRef = () => {
4079
+ if (timeoutRef.current) {
4080
+ clearTimeout(timeoutRef.current);
4081
+ timeoutRef.current = null;
4082
+ }
4083
+ };
4084
+ const execute = useCallback(
4085
+ (callback, delay, ...args) => {
4086
+ {
4087
+ const now = Date.now();
4088
+ lastArgsRef.current = args;
4089
+ if (now - lastCallTimeRef.current >= delay) {
4090
+ lastCallTimeRef.current = now;
4091
+ callback(...args);
4092
+ clearTimeoutRef();
4093
+ } else {
4094
+ clearTimeoutRef();
4095
+ timeoutRef.current = setTimeout(
4096
+ () => {
4097
+ if (lastArgsRef.current) {
4098
+ lastCallTimeRef.current = Date.now();
4099
+ callback(...lastArgsRef.current);
4100
+ timeoutRef.current = null;
4101
+ lastArgsRef.current = null;
4102
+ }
4103
+ },
4104
+ delay - (now - lastCallTimeRef.current)
4105
+ );
4106
+ }
4107
+ }
4108
+ },
4109
+ [mode]
4110
+ );
4111
+ return execute;
4112
+ }
4113
+
4114
+ // src/utils/throttledOnScroll.ts
4115
+ function useThrottledOnScroll(originalHandler, scrollEventThrottle) {
4116
+ const throttle = useThrottleDebounce("throttle");
4117
+ return (event) => throttle(originalHandler, scrollEventThrottle, { nativeEvent: event.nativeEvent });
4118
+ }
4119
+
4120
+ // src/components/LegendList.tsx
4121
+ var LegendList = typedMemo2(
4122
+ // biome-ignore lint/nursery/noShadow: const function name shadowing is intentional
4123
+ typedForwardRef(function LegendList2(props, forwardedRef) {
4124
+ const { children, data: dataProp, renderItem: renderItemProp, ...restProps } = props;
4125
+ const isChildrenMode = children !== void 0 && dataProp === void 0;
4126
+ const processedProps = isChildrenMode ? {
4127
+ ...restProps,
4128
+ childrenMode: true,
4129
+ data: (isArray(children) ? children : React2.Children.toArray(children)).flat(1),
4130
+ renderItem: ({ item }) => item
4131
+ } : {
4132
+ ...restProps,
4133
+ data: dataProp || [],
4134
+ renderItem: renderItemProp
4135
+ };
4136
+ return /* @__PURE__ */ React2.createElement(StateProvider, null, /* @__PURE__ */ React2.createElement(LegendListInner, { ...processedProps, ref: forwardedRef }));
4137
+ })
4138
+ );
4139
+ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwardedRef) {
4140
+ var _a3, _b, _c, _d, _e, _f, _g, _h;
4141
+ const {
4142
+ alignItemsAtEnd = false,
4143
+ alwaysRender,
4144
+ columnWrapperStyle,
4145
+ contentContainerStyle: contentContainerStyleProp,
4146
+ contentInset,
4147
+ data: dataProp = [],
4148
+ dataVersion,
4149
+ drawDistance = 250,
4150
+ estimatedItemSize = 100,
4151
+ estimatedListSize,
4152
+ extraData,
4153
+ getEstimatedItemSize,
4154
+ getFixedItemSize,
4155
+ getItemType,
4156
+ horizontal,
4157
+ initialContainerPoolRatio = 2,
4158
+ initialScrollAtEnd = false,
4159
+ initialScrollIndex: initialScrollIndexProp,
4160
+ initialScrollOffset: initialScrollOffsetProp,
4161
+ itemsAreEqual,
4162
+ keyExtractor: keyExtractorProp,
4163
+ ListEmptyComponent,
4164
+ ListHeaderComponent,
4165
+ maintainScrollAtEnd = false,
4166
+ maintainScrollAtEndThreshold = 0.1,
4167
+ maintainVisibleContentPosition: maintainVisibleContentPositionProp,
4168
+ numColumns: numColumnsProp = 1,
4169
+ overrideItemLayout,
4170
+ onEndReached,
4171
+ onEndReachedThreshold = 0.5,
4172
+ onItemSizeChanged,
4173
+ onMetricsChange,
4174
+ onLayout: onLayoutProp,
4175
+ onLoad,
4176
+ onMomentumScrollEnd,
4177
+ onRefresh,
4178
+ onScroll: onScrollProp,
4179
+ onStartReached,
4180
+ onStartReachedThreshold = 0.5,
4181
+ onStickyHeaderChange,
4182
+ onViewableItemsChanged,
4183
+ progressViewOffset,
4184
+ recycleItems = false,
4185
+ refreshControl,
4186
+ refreshing,
4187
+ refScrollView,
4188
+ renderScrollComponent,
4189
+ renderItem,
4190
+ scrollEventThrottle,
4191
+ snapToIndices,
4192
+ stickyHeaderIndices: stickyHeaderIndicesProp,
4193
+ stickyIndices: stickyIndicesDeprecated,
4194
+ // TODOV3: Remove from v3 release
4195
+ style: styleProp,
4196
+ suggestEstimatedItemSize,
4197
+ useWindowScroll = false,
4198
+ viewabilityConfig,
4199
+ viewabilityConfigCallbackPairs,
4200
+ waitForInitialLayout = true,
4201
+ ...rest
4202
+ } = props;
4203
+ const animatedPropsInternal = props.animatedPropsInternal;
4204
+ const positionComponentInternal = props.positionComponentInternal;
4205
+ const stickyPositionComponentInternal = props.stickyPositionComponentInternal;
4206
+ const {
4207
+ childrenMode,
4208
+ positionComponentInternal: _positionComponentInternal,
4209
+ stickyPositionComponentInternal: _stickyPositionComponentInternal,
4210
+ ...restProps
4211
+ } = rest;
4212
+ const contentContainerStyleBase = StyleSheet.flatten(contentContainerStyleProp);
4213
+ const shouldFlexGrow = alignItemsAtEnd && (horizontal ? (contentContainerStyleBase == null ? void 0 : contentContainerStyleBase.minWidth) == null : (contentContainerStyleBase == null ? void 0 : contentContainerStyleBase.minHeight) == null);
4214
+ const contentContainerStyle = {
4215
+ ...contentContainerStyleBase,
4216
+ ...alignItemsAtEnd ? {
4217
+ display: "flex",
4218
+ flexDirection: horizontal ? "row" : "column",
4219
+ ...shouldFlexGrow ? { flexGrow: 1 } : {},
4220
+ justifyContent: "flex-end"
4221
+ } : {}
4222
+ };
4223
+ const style = { ...StyleSheet.flatten(styleProp) };
4224
+ const stylePaddingTopState = extractPadding(style, contentContainerStyle, "Top");
4225
+ const stylePaddingBottomState = extractPadding(style, contentContainerStyle, "Bottom");
4226
+ const maintainScrollAtEndConfig = normalizeMaintainScrollAtEnd(maintainScrollAtEnd);
4227
+ const maintainVisibleContentPositionConfig = normalizeMaintainVisibleContentPosition(
4228
+ maintainVisibleContentPositionProp
4229
+ );
4230
+ const hasInitialScrollIndex = initialScrollIndexProp !== void 0 && initialScrollIndexProp !== null;
4231
+ const hasInitialScrollOffset = initialScrollOffsetProp !== void 0 && initialScrollOffsetProp !== null;
4232
+ const initialScrollUsesOffsetOnly = !initialScrollAtEnd && !hasInitialScrollIndex && hasInitialScrollOffset;
4233
+ const initialScrollProp = initialScrollAtEnd ? { index: Math.max(0, dataProp.length - 1), viewOffset: -stylePaddingBottomState, viewPosition: 1 } : hasInitialScrollIndex ? typeof initialScrollIndexProp === "object" ? {
4234
+ index: (_a3 = initialScrollIndexProp.index) != null ? _a3 : 0,
4235
+ viewOffset: (_b = initialScrollIndexProp.viewOffset) != null ? _b : initialScrollIndexProp.viewPosition === 1 ? -stylePaddingBottomState : 0,
4236
+ viewPosition: (_c = initialScrollIndexProp.viewPosition) != null ? _c : 0
4237
+ } : {
4238
+ index: initialScrollIndexProp != null ? initialScrollIndexProp : 0,
4239
+ viewOffset: initialScrollOffsetProp != null ? initialScrollOffsetProp : 0
4240
+ } : initialScrollUsesOffsetOnly ? {
4241
+ contentOffset: initialScrollOffsetProp != null ? initialScrollOffsetProp : 0,
4242
+ index: 0,
4243
+ viewOffset: 0
4244
+ } : void 0;
4245
+ const [canRender, setCanRender] = React2.useState(!IsNewArchitecture);
4246
+ const ctx = useStateContext();
4247
+ ctx.columnWrapperStyle = columnWrapperStyle || (contentContainerStyle ? createColumnWrapperStyle(contentContainerStyle) : void 0);
4248
+ const refScroller = useRef(null);
4249
+ const combinedRef = useCombinedRef(refScroller, refScrollView);
4250
+ const keyExtractor = keyExtractorProp != null ? keyExtractorProp : ((_item, index) => index.toString());
4251
+ const stickyHeaderIndices = stickyHeaderIndicesProp != null ? stickyHeaderIndicesProp : stickyIndicesDeprecated;
4252
+ const alwaysRenderIndices = useMemo(() => {
4253
+ const indices = getAlwaysRenderIndices(alwaysRender, dataProp, keyExtractor);
4254
+ return { arr: indices, set: new Set(indices) };
4255
+ }, [
4256
+ alwaysRender == null ? void 0 : alwaysRender.top,
4257
+ alwaysRender == null ? void 0 : alwaysRender.bottom,
4258
+ (_d = alwaysRender == null ? void 0 : alwaysRender.indices) == null ? void 0 : _d.join(","),
4259
+ (_e = alwaysRender == null ? void 0 : alwaysRender.keys) == null ? void 0 : _e.join(","),
4260
+ dataProp,
4261
+ dataVersion,
4262
+ keyExtractor
4263
+ ]);
4264
+ if (IS_DEV && stickyIndicesDeprecated && !stickyHeaderIndicesProp) {
4265
+ warnDevOnce(
4266
+ "stickyIndices",
4267
+ "stickyIndices has been renamed to stickyHeaderIndices. Please update your props to use stickyHeaderIndices."
4268
+ );
4269
+ }
4270
+ if (IS_DEV && useWindowScroll && renderScrollComponent) {
4271
+ warnDevOnce(
4272
+ "useWindowScrollRenderScrollComponent",
4273
+ "useWindowScroll is not supported when renderScrollComponent is provided."
4274
+ );
4275
+ }
4276
+ const useWindowScrollResolved = Platform2.OS === "web" && !!useWindowScroll && !renderScrollComponent;
4277
+ const refState = useRef(void 0);
4278
+ const hasOverrideItemLayout = !!overrideItemLayout;
4279
+ const prevHasOverrideItemLayout = useRef(hasOverrideItemLayout);
4280
+ if (!refState.current) {
4281
+ if (!ctx.state) {
4282
+ const initialScrollLength = (estimatedListSize != null ? estimatedListSize : IsNewArchitecture ? { height: 0, width: 0 } : getWindowSize())[horizontal ? "width" : "height"];
4283
+ ctx.state = {
4284
+ activeStickyIndex: -1,
4285
+ averageSizes: {},
4286
+ columnSpans: [],
4287
+ columns: [],
4288
+ containerItemKeys: /* @__PURE__ */ new Map(),
4289
+ containerItemTypes: /* @__PURE__ */ new Map(),
4290
+ contentInsetOverride: void 0,
4291
+ dataChangeEpoch: 0,
4292
+ dataChangeNeedsScrollUpdate: false,
4293
+ didColumnsChange: false,
4294
+ didDataChange: false,
4295
+ enableScrollForNextCalculateItemsInView: true,
4296
+ endBuffered: -1,
4297
+ endNoBuffer: -1,
4298
+ endReachedSnapshot: void 0,
4299
+ firstFullyOnScreenIndex: -1,
4300
+ idCache: [],
4301
+ idsInView: [],
4302
+ indexByKey: /* @__PURE__ */ new Map(),
4303
+ initialAnchor: !initialScrollUsesOffsetOnly && (initialScrollProp == null ? void 0 : initialScrollProp.index) !== void 0 && (initialScrollProp == null ? void 0 : initialScrollProp.viewPosition) !== void 0 ? {
4304
+ attempts: 0,
4305
+ index: initialScrollProp.index,
4306
+ settledTicks: 0,
4307
+ viewOffset: (_f = initialScrollProp.viewOffset) != null ? _f : 0,
4308
+ viewPosition: initialScrollProp.viewPosition
4309
+ } : void 0,
4310
+ initialNativeScrollWatchdog: void 0,
4311
+ initialScroll: initialScrollProp,
4312
+ initialScrollLastDidFinish: false,
4313
+ initialScrollLastTarget: initialScrollProp,
4314
+ initialScrollLastTargetUsesOffset: initialScrollUsesOffsetOnly,
4315
+ initialScrollPreviousDataLength: dataProp.length,
4316
+ initialScrollRetryLastLength: void 0,
4317
+ initialScrollRetryWindowUntil: 0,
4318
+ initialScrollUsesOffset: initialScrollUsesOffsetOnly,
4319
+ isAtEnd: false,
4320
+ isAtStart: false,
4321
+ isEndReached: null,
4322
+ isFirst: true,
4323
+ isStartReached: null,
4324
+ lastBatchingAction: Date.now(),
4325
+ lastLayout: void 0,
4326
+ lastScrollDelta: 0,
4327
+ loadStartTime: Date.now(),
4328
+ minIndexSizeChanged: 0,
4329
+ nativeContentInset: void 0,
4330
+ nativeMarginTop: 0,
4331
+ pendingNativeMVCPAdjust: void 0,
4332
+ positions: [],
4333
+ props: {},
4334
+ queuedCalculateItemsInView: 0,
4335
+ refScroller: { current: null },
4336
+ scroll: 0,
4337
+ scrollAdjustHandler: new ScrollAdjustHandler(ctx),
4338
+ scrollForNextCalculateItemsInView: void 0,
4339
+ scrollHistory: [],
4340
+ scrollLength: initialScrollLength,
4341
+ scrollPending: 0,
4342
+ scrollPrev: 0,
4343
+ scrollPrevTime: 0,
4344
+ scrollProcessingEnabled: true,
4345
+ scrollTime: 0,
4346
+ sizes: /* @__PURE__ */ new Map(),
4347
+ sizesKnown: /* @__PURE__ */ new Map(),
4348
+ startBuffered: -1,
4349
+ startNoBuffer: -1,
4350
+ startReachedSnapshot: void 0,
4351
+ startReachedSnapshotDataChangeEpoch: void 0,
4352
+ stickyContainerPool: /* @__PURE__ */ new Set(),
4353
+ stickyContainers: /* @__PURE__ */ new Map(),
4354
+ timeoutSizeMessage: 0,
4355
+ timeouts: /* @__PURE__ */ new Set(),
4356
+ totalSize: 0,
4357
+ viewabilityConfigCallbackPairs: void 0
4358
+ };
4359
+ const internalState = ctx.state;
4360
+ internalState.triggerCalculateItemsInView = (params) => calculateItemsInView(ctx, params);
4361
+ set$(ctx, "maintainVisibleContentPosition", maintainVisibleContentPositionConfig);
4362
+ set$(ctx, "extraData", extraData);
4363
+ }
4364
+ refState.current = ctx.state;
4365
+ }
4366
+ const state = refState.current;
4367
+ const isFirstLocal = state.isFirst;
4368
+ state.didColumnsChange = numColumnsProp !== state.props.numColumns;
4369
+ const didDataReferenceChangeLocal = state.props.data !== dataProp;
4370
+ const didDataVersionChangeLocal = state.props.dataVersion !== dataVersion;
4371
+ const didDataChangeLocal = didDataVersionChangeLocal || didDataReferenceChangeLocal && checkActualChange(state, dataProp, state.props.data);
4372
+ if (didDataChangeLocal) {
4373
+ state.dataChangeEpoch += 1;
4374
+ state.dataChangeNeedsScrollUpdate = true;
4375
+ state.didDataChange = true;
4376
+ state.previousData = state.props.data;
4377
+ }
4378
+ const throttleScrollFn = scrollEventThrottle && onScrollProp ? useThrottledOnScroll(onScrollProp, scrollEventThrottle) : onScrollProp;
4379
+ state.props = {
4380
+ alignItemsAtEnd,
4381
+ alwaysRender,
4382
+ alwaysRenderIndicesArr: alwaysRenderIndices.arr,
4383
+ alwaysRenderIndicesSet: alwaysRenderIndices.set,
4384
+ animatedProps: animatedPropsInternal,
4385
+ contentInset,
4386
+ data: dataProp,
4387
+ dataVersion,
4388
+ drawDistance,
4389
+ estimatedItemSize,
4390
+ getEstimatedItemSize: useWrapIfItem(getEstimatedItemSize),
4391
+ getFixedItemSize: useWrapIfItem(getFixedItemSize),
4392
+ getItemType: useWrapIfItem(getItemType),
4393
+ horizontal: !!horizontal,
4394
+ initialContainerPoolRatio,
4395
+ itemsAreEqual,
4396
+ keyExtractor: useWrapIfItem(keyExtractor),
4397
+ maintainScrollAtEnd: maintainScrollAtEndConfig,
4398
+ maintainScrollAtEndThreshold,
4399
+ maintainVisibleContentPosition: maintainVisibleContentPositionConfig,
4400
+ numColumns: numColumnsProp,
4401
+ onEndReached,
4402
+ onEndReachedThreshold,
4403
+ onItemSizeChanged,
4404
+ onLoad,
4405
+ onScroll: throttleScrollFn,
4406
+ onStartReached,
4407
+ onStartReachedThreshold,
4408
+ onStickyHeaderChange,
4409
+ overrideItemLayout,
4410
+ positionComponentInternal,
4411
+ recycleItems: !!recycleItems,
4412
+ renderItem,
4413
+ snapToIndices,
4414
+ stickyIndicesArr: stickyHeaderIndices != null ? stickyHeaderIndices : [],
4415
+ stickyIndicesSet: useMemo(() => new Set(stickyHeaderIndices != null ? stickyHeaderIndices : []), [stickyHeaderIndices == null ? void 0 : stickyHeaderIndices.join(",")]),
4416
+ stickyPositionComponentInternal,
4417
+ stylePaddingBottom: stylePaddingBottomState,
4418
+ stylePaddingTop: stylePaddingTopState,
4419
+ suggestEstimatedItemSize: !!suggestEstimatedItemSize,
4420
+ useWindowScroll: useWindowScrollResolved
4421
+ };
4422
+ state.refScroller = refScroller;
4423
+ const memoizedLastItemKeys = useMemo(() => {
4424
+ if (!dataProp.length) return [];
4425
+ return Array.from(
4426
+ { length: Math.min(numColumnsProp, dataProp.length) },
4427
+ (_, i) => getId(state, dataProp.length - 1 - i)
4428
+ );
4429
+ }, [dataProp, dataVersion, numColumnsProp]);
4430
+ const initializeStateVars = (shouldAdjustPadding) => {
4431
+ set$(ctx, "lastItemKeys", memoizedLastItemKeys);
4432
+ set$(ctx, "numColumns", numColumnsProp);
4433
+ const prevPaddingTop = peek$(ctx, "stylePaddingTop");
4434
+ setPaddingTop(ctx, { stylePaddingTop: stylePaddingTopState });
4435
+ refState.current.props.stylePaddingBottom = stylePaddingBottomState;
4436
+ let paddingDiff = stylePaddingTopState - prevPaddingTop;
4437
+ if (shouldAdjustPadding && maintainVisibleContentPositionConfig.size && paddingDiff && prevPaddingTop !== void 0 && Platform2.OS === "ios") {
4438
+ if (state.scroll < 0) {
4439
+ paddingDiff += state.scroll;
4440
+ }
4441
+ requestAdjust(ctx, paddingDiff);
4442
+ }
4443
+ };
4444
+ if (isFirstLocal) {
4445
+ initializeStateVars(false);
4446
+ updateItemPositions(
4447
+ ctx,
4448
+ /*dataChanged*/
4449
+ true
4450
+ );
4451
+ }
4452
+ const resolveInitialScrollOffset = useCallback((initialScroll) => {
4453
+ var _a4;
4454
+ if (state.initialScrollUsesOffset) {
4455
+ return clampScrollOffset(ctx, (_a4 = initialScroll.contentOffset) != null ? _a4 : 0);
4456
+ }
4457
+ const baseOffset = initialScroll.index !== void 0 ? calculateOffsetForIndex(ctx, initialScroll.index) : 0;
4458
+ const resolvedOffset = calculateOffsetWithOffsetPosition(ctx, baseOffset, initialScroll);
4459
+ return clampScrollOffset(ctx, resolvedOffset, initialScroll);
4460
+ }, []);
4461
+ const finishInitialScrollWithoutScroll = useCallback(() => {
4462
+ refState.current.initialAnchor = void 0;
4463
+ refState.current.initialScroll = void 0;
4464
+ state.initialAnchor = void 0;
4465
+ state.initialScroll = void 0;
4466
+ state.initialScrollUsesOffset = false;
4467
+ state.initialScrollLastTarget = void 0;
4468
+ state.initialScrollLastTargetUsesOffset = false;
4469
+ setInitialRenderState(ctx, { didInitialScroll: true });
4470
+ }, []);
4471
+ const setActiveInitialScrollTarget = useCallback(
4472
+ (target, options) => {
4473
+ var _a4;
4474
+ const usesOffset = !!(options == null ? void 0 : options.usesOffset);
4475
+ state.initialScrollUsesOffset = usesOffset;
4476
+ state.initialScrollLastTarget = target;
4477
+ state.initialScrollLastTargetUsesOffset = usesOffset;
4478
+ refState.current.initialScroll = target;
4479
+ state.initialScroll = target;
4480
+ if ((options == null ? void 0 : options.resetDidFinish) && state.didFinishInitialScroll) {
4481
+ state.didFinishInitialScroll = false;
4482
+ }
4483
+ if (!(options == null ? void 0 : options.syncAnchor)) {
4484
+ return;
4485
+ }
4486
+ if (!IsNewArchitecture && !usesOffset && target.index !== void 0 && target.viewPosition !== void 0) {
4487
+ state.initialAnchor = {
4488
+ attempts: 0,
4489
+ index: target.index,
4490
+ settledTicks: 0,
4491
+ viewOffset: (_a4 = target.viewOffset) != null ? _a4 : 0,
4492
+ viewPosition: target.viewPosition
4493
+ };
4494
+ }
4495
+ },
4496
+ []
4497
+ );
4498
+ const shouldFinishInitialScrollAtOrigin = useCallback(
4499
+ (initialScroll, offset) => {
4500
+ var _a4, _b2, _c2;
4501
+ if (offset !== 0 || initialScrollAtEnd) {
4502
+ return false;
4503
+ }
4504
+ if (state.initialScrollUsesOffset) {
4505
+ return Math.abs((_a4 = initialScroll.contentOffset) != null ? _a4 : 0) <= 1;
4506
+ }
4507
+ return initialScroll.index === 0 && ((_b2 = initialScroll.viewPosition) != null ? _b2 : 0) === 0 && Math.abs((_c2 = initialScroll.viewOffset) != null ? _c2 : 0) <= 1;
4508
+ },
4509
+ [initialScrollAtEnd]
4510
+ );
4511
+ const shouldFinishEmptyInitialScrollAtEnd = useCallback(
4512
+ (initialScroll, offset) => {
4513
+ return dataProp.length === 0 && initialScrollAtEnd && offset === 0 && initialScroll.viewPosition === 1;
4514
+ },
4515
+ [dataProp.length, initialScrollAtEnd]
4516
+ );
4517
+ const shouldRearmFinishedEmptyInitialScrollAtEnd = useCallback(
4518
+ (initialScroll) => {
4519
+ var _a4;
4520
+ return !!(state.didFinishInitialScroll && dataProp.length > 0 && initialScroll && !state.initialScrollUsesOffset && initialScroll.index === 0 && initialScroll.viewPosition === 1 && ((_a4 = initialScroll.contentOffset) != null ? _a4 : 0) === 0);
4521
+ },
4522
+ [dataProp.length]
4523
+ );
4524
+ const initialContentOffset = useMemo(() => {
4525
+ var _a4;
4526
+ let value;
4527
+ const { initialScroll, initialAnchor } = refState.current;
4528
+ if (initialScroll) {
4529
+ if (!state.initialScrollUsesOffset && !IsNewArchitecture && initialScroll.index !== void 0 && (!initialAnchor || (initialAnchor == null ? void 0 : initialAnchor.index) !== initialScroll.index)) {
4530
+ refState.current.initialAnchor = {
4531
+ attempts: 0,
4532
+ index: initialScroll.index,
4533
+ settledTicks: 0,
4534
+ viewOffset: (_a4 = initialScroll.viewOffset) != null ? _a4 : 0,
4535
+ viewPosition: initialScroll.viewPosition
4536
+ };
4537
+ }
4538
+ if (initialScroll.contentOffset !== void 0) {
4539
+ value = initialScroll.contentOffset;
4540
+ } else {
4541
+ const clampedOffset = resolveInitialScrollOffset(initialScroll);
4542
+ const updatedInitialScroll = { ...initialScroll, contentOffset: clampedOffset };
4543
+ setActiveInitialScrollTarget(updatedInitialScroll, {
4544
+ usesOffset: state.initialScrollUsesOffset
4545
+ });
4546
+ value = clampedOffset;
4547
+ }
4548
+ } else {
4549
+ refState.current.initialAnchor = void 0;
4550
+ value = 0;
4551
+ }
4552
+ const hasPendingDataDependentInitialScroll = !!initialScroll && dataProp.length === 0 && !shouldFinishInitialScrollAtOrigin(initialScroll, value) && !shouldFinishEmptyInitialScrollAtEnd(initialScroll, value);
4553
+ if (!value && !hasPendingDataDependentInitialScroll) {
4554
+ if (initialScroll && shouldFinishInitialScrollAtOrigin(initialScroll, value)) {
4555
+ finishInitialScrollWithoutScroll();
4556
+ } else {
4557
+ setInitialRenderState(ctx, { didInitialScroll: true });
4558
+ }
4559
+ }
4560
+ return value;
4561
+ }, []);
4562
+ if (isFirstLocal || didDataChangeLocal || numColumnsProp !== peek$(ctx, "numColumns")) {
4563
+ refState.current.lastBatchingAction = Date.now();
4564
+ if (!keyExtractorProp && !isFirstLocal && didDataChangeLocal) {
4565
+ IS_DEV && !childrenMode && warnDevOnce(
4566
+ "keyExtractor",
4567
+ "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."
4568
+ );
4569
+ refState.current.sizes.clear();
4570
+ refState.current.positions.length = 0;
4571
+ refState.current.totalSize = 0;
4572
+ set$(ctx, "totalSize", 0);
4573
+ }
4574
+ }
4575
+ const doInitialScroll = useCallback((options) => {
4576
+ var _a4, _b2;
4577
+ const allowPostFinishRetry = !!(options == null ? void 0 : options.allowPostFinishRetry);
4578
+ const { didFinishInitialScroll, queuedInitialLayout, scrollingTo } = state;
4579
+ const initialScroll = (_a4 = state.initialScroll) != null ? _a4 : allowPostFinishRetry ? state.initialScrollLastTarget : void 0;
4580
+ const isInitialScrollInProgress = !!(scrollingTo == null ? void 0 : scrollingTo.isInitialScroll);
4581
+ const needsContainerLayoutForInitialScroll = !state.initialScrollUsesOffset;
4582
+ const shouldWaitForInitialLayout = waitForInitialLayout && needsContainerLayoutForInitialScroll && !queuedInitialLayout && !allowPostFinishRetry && !isInitialScrollInProgress;
4583
+ if (!initialScroll || shouldWaitForInitialLayout || didFinishInitialScroll && !allowPostFinishRetry || scrollingTo && !isInitialScrollInProgress) {
4584
+ return;
4585
+ }
4586
+ if (allowPostFinishRetry && state.initialScrollLastTargetUsesOffset) {
4587
+ return;
4588
+ }
4589
+ const didMoveAwayFromInitialTarget = allowPostFinishRetry && initialScroll.contentOffset !== void 0 && Math.abs(state.scroll - initialScroll.contentOffset) > 1;
4590
+ if (didMoveAwayFromInitialTarget) {
4591
+ state.initialScrollRetryWindowUntil = 0;
4592
+ return;
4593
+ }
4594
+ const offset = resolveInitialScrollOffset(initialScroll);
4595
+ const activeInitialTargetOffset = isInitialScrollInProgress ? (_b2 = scrollingTo.targetOffset) != null ? _b2 : scrollingTo.offset : void 0;
4596
+ const didOffsetChange = initialScroll.contentOffset === void 0 || Math.abs(initialScroll.contentOffset - offset) > 1;
4597
+ const didActiveInitialTargetChange = activeInitialTargetOffset !== void 0 && Math.abs(activeInitialTargetOffset - offset) > 1;
4598
+ if (!didOffsetChange && (allowPostFinishRetry || isInitialScrollInProgress && !didActiveInitialTargetChange)) {
4599
+ return;
4600
+ }
4601
+ if (didOffsetChange) {
4602
+ const updatedInitialScroll = { ...initialScroll, contentOffset: offset };
4603
+ if (!state.initialScrollUsesOffset) {
4604
+ state.initialScrollLastTarget = updatedInitialScroll;
4605
+ state.initialScrollLastTargetUsesOffset = false;
4606
+ if (state.initialScroll) {
4607
+ refState.current.initialScroll = updatedInitialScroll;
4608
+ state.initialScroll = updatedInitialScroll;
4609
+ }
4610
+ }
4611
+ }
4612
+ const hasMeasuredScrollLayout = !!state.lastLayout && state.scrollLength > 0;
4613
+ const shouldForceNativeInitialScroll = state.initialScrollUsesOffset && hasMeasuredScrollLayout || allowPostFinishRetry || !!queuedInitialLayout || isInitialScrollInProgress && didOffsetChange;
4614
+ performInitialScroll(ctx, {
4615
+ forceScroll: shouldForceNativeInitialScroll,
4616
+ initialScrollUsesOffset: state.initialScrollUsesOffset,
4617
+ resolvedOffset: offset,
4618
+ target: initialScroll
4619
+ });
4620
+ }, []);
4621
+ useLayoutEffect(() => {
4622
+ var _a4;
4623
+ const previousDataLength = state.initialScrollPreviousDataLength;
4624
+ state.initialScrollPreviousDataLength = dataProp.length;
4625
+ if (previousDataLength !== 0 || dataProp.length === 0 || !state.initialScroll || !state.queuedInitialLayout) {
4626
+ return;
4627
+ }
4628
+ if (initialScrollAtEnd) {
4629
+ const lastIndex = Math.max(0, dataProp.length - 1);
4630
+ const initialScroll = state.initialScroll;
4631
+ const shouldRearm = shouldRearmFinishedEmptyInitialScrollAtEnd(initialScroll);
4632
+ if (state.didFinishInitialScroll && !shouldRearm) {
4633
+ return;
4634
+ }
4635
+ if (initialScroll && !state.initialScrollUsesOffset && initialScroll.index === lastIndex && initialScroll.viewPosition === 1 && !shouldRearm) {
4636
+ return;
4637
+ }
4638
+ const updatedInitialScroll = {
4639
+ contentOffset: void 0,
4640
+ index: lastIndex,
4641
+ viewOffset: (_a4 = initialScroll == null ? void 0 : initialScroll.viewOffset) != null ? _a4 : -stylePaddingBottomState,
4642
+ viewPosition: 1
4643
+ };
4644
+ setActiveInitialScrollTarget(updatedInitialScroll, {
4645
+ resetDidFinish: shouldRearm,
4646
+ syncAnchor: true
4647
+ });
4648
+ doInitialScroll();
4649
+ return;
4650
+ }
4651
+ if (state.didFinishInitialScroll) {
4652
+ return;
4653
+ }
4654
+ doInitialScroll();
4655
+ }, [
4656
+ dataProp.length,
4657
+ doInitialScroll,
4658
+ initialScrollAtEnd,
4659
+ shouldRearmFinishedEmptyInitialScrollAtEnd,
4660
+ stylePaddingBottomState
4661
+ ]);
4662
+ useLayoutEffect(() => {
4663
+ var _a4;
4664
+ if (!initialScrollAtEnd) {
4665
+ return;
4666
+ }
4667
+ const lastIndex = Math.max(0, dataProp.length - 1);
4668
+ const initialScroll = state.initialScroll;
4669
+ const shouldRearm = shouldRearmFinishedEmptyInitialScrollAtEnd(initialScroll);
4670
+ if (state.didFinishInitialScroll && !shouldRearm) {
4671
+ return;
4672
+ }
4673
+ if (shouldRearm) {
4674
+ state.didFinishInitialScroll = false;
4675
+ }
4676
+ if (initialScroll && !state.initialScrollUsesOffset && initialScroll.index === lastIndex && initialScroll.viewPosition === 1 && !shouldRearm) {
4677
+ return;
4678
+ }
4679
+ const updatedInitialScroll = {
4680
+ contentOffset: void 0,
4681
+ index: lastIndex,
4682
+ viewOffset: (_a4 = initialScroll == null ? void 0 : initialScroll.viewOffset) != null ? _a4 : -stylePaddingBottomState,
4683
+ viewPosition: 1
4684
+ };
4685
+ setActiveInitialScrollTarget(updatedInitialScroll, {
4686
+ resetDidFinish: shouldRearm,
4687
+ syncAnchor: true
4688
+ });
4689
+ doInitialScroll();
4690
+ }, [
4691
+ dataProp.length,
4692
+ doInitialScroll,
4693
+ initialScrollAtEnd,
4694
+ shouldRearmFinishedEmptyInitialScrollAtEnd,
4695
+ stylePaddingBottomState
4696
+ ]);
4697
+ const onLayoutFooter = useCallback(
4698
+ (layout) => {
4699
+ var _a4;
4700
+ if (!initialScrollAtEnd) {
4701
+ return;
4702
+ }
4703
+ const { initialScroll } = state;
4704
+ if (!initialScroll) {
4705
+ return;
4706
+ }
4707
+ const lastIndex = Math.max(0, dataProp.length - 1);
4708
+ if (initialScroll.index !== lastIndex || initialScroll.viewPosition !== 1) {
4709
+ return;
4710
+ }
4711
+ const footerSize = layout[horizontal ? "width" : "height"];
4712
+ const viewOffset = -stylePaddingBottomState - footerSize;
4713
+ if (initialScroll.viewOffset !== viewOffset) {
4714
+ const previousTargetOffset = (_a4 = initialScroll.contentOffset) != null ? _a4 : resolveInitialScrollOffset(initialScroll);
4715
+ const didMoveAwayFromFinishedInitialTarget = state.didFinishInitialScroll && Math.abs(state.scroll - previousTargetOffset) > 1;
4716
+ if (didMoveAwayFromFinishedInitialTarget) {
4717
+ return;
4718
+ }
4719
+ const updatedInitialScroll = { ...initialScroll, viewOffset };
4720
+ setActiveInitialScrollTarget(updatedInitialScroll, {
4721
+ resetDidFinish: true
4722
+ });
4723
+ doInitialScroll();
4724
+ }
4725
+ },
4726
+ [
4727
+ dataProp.length,
4728
+ doInitialScroll,
4729
+ horizontal,
4730
+ initialScrollAtEnd,
4731
+ resolveInitialScrollOffset,
4732
+ stylePaddingBottomState
4733
+ ]
4734
+ );
4735
+ const onLayoutChange = useCallback((layout) => {
4736
+ var _a4;
4737
+ handleLayout(ctx, layout, setCanRender);
4738
+ const SCROLL_LENGTH_RETRY_WINDOW_MS = 600;
4739
+ const now = Date.now();
4740
+ const didFinishInitialScroll = !!state.didFinishInitialScroll;
4741
+ if (didFinishInitialScroll && !state.initialScrollLastDidFinish) {
4742
+ state.initialScrollRetryWindowUntil = now + SCROLL_LENGTH_RETRY_WINDOW_MS;
4743
+ }
4744
+ state.initialScrollLastDidFinish = didFinishInitialScroll;
4745
+ const previousScrollLength = state.initialScrollRetryLastLength;
4746
+ const currentScrollLength = state.scrollLength;
4747
+ const didScrollLengthChange = previousScrollLength === void 0 || Math.abs(currentScrollLength - previousScrollLength) > 1;
4748
+ if (didScrollLengthChange) {
4749
+ state.initialScrollRetryLastLength = currentScrollLength;
4750
+ }
4751
+ if (didFinishInitialScroll && didScrollLengthChange && now <= state.initialScrollRetryWindowUntil && !state.initialScrollLastTargetUsesOffset && ((_a4 = state.initialScrollLastTarget) == null ? void 0 : _a4.index) !== void 0) {
4752
+ doInitialScroll({ allowPostFinishRetry: true });
4753
+ return;
4754
+ }
4755
+ doInitialScroll();
4756
+ }, []);
4757
+ const { onLayout } = useOnLayoutSync({
4758
+ onLayoutChange,
4759
+ onLayoutProp,
4760
+ ref: refScroller
4761
+ // the type of ScrollView doesn't include measure?
4762
+ });
4763
+ useLayoutEffect(() => {
4764
+ if (snapToIndices) {
4765
+ updateSnapToOffsets(ctx);
4766
+ }
4767
+ }, [snapToIndices]);
4768
+ useLayoutEffect(() => {
4769
+ const {
4770
+ didColumnsChange,
4771
+ didDataChange,
4772
+ isFirst,
4773
+ props: { data }
4774
+ } = state;
4775
+ const didAllocateContainers = data.length > 0 && doInitialAllocateContainers(ctx);
4776
+ if (!didAllocateContainers && !isFirst && (didDataChange || didColumnsChange)) {
4777
+ checkResetContainers(ctx, data);
4778
+ }
4779
+ state.didColumnsChange = false;
4780
+ state.didDataChange = false;
4781
+ state.isFirst = false;
4782
+ }, [dataProp, dataVersion, numColumnsProp]);
4783
+ useLayoutEffect(() => {
4784
+ var _a4;
4785
+ set$(ctx, "extraData", extraData);
4786
+ const didToggleOverride = prevHasOverrideItemLayout.current !== hasOverrideItemLayout;
4787
+ prevHasOverrideItemLayout.current = hasOverrideItemLayout;
4788
+ if ((hasOverrideItemLayout || didToggleOverride) && numColumnsProp > 1) {
4789
+ (_a4 = state.triggerCalculateItemsInView) == null ? void 0 : _a4.call(state, { forceFullItemPositions: true });
4790
+ }
4791
+ }, [extraData, hasOverrideItemLayout, numColumnsProp]);
4792
+ useLayoutEffect(
4793
+ () => initializeStateVars(true),
4794
+ [dataVersion, memoizedLastItemKeys.join(","), numColumnsProp, stylePaddingBottomState, stylePaddingTopState]
4795
+ );
4796
+ useEffect(() => {
4797
+ if (!onMetricsChange) {
4798
+ return;
4799
+ }
4800
+ let lastMetrics;
4801
+ const emitMetrics = () => {
4802
+ const metrics = {
4803
+ footerSize: peek$(ctx, "footerSize") || 0,
4804
+ headerSize: peek$(ctx, "headerSize") || 0
4805
+ };
4806
+ if (!lastMetrics || metrics.headerSize !== lastMetrics.headerSize || metrics.footerSize !== lastMetrics.footerSize) {
4807
+ lastMetrics = metrics;
4808
+ onMetricsChange(metrics);
4809
+ }
4810
+ };
4811
+ emitMetrics();
4812
+ const unsubscribe = [listen$(ctx, "headerSize", emitMetrics), listen$(ctx, "footerSize", emitMetrics)];
4813
+ return () => {
4814
+ for (const unsub of unsubscribe) {
4815
+ unsub();
4816
+ }
4817
+ };
4818
+ }, [ctx, onMetricsChange]);
4819
+ useEffect(() => {
4820
+ const viewability = setupViewability({
4821
+ onViewableItemsChanged,
4822
+ viewabilityConfig,
4823
+ viewabilityConfigCallbackPairs
4824
+ });
4825
+ state.viewabilityConfigCallbackPairs = viewability;
4826
+ state.enableScrollForNextCalculateItemsInView = !viewability;
4827
+ }, [viewabilityConfig, viewabilityConfigCallbackPairs, onViewableItemsChanged]);
4828
+ if (!IsNewArchitecture) {
4829
+ useInit(() => {
4830
+ doInitialAllocateContainers(ctx);
4831
+ });
4832
+ }
4833
+ useImperativeHandle(forwardedRef, () => createImperativeHandle(ctx), []);
4834
+ if (Platform2.OS === "web") {
4835
+ useEffect(doInitialScroll, []);
4836
+ }
4837
+ const fns = useMemo(
4838
+ () => ({
4839
+ getRenderedItem: (key) => getRenderedItem(ctx, key),
4840
+ onMomentumScrollEnd: (event) => {
4841
+ checkFinishedScrollFallback(ctx);
4842
+ if (onMomentumScrollEnd) {
4843
+ onMomentumScrollEnd(event);
4844
+ }
4845
+ },
4846
+ onScroll: (event) => onScroll(ctx, event),
4847
+ updateItemSize: (itemKey, sizeObj) => updateItemSize(ctx, itemKey, sizeObj)
4848
+ }),
4849
+ []
4850
+ );
4851
+ const onScrollHandler = useStickyScrollHandler(stickyHeaderIndices, horizontal, ctx, fns.onScroll);
4852
+ const refreshControlElement = refreshControl;
4853
+ return /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement(
4854
+ ListComponent,
4855
+ {
4856
+ ...restProps,
4857
+ alignItemsAtEnd,
4858
+ canRender,
4859
+ contentContainerStyle,
4860
+ contentInset,
4861
+ getRenderedItem: fns.getRenderedItem,
4862
+ horizontal,
4863
+ initialContentOffset,
4864
+ ListEmptyComponent: dataProp.length === 0 ? ListEmptyComponent : void 0,
4865
+ ListHeaderComponent,
4866
+ onLayout,
4867
+ onLayoutFooter,
4868
+ onMomentumScrollEnd: fns.onMomentumScrollEnd,
4869
+ onScroll: onScrollHandler,
4870
+ recycleItems,
4871
+ refreshControl: refreshControlElement ? stylePaddingTopState > 0 ? React2.cloneElement(refreshControlElement, {
4872
+ progressViewOffset: ((_g = refreshControlElement.props.progressViewOffset) != null ? _g : 0) + stylePaddingTopState
4873
+ }) : refreshControlElement : onRefresh && /* @__PURE__ */ React2.createElement(
4874
+ RefreshControl,
4875
+ {
4876
+ onRefresh,
4877
+ progressViewOffset: (progressViewOffset || 0) + stylePaddingTopState,
4878
+ refreshing: !!refreshing
4879
+ }
4880
+ ),
4881
+ refScrollView: combinedRef,
4882
+ renderScrollComponent,
4883
+ scrollAdjustHandler: (_h = refState.current) == null ? void 0 : _h.scrollAdjustHandler,
4884
+ scrollEventThrottle: 0,
4885
+ snapToIndices,
4886
+ stickyHeaderIndices,
4887
+ style,
4888
+ updateItemSize: fns.updateItemSize,
4889
+ useWindowScroll: useWindowScrollResolved,
4890
+ waitForInitialLayout
4891
+ }
4892
+ ), IS_DEV && ENABLE_DEBUG_VIEW);
4893
+ });
4894
+
4895
+ // src/entrypoints/shared.ts
4896
+ var LegendListRuntime = LegendList;
4897
+ var internal = {
4898
+ getComponent,
4899
+ IsNewArchitecture,
4900
+ POSITION_OUT_OF_VIEW,
4901
+ peek$,
4902
+ useArr$,
4903
+ useCombinedRef,
4904
+ useStateContext
4905
+ };
4906
+
4907
+ // src/react-native.ts
4908
+ var LegendList3 = LegendListRuntime;
4909
+ var internal2 = internal;
4910
+
4911
+ export { LegendList3 as LegendList, internal2 as internal, typedForwardRef, typedMemo2 as typedMemo, useIsLastItem, useListScrollSize, useRecyclingEffect, useRecyclingState, useSyncLayout, useViewability, useViewabilityAmount };