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

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