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

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