From 8e269509afc8605464ebe4d8bb46158e3dd9a62c Mon Sep 17 00:00:00 2001 From: karthick-murugan Date: Thu, 14 Nov 2024 10:37:08 +0530 Subject: [PATCH] Add Command:Open Media Library --- .../editor/src/components/commands/index.js | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/packages/editor/src/components/commands/index.js b/packages/editor/src/components/commands/index.js index 0040a09fbdc07d..4add0cf3b80252 100644 --- a/packages/editor/src/components/commands/index.js +++ b/packages/editor/src/components/commands/index.js @@ -18,6 +18,7 @@ import { layout, rotateRight, rotateLeft, + gallery, } from '@wordpress/icons'; import { useCommandLoader } from '@wordpress/commands'; import { store as preferencesStore } from '@wordpress/preferences'; @@ -92,6 +93,7 @@ const getEditorCommandLoader = () => const { getCurrentPostId } = useSelect( editorStore ); const allowSwitchEditorMode = isCodeEditingEnabled && isRichEditingEnabled; + const { wp } = window; if ( isPreviewMode ) { return { commands: [], isLoading: false }; @@ -258,6 +260,78 @@ const getEditorCommandLoader = () => }, } ); + commands.push( { + name: 'core/open-media-library', + label: __( 'Open Media Library' ), + icon: gallery, + callback: ( { close } ) => { + close(); + + const frame = wp.media( { + title: __( 'Select or Upload Media' ), + button: { + text: __( 'Select' ), + }, + multiple: false, + } ); + + // Handle the selected media + frame.on( 'select', () => { + const attachment = frame + .state() + .get( 'selection' ) + .first() + .toJSON(); + + // If you want to insert into the block editor, use the blockEditorStore + const { insertBlocks } = + wp.data.dispatch( 'core/block-editor' ); + const { createBlock } = wp.blocks; + + // Create an image block with the selected media URL + const imageBlock = createBlock( 'core/image', { + url: attachment.url, + alt: attachment.alt, + } ); + + // Get the selected block client ID + const selectedBlockClientId = wp.data + .select( 'core/block-editor' ) + .getSelectedBlockClientId(); + + // Get the parent block client ID + const parentBlockClientId = wp.data + .select( 'core/block-editor' ) + .getBlockRootClientId( selectedBlockClientId ); + + // Get the order of blocks within the parent block + const blockOrder = wp.data + .select( 'core/block-editor' ) + .getBlockOrder( parentBlockClientId ); + + // Find the index of the selected block within the parent block + const blockIndex = blockOrder.indexOf( + selectedBlockClientId + ); + + if ( selectedBlockClientId !== null && blockIndex !== -1 ) { + // Insert the image block after the selected block within the parent block + insertBlocks( + imageBlock, + blockIndex + 1, + parentBlockClientId + ); + } else { + // If no block is selected, insert the image block at the end + insertBlocks( imageBlock ); + } + } ); + + // Open the frame + frame.open(); + }, + } ); + if ( isViewable ) { commands.push( { name: 'core/preview-link',