From 8e799fac6d0699f484b44e67135afc51d979f766 Mon Sep 17 00:00:00 2001 From: Eric Koslow Date: Tue, 17 Nov 2015 14:17:43 -0800 Subject: [PATCH] Automatically set srcSet attributes This adds a new option called `generateSrcSet` which defaults to true. When enabled, the 2x and 3x srcSet attributes will be added to rendered component. Currently, the attribute will only be added if the rendered component is an `img`. --- src/index.js | 22 ++++++++++++++++++---- src/index.test.js | 13 +++++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/index.js b/src/index.js index 6ab5d705..22504789 100644 --- a/src/index.js +++ b/src/index.js @@ -35,7 +35,8 @@ export default class ReactImgix extends Component { fluid: PropTypes.bool, children: PropTypes.any, customParams: PropTypes.object, - entropy: PropTypes.bool + entropy: PropTypes.bool, + generateSrcSet: PropTypes.bool } static defaultProps = { precision: 100, @@ -45,7 +46,8 @@ export default class ReactImgix extends Component { faces: true, fit: 'crop', entropy: false, - auto: ['format'] + auto: ['format'], + generateSrcSet: true } state = { width: null, @@ -64,6 +66,7 @@ export default class ReactImgix extends Component { render () { let src = '' + let srcSet = '' let component = this.props.component let width = this._findSizeForDimension('width') @@ -78,14 +81,19 @@ export default class ReactImgix extends Component { if (this.props.fit) fit = this.props.fit if (this.state.mounted || this.props.aggresiveLoad) { - src = processImage(this.props.src, { + const srcOptions = { auto: this.props.auto, ...this.props.customParams, crop, fit, width, height - }) + } + + src = processImage(this.props.src, srcOptions) + const dpr2 = processImage(this.props.src, {...srcOptions, dpr: 2}) + const dpr3 = processImage(this.props.src, {...srcOptions, dpr: 3}) + srcSet = `${dpr2} 2x, ${dpr3} 3x` } let childProps = {...this.props} @@ -100,10 +108,16 @@ export default class ReactImgix extends Component { backgroundSize: 'cover' } delete childProps.src + delete childProps.srcSet } else { if (!this.props.component) { component = 'img' } + + if (component === 'img' && this.props.generateSrcSet) { + childProps.srcSet = srcSet + } + childProps.src = src } return React.createElement(component, diff --git a/src/index.test.js b/src/index.test.js index 11f3873c..fbd86cd9 100644 --- a/src/index.test.js +++ b/src/index.test.js @@ -118,4 +118,17 @@ describe('image props', () => { // it.skip('custom props', () => { // expect(vdom.props.src).to.include('auto=format,enhance') // }) + it('generateSrcSet prop', () => { + tree = sd.shallowRender( + + ) + vdom = tree.getRenderOutput() + + expect(vdom.props.srcSet).toInclude('dpr=2') + expect(vdom.props.srcSet).toInclude('dpr=3') + }) })