forked from bvaughn/react-virtualized
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Masonry.js
475 lines (408 loc) · 13.1 KB
/
Masonry.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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
/** @flow */
import React, { PureComponent } from 'react'
import cn from 'classnames'
import PositionCache from './PositionCache'
const emptyObject = {}
/**
* Specifies the number of miliseconds during which to disable pointer events while a scroll is in progress.
* This improves performance and makes scrolling smoother.
*/
export const DEFAULT_SCROLLING_RESET_TIME_INTERVAL = 150
/**
* This component efficiently displays arbitrarily positioned cells using windowing techniques.
* Cell position is determined by an injected `cellPositioner` property.
* Windowing is vertical; this component does not support horizontal scrolling.
*
* Rendering occurs in two phases:
* 1) First pass uses estimated cell sizes (provided by the cache) to determine how many cells to measure in a batch.
* Batch size is chosen using a fast, naive layout algorithm that stacks images in order until the viewport has been filled.
* After measurement is complete (componentDidMount or componentDidUpdate) this component evaluates positioned cells
* in order to determine if another measurement pass is required (eg if actual cell sizes were less than estimated sizes).
* All measurements are permanently cached (keyed by `keyMapper`) for performance purposes.
* 2) Second pass uses the external `cellPositioner` to layout cells.
* At this time the positioner has access to cached size measurements for all cells.
* The positions it returns are cached by Masonry for fast access later.
* Phase one is repeated if the user scrolls beyond the current layout's bounds.
* If the layout is invalidated due to eg a resize, cached positions can be cleared using `recomputeCellPositions()`.
*
* Animation constraints:
* Simple animations are supported (eg translate/slide into place on initial reveal).
* More complex animations are not (eg flying from one position to another on resize).
*
* Layout constraints:
* This component supports multi-column layout.
* The height of each item may vary.
* The width of each item must not exceed the width of the column it is "in".
* The left position of all items within a column must align.
* (Items may not span multiple columns.)
*/
export default class Masonry extends PureComponent {
props: Props;
static defaultProps = {
autoHeight: false,
keyMapper: identity,
onCellsRendered: noop,
onScroll: noop,
overscanByPixels: 20,
role: 'grid',
scrollingResetTimeInterval: DEFAULT_SCROLLING_RESET_TIME_INTERVAL,
style: emptyObject,
tabIndex: 0
}
_invalidateOnUpdateStartIndex: ?number = null;
_invalidateOnUpdateStopIndex: ?number = null;
_positionCache: PositionCache = new PositionCache();
_startIndex: ?number = null;
_startIndexMemoized: ?number = null;
_stopIndex: ?number = null;
_stopIndexMemoized: ?number = null;
constructor (props, context) {
super(props, context)
this.state = {
isScrolling: false,
scrollTop: 0
}
this._debounceResetIsScrollingCallback = this._debounceResetIsScrollingCallback.bind(this)
this._setScrollingContainerRef = this._setScrollingContainerRef.bind(this)
this._onScroll = this._onScroll.bind(this)
}
clearCellPositions () {
this._positionCache = new PositionCache()
this.forceUpdate()
}
// HACK This method signature was intended for Grid
invalidateCellSizeAfterRender ({ rowIndex: index }) {
if (this._invalidateOnUpdateStartIndex === null) {
this._invalidateOnUpdateStartIndex = index
this._invalidateOnUpdateStopIndex = index
} else {
this._invalidateOnUpdateStartIndex = Math.min(this._invalidateOnUpdateStartIndex, index)
this._invalidateOnUpdateStopIndex = Math.max(this._invalidateOnUpdateStopIndex, index)
}
}
recomputeCellPositions () {
const stopIndex = this._positionCache.count - 1
this._positionCache = new PositionCache()
this._populatePositionCache(0, stopIndex)
this.forceUpdate()
}
componentDidMount () {
this._checkInvalidateOnUpdate()
this._invokeOnScrollCallback()
this._invokeOnCellsRenderedCallback()
}
componentDidUpdate (prevProps, prevState) {
this._checkInvalidateOnUpdate()
this._invokeOnScrollCallback()
this._invokeOnCellsRenderedCallback()
}
componentWillUnmount () {
if (this._debounceResetIsScrollingId) {
clearTimeout(this._debounceResetIsScrollingId)
}
}
componentWillReceiveProps (nextProps) {
const { scrollTop } = this.props
if (scrollTop !== nextProps.scrollTop) {
this._debounceResetIsScrolling()
this.setState({
isScrolling: true,
scrollTop: nextProps.scrollTop
})
}
}
render () {
const {
autoHeight,
cellCount,
cellMeasurerCache,
cellRenderer,
className,
height,
id,
keyMapper,
overscanByPixels,
role,
style,
tabIndex,
width
} = this.props
const {
isScrolling,
scrollTop
} = this.state
const children = []
const estimateTotalHeight = this._getEstimatedTotalHeight()
const shortestColumnSize = this._positionCache.shortestColumnSize
const measuredCellCount = this._positionCache.count
// We need to measure more cells before layout
if (
shortestColumnSize < scrollTop + height + overscanByPixels &&
measuredCellCount < cellCount
) {
const batchSize =
Math.min(
cellCount - measuredCellCount,
Math.ceil(
(scrollTop + height + overscanByPixels - shortestColumnSize) / cellMeasurerCache.defaultHeight *
width / cellMeasurerCache.defaultWidth
)
)
for (let index = measuredCellCount; index < measuredCellCount + batchSize; index++) {
children.push(
cellRenderer({
index: index,
isScrolling,
key: keyMapper(index),
parent: this,
style: {
width: cellMeasurerCache.getWidth(index)
}
})
)
}
} else {
let stopIndex
let startIndex
this._positionCache.range(
scrollTop - overscanByPixels,
height + overscanByPixels,
(index: number, left: number, top: number) => {
if (typeof startIndex === 'undefined') {
startIndex = index
stopIndex = index
} else {
startIndex = Math.min(startIndex, index)
stopIndex = Math.max(stopIndex, index)
}
children.push(
cellRenderer({
index,
isScrolling,
key: keyMapper(index),
parent: this,
style: {
height: cellMeasurerCache.getHeight(index),
left,
position: 'absolute',
top,
width: cellMeasurerCache.getWidth(index)
}
})
)
this._startIndex = startIndex
this._stopIndex = stopIndex
}
)
}
return (
<div
ref={this._setScrollingContainerRef}
aria-label={this.props['aria-label']}
className={cn('ReactVirtualized__Masonry', className)}
id={id}
onScroll={this._onScroll}
role={role}
style={{
boxSizing: 'border-box',
direction: 'ltr',
height: autoHeight ? 'auto' : height,
overflowX: 'hidden',
overflowY: estimateTotalHeight < height ? 'hidden' : 'auto',
position: 'relative',
width,
WebkitOverflowScrolling: 'touch',
willChange: 'transform',
...style
}}
tabIndex={tabIndex}
>
<div
className='ReactVirtualized__Masonry__innerScrollContainer'
style={{
width: '100%',
height: estimateTotalHeight,
maxWidth: '100%',
maxHeight: estimateTotalHeight,
overflow: 'hidden',
pointerEvents: isScrolling ? 'none' : '',
position: 'relative'
}}
>
{children}
</div>
</div>
)
}
_checkInvalidateOnUpdate () {
if (typeof this._invalidateOnUpdateStartIndex === 'number') {
const startIndex = this._invalidateOnUpdateStartIndex
const stopIndex = this._invalidateOnUpdateStopIndex
this._invalidateOnUpdateStartIndex = null
this._invalidateOnUpdateStopIndex = null
// Query external layout logic for position of newly-measured cells
this._populatePositionCache(startIndex, stopIndex)
this.forceUpdate()
}
}
_debounceResetIsScrolling () {
if (this._debounceResetIsScrollingId) {
window.cancelAnimationFrame(this._debounceResetIsScrollingId)
}
const delay = () => {
if (Date.now() - this._scrollDebounceStart >= this.props.scrollingResetTimeInterval) {
this._debounceResetIsScrollingCallback()
} else {
this._debounceResetIsScrollingId = window.requestAnimationFrame(delay)
}
}
this._scrollDebounceStart = Date.now()
this._debounceResetIsScrollingId = window.requestAnimationFrame(delay)
}
_debounceResetIsScrollingCallback () {
this.setState({
isScrolling: false
})
}
_getEstimatedTotalHeight () {
const {
cellCount,
cellMeasurerCache,
width
} = this.props
const estimatedColumnCount = Math.floor(width / cellMeasurerCache.defaultWidth)
return this._positionCache.estimateTotalHeight(
cellCount,
estimatedColumnCount,
cellMeasurerCache.defaultHeight
)
}
_invokeOnScrollCallback () {
const {
height,
onScroll
} = this.props
const { scrollTop } = this.state
if (this._onScrollMemoized !== scrollTop) {
onScroll({
clientHeight: height,
scrollHeight: this._getEstimatedTotalHeight(),
scrollTop
})
this._onScrollMemoized = scrollTop
}
}
_invokeOnCellsRenderedCallback () {
if (
this._startIndexMemoized !== this._startIndex ||
this._stopIndexMemoized !== this._stopIndex
) {
const { onCellsRendered } = this.props
onCellsRendered({
startIndex: this._startIndex,
stopIndex: this._stopIndex
})
this._startIndexMemoized = this._startIndex
this._stopIndexMemoized = this._stopIndex
}
}
_populatePositionCache (
startIndex: number,
stopIndex: number
) {
const {
cellMeasurerCache,
cellPositioner
} = this.props
for (let index = startIndex; index <= stopIndex; index++) {
const { left, top } = cellPositioner(index)
this._positionCache.setPosition(
index,
left,
top,
cellMeasurerCache.getHeight(index)
)
}
}
_setScrollingContainerRef (ref) {
this._scrollingContainer = ref
}
_onScroll (event) {
const { height } = this.props
const eventScrollTop = event.target.scrollTop
// When this component is shrunk drastically, React dispatches a series of back-to-back scroll events,
// Gradually converging on a scrollTop that is within the bounds of the new, smaller height.
// This causes a series of rapid renders that is slow for long lists.
// We can avoid that by doing some simple bounds checking to ensure that scroll offsets never exceed their bounds.
const scrollTop = Math.min(Math.max(0, this._getEstimatedTotalHeight() - height), eventScrollTop)
// On iOS, we can arrive at negative offsets by swiping past the start or end.
// Avoid re-rendering in this case as it can cause problems; see #532 for more.
if (eventScrollTop !== scrollTop) {
return
}
// Prevent pointer events from interrupting a smooth scroll
this._debounceResetIsScrolling()
// Certain devices (like Apple touchpad) rapid-fire duplicate events.
// Don't force a re-render if this is the case.
// The mouse may move faster then the animation frame does.
// Use requestAnimationFrame to avoid over-updating.
if (this.state.scrollTop !== scrollTop) {
this.setState({
isScrolling: true,
scrollTop
})
}
}
}
function identity (value) {
return value
}
function noop () {
}
type KeyMapper = (index: number) => mixed;
export type CellMeasurerCache = {
defaultHeight: number,
defaultWidth: number,
getHeight: (index: number) => number,
getWidth: (index: number) => number
};
type CellRenderer = (params: {|
index: number,
isScrolling: boolean,
key: mixed,
parent: mixed,
style: mixed
|}) => mixed;
type OnCellsRenderedCallback = (params: {|
startIndex: number,
stopIndex: number
|}) => void;
type OnScrollCallback = (params: {|
clientHeight: number,
scrollHeight: number,
scrollTop: number
|}) => void;
type Position = {
left: number,
top: number
};
export type Positioner = (index: number) => Position;
type Props = {
autoHeight: boolean,
cellCount: number,
cellMeasurerCache: CellMeasurerCache,
cellPositioner: Positioner,
cellRenderer: CellRenderer,
className: ?string,
height: number,
id: ?string,
keyMapper: KeyMapper,
onCellsRendered: ?OnCellsRenderedCallback,
onScroll: ?OnScrollCallback,
overscanByPixels: number,
role: string,
scrollingResetTimeInterval: number,
style: mixed,
tabIndex: number,
width: number
};