ImageUpload.jsx
76 lines
| 1 | import { __ } from '@wordpress/i18n'; |
| 2 | import { BaseControl, Button, TextControl, useBaseControlProps } from '@wordpress/components'; |
| 3 | import { MediaUpload, MediaUploadCheck } from '@wordpress/block-editor'; |
| 4 | import { Stack } from '@edge22/components'; |
| 5 | import { DynamicTagModal } from '../../dynamic-tags'; |
| 6 | import './editor.scss'; |
| 7 | |
| 8 | export function ImageUpload( { |
| 9 | label = __( 'Image', 'generateblocks' ), |
| 10 | value, |
| 11 | onInsert, |
| 12 | onSelectImage, |
| 13 | showInput = true, |
| 14 | previewUrl = '', |
| 15 | allowDynamicTags = false, |
| 16 | onInsertDynamicTag, |
| 17 | context, |
| 18 | sizeSlug = null, |
| 19 | } ) { |
| 20 | const { baseControlProps, controlProps } = useBaseControlProps( { |
| 21 | label, |
| 22 | } ); |
| 23 | |
| 24 | return ( |
| 25 | <BaseControl { ...baseControlProps }> |
| 26 | <Stack |
| 27 | className="gb-image-upload-stack" |
| 28 | layout="flex" |
| 29 | direction="horizontal" |
| 30 | gap="5px" |
| 31 | wrap={ false } |
| 32 | > |
| 33 | { !! showInput && ( |
| 34 | <TextControl |
| 35 | { ...controlProps } |
| 36 | value={ value } |
| 37 | onChange={ ( newValue ) => onInsert( newValue ) } |
| 38 | style={ { marginBottom: 0 } } |
| 39 | /> |
| 40 | ) } |
| 41 | |
| 42 | { !! previewUrl && ( |
| 43 | <img |
| 44 | src={ previewUrl } |
| 45 | alt="" |
| 46 | style={ { width: 'auto', height: '32px', objectFit: 'cover' } } |
| 47 | /> |
| 48 | ) } |
| 49 | |
| 50 | <MediaUploadCheck> |
| 51 | <MediaUpload |
| 52 | onSelect={ ( media ) => onSelectImage( media, sizeSlug ) } |
| 53 | allowedTypes={ [ 'image' ] } |
| 54 | render={ ( { open } ) => ( |
| 55 | <Button |
| 56 | onClick={ open } |
| 57 | variant="secondary" |
| 58 | > |
| 59 | { __( 'Browse', 'generateblocks' ) } |
| 60 | </Button> |
| 61 | ) } |
| 62 | /> |
| 63 | </MediaUploadCheck> |
| 64 | |
| 65 | { allowDynamicTags && ( |
| 66 | <DynamicTagModal |
| 67 | onInsert={ ( newValue ) => onInsertDynamicTag( newValue ) } |
| 68 | selectedText={ value?.startsWith( '{{' ) ? value : '' } |
| 69 | context={ context } |
| 70 | /> |
| 71 | ) } |
| 72 | </Stack> |
| 73 | </BaseControl> |
| 74 | ); |
| 75 | } |
| 76 |