-
-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
Copy pathShowGuesser.tsx
84 lines (72 loc) · 2.29 KB
/
ShowGuesser.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
84
import * as React from 'react';
import { useEffect, useState } from 'react';
import inflection from 'inflection';
import {
ShowBase,
InferredElement,
getElementsFromRecords,
useResourceContext,
useShowContext,
} from 'ra-core';
import { ShowProps } from '../types';
import { ShowView } from './ShowView';
import { showFieldTypes } from './showFieldTypes';
export const ShowGuesser = ({
id,
queryOptions,
resource,
...rest
}: Omit<ShowProps, 'children'>) => (
<ShowBase id={id} resource={resource} queryOptions={queryOptions}>
<ShowViewGuesser {...rest} />
</ShowBase>
);
const ShowViewGuesser = props => {
const resource = useResourceContext(props);
const { record } = useShowContext();
const [child, setChild] = useState(null);
useEffect(() => {
setChild(null);
}, [resource]);
useEffect(() => {
if (record && !child) {
const inferredElements = getElementsFromRecords(
[record],
showFieldTypes
);
const inferredChild = new InferredElement(
showFieldTypes.show,
null,
inferredElements
);
setChild(inferredChild.getElement());
if (process.env.NODE_ENV === 'production') return;
const representation = inferredChild.getRepresentation();
const components = ['Show']
.concat(
Array.from(
new Set(
Array.from(representation.matchAll(/<([^/\s>]+)/g))
.map(match => match[1])
.filter(component => component !== 'span')
)
)
)
.sort();
// eslint-disable-next-line no-console
console.log(
`Guessed Show:
import { ${components.join(', ')} } from 'react-admin';
export const ${inflection.capitalize(
inflection.singularize(resource)
)}Show = () => (
<Show>
${inferredChild.getRepresentation()}
</Show>
);`
);
}
}, [record, child, resource]);
return <ShowView {...props}>{child}</ShowView>;
};
ShowViewGuesser.propTypes = ShowView.propTypes;