Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DataGrid] Use binary search to find column indexes in virtualization #1903

Merged
merged 6 commits into from
Jun 18, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import { useGridApiMethod } from '../../root/useGridApiMethod';
import { useGridApiEventHandler } from '../../root/useGridApiEventHandler';
import {
gridColumnsMetaSelector,
visibleGridColumnsLengthSelector,
visibleGridColumnsSelector,
} from '../columns/gridColumnsSelector';
import { useGridSelector } from '../core/useGridSelector';
Expand All @@ -27,6 +26,28 @@ type UseVirtualColumnsReturnType = [
UpdateRenderedColsFnType,
];

// Uses binary search to avoid looping through all possible positions
function getIdxFromScroll(
offset: number,
positions: number[],
sliceStart = 0,
sliceEnd = positions.length,
): number {
if (positions.length <= 0) {
return -1;
}

if (sliceStart >= sliceEnd) {
return sliceStart;
}

const pivot = sliceStart + Math.floor((sliceEnd - sliceStart) / 2);
const itemOffset = positions[pivot];
return offset <= itemOffset
? getIdxFromScroll(offset, positions, sliceStart, pivot)
: getIdxFromScroll(offset, positions, pivot + 1, sliceEnd);
}

export const useGridVirtualColumns = (
options: GridOptions,
apiRef: GridApiRef,
Expand All @@ -37,21 +58,11 @@ export const useGridVirtualColumns = (
const containerPropsRef = React.useRef<GridContainerProps | null>(null);
const lastScrollLeftRef = React.useRef<number>(0);
const columnsMeta = useGridSelector(apiRef, gridColumnsMetaSelector);
const visibleColumnCount = useGridSelector(apiRef, visibleGridColumnsLengthSelector);
const visibleColumns = useGridSelector(apiRef, visibleGridColumnsSelector);

const getColumnIdxFromScroll = React.useCallback(
(left: number) => {
const positions = columnsMeta.positions;

if (!visibleColumnCount) {
return -1;
}
let colIdx = [...positions].reverse().findIndex((p) => left >= p);
colIdx = positions.length - 1 - colIdx;
return colIdx;
},
[columnsMeta.positions, visibleColumnCount],
(left: number) => getIdxFromScroll(left, columnsMeta.positions),
[columnsMeta.positions],
);

const getColumnFromScroll = React.useCallback(
Expand Down