This repository has been archived by the owner on Apr 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
scope-appropriate-image.js
80 lines (71 loc) · 2.25 KB
/
scope-appropriate-image.js
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
import React from 'react';
import PropTypes from 'prop-types';
import survey from '@mapbox/react-simple-surveyor';
import getAppropriateImageUrl from '@mapbox/appropriate-images-get-url';
function scopeAppropriateImage(imageConfig, options) {
options = options || {};
const transformUrl = options.transformUrl !== undefined
? options.transformUrl
: x => x;
const hiResRatio = options.hiResRatio !== undefined
? options.hiResRatio
: 1.3;
class AppropriateImage extends React.PureComponent {
render() {
let url = getAppropriateImageUrl({
imageId: this.props.imageId,
availableWidth: this.props.width,
imageConfig,
hiResRatio
});
url = transformUrl(url);
const elementProps = Object.keys(this.props).reduce((result, key) => {
// All prop types we don't want to pass to the element should fail this condition.
if (
!/^(imageId|width|background|backgroundPosition|backgroundSize)$/.test(
key
)
) {
result[key] = this.props[key];
}
return result;
}, {});
if (!this.props.background) {
return <img src={url} {...elementProps} />;
}
const backgroundStyle = {
backgroundImage: `url("${url}")`,
backgroundRepeat: 'no-repeat',
backgroundPosition: this.props.backgroundPosition,
backgroundSize: this.props.backgroundSize,
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0
};
if (elementProps.style) {
Object.keys(elementProps.style).forEach(key => {
backgroundStyle[key] = elementProps.style[key];
});
delete elementProps.style;
}
return <div {...this.props.imageProps} style={backgroundStyle} />;
}
}
AppropriateImage.propTypes = {
imageId: PropTypes.string.isRequired,
background: PropTypes.bool,
backgroundPosition: PropTypes.string,
backgroundSize: PropTypes.string,
// Provided by survey
width: PropTypes.number.isRequired
};
AppropriateImage.defaultProps = {
background: false,
backgroundPosition: 'center center',
backgroundSize: 'cover'
};
return survey(AppropriateImage);
}
export { scopeAppropriateImage };