UNPKG

@wordpress/block-library

Version:
45 lines (40 loc) • 1.34 kB
import { useSelect } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; const EMPTY_IMAGE_MEDIA = []; /** * Retrieves the extended media info for each gallery image from the store. This is used to * determine which image size options are available for the current gallery. * * @param {Array} innerBlockImages An array of the innerBlock images currently in the gallery. * * @return {Array} An array of media info options for each gallery image. */ export default function useGetMedia( innerBlockImages ) { return useSelect( ( select ) => { // Sorted so the query only changes when the set of images changes, // not when they're reordered: a reorder would otherwise be a new // query, and the records would read as empty until it resolved. // Consumers look records up by id, so the returned order doesn't // matter. const imageIds = innerBlockImages .map( ( imageBlock ) => imageBlock.attributes.id ) .filter( ( id ) => id !== undefined ) .sort( ( a, b ) => a - b ); if ( imageIds.length === 0 ) { return EMPTY_IMAGE_MEDIA; } return ( select( coreStore ).getEntityRecords( 'postType', 'attachment', { include: imageIds.join( ',' ), per_page: -1, } ) ?? EMPTY_IMAGE_MEDIA ); }, [ innerBlockImages ] ); }