@react-native-tvos/virtualized-lists 0.73.4-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.
@@ -0,0 +1,348 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @flow
8
+ * @format
9
+ */
10
+
11
+ 'use strict';
12
+
13
+ import type {CellMetricProps} from './ListMetricsAggregator';
14
+ import ListMetricsAggregator from './ListMetricsAggregator';
15
+
16
+ const invariant = require('invariant');
17
+
18
+ export type ViewToken = {
19
+ item: any,
20
+ key: string,
21
+ index: ?number,
22
+ isViewable: boolean,
23
+ section?: any,
24
+ ...
25
+ };
26
+
27
+ export type ViewabilityConfigCallbackPair = {
28
+ viewabilityConfig: ViewabilityConfig,
29
+ onViewableItemsChanged: (info: {
30
+ viewableItems: Array<ViewToken>,
31
+ changed: Array<ViewToken>,
32
+ ...
33
+ }) => void,
34
+ ...
35
+ };
36
+
37
+ export type ViewabilityConfig = {|
38
+ /**
39
+ * Minimum amount of time (in milliseconds) that an item must be physically viewable before the
40
+ * viewability callback will be fired. A high number means that scrolling through content without
41
+ * stopping will not mark the content as viewable.
42
+ */
43
+ minimumViewTime?: number,
44
+
45
+ /**
46
+ * Percent of viewport that must be covered for a partially occluded item to count as
47
+ * "viewable", 0-100. Fully visible items are always considered viewable. A value of 0 means
48
+ * that a single pixel in the viewport makes the item viewable, and a value of 100 means that
49
+ * an item must be either entirely visible or cover the entire viewport to count as viewable.
50
+ */
51
+ viewAreaCoveragePercentThreshold?: number,
52
+
53
+ /**
54
+ * Similar to `viewAreaPercentThreshold`, but considers the percent of the item that is visible,
55
+ * rather than the fraction of the viewable area it covers.
56
+ */
57
+ itemVisiblePercentThreshold?: number,
58
+
59
+ /**
60
+ * Nothing is considered viewable until the user scrolls or `recordInteraction` is called after
61
+ * render.
62
+ */
63
+ waitForInteraction?: boolean,
64
+ |};
65
+
66
+ /**
67
+ * A Utility class for calculating viewable items based on current metrics like scroll position and
68
+ * layout.
69
+ *
70
+ * An item is said to be in a "viewable" state when any of the following
71
+ * is true for longer than `minimumViewTime` milliseconds (after an interaction if `waitForInteraction`
72
+ * is true):
73
+ *
74
+ * - Occupying >= `viewAreaCoveragePercentThreshold` of the view area XOR fraction of the item
75
+ * visible in the view area >= `itemVisiblePercentThreshold`.
76
+ * - Entirely visible on screen
77
+ */
78
+ class ViewabilityHelper {
79
+ _config: ViewabilityConfig;
80
+ _hasInteracted: boolean = false;
81
+ _timers: Set<number> = new Set();
82
+ _viewableIndices: Array<number> = [];
83
+ _viewableItems: Map<string, ViewToken> = new Map();
84
+
85
+ constructor(
86
+ config: ViewabilityConfig = {viewAreaCoveragePercentThreshold: 0},
87
+ ) {
88
+ this._config = config;
89
+ }
90
+
91
+ /**
92
+ * Cleanup, e.g. on unmount. Clears any pending timers.
93
+ */
94
+ dispose() {
95
+ /* $FlowFixMe[incompatible-call] (>=0.63.0 site=react_native_fb) This
96
+ * comment suppresses an error found when Flow v0.63 was deployed. To see
97
+ * the error delete this comment and run Flow. */
98
+ this._timers.forEach(clearTimeout);
99
+ }
100
+
101
+ /**
102
+ * Determines which items are viewable based on the current metrics and config.
103
+ */
104
+ computeViewableItems(
105
+ props: CellMetricProps,
106
+ scrollOffset: number,
107
+ viewportHeight: number,
108
+ listMetrics: ListMetricsAggregator,
109
+ // Optional optimization to reduce the scan size
110
+ renderRange?: {
111
+ first: number,
112
+ last: number,
113
+ ...
114
+ },
115
+ ): Array<number> {
116
+ const itemCount = props.getItemCount(props.data);
117
+ const {itemVisiblePercentThreshold, viewAreaCoveragePercentThreshold} =
118
+ this._config;
119
+ const viewAreaMode = viewAreaCoveragePercentThreshold != null;
120
+ const viewablePercentThreshold = viewAreaMode
121
+ ? viewAreaCoveragePercentThreshold
122
+ : itemVisiblePercentThreshold;
123
+ invariant(
124
+ viewablePercentThreshold != null &&
125
+ (itemVisiblePercentThreshold != null) !==
126
+ (viewAreaCoveragePercentThreshold != null),
127
+ 'Must set exactly one of itemVisiblePercentThreshold or viewAreaCoveragePercentThreshold',
128
+ );
129
+ const viewableIndices = [];
130
+ if (itemCount === 0) {
131
+ return viewableIndices;
132
+ }
133
+ let firstVisible = -1;
134
+ const {first, last} = renderRange || {first: 0, last: itemCount - 1};
135
+ if (last >= itemCount) {
136
+ console.warn(
137
+ 'Invalid render range computing viewability ' +
138
+ JSON.stringify({renderRange, itemCount}),
139
+ );
140
+ return [];
141
+ }
142
+ for (let idx = first; idx <= last; idx++) {
143
+ const metrics = listMetrics.getCellMetrics(idx, props);
144
+ if (!metrics) {
145
+ continue;
146
+ }
147
+ const top = Math.floor(metrics.offset - scrollOffset);
148
+ const bottom = Math.floor(top + metrics.length);
149
+
150
+ if (top < viewportHeight && bottom > 0) {
151
+ firstVisible = idx;
152
+ if (
153
+ _isViewable(
154
+ viewAreaMode,
155
+ viewablePercentThreshold,
156
+ top,
157
+ bottom,
158
+ viewportHeight,
159
+ metrics.length,
160
+ )
161
+ ) {
162
+ viewableIndices.push(idx);
163
+ }
164
+ } else if (firstVisible >= 0) {
165
+ break;
166
+ }
167
+ }
168
+ return viewableIndices;
169
+ }
170
+
171
+ /**
172
+ * Figures out which items are viewable and how that has changed from before and calls
173
+ * `onViewableItemsChanged` as appropriate.
174
+ */
175
+ onUpdate(
176
+ props: CellMetricProps,
177
+ scrollOffset: number,
178
+ viewportHeight: number,
179
+ listMetrics: ListMetricsAggregator,
180
+ createViewToken: (
181
+ index: number,
182
+ isViewable: boolean,
183
+ props: CellMetricProps,
184
+ ) => ViewToken,
185
+ onViewableItemsChanged: ({
186
+ viewableItems: Array<ViewToken>,
187
+ changed: Array<ViewToken>,
188
+ ...
189
+ }) => void,
190
+ // Optional optimization to reduce the scan size
191
+ renderRange?: {
192
+ first: number,
193
+ last: number,
194
+ ...
195
+ },
196
+ ): void {
197
+ const itemCount = props.getItemCount(props.data);
198
+ if (
199
+ (this._config.waitForInteraction && !this._hasInteracted) ||
200
+ itemCount === 0 ||
201
+ !listMetrics.getCellMetrics(0, props)
202
+ ) {
203
+ return;
204
+ }
205
+ let viewableIndices: Array<number> = [];
206
+ if (itemCount) {
207
+ viewableIndices = this.computeViewableItems(
208
+ props,
209
+ scrollOffset,
210
+ viewportHeight,
211
+ listMetrics,
212
+ renderRange,
213
+ );
214
+ }
215
+ if (
216
+ this._viewableIndices.length === viewableIndices.length &&
217
+ this._viewableIndices.every((v, ii) => v === viewableIndices[ii])
218
+ ) {
219
+ // We might get a lot of scroll events where visibility doesn't change and we don't want to do
220
+ // extra work in those cases.
221
+ return;
222
+ }
223
+ this._viewableIndices = viewableIndices;
224
+ if (this._config.minimumViewTime) {
225
+ const handle: TimeoutID = setTimeout(() => {
226
+ /* $FlowFixMe[incompatible-call] (>=0.63.0 site=react_native_fb) This
227
+ * comment suppresses an error found when Flow v0.63 was deployed. To
228
+ * see the error delete this comment and run Flow. */
229
+ this._timers.delete(handle);
230
+ this._onUpdateSync(
231
+ props,
232
+ viewableIndices,
233
+ onViewableItemsChanged,
234
+ createViewToken,
235
+ );
236
+ }, this._config.minimumViewTime);
237
+ /* $FlowFixMe[incompatible-call] (>=0.63.0 site=react_native_fb) This
238
+ * comment suppresses an error found when Flow v0.63 was deployed. To see
239
+ * the error delete this comment and run Flow. */
240
+ this._timers.add(handle);
241
+ } else {
242
+ this._onUpdateSync(
243
+ props,
244
+ viewableIndices,
245
+ onViewableItemsChanged,
246
+ createViewToken,
247
+ );
248
+ }
249
+ }
250
+
251
+ /**
252
+ * clean-up cached _viewableIndices to evaluate changed items on next update
253
+ */
254
+ resetViewableIndices() {
255
+ this._viewableIndices = [];
256
+ }
257
+
258
+ /**
259
+ * Records that an interaction has happened even if there has been no scroll.
260
+ */
261
+ recordInteraction() {
262
+ this._hasInteracted = true;
263
+ }
264
+
265
+ _onUpdateSync(
266
+ props: CellMetricProps,
267
+ viewableIndicesToCheck: Array<number>,
268
+ onViewableItemsChanged: ({
269
+ changed: Array<ViewToken>,
270
+ viewableItems: Array<ViewToken>,
271
+ ...
272
+ }) => void,
273
+ createViewToken: (
274
+ index: number,
275
+ isViewable: boolean,
276
+ props: CellMetricProps,
277
+ ) => ViewToken,
278
+ ) {
279
+ // Filter out indices that have gone out of view since this call was scheduled.
280
+ viewableIndicesToCheck = viewableIndicesToCheck.filter(ii =>
281
+ this._viewableIndices.includes(ii),
282
+ );
283
+ const prevItems = this._viewableItems;
284
+ const nextItems = new Map(
285
+ viewableIndicesToCheck.map(ii => {
286
+ const viewable = createViewToken(ii, true, props);
287
+ return [viewable.key, viewable];
288
+ }),
289
+ );
290
+
291
+ const changed = [];
292
+ for (const [key, viewable] of nextItems) {
293
+ if (!prevItems.has(key)) {
294
+ changed.push(viewable);
295
+ }
296
+ }
297
+ for (const [key, viewable] of prevItems) {
298
+ if (!nextItems.has(key)) {
299
+ changed.push({...viewable, isViewable: false});
300
+ }
301
+ }
302
+ if (changed.length > 0) {
303
+ this._viewableItems = nextItems;
304
+ onViewableItemsChanged({
305
+ viewableItems: Array.from(nextItems.values()),
306
+ changed,
307
+ viewabilityConfig: this._config,
308
+ });
309
+ }
310
+ }
311
+ }
312
+
313
+ function _isViewable(
314
+ viewAreaMode: boolean,
315
+ viewablePercentThreshold: number,
316
+ top: number,
317
+ bottom: number,
318
+ viewportHeight: number,
319
+ itemLength: number,
320
+ ): boolean {
321
+ if (_isEntirelyVisible(top, bottom, viewportHeight)) {
322
+ return true;
323
+ } else {
324
+ const pixels = _getPixelsVisible(top, bottom, viewportHeight);
325
+ const percent =
326
+ 100 * (viewAreaMode ? pixels / viewportHeight : pixels / itemLength);
327
+ return percent >= viewablePercentThreshold;
328
+ }
329
+ }
330
+
331
+ function _getPixelsVisible(
332
+ top: number,
333
+ bottom: number,
334
+ viewportHeight: number,
335
+ ): number {
336
+ const visibleHeight = Math.min(bottom, viewportHeight) - Math.max(top, 0);
337
+ return Math.max(0, visibleHeight);
338
+ }
339
+
340
+ function _isEntirelyVisible(
341
+ top: number,
342
+ bottom: number,
343
+ viewportHeight: number,
344
+ ): boolean {
345
+ return top >= 0 && bottom <= viewportHeight && bottom > top;
346
+ }
347
+
348
+ module.exports = ViewabilityHelper;
@@ -0,0 +1,245 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @flow
8
+ * @format
9
+ */
10
+
11
+ 'use strict';
12
+
13
+ import type ListMetricsAggregator, {
14
+ CellMetricProps,
15
+ } from './ListMetricsAggregator';
16
+
17
+ /**
18
+ * Used to find the indices of the frames that overlap the given offsets. Useful for finding the
19
+ * items that bound different windows of content, such as the visible area or the buffered overscan
20
+ * area.
21
+ */
22
+ export function elementsThatOverlapOffsets(
23
+ offsets: Array<number>,
24
+ props: CellMetricProps,
25
+ listMetrics: ListMetricsAggregator,
26
+ zoomScale: number = 1,
27
+ ): Array<number> {
28
+ const itemCount = props.getItemCount(props.data);
29
+ const result = [];
30
+ for (let offsetIndex = 0; offsetIndex < offsets.length; offsetIndex++) {
31
+ const currentOffset = offsets[offsetIndex];
32
+ let left = 0;
33
+ let right = itemCount - 1;
34
+
35
+ while (left <= right) {
36
+ const mid = left + Math.floor((right - left) / 2);
37
+ const frame = listMetrics.getCellMetricsApprox(mid, props);
38
+ const scaledOffsetStart = frame.offset * zoomScale;
39
+ const scaledOffsetEnd = (frame.offset + frame.length) * zoomScale;
40
+
41
+ // We want the first frame that contains the offset, with inclusive bounds. Thus, for the
42
+ // first frame the scaledOffsetStart is inclusive, while for other frames it is exclusive.
43
+ if (
44
+ (mid === 0 && currentOffset < scaledOffsetStart) ||
45
+ (mid !== 0 && currentOffset <= scaledOffsetStart)
46
+ ) {
47
+ right = mid - 1;
48
+ } else if (currentOffset > scaledOffsetEnd) {
49
+ left = mid + 1;
50
+ } else {
51
+ result[offsetIndex] = mid;
52
+ break;
53
+ }
54
+ }
55
+ }
56
+
57
+ return result;
58
+ }
59
+
60
+ /**
61
+ * Computes the number of elements in the `next` range that are new compared to the `prev` range.
62
+ * Handy for calculating how many new items will be rendered when the render window changes so we
63
+ * can restrict the number of new items render at once so that content can appear on the screen
64
+ * faster.
65
+ */
66
+ export function newRangeCount(
67
+ prev: {
68
+ first: number,
69
+ last: number,
70
+ ...
71
+ },
72
+ next: {
73
+ first: number,
74
+ last: number,
75
+ ...
76
+ },
77
+ ): number {
78
+ return (
79
+ next.last -
80
+ next.first +
81
+ 1 -
82
+ Math.max(
83
+ 0,
84
+ 1 + Math.min(next.last, prev.last) - Math.max(next.first, prev.first),
85
+ )
86
+ );
87
+ }
88
+
89
+ /**
90
+ * Custom logic for determining which items should be rendered given the current frame and scroll
91
+ * metrics, as well as the previous render state. The algorithm may evolve over time, but generally
92
+ * prioritizes the visible area first, then expands that with overscan regions ahead and behind,
93
+ * biased in the direction of scroll.
94
+ */
95
+ export function computeWindowedRenderLimits(
96
+ props: CellMetricProps,
97
+ maxToRenderPerBatch: number,
98
+ windowSize: number,
99
+ prev: {
100
+ first: number,
101
+ last: number,
102
+ },
103
+ listMetrics: ListMetricsAggregator,
104
+ scrollMetrics: {
105
+ dt: number,
106
+ offset: number,
107
+ velocity: number,
108
+ visibleLength: number,
109
+ zoomScale: number,
110
+ ...
111
+ },
112
+ ): {
113
+ first: number,
114
+ last: number,
115
+ } {
116
+ const itemCount = props.getItemCount(props.data);
117
+ if (itemCount === 0) {
118
+ return {first: 0, last: -1};
119
+ }
120
+ const {offset, velocity, visibleLength, zoomScale = 1} = scrollMetrics;
121
+
122
+ // Start with visible area, then compute maximum overscan region by expanding from there, biased
123
+ // in the direction of scroll. Total overscan area is capped, which should cap memory consumption
124
+ // too.
125
+ const visibleBegin = Math.max(0, offset);
126
+ const visibleEnd = visibleBegin + visibleLength;
127
+ const overscanLength = (windowSize - 1) * visibleLength;
128
+
129
+ // Considering velocity seems to introduce more churn than it's worth.
130
+ const leadFactor = 0.5; // Math.max(0, Math.min(1, velocity / 25 + 0.5));
131
+
132
+ const fillPreference =
133
+ velocity > 1 ? 'after' : velocity < -1 ? 'before' : 'none';
134
+
135
+ const overscanBegin = Math.max(
136
+ 0,
137
+ visibleBegin - (1 - leadFactor) * overscanLength,
138
+ );
139
+ const overscanEnd = Math.max(0, visibleEnd + leadFactor * overscanLength);
140
+
141
+ const lastItemOffset =
142
+ listMetrics.getCellMetricsApprox(itemCount - 1, props).offset * zoomScale;
143
+ if (lastItemOffset < overscanBegin) {
144
+ // Entire list is before our overscan window
145
+ return {
146
+ first: Math.max(0, itemCount - 1 - maxToRenderPerBatch),
147
+ last: itemCount - 1,
148
+ };
149
+ }
150
+
151
+ // Find the indices that correspond to the items at the render boundaries we're targeting.
152
+ let [overscanFirst, first, last, overscanLast] = elementsThatOverlapOffsets(
153
+ [overscanBegin, visibleBegin, visibleEnd, overscanEnd],
154
+ props,
155
+ listMetrics,
156
+ zoomScale,
157
+ );
158
+ overscanFirst = overscanFirst == null ? 0 : overscanFirst;
159
+ first = first == null ? Math.max(0, overscanFirst) : first;
160
+ overscanLast = overscanLast == null ? itemCount - 1 : overscanLast;
161
+ last =
162
+ last == null
163
+ ? Math.min(overscanLast, first + maxToRenderPerBatch - 1)
164
+ : last;
165
+ const visible = {first, last};
166
+
167
+ // We want to limit the number of new cells we're rendering per batch so that we can fill the
168
+ // content on the screen quickly. If we rendered the entire overscan window at once, the user
169
+ // could be staring at white space for a long time waiting for a bunch of offscreen content to
170
+ // render.
171
+ let newCellCount = newRangeCount(prev, visible);
172
+
173
+ while (true) {
174
+ if (first <= overscanFirst && last >= overscanLast) {
175
+ // If we fill the entire overscan range, we're done.
176
+ break;
177
+ }
178
+ const maxNewCells = newCellCount >= maxToRenderPerBatch;
179
+ const firstWillAddMore = first <= prev.first || first > prev.last;
180
+ const firstShouldIncrement =
181
+ first > overscanFirst && (!maxNewCells || !firstWillAddMore);
182
+ const lastWillAddMore = last >= prev.last || last < prev.first;
183
+ const lastShouldIncrement =
184
+ last < overscanLast && (!maxNewCells || !lastWillAddMore);
185
+ if (maxNewCells && !firstShouldIncrement && !lastShouldIncrement) {
186
+ // We only want to stop if we've hit maxNewCells AND we cannot increment first or last
187
+ // without rendering new items. This let's us preserve as many already rendered items as
188
+ // possible, reducing render churn and keeping the rendered overscan range as large as
189
+ // possible.
190
+ break;
191
+ }
192
+ if (
193
+ firstShouldIncrement &&
194
+ !(fillPreference === 'after' && lastShouldIncrement && lastWillAddMore)
195
+ ) {
196
+ if (firstWillAddMore) {
197
+ newCellCount++;
198
+ }
199
+ first--;
200
+ }
201
+ if (
202
+ lastShouldIncrement &&
203
+ !(fillPreference === 'before' && firstShouldIncrement && firstWillAddMore)
204
+ ) {
205
+ if (lastWillAddMore) {
206
+ newCellCount++;
207
+ }
208
+ last++;
209
+ }
210
+ }
211
+ if (
212
+ !(
213
+ last >= first &&
214
+ first >= 0 &&
215
+ last < itemCount &&
216
+ first >= overscanFirst &&
217
+ last <= overscanLast &&
218
+ first <= visible.first &&
219
+ last >= visible.last
220
+ )
221
+ ) {
222
+ throw new Error(
223
+ 'Bad window calculation ' +
224
+ JSON.stringify({
225
+ first,
226
+ last,
227
+ itemCount,
228
+ overscanFirst,
229
+ overscanLast,
230
+ visible,
231
+ }),
232
+ );
233
+ }
234
+ return {first, last};
235
+ }
236
+
237
+ export function keyExtractor(item: any, index: number): string {
238
+ if (typeof item === 'object' && item?.key != null) {
239
+ return item.key;
240
+ }
241
+ if (typeof item === 'object' && item?.id != null) {
242
+ return item.id;
243
+ }
244
+ return String(index);
245
+ }