-
-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
ImageField.tsx
112 lines (100 loc) · 2.94 KB
/
ImageField.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
import * as React from 'react';
import { FC } from 'react';
import PropTypes from 'prop-types';
import get from 'lodash/get';
import { makeStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import classnames from 'classnames';
import sanitizeFieldRestProps from './sanitizeFieldRestProps';
import { PublicFieldProps, InjectedFieldProps, fieldPropTypes } from './types';
const useStyles = makeStyles(
{
list: {
display: 'flex',
listStyleType: 'none',
},
image: {
margin: '0.5rem',
maxHeight: '10rem',
},
},
{ name: 'RaImageField' }
);
export interface ImageFieldProps extends PublicFieldProps, InjectedFieldProps {
src?: string;
title?: string;
classes?: object;
}
const ImageField: FC<ImageFieldProps> = props => {
const {
className,
classes: classesOverride,
emptyText,
record,
source,
src,
title,
...rest
} = props;
const sourceValue = get(record, source);
const classes = useStyles(props);
if (!sourceValue) {
return emptyText ? (
<Typography
component="span"
variant="body2"
className={className}
{...sanitizeFieldRestProps(rest)}
>
{emptyText}
</Typography>
) : (
<div className={className} {...sanitizeFieldRestProps(rest)} />
);
}
if (Array.isArray(sourceValue)) {
return (
<ul
className={classnames(classes.list, className)}
{...sanitizeFieldRestProps(rest)}
>
{sourceValue.map((file, index) => {
const fileTitleValue = get(file, title) || title;
const srcValue = get(file, src) || title;
return (
<li key={index}>
<img
alt={fileTitleValue}
title={fileTitleValue}
src={srcValue}
className={classes.image}
/>
</li>
);
})}
</ul>
);
}
const titleValue = get(record, title) || title;
return (
<div className={className} {...sanitizeFieldRestProps(rest)}>
<img
title={titleValue}
alt={titleValue}
src={sourceValue}
className={classes.image}
/>
</div>
);
};
// What? TypeScript loses the displayName if we don't set it explicitly
ImageField.displayName = 'ImageField';
ImageField.defaultProps = {
addLabel: true,
};
ImageField.propTypes = {
...fieldPropTypes,
src: PropTypes.string,
title: PropTypes.string,
};
export default ImageField;