/
useListController.ts
480 lines (453 loc) · 14.2 KB
/
useListController.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
import { isValidElement, useEffect, useMemo } from 'react';
import { UseQueryOptions } from 'react-query';
import { useAuthenticated } from '../../auth';
import { useTranslate } from '../../i18n';
import { useNotify } from '../../notification';
import { useGetList, UseGetListHookValue } from '../../dataProvider';
import { SORT_ASC } from './queryReducer';
import { defaultExporter } from '../../export';
import { FilterPayload, SortPayload, RaRecord, Exporter } from '../../types';
import { useResourceContext, useGetResourceLabel } from '../../core';
import { useRecordSelection } from './useRecordSelection';
import { useListParams } from './useListParams';
/**
* Prepare data for the List view
*
* @param {Object} props The props passed to the List component.
*
* @return {Object} controllerProps Fetched and computed data for the List view
*
* @example
*
* import { useListController } from 'react-admin';
* import ListView from './ListView';
*
* const MyList = props => {
* const controllerProps = useListController(props);
* return <ListView {...controllerProps} {...props} />;
* }
*/
export const useListController = <RecordType extends RaRecord = any>(
props: ListControllerProps<RecordType> = {}
): ListControllerResult<RecordType> => {
const {
debounce = 500,
disableAuthentication,
disableSyncWithLocation,
exporter = defaultExporter,
filter,
filterDefaultValues,
perPage = 10,
queryOptions = {},
sort = defaultSort,
storeKey,
} = props;
useAuthenticated({ enabled: !disableAuthentication });
const resource = useResourceContext(props);
const { meta, ...otherQueryOptions } = queryOptions;
if (!resource) {
throw new Error(
`<List> was called outside of a ResourceContext and without a resource prop. You must set the resource prop.`
);
}
if (filter && isValidElement(filter)) {
throw new Error(
'<List> received a React element as `filter` props. If you intended to set the list filter elements, use the `filters` (with an s) prop instead. The `filter` prop is internal and should not be set by the developer.'
);
}
const translate = useTranslate();
const notify = useNotify();
const [query, queryModifiers] = useListParams({
debounce,
disableSyncWithLocation,
filterDefaultValues,
perPage,
resource,
sort,
storeKey,
});
const [selectedIds, selectionModifiers] = useRecordSelection(resource);
const {
data,
pageInfo,
total,
error,
isLoading,
isFetching,
refetch,
} = useGetList<RecordType>(
resource,
{
pagination: {
page: query.page,
perPage: query.perPage,
},
sort: { field: query.sort, order: query.order },
filter: { ...query.filter, ...filter },
meta,
},
{
keepPreviousData: true,
retry: false,
onError: error =>
notify(error?.message || 'ra.notification.http_error', {
type: 'error',
messageArgs: {
_: error?.message,
},
}),
...otherQueryOptions,
}
);
// change page if there is no data
useEffect(() => {
if (
query.page <= 0 ||
(!isFetching &&
query.page > 1 &&
(data == null || data?.length === 0))
) {
// Query for a page that doesn't exist, set page to 1
queryModifiers.setPage(1);
return;
}
if (total == null) {
return;
}
const totalPages = Math.ceil(total / query.perPage) || 1;
if (!isFetching && query.page > totalPages) {
// Query for a page out of bounds, set page to the last existing page
// It occurs when deleting the last element of the last page
queryModifiers.setPage(totalPages);
}
}, [isFetching, query.page, query.perPage, data, queryModifiers, total]);
const currentSort = useMemo(
() => ({
field: query.sort,
order: query.order,
}),
[query.sort, query.order]
);
const getResourceLabel = useGetResourceLabel();
const defaultTitle = translate('ra.page.list', {
name: getResourceLabel(resource, 2),
});
return {
sort: currentSort,
data,
defaultTitle,
displayedFilters: query.displayedFilters,
error,
exporter,
filter,
filterValues: query.filterValues,
hideFilter: queryModifiers.hideFilter,
isFetching,
isLoading,
onSelect: selectionModifiers.select,
onToggleItem: selectionModifiers.toggle,
onUnselectItems: selectionModifiers.clearSelection,
page: query.page,
perPage: query.perPage,
refetch,
resource,
selectedIds,
setFilters: queryModifiers.setFilters,
setPage: queryModifiers.setPage,
setPerPage: queryModifiers.setPerPage,
setSort: queryModifiers.setSort,
showFilter: queryModifiers.showFilter,
total: total,
hasNextPage: pageInfo
? pageInfo.hasNextPage
: total != null
? query.page * query.perPage < total
: undefined,
hasPreviousPage: pageInfo ? pageInfo.hasPreviousPage : query.page > 1,
};
};
export interface ListControllerProps<RecordType extends RaRecord = any> {
/**
* The debounce delay for filter queries in milliseconds. Defaults to 500ms.
*
* @see https://marmelab.com/react-admin/List.html#debounce
* @example
* // wait 1 seconds instead of 500 milliseconds befoce calling the dataProvider
* const PostList = () => (
* <List debounce={1000}>
* ...
* </List>
* );
*/
debounce?: number;
/**
* Allow anonymous access to the list view. Defaults to false.
*
* @see https://marmelab.com/react-admin/List.html#disableauthentication
* @example
* import { List } from 'react-admin';
*
* const BoolkList = () => (
* <List disableAuthentication>
* ...
* </List>
* );
*/
disableAuthentication?: boolean;
/**
* Whether to disable the synchronization of the list parameters with the current location (URL search parameters)
*
* @see https://marmelab.com/react-admin/List.html#disablesyncwithlocation
* @example
* const Dashboard = () => (
* <div>
* // ...
* <ResourceContextProvider value="posts">
* <List disableSyncWithLocation>
* <SimpleList
* primaryText={record => record.title}
* secondaryText={record => `${record.views} views`}
* tertiaryText={record => new Date(record.published_at).toLocaleDateString()}
* />
* </List>
* </ResourceContextProvider>
* <ResourceContextProvider value="comments">
* <List disableSyncWithLocation>
* <SimpleList
* primaryText={record => record.title}
* secondaryText={record => `${record.views} views`}
* tertiaryText={record => new Date(record.published_at).toLocaleDateString()}
* />
* </List>
* </ResourceContextProvider>
* </div>
* )
*/
disableSyncWithLocation?: boolean;
/**
* The function called when a user exports the list
*
* @see https://marmelab.com/react-admin/List.html#exporter
* @example
* import { List, downloadCSV } from 'react-admin';
* import jsonExport from 'jsonexport/dist';
*
* const exporter = posts => {
* const postsForExport = posts.map(post => {
* const { backLinks, author, ...postForExport } = post; // omit backLinks and author
* postForExport.author_name = post.author.name; // add a field
* return postForExport;
* });
* jsonExport(postsForExport, {
* headers: ['id', 'title', 'author_name', 'body'] // order fields in the export
* }, (err, csv) => {
* downloadCSV(csv, 'posts'); // download as 'posts.csv` file
* });
* };
*
* const PostList = () => (
* <List exporter={exporter}>
* ...
* </List>
* )
*/
exporter?: Exporter | false;
/**
* Permanent filter applied to all getList queries, regardless of the user selected filters.
*
* @see https://marmelab.com/react-admin/List.html#filter
* @example
* export const PostList = () => (
* <List filter={{ is_published: true }}>
* ...
* </List>
* );
*/
filter?: FilterPayload;
/**
* The filter to apply when calling getList if the filter is empty.
*
* @see https://marmelab.com/react-admin/List.html#filterdefaultvalues
* @example
* const postFilters = [
* <TextInput label="Search" source="q" alwaysOn />,
* <BooleanInput source="is_published" alwaysOn />,
* <TextInput source="title" defaultValue="Hello, World!" />,
* ];
*
* export const PostList = () => (
* <List filters={postFilters} filterDefaultValues={{ is_published: true }}>
* ...
* </List>
* );
*/
filterDefaultValues?: object;
/**
* The number of results per page. Defaults to 10.
*
* @see https://marmelab.com/react-admin/List.html#perpage
* @example
* export const PostList = () => (
* <List perPage={25}>
* ...
* </List>
* );
*/
perPage?: number;
/**
* The options passed to react-query's useQuery when calling getList.
*
* @see https://marmelab.com/react-admin/List.html#queryoptions
* @example
* import { useNotify, useRedirect, List } from 'react-admin';
*
* const PostList = () => {
* const notify = useNotify();
* const redirect = useRedirect();
*
* const onError = (error) => {
* notify(`Could not load list: ${error.message}`, { type: 'error' });
* redirect('/dashboard');
* };
*
* return (
* <List queryOptions={{ onError }}>
* ...
* </List>
* );
* }
*/
queryOptions?: UseQueryOptions<{
data: RecordType[];
total?: number;
pageInfo?: {
hasNextPage?: boolean;
hasPreviousPage?: boolean;
};
}> & { meta?: any };
/**
* The resource name. Defaults to the resource from ResourceContext.
*
* @see https://marmelab.com/react-admin/List.html#resource
* @example
* import { List } from 'react-admin';
*
* const PostList = () => (
* <List resource="posts">
* ...
* </List>
* );
*/
resource?: string;
/**
* The default sort field and order. Defaults to { field: 'id', order: 'ASC' }.
*
* @see https://marmelab.com/react-admin/List.html#sort
* @example
* export const PostList = () => (
* <List sort={{ field: 'published_at', order: 'DESC' }}>
* ...
* </List>
* );
*/
sort?: SortPayload;
/**
* The key to use to store the current filter & sort. Pass false to disable.
*
* @see https://marmelab.com/react-admin/List.html#storekey
* @example
* const NewerBooks = () => (
* <List
* resource="books"
* storeKey="newerBooks"
* sort={{ field: 'year', order: 'DESC' }}
* >
* ...
* </List>
* );
*/
storeKey?: string | false;
}
const defaultSort = {
field: 'id',
order: SORT_ASC,
} as const;
export interface ListControllerResult<RecordType extends RaRecord = any> {
sort: SortPayload;
data: RecordType[];
defaultTitle?: string;
displayedFilters: any;
error?: any;
exporter?: Exporter | false;
filter?: FilterPayload;
filterValues: any;
hideFilter: (filterName: string) => void;
isFetching: boolean;
isLoading: boolean;
onSelect: (ids: RecordType['id'][]) => void;
onToggleItem: (id: RecordType['id']) => void;
onUnselectItems: () => void;
page: number;
perPage: number;
refetch: (() => void) | UseGetListHookValue<RecordType>['refetch'];
resource: string;
selectedIds: RecordType['id'][];
setFilters: (
filters: any,
displayedFilters: any,
debounce?: boolean
) => void;
setPage: (page: number) => void;
setPerPage: (page: number) => void;
setSort: (sort: SortPayload) => void;
showFilter: (filterName: string, defaultValue: any) => void;
total: number;
hasNextPage: boolean;
hasPreviousPage: boolean;
}
export const injectedProps = [
'sort',
'data',
'defaultTitle',
'displayedFilters',
'error',
'exporter',
'filterValues',
'hasNextPage',
'hasPreviousPage',
'hideFilter',
'isFetching',
'isLoading',
'onSelect',
'onToggleItem',
'onUnselectItems',
'page',
'perPage',
'refetch',
'refresh',
'resource',
'selectedIds',
'setFilters',
'setPage',
'setPerPage',
'setSort',
'showFilter',
'total',
'totalPages',
];
/**
* Select the props injected by the useListController hook
* to be passed to the List children need
* This is an implementation of pick()
*/
export const getListControllerProps = props =>
injectedProps.reduce((acc, key) => ({ ...acc, [key]: props[key] }), {});
/**
* Select the props not injected by the useListController hook
* to be used inside the List children to sanitize props injected by List
* This is an implementation of omit()
*/
export const sanitizeListRestProps = props =>
Object.keys(props)
.filter(propName => !injectedProps.includes(propName))
.reduce((acc, key) => ({ ...acc, [key]: props[key] }), {});