/** * Media image field — a labeled control that opens the native WordPress Media * Library (`wp.media`, enqueued on this page via wp_enqueue_media()) to pick a * single image, showing a thumbnail preview with Replace / Remove actions. * * Stores the chosen attachment id and its URL through one `onChange( id, url )` * callback so the caller can persist the id (authoritative) and reuse the URL * for the preview thumbnail without a round-trip. */ import { __ } from '@wordpress/i18n'; import { BaseControl, Button } from '@wordpress/components'; import { ImagePlus, Trash2 } from '../icons'; interface MediaAttachment { id: number; url: string; sizes?: { thumbnail?: { url?: string }; medium?: { url?: string } }; } interface MediaFrame { open: () => void; on: ( event: string, callback: () => void ) => void; state: () => { get: ( key: string ) => { first: () => { toJSON: () => MediaAttachment }; }; }; } declare global { interface Window { wp?: { media?: ( options: Record< string, unknown > ) => unknown; }; } } // On while the library is open; hides any open Modal (see style.scss). const MEDIA_OPEN_CLASS = 'aureon-media-open'; interface MediaImageFieldProps { label: string; value: number; previewUrl?: string; help?: string; onChange: ( id: number, url: string ) => void; } export default function MediaImageField( { label, value, previewUrl, help, onChange, }: MediaImageFieldProps ) { const openLibrary = ( event: { currentTarget: HTMLElement } ) => { // window.wp.media's real signature is untyped at the `wp` global level // (WordPress ships no first-party types for it); cast to this control's // image frame shape. const media = window.wp?.media as unknown as | ( ( options: Record< string, unknown > ) => MediaFrame ) | undefined; if ( ! media ) { return; } const frame = media( { title: label, button: { text: __( 'Use this image', 'aureon' ) }, library: { type: [ 'image' ] }, multiple: false, } ); frame.on( 'select', () => { const selected = frame.state().get( 'selection' ).first().toJSON(); const url = selected.sizes?.medium?.url ?? selected.sizes?.thumbnail?.url ?? selected.url; onChange( selected.id, url ?? '' ); } ); // Opened from inside a builder settings dialog, the library would sit // under it, so the dialog steps aside while the library is up. The // library hands focus back to its opener before it fires `close` — // while the dialog is still hidden, so that focus is lost — so it's // restored here once the dialog is back. The clicked button is the opener. const opener = event.currentTarget; document.body.classList.add( MEDIA_OPEN_CLASS ); frame.on( 'close', () => { document.body.classList.remove( MEDIA_OPEN_CLASS ); opener?.focus(); } ); frame.open(); }; const hasImage = value > 0 && !! previewUrl; return ( { label }
{ hasImage && ( ) }
{ hasImage && ( ) }
); }