index.js
68 lines
| 1 | /** |
| 2 | * Vendor dependencies |
| 3 | */ |
| 4 | import PropTypes from 'prop-types'; |
| 5 | |
| 6 | /** |
| 7 | * WordPress dependencies |
| 8 | */ |
| 9 | const { useInstanceId } = wp.compose; |
| 10 | const { BaseControl, Button } = wp.components; |
| 11 | const { MediaUpload } = wp.blockEditor; |
| 12 | const { __ } = wp.i18n; |
| 13 | |
| 14 | const ImageControl = ( { name, label, help, className, value, hideLabelFromVision, onChange } ) => { |
| 15 | const instanceId = useInstanceId( ImageControl ); |
| 16 | const id = `give-image-control-${ name }-${ instanceId }`; |
| 17 | return ( |
| 18 | <BaseControl |
| 19 | label={ label } |
| 20 | hideLabelFromVision={ hideLabelFromVision } |
| 21 | id={ id } |
| 22 | help={ help } |
| 23 | className={ className } |
| 24 | > |
| 25 | <MediaUpload |
| 26 | allowedTypes={ [ 'image' ] } |
| 27 | onSelect={ ( media ) => onChange( media.sizes.full.url ) } |
| 28 | render={ ( { open } ) => { |
| 29 | return value ? ( |
| 30 | <div> |
| 31 | <img src={ value } onClick={ open } style={ { cursor: 'pointer' } } /> |
| 32 | <Button isPrimary isSmall onClick={ open } id={ id }> |
| 33 | { __( 'Change Image', 'give' ) } |
| 34 | </Button> |
| 35 | <Button isSecondary isSmall onClick={ () => onChange( '' ) } id={ id }> |
| 36 | { __( 'Remove Image', 'give' ) } |
| 37 | </Button> |
| 38 | </div> |
| 39 | ) : ( |
| 40 | <div> |
| 41 | <Button isPrimary onClick={ open } id={ id }> |
| 42 | { __( 'Select an Image', 'give' ) } |
| 43 | </Button> |
| 44 | </div> |
| 45 | ); |
| 46 | } } |
| 47 | /> |
| 48 | </BaseControl> |
| 49 | ); |
| 50 | }; |
| 51 | |
| 52 | ImageControl.propTypes = { |
| 53 | label: PropTypes.string, |
| 54 | value: PropTypes.any.isRequired, |
| 55 | onChange: PropTypes.func, |
| 56 | name: PropTypes.string.isRequired, |
| 57 | help: PropTypes.string, |
| 58 | className: PropTypes.string, |
| 59 | hideLabelFromVision: PropTypes.bool, |
| 60 | }; |
| 61 | |
| 62 | ImageControl.defaultProps = { |
| 63 | onChange: null, |
| 64 | options: null, |
| 65 | }; |
| 66 | |
| 67 | export default ImageControl; |
| 68 |