/** * External dependencies */ import clsx from 'clsx'; /** * WordPress dependencies */ import { useSelect } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; import { __experimentalTruncate as Truncate, __experimentalVStack as VStack, Icon as WCIcon, } from '@wordpress/components'; import { useState, useRef, useLayoutEffect } from '@wordpress/element'; import type { Attachment } from '@wordpress/core-data'; import { getFilename } from '@wordpress/url'; import type { DataViewRenderFieldProps } from '@wordpress/dataviews'; /** * Internal dependencies */ import { getMediaTypeFromMimeType } from '../utils/get-media-type-from-mime-type'; import type { MediaItem } from '../types'; /** * Given the available image sizes and a target display width, returns the URL * of the smallest size whose width is >= the target. Falls back to the largest * available size, or the original source_url. * * @param featuredMedia The media item with size details. * @param configSizes The target display size string (e.g. '900px'). */ export function getBestImageUrl( featuredMedia: Attachment | MediaItem, configSizes?: string ): string { const sizes = featuredMedia?.media_details?.sizes; if ( ! sizes ) { return featuredMedia.source_url; } const sizeEntries = Object.values( sizes ); if ( ! sizeEntries.length ) { return featuredMedia.source_url; } // Parse target width from config.sizes (e.g. '900px' → 900). const targetWidth = configSizes ? parseInt( configSizes, 10 ) : NaN; if ( ! Number.isNaN( targetWidth ) ) { // Filter to entries that have a valid numeric width. const validEntries = sizeEntries.filter( ( s ) => typeof s.width === 'number' && ! Number.isNaN( s.width ) ); if ( ! validEntries.length ) { return featuredMedia.source_url; } // Sort ascending by width. const sorted = [ ...validEntries ].sort( ( a, b ) => a.width - b.width ); // Pick the smallest size that is >= target width. const match = sorted.find( ( s ) => s.width >= targetWidth ); if ( match ) { return match.source_url; } // No size large enough — use the largest available. return sorted[ sorted.length - 1 ].source_url; } // If we can't parse the target, fall back to source_url. return featuredMedia.source_url; } function FallbackView( { item, filename, }: { item: MediaItem; filename: string; } ) { return (