/** * Post grid featured image. */ import get from 'lodash/get'; import classnames from 'classnames'; const { __ } = wp.i18n; const { Fragment, Component } = wp.element; const { Placeholder, Dashicon } = wp.components; export default class PostGridImage extends Component { constructor( props ) { super( ...arguments ); this.state = { imageUrl: '', imageLoaded: false, } } componentDidUpdate( prevProps ) { if ( this.props.imgSize !== prevProps.imgSize ) { this.setImageUrl(); } } componentDidMount() { /** * Set the image URL on load and when state changes. */ wp.data.subscribe( () => { this.setImageUrl(); } ); } setImageUrl() { let imageUrl = this.getImageUrl(); if ( ! imageUrl ) { imageUrl = this.getFullImageSize(); } if ( imageUrl ) { this.setState( { imageUrl, imageLoaded: true, } ); } } getImageUrl() { return ( get( /* getMedia accepts an image id and returns an object with all the image data. */ wp.data.select( 'core' ).getMedia( this.props.imgID ), [ 'media_details', 'sizes', this.props.imgSize, /* Get the image slug from the inspector. */ 'source_url' /* Return the url of the image size. */ ], /* A default image url can be passed here. */ ) ); } /* Get the full image size value as a placeholder. */ getFullImageSize() { return ( get( /* getMedia accepts an image id and returns an object with all the image data. */ wp.data.select( 'core' ).getMedia( this.props.imgID ), [ 'media_details', 'sizes', 'full', /* Get the full image size. */ 'source_url' /* Return the url of the full image size. */ ], ) ); } render() { return (
{ { /* If we don't have the selected image size, show a warning */ ( ! this.getImageUrl() && this.state.imageLoaded && this.props.imgSize !== 'selectimage' ) &&
{ __( 'There is no image generated for the selected image size, so a fallback image size is being used.', 'atomic-blocks' ) }
}
); } }