forked from bvaughn/react-virtualized
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollectionView.js
More file actions
597 lines (491 loc) · 21 KB
/
CollectionView.js
File metadata and controls
597 lines (491 loc) · 21 KB
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _createCallbackMemoizer = require('../utils/createCallbackMemoizer');
var _createCallbackMemoizer2 = _interopRequireDefault(_createCallbackMemoizer);
var _scrollbarSize = require('dom-helpers/util/scrollbarSize');
var _scrollbarSize2 = _interopRequireDefault(_scrollbarSize);
var _raf = require('raf');
var _raf2 = _interopRequireDefault(_raf);
var _reactAddonsShallowCompare = require('react-addons-shallow-compare');
var _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
// @TODO It would be nice to refactor Grid to use this code as well.
/**
* Specifies the number of miliseconds during which to disable pointer events while a scroll is in progress.
* This improves performance and makes scrolling smoother.
*/
var IS_SCROLLING_TIMEOUT = 150;
/**
* Controls whether the Grid updates the DOM element's scrollLeft/scrollTop based on the current state or just observes it.
* This prevents Grid from interrupting mouse-wheel animations (see issue #2).
*/
var SCROLL_POSITION_CHANGE_REASONS = {
OBSERVED: 'observed',
REQUESTED: 'requested'
};
/**
* Monitors changes in properties (eg. cellCount) and state (eg. scroll offsets) to determine when rendering needs to occur.
* This component does not render any visible content itself; it defers to the specified :cellLayoutManager.
*/
var CollectionView = function (_Component) {
_inherits(CollectionView, _Component);
function CollectionView(props, context) {
_classCallCheck(this, CollectionView);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(CollectionView).call(this, props, context));
_this.state = {
calculateSizeAndPositionDataOnNextUpdate: false,
isScrolling: false,
scrollLeft: 0,
scrollTop: 0
};
// Invokes callbacks only when their values have changed.
_this._onSectionRenderedMemoizer = (0, _createCallbackMemoizer2.default)();
_this._onScrollMemoizer = (0, _createCallbackMemoizer2.default)(false);
// Bind functions to instance so they don't lose context when passed around.
_this._invokeOnSectionRenderedHelper = _this._invokeOnSectionRenderedHelper.bind(_this);
_this._onScroll = _this._onScroll.bind(_this);
_this._updateScrollPositionForScrollToCell = _this._updateScrollPositionForScrollToCell.bind(_this);
return _this;
}
/**
* Forced recompute of cell sizes and positions.
* This function should be called if cell sizes have changed but nothing else has.
* Since cell positions are calculated by callbacks, the collection view has no way of detecting when the underlying data has changed.
*/
_createClass(CollectionView, [{
key: 'recomputeCellSizesAndPositions',
value: function recomputeCellSizesAndPositions() {
this.setState({
calculateSizeAndPositionDataOnNextUpdate: true
});
}
/* ---------------------------- Component lifecycle methods ---------------------------- */
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var _props = this.props;
var cellLayoutManager = _props.cellLayoutManager;
var scrollLeft = _props.scrollLeft;
var scrollToCell = _props.scrollToCell;
var scrollTop = _props.scrollTop;
this._scrollbarSize = (0, _scrollbarSize2.default)();
// Update onSectionRendered callback.
this._invokeOnSectionRenderedHelper();
var _cellLayoutManager$ge = cellLayoutManager.getTotalSize();
var totalHeight = _cellLayoutManager$ge.height;
var totalWidth = _cellLayoutManager$ge.width;
if (scrollToCell >= 0) {
this._updateScrollPositionForScrollToCell();
}
// Initialize onScroll callback.
this._invokeOnScrollMemoizer({
scrollLeft: scrollLeft || 0,
scrollTop: scrollTop || 0,
totalHeight: totalHeight,
totalWidth: totalWidth
});
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate(prevProps, prevState) {
var _props2 = this.props;
var height = _props2.height;
var scrollToCell = _props2.scrollToCell;
var width = _props2.width;
var _state = this.state;
var scrollLeft = _state.scrollLeft;
var scrollPositionChangeReason = _state.scrollPositionChangeReason;
var scrollTop = _state.scrollTop;
// Make sure requested changes to :scrollLeft or :scrollTop get applied.
// Assigning to scrollLeft/scrollTop tells the browser to interrupt any running scroll animations,
// And to discard any pending async changes to the scroll position that may have happened in the meantime (e.g. on a separate scrolling thread).
// So we only set these when we require an adjustment of the scroll position.
// See issue #2 for more information.
if (scrollPositionChangeReason === SCROLL_POSITION_CHANGE_REASONS.REQUESTED) {
if (scrollLeft >= 0 && scrollLeft !== prevState.scrollLeft && scrollLeft !== this.refs.scrollingContainer.scrollLeft) {
this.refs.scrollingContainer.scrollLeft = scrollLeft;
}
if (scrollTop >= 0 && scrollTop !== prevState.scrollTop && scrollTop !== this.refs.scrollingContainer.scrollTop) {
this.refs.scrollingContainer.scrollTop = scrollTop;
}
}
// Update scroll offsets if the current :scrollToCell values requires it
if (height !== prevProps.height || scrollToCell !== prevProps.scrollToCell || width !== prevProps.width) {
this._updateScrollPositionForScrollToCell();
}
// Update onRowsRendered callback if start/stop indices have changed
this._invokeOnSectionRenderedHelper();
}
}, {
key: 'componentWillMount',
value: function componentWillMount() {
var _props3 = this.props;
var cellLayoutManager = _props3.cellLayoutManager;
var scrollLeft = _props3.scrollLeft;
var scrollTop = _props3.scrollTop;
cellLayoutManager.calculateSizeAndPositionData();
if (scrollLeft >= 0 || scrollTop >= 0) {
this._setScrollPosition({ scrollLeft: scrollLeft, scrollTop: scrollTop });
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
if (this._disablePointerEventsTimeoutId) {
clearTimeout(this._disablePointerEventsTimeoutId);
}
if (this._setNextStateAnimationFrameId) {
_raf2.default.cancel(this._setNextStateAnimationFrameId);
}
}
/**
* @private
* This method updates scrollLeft/scrollTop in state for the following conditions:
* 1) Empty content (0 rows or columns)
* 2) New scroll props overriding the current state
* 3) Cells-count or cells-size has changed, making previous scroll offsets invalid
*/
}, {
key: 'componentWillUpdate',
value: function componentWillUpdate(nextProps, nextState) {
if (nextProps.cellCount === 0 && (nextState.scrollLeft !== 0 || nextState.scrollTop !== 0)) {
this._setScrollPosition({
scrollLeft: 0,
scrollTop: 0
});
} else if (nextProps.scrollLeft !== this.props.scrollLeft || nextProps.scrollTop !== this.props.scrollTop) {
this._setScrollPosition({
scrollLeft: nextProps.scrollLeft,
scrollTop: nextProps.scrollTop
});
}
if (nextProps.cellCount !== this.props.cellCount || nextProps.cellLayoutManager !== this.props.cellLayoutManager || nextState.calculateSizeAndPositionDataOnNextUpdate) {
nextProps.cellLayoutManager.calculateSizeAndPositionData();
}
if (nextState.calculateSizeAndPositionDataOnNextUpdate) {
this.setState({
calculateSizeAndPositionDataOnNextUpdate: false
});
}
}
}, {
key: 'render',
value: function render() {
var _props4 = this.props;
var cellLayoutManager = _props4.cellLayoutManager;
var className = _props4.className;
var height = _props4.height;
var noContentRenderer = _props4.noContentRenderer;
var width = _props4.width;
var _state2 = this.state;
var isScrolling = _state2.isScrolling;
var scrollLeft = _state2.scrollLeft;
var scrollTop = _state2.scrollTop;
var childrenToDisplay = height > 0 && width > 0 ? cellLayoutManager.renderCells({
height: height,
isScrolling: isScrolling,
width: width,
x: scrollLeft,
y: scrollTop
}) : [];
var _cellLayoutManager$ge2 = cellLayoutManager.getTotalSize();
var totalHeight = _cellLayoutManager$ge2.height;
var totalWidth = _cellLayoutManager$ge2.width;
var gridStyle = {
height: height,
width: width
};
// Force browser to hide scrollbars when we know they aren't necessary.
// Otherwise once scrollbars appear they may not disappear again.
// For more info see issue #116
if (totalHeight <= height) {
gridStyle.overflowY = 'hidden';
}
if (totalWidth <= width) {
gridStyle.overflowX = 'hidden';
}
return _react2.default.createElement(
'div',
{
ref: 'scrollingContainer',
'aria-label': this.props['aria-label'],
className: (0, _classnames2.default)('Collection', className),
onScroll: this._onScroll,
role: 'grid',
style: gridStyle,
tabIndex: 0
},
childrenToDisplay.length > 0 && _react2.default.createElement(
'div',
{
className: 'Collection__innerScrollContainer',
style: {
height: totalHeight,
maxHeight: totalHeight,
maxWidth: totalWidth,
pointerEvents: isScrolling ? 'none' : 'auto',
width: totalWidth
}
},
childrenToDisplay
),
childrenToDisplay.length === 0 && noContentRenderer()
);
}
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
return (0, _reactAddonsShallowCompare2.default)(this, nextProps, nextState);
}
/* ---------------------------- Helper methods ---------------------------- */
/**
* Sets an :isScrolling flag for a small window of time.
* This flag is used to disable pointer events on the scrollable portion of the Collection.
* This prevents jerky/stuttery mouse-wheel scrolling.
*/
}, {
key: '_enablePointerEventsAfterDelay',
value: function _enablePointerEventsAfterDelay() {
var _this2 = this;
if (this._disablePointerEventsTimeoutId) {
clearTimeout(this._disablePointerEventsTimeoutId);
}
this._disablePointerEventsTimeoutId = setTimeout(function () {
_this2._disablePointerEventsTimeoutId = null;
_this2.setState({
isScrolling: false
});
}, IS_SCROLLING_TIMEOUT);
}
}, {
key: '_invokeOnSectionRenderedHelper',
value: function _invokeOnSectionRenderedHelper() {
var _props5 = this.props;
var cellLayoutManager = _props5.cellLayoutManager;
var onSectionRendered = _props5.onSectionRendered;
this._onSectionRenderedMemoizer({
callback: onSectionRendered,
indices: cellLayoutManager.getLastRenderedIndices()
});
}
}, {
key: '_invokeOnScrollMemoizer',
value: function _invokeOnScrollMemoizer(_ref) {
var _this3 = this;
var scrollLeft = _ref.scrollLeft;
var scrollTop = _ref.scrollTop;
var totalHeight = _ref.totalHeight;
var totalWidth = _ref.totalWidth;
this._onScrollMemoizer({
callback: function callback(_ref2) {
var scrollLeft = _ref2.scrollLeft;
var scrollTop = _ref2.scrollTop;
var _props6 = _this3.props;
var height = _props6.height;
var onScroll = _props6.onScroll;
var width = _props6.width;
onScroll({
clientHeight: height,
clientWidth: width,
scrollHeight: totalHeight,
scrollLeft: scrollLeft,
scrollTop: scrollTop,
scrollWidth: totalWidth
});
},
indices: {
scrollLeft: scrollLeft,
scrollTop: scrollTop
}
});
}
/**
* Updates the state during the next animation frame.
* Use this method to avoid multiple renders in a small span of time.
* This helps performance for bursty events (like onScroll).
*/
}, {
key: '_setNextState',
value: function _setNextState(state) {
var _this4 = this;
if (this._setNextStateAnimationFrameId) {
_raf2.default.cancel(this._setNextStateAnimationFrameId);
}
this._setNextStateAnimationFrameId = (0, _raf2.default)(function () {
_this4._setNextStateAnimationFrameId = null;
_this4.setState(state);
});
}
}, {
key: '_setScrollPosition',
value: function _setScrollPosition(_ref3) {
var scrollLeft = _ref3.scrollLeft;
var scrollTop = _ref3.scrollTop;
var newState = {
scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.REQUESTED
};
if (scrollLeft >= 0) {
newState.scrollLeft = scrollLeft;
}
if (scrollTop >= 0) {
newState.scrollTop = scrollTop;
}
if (scrollLeft >= 0 && scrollLeft !== this.state.scrollLeft || scrollTop >= 0 && scrollTop !== this.state.scrollTop) {
this.setState(newState);
}
}
}, {
key: '_updateScrollPositionForScrollToCell',
value: function _updateScrollPositionForScrollToCell() {
var _props7 = this.props;
var cellLayoutManager = _props7.cellLayoutManager;
var height = _props7.height;
var scrollToCell = _props7.scrollToCell;
var width = _props7.width;
var _state3 = this.state;
var scrollLeft = _state3.scrollLeft;
var scrollTop = _state3.scrollTop;
if (scrollToCell >= 0) {
var scrollPosition = cellLayoutManager.getScrollPositionForCell({
cellIndex: scrollToCell,
height: height,
scrollLeft: scrollLeft,
scrollTop: scrollTop,
width: width
});
if (scrollPosition.scrollLeft !== scrollLeft || scrollPosition.scrollTop !== scrollTop) {
this._setScrollPosition(scrollPosition);
}
}
}
}, {
key: '_onScroll',
value: function _onScroll(event) {
// In certain edge-cases React dispatches an onScroll event with an invalid target.scrollLeft / target.scrollTop.
// This invalid event can be detected by comparing event.target to this component's scrollable DOM element.
// See issue #404 for more information.
if (event.target !== this.refs.scrollingContainer) {
return;
}
// Prevent pointer events from interrupting a smooth scroll
this._enablePointerEventsAfterDelay();
// 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 scrollTop never exceeds the total height.
var _props8 = this.props;
var cellLayoutManager = _props8.cellLayoutManager;
var height = _props8.height;
var width = _props8.width;
var scrollbarSize = this._scrollbarSize;
var _cellLayoutManager$ge3 = cellLayoutManager.getTotalSize();
var totalHeight = _cellLayoutManager$ge3.height;
var totalWidth = _cellLayoutManager$ge3.width;
var scrollLeft = Math.min(totalWidth - width + scrollbarSize, event.target.scrollLeft);
var scrollTop = Math.min(totalHeight - height + scrollbarSize, event.target.scrollTop);
// 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.scrollLeft !== scrollLeft || this.state.scrollTop !== scrollTop) {
// Browsers with cancelable scroll events (eg. Firefox) interrupt scrolling animations if scrollTop/scrollLeft is set.
// Other browsers (eg. Safari) don't scroll as well without the help under certain conditions (DOM or style changes during scrolling).
// All things considered, this seems to be the best current work around that I'm aware of.
// For more information see https://github.com/bvaughn/react-virtualized/pull/124
var scrollPositionChangeReason = event.cancelable ? SCROLL_POSITION_CHANGE_REASONS.OBSERVED : SCROLL_POSITION_CHANGE_REASONS.REQUESTED;
// Synchronously set :isScrolling the first time (since _setNextState will reschedule its animation frame each time it's called)
if (!this.state.isScrolling) {
this.setState({
isScrolling: true
});
}
this._setNextState({
isScrolling: true,
scrollLeft: scrollLeft,
scrollPositionChangeReason: scrollPositionChangeReason,
scrollTop: scrollTop
});
}
this._invokeOnScrollMemoizer({
scrollLeft: scrollLeft,
scrollTop: scrollTop,
totalWidth: totalWidth,
totalHeight: totalHeight
});
}
}]);
return CollectionView;
}(_react.Component);
CollectionView.propTypes = {
'aria-label': _react.PropTypes.string,
/**
* Number of cells in collection.
*/
cellCount: _react.PropTypes.number.isRequired,
/**
* Calculates cell sizes and positions and manages rendering the appropriate cells given a specified window.
*/
cellLayoutManager: _react.PropTypes.object.isRequired,
/**
* Optional custom CSS class name to attach to root Collection element.
*/
className: _react.PropTypes.string,
/**
* Height of Collection; this property determines the number of visible (vs virtualized) rows.
*/
height: _react.PropTypes.number.isRequired,
/**
* Optional renderer to be used in place of rows when either :rowsCount or :cellCount is 0.
*/
noContentRenderer: _react.PropTypes.func.isRequired,
/**
* Callback invoked whenever the scroll offset changes within the inner scrollable region.
* This callback can be used to sync scrolling between lists, tables, or grids.
* ({ clientHeight, clientWidth, scrollHeight, scrollLeft, scrollTop, scrollWidth }): void
*/
onScroll: _react.PropTypes.func.isRequired,
/**
* Callback invoked with information about the section of the Collection that was just rendered.
* This callback is passed an array of the most recently rendered section indices.
*/
onSectionRendered: _react.PropTypes.func.isRequired,
/**
* Horizontal offset.
*/
scrollLeft: _react.PropTypes.number,
/**
* Cell index to ensure visible (by forcefully scrolling if necessary).
*/
scrollToCell: _react.PropTypes.number,
/**
* Vertical offset.
*/
scrollTop: _react.PropTypes.number,
/**
* Width of Collection; this property determines the number of visible (vs virtualized) columns.
*/
width: _react.PropTypes.number.isRequired
};
CollectionView.defaultProps = {
'aria-label': 'grid',
noContentRenderer: function noContentRenderer() {
return null;
},
onScroll: function onScroll() {
return null;
},
onSectionRendered: function onSectionRendered() {
return null;
}
};
exports.default = CollectionView;