forked from lencx/ChatGPT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
useTable.tsx
57 lines (50 loc) · 1.72 KB
/
useTable.tsx
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
import React, { useState } from 'react';
import { Table } from 'antd';
import type { TableRowSelection } from 'antd/es/table/interface';
import { safeKey } from '@/hooks/useData';
type rowSelectionOptions = {
key: 'id' | string;
rowType: 'id' | 'row' | 'all';
};
export function useTableRowSelection(options?: Partial<rowSelectionOptions>) {
const { key = 'id', rowType = 'id' } = options || {};
const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
const [selectedRowIDs, setSelectedRowIDs] = useState<string[]>([]);
const [selectedRows, setSelectedRows] = useState<Record<string | symbol, any>[]>([]);
const onSelectChange = (
newSelectedRowKeys: React.Key[],
newSelectedRows: Record<string | symbol, any>[],
) => {
const keys = newSelectedRows.map((i: any) => i[safeKey] || i[key]);
setSelectedRowKeys(newSelectedRowKeys);
if (rowType === 'id') {
setSelectedRowIDs(keys);
}
if (rowType === 'row') {
setSelectedRows(newSelectedRows);
}
if (rowType === 'all') {
setSelectedRowIDs(keys);
setSelectedRows(newSelectedRows);
}
};
const rowReset = () => {
setSelectedRowKeys([]);
setSelectedRowIDs([]);
setSelectedRows([]);
};
const rowSelection: TableRowSelection<Record<string, any>> = {
selectedRowKeys,
onChange: onSelectChange,
selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT, Table.SELECTION_NONE],
};
return { rowSelection, selectedRowIDs, selectedRows, rowReset };
}
export const TABLE_PAGINATION = {
hideOnSinglePage: true,
showSizeChanger: true,
showQuickJumper: true,
defaultPageSize: 10,
pageSizeOptions: [5, 10, 15, 20],
showTotal: (total: number) => <span>Total {total} items</span>,
};