-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathGrid.js
1657 lines (1454 loc) · 52.7 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
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** @flow */
import type {
CellRenderer,
CellRangeRenderer,
CellPosition,
CellSize,
CellSizeGetter,
NoContentRenderer,
Scroll,
ScrollbarPresenceChange,
RenderedSection,
OverscanIndicesGetter,
Alignment,
CellCache,
StyleCache,
} from './types';
import type {AnimationTimeoutId} from '../utils/requestAnimationTimeout';
import * as React from 'react';
import clsx from 'clsx';
import calculateSizeAndPositionDataAndUpdateScrollOffset from './utils/calculateSizeAndPositionDataAndUpdateScrollOffset';
import ScalingCellSizeAndPositionManager from './utils/ScalingCellSizeAndPositionManager';
import createCallbackMemoizer from '../utils/createCallbackMemoizer';
import defaultOverscanIndicesGetter, {
SCROLL_DIRECTION_BACKWARD,
SCROLL_DIRECTION_FORWARD,
} from './defaultOverscanIndicesGetter';
import updateScrollIndexHelper from './utils/updateScrollIndexHelper';
import defaultCellRangeRenderer from './defaultCellRangeRenderer';
import scrollbarSize from 'dom-helpers/scrollbarSize';
import {polyfill} from 'react-lifecycles-compat';
import {
requestAnimationTimeout,
cancelAnimationTimeout,
} from '../utils/requestAnimationTimeout';
/**
* Specifies the number of milliseconds 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',
};
const renderNull: NoContentRenderer = () => null;
type ScrollPosition = {
scrollTop?: number,
scrollLeft?: number,
};
type Props = {
'aria-label': string,
'aria-readonly'?: boolean,
/**
* 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: boolean,
/**
* Removes fixed height from the scrollingContainer so that the total height of rows can stretch the window.
* Intended for use with WindowScroller
*/
autoHeight: boolean,
/**
* Removes fixed width from the scrollingContainer so that the total width of rows can stretch the window.
* Intended for use with WindowScroller
*/
autoWidth: boolean,
/** Responsible for rendering a cell given an row and column index. */
cellRenderer: CellRenderer,
/** Responsible for rendering a group of cells given their index ranges. */
cellRangeRenderer: CellRangeRenderer,
/** Optional custom CSS class name to attach to root Grid element. */
className?: string,
/** Number of columns in grid. */
columnCount: number,
/** Either a fixed column width (number) or a function that returns the width of a column given its index. */
columnWidth: CellSize,
/** Unfiltered props for the Grid container. */
containerProps?: Object,
/** ARIA role for the cell-container. */
containerRole: string,
/** Optional inline style applied to inner cell-container */
containerStyle: Object,
/**
* If CellMeasurer is used to measure this Grid's children, this should be a pointer to its CellMeasurerCache.
* A shared CellMeasurerCache reference enables Grid and CellMeasurer to share measurement data.
*/
deferredMeasurementCache?: 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: number,
/**
* 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: number,
/** Exposed for testing purposes only. */
getScrollbarSize: () => number,
/** Height of Grid; this property determines the number of visible (vs virtualized) rows. */
height: number,
/** Optional custom id to attach to root Grid element. */
id?: string,
/**
* Override internal is-scrolling state tracking.
* This property is primarily intended for use with the WindowScroller component.
*/
isScrolling?: boolean,
/**
* Opt-out of isScrolling param passed to cellRangeRenderer.
* To avoid the extra render when scroll stops.
*/
isScrollingOptOut: boolean,
/** Optional renderer to be used in place of rows when either :rowCount or :columnCount is 0. */
noContentRenderer: NoContentRenderer,
/**
* 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.
*/
onScroll: (params: Scroll) => void,
/**
* Called whenever a horizontal or vertical scrollbar is added or removed.
* This prop is not intended for end-user use;
* It is used by MultiGrid to support fixed-row/fixed-column scroll syncing.
*/
onScrollbarPresenceChange: (params: ScrollbarPresenceChange) => void,
/** Callback invoked with information about the section of the Grid that was just rendered. */
onSectionRendered: (params: RenderedSection) => void,
/**
* 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: number,
/**
* Calculates the number of cells to overscan before and after a specified range.
* This function ensures that overscanning doesn't exceed the available cells.
*/
overscanIndicesGetter: OverscanIndicesGetter,
/**
* 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: number,
/** ARIA role for the grid element. */
role: string,
/**
* 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: CellSize,
/** Number of rows in grid. */
rowCount: number,
/** Wait this amount of time after the last scroll event before resetting Grid `pointer-events`. */
scrollingResetTimeInterval: number,
/** Horizontal offset. */
scrollLeft?: 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: Alignment,
/** Column index to ensure visible (by forcefully scrolling if necessary) */
scrollToColumn: number,
/** Vertical offset. */
scrollTop?: number,
/** Row index to ensure visible (by forcefully scrolling if necessary) */
scrollToRow: number,
/** Optional inline style */
style: Object,
/** Tab index for focus */
tabIndex: ?number,
/** Width of Grid; this property determines the number of visible (vs virtualized) columns. */
width: number,
/** Reference to DOM node */
elementRef?: React.Ref<React.ElementType>,
};
type InstanceProps = {
prevColumnWidth: CellSize,
prevRowHeight: CellSize,
prevColumnCount: number,
prevRowCount: number,
prevIsScrolling: boolean,
prevScrollToColumn: number,
prevScrollToRow: number,
columnSizeAndPositionManager: ScalingCellSizeAndPositionManager,
rowSizeAndPositionManager: ScalingCellSizeAndPositionManager,
scrollbarSize: number,
scrollbarSizeMeasured: boolean,
};
type State = {
instanceProps: InstanceProps,
isScrolling: boolean,
scrollDirectionHorizontal: -1 | 1,
scrollDirectionVertical: -1 | 1,
scrollLeft: number,
scrollTop: number,
scrollPositionChangeReason: 'observed' | 'requested' | null,
needToResetStyleCache: boolean,
};
/**
* 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.
*/
class Grid extends React.PureComponent<Props, State> {
static defaultProps = {
'aria-label': 'grid',
'aria-readonly': true,
autoContainerWidth: false,
autoHeight: false,
autoWidth: false,
cellRangeRenderer: defaultCellRangeRenderer,
containerRole: 'row',
containerStyle: {},
estimatedColumnSize: 100,
estimatedRowSize: 30,
getScrollbarSize: scrollbarSize,
noContentRenderer: renderNull,
onScroll: () => {},
onScrollbarPresenceChange: () => {},
onSectionRendered: () => {},
overscanColumnCount: 0,
overscanIndicesGetter: defaultOverscanIndicesGetter,
overscanRowCount: 10,
role: 'grid',
scrollingResetTimeInterval: DEFAULT_SCROLLING_RESET_TIME_INTERVAL,
scrollToAlignment: 'auto',
scrollToColumn: -1,
scrollToRow: -1,
style: {},
tabIndex: 0,
isScrollingOptOut: false,
};
// Invokes onSectionRendered callback only when start/stop row or column indices change
_onGridRenderedMemoizer = createCallbackMemoizer();
_onScrollMemoizer = createCallbackMemoizer(false);
_deferredInvalidateColumnIndex = null;
_deferredInvalidateRowIndex = null;
_recomputeScrollLeftFlag = false;
_recomputeScrollTopFlag = false;
_horizontalScrollBarSize = 0;
_verticalScrollBarSize = 0;
_scrollbarPresenceChanged = false;
_scrollingContainer: Element;
_childrenToDisplay: React.Element<*>[];
_columnStartIndex: number;
_columnStopIndex: number;
_rowStartIndex: number;
_rowStopIndex: number;
_renderedColumnStartIndex = 0;
_renderedColumnStopIndex = 0;
_renderedRowStartIndex = 0;
_renderedRowStopIndex = 0;
_initialScrollTop: number;
_initialScrollLeft: number;
_disablePointerEventsTimeoutId: ?AnimationTimeoutId;
_styleCache: StyleCache = {};
_cellCache: CellCache = {};
constructor(props: Props) {
super(props);
const columnSizeAndPositionManager = new ScalingCellSizeAndPositionManager({
cellCount: props.columnCount,
cellSizeGetter: params => Grid._wrapSizeGetter(props.columnWidth)(params),
estimatedCellSize: Grid._getEstimatedColumnSize(props),
});
const rowSizeAndPositionManager = new ScalingCellSizeAndPositionManager({
cellCount: props.rowCount,
cellSizeGetter: params => Grid._wrapSizeGetter(props.rowHeight)(params),
estimatedCellSize: Grid._getEstimatedRowSize(props),
});
this.state = {
instanceProps: {
columnSizeAndPositionManager,
rowSizeAndPositionManager,
prevColumnWidth: props.columnWidth,
prevRowHeight: props.rowHeight,
prevColumnCount: props.columnCount,
prevRowCount: props.rowCount,
prevIsScrolling: props.isScrolling === true,
prevScrollToColumn: props.scrollToColumn,
prevScrollToRow: props.scrollToRow,
scrollbarSize: 0,
scrollbarSizeMeasured: false,
},
isScrolling: false,
scrollDirectionHorizontal: SCROLL_DIRECTION_FORWARD,
scrollDirectionVertical: SCROLL_DIRECTION_FORWARD,
scrollLeft: 0,
scrollTop: 0,
scrollPositionChangeReason: null,
needToResetStyleCache: false,
};
if (props.scrollToRow > 0) {
this._initialScrollTop = this._getCalculatedScrollTop(props, this.state);
}
if (props.scrollToColumn > 0) {
this._initialScrollLeft = this._getCalculatedScrollLeft(
props,
this.state,
);
}
}
/**
* Gets offsets for a given cell and alignment.
*/
getOffsetForCell({
alignment = this.props.scrollToAlignment,
columnIndex = this.props.scrollToColumn,
rowIndex = this.props.scrollToRow,
}: {
alignment?: Alignment,
columnIndex?: number,
rowIndex?: number,
} = {}) {
const offsetProps = {
...this.props,
scrollToAlignment: alignment,
scrollToColumn: columnIndex,
scrollToRow: rowIndex,
};
return {
scrollLeft: this._getCalculatedScrollLeft(offsetProps),
scrollTop: this._getCalculatedScrollTop(offsetProps),
};
}
/**
* Gets estimated total rows' height.
*/
getTotalRowsHeight() {
return this.state.instanceProps.rowSizeAndPositionManager.getTotalSize();
}
/**
* Gets estimated total columns' width.
*/
getTotalColumnsWidth() {
return this.state.instanceProps.columnSizeAndPositionManager.getTotalSize();
}
/**
* This method handles a scroll event originating from an external scroll control.
* It's an advanced method and should probably not be used unless you're implementing a custom scroll-bar solution.
*/
handleScrollEvent({
scrollLeft: scrollLeftParam = 0,
scrollTop: scrollTopParam = 0,
}: ScrollPosition) {
// On iOS, we can arrive at negative offsets by swiping past the start.
// To prevent flicker here, we make playing in the negative offset zone cause nothing to happen.
if (scrollTopParam < 0) {
return;
}
// Prevent pointer events from interrupting a smooth scroll
this._debounceScrollEnded();
const {autoHeight, autoWidth, height, width} = this.props;
const {instanceProps} = this.state;
// 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 scrollbarSize = instanceProps.scrollbarSize;
const totalRowsHeight = instanceProps.rowSizeAndPositionManager.getTotalSize();
const totalColumnsWidth = instanceProps.columnSizeAndPositionManager.getTotalSize();
const scrollLeft = Math.min(
Math.max(0, totalColumnsWidth - width + scrollbarSize),
scrollLeftParam,
);
const scrollTop = Math.min(
Math.max(0, totalRowsHeight - height + scrollbarSize),
scrollTopParam,
);
// 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.
// Don't change direction for an axis unless scroll offset has changed.
const scrollDirectionHorizontal =
scrollLeft !== this.state.scrollLeft
? scrollLeft > this.state.scrollLeft
? SCROLL_DIRECTION_FORWARD
: SCROLL_DIRECTION_BACKWARD
: this.state.scrollDirectionHorizontal;
const scrollDirectionVertical =
scrollTop !== this.state.scrollTop
? scrollTop > this.state.scrollTop
? SCROLL_DIRECTION_FORWARD
: SCROLL_DIRECTION_BACKWARD
: this.state.scrollDirectionVertical;
const newState: $Shape<State> = {
isScrolling: true,
scrollDirectionHorizontal,
scrollDirectionVertical,
scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.OBSERVED,
};
if (!autoHeight) {
newState.scrollTop = scrollTop;
}
if (!autoWidth) {
newState.scrollLeft = scrollLeft;
}
newState.needToResetStyleCache = false;
this.setState(newState);
}
this._invokeOnScrollMemoizer({
scrollLeft,
scrollTop,
totalColumnsWidth,
totalRowsHeight,
});
}
/**
* Invalidate Grid size and recompute visible cells.
* This is a deferred wrapper for recomputeGridSize().
* It sets a flag to be evaluated on cDM/cDU to avoid unnecessary renders.
* This method is intended for advanced use-cases like CellMeasurer.
*/
// @TODO (bvaughn) Add automated test coverage for this.
invalidateCellSizeAfterRender({columnIndex, rowIndex}: CellPosition) {
this._deferredInvalidateColumnIndex =
typeof this._deferredInvalidateColumnIndex === 'number'
? Math.min(this._deferredInvalidateColumnIndex, columnIndex)
: columnIndex;
this._deferredInvalidateRowIndex =
typeof this._deferredInvalidateRowIndex === 'number'
? Math.min(this._deferredInvalidateRowIndex, rowIndex)
: rowIndex;
}
/**
* 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;
const {instanceProps} = this.state;
instanceProps.columnSizeAndPositionManager.getSizeAndPositionOfCell(
columnCount - 1,
);
instanceProps.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}: CellPosition = {}) {
const {scrollToColumn, scrollToRow} = this.props;
const {instanceProps} = this.state;
instanceProps.columnSizeAndPositionManager.resetCell(columnIndex);
instanceProps.rowSizeAndPositionManager.resetCell(rowIndex);
// Cell sizes may be determined by a function property.
// In this case the cDU handler can't know if they changed.
// Store this flag to let the next cDU pass know it needs to recompute the scroll offset.
this._recomputeScrollLeftFlag =
scrollToColumn >= 0 &&
(this.state.scrollDirectionHorizontal === SCROLL_DIRECTION_FORWARD
? columnIndex <= scrollToColumn
: columnIndex >= scrollToColumn);
this._recomputeScrollTopFlag =
scrollToRow >= 0 &&
(this.state.scrollDirectionVertical === SCROLL_DIRECTION_FORWARD
? rowIndex <= scrollToRow
: rowIndex >= scrollToRow);
// Clear cell cache in case we are scrolling;
// Invalid row heights likely mean invalid cached content as well.
this._styleCache = {};
this._cellCache = {};
this.forceUpdate();
}
/**
* Ensure column and row are visible.
*/
scrollToCell({columnIndex, rowIndex}: CellPosition) {
const {columnCount} = this.props;
const props = this.props;
// Don't adjust scroll offset for single-column grids (eg List, Table).
// This can cause a funky scroll offset because of the vertical scrollbar width.
if (columnCount > 1 && columnIndex !== undefined) {
this._updateScrollLeftForScrollToColumn({
...props,
scrollToColumn: columnIndex,
});
}
if (rowIndex !== undefined) {
this._updateScrollTopForScrollToRow({
...props,
scrollToRow: rowIndex,
});
}
}
componentDidMount() {
const {
getScrollbarSize,
height,
scrollLeft,
scrollToColumn,
scrollTop,
scrollToRow,
width,
} = this.props;
const {instanceProps} = this.state;
// Reset initial offsets to be ignored in browser
this._initialScrollTop = 0;
this._initialScrollLeft = 0;
// If cell sizes have been invalidated (eg we are using CellMeasurer) then reset cached positions.
// We must do this at the start of the method as we may calculate and update scroll position below.
this._handleInvalidatedGridSize();
// If this component was first rendered server-side, scrollbar size will be undefined.
// In that event we need to remeasure.
if (!instanceProps.scrollbarSizeMeasured) {
this.setState(prevState => {
const stateUpdate = {...prevState, needToResetStyleCache: false};
stateUpdate.instanceProps.scrollbarSize = getScrollbarSize();
stateUpdate.instanceProps.scrollbarSizeMeasured = true;
return stateUpdate;
});
}
if (
(typeof scrollLeft === 'number' && scrollLeft >= 0) ||
(typeof scrollTop === 'number' && scrollTop >= 0)
) {
const stateUpdate = Grid._getScrollToPositionStateUpdate({
prevState: this.state,
scrollLeft,
scrollTop,
});
if (stateUpdate) {
stateUpdate.needToResetStyleCache = false;
this.setState(stateUpdate);
}
}
// refs don't work in `react-test-renderer`
if (this._scrollingContainer) {
// setting the ref's scrollLeft and scrollTop.
// Somehow in MultiGrid the main grid doesn't trigger a update on mount.
if (this._scrollingContainer.scrollLeft !== this.state.scrollLeft) {
this._scrollingContainer.scrollLeft = this.state.scrollLeft;
}
if (this._scrollingContainer.scrollTop !== this.state.scrollTop) {
this._scrollingContainer.scrollTop = this.state.scrollTop;
}
}
// Don't update scroll offset if the size is 0; we don't render any cells in this case.
// Setting a state may cause us to later thing we've updated the offce when we haven't.
const sizeIsBiggerThanZero = height > 0 && width > 0;
if (scrollToColumn >= 0 && sizeIsBiggerThanZero) {
this._updateScrollLeftForScrollToColumn();
}
if (scrollToRow >= 0 && sizeIsBiggerThanZero) {
this._updateScrollTopForScrollToRow();
}
// Update onRowsRendered callback
this._invokeOnGridRenderedHelper();
// Initialize onScroll callback
this._invokeOnScrollMemoizer({
scrollLeft: scrollLeft || 0,
scrollTop: scrollTop || 0,
totalColumnsWidth: instanceProps.columnSizeAndPositionManager.getTotalSize(),
totalRowsHeight: instanceProps.rowSizeAndPositionManager.getTotalSize(),
});
this._maybeCallOnScrollbarPresenceChange();
}
/**
* @private
* This method updates scrollLeft/scrollTop in state for the following conditions:
* 1) New scroll-to-cell props have been set
*/
componentDidUpdate(prevProps: Props, prevState: State) {
const {
autoHeight,
autoWidth,
columnCount,
height,
rowCount,
scrollToAlignment,
scrollToColumn,
scrollToRow,
width,
} = this.props;
const {
scrollLeft,
scrollPositionChangeReason,
scrollTop,
instanceProps,
} = this.state;
// If cell sizes have been invalidated (eg we are using CellMeasurer) then reset cached positions.
// We must do this at the start of the method as we may calculate and update scroll position below.
this._handleInvalidatedGridSize();
// 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
) {
// @TRICKY :autoHeight and :autoWidth properties instructs Grid to leave :scrollTop and :scrollLeft management to an external HOC (eg WindowScroller).
// In this case we should avoid checking scrollingContainer.scrollTop and scrollingContainer.scrollLeft since it forces layout/flow.
if (
!autoWidth &&
scrollLeft >= 0 &&
(scrollLeft !== this._scrollingContainer.scrollLeft ||
columnOrRowCountJustIncreasedFromZero)
) {
this._scrollingContainer.scrollLeft = scrollLeft;
}
if (
!autoHeight &&
scrollTop >= 0 &&
(scrollTop !== this._scrollingContainer.scrollTop ||
columnOrRowCountJustIncreasedFromZero)
) {
this._scrollingContainer.scrollTop = scrollTop;
}
}
// Special case where the previous size was 0:
// In this case we don't show any windowed cells at all.
// So we should always recalculate offset afterwards.
const sizeJustIncreasedFromZero =
(prevProps.width === 0 || prevProps.height === 0) &&
height > 0 &&
width > 0;
// 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?
if (this._recomputeScrollLeftFlag) {
this._recomputeScrollLeftFlag = false;
this._updateScrollLeftForScrollToColumn(this.props);
} else {
updateScrollIndexHelper({
cellSizeAndPositionManager: instanceProps.columnSizeAndPositionManager,
previousCellsCount: prevProps.columnCount,
previousCellSize: prevProps.columnWidth,
previousScrollToAlignment: prevProps.scrollToAlignment,
previousScrollToIndex: prevProps.scrollToColumn,
previousSize: prevProps.width,
scrollOffset: scrollLeft,
scrollToAlignment,
scrollToIndex: scrollToColumn,
size: width,
sizeJustIncreasedFromZero,
updateScrollIndexCallback: () =>
this._updateScrollLeftForScrollToColumn(this.props),
});
}
if (this._recomputeScrollTopFlag) {
this._recomputeScrollTopFlag = false;
this._updateScrollTopForScrollToRow(this.props);
} else {
updateScrollIndexHelper({
cellSizeAndPositionManager: instanceProps.rowSizeAndPositionManager,
previousCellsCount: prevProps.rowCount,
previousCellSize: prevProps.rowHeight,
previousScrollToAlignment: prevProps.scrollToAlignment,
previousScrollToIndex: prevProps.scrollToRow,
previousSize: prevProps.height,
scrollOffset: scrollTop,
scrollToAlignment,
scrollToIndex: scrollToRow,
size: height,
sizeJustIncreasedFromZero,
updateScrollIndexCallback: () =>
this._updateScrollTopForScrollToRow(this.props),
});
}
// 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 = instanceProps.rowSizeAndPositionManager.getTotalSize();
const totalColumnsWidth = instanceProps.columnSizeAndPositionManager.getTotalSize();
this._invokeOnScrollMemoizer({
scrollLeft,
scrollTop,
totalColumnsWidth,
totalRowsHeight,
});
}
this._maybeCallOnScrollbarPresenceChange();
}
componentWillUnmount() {
if (this._disablePointerEventsTimeoutId) {
cancelAnimationTimeout(this._disablePointerEventsTimeoutId);
}
}
/**
* 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
*/
static getDerivedStateFromProps(
nextProps: Props,
prevState: State,
): $Shape<State> {
const newState = {};
if (
(nextProps.columnCount === 0 && prevState.scrollLeft !== 0) ||
(nextProps.rowCount === 0 && prevState.scrollTop !== 0)
) {
newState.scrollLeft = 0;
newState.scrollTop = 0;
// only use scroll{Left,Top} from props if scrollTo{Column,Row} isn't specified
// scrollTo{Column,Row} should override scroll{Left,Top}
} else if (
(nextProps.scrollLeft !== prevState.scrollLeft &&
nextProps.scrollToColumn < 0) ||
(nextProps.scrollTop !== prevState.scrollTop && nextProps.scrollToRow < 0)
) {
Object.assign(
newState,
Grid._getScrollToPositionStateUpdate({
prevState,
scrollLeft: nextProps.scrollLeft,
scrollTop: nextProps.scrollTop,
}),
);
}
let {instanceProps} = prevState;
// Initially we should not clearStyleCache
newState.needToResetStyleCache = false;
if (
nextProps.columnWidth !== instanceProps.prevColumnWidth ||
nextProps.rowHeight !== instanceProps.prevRowHeight
) {
// Reset cache. set it to {} in render
newState.needToResetStyleCache = true;
}
instanceProps.columnSizeAndPositionManager.configure({
cellCount: nextProps.columnCount,
estimatedCellSize: Grid._getEstimatedColumnSize(nextProps),
cellSizeGetter: Grid._wrapSizeGetter(nextProps.columnWidth),
});
instanceProps.rowSizeAndPositionManager.configure({
cellCount: nextProps.rowCount,
estimatedCellSize: Grid._getEstimatedRowSize(nextProps),
cellSizeGetter: Grid._wrapSizeGetter(nextProps.rowHeight),
});
if (
instanceProps.prevColumnCount === 0 ||
instanceProps.prevRowCount === 0
) {
instanceProps.prevColumnCount = 0;
instanceProps.prevRowCount = 0;
}
// If scrolling is controlled outside this component, clear cache when scrolling stops
if (
nextProps.autoHeight &&
nextProps.isScrolling === false &&
instanceProps.prevIsScrolling === true
) {
Object.assign(newState, {
isScrolling: false,
});
}
let maybeStateA;
let maybeStateB;
calculateSizeAndPositionDataAndUpdateScrollOffset({
cellCount: instanceProps.prevColumnCount,
cellSize:
typeof instanceProps.prevColumnWidth === 'number'
? instanceProps.prevColumnWidth
: null,
computeMetadataCallback: () =>
instanceProps.columnSizeAndPositionManager.resetCell(0),
computeMetadataCallbackProps: nextProps,
nextCellsCount: nextProps.columnCount,
nextCellSize:
typeof nextProps.columnWidth === 'number'
? nextProps.columnWidth
: null,
nextScrollToIndex: nextProps.scrollToColumn,
scrollToIndex: instanceProps.prevScrollToColumn,
updateScrollOffsetForScrollToIndex: () => {
maybeStateA = Grid._getScrollLeftForScrollToColumnStateUpdate(
nextProps,
prevState,
);
},
});
calculateSizeAndPositionDataAndUpdateScrollOffset({
cellCount: instanceProps.prevRowCount,
cellSize:
typeof instanceProps.prevRowHeight === 'number'
? instanceProps.prevRowHeight
: null,
computeMetadataCallback: () =>
instanceProps.rowSizeAndPositionManager.resetCell(0),
computeMetadataCallbackProps: nextProps,
nextCellsCount: nextProps.rowCount,
nextCellSize:
typeof nextProps.rowHeight === 'number' ? nextProps.rowHeight : null,
nextScrollToIndex: nextProps.scrollToRow,
scrollToIndex: instanceProps.prevScrollToRow,
updateScrollOffsetForScrollToIndex: () => {
maybeStateB = Grid._getScrollTopForScrollToRowStateUpdate(
nextProps,
prevState,
);
},
});
instanceProps.prevColumnCount = nextProps.columnCount;
instanceProps.prevColumnWidth = nextProps.columnWidth;
instanceProps.prevIsScrolling = nextProps.isScrolling === true;
instanceProps.prevRowCount = nextProps.rowCount;
instanceProps.prevRowHeight = nextProps.rowHeight;
instanceProps.prevScrollToColumn = nextProps.scrollToColumn;
instanceProps.prevScrollToRow = nextProps.scrollToRow;
// getting scrollBarSize (moved from componentWillMount)
instanceProps.scrollbarSize = nextProps.getScrollbarSize();
if (instanceProps.scrollbarSize === undefined) {
instanceProps.scrollbarSizeMeasured = false;
instanceProps.scrollbarSize = 0;
} else {
instanceProps.scrollbarSizeMeasured = true;
}
newState.instanceProps = instanceProps;
return {...newState, ...maybeStateA, ...maybeStateB};
}
render() {
const {
autoContainerWidth,
autoHeight,
autoWidth,
className,
containerProps,
containerRole,
containerStyle,
height,
id,
noContentRenderer,
role,
style,
tabIndex,
width,
} = this.props;
const {instanceProps, needToResetStyleCache} = this.state;
const isScrolling = this._isScrolling();
const gridStyle: Object = {
boxSizing: 'border-box',
direction: 'ltr',
height: autoHeight ? 'auto' : height,
position: 'relative',
width: autoWidth ? 'auto' : width,
WebkitOverflowScrolling: 'touch',
willChange: 'transform',
};
if (needToResetStyleCache) {
this._styleCache = {};
}