-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Gallery block - Add useGetMedia native variant
- Loading branch information
Gerardo
committed
Jul 4, 2022
1 parent
0f25eb3
commit caf8801
Showing
1 changed file
with
61 additions
and
0 deletions.
There are no files selected for viewing
61 changes: 61 additions & 0 deletions
61
packages/block-library/src/gallery/use-get-media.native.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
/** | ||
* WordPress dependencies | ||
*/ | ||
import { useState } from '@wordpress/element'; | ||
import { useSelect } from '@wordpress/data'; | ||
import { store as coreStore } from '@wordpress/core-data'; | ||
|
||
/** | ||
* 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 ) { | ||
const [ currentImageMedia, setCurrentImageMedia ] = useState( [] ); | ||
|
||
const imagesUploading = innerBlockImages.some( | ||
( { attributes } ) => attributes?.url?.indexOf( 'file:' ) === 0 | ||
); | ||
|
||
const imageMedia = useSelect( | ||
( select ) => { | ||
if ( ! innerBlockImages?.length || imagesUploading ) { | ||
return currentImageMedia; | ||
} | ||
const imageIds = innerBlockImages | ||
.filter( ( { attributes } ) => { | ||
const { id, url } = attributes; | ||
return id !== undefined && url?.indexOf( 'file:' ) !== 0; | ||
} ) | ||
.map( ( imageBlock ) => imageBlock.attributes.id ); | ||
|
||
if ( imageIds.length === 0 ) { | ||
return currentImageMedia; | ||
} | ||
|
||
return select( coreStore ).getMediaItems( { | ||
include: imageIds.join( ',' ), | ||
per_page: imageIds.length, | ||
orderby: 'include', | ||
} ); | ||
}, | ||
[ innerBlockImages ] | ||
); | ||
|
||
if ( | ||
imageMedia?.length !== currentImageMedia?.length || | ||
imageMedia?.some( | ||
( newImage ) => | ||
! currentImageMedia.find( | ||
( currentImage ) => currentImage.id === newImage.id | ||
) | ||
) | ||
) { | ||
setCurrentImageMedia( imageMedia ); | ||
return imageMedia; | ||
} | ||
return currentImageMedia; | ||
} |