hooks_use-media-manager.js

import { React } from '@gravityforms/libraries';

const { useEffect } = React;

/**
 * @module useMediaManager
 * @description A hook that provides a way to use the media manager.
 *
 * @since 4.1.0
 *
 * @return {object} The media manager hook.
 */
const useMediaManager = () => {
	useEffect( () => {
		if ( ! window?.wp?.media ) {
			console.error( 'window.wp.media is not available.' );
		}
	}, [] );

	/**
	 * @function openMediaManager
	 * @description Opens the media manager.
	 *
	 * @since 4.1.0
	 *
	 * @param {string}   [contentMode]   - The content mode for the media manager (can be upload or browse).
	 * @param {object}   [id]            - The id for the media manager.
	 * @param {function} [onMediaSelect] - The callback to run when media is selected.
	 * @param {object}   [options]       - The options for the media manager.
	 */
	const openMediaManager = ( {
		contentMode = 'browse',
		id = '',
		onMediaSelect = () => {},
		options = {},
	} ) => {
		if ( ! window?.wp?.media ) {
			return;
		}

		const mediaManager = window.wp.media( {
			library: {
				type: 'image',
			},
			multiple: false,
			...options,
		} );

		mediaManager.on( 'open', function() {
			mediaManager.content.mode( contentMode );
		} );

		mediaManager.on( 'select', () => {
			const selection = mediaManager.state().get( 'selection' );
			const attachments = options?.multiple
				? selection.map( ( attachment ) => attachment.toJSON() )
				: selection.first().toJSON();

			if ( onMediaSelect ) {
				onMediaSelect( { attachments, id } );
			}
		} );

		mediaManager.open();
	};

	return {
		openMediaManager,
	};
};

export default useMediaManager;