gab-social/app/javascript/gabsocial/components/image.js

60 lines
1.3 KiB
JavaScript
Raw Normal View History

2020-02-19 23:57:07 +00:00
import classNames from 'classnames/bind'
// : testing :
2020-04-04 00:18:26 +01:00
// : todo :
const placeholderSource = 'https://source.unsplash.com/random'
const imageUnavailable = 'https://source.unsplash.com/random'
2020-02-19 23:57:07 +00:00
const cx = classNames.bind(_s)
export default class Image extends PureComponent {
static propTypes = {
alt: PropTypes.string,
src: PropTypes.string,
className: PropTypes.string,
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
fit: PropTypes.oneOf(['contain', 'cover', 'tile', 'none']),
2020-04-04 00:18:26 +01:00
nullable: PropTypes.bool,
2020-02-19 23:57:07 +00:00
}
static defaultProps = {
width: '100%',
fit: 'cover',
}
2020-04-04 00:18:26 +01:00
state = {
error: false,
}
handleOnError = () => {
this.setState({ error: true })
}
2020-02-19 23:57:07 +00:00
render() {
2020-04-04 00:18:26 +01:00
const { src, fit, className, nullable, ...otherProps } = this.props
const { error } = this.state
2020-02-19 23:57:07 +00:00
2020-04-04 00:18:26 +01:00
let source = src || placeholderSource
2020-02-19 23:57:07 +00:00
const classes = cx(className, {
default: 1,
objectFitCover: fit === 'cover'
})
2020-04-04 00:18:26 +01:00
//If error and not our own image
if (error && nullable) {
return null
} else if (error) {
source = imageUnavailable
}
2020-02-19 23:57:07 +00:00
return (
<img
className={classes}
{...otherProps}
src={source}
2020-04-04 00:18:26 +01:00
onError={this.handleOnError}
2020-02-19 23:57:07 +00:00
/>
)
}
}