-
Notifications
You must be signed in to change notification settings - Fork 101
/
FixedHeightWindowedListView.js
428 lines (360 loc) · 13 KB
/
FixedHeightWindowedListView.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/**
* @providesModule FixedHeightWindowedListView
*/
'use strict';
import React, { Component } from 'react'
import PropTypes from 'prop-types';
import {
Platform,
ScrollView,
Text,
View,
Dimensions,
} from 'react-native';
import FixedHeightWindowedListViewDataSource from './FixedHeightWindowedListViewDataSource';
import clamp from './clamp';
import deepDiffer from './deepDiffer';
import invariant from './invariant';
import _ from 'lodash';
/**
* An experimental ListView implementation that only renders a subset of rows of
* a potentially very large set of data.
*
* Row data should be provided as a simple array corresponding to rows. `===`
* is used to determine if a row has changed and should be re-rendered.
*
* Rendering is done incrementally by row to minimize the amount of work done
* per JS event tick.
*
* Rows must have a pre-determined height, thus FixedHeight. The height
* of the rows can vary depending on the section that they are in.
*/
export default class FixedHeightWindowedListView extends Component {
constructor(props, context) {
super(props, context);
invariant(
this.props.numToRenderAhead < this.props.maxNumToRender,
'FixedHeightWindowedListView: numToRenderAhead must be less than maxNumToRender'
);
invariant(
this.props.numToRenderBehind < this.props.maxNumToRender,
'FixedHeightWindowedListView: numToRenderBehind must be less than maxNumToRender'
);
this.__onScroll = this.__onScroll.bind(this);
this.__enqueueComputeRowsToRender = this.__enqueueComputeRowsToRender.bind(this);
this.__computeRowsToRenderSync = this.__computeRowsToRenderSync.bind(this);
this.scrollOffsetY = 0;
this.height = 0;
this.willComputeRowsToRender = false;
this.timeoutHandle = 0;
this.nextSectionToScrollTo = null;
this.scrollDirection = 'down';
let { dataSource, initialNumToRender } = this.props;
this.state = {
firstRow: 0,
lastRow: Math.min(dataSource.getRowCount() - 1, initialNumToRender),
bufferFirstRow: null,
bufferLastRow: null,
};
}
componentWillReceiveProps(nextProps) {
this.__computeRowsToRenderSync(nextProps, true);
}
componentWillUnmount() {
clearTimeout(this.timeoutHandle);
}
render() {
this.__rowCache = this.__rowCache || {};
let { bufferFirstRow, bufferLastRow } = this.state;
let { firstRow, lastRow } = this.state;
let { spacerTopHeight, spacerBottomHeight, spacerMidHeight } = this.__calculateSpacers();
let rows = [];
rows.push(<View key="sp-top" style={{height: spacerTopHeight}} />);
if (bufferFirstRow < firstRow && bufferFirstRow !== null) {
bufferLastRow = clamp(0, bufferLastRow, firstRow - 1);
this.__renderCells(rows, bufferFirstRow, bufferLastRow);
// It turns out that this isn't needed, we don't really care about what
// is rendered after in this case because it will be immediately replaced
// with the non-buffered window. Leaving this in can sometimes lead to
// white screen flashes on Android.
// rows.push(<View key="sp-mid" style={{height: spacerMidHeight}} />);
}
this.__renderCells(rows, firstRow, lastRow);
if (bufferFirstRow > lastRow && bufferFirstRow !== null) {
rows.push(<View key="sp-mid" style={{height: spacerMidHeight}} />);
this.__renderCells(rows, bufferFirstRow, bufferLastRow);
}
let totalRows = this.props.dataSource.getRowCount();
rows.push(<View key="sp-bot" style={{height: spacerBottomHeight || 0}} />);
return (
<ScrollView
scrollEventThrottle={50}
removeClippedSubviews={this.props.numToRenderAhead === 0 ? false : true}
automaticallyAdjustContentInsets={false}
{...this.props}
ref={(ref) => { this.scrollRef = ref; }}
onScroll={this.__onScroll}>
{rows}
</ScrollView>
);
}
getScrollResponder() {
return this.scrollRef &&
this.scrollRef.getScrollResponder &&
this.scrollRef.getScrollResponder();
}
scrollToSectionBuffered(sectionId) {
if (!this.isScrollingToSection && this.props.dataSource.hasSection(sectionId)) {
let { row, startY } = this.props.dataSource.getFirstRowOfSection(sectionId);
let { initialNumToRender, numToRenderBehind } = this.props;
let totalRows = this.props.dataSource.getRowCount();
let lastRow = totalRows - 1;
// We don't want to run computeRowsToRenderSync while scrolling
this.__clearEnqueuedComputation();
this.isScrollingToSection = true;
let windowFirstRow = row;
let windowLastRow = Math.min(lastRow, row + initialNumToRender);
// If we are at the bottom of the list, subtract any left over rows from the firstRow
if (windowLastRow - lastRow === 0) {
windowFirstRow = Math.max(0, windowLastRow - initialNumToRender);
}
// Set up the buffer
this.setState({
bufferFirstRow: windowFirstRow,
bufferLastRow: windowLastRow,
}, () => {
this.__maybeWait(() => {
this.setState({
firstRow: windowFirstRow,
lastRow: windowLastRow,
bufferFirstRow: null,
bufferLastRow: null,
}, () => {
if (this.nextSectionToScrollTo !== null) {
requestAnimationFrame(() => {
let nextSectionID = this.nextSectionToScrollTo;
this.nextSectionToScrollTo = null;
this.isScrollingToSection = false;
this.scrollToSectionBuffered(nextSectionID);
});
} else {
// On Android it seems like it is possible for the scroll
// position to be reported incorrectly sometimes, so we
// delay setting isScrollingToSection to false here to
// give it more time for the scroll position to catch up (?)
// which is important for calculating the firstVisible and
// lastVisible, ultimately determining rows to render.
// Leaving this out sometimes causes a blank screen briefly,
// with the firstRow exceeding lastRow.
setTimeout(() => {
this.isScrollingToSection = false;
this.__clearEnqueuedComputation();
this.__enqueueComputeRowsToRender();
}, 100);
}
});
});
});
// Scroll to the buffer area as soon as setState is complete
this.scrollRef.scrollTo({ y: startY, animated: false });
// this.scrollRef.scrollTo({x: 0, y: startY, animation: false});
} else {
this.nextSectionToScrollTo = sectionId; // Only keep the most recent value
}
}
scrollWithoutAnimationTo(destY, destX) {
this.scrollRef &&
this.scrollRef.scrollTo({ y: destY, x: destX, animated: false });
}
// Android requires us to wait a frame between setting the buffer, scrolling
// to it, and then setting the firstRow and lastRow to the buffer. If not,
// white flash. iOS doesnt't care.
__maybeWait(callback) {
if (Platform.OS === 'android') {
requestAnimationFrame(() => {
callback();
});
} else {
callback();
}
}
__renderCells(rows, firstRow, lastRow) {
for (var idx = firstRow; idx <= lastRow; idx++) {
let data = this.props.dataSource.getRowData(idx);
let id = idx.toString();
let parentSectionId = '';
// TODO: generalize this!
if (data && data.get && data.get('guid_token')) {
id = data.get('guid_token');
}
let key = id;
if (!(data && _.isObject(data) && data.sectionId)) {
parentSectionId = this.props.dataSource.getSectionId(idx)
key = `${key}-${id}`;
}
rows.push(
<CellRenderer
key={key}
shouldUpdate={data !== this.__rowCache[key]}
render={this.__renderRow.bind(this, data, parentSectionId, idx, key)}
/>
);
this.__rowCache[key] = data;
}
}
__renderRow(data, parentSectionId, idx, key) {
if (data && _.isObject(data) && data.sectionId) {
return this.props.renderSectionHeader(data, null, idx, key);
} else {
return this.props.renderCell(data, parentSectionId, idx, key);
}
}
__onScroll(e) {
this.prevScrollOffsetY = this.scrollOffsetY || 0;
this.scrollOffsetY = e.nativeEvent.contentOffset.y;
this.scrollDirection = this.__getScrollDirection();
this.height = e.nativeEvent.layoutMeasurement.height;
this.__enqueueComputeRowsToRender();
if (this.props.onEndReached) {
const windowHeight = Dimensions.get('window').height;
const { height } = e.nativeEvent.contentSize;
const offset = e.nativeEvent.contentOffset.y;
if( windowHeight + offset >= height ){
// ScrollEnd
this.props.onEndReached(e);
}
}
if (this.props.onScroll) {
this.props.onScroll(e);
}
}
__getScrollDirection() {
if (this.scrollOffsetY - this.prevScrollOffsetY >= 0) {
return 'down';
} else {
return 'up';
}
}
__clearEnqueuedComputation() {
clearTimeout(this.timeoutHandle);
this.willComputeRowsToRender = false;
}
__enqueueComputeRowsToRender() {
if (!this.willComputeRowsToRender) {
this.willComputeRowsToRender = true; // batch up computations
clearTimeout(this.timeoutHandle);
this.timeoutHandle = setTimeout(() => {
this.willComputeRowsToRender = false;
this.__computeRowsToRenderSync(this.props);
}, this.props.incrementDelay);
}
}
/**
* The result of this is an up-to-date state of firstRow and lastRow, given
* the viewport.
*/
__computeRowsToRenderSync(props, forceUpdate = false) {
if (this.props.bufferFirstRow === 0 || this.props.bufferFirstRow > 0 || this.isScrollingToSection) {
requestAnimationFrame(() => {
this.__computeRowsToRenderSync(this.props);
});
return;
}
let { dataSource } = this.props;
let totalRows = dataSource.getRowCount();
if (totalRows === 0) {
this.setState({ firstRow: 0, lastRow: -1 });
return;
}
if (this.props.numToRenderAhead === 0) {
return;
}
let { firstVisible, lastVisible } = dataSource.computeVisibleRows(
this.scrollOffsetY,
this.height,
);
if ((lastVisible >= totalRows - 1) && !forceUpdate) {
return;
}
let scrollDirection = this.props.isTouchingSectionPicker ? 'down' : this.scrollDirection;
let { firstRow, lastRow, targetFirstRow, targetLastRow } = dataSource.computeRowsToRender({
scrollDirection,
firstVisible,
lastVisible,
firstRendered: this.state.firstRow,
lastRendered: this.state.lastRow,
maxNumToRender: props.maxNumToRender,
pageSize: props.pageSize,
numToRenderAhead: props.numToRenderAhead,
numToRenderBehind: props.numToRenderBehind,
totalRows,
});
this.setState({firstRow, lastRow});
// Keep enqueuing updates until we reach the targetLastRow or
// targetFirstRow
if (lastRow !== targetLastRow || firstRow !== targetFirstRow) {
this.__enqueueComputeRowsToRender();
}
}
/**
* TODO: pull this out into data source, add tests
*/
__calculateSpacers() {
let { bufferFirstRow, bufferLastRow } = this.state;
let { firstRow, lastRow } = this.state;
let spacerTopHeight = this.props.dataSource.getHeightBeforeRow(firstRow);
let spacerBottomHeight = this.props.dataSource.getHeightAfterRow(lastRow);
let spacerMidHeight;
if (bufferFirstRow !== null && bufferFirstRow < firstRow) {
spacerMidHeight = this.props.dataSource.
getHeightBetweenRows(bufferLastRow, firstRow);
let bufferHeight = this.props.dataSource.
getHeightBetweenRows(bufferFirstRow - 1, bufferLastRow + 1);
spacerTopHeight -= (spacerMidHeight + bufferHeight);
} else if (bufferFirstRow !== null && bufferFirstRow > lastRow) {
spacerMidHeight = this.props.dataSource.
getHeightBetweenRows(lastRow, bufferFirstRow);
spacerBottomHeight -= spacerMidHeight;
}
return {
spacerTopHeight,
spacerBottomHeight,
spacerMidHeight,
}
}
}
FixedHeightWindowedListView.DataSource = FixedHeightWindowedListViewDataSource;
FixedHeightWindowedListView.propTypes = {
dataSource: PropTypes.object.isRequired,
renderCell: PropTypes.func.isRequired,
renderSectionHeader: PropTypes.func,
incrementDelay: PropTypes.number,
initialNumToRender: PropTypes.number,
maxNumToRender: PropTypes.number,
numToRenderAhead: PropTypes.number,
numToRenderBehind: PropTypes.number,
pageSize: PropTypes.number,
onEndReached: PropTypes.func,
onScroll: PropTypes.func,
};
FixedHeightWindowedListView.defaultProps = {
incrementDelay: 17,
initialNumToRender: 1,
maxNumToRender: 20,
numToRenderAhead: 4,
numToRenderBehind: 2,
pageSize: 5,
};
const DEBUG = false;
class CellRenderer extends React.Component {
shouldComponentUpdate(newProps) {
return newProps.shouldUpdate;
}
render() {
return this.props.render()
}
}
CellRenderer.propTypes = {
shouldUpdate: PropTypes.bool,
render: PropTypes.func,
};