Back

0% Statements 0/34
0% Branches 0/6
0% Functions 0/10
0% Lines 0/33

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90                                                                                                                                                                                   
/**
 * External dependencies
 */
import { isBlobURL } from '@wordpress/blob';
import { store as blockEditorStore } from '@wordpress/block-editor';
import { useSelect } from '@wordpress/data';
import { useState } from '@wordpress/element';
import debugFactory from 'debug';
 
const debug = debugFactory( 'ai-client:save-to-media-library' );
 
/**
 * Hook to save an image to the media library.
 *
 * @return {object} Object with the loading state and the function to save the image to the media library.
 */
export default function useSaveToMediaLibrary() {
	const [ isLoading, setIsLoading ] = useState( false );
	const { getSettings } = useSelect( select => select( blockEditorStore ), [] );
 
	const saveToMediaLibrary = (
		url: string,
		name?: string
	): Promise< { id: string; url: string } > => {
		// eslint-disable-next-line @typescript-eslint/no-explicit-any
		const settings = getSettings() as any;
 
		return new Promise( ( resolve, reject ) => {
			setIsLoading( true );
 
			debug( 'Fetching image from URL' );
 
			fetch( url )
				.then( response => {
					debug( 'Transforming response to blob' );
 
					response
						.blob()
						.then( ( blob: Blob ) => {
							debug( 'Uploading blob to media library' );
							const filesList = Array< File | Blob >();
 
							if ( name ) {
								filesList.push( new File( [ blob ], name ) );
							} else {
								filesList.push( blob );
							}
 
							settings.mediaUpload( {
								allowedTypes: [ 'image' ],
								filesList,
								onFileChange( [ image ] ) {
									if ( isBlobURL( image?.url ) ) {
										return;
									}
 
									if ( image ) {
										debug( 'Image uploaded to media library', image );
										resolve( image );
									}
 
									setIsLoading( false );
								},
								onError( message ) {
									debug( 'Error uploading image to media library:', message );
									reject( message );
									setIsLoading( false );
								},
							} );
						} )
						.catch( e => {
							debug( 'Error transforming response to blob:', e?.message );
							reject( e?.message );
							setIsLoading( false );
						} );
				} )
				.catch( e => {
					debug( 'Error fetching image from URL:', e?.message );
					reject( e?.message );
					setIsLoading( false );
				} );
		} );
	};
 
	return {
		isLoading,
		saveToMediaLibrary,
	};
}