-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathuseGridScroll.ts
178 lines (159 loc) · 6.96 KB
/
useGridScroll.ts
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
import * as React from 'react';
import { useRtl } from '@mui/system/RtlProvider';
import { GridCellIndexCoordinates } from '../../../models/gridCell';
import { GridPrivateApiCommunity } from '../../../models/api/gridApiCommunity';
import { useGridLogger } from '../../utils/useGridLogger';
import {
gridColumnPositionsSelector,
gridVisibleColumnDefinitionsSelector,
} from '../columns/gridColumnsSelector';
import { useGridSelector } from '../../utils/useGridSelector';
import { DataGridProcessedProps } from '../../../models/props/DataGridProps';
import { gridPageSelector, gridPageSizeSelector } from '../pagination/gridPaginationSelector';
import { gridRowCountSelector } from '../rows/gridRowsSelector';
import { gridRowsMetaSelector } from '../rows/gridRowsMetaSelector';
import { GridScrollParams } from '../../../models/params/gridScrollParams';
import { GridScrollApi } from '../../../models/api/gridScrollApi';
import { useGridApiMethod } from '../../utils/useGridApiMethod';
import { gridExpandedSortedRowEntriesSelector } from '../filter/gridFilterSelector';
import { gridDimensionsSelector } from '../dimensions';
// Logic copied from https://www.w3.org/TR/wai-aria-practices/examples/listbox/js/listbox.js
// Similar to https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
function scrollIntoView(dimensions: {
containerSize: number;
scrollPosition: number;
elementSize: number;
elementOffset: number;
}) {
const { containerSize, scrollPosition, elementSize, elementOffset } = dimensions;
const elementEnd = elementOffset + elementSize;
// Always scroll to top when cell is higher than viewport to avoid scroll jump
// See https://github.com/mui/mui-x/issues/4513 and https://github.com/mui/mui-x/issues/4514
if (elementSize > containerSize) {
return elementOffset;
}
if (elementEnd - containerSize > scrollPosition) {
return elementEnd - containerSize;
}
if (elementOffset < scrollPosition) {
return elementOffset;
}
return undefined;
}
/**
* @requires useGridPagination (state) - can be after, async only
* @requires useGridColumns (state) - can be after, async only
* @requires useGridRows (state) - can be after, async only
* @requires useGridRowsMeta (state) - can be after, async only
* @requires useGridFilter (state)
* @requires useGridColumnSpanning (method)
*/
export const useGridScroll = (
apiRef: React.MutableRefObject<GridPrivateApiCommunity>,
props: Pick<DataGridProcessedProps, 'pagination'>,
): void => {
const isRtl = useRtl();
const logger = useGridLogger(apiRef, 'useGridScroll');
const colRef = apiRef.current.columnHeadersContainerRef;
const virtualScrollerRef = apiRef.current.virtualScrollerRef!;
const visibleSortedRows = useGridSelector(apiRef, gridExpandedSortedRowEntriesSelector);
const scrollToIndexes = React.useCallback<GridScrollApi['scrollToIndexes']>(
(params: Partial<GridCellIndexCoordinates>) => {
const dimensions = gridDimensionsSelector(apiRef.current.state);
const totalRowCount = gridRowCountSelector(apiRef);
const visibleColumns = gridVisibleColumnDefinitionsSelector(apiRef);
const scrollToHeader = params.rowIndex == null;
if ((!scrollToHeader && totalRowCount === 0) || visibleColumns.length === 0) {
return false;
}
logger.debug(`Scrolling to cell at row ${params.rowIndex}, col: ${params.colIndex} `);
let scrollCoordinates: Partial<GridScrollParams> = {};
if (params.colIndex !== undefined) {
const columnPositions = gridColumnPositionsSelector(apiRef);
let cellWidth: number | undefined;
if (typeof params.rowIndex !== 'undefined') {
const rowId = visibleSortedRows[params.rowIndex]?.id;
const cellColSpanInfo = apiRef.current.unstable_getCellColSpanInfo(
rowId,
params.colIndex,
);
if (cellColSpanInfo && !cellColSpanInfo.spannedByColSpan) {
cellWidth = cellColSpanInfo.cellProps.width;
}
}
if (typeof cellWidth === 'undefined') {
cellWidth = visibleColumns[params.colIndex].computedWidth;
}
// When using RTL, `scrollLeft` becomes negative, so we must ensure that we only compare values.
scrollCoordinates.left = scrollIntoView({
containerSize: dimensions.viewportOuterSize.width,
scrollPosition: Math.abs(virtualScrollerRef.current!.scrollLeft),
elementSize: cellWidth,
elementOffset: columnPositions[params.colIndex],
});
}
if (params.rowIndex !== undefined) {
const rowsMeta = gridRowsMetaSelector(apiRef.current.state);
const page = gridPageSelector(apiRef);
const pageSize = gridPageSizeSelector(apiRef);
const elementIndex = !props.pagination
? params.rowIndex
: params.rowIndex - page * pageSize;
const targetOffsetHeight = rowsMeta.positions[elementIndex + 1]
? rowsMeta.positions[elementIndex + 1] - rowsMeta.positions[elementIndex]
: rowsMeta.currentPageTotalHeight - rowsMeta.positions[elementIndex];
scrollCoordinates.top = scrollIntoView({
containerSize: dimensions.viewportInnerSize.height,
scrollPosition: virtualScrollerRef.current!.scrollTop,
elementSize: targetOffsetHeight,
elementOffset: rowsMeta.positions[elementIndex],
});
}
scrollCoordinates = apiRef.current.unstable_applyPipeProcessors(
'scrollToIndexes',
scrollCoordinates,
params,
);
if (
typeof scrollCoordinates.left !== undefined ||
typeof scrollCoordinates.top !== undefined
) {
apiRef.current.scroll(scrollCoordinates);
return true;
}
return false;
},
[logger, apiRef, virtualScrollerRef, props.pagination, visibleSortedRows],
);
const scroll = React.useCallback<GridScrollApi['scroll']>(
(params: Partial<GridScrollParams>) => {
if (virtualScrollerRef.current && params.left !== undefined && colRef.current) {
const direction = isRtl ? -1 : 1;
colRef.current.scrollLeft = params.left;
virtualScrollerRef.current.scrollLeft = direction * params.left;
logger.debug(`Scrolling left: ${params.left}`);
}
if (virtualScrollerRef.current && params.top !== undefined) {
virtualScrollerRef.current.scrollTop = params.top;
logger.debug(`Scrolling top: ${params.top}`);
}
logger.debug(`Scrolling, updating container, and viewport`);
},
[virtualScrollerRef, isRtl, colRef, logger],
);
const getScrollPosition = React.useCallback<GridScrollApi['getScrollPosition']>(() => {
if (!virtualScrollerRef?.current) {
return { top: 0, left: 0 };
}
return {
top: virtualScrollerRef.current.scrollTop,
left: virtualScrollerRef.current.scrollLeft,
};
}, [virtualScrollerRef]);
const scrollApi: GridScrollApi = {
scroll,
scrollToIndexes,
getScrollPosition,
};
useGridApiMethod(apiRef, scrollApi, 'public');
};