-
-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
Copy pathuseReferenceInputController.ts
259 lines (244 loc) · 7.16 KB
/
useReferenceInputController.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import { useCallback } from 'react';
import useGetList from '../../dataProvider/useGetList';
import { getStatusForInput as getDataStatus } from './referenceDataStatus';
import useTranslate from '../../i18n/useTranslate';
import {
PaginationPayload,
Record,
RecordMap,
Identifier,
SortPayload,
} from '../../types';
import { ListControllerProps } from '../useListController';
import useReference from '../useReference';
import usePaginationState from '../usePaginationState';
import { useSortState } from '..';
import useFilterState from '../useFilterState';
import useSelectionState from '../useSelectionState';
import { useResourceContext } from '../../core';
const defaultReferenceSource = (resource: string, source: string) =>
`${resource}@${source}`;
const defaultFilter = {};
/**
* A hook for choosing a reference record. Useful for foreign keys.
*
* This hook fetches the possible values in the reference resource
* (using `dataProvider.getMatching()`), it returns the possible choices
* as the `choices` attribute.
*
* @example
* const {
* choices, // the available reference resource
* } = useReferenceInputController({
* input, // the input props
* resource: 'comments',
* reference: 'posts',
* source: 'post_id',
* });
*
* The hook also allow to filter results. It returns a `setFilter`
* function. It uses the value to create a filter
* for the query - by default { q: [searchText] }. You can customize the mapping
* searchText => searchQuery by setting a custom `filterToQuery` function option
* You can also add a permanentFilter to further filter the result:
*
* @example
* const {
* choices, // the available reference resource
* setFilter,
* } = useReferenceInputController({
* input, // the input props
* resource: 'comments',
* reference: 'posts',
* source: 'post_id',
* permanentFilter: {
* author: 'john'
* },
* filterToQuery: searchText => ({ title: searchText })
* });
*/
export const useReferenceInputController = (
props: Option
): ReferenceInputValue => {
const {
basePath,
input,
page: initialPage = 1,
perPage: initialPerPage = 25,
filter = defaultFilter,
reference,
filterToQuery,
// @deprecated
referenceSource = defaultReferenceSource,
sort: sortOverride,
source,
} = props;
const { resource } = useResourceContext(props);
const translate = useTranslate();
// pagination logic
const {
pagination,
setPagination,
page,
setPage,
perPage,
setPerPage,
} = usePaginationState({ page: initialPage, perPage: initialPerPage });
// sort logic
const { sort, setSort: setSortObject } = useSortState(sortOverride);
const setSort = useCallback(
(field: string, order: string = 'ASC') => {
setSortObject({ field, order });
setPage(1);
},
[setPage, setSortObject]
);
// filter logic
const { filter: filterValues, setFilter } = useFilterState({
permanentFilter: filter,
filterToQuery,
});
const displayedFilters = [];
// plus showFilter and hideFilter defined outside of the hook because
// they never change
// selection logic
const {
selectedIds,
onSelect,
onToggleItem,
onUnselectItems,
} = useSelectionState();
// fetch possible values
const {
ids: possibleValuesIds,
data: possibleValuesData,
total: possibleValuesTotal,
loaded: possibleValuesLoaded,
loading: possibleValuesLoading,
error: possibleValuesError,
} = useGetList(reference, pagination, sort, filterValues);
// fetch current value
const {
referenceRecord,
error: referenceError,
loading: referenceLoading,
loaded: referenceLoaded,
} = useReference({
id: input.value,
reference,
});
// add current value to possible sources
let finalIds: Identifier[],
finalData: RecordMap<Record>,
finalTotal: number;
if (!referenceRecord || possibleValuesIds.includes(input.value)) {
finalIds = possibleValuesIds;
finalData = possibleValuesData;
finalTotal = possibleValuesTotal;
} else {
finalIds = [input.value, ...possibleValuesIds];
finalData = { [input.value]: referenceRecord, ...possibleValuesData };
finalTotal += 1;
}
// overall status
const dataStatus = getDataStatus({
input,
matchingReferences: Object.keys(finalData).map(id => finalData[id]),
referenceRecord,
translate,
});
return {
// should match the ListContext shape
possibleValues: {
basePath,
data: finalData,
ids: finalIds,
total: finalTotal,
error: possibleValuesError,
loaded: possibleValuesLoaded,
loading: possibleValuesLoading,
hasCreate: false,
page,
setPage,
perPage,
setPerPage,
currentSort: sort,
setSort,
filterValues,
displayedFilters,
setFilters: setFilter,
showFilter,
hideFilter,
selectedIds,
onSelect,
onToggleItem,
onUnselectItems,
resource,
},
referenceRecord: {
data: referenceRecord,
loaded: referenceLoaded,
loading: referenceLoading,
error: referenceError,
},
dataStatus: {
error: dataStatus.error,
loading: dataStatus.waiting,
warning: dataStatus.warning,
},
choices: Object.keys(finalData).map(id => finalData[id]),
// kept for backwards compatibility
// @deprecated to be removed in 4.0
error: dataStatus.error,
loading: dataStatus.waiting,
filter: filterValues,
setFilter,
pagination,
setPagination,
sort,
setSort: setSortObject,
warning: dataStatus.warning,
};
};
const hideFilter = () => {};
const showFilter = () => {};
export interface ReferenceInputValue {
possibleValues: ListControllerProps;
referenceRecord: {
data?: Record;
loaded: boolean;
loading: boolean;
error?: any;
};
dataStatus: {
error?: any;
loading: boolean;
warning?: string;
};
choices: Record[];
error?: string;
loading: boolean;
pagination: PaginationPayload;
setFilter: (filter: string) => void;
filter: any;
setPagination: (pagination: PaginationPayload) => void;
setSort: (sort: SortPayload) => void;
sort: SortPayload;
warning?: string;
}
interface Option {
allowEmpty?: boolean;
basePath?: string;
filter?: any;
filterToQuery?: (filter: string) => any;
input?: any;
page?: number;
perPage?: number;
record?: Record;
reference: string;
// @deprecated ignored
referenceSource?: typeof defaultReferenceSource;
resource?: string;
sort?: SortPayload;
source: string;
}