@shopify/flash-list 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/FlashList.d.ts +1 -1
  3. package/dist/FlashList.d.ts.map +1 -1
  4. package/dist/FlashList.js +8 -4
  5. package/dist/FlashList.js.map +1 -1
  6. package/dist/MasonryFlashList.d.ts +39 -0
  7. package/dist/MasonryFlashList.d.ts.map +1 -0
  8. package/dist/MasonryFlashList.js +241 -0
  9. package/dist/MasonryFlashList.js.map +1 -0
  10. package/dist/__tests__/MasonryFlashList.test.d.ts +2 -0
  11. package/dist/__tests__/MasonryFlashList.test.d.ts.map +1 -0
  12. package/dist/__tests__/MasonryFlashList.test.js +205 -0
  13. package/dist/__tests__/MasonryFlashList.test.js.map +1 -0
  14. package/dist/__tests__/helpers/mountMasonryFlashList.d.ts +18 -0
  15. package/dist/__tests__/helpers/mountMasonryFlashList.d.ts.map +1 -0
  16. package/dist/__tests__/helpers/mountMasonryFlashList.js +44 -0
  17. package/dist/__tests__/helpers/mountMasonryFlashList.js.map +1 -0
  18. package/dist/errors/ExceptionList.d.ts +4 -0
  19. package/dist/errors/ExceptionList.d.ts.map +1 -1
  20. package/dist/errors/ExceptionList.js +4 -0
  21. package/dist/errors/ExceptionList.js.map +1 -1
  22. package/dist/index.d.ts +1 -0
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +3 -1
  25. package/dist/index.js.map +1 -1
  26. package/dist/native/auto-layout/AutoLayoutView.d.ts +2 -1
  27. package/dist/native/auto-layout/AutoLayoutView.d.ts.map +1 -1
  28. package/dist/native/auto-layout/AutoLayoutView.js.map +1 -1
  29. package/dist/native/auto-layout/AutoLayoutViewNativeComponentProps.d.ts +2 -0
  30. package/dist/native/auto-layout/AutoLayoutViewNativeComponentProps.d.ts.map +1 -1
  31. package/dist/tsconfig.tsbuildinfo +1 -1
  32. package/dist/viewability/ViewabilityManager.d.ts.map +1 -1
  33. package/dist/viewability/ViewabilityManager.js +3 -3
  34. package/dist/viewability/ViewabilityManager.js.map +1 -1
  35. package/package.json +11 -2
  36. package/src/FlashList.tsx +10 -5
  37. package/src/MasonryFlashList.tsx +439 -0
  38. package/src/__tests__/MasonryFlashList.test.ts +235 -0
  39. package/src/__tests__/helpers/mountMasonryFlashList.tsx +65 -0
  40. package/src/errors/ExceptionList.ts +5 -0
  41. package/src/index.ts +7 -0
  42. package/src/native/auto-layout/AutoLayoutView.tsx +2 -1
  43. package/src/native/auto-layout/AutoLayoutViewNativeComponentProps.ts +3 -0
  44. package/src/viewability/ViewabilityManager.ts +2 -1
@@ -0,0 +1,439 @@
1
+ import React, { useCallback, useRef, useEffect, useMemo } from "react";
2
+ import {
3
+ View,
4
+ Dimensions,
5
+ ScrollViewProps,
6
+ LayoutChangeEvent,
7
+ NativeScrollEvent,
8
+ NativeSyntheticEvent,
9
+ } from "react-native";
10
+
11
+ import CustomError from "./errors/CustomError";
12
+ import ExceptionList from "./errors/ExceptionList";
13
+ import FlashList from "./FlashList";
14
+ import { FlashListProps } from "./FlashListProps";
15
+ import ViewToken from "./viewability/ViewToken";
16
+
17
+ export interface MasonryFlashListProps<T>
18
+ extends Omit<
19
+ FlashListProps<T>,
20
+ | "horizontal"
21
+ | "initialScrollIndex"
22
+ | "inverted"
23
+ | "onBlankArea"
24
+ | "viewabilityConfigCallbackPairs"
25
+ > {
26
+ /**
27
+ * Allows you to change the column widths of the list. This is helpful if you want some columns to be wider than the others.
28
+ * e.g, if `numColumns` is `3`, you can return `2` for `index 1` and `1` for the rest to achieve a `1:2:1` split by width.
29
+ */
30
+ getColumnFlex?: (
31
+ items: MasonryListItem<T>[],
32
+ columnIndex: number,
33
+ maxColumns: number,
34
+ extraData?: any
35
+ ) => number;
36
+
37
+ /**
38
+ * If enabled, MasonryFlashList will try to reduce difference in column height by modifying item order.
39
+ * `overrideItemLayout` is required to make this work.
40
+ */
41
+ optimizeItemArrangement?: boolean;
42
+ }
43
+
44
+ type OnScrollCallback = ScrollViewProps["onScroll"];
45
+ const defaultEstimatedItemSize = 100;
46
+
47
+ export interface MasonryFlashListScrollEvent extends NativeScrollEvent {
48
+ doNotPropagate?: boolean;
49
+ }
50
+
51
+ export interface MasonryListItem<T> {
52
+ originalIndex: number;
53
+ originalItem: T;
54
+ }
55
+
56
+ /**
57
+ * MasonryFlashListRef with support for scroll related methods
58
+ */
59
+ export interface MasonryFlashListRef<T> {
60
+ scrollToOffset: FlashList<T>["scrollToOffset"];
61
+ scrollToEnd: FlashList<T>["scrollToEnd"];
62
+ getScrollableNode: FlashList<T>["getScrollableNode"];
63
+ }
64
+
65
+ /**
66
+ * FlashList variant that enables rendering of masonry layouts.
67
+ * If you want `MasonryFlashList` to optimize item arrangement, enable `optimizeItemArrangement` and pass a valid `overrideItemLayout` function.
68
+ */
69
+ const MasonryFlashListComponent = React.forwardRef(
70
+ <T,>(
71
+ /**
72
+ * Forward Ref will force cast generic parament T to unknown. Export has a explicit cast to solve this.
73
+ */
74
+ props: MasonryFlashListProps<T>,
75
+ forwardRef: React.ForwardedRef<MasonryFlashListRef<T>>
76
+ ) => {
77
+ const columnCount = props.numColumns || 1;
78
+ const drawDistance = props.drawDistance;
79
+ const estimatedListSize = props.estimatedListSize ??
80
+ Dimensions.get("window") ?? { height: 500, width: 500 };
81
+
82
+ if (props.optimizeItemArrangement && !props.overrideItemLayout) {
83
+ throw new CustomError(
84
+ ExceptionList.overrideItemLayoutRequiredForMasonryOptimization
85
+ );
86
+ }
87
+ const dataSet = useDataSet(
88
+ columnCount,
89
+ Boolean(props.optimizeItemArrangement),
90
+ props.data,
91
+ props.overrideItemLayout,
92
+ props.extraData
93
+ );
94
+
95
+ const totalColumnFlex = useTotalColumnFlex(dataSet, props);
96
+
97
+ const onScrollRef = useRef<OnScrollCallback[]>([]);
98
+ const emptyScrollEvent = useRef(getEmptyScrollEvent())
99
+ .current as NativeSyntheticEvent<MasonryFlashListScrollEvent>;
100
+ const ScrollComponent = useRef(
101
+ getFlashListScrollView(onScrollRef, () => {
102
+ return (
103
+ getListRenderedSize(parentFlashList)?.height ||
104
+ estimatedListSize.height
105
+ );
106
+ })
107
+ ).current;
108
+
109
+ const onScrollProxy = useRef<OnScrollCallback>(
110
+ (scrollEvent: NativeSyntheticEvent<MasonryFlashListScrollEvent>) => {
111
+ emptyScrollEvent.nativeEvent.contentOffset.y =
112
+ scrollEvent.nativeEvent.contentOffset.y -
113
+ (parentFlashList.current?.firstItemOffset ?? 0);
114
+ onScrollRef.current?.forEach((onScrollCallback) => {
115
+ onScrollCallback?.(emptyScrollEvent);
116
+ });
117
+ if (!scrollEvent.nativeEvent.doNotPropagate) {
118
+ props.onScroll?.(scrollEvent);
119
+ }
120
+ }
121
+ ).current;
122
+
123
+ /**
124
+ * We're triggering an onScroll on internal lists so that they register the correct offset which is offset - header size.
125
+ * This will make sure viewability callbacks are triggered correctly.
126
+ * 32 ms is equal to two frames at 60 fps. Faster framerates will not cause any problems.
127
+ */
128
+ const onLoadForNestedLists = useRef((args: { elapsedTimeInMs: number }) => {
129
+ setTimeout(() => {
130
+ emptyScrollEvent.nativeEvent.doNotPropagate = true;
131
+ onScrollProxy?.(emptyScrollEvent);
132
+ emptyScrollEvent.nativeEvent.doNotPropagate = false;
133
+ }, 32);
134
+ props.onLoad?.(args);
135
+ }).current;
136
+
137
+ const [parentFlashList, getFlashList] =
138
+ useRefWithForwardRef<FlashList<MasonryListItem<T>[]>>(forwardRef);
139
+
140
+ const {
141
+ renderItem,
142
+ getItemType,
143
+ getColumnFlex,
144
+ overrideItemLayout,
145
+ viewabilityConfig,
146
+ keyExtractor,
147
+ onLoad,
148
+ onViewableItemsChanged,
149
+ data,
150
+ stickyHeaderIndices,
151
+ CellRendererComponent,
152
+ ItemSeparatorComponent,
153
+ ...remainingProps
154
+ } = props;
155
+
156
+ const firstColumnHeight =
157
+ (dataSet[0]?.length ?? 0) *
158
+ (props.estimatedItemSize ?? defaultEstimatedItemSize);
159
+
160
+ return (
161
+ <FlashList
162
+ ref={getFlashList}
163
+ {...remainingProps}
164
+ horizontal={false}
165
+ numColumns={columnCount}
166
+ data={dataSet}
167
+ onScroll={onScrollProxy}
168
+ estimatedItemSize={firstColumnHeight || estimatedListSize.height}
169
+ renderItem={(args) => {
170
+ return (
171
+ <FlashList
172
+ renderScrollComponent={ScrollComponent}
173
+ estimatedItemSize={props.estimatedItemSize}
174
+ data={args.item}
175
+ onLoad={args.index === 0 ? onLoadForNestedLists : undefined}
176
+ renderItem={(innerArgs) => {
177
+ return (
178
+ renderItem?.({
179
+ ...innerArgs,
180
+ item: innerArgs.item.originalItem,
181
+ index: innerArgs.item.originalIndex,
182
+ }) ?? null
183
+ );
184
+ }}
185
+ keyExtractor={
186
+ keyExtractor
187
+ ? (item, _) => {
188
+ return keyExtractor?.(
189
+ item.originalItem,
190
+ item.originalIndex
191
+ );
192
+ }
193
+ : undefined
194
+ }
195
+ getItemType={
196
+ getItemType
197
+ ? (item, _, extraData) => {
198
+ return getItemType?.(
199
+ item.originalItem,
200
+ item.originalIndex,
201
+ extraData
202
+ );
203
+ }
204
+ : undefined
205
+ }
206
+ drawDistance={drawDistance}
207
+ estimatedListSize={{
208
+ height: estimatedListSize.height,
209
+ width:
210
+ ((getListRenderedSize(parentFlashList)?.width ||
211
+ estimatedListSize.width) /
212
+ totalColumnFlex) *
213
+ (getColumnFlex?.(
214
+ args.item,
215
+ args.index,
216
+ columnCount,
217
+ props.extraData
218
+ ) ?? 1),
219
+ }}
220
+ extraData={props.extraData}
221
+ CellRendererComponent={CellRendererComponent}
222
+ ItemSeparatorComponent={ItemSeparatorComponent}
223
+ viewabilityConfig={viewabilityConfig}
224
+ onViewableItemsChanged={
225
+ onViewableItemsChanged
226
+ ? (info) => {
227
+ updateViewTokens(info.viewableItems);
228
+ updateViewTokens(info.changed);
229
+ onViewableItemsChanged?.(info);
230
+ }
231
+ : undefined
232
+ }
233
+ overrideItemLayout={
234
+ overrideItemLayout
235
+ ? (layout, item, _, __, extraData) => {
236
+ overrideItemLayout?.(
237
+ layout,
238
+ item.originalItem,
239
+ item.originalIndex,
240
+ columnCount,
241
+ extraData
242
+ );
243
+ layout.span = undefined;
244
+ }
245
+ : undefined
246
+ }
247
+ />
248
+ );
249
+ }}
250
+ overrideItemLayout={
251
+ getColumnFlex
252
+ ? (layout, item, index, maxColumns, extraData) => {
253
+ layout.span =
254
+ (columnCount *
255
+ getColumnFlex(item, index, maxColumns, extraData)) /
256
+ totalColumnFlex;
257
+ }
258
+ : undefined
259
+ }
260
+ />
261
+ );
262
+ }
263
+ );
264
+
265
+ /**
266
+ * Splits data for each column's FlashList
267
+ */
268
+ const useDataSet = <T,>(
269
+ columnCount: number,
270
+ optimizeItemArrangement: boolean,
271
+ sourceData?: FlashListProps<T>["data"],
272
+ overrideItemLayout?: MasonryFlashListProps<T>["overrideItemLayout"],
273
+ extraData?: MasonryFlashListProps<T>["extraData"]
274
+ ): MasonryListItem<T>[][] => {
275
+ return useMemo(() => {
276
+ if (!sourceData || sourceData.length === 0) {
277
+ return [];
278
+ }
279
+ const columnHeightTracker = new Array<number>(columnCount).fill(0);
280
+ const layoutObject: { size: number | undefined } = { size: undefined };
281
+ const dataSet = new Array<MasonryListItem<T>[]>(columnCount);
282
+ const dataSize = sourceData.length;
283
+
284
+ for (let i = 0; i < columnCount; i++) {
285
+ dataSet[i] = [];
286
+ }
287
+ for (let i = 0; i < dataSize; i++) {
288
+ let nextColumnIndex = i % columnCount;
289
+ if (optimizeItemArrangement) {
290
+ for (let j = 0; j < columnCount; j++) {
291
+ if (columnHeightTracker[j] < columnHeightTracker[nextColumnIndex]) {
292
+ nextColumnIndex = j;
293
+ }
294
+ }
295
+ // update height of column
296
+ layoutObject.size = undefined;
297
+ overrideItemLayout!(
298
+ layoutObject,
299
+ sourceData[i],
300
+ i,
301
+ columnCount,
302
+ extraData
303
+ );
304
+ columnHeightTracker[nextColumnIndex] +=
305
+ layoutObject.size ?? defaultEstimatedItemSize;
306
+ }
307
+ dataSet[nextColumnIndex].push({
308
+ originalItem: sourceData[i],
309
+ originalIndex: i,
310
+ });
311
+ }
312
+ return dataSet;
313
+ // eslint-disable-next-line react-hooks/exhaustive-deps
314
+ }, [sourceData, columnCount, optimizeItemArrangement, extraData]);
315
+ };
316
+
317
+ const useTotalColumnFlex = <T,>(
318
+ dataSet: MasonryListItem<T>[][],
319
+ props: MasonryFlashListProps<T>
320
+ ): number => {
321
+ return useMemo(() => {
322
+ const columnCount = props.numColumns || 1;
323
+ if (!props.getColumnFlex) {
324
+ return columnCount;
325
+ }
326
+ let totalFlexSum = 0;
327
+ const dataSize = dataSet.length;
328
+ for (let i = 0; i < dataSize; i++) {
329
+ totalFlexSum += props.getColumnFlex(
330
+ dataSet[i],
331
+ i,
332
+ columnCount,
333
+ props.extraData
334
+ );
335
+ }
336
+ return totalFlexSum;
337
+ // eslint-disable-next-line react-hooks/exhaustive-deps
338
+ }, [dataSet, props.getColumnFlex, props.extraData]);
339
+ };
340
+
341
+ /**
342
+ * Handle both function refs and refs with current property
343
+ */
344
+ const useRefWithForwardRef = <T,>(
345
+ forwardRef: any
346
+ ): [React.MutableRefObject<T | null>, (instance: T | null) => void] => {
347
+ const ref: React.MutableRefObject<T | null> = useRef(null);
348
+ return [
349
+ ref,
350
+ useCallback(
351
+ (instance: T | null) => {
352
+ ref.current = instance;
353
+ if (typeof forwardRef === "function") {
354
+ forwardRef(instance);
355
+ } else if (forwardRef) {
356
+ forwardRef.current = instance;
357
+ }
358
+ },
359
+ [forwardRef]
360
+ ),
361
+ ];
362
+ };
363
+
364
+ /**
365
+ * This ScrollView is actually just a view mimicking a scrollview. We block the onScroll event from being passed to the parent list directly.
366
+ * We manually drive onScroll from the parent and thus, achieve recycling.
367
+ */
368
+ const getFlashListScrollView = (
369
+ onScrollRef: React.RefObject<OnScrollCallback[]>,
370
+ getParentHeight: () => number
371
+ ) => {
372
+ const FlashListScrollView = React.forwardRef(
373
+ (props: ScrollViewProps, ref: React.ForwardedRef<View>) => {
374
+ const { onLayout, onScroll, ...rest } = props;
375
+ const onLayoutProxy = useCallback(
376
+ (layoutEvent: LayoutChangeEvent) => {
377
+ onLayout?.({
378
+ nativeEvent: {
379
+ layout: {
380
+ height: getParentHeight(),
381
+ width: layoutEvent.nativeEvent.layout.width,
382
+ },
383
+ },
384
+ } as LayoutChangeEvent);
385
+ },
386
+ [onLayout]
387
+ );
388
+ useEffect(() => {
389
+ if (onScroll) {
390
+ onScrollRef.current?.push(onScroll);
391
+ }
392
+ return () => {
393
+ if (!onScrollRef.current || !onScroll) {
394
+ return;
395
+ }
396
+ const indexToDelete = onScrollRef.current.indexOf(onScroll);
397
+ if (indexToDelete > -1) {
398
+ onScrollRef.current.splice(indexToDelete, 1);
399
+ }
400
+ };
401
+ }, [onScroll]);
402
+ return <View ref={ref} {...rest} onLayout={onLayoutProxy} />;
403
+ }
404
+ );
405
+ FlashListScrollView.displayName = "FlashListScrollView";
406
+ return FlashListScrollView;
407
+ };
408
+ const updateViewTokens = (tokens: ViewToken[]) => {
409
+ const length = tokens.length;
410
+ for (let i = 0; i < length; i++) {
411
+ const token = tokens[i];
412
+ if (token.index !== null && token.index !== undefined) {
413
+ token.index = token.item.originalIndex;
414
+ token.item = token.item.originalItem;
415
+ }
416
+ }
417
+ };
418
+
419
+ const getEmptyScrollEvent = () => {
420
+ return {
421
+ nativeEvent: { contentOffset: { y: 0, x: 0 } },
422
+ };
423
+ };
424
+ const getListRenderedSize = <T,>(
425
+ parentFlashList: React.MutableRefObject<FlashList<T[]> | null>
426
+ ) => {
427
+ return parentFlashList?.current?.recyclerlistview_unsafe?.getRenderedSize();
428
+ };
429
+ MasonryFlashListComponent.displayName = "MasonryFlashList";
430
+
431
+ /**
432
+ * FlashList variant that enables rendering of masonry layouts.
433
+ * If you want `MasonryFlashList` to optimize item arrangement, enable `optimizeItemArrangement` and pass a valid `overrideItemLayout` function.
434
+ */
435
+ export const MasonryFlashList = MasonryFlashListComponent as <T>(
436
+ props: MasonryFlashListProps<T> & {
437
+ ref?: React.RefObject<MasonryFlashListRef<T>>;
438
+ }
439
+ ) => React.ReactElement;
@@ -0,0 +1,235 @@
1
+ import { ScrollView, Text, View } from "react-native";
2
+ import "@quilted/react-testing/matchers";
3
+ import { ProgressiveListView } from "recyclerlistview";
4
+ import React from "react";
5
+
6
+ import {
7
+ MasonryFlashListProps,
8
+ MasonryFlashListRef,
9
+ } from "../MasonryFlashList";
10
+ import FlashList from "../FlashList";
11
+
12
+ import { mountMasonryFlashList } from "./helpers/mountMasonryFlashList";
13
+
14
+ describe("MasonryFlashList", () => {
15
+ beforeEach(() => {
16
+ jest.clearAllMocks();
17
+ jest.useFakeTimers();
18
+ });
19
+
20
+ it("renders items and has 3 internal lists", () => {
21
+ const masonryFlashList = mountMasonryFlashList();
22
+ expect(masonryFlashList.findAll(ProgressiveListView).length).toBe(3);
23
+ expect(masonryFlashList).toContainReactComponent(Text, { children: "One" });
24
+ expect(masonryFlashList).toContainReactComponent(ProgressiveListView, {
25
+ isHorizontal: false,
26
+ });
27
+ masonryFlashList.unmount();
28
+ });
29
+ it("raised onLoad event only when first internal child mounts", () => {
30
+ const onLoadMock = jest.fn();
31
+ const ref = React.createRef<MasonryFlashListRef<string>>();
32
+ const masonryFlashList = mountMasonryFlashList(
33
+ {
34
+ onLoad: onLoadMock,
35
+ },
36
+ ref
37
+ );
38
+ expect(onLoadMock).not.toHaveBeenCalled();
39
+ masonryFlashList.findAll(ProgressiveListView)[1]?.instance.onItemLayout(0);
40
+ expect(onLoadMock).toHaveBeenCalledTimes(1);
41
+
42
+ // on load shouldn't be passed to wrapper list
43
+ expect((ref.current as FlashList<string>).props.onLoad).toBeUndefined();
44
+ masonryFlashList.unmount();
45
+ });
46
+ it("can resize columns using getColumnFlex", () => {
47
+ const masonryFlashList = mountMasonryFlashList({
48
+ getColumnFlex: (_, column) => (column === 0 ? 1 : 3),
49
+ });
50
+ const progressiveListView =
51
+ masonryFlashList.find(ProgressiveListView)!.instance;
52
+ expect(progressiveListView.getLayout(0).width).toBe(100);
53
+ expect(progressiveListView.getLayout(1).width).toBe(300);
54
+
55
+ expect(masonryFlashList.findAll(ProgressiveListView).length).toBe(3);
56
+ masonryFlashList.findAll(ProgressiveListView).forEach((plv, index) => {
57
+ if (index === 1) {
58
+ expect(plv.instance.props.layoutSize.width).toBe(100);
59
+ }
60
+ if (index === 2) {
61
+ expect(plv.instance.props.layoutSize.width).toBe(300);
62
+ }
63
+ });
64
+ masonryFlashList.unmount();
65
+ });
66
+ it("mounts a single ScrollView", () => {
67
+ const masonryFlashList = mountMasonryFlashList();
68
+ expect(masonryFlashList.findAll(ScrollView)).toHaveLength(1);
69
+ masonryFlashList.unmount();
70
+ });
71
+ it("forwards single onScroll event to external listener", () => {
72
+ const onScrollMock = jest.fn();
73
+ const masonryFlashList = mountMasonryFlashList({
74
+ onScroll: onScrollMock,
75
+ });
76
+ masonryFlashList.find(ScrollView)?.instance.props.onScroll({
77
+ nativeEvent: { contentOffset: { x: 0, y: 0 } },
78
+ });
79
+ expect(onScrollMock).toHaveBeenCalledTimes(1);
80
+ masonryFlashList.unmount();
81
+ });
82
+ it("updates scroll offset of all internal lists", () => {
83
+ const onScrollMock = jest.fn();
84
+ const masonryFlashList = mountMasonryFlashList({
85
+ onScroll: onScrollMock,
86
+ });
87
+ masonryFlashList.find(ScrollView)?.instance.props.onScroll({
88
+ nativeEvent: { contentOffset: { x: 0, y: 100 } },
89
+ });
90
+ masonryFlashList.findAll(ProgressiveListView).forEach((list) => {
91
+ expect(list.instance.getCurrentScrollOffset()).toBe(100);
92
+ });
93
+ masonryFlashList.unmount();
94
+ });
95
+ it("has a valid ref object", () => {
96
+ const ref = React.createRef<MasonryFlashListRef<string>>();
97
+ const masonryFlashList = mountMasonryFlashList({}, ref);
98
+ expect(ref.current).toBeDefined();
99
+ masonryFlashList.unmount();
100
+ });
101
+ it("forwards overrideItemLayout to internal lists", () => {
102
+ const overrideItemLayout = jest.fn((layout) => {
103
+ layout.size = 300;
104
+ });
105
+ const masonryFlashList = mountMasonryFlashList({
106
+ overrideItemLayout,
107
+ });
108
+ expect(masonryFlashList.findAll(ProgressiveListView).length).toBe(3);
109
+ masonryFlashList.findAll(ProgressiveListView).forEach((list, index) => {
110
+ if (index !== 0) {
111
+ expect(list.instance.getLayout(0).height).toBe(300);
112
+ }
113
+ });
114
+ masonryFlashList.unmount();
115
+ });
116
+ it("forwards keyExtractor to internal list", () => {
117
+ const keyExtractor = (_: string, index: number) => (index + 1).toString();
118
+ const masonryFlashList = mountMasonryFlashList({
119
+ keyExtractor,
120
+ });
121
+ expect(masonryFlashList.findAll(ProgressiveListView).length).toBe(3);
122
+ expect(
123
+ masonryFlashList
124
+ .findAll(ProgressiveListView)[0]
125
+ .instance.props.dataProvider.getStableId(0)
126
+ ).toBe("0");
127
+ expect(
128
+ masonryFlashList
129
+ .findAll(ProgressiveListView)[1]
130
+ .instance.props.dataProvider.getStableId(0)
131
+ ).toBe("1");
132
+ expect(
133
+ masonryFlashList
134
+ .findAll(ProgressiveListView)[2]
135
+ .instance.props.dataProvider.getStableId(0)
136
+ ).toBe("2");
137
+ masonryFlashList.unmount();
138
+ });
139
+ it("correctly maps list indices to actual indices", () => {
140
+ const data = new Array(20).fill(0).map((_, index) => index.toString());
141
+ const getItemType = (item: string, index: number) => {
142
+ expect(index.toString()).toBe(item);
143
+ return 0;
144
+ };
145
+ const renderItem: MasonryFlashListProps<string>["renderItem"] = ({
146
+ item,
147
+ index,
148
+ }) => {
149
+ expect(index.toString()).toBe(item);
150
+ return null;
151
+ };
152
+ const overrideItemLayout: MasonryFlashListProps<string>["overrideItemLayout"] =
153
+ (layout, item: string, index: number) => {
154
+ expect(index.toString()).toBe(item);
155
+ };
156
+ const keyExtractor = (item: string, index: number) => {
157
+ expect(index.toString()).toBe(item);
158
+ return index.toString();
159
+ };
160
+ const onViewableItemsChanged: MasonryFlashListProps<string>["onViewableItemsChanged"] =
161
+ (info) => {
162
+ info.viewableItems.forEach((viewToken) => {
163
+ expect(viewToken.index?.toString()).toBe(viewToken.item);
164
+ });
165
+ };
166
+
167
+ const masonryFlashList = mountMasonryFlashList({
168
+ data,
169
+ renderItem,
170
+ getItemType,
171
+ overrideItemLayout,
172
+ keyExtractor,
173
+ onViewableItemsChanged,
174
+ });
175
+ jest.advanceTimersByTime(1000);
176
+ masonryFlashList.unmount();
177
+ });
178
+ it("internal list height should be derived from the parent and width from itself", () => {
179
+ const masonryFlashList = mountMasonryFlashList({
180
+ testID: "MasonryProxyScrollView",
181
+ });
182
+ expect(masonryFlashList.findAll(ProgressiveListView).length).toBe(3);
183
+ masonryFlashList.findAll(View).forEach((view: any) => {
184
+ view.props?.onLayout?.({
185
+ nativeEvent: { layout: { width: 500, height: 500 } },
186
+ });
187
+ });
188
+ masonryFlashList.findAll(ProgressiveListView).forEach((list, index) => {
189
+ if (index !== 0) {
190
+ expect(list.instance.getRenderedSize().width).toBe(500);
191
+ expect(list.instance.getRenderedSize().height).toBe(900);
192
+ }
193
+ });
194
+ masonryFlashList.unmount();
195
+ });
196
+ it("can optimize item arrangement", () => {
197
+ const columnCount = 3;
198
+ const data = new Array(999).fill(null).map((_, index) => {
199
+ return "1";
200
+ });
201
+ const masonryFlashList = mountMasonryFlashList({
202
+ data,
203
+ optimizeItemArrangement: true,
204
+ numColumns: columnCount,
205
+ overrideItemLayout(layout, _, index, __, ___?) {
206
+ layout.size = ((index * 10) % 100) + 100 / ((index % columnCount) + 1);
207
+ },
208
+ });
209
+ expect(masonryFlashList.findAll(ProgressiveListView).length).toBe(4);
210
+
211
+ // I've verified that the following values are correct by observing the algorithm in action
212
+ // Captured values will help prevent regression in the future
213
+ expect(
214
+ Math.floor(
215
+ masonryFlashList
216
+ .findAll(ProgressiveListView)[1]
217
+ .instance.getContentDimension().height
218
+ )
219
+ ).toBe(35306);
220
+ expect(
221
+ Math.floor(
222
+ masonryFlashList
223
+ .findAll(ProgressiveListView)[2]
224
+ .instance.getContentDimension().height
225
+ )
226
+ ).toBe(35313);
227
+ expect(
228
+ Math.floor(
229
+ masonryFlashList
230
+ .findAll(ProgressiveListView)[3]
231
+ .instance.getContentDimension().height
232
+ )
233
+ ).toBe(35339);
234
+ });
235
+ });