Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open Media Library: Add Media Library Command to Editor Command Palette #66759

Open
wants to merge 1 commit into
base: trunk
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading