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 91 92 93 94 95 96 97 98 99 100 101 102 | /**
* 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( 'jetpack-ai-client:save-to-media-library' );
type SavedMediaItem = {
id: string;
url: string;
mime?: string;
};
type UseSaveToMediaLibraryReturn = {
isLoading: boolean;
saveToMediaLibrary: ( url: string, name?: string ) => Promise< SavedMediaItem >;
};
/**
* Hook to save data to media library
*
* @return {UseSaveToMediaLibraryReturn} - Object containing properties to save data to media library.
*/
export default function useSaveToMediaLibrary() {
const [ isLoading, setIsLoading ] = useState( false );
const { getSettings } = useSelect( select => select( blockEditorStore ), [] );
const saveToMediaLibrary = ( url: string, name: string = null ): Promise< SavedMediaItem > => {
// 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 = [];
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( {
id: image.id,
url: image.url,
mime: image.mime,
} );
}
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,
};
}
|