@legendapp/list 3.0.0-beta.2 → 3.0.0-beta.20

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