-
-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
ListGuesser.tsx
83 lines (75 loc) · 2.45 KB
/
ListGuesser.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
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
import * as React from 'react';
import { useState, useEffect } from 'react';
import inflection from 'inflection';
import {
useListController,
getElementsFromRecords,
InferredElement,
ListContextProvider,
useResourceContext,
} from 'ra-core';
import ListView, { ListViewProps } from './ListView';
import listFieldTypes from './listFieldTypes';
import { ListProps } from '../types';
/**
* List component rendering a <Datagrid> based on the result of the
* dataProvider.getList() call.
*
* The result (choice and type of columns) isn't configurable, but the
* <ListGuesser> outputs the <Datagrid> it has guessed to the console so that
* developers can start from there.
*
* To be used as the list prop of a <Resource>.
*
* @example
*
* import { Admin, Resource, ListGuesser } from 'react-admin';
*
* const App = () => (
* <Admin dataProvider={myDataProvider}>
* <Resource name="posts" list={ListGuesser} />
* </Admin>
* );
*/
const ListGuesser = (props: ListProps) => {
const controllerProps = useListController(props);
return (
<ListContextProvider value={controllerProps}>
<ListViewGuesser {...props} {...controllerProps} />
</ListContextProvider>
);
};
const ListViewGuesser = (props: Omit<ListViewProps, 'children'>) => {
const { ids, data } = props;
const resource = useResourceContext(props);
const [inferredChild, setInferredChild] = useState(null);
useEffect(() => {
if (ids.length > 0 && data && !inferredChild) {
const inferredElements = getElementsFromRecords(
ids.map(id => data[id]),
listFieldTypes
);
const inferredChild = new InferredElement(
listFieldTypes.table,
null,
inferredElements
);
process.env.NODE_ENV !== 'production' &&
// eslint-disable-next-line no-console
console.log(
`Guessed List:
export const ${inflection.capitalize(
inflection.singularize(resource)
)}List = props => (
<List {...props}>
${inferredChild.getRepresentation()}
</List>
);`
);
setInferredChild(inferredChild.getElement());
}
}, [data, ids, inferredChild, resource]);
return <ListView {...props}>{inferredChild}</ListView>;
};
ListViewGuesser.propTypes = ListView.propTypes;
export default ListGuesser;