vega-frontend-monorepo/libs/react-helpers/src/lib/pagination.ts
Bartłomiej Głownia b88fda787c
Feature/373 pagination of orders (#809)
* feat(#373): switch orders to infinite scroll mode

* feat(#373): fix orders tests

* feat(#218): improve typing in order-list

* feat(#373): add generic getRows for infinite rowModelType
2022-07-21 15:25:37 +02:00

54 lines
1.4 KiB
TypeScript

import type { IGetRowsParams } from 'ag-grid-community';
import type { Load } from './generic-data-provider';
import type { MutableRefObject } from 'react';
const getLastRow = (
startRow: number,
endRow: number,
blockLength: number,
totalCount?: number
) => {
let lastRow = -1;
if (totalCount !== undefined) {
if (!totalCount) {
lastRow = 0;
} else if (totalCount <= endRow) {
lastRow = totalCount;
}
} else if (blockLength < endRow - startRow) {
lastRow = blockLength;
}
return lastRow;
};
export const makeInfiniteScrollGetRows =
<T extends { node: any }>( // eslint-disable-line @typescript-eslint/no-explicit-any
newRows: MutableRefObject<number>,
data: MutableRefObject<(T | null)[] | null>,
totalCount: MutableRefObject<number | undefined>,
load: Load<(T | null)[]>
) =>
async ({
successCallback,
failCallback,
startRow,
endRow,
}: IGetRowsParams) => {
startRow += newRows.current;
endRow += newRows.current;
try {
if (data.current && data.current.indexOf(null) < endRow) {
await load();
}
const rowsThisBlock = data.current
? data.current.slice(startRow, endRow).map((edge) => edge?.node)
: [];
successCallback(
rowsThisBlock,
getLastRow(startRow, endRow, rowsThisBlock.length, totalCount.current)
);
} catch (e) {
failCallback();
}
};