-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Grid.js
943 lines (816 loc) · 32.5 KB
/
Grid.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
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
/** @flow */
import React, { Component, PropTypes } from 'react'
import cn from 'classnames'
import calculateSizeAndPositionDataAndUpdateScrollOffset from './utils/calculateSizeAndPositionDataAndUpdateScrollOffset'
import ScalingCellSizeAndPositionManager from './utils/ScalingCellSizeAndPositionManager'
import createCallbackMemoizer from '../utils/createCallbackMemoizer'
import getOverscanIndices, { SCROLL_DIRECTION_BACKWARD, SCROLL_DIRECTION_FORWARD } from './utils/getOverscanIndices'
import getScrollbarSize from 'dom-helpers/util/scrollbarSize'
import shallowCompare from 'react-addons-shallow-compare'
import updateScrollIndexHelper from './utils/updateScrollIndexHelper'
import defaultCellRangeRenderer from './defaultCellRangeRenderer'
/**
* 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
/**
* 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).
*/
const SCROLL_POSITION_CHANGE_REASONS = {
OBSERVED: 'observed',
REQUESTED: 'requested'
}
/**
* Renders tabular data with virtualization along the vertical and horizontal axes.
* Row heights and column widths must be known ahead of time and specified as properties.
*/
export default class Grid extends Component {
static propTypes = {
'aria-label': PropTypes.string,
/**
* Set the width of the inner scrollable container to 'auto'.
* This is useful for single-column Grids to ensure that the column doesn't extend below a vertical scrollbar.
*/
autoContainerWidth: PropTypes.bool,
/**
* Removes fixed height from the scrollingContainer so that the total height
* of rows can stretch the window. Intended for use with WindowScroller
*/
autoHeight: PropTypes.bool,
/**
* Responsible for rendering a cell given an row and column index.
* Should implement the following interface: ({ columnIndex: number, rowIndex: number }): PropTypes.node
*/
cellRenderer: PropTypes.func.isRequired,
/**
* Responsible for rendering a group of cells given their index ranges.
* Should implement the following interface: ({
* cellCache: Map,
* cellRenderer: Function,
* columnSizeAndPositionManager: CellSizeAndPositionManager,
* columnStartIndex: number,
* columnStopIndex: number,
* isScrolling: boolean,
* rowSizeAndPositionManager: CellSizeAndPositionManager,
* rowStartIndex: number,
* rowStopIndex: number,
* scrollLeft: number,
* scrollTop: number
* }): Array<PropTypes.node>
*/
cellRangeRenderer: PropTypes.func.isRequired,
/**
* Optional custom CSS class name to attach to root Grid element.
*/
className: PropTypes.string,
/**
* Number of columns in grid.
*/
columnCount: PropTypes.number.isRequired,
/**
* Either a fixed column width (number) or a function that returns the width of a column given its index.
* Should implement the following interface: (index: number): number
*/
columnWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.func]).isRequired,
/** Optional inline style applied to inner cell-container */
containerStyle: PropTypes.object,
/**
* Used to estimate the total width of a Grid before all of its columns have actually been measured.
* The estimated total width is adjusted as columns are rendered.
*/
estimatedColumnSize: PropTypes.number.isRequired,
/**
* Used to estimate the total height of a Grid before all of its rows have actually been measured.
* The estimated total height is adjusted as rows are rendered.
*/
estimatedRowSize: PropTypes.number.isRequired,
/**
* Height of Grid; this property determines the number of visible (vs virtualized) rows.
*/
height: PropTypes.number.isRequired,
/**
* Optional custom id to attach to root Grid element.
*/
id: PropTypes.string,
/**
* Optional renderer to be used in place of rows when either :rowCount or :columnCount is 0.
*/
noContentRenderer: 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: PropTypes.func.isRequired,
/**
* Callback invoked with information about the section of the Grid that was just rendered.
* ({ columnStartIndex, columnStopIndex, rowStartIndex, rowStopIndex }): void
*/
onSectionRendered: PropTypes.func.isRequired,
/**
* Number of columns to render before/after the visible section of the grid.
* These columns can help for smoother scrolling on touch devices or browsers that send scroll events infrequently.
*/
overscanColumnCount: PropTypes.number.isRequired,
/**
* Number of rows to render above/below the visible section of the grid.
* These rows can help for smoother scrolling on touch devices or browsers that send scroll events infrequently.
*/
overscanRowCount: PropTypes.number.isRequired,
/**
* Either a fixed row height (number) or a function that returns the height of a row given its index.
* Should implement the following interface: ({ index: number }): number
*/
rowHeight: PropTypes.oneOfType([PropTypes.number, PropTypes.func]).isRequired,
/**
* Number of rows in grid.
*/
rowCount: PropTypes.number.isRequired,
/** Wait this amount of time after the last scroll event before resetting Grid `pointer-events`. */
scrollingResetTimeInterval: PropTypes.number,
/** Horizontal offset. */
scrollLeft: PropTypes.number,
/**
* Controls scroll-to-cell behavior of the Grid.
* The default ("auto") scrolls the least amount possible to ensure that the specified cell is fully visible.
* Use "start" to align cells to the top/left of the Grid and "end" to align bottom/right.
*/
scrollToAlignment: PropTypes.oneOf(['auto', 'end', 'start', 'center']).isRequired,
/**
* Column index to ensure visible (by forcefully scrolling if necessary)
*/
scrollToColumn: PropTypes.number,
/** Vertical offset. */
scrollTop: PropTypes.number,
/**
* Row index to ensure visible (by forcefully scrolling if necessary)
*/
scrollToRow: PropTypes.number,
/** Optional inline style */
style: PropTypes.object,
/** Tab index for focus */
tabIndex: PropTypes.number,
/**
* Width of Grid; this property determines the number of visible (vs virtualized) columns.
*/
width: PropTypes.number.isRequired
};
static defaultProps = {
'aria-label': 'grid',
cellRangeRenderer: defaultCellRangeRenderer,
estimatedColumnSize: 100,
estimatedRowSize: 30,
noContentRenderer: () => null,
onScroll: () => null,
onSectionRendered: () => null,
overscanColumnCount: 0,
overscanRowCount: 10,
scrollingResetTimeInterval: DEFAULT_SCROLLING_RESET_TIME_INTERVAL,
scrollToAlignment: 'auto',
style: {},
tabIndex: 0
};
constructor (props, context) {
super(props, context)
this.state = {
isScrolling: false,
scrollDirectionHorizontal: SCROLL_DIRECTION_FORWARD,
scrollDirectionVertical: SCROLL_DIRECTION_FORWARD,
scrollLeft: 0,
scrollTop: 0
}
// Invokes onSectionRendered callback only when start/stop row or column indices change
this._onGridRenderedMemoizer = createCallbackMemoizer()
this._onScrollMemoizer = createCallbackMemoizer(false)
// Bind functions to instance so they don't lose context when passed around
this._debounceScrollEndedCallback = this._debounceScrollEndedCallback.bind(this)
this._invokeOnGridRenderedHelper = this._invokeOnGridRenderedHelper.bind(this)
this._onScroll = this._onScroll.bind(this)
this._updateScrollLeftForScrollToColumn = this._updateScrollLeftForScrollToColumn.bind(this)
this._updateScrollTopForScrollToRow = this._updateScrollTopForScrollToRow.bind(this)
this._columnWidthGetter = this._wrapSizeGetter(props.columnWidth)
this._rowHeightGetter = this._wrapSizeGetter(props.rowHeight)
this._columnSizeAndPositionManager = new ScalingCellSizeAndPositionManager({
cellCount: props.columnCount,
cellSizeGetter: (params) => this._columnWidthGetter(params),
estimatedCellSize: this._getEstimatedColumnSize(props)
})
this._rowSizeAndPositionManager = new ScalingCellSizeAndPositionManager({
cellCount: props.rowCount,
cellSizeGetter: (params) => this._rowHeightGetter(params),
estimatedCellSize: this._getEstimatedRowSize(props)
})
// See defaultCellRangeRenderer() for more information on the usage of these caches
this._cellCache = {}
this._styleCache = {}
}
/**
* Pre-measure all columns and rows in a Grid.
* Typically cells are only measured as needed and estimated sizes are used for cells that have not yet been measured.
* This method ensures that the next call to getTotalSize() returns an exact size (as opposed to just an estimated one).
*/
measureAllCells () {
const { columnCount, rowCount } = this.props
this._columnSizeAndPositionManager.getSizeAndPositionOfCell(columnCount - 1)
this._rowSizeAndPositionManager.getSizeAndPositionOfCell(rowCount - 1)
}
/**
* Forced recompute of row heights and column widths.
* This function should be called if dynamic column or row sizes have changed but nothing else has.
* Since Grid only receives :columnCount and :rowCount it has no way of detecting when the underlying data changes.
*/
recomputeGridSize ({
columnIndex = 0,
rowIndex = 0
} = {}) {
this._columnSizeAndPositionManager.resetCell(columnIndex)
this._rowSizeAndPositionManager.resetCell(rowIndex)
// Clear cell cache in case we are scrolling;
// Invalid row heights likely mean invalid cached content as well.
this._cellCache = {}
this._styleCache = {}
this.forceUpdate()
}
/**
* Ensure column and row are visible.
*/
scrollToCell ({
columnIndex,
rowIndex
}) {
const props = this.props
this._updateScrollLeftForScrollToColumn({
...props,
scrollToColumn: columnIndex
})
this._updateScrollTopForScrollToRow({
...props,
scrollToRow: rowIndex
})
}
componentDidMount () {
const { scrollLeft, scrollToColumn, scrollTop, scrollToRow } = this.props
// If this component was first rendered server-side, scrollbar size will be undefined.
// In that event we need to remeasure.
if (!this._scrollbarSizeMeasured) {
this._scrollbarSize = getScrollbarSize()
this._scrollbarSizeMeasured = true
this.setState({})
}
if (scrollLeft >= 0 || scrollTop >= 0) {
this._setScrollPosition({ scrollLeft, scrollTop })
}
if (scrollToColumn >= 0 || scrollToRow >= 0) {
this._updateScrollLeftForScrollToColumn()
this._updateScrollTopForScrollToRow()
}
// Update onRowsRendered callback
this._invokeOnGridRenderedHelper()
// Initialize onScroll callback
this._invokeOnScrollMemoizer({
scrollLeft: scrollLeft || 0,
scrollTop: scrollTop || 0,
totalColumnsWidth: this._columnSizeAndPositionManager.getTotalSize(),
totalRowsHeight: this._rowSizeAndPositionManager.getTotalSize()
})
}
/**
* @private
* This method updates scrollLeft/scrollTop in state for the following conditions:
* 1) New scroll-to-cell props have been set
*/
componentDidUpdate (prevProps, prevState) {
const { autoHeight, columnCount, height, rowCount, scrollToAlignment, scrollToColumn, scrollToRow, width } = this.props
const { scrollLeft, scrollPositionChangeReason, scrollTop } = this.state
// Handle edge case where column or row count has only just increased over 0.
// In this case we may have to restore a previously-specified scroll offset.
// For more info see bvaughn/react-virtualized/issues/218
const columnOrRowCountJustIncreasedFromZero = (
columnCount > 0 &&
prevProps.columnCount === 0 ||
rowCount > 0 &&
prevProps.rowCount === 0
)
// 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._scrollingContainer.scrollLeft ||
columnOrRowCountJustIncreasedFromZero
)
) {
this._scrollingContainer.scrollLeft = scrollLeft
}
// @TRICKY :autoHeight property instructs Grid to leave :scrollTop management to an external HOC (eg WindowScroller).
// In this case we should avoid checking scrollingContainer.scrollTop since it forces layout/flow.
if (
!autoHeight &&
scrollTop >= 0 &&
(
scrollTop !== prevState.scrollTop &&
scrollTop !== this._scrollingContainer.scrollTop ||
columnOrRowCountJustIncreasedFromZero
)
) {
this._scrollingContainer.scrollTop = scrollTop
}
}
// Update scroll offsets if the current :scrollToColumn or :scrollToRow values requires it
// @TODO Do we also need this check or can the one in componentWillUpdate() suffice?
updateScrollIndexHelper({
cellSizeAndPositionManager: this._columnSizeAndPositionManager,
previousCellsCount: prevProps.columnCount,
previousCellSize: prevProps.columnWidth,
previousScrollToAlignment: prevProps.scrollToAlignment,
previousScrollToIndex: prevProps.scrollToColumn,
previousSize: prevProps.width,
scrollOffset: scrollLeft,
scrollToAlignment,
scrollToIndex: scrollToColumn,
size: width,
updateScrollIndexCallback: (scrollToColumn) => this._updateScrollLeftForScrollToColumn({ ...this.props, scrollToColumn })
})
updateScrollIndexHelper({
cellSizeAndPositionManager: this._rowSizeAndPositionManager,
previousCellsCount: prevProps.rowCount,
previousCellSize: prevProps.rowHeight,
previousScrollToAlignment: prevProps.scrollToAlignment,
previousScrollToIndex: prevProps.scrollToRow,
previousSize: prevProps.height,
scrollOffset: scrollTop,
scrollToAlignment,
scrollToIndex: scrollToRow,
size: height,
updateScrollIndexCallback: (scrollToRow) => this._updateScrollTopForScrollToRow({ ...this.props, scrollToRow })
})
// Update onRowsRendered callback if start/stop indices have changed
this._invokeOnGridRenderedHelper()
// Changes to :scrollLeft or :scrollTop should also notify :onScroll listeners
if (
scrollLeft !== prevState.scrollLeft ||
scrollTop !== prevState.scrollTop
) {
const totalRowsHeight = this._rowSizeAndPositionManager.getTotalSize()
const totalColumnsWidth = this._columnSizeAndPositionManager.getTotalSize()
this._invokeOnScrollMemoizer({ scrollLeft, scrollTop, totalColumnsWidth, totalRowsHeight })
}
}
componentWillMount () {
// If this component is being rendered server-side, getScrollbarSize() will return undefined.
// We handle this case in componentDidMount()
this._scrollbarSize = getScrollbarSize()
if (this._scrollbarSize === undefined) {
this._scrollbarSizeMeasured = false
this._scrollbarSize = 0
} else {
this._scrollbarSizeMeasured = true
}
this._calculateChildrenToRender()
}
componentWillUnmount () {
if (this._disablePointerEventsTimeoutId) {
clearTimeout(this._disablePointerEventsTimeoutId)
}
}
/**
* @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
*/
componentWillUpdate (nextProps, nextState) {
if (
nextProps.columnCount === 0 &&
nextState.scrollLeft !== 0 ||
nextProps.rowCount === 0 &&
nextState.scrollTop !== 0
) {
this._setScrollPosition({
scrollLeft: 0,
scrollTop: 0
})
} else if (
nextProps.scrollLeft !== this.props.scrollLeft ||
nextProps.scrollTop !== this.props.scrollTop
) {
const newState = {}
if (nextProps.scrollLeft != null) {
newState.scrollLeft = nextProps.scrollLeft
}
if (nextProps.scrollTop != null) {
newState.scrollTop = nextProps.scrollTop
}
this._setScrollPosition(newState)
}
if (
nextProps.columnWidth !== this.props.columnWidth ||
nextProps.rowHeight !== this.props.rowHeight
) {
this._styleCache = {}
}
this._columnWidthGetter = this._wrapSizeGetter(nextProps.columnWidth)
this._rowHeightGetter = this._wrapSizeGetter(nextProps.rowHeight)
this._columnSizeAndPositionManager.configure({
cellCount: nextProps.columnCount,
estimatedCellSize: this._getEstimatedColumnSize(nextProps)
})
this._rowSizeAndPositionManager.configure({
cellCount: nextProps.rowCount,
estimatedCellSize: this._getEstimatedRowSize(nextProps)
})
// Update scroll offsets if the size or number of cells have changed, invalidating the previous value
calculateSizeAndPositionDataAndUpdateScrollOffset({
cellCount: this.props.columnCount,
cellSize: this.props.columnWidth,
computeMetadataCallback: () => this._columnSizeAndPositionManager.resetCell(0),
computeMetadataCallbackProps: nextProps,
nextCellsCount: nextProps.columnCount,
nextCellSize: nextProps.columnWidth,
nextScrollToIndex: nextProps.scrollToColumn,
scrollToIndex: this.props.scrollToColumn,
updateScrollOffsetForScrollToIndex: () => this._updateScrollLeftForScrollToColumn(nextProps, nextState)
})
calculateSizeAndPositionDataAndUpdateScrollOffset({
cellCount: this.props.rowCount,
cellSize: this.props.rowHeight,
computeMetadataCallback: () => this._rowSizeAndPositionManager.resetCell(0),
computeMetadataCallbackProps: nextProps,
nextCellsCount: nextProps.rowCount,
nextCellSize: nextProps.rowHeight,
nextScrollToIndex: nextProps.scrollToRow,
scrollToIndex: this.props.scrollToRow,
updateScrollOffsetForScrollToIndex: () => this._updateScrollTopForScrollToRow(nextProps, nextState)
})
this._calculateChildrenToRender(nextProps, nextState)
}
render () {
const {
autoContainerWidth,
autoHeight,
className,
containerStyle,
height,
id,
noContentRenderer,
style,
tabIndex,
width
} = this.props
const { isScrolling } = this.state
const gridStyle = {
boxSizing: 'border-box',
direction: 'ltr',
height: autoHeight ? 'auto' : height,
position: 'relative',
width,
WebkitOverflowScrolling: 'touch',
willChange: 'transform'
}
const totalColumnsWidth = this._columnSizeAndPositionManager.getTotalSize()
const totalRowsHeight = this._rowSizeAndPositionManager.getTotalSize()
// 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
const verticalScrollBarSize = totalRowsHeight > height ? this._scrollbarSize : 0
const horizontalScrollBarSize = totalColumnsWidth > width ? this._scrollbarSize : 0
// Also explicitly init styles to 'auto' if scrollbars are required.
// This works around an obscure edge case where external CSS styles have not yet been loaded,
// But an initial scroll index of offset is set as an external prop.
// Without this style, Grid would render the correct range of cells but would NOT update its internal offset.
// This was originally reported via clauderic/react-infinite-calendar/issues/23
gridStyle.overflowX = totalColumnsWidth + verticalScrollBarSize <= width
? 'hidden'
: 'auto'
gridStyle.overflowY = totalRowsHeight + horizontalScrollBarSize <= height
? 'hidden'
: 'auto'
const childrenToDisplay = this._childrenToDisplay
const showNoContentRenderer = (
childrenToDisplay.length === 0 &&
height > 0 &&
width > 0
)
return (
<div
ref={(ref) => {
this._scrollingContainer = ref
}}
aria-label={this.props['aria-label']}
className={cn('ReactVirtualized__Grid', className)}
id={id}
onScroll={this._onScroll}
role='grid'
style={{
...gridStyle,
...style
}}
tabIndex={tabIndex}
>
{childrenToDisplay.length > 0 &&
<div
className='ReactVirtualized__Grid__innerScrollContainer'
style={{
width: autoContainerWidth ? 'auto' : totalColumnsWidth,
height: totalRowsHeight,
maxWidth: totalColumnsWidth,
maxHeight: totalRowsHeight,
overflow: 'hidden',
pointerEvents: isScrolling ? 'none' : '',
...containerStyle
}}
>
{childrenToDisplay}
</div>
}
{showNoContentRenderer &&
noContentRenderer()
}
</div>
)
}
shouldComponentUpdate (nextProps, nextState) {
return shallowCompare(this, nextProps, nextState)
}
/* ---------------------------- Helper methods ---------------------------- */
_calculateChildrenToRender (props = this.props, state = this.state) {
const {
cellRenderer,
cellRangeRenderer,
columnCount,
height,
overscanColumnCount,
overscanRowCount,
rowCount,
width
} = props
const {
isScrolling,
scrollDirectionHorizontal,
scrollDirectionVertical,
scrollLeft,
scrollTop
} = state
this._childrenToDisplay = []
// Render only enough columns and rows to cover the visible area of the grid.
if (height > 0 && width > 0) {
const visibleColumnIndices = this._columnSizeAndPositionManager.getVisibleCellRange({
containerSize: width,
offset: scrollLeft
})
const visibleRowIndices = this._rowSizeAndPositionManager.getVisibleCellRange({
containerSize: height,
offset: scrollTop
})
const horizontalOffsetAdjustment = this._columnSizeAndPositionManager.getOffsetAdjustment({
containerSize: width,
offset: scrollLeft
})
const verticalOffsetAdjustment = this._rowSizeAndPositionManager.getOffsetAdjustment({
containerSize: height,
offset: scrollTop
})
// Store for _invokeOnGridRenderedHelper()
this._renderedColumnStartIndex = visibleColumnIndices.start
this._renderedColumnStopIndex = visibleColumnIndices.stop
this._renderedRowStartIndex = visibleRowIndices.start
this._renderedRowStopIndex = visibleRowIndices.stop
const overscanColumnIndices = getOverscanIndices({
cellCount: columnCount,
overscanCellsCount: overscanColumnCount,
scrollDirection: scrollDirectionHorizontal,
startIndex: this._renderedColumnStartIndex,
stopIndex: this._renderedColumnStopIndex
})
const overscanRowIndices = getOverscanIndices({
cellCount: rowCount,
overscanCellsCount: overscanRowCount,
scrollDirection: scrollDirectionVertical,
startIndex: this._renderedRowStartIndex,
stopIndex: this._renderedRowStopIndex
})
// Store for _invokeOnGridRenderedHelper()
this._columnStartIndex = overscanColumnIndices.overscanStartIndex
this._columnStopIndex = overscanColumnIndices.overscanStopIndex
this._rowStartIndex = overscanRowIndices.overscanStartIndex
this._rowStopIndex = overscanRowIndices.overscanStopIndex
this._childrenToDisplay = cellRangeRenderer({
cellCache: this._cellCache,
cellRenderer,
columnSizeAndPositionManager: this._columnSizeAndPositionManager,
columnStartIndex: this._columnStartIndex,
columnStopIndex: this._columnStopIndex,
horizontalOffsetAdjustment,
isScrolling,
rowSizeAndPositionManager: this._rowSizeAndPositionManager,
rowStartIndex: this._rowStartIndex,
rowStopIndex: this._rowStopIndex,
scrollLeft,
scrollTop,
styleCache: this._styleCache,
verticalOffsetAdjustment,
visibleColumnIndices,
visibleRowIndices
})
}
}
/**
* Sets an :isScrolling flag for a small window of time.
* This flag is used to disable pointer events on the scrollable portion of the Grid.
* This prevents jerky/stuttery mouse-wheel scrolling.
*/
_debounceScrollEnded () {
const { scrollingResetTimeInterval } = this.props
if (this._disablePointerEventsTimeoutId) {
clearTimeout(this._disablePointerEventsTimeoutId)
}
this._disablePointerEventsTimeoutId = setTimeout(
this._debounceScrollEndedCallback,
scrollingResetTimeInterval
)
}
_debounceScrollEndedCallback () {
this._disablePointerEventsTimeoutId = null
const styleCache = this._styleCache
// Reset cell and style caches once scrolling stops.
// This makes Grid simpler to use (since cells commonly change).
// And it keeps the caches from growing too large.
// Performance is most sensitive when a user is scrolling.
this._cellCache = {}
this._styleCache = {}
// Copy over the visible cell styles so avoid unnecessary re-render.
for (let rowIndex = this._rowStartIndex; rowIndex <= this._rowStopIndex; rowIndex++) {
for (let columnIndex = this._columnStartIndex; columnIndex <= this._columnStopIndex; columnIndex++) {
let key = `${rowIndex}-${columnIndex}`
this._styleCache[key] = styleCache[key]
}
}
this.setState({
isScrolling: false
})
}
_getEstimatedColumnSize (props) {
return typeof props.columnWidth === 'number'
? props.columnWidth
: props.estimatedColumnSize
}
_getEstimatedRowSize (props) {
return typeof props.rowHeight === 'number'
? props.rowHeight
: props.estimatedRowSize
}
_invokeOnGridRenderedHelper () {
const { onSectionRendered } = this.props
this._onGridRenderedMemoizer({
callback: onSectionRendered,
indices: {
columnOverscanStartIndex: this._columnStartIndex,
columnOverscanStopIndex: this._columnStopIndex,
columnStartIndex: this._renderedColumnStartIndex,
columnStopIndex: this._renderedColumnStopIndex,
rowOverscanStartIndex: this._rowStartIndex,
rowOverscanStopIndex: this._rowStopIndex,
rowStartIndex: this._renderedRowStartIndex,
rowStopIndex: this._renderedRowStopIndex
}
})
}
_invokeOnScrollMemoizer ({ scrollLeft, scrollTop, totalColumnsWidth, totalRowsHeight }) {
this._onScrollMemoizer({
callback: ({ scrollLeft, scrollTop }) => {
const { height, onScroll, width } = this.props
onScroll({
clientHeight: height,
clientWidth: width,
scrollHeight: totalRowsHeight,
scrollLeft,
scrollTop,
scrollWidth: totalColumnsWidth
})
},
indices: {
scrollLeft,
scrollTop
}
})
}
_setScrollPosition ({ scrollLeft, scrollTop }) {
const newState = {
scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.REQUESTED
}
if (scrollLeft >= 0) {
newState.scrollDirectionHorizontal = scrollLeft > this.state.scrollLeft
? SCROLL_DIRECTION_FORWARD
: SCROLL_DIRECTION_BACKWARD
newState.scrollLeft = scrollLeft
}
if (scrollTop >= 0) {
newState.scrollDirectionVertical = scrollTop > this.state.scrollTop
? SCROLL_DIRECTION_FORWARD
: SCROLL_DIRECTION_BACKWARD
newState.scrollTop = scrollTop
}
if (
scrollLeft >= 0 && scrollLeft !== this.state.scrollLeft ||
scrollTop >= 0 && scrollTop !== this.state.scrollTop
) {
this.setState(newState)
}
}
_wrapPropertyGetter (value) {
return value instanceof Function
? value
: () => value
}
_wrapSizeGetter (size) {
return this._wrapPropertyGetter(size)
}
_updateScrollLeftForScrollToColumn (props = this.props, state = this.state) {
const { columnCount, scrollToAlignment, scrollToColumn, width } = props
const { scrollLeft } = state
if (scrollToColumn >= 0 && columnCount > 0) {
const targetIndex = Math.max(0, Math.min(columnCount - 1, scrollToColumn))
const calculatedScrollLeft = this._columnSizeAndPositionManager.getUpdatedOffsetForIndex({
align: scrollToAlignment,
containerSize: width,
currentOffset: scrollLeft,
targetIndex
})
if (scrollLeft !== calculatedScrollLeft) {
this._setScrollPosition({
scrollLeft: calculatedScrollLeft
})
}
}
}
_updateScrollTopForScrollToRow (props = this.props, state = this.state) {
const { height, rowCount, scrollToAlignment, scrollToRow } = props
const { scrollTop } = state
if (scrollToRow >= 0 && rowCount > 0) {
const targetIndex = Math.max(0, Math.min(rowCount - 1, scrollToRow))
const calculatedScrollTop = this._rowSizeAndPositionManager.getUpdatedOffsetForIndex({
align: scrollToAlignment,
containerSize: height,
currentOffset: scrollTop,
targetIndex
})
if (scrollTop !== calculatedScrollTop) {
this._setScrollPosition({
scrollTop: calculatedScrollTop
})
}
}
}
_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._scrollingContainer) {
return
}
// Prevent pointer events from interrupting a smooth scroll
this._debounceScrollEnded()
// 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.
const { autoHeight, height, width } = this.props
const scrollbarSize = this._scrollbarSize
const totalRowsHeight = this._rowSizeAndPositionManager.getTotalSize()
const totalColumnsWidth = this._columnSizeAndPositionManager.getTotalSize()
const scrollLeft = Math.min(Math.max(0, totalColumnsWidth - width + scrollbarSize), event.target.scrollLeft)
const scrollTop = Math.min(Math.max(0, totalRowsHeight - 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
) {
// Track scrolling direction so we can more efficiently overscan rows to reduce empty space around the edges while scrolling.
const scrollDirectionHorizontal = scrollLeft > this.state.scrollLeft ? SCROLL_DIRECTION_FORWARD : SCROLL_DIRECTION_BACKWARD
const scrollDirectionVertical = scrollTop > this.state.scrollTop ? SCROLL_DIRECTION_FORWARD : SCROLL_DIRECTION_BACKWARD
const newState = {
isScrolling: true,
scrollDirectionHorizontal,
scrollDirectionVertical,
scrollLeft,
scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.OBSERVED
}
if (!autoHeight) {
newState.scrollTop = scrollTop
}
this.setState(newState)
}
this._invokeOnScrollMemoizer({ scrollLeft, scrollTop, totalColumnsWidth, totalRowsHeight })
}
}