2021-08-09 15:27:13 +00:00
|
|
|
import { stringifyQs } from "@saleor/utils/urls";
|
2019-06-19 14:40:52 +00:00
|
|
|
|
|
|
|
import { Pagination } from "../types";
|
|
|
|
import useNavigator from "./useNavigator";
|
|
|
|
|
|
|
|
export interface PageInfo {
|
|
|
|
endCursor: string;
|
|
|
|
hasNextPage: boolean;
|
|
|
|
hasPreviousPage: boolean;
|
|
|
|
startCursor: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface PaginationState {
|
|
|
|
after?: string;
|
|
|
|
before?: string;
|
|
|
|
first?: number;
|
|
|
|
last?: number;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function createPaginationState(
|
|
|
|
paginateBy: number,
|
|
|
|
queryString: Pagination
|
|
|
|
): PaginationState {
|
|
|
|
return queryString && (queryString.before || queryString.after)
|
|
|
|
? queryString.after
|
|
|
|
? {
|
|
|
|
after: queryString.after,
|
|
|
|
first: paginateBy
|
|
|
|
}
|
|
|
|
: {
|
|
|
|
before: queryString.before,
|
|
|
|
last: paginateBy
|
|
|
|
}
|
|
|
|
: {
|
|
|
|
first: paginateBy
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
function usePaginator() {
|
|
|
|
const navigate = useNavigator();
|
|
|
|
|
|
|
|
function paginate(
|
|
|
|
pageInfo: PageInfo,
|
|
|
|
paginationState: PaginationState,
|
|
|
|
queryString: Pagination
|
|
|
|
) {
|
|
|
|
const loadNextPage = () =>
|
|
|
|
navigate(
|
|
|
|
"?" +
|
|
|
|
stringifyQs({
|
|
|
|
...queryString,
|
|
|
|
after: pageInfo.endCursor,
|
|
|
|
before: undefined
|
|
|
|
}),
|
2021-12-06 14:41:18 +00:00
|
|
|
{ replace: true, resetScroll: true }
|
2019-06-19 14:40:52 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
const loadPreviousPage = () =>
|
|
|
|
navigate(
|
|
|
|
"?" +
|
|
|
|
stringifyQs({
|
|
|
|
...queryString,
|
|
|
|
after: undefined,
|
|
|
|
before: pageInfo.startCursor
|
|
|
|
}),
|
2021-12-06 14:41:18 +00:00
|
|
|
{ replace: true, resetScroll: true }
|
2019-06-19 14:40:52 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
const newPageInfo = pageInfo
|
|
|
|
? {
|
|
|
|
...pageInfo,
|
|
|
|
hasNextPage: !!paginationState.before || pageInfo.hasNextPage,
|
|
|
|
hasPreviousPage: !!paginationState.after || pageInfo.hasPreviousPage
|
|
|
|
}
|
|
|
|
: undefined;
|
|
|
|
|
|
|
|
return {
|
|
|
|
loadNextPage,
|
|
|
|
loadPreviousPage,
|
|
|
|
pageInfo: newPageInfo
|
|
|
|
};
|
|
|
|
}
|
|
|
|
return paginate;
|
|
|
|
}
|
|
|
|
export default usePaginator;
|