/** * Media Upload Component * * WordPress media library integration for uploading images * * @package ProRank\SEO * @since 1.0.0 */ import { useState, useEffect } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; import { MediaUpload as WPMediaUpload, MediaUploadCheck } from '@wordpress/block-editor'; import { Button } from '@wordpress/components'; import ProrankButton from './ProrankButton'; interface MediaUploadProps { value?: number | string; onChange: (value: number | string) => void; allowedTypes?: string[]; render?: (props: { open: () => void }) => React.ReactNode; label?: string; help?: string; multiple?: boolean; } const MediaUpload: React.FC = ({ value, onChange, allowedTypes = ['image'], render, label = __('Select Image', 'prorank-seo'), help, multiple = false }) => { const [mediaUrl, setMediaUrl] = useState(''); const [isLoading, setIsLoading] = useState(false); useEffect(() => { if (value && typeof value === 'number') { // Fetch media details if we have an ID setIsLoading(true); wp.media.attachment(value).fetch().then(() => { const attachment = wp.media.attachment(value); setMediaUrl(attachment.get('url')); setIsLoading(false); }).catch(() => { setIsLoading(false); }); } else if (typeof value === 'string') { setMediaUrl(value); } }, [value]); const onSelectMedia = (media: any) => { if (multiple && Array.isArray(media)) { // Handle multiple selection const ids = media.map(m => m.id); onChange(ids.join(',')); } else { // Single selection const singleMedia = Array.isArray(media) ? media[0] : media; onChange(singleMedia.id); setMediaUrl(singleMedia.url); } }; const onRemoveMedia = () => { onChange(''); setMediaUrl(''); }; // Use WordPress MediaUpload if available if (typeof wp !== 'undefined' && wp.media) { return (
{help &&

{help}

} ( <> {render ? ( render({ open }) ) : (
{mediaUrl && !isLoading && (
{__('Selected
)}
{mediaUrl ? __('Change Image', 'prorank-seo') : label} {mediaUrl && ( {__('Remove', 'prorank-seo')} )}
)} )} />
); } // Fallback for when WordPress MediaUpload is not available return (
{help &&

{help}

} { setMediaUrl(e.target.value); onChange(e.target.value); }} placeholder={__('Enter image URL', 'prorank-seo')} className="regular-text" style={{ marginBottom: '10px' }} /> {mediaUrl && (
{__('Selected { e.currentTarget.style.display = 'none'; }} />
)}
); }; export default MediaUpload;