@legendapp/list 2.1.0-beta.11 → 2.1.0-beta.13

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