@legendapp/list 3.0.0-beta.32 → 3.0.0-beta.33

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