Skip to content

Commit

Permalink
Adding command to open media library
Browse files Browse the repository at this point in the history
  • Loading branch information
karthick-murugan committed Nov 5, 2024
1 parent 2da866b commit a6c4fbb
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions packages/editor/src/components/commands/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
listView,
external,
keyboard,
gallery,
symbol,
} from '@wordpress/icons';
import { useCommandLoader } from '@wordpress/commands';
Expand Down Expand Up @@ -240,6 +241,76 @@ function useEditorCommandLoader() {
},
} );

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',
Expand Down

0 comments on commit a6c4fbb

Please sign in to comment.