-
-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
Copy pathReferenceField.tsx
297 lines (278 loc) · 9.16 KB
/
ReferenceField.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
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
import * as React from 'react';
import { ReactNode } from 'react';
import PropTypes from 'prop-types';
import get from 'lodash/get';
import { Typography, SxProps } from '@mui/material';
import { styled } from '@mui/material/styles';
import ErrorIcon from '@mui/icons-material/Error';
import {
useReference,
UseReferenceResult,
LinkToType,
ResourceContextProvider,
RecordContextProvider,
useRecordContext,
useCreatePath,
Identifier,
useGetRecordRepresentation,
useResourceDefinition,
useTranslate,
RaRecord,
} from 'ra-core';
import { UseQueryOptions } from 'react-query';
import { LinearProgress } from '../layout';
import { Link } from '../Link';
import { FieldProps, fieldPropTypes } from './types';
import { genericMemo } from './genericMemo';
/**
* Fetch reference record, and render its representation, or delegate rendering to child component.
*
* The reference prop should be the name of one of the <Resource> components
* added as <Admin> child.
*
* @example // using recordRepresentation
* <ReferenceField label="User" source="userId" reference="users" />
*
* @example // using a Field component to represent the record
* <ReferenceField label="User" source="userId" reference="users">
* <TextField source="name" />
* </ReferenceField>
*
* @example // By default, includes a link to the <Edit> page of the related record
* // (`/users/:userId` in the previous example).
* // Set the `link` prop to "show" to link to the <Show> page instead.
* <ReferenceField label="User" source="userId" reference="users" link="show" />
*
* @example // You can also prevent `<ReferenceField>` from adding link to children
* // by setting `link` to false.
* <ReferenceField label="User" source="userId" reference="users" link={false} />
*
* @example // Alternatively, you can also pass a custom function to `link`.
* // It must take reference and record as arguments and return a string
* <ReferenceField label="User" source="userId" reference="users" link={(record, reference) => "/path/to/${reference}/${record}"} />
*
* @default
* In previous versions of React-Admin, the prop `linkType` was used. It is now deprecated and replaced with `link`. However
* backward-compatibility is still kept
*/
export const ReferenceField = <
RecordType extends Record<string, any> = Record<string, any>,
ReferenceRecordType extends RaRecord = RaRecord
>(
props: ReferenceFieldProps<RecordType, ReferenceRecordType>
) => {
const { source, emptyText, link = 'edit', ...rest } = props;
const record = useRecordContext<RecordType>(props);
const id = get(record, source);
const translate = useTranslate();
return id == null ? (
emptyText ? (
<Typography component="span" variant="body2">
{emptyText && translate(emptyText, { _: emptyText })}
</Typography>
) : null
) : (
<NonEmptyReferenceField<RecordType, ReferenceRecordType>
{...rest}
link={link}
emptyText={emptyText}
record={record}
id={id as Identifier}
/>
);
};
ReferenceField.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
cellClassName: PropTypes.string,
headerClassName: PropTypes.string,
label: fieldPropTypes.label,
record: PropTypes.any,
reference: PropTypes.string.isRequired,
resource: PropTypes.string,
sortBy: PropTypes.string,
sortByOrder: fieldPropTypes.sortByOrder,
source: PropTypes.string.isRequired,
translateChoice: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]),
// @ts-ignore
link: PropTypes.oneOfType([
PropTypes.string,
PropTypes.bool,
PropTypes.func,
]),
};
export interface ReferenceFieldProps<
RecordType extends Record<string, any> = Record<string, any>,
ReferenceRecordType extends RaRecord = RaRecord
> extends Omit<FieldProps<RecordType>, 'source'>,
Required<Pick<FieldProps<RecordType>, 'source'>> {
children?: ReactNode;
queryOptions?: UseQueryOptions<ReferenceRecordType[], Error> & {
meta?: any;
};
reference: string;
translateChoice?: Function | boolean;
link?: LinkToType<ReferenceRecordType>;
sx?: SxProps;
}
/**
* This intermediate component is made necessary by the useReference hook,
* which cannot be called conditionally when get(record, source) is empty.
*/
export const NonEmptyReferenceField = <
RecordType extends Record<string, any> = Record<string, any>,
ReferenceRecordType extends RaRecord = RaRecord
>({
children,
id,
reference,
queryOptions,
link,
...props
}: Omit<ReferenceFieldProps<RecordType, ReferenceRecordType>, 'source'> & {
id: Identifier;
}) => {
return (
<ResourceContextProvider value={reference}>
{/* @ts-ignore */}
<PureReferenceFieldView<RecordType, ReferenceRecordType>
reference={reference}
{...props}
{...useReference<ReferenceRecordType>({
reference,
id,
options: queryOptions,
})}
resourceLinkPath={link}
>
{children}
</PureReferenceFieldView>
</ResourceContextProvider>
);
};
// useful to prevent click bubbling in a datagrid with rowClick
const stopPropagation = e => e.stopPropagation();
export const ReferenceFieldView = <
RecordType extends Record<string, any> = Record<string, any>
>(
props: ReferenceFieldViewProps<RecordType>
) => {
const {
children,
className,
emptyText,
error,
isLoading,
reference,
referenceRecord,
resourceLinkPath,
sx,
} = props;
const getRecordRepresentation = useGetRecordRepresentation(reference);
const translate = useTranslate();
const createPath = useCreatePath();
const resourceDefinition = useResourceDefinition({ resource: reference });
if (error) {
return (
/* eslint-disable jsx-a11y/role-supports-aria-props */
<ErrorIcon
aria-errormessage={error.message ? error.message : error}
role="presentation"
color="error"
fontSize="small"
/>
/* eslint-enable */
);
}
if (isLoading) {
return <LinearProgress />;
}
if (!referenceRecord) {
return emptyText ? (
<>{emptyText && translate(emptyText, { _: emptyText })}</>
) : null;
}
const link =
resourceLinkPath === false ||
(resourceLinkPath === 'edit' && !resourceDefinition.hasEdit) ||
(resourceLinkPath === 'show' && !resourceDefinition.hasShow)
? false
: createPath({
resource: reference,
id: referenceRecord.id,
type:
typeof resourceLinkPath === 'function'
? resourceLinkPath(referenceRecord, reference)
: resourceLinkPath,
});
let child = children || (
<Typography component="span" variant="body2">
{getRecordRepresentation(referenceRecord)}
</Typography>
);
if (link) {
return (
<Root className={className} sx={sx}>
<RecordContextProvider value={referenceRecord}>
<Link
to={link}
className={ReferenceFieldClasses.link}
onClick={stopPropagation}
>
{child}
</Link>
</RecordContextProvider>
</Root>
);
}
return (
<RecordContextProvider value={referenceRecord}>
{child}
</RecordContextProvider>
);
};
ReferenceFieldView.propTypes = {
children: PropTypes.element,
className: PropTypes.string,
isLoading: PropTypes.bool,
record: PropTypes.any,
reference: PropTypes.string,
referenceRecord: PropTypes.any,
resource: PropTypes.string,
// @ts-ignore
resourceLinkPath: PropTypes.oneOfType([
PropTypes.string,
PropTypes.bool,
PropTypes.func,
]).isRequired,
source: PropTypes.string,
translateChoice: PropTypes.oneOfType([PropTypes.func, PropTypes.bool]),
};
export interface ReferenceFieldViewProps<
RecordType extends Record<string, any> = Record<string, any>,
ReferenceRecordType extends RaRecord = RaRecord
> extends FieldProps<RecordType>,
UseReferenceResult {
children?: ReactNode;
reference: string;
resource?: string;
translateChoice?: Function | boolean;
resourceLinkPath?: LinkToType<ReferenceRecordType>;
sx?: SxProps;
}
const PureReferenceFieldView = genericMemo(ReferenceFieldView);
const PREFIX = 'RaReferenceField';
export const ReferenceFieldClasses = {
link: `${PREFIX}-link`,
};
const Root = styled('span', {
name: PREFIX,
overridesResolver: (props, styles) => styles.root,
})(({ theme }) => ({
lineHeight: 'initial',
[`& .${ReferenceFieldClasses.link}`]: {
'& > *': {
color: theme.palette.primary.main,
},
},
}));