-
-
Notifications
You must be signed in to change notification settings - Fork 46.8k
/
usePagination.ts
88 lines (75 loc) · 2.55 KB
/
usePagination.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
import { useState } from 'react';
import type { PaginationProps } from '../../pagination';
import type { TablePaginationConfig } from '../interface';
import extendsObject from '../../_util/extendsObject';
export const DEFAULT_PAGE_SIZE = 10;
export function getPaginationParam(
pagination: TablePaginationConfig | boolean | undefined,
mergedPagination: TablePaginationConfig,
) {
const param: any = {
current: mergedPagination.current,
pageSize: mergedPagination.pageSize,
};
const paginationObj = pagination && typeof pagination === 'object' ? pagination : {};
Object.keys(paginationObj).forEach((pageProp) => {
const value = (mergedPagination as any)[pageProp];
if (typeof value !== 'function') {
param[pageProp] = value;
}
});
return param;
}
export default function usePagination(
total: number,
pagination: TablePaginationConfig | false | undefined,
onChange: (current: number, pageSize: number) => void,
): [TablePaginationConfig, () => void] {
const { total: paginationTotal = 0, ...paginationObj } =
pagination && typeof pagination === 'object' ? pagination : {};
const [innerPagination, setInnerPagination] = useState<{
current?: number;
pageSize?: number;
}>(() => ({
current: 'defaultCurrent' in paginationObj ? paginationObj.defaultCurrent : 1,
pageSize:
'defaultPageSize' in paginationObj ? paginationObj.defaultPageSize : DEFAULT_PAGE_SIZE,
}));
// ============ Basic Pagination Config ============
const mergedPagination = extendsObject<Partial<TablePaginationConfig>>(
innerPagination,
paginationObj,
{
total: paginationTotal > 0 ? paginationTotal : total,
},
);
// Reset `current` if data length or pageSize changed
const maxPage = Math.ceil((paginationTotal || total) / mergedPagination.pageSize!);
if (mergedPagination.current! > maxPage) {
// Prevent a maximum page count of 0
mergedPagination.current = maxPage || 1;
}
const refreshPagination = (current?: number, pageSize?: number) => {
setInnerPagination({
current: current ?? 1,
pageSize: pageSize || mergedPagination.pageSize,
});
};
const onInternalChange: PaginationProps['onChange'] = (current, pageSize) => {
if (pagination) {
pagination.onChange?.(current, pageSize);
}
refreshPagination(current, pageSize);
onChange(current, pageSize || mergedPagination?.pageSize!);
};
if (pagination === false) {
return [{}, () => {}];
}
return [
{
...mergedPagination,
onChange: onInternalChange,
},
refreshPagination,
];
}