-
Notifications
You must be signed in to change notification settings - Fork 0
/
with-expanded.add-on.ts
58 lines (48 loc) · 2.15 KB
/
with-expanded.add-on.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
import { useCallback, useMemo } from 'react';
import { IdType, useExpanded, UseExpandedInstanceProps, UseExpandedOptions, UseExpandedState } from 'react-table';
import { forEach, values } from 'lodash-es';
import { ExpandSetter, IRelatableStateInstance, TableAddOnReturn } from '../relatable.types';
import { ExpandedRow, IRowProps } from '../components/renderers';
import arrayHasItems from '../utils/array-has-items';
export interface IWithExpandedOptions<Data extends object = any> extends UseExpandedOptions<Data> {
onExpandedChange?: ExpandSetter<Data>;
expandedRowComponent?: React.FC<IRowProps>;
// react-table state override https://react-table.js.org/api/useExpanded
expanded?: IdType<Data>[];
}
export interface IWithExpandedState<Data extends object = any> extends UseExpandedState<Data> {
expandSubRows: false;
CustomExpandedRowComponent: React.FC<IRowProps>;
onCustomExpandedChange: ExpandSetter<Data>;
}
export interface IWithExpandedInstance<Data extends object = any> extends UseExpandedInstanceProps<Data>, IRelatableStateInstance<Data, IWithExpandedState<Data>> {
expandSubRows: false;
CustomExpandedRowComponent: React.FC<IRowProps>;
onCustomExpandedChange: ExpandSetter<Data>;
}
export default function withExpanded<Data extends object = any>(options: IWithExpandedOptions<Data> = {}): TableAddOnReturn {
const { expanded, expandedRowComponent = ExpandedRow, onExpandedChange, ...tableParams } = options;
const stateParams = expanded
? { expanded }
: {};
const onCustomExpandedChange: ExpandSetter = useCallback((rows, expand) => {
if (onExpandedChange) {
onExpandedChange(rows, expand);
return;
}
forEach(rows, (row) => row.toggleRowExpanded(expand));
}, [onExpandedChange]);
return [
withExpanded.name,
null,
({ subRows }) => arrayHasItems(subRows),
() => useMemo((): Partial<IWithExpandedInstance> => ({
...tableParams,
expandSubRows: false,
CustomExpandedRowComponent: expandedRowComponent,
onCustomExpandedChange,
}), [expandedRowComponent, onCustomExpandedChange, ...values(tableParams)]),
() => useMemo(() => stateParams, [expanded]),
useExpanded,
];
}