Skip to content

Commit

Permalink
Add Command:Open Media Library
Browse files Browse the repository at this point in the history
  • Loading branch information
karthick-murugan committed Nov 14, 2024
1 parent d0a190b commit 8e26950
Showing 1 changed file with 74 additions and 0 deletions.
74 changes: 74 additions & 0 deletions packages/editor/src/components/commands/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
layout,
rotateRight,
rotateLeft,
gallery,
} from '@wordpress/icons';
import { useCommandLoader } from '@wordpress/commands';
import { store as preferencesStore } from '@wordpress/preferences';
Expand Down Expand Up @@ -92,6 +93,7 @@ const getEditorCommandLoader = () =>
const { getCurrentPostId } = useSelect( editorStore );
const allowSwitchEditorMode =
isCodeEditingEnabled && isRichEditingEnabled;
const { wp } = window;

if ( isPreviewMode ) {
return { commands: [], isLoading: false };
Expand Down Expand Up @@ -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',
Expand Down

0 comments on commit 8e26950

Please sign in to comment.