-
Notifications
You must be signed in to change notification settings - Fork 0
/
with-grouping.add-on.ts
78 lines (67 loc) · 2.33 KB
/
with-grouping.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { useCallback, useMemo } from 'react';
import {
Column,
IdType,
useGroupBy,
UseGroupByColumnOptions,
UseGroupByInstanceProps,
UseGroupByOptions, UseGroupByState,
} from 'react-table';
import { values } from 'lodash-es';
import { GroupSetter, IRelatableStateInstance, TableAddOnReturn } from '../relatable.types';
import { DEFAULT_AGGREGATE_OPTIONS } from '../constants';
import { ValueAggregate, ICellProps } from '../components/renderers';
export interface IWithGroupingOptions<Data extends object = any> extends UseGroupByOptions<Data> {
defaultAggregate?: string[] | string | ((values: any[]) => any);
defaultAggregateCell?: React.FC<ICellProps>;
onGroupChange?: GroupSetter<Data>;
// react-table state override https://react-table.js.org/api/useGroupBy
groupBy?: IdType<Data>[];
}
export interface IWithGroupingState<Data extends object = any> extends UseGroupByState<Data> {}
export interface IWithGroupingInstance<Data extends object = any> extends UseGroupByInstanceProps<Data>, IRelatableStateInstance<Data, IWithGroupingState<Data>>{
onCustomGroupingChange: GroupSetter<Data>;
defaultColumn: Partial<Column<Data> & UseGroupByColumnOptions<Data>>;
}
export default function withGrouping<Data extends object = any>(options: IWithGroupingOptions<Data> = {}): TableAddOnReturn {
const {
groupBy,
onGroupChange,
defaultAggregateCell,
defaultAggregate = DEFAULT_AGGREGATE_OPTIONS,
...rest
} = options;
const stateParams = groupBy
? { groupBy }
: {};
const onCustomGroupingChange: GroupSetter = useCallback((column, group) => {
if (onGroupChange) {
onGroupChange(column, group);
return;
}
column.toggleGroupBy();
}, [onGroupChange]);
const tableParams = {
...rest,
onCustomGroupingChange,
defaultColumn: {
aggregate: defaultAggregate,
Aggregated: defaultAggregateCell || ValueAggregate,
},
};
return [
withGrouping.name,
null,
({ canGroupBy }) => canGroupBy,
({ defaultColumn }) => useMemo((): Partial<IWithGroupingInstance> => ({
...tableParams,
// @ts-ignore
defaultColumn: {
...defaultColumn,
...tableParams.defaultColumn,
},
}), [onCustomGroupingChange, defaultAggregateCell, defaultAggregate, ...values(rest)]),
() => useMemo(() => stateParams, [groupBy]),
useGroupBy,
];
}