import {useState, useEffect} from '@wordpress/element'; import {__} from '@wordpress/i18n'; import Button from '../components/Button'; import '../scss/_image_upload.scss'; const ImageUploadField = ( {field, value, onChange} ) => { const [previewUrl, setPreviewUrl] = useState( '' ); const [isLoading, setIsLoading] = useState( false ); useEffect( () => { const imageId = parseInt( value, 10 ); if ( imageId && imageId > 0 ) { setIsLoading( true ); wp.apiFetch( {path: `/wp/v2/media/${imageId}`} ) .then( media => { const thumbnailUrl = media.media_details?.sizes?.thumbnail?.source_url || media.source_url; setPreviewUrl( thumbnailUrl ); } ) .catch( error => { console.error( 'Could not fetch image preview:', error ); setPreviewUrl( '' ); } ) .finally( () => { setIsLoading( false ); } ); } else { setPreviewUrl( '' ); } }, [value] ); const openMediaLibrary = () => { const frame = wp.media( { title: __( 'Select Image', 'adpresso' ), button: {text: __( 'Use this image', 'adpresso' )}, multiple: false } ); frame.on( 'select', () => { const attachment = frame.state().get( 'selection' ).first().toJSON(); onChange( field.id, attachment.id ); } ); frame.open(); }; return (